xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/fortran/resolve.c (revision 53b02e147d4ed531c0d2a5ca9b3e8026ba3e99b5)
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001-2019 Free Software Foundation, Inc.
3    Contributed by Andy Vaught
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify it under
8 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 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "options.h"
25 #include "bitmap.h"
26 #include "gfortran.h"
27 #include "arith.h"  /* For gfc_compare_expr().  */
28 #include "dependency.h"
29 #include "data.h"
30 #include "target-memory.h" /* for gfc_simplify_transfer */
31 #include "constructor.h"
32 
33 /* Types used in equivalence statements.  */
34 
35 enum seq_type
36 {
37   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
38 };
39 
40 /* Stack to keep track of the nesting of blocks as we move through the
41    code.  See resolve_branch() and gfc_resolve_code().  */
42 
43 typedef struct code_stack
44 {
45   struct gfc_code *head, *current;
46   struct code_stack *prev;
47 
48   /* This bitmap keeps track of the targets valid for a branch from
49      inside this block except for END {IF|SELECT}s of enclosing
50      blocks.  */
51   bitmap reachable_labels;
52 }
53 code_stack;
54 
55 static code_stack *cs_base = NULL;
56 
57 
58 /* Nonzero if we're inside a FORALL or DO CONCURRENT block.  */
59 
60 static int forall_flag;
61 int gfc_do_concurrent_flag;
62 
63 /* True when we are resolving an expression that is an actual argument to
64    a procedure.  */
65 static bool actual_arg = false;
66 /* True when we are resolving an expression that is the first actual argument
67    to a procedure.  */
68 static bool first_actual_arg = false;
69 
70 
71 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
72 
73 static int omp_workshare_flag;
74 
75 /* True if we are processing a formal arglist. The corresponding function
76    resets the flag each time that it is read.  */
77 static bool formal_arg_flag = false;
78 
79 /* True if we are resolving a specification expression.  */
80 static bool specification_expr = false;
81 
82 /* The id of the last entry seen.  */
83 static int current_entry_id;
84 
85 /* We use bitmaps to determine if a branch target is valid.  */
86 static bitmap_obstack labels_obstack;
87 
88 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
89 static bool inquiry_argument = false;
90 
91 
92 bool
93 gfc_is_formal_arg (void)
94 {
95   return formal_arg_flag;
96 }
97 
98 /* Is the symbol host associated?  */
99 static bool
100 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
101 {
102   for (ns = ns->parent; ns; ns = ns->parent)
103     {
104       if (sym->ns == ns)
105 	return true;
106     }
107 
108   return false;
109 }
110 
111 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
112    an ABSTRACT derived-type.  If where is not NULL, an error message with that
113    locus is printed, optionally using name.  */
114 
115 static bool
116 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
117 {
118   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
119     {
120       if (where)
121 	{
122 	  if (name)
123 	    gfc_error ("%qs at %L is of the ABSTRACT type %qs",
124 		       name, where, ts->u.derived->name);
125 	  else
126 	    gfc_error ("ABSTRACT type %qs used at %L",
127 		       ts->u.derived->name, where);
128 	}
129 
130       return false;
131     }
132 
133   return true;
134 }
135 
136 
137 static bool
138 check_proc_interface (gfc_symbol *ifc, locus *where)
139 {
140   /* Several checks for F08:C1216.  */
141   if (ifc->attr.procedure)
142     {
143       gfc_error ("Interface %qs at %L is declared "
144 		 "in a later PROCEDURE statement", ifc->name, where);
145       return false;
146     }
147   if (ifc->generic)
148     {
149       /* For generic interfaces, check if there is
150 	 a specific procedure with the same name.  */
151       gfc_interface *gen = ifc->generic;
152       while (gen && strcmp (gen->sym->name, ifc->name) != 0)
153 	gen = gen->next;
154       if (!gen)
155 	{
156 	  gfc_error ("Interface %qs at %L may not be generic",
157 		     ifc->name, where);
158 	  return false;
159 	}
160     }
161   if (ifc->attr.proc == PROC_ST_FUNCTION)
162     {
163       gfc_error ("Interface %qs at %L may not be a statement function",
164 		 ifc->name, where);
165       return false;
166     }
167   if (gfc_is_intrinsic (ifc, 0, ifc->declared_at)
168       || gfc_is_intrinsic (ifc, 1, ifc->declared_at))
169     ifc->attr.intrinsic = 1;
170   if (ifc->attr.intrinsic && !gfc_intrinsic_actual_ok (ifc->name, 0))
171     {
172       gfc_error ("Intrinsic procedure %qs not allowed in "
173 		 "PROCEDURE statement at %L", ifc->name, where);
174       return false;
175     }
176   if (!ifc->attr.if_source && !ifc->attr.intrinsic && ifc->name[0] != '\0')
177     {
178       gfc_error ("Interface %qs at %L must be explicit", ifc->name, where);
179       return false;
180     }
181   return true;
182 }
183 
184 
185 static void resolve_symbol (gfc_symbol *sym);
186 
187 
188 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
189 
190 static bool
191 resolve_procedure_interface (gfc_symbol *sym)
192 {
193   gfc_symbol *ifc = sym->ts.interface;
194 
195   if (!ifc)
196     return true;
197 
198   if (ifc == sym)
199     {
200       gfc_error ("PROCEDURE %qs at %L may not be used as its own interface",
201 		 sym->name, &sym->declared_at);
202       return false;
203     }
204   if (!check_proc_interface (ifc, &sym->declared_at))
205     return false;
206 
207   if (ifc->attr.if_source || ifc->attr.intrinsic)
208     {
209       /* Resolve interface and copy attributes.  */
210       resolve_symbol (ifc);
211       if (ifc->attr.intrinsic)
212 	gfc_resolve_intrinsic (ifc, &ifc->declared_at);
213 
214       if (ifc->result)
215 	{
216 	  sym->ts = ifc->result->ts;
217 	  sym->attr.allocatable = ifc->result->attr.allocatable;
218 	  sym->attr.pointer = ifc->result->attr.pointer;
219 	  sym->attr.dimension = ifc->result->attr.dimension;
220 	  sym->attr.class_ok = ifc->result->attr.class_ok;
221 	  sym->as = gfc_copy_array_spec (ifc->result->as);
222 	  sym->result = sym;
223 	}
224       else
225 	{
226 	  sym->ts = ifc->ts;
227 	  sym->attr.allocatable = ifc->attr.allocatable;
228 	  sym->attr.pointer = ifc->attr.pointer;
229 	  sym->attr.dimension = ifc->attr.dimension;
230 	  sym->attr.class_ok = ifc->attr.class_ok;
231 	  sym->as = gfc_copy_array_spec (ifc->as);
232 	}
233       sym->ts.interface = ifc;
234       sym->attr.function = ifc->attr.function;
235       sym->attr.subroutine = ifc->attr.subroutine;
236 
237       sym->attr.pure = ifc->attr.pure;
238       sym->attr.elemental = ifc->attr.elemental;
239       sym->attr.contiguous = ifc->attr.contiguous;
240       sym->attr.recursive = ifc->attr.recursive;
241       sym->attr.always_explicit = ifc->attr.always_explicit;
242       sym->attr.ext_attr |= ifc->attr.ext_attr;
243       sym->attr.is_bind_c = ifc->attr.is_bind_c;
244       /* Copy char length.  */
245       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
246 	{
247 	  sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
248 	  if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
249 	      && !gfc_resolve_expr (sym->ts.u.cl->length))
250 	    return false;
251 	}
252     }
253 
254   return true;
255 }
256 
257 
258 /* Resolve types of formal argument lists.  These have to be done early so that
259    the formal argument lists of module procedures can be copied to the
260    containing module before the individual procedures are resolved
261    individually.  We also resolve argument lists of procedures in interface
262    blocks because they are self-contained scoping units.
263 
264    Since a dummy argument cannot be a non-dummy procedure, the only
265    resort left for untyped names are the IMPLICIT types.  */
266 
267 static void
268 resolve_formal_arglist (gfc_symbol *proc)
269 {
270   gfc_formal_arglist *f;
271   gfc_symbol *sym;
272   bool saved_specification_expr;
273   int i;
274 
275   if (proc->result != NULL)
276     sym = proc->result;
277   else
278     sym = proc;
279 
280   if (gfc_elemental (proc)
281       || sym->attr.pointer || sym->attr.allocatable
282       || (sym->as && sym->as->rank != 0))
283     {
284       proc->attr.always_explicit = 1;
285       sym->attr.always_explicit = 1;
286     }
287 
288   formal_arg_flag = true;
289 
290   for (f = proc->formal; f; f = f->next)
291     {
292       gfc_array_spec *as;
293 
294       sym = f->sym;
295 
296       if (sym == NULL)
297 	{
298 	  /* Alternate return placeholder.  */
299 	  if (gfc_elemental (proc))
300 	    gfc_error ("Alternate return specifier in elemental subroutine "
301 		       "%qs at %L is not allowed", proc->name,
302 		       &proc->declared_at);
303 	  if (proc->attr.function)
304 	    gfc_error ("Alternate return specifier in function "
305 		       "%qs at %L is not allowed", proc->name,
306 		       &proc->declared_at);
307 	  continue;
308 	}
309       else if (sym->attr.procedure && sym->attr.if_source != IFSRC_DECL
310 	       && !resolve_procedure_interface (sym))
311 	return;
312 
313       if (strcmp (proc->name, sym->name) == 0)
314         {
315           gfc_error ("Self-referential argument "
316                      "%qs at %L is not allowed", sym->name,
317                      &proc->declared_at);
318           return;
319         }
320 
321       if (sym->attr.if_source != IFSRC_UNKNOWN)
322 	resolve_formal_arglist (sym);
323 
324       if (sym->attr.subroutine || sym->attr.external)
325 	{
326 	  if (sym->attr.flavor == FL_UNKNOWN)
327 	    gfc_add_flavor (&sym->attr, FL_PROCEDURE, sym->name, &sym->declared_at);
328 	}
329       else
330 	{
331 	  if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
332 	      && (!sym->attr.function || sym->result == sym))
333 	    gfc_set_default_type (sym, 1, sym->ns);
334 	}
335 
336       as = sym->ts.type == BT_CLASS && sym->attr.class_ok
337 	   ? CLASS_DATA (sym)->as : sym->as;
338 
339       saved_specification_expr = specification_expr;
340       specification_expr = true;
341       gfc_resolve_array_spec (as, 0);
342       specification_expr = saved_specification_expr;
343 
344       /* We can't tell if an array with dimension (:) is assumed or deferred
345 	 shape until we know if it has the pointer or allocatable attributes.
346       */
347       if (as && as->rank > 0 && as->type == AS_DEFERRED
348 	  && ((sym->ts.type != BT_CLASS
349 	       && !(sym->attr.pointer || sym->attr.allocatable))
350               || (sym->ts.type == BT_CLASS
351 		  && !(CLASS_DATA (sym)->attr.class_pointer
352 		       || CLASS_DATA (sym)->attr.allocatable)))
353 	  && sym->attr.flavor != FL_PROCEDURE)
354 	{
355 	  as->type = AS_ASSUMED_SHAPE;
356 	  for (i = 0; i < as->rank; i++)
357 	    as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
358 	}
359 
360       if ((as && as->rank > 0 && as->type == AS_ASSUMED_SHAPE)
361 	  || (as && as->type == AS_ASSUMED_RANK)
362 	  || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
363 	  || (sym->ts.type == BT_CLASS && sym->attr.class_ok
364 	      && (CLASS_DATA (sym)->attr.class_pointer
365 		  || CLASS_DATA (sym)->attr.allocatable
366 		  || CLASS_DATA (sym)->attr.target))
367 	  || sym->attr.optional)
368 	{
369 	  proc->attr.always_explicit = 1;
370 	  if (proc->result)
371 	    proc->result->attr.always_explicit = 1;
372 	}
373 
374       /* If the flavor is unknown at this point, it has to be a variable.
375 	 A procedure specification would have already set the type.  */
376 
377       if (sym->attr.flavor == FL_UNKNOWN)
378 	gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
379 
380       if (gfc_pure (proc))
381 	{
382 	  if (sym->attr.flavor == FL_PROCEDURE)
383 	    {
384 	      /* F08:C1279.  */
385 	      if (!gfc_pure (sym))
386 		{
387 		  gfc_error ("Dummy procedure %qs of PURE procedure at %L must "
388 			    "also be PURE", sym->name, &sym->declared_at);
389 		  continue;
390 		}
391 	    }
392 	  else if (!sym->attr.pointer)
393 	    {
394 	      if (proc->attr.function && sym->attr.intent != INTENT_IN)
395 		{
396 		  if (sym->attr.value)
397 		    gfc_notify_std (GFC_STD_F2008, "Argument %qs"
398 				    " of pure function %qs at %L with VALUE "
399 				    "attribute but without INTENT(IN)",
400 				    sym->name, proc->name, &sym->declared_at);
401 		  else
402 		    gfc_error ("Argument %qs of pure function %qs at %L must "
403 			       "be INTENT(IN) or VALUE", sym->name, proc->name,
404 			       &sym->declared_at);
405 		}
406 
407 	      if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
408 		{
409 		  if (sym->attr.value)
410 		    gfc_notify_std (GFC_STD_F2008, "Argument %qs"
411 				    " of pure subroutine %qs at %L with VALUE "
412 				    "attribute but without INTENT", sym->name,
413 				    proc->name, &sym->declared_at);
414 		  else
415 		    gfc_error ("Argument %qs of pure subroutine %qs at %L "
416 			       "must have its INTENT specified or have the "
417 			       "VALUE attribute", sym->name, proc->name,
418 			       &sym->declared_at);
419 		}
420 	    }
421 
422 	  /* F08:C1278a.  */
423 	  if (sym->ts.type == BT_CLASS && sym->attr.intent == INTENT_OUT)
424 	    {
425 	      gfc_error ("INTENT(OUT) argument %qs of pure procedure %qs at %L"
426 			 " may not be polymorphic", sym->name, proc->name,
427 			 &sym->declared_at);
428 	      continue;
429 	    }
430 	}
431 
432       if (proc->attr.implicit_pure)
433 	{
434 	  if (sym->attr.flavor == FL_PROCEDURE)
435 	    {
436 	      if (!gfc_pure (sym))
437 		proc->attr.implicit_pure = 0;
438 	    }
439 	  else if (!sym->attr.pointer)
440 	    {
441 	      if (proc->attr.function && sym->attr.intent != INTENT_IN
442 		  && !sym->value)
443 		proc->attr.implicit_pure = 0;
444 
445 	      if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN
446 		  && !sym->value)
447 		proc->attr.implicit_pure = 0;
448 	    }
449 	}
450 
451       if (gfc_elemental (proc))
452 	{
453 	  /* F08:C1289.  */
454 	  if (sym->attr.codimension
455 	      || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
456 		  && CLASS_DATA (sym)->attr.codimension))
457 	    {
458 	      gfc_error ("Coarray dummy argument %qs at %L to elemental "
459 			 "procedure", sym->name, &sym->declared_at);
460 	      continue;
461 	    }
462 
463 	  if (sym->as || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
464 			  && CLASS_DATA (sym)->as))
465 	    {
466 	      gfc_error ("Argument %qs of elemental procedure at %L must "
467 			 "be scalar", sym->name, &sym->declared_at);
468 	      continue;
469 	    }
470 
471 	  if (sym->attr.allocatable
472 	      || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
473 		  && CLASS_DATA (sym)->attr.allocatable))
474 	    {
475 	      gfc_error ("Argument %qs of elemental procedure at %L cannot "
476 			 "have the ALLOCATABLE attribute", sym->name,
477 			 &sym->declared_at);
478 	      continue;
479 	    }
480 
481 	  if (sym->attr.pointer
482 	      || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
483 		  && CLASS_DATA (sym)->attr.class_pointer))
484 	    {
485 	      gfc_error ("Argument %qs of elemental procedure at %L cannot "
486 			 "have the POINTER attribute", sym->name,
487 			 &sym->declared_at);
488 	      continue;
489 	    }
490 
491 	  if (sym->attr.flavor == FL_PROCEDURE)
492 	    {
493 	      gfc_error ("Dummy procedure %qs not allowed in elemental "
494 			 "procedure %qs at %L", sym->name, proc->name,
495 			 &sym->declared_at);
496 	      continue;
497 	    }
498 
499 	  /* Fortran 2008 Corrigendum 1, C1290a.  */
500 	  if (sym->attr.intent == INTENT_UNKNOWN && !sym->attr.value)
501 	    {
502 	      gfc_error ("Argument %qs of elemental procedure %qs at %L must "
503 			 "have its INTENT specified or have the VALUE "
504 			 "attribute", sym->name, proc->name,
505 			 &sym->declared_at);
506 	      continue;
507 	    }
508 	}
509 
510       /* Each dummy shall be specified to be scalar.  */
511       if (proc->attr.proc == PROC_ST_FUNCTION)
512 	{
513 	  if (sym->as != NULL)
514 	    {
515 	      /* F03:C1263 (R1238) The function-name and each dummy-arg-name
516 		 shall be specified, explicitly or implicitly, to be scalar.  */
517 	      gfc_error ("Argument '%s' of statement function '%s' at %L "
518 			 "must be scalar", sym->name, proc->name,
519 			 &proc->declared_at);
520 	      continue;
521 	    }
522 
523 	  if (sym->ts.type == BT_CHARACTER)
524 	    {
525 	      gfc_charlen *cl = sym->ts.u.cl;
526 	      if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
527 		{
528 		  gfc_error ("Character-valued argument %qs of statement "
529 			     "function at %L must have constant length",
530 			     sym->name, &sym->declared_at);
531 		  continue;
532 		}
533 	    }
534 	}
535     }
536   formal_arg_flag = false;
537 }
538 
539 
540 /* Work function called when searching for symbols that have argument lists
541    associated with them.  */
542 
543 static void
544 find_arglists (gfc_symbol *sym)
545 {
546   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns
547       || gfc_fl_struct (sym->attr.flavor) || sym->attr.intrinsic)
548     return;
549 
550   resolve_formal_arglist (sym);
551 }
552 
553 
554 /* Given a namespace, resolve all formal argument lists within the namespace.
555  */
556 
557 static void
558 resolve_formal_arglists (gfc_namespace *ns)
559 {
560   if (ns == NULL)
561     return;
562 
563   gfc_traverse_ns (ns, find_arglists);
564 }
565 
566 
567 static void
568 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
569 {
570   bool t;
571 
572   if (sym && sym->attr.flavor == FL_PROCEDURE
573       && sym->ns->parent
574       && sym->ns->parent->proc_name
575       && sym->ns->parent->proc_name->attr.flavor == FL_PROCEDURE
576       && !strcmp (sym->name, sym->ns->parent->proc_name->name))
577     gfc_error ("Contained procedure %qs at %L has the same name as its "
578 	       "encompassing procedure", sym->name, &sym->declared_at);
579 
580   /* If this namespace is not a function or an entry master function,
581      ignore it.  */
582   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
583       || sym->attr.entry_master)
584     return;
585 
586   if (!sym->result)
587     return;
588 
589   /* Try to find out of what the return type is.  */
590   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
591     {
592       t = gfc_set_default_type (sym->result, 0, ns);
593 
594       if (!t && !sym->result->attr.untyped)
595 	{
596 	  if (sym->result == sym)
597 	    gfc_error ("Contained function %qs at %L has no IMPLICIT type",
598 		       sym->name, &sym->declared_at);
599 	  else if (!sym->result->attr.proc_pointer)
600 	    gfc_error ("Result %qs of contained function %qs at %L has "
601 		       "no IMPLICIT type", sym->result->name, sym->name,
602 		       &sym->result->declared_at);
603 	  sym->result->attr.untyped = 1;
604 	}
605     }
606 
607   /* Fortran 2008 Draft Standard, page 535, C418, on type-param-value
608      type, lists the only ways a character length value of * can be used:
609      dummy arguments of procedures, named constants, function results and
610      in allocate statements if the allocate_object is an assumed length dummy
611      in external functions.  Internal function results and results of module
612      procedures are not on this list, ergo, not permitted.  */
613 
614   if (sym->result->ts.type == BT_CHARACTER)
615     {
616       gfc_charlen *cl = sym->result->ts.u.cl;
617       if ((!cl || !cl->length) && !sym->result->ts.deferred)
618 	{
619 	  /* See if this is a module-procedure and adapt error message
620 	     accordingly.  */
621 	  bool module_proc;
622 	  gcc_assert (ns->parent && ns->parent->proc_name);
623 	  module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
624 
625 	  gfc_error (module_proc
626 		     ? G_("Character-valued module procedure %qs at %L"
627 			  " must not be assumed length")
628 		     : G_("Character-valued internal function %qs at %L"
629 			  " must not be assumed length"),
630 		     sym->name, &sym->declared_at);
631 	}
632     }
633 }
634 
635 
636 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
637    introduce duplicates.  */
638 
639 static void
640 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
641 {
642   gfc_formal_arglist *f, *new_arglist;
643   gfc_symbol *new_sym;
644 
645   for (; new_args != NULL; new_args = new_args->next)
646     {
647       new_sym = new_args->sym;
648       /* See if this arg is already in the formal argument list.  */
649       for (f = proc->formal; f; f = f->next)
650 	{
651 	  if (new_sym == f->sym)
652 	    break;
653 	}
654 
655       if (f)
656 	continue;
657 
658       /* Add a new argument.  Argument order is not important.  */
659       new_arglist = gfc_get_formal_arglist ();
660       new_arglist->sym = new_sym;
661       new_arglist->next = proc->formal;
662       proc->formal  = new_arglist;
663     }
664 }
665 
666 
667 /* Flag the arguments that are not present in all entries.  */
668 
669 static void
670 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
671 {
672   gfc_formal_arglist *f, *head;
673   head = new_args;
674 
675   for (f = proc->formal; f; f = f->next)
676     {
677       if (f->sym == NULL)
678 	continue;
679 
680       for (new_args = head; new_args; new_args = new_args->next)
681 	{
682 	  if (new_args->sym == f->sym)
683 	    break;
684 	}
685 
686       if (new_args)
687 	continue;
688 
689       f->sym->attr.not_always_present = 1;
690     }
691 }
692 
693 
694 /* Resolve alternate entry points.  If a symbol has multiple entry points we
695    create a new master symbol for the main routine, and turn the existing
696    symbol into an entry point.  */
697 
698 static void
699 resolve_entries (gfc_namespace *ns)
700 {
701   gfc_namespace *old_ns;
702   gfc_code *c;
703   gfc_symbol *proc;
704   gfc_entry_list *el;
705   char name[GFC_MAX_SYMBOL_LEN + 1];
706   static int master_count = 0;
707 
708   if (ns->proc_name == NULL)
709     return;
710 
711   /* No need to do anything if this procedure doesn't have alternate entry
712      points.  */
713   if (!ns->entries)
714     return;
715 
716   /* We may already have resolved alternate entry points.  */
717   if (ns->proc_name->attr.entry_master)
718     return;
719 
720   /* If this isn't a procedure something has gone horribly wrong.  */
721   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
722 
723   /* Remember the current namespace.  */
724   old_ns = gfc_current_ns;
725 
726   gfc_current_ns = ns;
727 
728   /* Add the main entry point to the list of entry points.  */
729   el = gfc_get_entry_list ();
730   el->sym = ns->proc_name;
731   el->id = 0;
732   el->next = ns->entries;
733   ns->entries = el;
734   ns->proc_name->attr.entry = 1;
735 
736   /* If it is a module function, it needs to be in the right namespace
737      so that gfc_get_fake_result_decl can gather up the results. The
738      need for this arose in get_proc_name, where these beasts were
739      left in their own namespace, to keep prior references linked to
740      the entry declaration.*/
741   if (ns->proc_name->attr.function
742       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
743     el->sym->ns = ns;
744 
745   /* Do the same for entries where the master is not a module
746      procedure.  These are retained in the module namespace because
747      of the module procedure declaration.  */
748   for (el = el->next; el; el = el->next)
749     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
750 	  && el->sym->attr.mod_proc)
751       el->sym->ns = ns;
752   el = ns->entries;
753 
754   /* Add an entry statement for it.  */
755   c = gfc_get_code (EXEC_ENTRY);
756   c->ext.entry = el;
757   c->next = ns->code;
758   ns->code = c;
759 
760   /* Create a new symbol for the master function.  */
761   /* Give the internal function a unique name (within this file).
762      Also include the function name so the user has some hope of figuring
763      out what is going on.  */
764   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
765 	    master_count++, ns->proc_name->name);
766   gfc_get_ha_symbol (name, &proc);
767   gcc_assert (proc != NULL);
768 
769   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
770   if (ns->proc_name->attr.subroutine)
771     gfc_add_subroutine (&proc->attr, proc->name, NULL);
772   else
773     {
774       gfc_symbol *sym;
775       gfc_typespec *ts, *fts;
776       gfc_array_spec *as, *fas;
777       gfc_add_function (&proc->attr, proc->name, NULL);
778       proc->result = proc;
779       fas = ns->entries->sym->as;
780       fas = fas ? fas : ns->entries->sym->result->as;
781       fts = &ns->entries->sym->result->ts;
782       if (fts->type == BT_UNKNOWN)
783 	fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
784       for (el = ns->entries->next; el; el = el->next)
785 	{
786 	  ts = &el->sym->result->ts;
787 	  as = el->sym->as;
788 	  as = as ? as : el->sym->result->as;
789 	  if (ts->type == BT_UNKNOWN)
790 	    ts = gfc_get_default_type (el->sym->result->name, NULL);
791 
792 	  if (! gfc_compare_types (ts, fts)
793 	      || (el->sym->result->attr.dimension
794 		  != ns->entries->sym->result->attr.dimension)
795 	      || (el->sym->result->attr.pointer
796 		  != ns->entries->sym->result->attr.pointer))
797 	    break;
798 	  else if (as && fas && ns->entries->sym->result != el->sym->result
799 		      && gfc_compare_array_spec (as, fas) == 0)
800 	    gfc_error ("Function %s at %L has entries with mismatched "
801 		       "array specifications", ns->entries->sym->name,
802 		       &ns->entries->sym->declared_at);
803 	  /* The characteristics need to match and thus both need to have
804 	     the same string length, i.e. both len=*, or both len=4.
805 	     Having both len=<variable> is also possible, but difficult to
806 	     check at compile time.  */
807 	  else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
808 		   && (((ts->u.cl->length && !fts->u.cl->length)
809 			||(!ts->u.cl->length && fts->u.cl->length))
810 		       || (ts->u.cl->length
811 			   && ts->u.cl->length->expr_type
812 			      != fts->u.cl->length->expr_type)
813 		       || (ts->u.cl->length
814 			   && ts->u.cl->length->expr_type == EXPR_CONSTANT
815 		           && mpz_cmp (ts->u.cl->length->value.integer,
816 				       fts->u.cl->length->value.integer) != 0)))
817 	    gfc_notify_std (GFC_STD_GNU, "Function %s at %L with "
818 			    "entries returning variables of different "
819 			    "string lengths", ns->entries->sym->name,
820 			    &ns->entries->sym->declared_at);
821 	}
822 
823       if (el == NULL)
824 	{
825 	  sym = ns->entries->sym->result;
826 	  /* All result types the same.  */
827 	  proc->ts = *fts;
828 	  if (sym->attr.dimension)
829 	    gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
830 	  if (sym->attr.pointer)
831 	    gfc_add_pointer (&proc->attr, NULL);
832 	}
833       else
834 	{
835 	  /* Otherwise the result will be passed through a union by
836 	     reference.  */
837 	  proc->attr.mixed_entry_master = 1;
838 	  for (el = ns->entries; el; el = el->next)
839 	    {
840 	      sym = el->sym->result;
841 	      if (sym->attr.dimension)
842 		{
843 		  if (el == ns->entries)
844 		    gfc_error ("FUNCTION result %s cannot be an array in "
845 			       "FUNCTION %s at %L", sym->name,
846 			       ns->entries->sym->name, &sym->declared_at);
847 		  else
848 		    gfc_error ("ENTRY result %s cannot be an array in "
849 			       "FUNCTION %s at %L", sym->name,
850 			       ns->entries->sym->name, &sym->declared_at);
851 		}
852 	      else if (sym->attr.pointer)
853 		{
854 		  if (el == ns->entries)
855 		    gfc_error ("FUNCTION result %s cannot be a POINTER in "
856 			       "FUNCTION %s at %L", sym->name,
857 			       ns->entries->sym->name, &sym->declared_at);
858 		  else
859 		    gfc_error ("ENTRY result %s cannot be a POINTER in "
860 			       "FUNCTION %s at %L", sym->name,
861 			       ns->entries->sym->name, &sym->declared_at);
862 		}
863 	      else
864 		{
865 		  ts = &sym->ts;
866 		  if (ts->type == BT_UNKNOWN)
867 		    ts = gfc_get_default_type (sym->name, NULL);
868 		  switch (ts->type)
869 		    {
870 		    case BT_INTEGER:
871 		      if (ts->kind == gfc_default_integer_kind)
872 			sym = NULL;
873 		      break;
874 		    case BT_REAL:
875 		      if (ts->kind == gfc_default_real_kind
876 			  || ts->kind == gfc_default_double_kind)
877 			sym = NULL;
878 		      break;
879 		    case BT_COMPLEX:
880 		      if (ts->kind == gfc_default_complex_kind)
881 			sym = NULL;
882 		      break;
883 		    case BT_LOGICAL:
884 		      if (ts->kind == gfc_default_logical_kind)
885 			sym = NULL;
886 		      break;
887 		    case BT_UNKNOWN:
888 		      /* We will issue error elsewhere.  */
889 		      sym = NULL;
890 		      break;
891 		    default:
892 		      break;
893 		    }
894 		  if (sym)
895 		    {
896 		      if (el == ns->entries)
897 			gfc_error ("FUNCTION result %s cannot be of type %s "
898 				   "in FUNCTION %s at %L", sym->name,
899 				   gfc_typename (ts), ns->entries->sym->name,
900 				   &sym->declared_at);
901 		      else
902 			gfc_error ("ENTRY result %s cannot be of type %s "
903 				   "in FUNCTION %s at %L", sym->name,
904 				   gfc_typename (ts), ns->entries->sym->name,
905 				   &sym->declared_at);
906 		    }
907 		}
908 	    }
909 	}
910     }
911   proc->attr.access = ACCESS_PRIVATE;
912   proc->attr.entry_master = 1;
913 
914   /* Merge all the entry point arguments.  */
915   for (el = ns->entries; el; el = el->next)
916     merge_argument_lists (proc, el->sym->formal);
917 
918   /* Check the master formal arguments for any that are not
919      present in all entry points.  */
920   for (el = ns->entries; el; el = el->next)
921     check_argument_lists (proc, el->sym->formal);
922 
923   /* Use the master function for the function body.  */
924   ns->proc_name = proc;
925 
926   /* Finalize the new symbols.  */
927   gfc_commit_symbols ();
928 
929   /* Restore the original namespace.  */
930   gfc_current_ns = old_ns;
931 }
932 
933 
934 /* Resolve common variables.  */
935 static void
936 resolve_common_vars (gfc_common_head *common_block, bool named_common)
937 {
938   gfc_symbol *csym = common_block->head;
939 
940   for (; csym; csym = csym->common_next)
941     {
942       /* gfc_add_in_common may have been called before, but the reported errors
943 	 have been ignored to continue parsing.
944 	 We do the checks again here.  */
945       if (!csym->attr.use_assoc)
946 	{
947 	  gfc_add_in_common (&csym->attr, csym->name, &common_block->where);
948 	  gfc_notify_std (GFC_STD_F2018_OBS, "COMMON block at %L",
949 			  &common_block->where);
950 	}
951 
952       if (csym->value || csym->attr.data)
953 	{
954 	  if (!csym->ns->is_block_data)
955 	    gfc_notify_std (GFC_STD_GNU, "Variable %qs at %L is in COMMON "
956 			    "but only in BLOCK DATA initialization is "
957 			    "allowed", csym->name, &csym->declared_at);
958 	  else if (!named_common)
959 	    gfc_notify_std (GFC_STD_GNU, "Initialized variable %qs at %L is "
960 			    "in a blank COMMON but initialization is only "
961 			    "allowed in named common blocks", csym->name,
962 			    &csym->declared_at);
963 	}
964 
965       if (UNLIMITED_POLY (csym))
966 	gfc_error_now ("%qs in cannot appear in COMMON at %L "
967 		       "[F2008:C5100]", csym->name, &csym->declared_at);
968 
969       if (csym->ts.type != BT_DERIVED)
970 	continue;
971 
972       if (!(csym->ts.u.derived->attr.sequence
973 	    || csym->ts.u.derived->attr.is_bind_c))
974 	gfc_error_now ("Derived type variable %qs in COMMON at %L "
975 		       "has neither the SEQUENCE nor the BIND(C) "
976 		       "attribute", csym->name, &csym->declared_at);
977       if (csym->ts.u.derived->attr.alloc_comp)
978 	gfc_error_now ("Derived type variable %qs in COMMON at %L "
979 		       "has an ultimate component that is "
980 		       "allocatable", csym->name, &csym->declared_at);
981       if (gfc_has_default_initializer (csym->ts.u.derived))
982 	gfc_error_now ("Derived type variable %qs in COMMON at %L "
983 		       "may not have default initializer", csym->name,
984 		       &csym->declared_at);
985 
986       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
987 	gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
988     }
989 }
990 
991 /* Resolve common blocks.  */
992 static void
993 resolve_common_blocks (gfc_symtree *common_root)
994 {
995   gfc_symbol *sym;
996   gfc_gsymbol * gsym;
997 
998   if (common_root == NULL)
999     return;
1000 
1001   if (common_root->left)
1002     resolve_common_blocks (common_root->left);
1003   if (common_root->right)
1004     resolve_common_blocks (common_root->right);
1005 
1006   resolve_common_vars (common_root->n.common, true);
1007 
1008   /* The common name is a global name - in Fortran 2003 also if it has a
1009      C binding name, since Fortran 2008 only the C binding name is a global
1010      identifier.  */
1011   if (!common_root->n.common->binding_label
1012       || gfc_notification_std (GFC_STD_F2008))
1013     {
1014       gsym = gfc_find_gsymbol (gfc_gsym_root,
1015 			       common_root->n.common->name);
1016 
1017       if (gsym && gfc_notification_std (GFC_STD_F2008)
1018 	  && gsym->type == GSYM_COMMON
1019 	  && ((common_root->n.common->binding_label
1020 	       && (!gsym->binding_label
1021 		   || strcmp (common_root->n.common->binding_label,
1022 			      gsym->binding_label) != 0))
1023 	      || (!common_root->n.common->binding_label
1024 		  && gsym->binding_label)))
1025 	{
1026 	  gfc_error ("In Fortran 2003 COMMON %qs block at %L is a global "
1027 		     "identifier and must thus have the same binding name "
1028 		     "as the same-named COMMON block at %L: %s vs %s",
1029 		     common_root->n.common->name, &common_root->n.common->where,
1030 		     &gsym->where,
1031 		     common_root->n.common->binding_label
1032 		     ? common_root->n.common->binding_label : "(blank)",
1033 		     gsym->binding_label ? gsym->binding_label : "(blank)");
1034 	  return;
1035 	}
1036 
1037       if (gsym && gsym->type != GSYM_COMMON
1038 	  && !common_root->n.common->binding_label)
1039 	{
1040 	  gfc_error ("COMMON block %qs at %L uses the same global identifier "
1041 		     "as entity at %L",
1042 		     common_root->n.common->name, &common_root->n.common->where,
1043 		     &gsym->where);
1044 	  return;
1045 	}
1046       if (gsym && gsym->type != GSYM_COMMON)
1047 	{
1048 	  gfc_error ("Fortran 2008: COMMON block %qs with binding label at "
1049 		     "%L sharing the identifier with global non-COMMON-block "
1050 		     "entity at %L", common_root->n.common->name,
1051 		     &common_root->n.common->where, &gsym->where);
1052 	  return;
1053 	}
1054       if (!gsym)
1055 	{
1056 	  gsym = gfc_get_gsymbol (common_root->n.common->name, false);
1057 	  gsym->type = GSYM_COMMON;
1058 	  gsym->where = common_root->n.common->where;
1059 	  gsym->defined = 1;
1060 	}
1061       gsym->used = 1;
1062     }
1063 
1064   if (common_root->n.common->binding_label)
1065     {
1066       gsym = gfc_find_gsymbol (gfc_gsym_root,
1067 			       common_root->n.common->binding_label);
1068       if (gsym && gsym->type != GSYM_COMMON)
1069 	{
1070 	  gfc_error ("COMMON block at %L with binding label %qs uses the same "
1071 		     "global identifier as entity at %L",
1072 		     &common_root->n.common->where,
1073 		     common_root->n.common->binding_label, &gsym->where);
1074 	  return;
1075 	}
1076       if (!gsym)
1077 	{
1078 	  gsym = gfc_get_gsymbol (common_root->n.common->binding_label, true);
1079 	  gsym->type = GSYM_COMMON;
1080 	  gsym->where = common_root->n.common->where;
1081 	  gsym->defined = 1;
1082 	}
1083       gsym->used = 1;
1084     }
1085 
1086   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
1087   if (sym == NULL)
1088     return;
1089 
1090   if (sym->attr.flavor == FL_PARAMETER)
1091     gfc_error ("COMMON block %qs at %L is used as PARAMETER at %L",
1092 	       sym->name, &common_root->n.common->where, &sym->declared_at);
1093 
1094   if (sym->attr.external)
1095     gfc_error ("COMMON block %qs at %L cannot have the EXTERNAL attribute",
1096 	       sym->name, &common_root->n.common->where);
1097 
1098   if (sym->attr.intrinsic)
1099     gfc_error ("COMMON block %qs at %L is also an intrinsic procedure",
1100 	       sym->name, &common_root->n.common->where);
1101   else if (sym->attr.result
1102 	   || gfc_is_function_return_value (sym, gfc_current_ns))
1103     gfc_notify_std (GFC_STD_F2003, "COMMON block %qs at %L "
1104 		    "that is also a function result", sym->name,
1105 		    &common_root->n.common->where);
1106   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
1107 	   && sym->attr.proc != PROC_ST_FUNCTION)
1108     gfc_notify_std (GFC_STD_F2003, "COMMON block %qs at %L "
1109 		    "that is also a global procedure", sym->name,
1110 		    &common_root->n.common->where);
1111 }
1112 
1113 
1114 /* Resolve contained function types.  Because contained functions can call one
1115    another, they have to be worked out before any of the contained procedures
1116    can be resolved.
1117 
1118    The good news is that if a function doesn't already have a type, the only
1119    way it can get one is through an IMPLICIT type or a RESULT variable, because
1120    by definition contained functions are contained namespace they're contained
1121    in, not in a sibling or parent namespace.  */
1122 
1123 static void
1124 resolve_contained_functions (gfc_namespace *ns)
1125 {
1126   gfc_namespace *child;
1127   gfc_entry_list *el;
1128 
1129   resolve_formal_arglists (ns);
1130 
1131   for (child = ns->contained; child; child = child->sibling)
1132     {
1133       /* Resolve alternate entry points first.  */
1134       resolve_entries (child);
1135 
1136       /* Then check function return types.  */
1137       resolve_contained_fntype (child->proc_name, child);
1138       for (el = child->entries; el; el = el->next)
1139 	resolve_contained_fntype (el->sym, child);
1140     }
1141 }
1142 
1143 
1144 
1145 /* A Parameterized Derived Type constructor must contain values for
1146    the PDT KIND parameters or they must have a default initializer.
1147    Go through the constructor picking out the KIND expressions,
1148    storing them in 'param_list' and then call gfc_get_pdt_instance
1149    to obtain the PDT instance.  */
1150 
1151 static gfc_actual_arglist *param_list, *param_tail, *param;
1152 
1153 static bool
1154 get_pdt_spec_expr (gfc_component *c, gfc_expr *expr)
1155 {
1156   param = gfc_get_actual_arglist ();
1157   if (!param_list)
1158     param_list = param_tail = param;
1159   else
1160     {
1161       param_tail->next = param;
1162       param_tail = param_tail->next;
1163     }
1164 
1165   param_tail->name = c->name;
1166   if (expr)
1167     param_tail->expr = gfc_copy_expr (expr);
1168   else if (c->initializer)
1169     param_tail->expr = gfc_copy_expr (c->initializer);
1170   else
1171     {
1172       param_tail->spec_type = SPEC_ASSUMED;
1173       if (c->attr.pdt_kind)
1174 	{
1175 	  gfc_error ("The KIND parameter %qs in the PDT constructor "
1176 		     "at %C has no value", param->name);
1177 	  return false;
1178 	}
1179     }
1180 
1181   return true;
1182 }
1183 
1184 static bool
1185 get_pdt_constructor (gfc_expr *expr, gfc_constructor **constr,
1186 		     gfc_symbol *derived)
1187 {
1188   gfc_constructor *cons = NULL;
1189   gfc_component *comp;
1190   bool t = true;
1191 
1192   if (expr && expr->expr_type == EXPR_STRUCTURE)
1193     cons = gfc_constructor_first (expr->value.constructor);
1194   else if (constr)
1195     cons = *constr;
1196   gcc_assert (cons);
1197 
1198   comp = derived->components;
1199 
1200   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
1201     {
1202       if (cons->expr
1203 	  && cons->expr->expr_type == EXPR_STRUCTURE
1204 	  && comp->ts.type == BT_DERIVED)
1205 	{
1206 	  t = get_pdt_constructor (cons->expr, NULL, comp->ts.u.derived);
1207 	  if (!t)
1208 	    return t;
1209 	}
1210       else if (comp->ts.type == BT_DERIVED)
1211 	{
1212 	  t = get_pdt_constructor (NULL, &cons, comp->ts.u.derived);
1213 	  if (!t)
1214 	    return t;
1215 	}
1216      else if ((comp->attr.pdt_kind || comp->attr.pdt_len)
1217 	       && derived->attr.pdt_template)
1218 	{
1219 	  t = get_pdt_spec_expr (comp, cons->expr);
1220 	  if (!t)
1221 	    return t;
1222 	}
1223     }
1224   return t;
1225 }
1226 
1227 
1228 static bool resolve_fl_derived0 (gfc_symbol *sym);
1229 static bool resolve_fl_struct (gfc_symbol *sym);
1230 
1231 
1232 /* Resolve all of the elements of a structure constructor and make sure that
1233    the types are correct. The 'init' flag indicates that the given
1234    constructor is an initializer.  */
1235 
1236 static bool
1237 resolve_structure_cons (gfc_expr *expr, int init)
1238 {
1239   gfc_constructor *cons;
1240   gfc_component *comp;
1241   bool t;
1242   symbol_attribute a;
1243 
1244   t = true;
1245 
1246   if (expr->ts.type == BT_DERIVED || expr->ts.type == BT_UNION)
1247     {
1248       if (expr->ts.u.derived->attr.flavor == FL_DERIVED)
1249         resolve_fl_derived0 (expr->ts.u.derived);
1250       else
1251         resolve_fl_struct (expr->ts.u.derived);
1252 
1253       /* If this is a Parameterized Derived Type template, find the
1254 	 instance corresponding to the PDT kind parameters.  */
1255       if (expr->ts.u.derived->attr.pdt_template)
1256 	{
1257 	  param_list = NULL;
1258 	  t = get_pdt_constructor (expr, NULL, expr->ts.u.derived);
1259 	  if (!t)
1260 	    return t;
1261 	  gfc_get_pdt_instance (param_list, &expr->ts.u.derived, NULL);
1262 
1263 	  expr->param_list = gfc_copy_actual_arglist (param_list);
1264 
1265 	  if (param_list)
1266 	    gfc_free_actual_arglist (param_list);
1267 
1268 	  if (!expr->ts.u.derived->attr.pdt_type)
1269 	    return false;
1270 	}
1271     }
1272 
1273   cons = gfc_constructor_first (expr->value.constructor);
1274 
1275   /* A constructor may have references if it is the result of substituting a
1276      parameter variable.  In this case we just pull out the component we
1277      want.  */
1278   if (expr->ref)
1279     comp = expr->ref->u.c.sym->components;
1280   else
1281     comp = expr->ts.u.derived->components;
1282 
1283   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
1284     {
1285       int rank;
1286 
1287       if (!cons->expr)
1288 	continue;
1289 
1290       /* Unions use an EXPR_NULL contrived expression to tell the translation
1291          phase to generate an initializer of the appropriate length.
1292          Ignore it here.  */
1293       if (cons->expr->ts.type == BT_UNION && cons->expr->expr_type == EXPR_NULL)
1294         continue;
1295 
1296       if (!gfc_resolve_expr (cons->expr))
1297 	{
1298 	  t = false;
1299 	  continue;
1300 	}
1301 
1302       rank = comp->as ? comp->as->rank : 0;
1303       if (comp->ts.type == BT_CLASS
1304 	  && !comp->ts.u.derived->attr.unlimited_polymorphic
1305 	  && CLASS_DATA (comp)->as)
1306  	rank = CLASS_DATA (comp)->as->rank;
1307 
1308       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
1309 	  && (comp->attr.allocatable || cons->expr->rank))
1310 	{
1311 	  gfc_error ("The rank of the element in the structure "
1312 		     "constructor at %L does not match that of the "
1313 		     "component (%d/%d)", &cons->expr->where,
1314 		     cons->expr->rank, rank);
1315 	  t = false;
1316 	}
1317 
1318       /* If we don't have the right type, try to convert it.  */
1319 
1320       if (!comp->attr.proc_pointer &&
1321 	  !gfc_compare_types (&cons->expr->ts, &comp->ts))
1322 	{
1323 	  if (strcmp (comp->name, "_extends") == 0)
1324 	    {
1325 	      /* Can afford to be brutal with the _extends initializer.
1326 		 The derived type can get lost because it is PRIVATE
1327 		 but it is not usage constrained by the standard.  */
1328 	      cons->expr->ts = comp->ts;
1329 	    }
1330 	  else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1331 	    {
1332 	      gfc_error ("The element in the structure constructor at %L, "
1333 			 "for pointer component %qs, is %s but should be %s",
1334 			 &cons->expr->where, comp->name,
1335 			 gfc_basic_typename (cons->expr->ts.type),
1336 			 gfc_basic_typename (comp->ts.type));
1337 	      t = false;
1338 	    }
1339 	  else
1340 	    {
1341 	      bool t2 = gfc_convert_type (cons->expr, &comp->ts, 1);
1342 	      if (t)
1343 		t = t2;
1344 	    }
1345 	}
1346 
1347       /* For strings, the length of the constructor should be the same as
1348 	 the one of the structure, ensure this if the lengths are known at
1349  	 compile time and when we are dealing with PARAMETER or structure
1350 	 constructors.  */
1351       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1352 	  && comp->ts.u.cl->length
1353 	  && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1354 	  && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1355 	  && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1356 	  && cons->expr->rank != 0
1357 	  && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1358 		      comp->ts.u.cl->length->value.integer) != 0)
1359 	{
1360 	  if (cons->expr->expr_type == EXPR_VARIABLE
1361 	      && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1362 	    {
1363 	      /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1364 		 to make use of the gfc_resolve_character_array_constructor
1365 		 machinery.  The expression is later simplified away to
1366 		 an array of string literals.  */
1367 	      gfc_expr *para = cons->expr;
1368 	      cons->expr = gfc_get_expr ();
1369 	      cons->expr->ts = para->ts;
1370 	      cons->expr->where = para->where;
1371 	      cons->expr->expr_type = EXPR_ARRAY;
1372 	      cons->expr->rank = para->rank;
1373 	      cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1374 	      gfc_constructor_append_expr (&cons->expr->value.constructor,
1375 					   para, &cons->expr->where);
1376 	    }
1377 
1378 	  if (cons->expr->expr_type == EXPR_ARRAY)
1379 	    {
1380 	      /* Rely on the cleanup of the namespace to deal correctly with
1381 		 the old charlen.  (There was a block here that attempted to
1382 		 remove the charlen but broke the chain in so doing.)  */
1383 	      cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1384 	      cons->expr->ts.u.cl->length_from_typespec = true;
1385 	      cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1386 	      gfc_resolve_character_array_constructor (cons->expr);
1387 	    }
1388 	}
1389 
1390       if (cons->expr->expr_type == EXPR_NULL
1391 	  && !(comp->attr.pointer || comp->attr.allocatable
1392 	       || comp->attr.proc_pointer || comp->ts.f90_type == BT_VOID
1393 	       || (comp->ts.type == BT_CLASS
1394 		   && (CLASS_DATA (comp)->attr.class_pointer
1395 		       || CLASS_DATA (comp)->attr.allocatable))))
1396 	{
1397 	  t = false;
1398 	  gfc_error ("The NULL in the structure constructor at %L is "
1399 		     "being applied to component %qs, which is neither "
1400 		     "a POINTER nor ALLOCATABLE", &cons->expr->where,
1401 		     comp->name);
1402 	}
1403 
1404       if (comp->attr.proc_pointer && comp->ts.interface)
1405 	{
1406 	  /* Check procedure pointer interface.  */
1407 	  gfc_symbol *s2 = NULL;
1408 	  gfc_component *c2;
1409 	  const char *name;
1410 	  char err[200];
1411 
1412 	  c2 = gfc_get_proc_ptr_comp (cons->expr);
1413 	  if (c2)
1414 	    {
1415 	      s2 = c2->ts.interface;
1416 	      name = c2->name;
1417 	    }
1418 	  else if (cons->expr->expr_type == EXPR_FUNCTION)
1419 	    {
1420 	      s2 = cons->expr->symtree->n.sym->result;
1421 	      name = cons->expr->symtree->n.sym->result->name;
1422 	    }
1423 	  else if (cons->expr->expr_type != EXPR_NULL)
1424 	    {
1425 	      s2 = cons->expr->symtree->n.sym;
1426 	      name = cons->expr->symtree->n.sym->name;
1427 	    }
1428 
1429 	  if (s2 && !gfc_compare_interfaces (comp->ts.interface, s2, name, 0, 1,
1430 					     err, sizeof (err), NULL, NULL))
1431 	    {
1432 	      gfc_error_opt (OPT_Wargument_mismatch,
1433 			     "Interface mismatch for procedure-pointer "
1434 			     "component %qs in structure constructor at %L:"
1435 			     " %s", comp->name, &cons->expr->where, err);
1436 	      return false;
1437 	    }
1438 	}
1439 
1440       if (!comp->attr.pointer || comp->attr.proc_pointer
1441 	  || cons->expr->expr_type == EXPR_NULL)
1442 	continue;
1443 
1444       a = gfc_expr_attr (cons->expr);
1445 
1446       if (!a.pointer && !a.target)
1447 	{
1448 	  t = false;
1449 	  gfc_error ("The element in the structure constructor at %L, "
1450 		     "for pointer component %qs should be a POINTER or "
1451 		     "a TARGET", &cons->expr->where, comp->name);
1452 	}
1453 
1454       if (init)
1455 	{
1456 	  /* F08:C461. Additional checks for pointer initialization.  */
1457 	  if (a.allocatable)
1458 	    {
1459 	      t = false;
1460 	      gfc_error ("Pointer initialization target at %L "
1461 			 "must not be ALLOCATABLE", &cons->expr->where);
1462 	    }
1463 	  if (!a.save)
1464 	    {
1465 	      t = false;
1466 	      gfc_error ("Pointer initialization target at %L "
1467 			 "must have the SAVE attribute", &cons->expr->where);
1468 	    }
1469 	}
1470 
1471       /* F2003, C1272 (3).  */
1472       bool impure = cons->expr->expr_type == EXPR_VARIABLE
1473 		    && (gfc_impure_variable (cons->expr->symtree->n.sym)
1474 			|| gfc_is_coindexed (cons->expr));
1475       if (impure && gfc_pure (NULL))
1476 	{
1477 	  t = false;
1478 	  gfc_error ("Invalid expression in the structure constructor for "
1479 		     "pointer component %qs at %L in PURE procedure",
1480 		     comp->name, &cons->expr->where);
1481 	}
1482 
1483       if (impure)
1484 	gfc_unset_implicit_pure (NULL);
1485     }
1486 
1487   return t;
1488 }
1489 
1490 
1491 /****************** Expression name resolution ******************/
1492 
1493 /* Returns 0 if a symbol was not declared with a type or
1494    attribute declaration statement, nonzero otherwise.  */
1495 
1496 static int
1497 was_declared (gfc_symbol *sym)
1498 {
1499   symbol_attribute a;
1500 
1501   a = sym->attr;
1502 
1503   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1504     return 1;
1505 
1506   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1507       || a.optional || a.pointer || a.save || a.target || a.volatile_
1508       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1509       || a.asynchronous || a.codimension)
1510     return 1;
1511 
1512   return 0;
1513 }
1514 
1515 
1516 /* Determine if a symbol is generic or not.  */
1517 
1518 static int
1519 generic_sym (gfc_symbol *sym)
1520 {
1521   gfc_symbol *s;
1522 
1523   if (sym->attr.generic ||
1524       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1525     return 1;
1526 
1527   if (was_declared (sym) || sym->ns->parent == NULL)
1528     return 0;
1529 
1530   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1531 
1532   if (s != NULL)
1533     {
1534       if (s == sym)
1535 	return 0;
1536       else
1537 	return generic_sym (s);
1538     }
1539 
1540   return 0;
1541 }
1542 
1543 
1544 /* Determine if a symbol is specific or not.  */
1545 
1546 static int
1547 specific_sym (gfc_symbol *sym)
1548 {
1549   gfc_symbol *s;
1550 
1551   if (sym->attr.if_source == IFSRC_IFBODY
1552       || sym->attr.proc == PROC_MODULE
1553       || sym->attr.proc == PROC_INTERNAL
1554       || sym->attr.proc == PROC_ST_FUNCTION
1555       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1556       || sym->attr.external)
1557     return 1;
1558 
1559   if (was_declared (sym) || sym->ns->parent == NULL)
1560     return 0;
1561 
1562   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1563 
1564   return (s == NULL) ? 0 : specific_sym (s);
1565 }
1566 
1567 
1568 /* Figure out if the procedure is specific, generic or unknown.  */
1569 
1570 enum proc_type
1571 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN };
1572 
1573 static proc_type
1574 procedure_kind (gfc_symbol *sym)
1575 {
1576   if (generic_sym (sym))
1577     return PTYPE_GENERIC;
1578 
1579   if (specific_sym (sym))
1580     return PTYPE_SPECIFIC;
1581 
1582   return PTYPE_UNKNOWN;
1583 }
1584 
1585 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1586    is nonzero when matching actual arguments.  */
1587 
1588 static int need_full_assumed_size = 0;
1589 
1590 static bool
1591 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1592 {
1593   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1594       return false;
1595 
1596   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1597      What should it be?  */
1598   if (e->ref && (e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1599 	  && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1600 	       && (e->ref->u.ar.type == AR_FULL))
1601     {
1602       gfc_error ("The upper bound in the last dimension must "
1603 		 "appear in the reference to the assumed size "
1604 		 "array %qs at %L", sym->name, &e->where);
1605       return true;
1606     }
1607   return false;
1608 }
1609 
1610 
1611 /* Look for bad assumed size array references in argument expressions
1612   of elemental and array valued intrinsic procedures.  Since this is
1613   called from procedure resolution functions, it only recurses at
1614   operators.  */
1615 
1616 static bool
1617 resolve_assumed_size_actual (gfc_expr *e)
1618 {
1619   if (e == NULL)
1620    return false;
1621 
1622   switch (e->expr_type)
1623     {
1624     case EXPR_VARIABLE:
1625       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1626 	return true;
1627       break;
1628 
1629     case EXPR_OP:
1630       if (resolve_assumed_size_actual (e->value.op.op1)
1631 	  || resolve_assumed_size_actual (e->value.op.op2))
1632 	return true;
1633       break;
1634 
1635     default:
1636       break;
1637     }
1638   return false;
1639 }
1640 
1641 
1642 /* Check a generic procedure, passed as an actual argument, to see if
1643    there is a matching specific name.  If none, it is an error, and if
1644    more than one, the reference is ambiguous.  */
1645 static int
1646 count_specific_procs (gfc_expr *e)
1647 {
1648   int n;
1649   gfc_interface *p;
1650   gfc_symbol *sym;
1651 
1652   n = 0;
1653   sym = e->symtree->n.sym;
1654 
1655   for (p = sym->generic; p; p = p->next)
1656     if (strcmp (sym->name, p->sym->name) == 0)
1657       {
1658 	e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1659 				       sym->name);
1660 	n++;
1661       }
1662 
1663   if (n > 1)
1664     gfc_error ("%qs at %L is ambiguous", e->symtree->n.sym->name,
1665 	       &e->where);
1666 
1667   if (n == 0)
1668     gfc_error ("GENERIC procedure %qs is not allowed as an actual "
1669 	       "argument at %L", sym->name, &e->where);
1670 
1671   return n;
1672 }
1673 
1674 
1675 /* See if a call to sym could possibly be a not allowed RECURSION because of
1676    a missing RECURSIVE declaration.  This means that either sym is the current
1677    context itself, or sym is the parent of a contained procedure calling its
1678    non-RECURSIVE containing procedure.
1679    This also works if sym is an ENTRY.  */
1680 
1681 static bool
1682 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1683 {
1684   gfc_symbol* proc_sym;
1685   gfc_symbol* context_proc;
1686   gfc_namespace* real_context;
1687 
1688   if (sym->attr.flavor == FL_PROGRAM
1689       || gfc_fl_struct (sym->attr.flavor))
1690     return false;
1691 
1692   /* If we've got an ENTRY, find real procedure.  */
1693   if (sym->attr.entry && sym->ns->entries)
1694     proc_sym = sym->ns->entries->sym;
1695   else
1696     proc_sym = sym;
1697 
1698   /* If sym is RECURSIVE, all is well of course.  */
1699   if (proc_sym->attr.recursive || flag_recursive)
1700     return false;
1701 
1702   /* Find the context procedure's "real" symbol if it has entries.
1703      We look for a procedure symbol, so recurse on the parents if we don't
1704      find one (like in case of a BLOCK construct).  */
1705   for (real_context = context; ; real_context = real_context->parent)
1706     {
1707       /* We should find something, eventually!  */
1708       gcc_assert (real_context);
1709 
1710       context_proc = (real_context->entries ? real_context->entries->sym
1711 					    : real_context->proc_name);
1712 
1713       /* In some special cases, there may not be a proc_name, like for this
1714 	 invalid code:
1715 	 real(bad_kind()) function foo () ...
1716 	 when checking the call to bad_kind ().
1717 	 In these cases, we simply return here and assume that the
1718 	 call is ok.  */
1719       if (!context_proc)
1720 	return false;
1721 
1722       if (context_proc->attr.flavor != FL_LABEL)
1723 	break;
1724     }
1725 
1726   /* A call from sym's body to itself is recursion, of course.  */
1727   if (context_proc == proc_sym)
1728     return true;
1729 
1730   /* The same is true if context is a contained procedure and sym the
1731      containing one.  */
1732   if (context_proc->attr.contained)
1733     {
1734       gfc_symbol* parent_proc;
1735 
1736       gcc_assert (context->parent);
1737       parent_proc = (context->parent->entries ? context->parent->entries->sym
1738 					      : context->parent->proc_name);
1739 
1740       if (parent_proc == proc_sym)
1741 	return true;
1742     }
1743 
1744   return false;
1745 }
1746 
1747 
1748 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1749    its typespec and formal argument list.  */
1750 
1751 bool
1752 gfc_resolve_intrinsic (gfc_symbol *sym, locus *loc)
1753 {
1754   gfc_intrinsic_sym* isym = NULL;
1755   const char* symstd;
1756 
1757   if (sym->formal)
1758     return true;
1759 
1760   /* Already resolved.  */
1761   if (sym->from_intmod && sym->ts.type != BT_UNKNOWN)
1762     return true;
1763 
1764   /* We already know this one is an intrinsic, so we don't call
1765      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1766      gfc_find_subroutine directly to check whether it is a function or
1767      subroutine.  */
1768 
1769   if (sym->intmod_sym_id && sym->attr.subroutine)
1770     {
1771       gfc_isym_id id = gfc_isym_id_by_intmod_sym (sym);
1772       isym = gfc_intrinsic_subroutine_by_id (id);
1773     }
1774   else if (sym->intmod_sym_id)
1775     {
1776       gfc_isym_id id = gfc_isym_id_by_intmod_sym (sym);
1777       isym = gfc_intrinsic_function_by_id (id);
1778     }
1779   else if (!sym->attr.subroutine)
1780     isym = gfc_find_function (sym->name);
1781 
1782   if (isym && !sym->attr.subroutine)
1783     {
1784       if (sym->ts.type != BT_UNKNOWN && warn_surprising
1785 	  && !sym->attr.implicit_type)
1786 	gfc_warning (OPT_Wsurprising,
1787 		     "Type specified for intrinsic function %qs at %L is"
1788 		      " ignored", sym->name, &sym->declared_at);
1789 
1790       if (!sym->attr.function &&
1791 	  !gfc_add_function(&sym->attr, sym->name, loc))
1792 	return false;
1793 
1794       sym->ts = isym->ts;
1795     }
1796   else if (isym || (isym = gfc_find_subroutine (sym->name)))
1797     {
1798       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1799 	{
1800 	  gfc_error ("Intrinsic subroutine %qs at %L shall not have a type"
1801 		      " specifier", sym->name, &sym->declared_at);
1802 	  return false;
1803 	}
1804 
1805       if (!sym->attr.subroutine &&
1806 	  !gfc_add_subroutine(&sym->attr, sym->name, loc))
1807 	return false;
1808     }
1809   else
1810     {
1811       gfc_error ("%qs declared INTRINSIC at %L does not exist", sym->name,
1812 		 &sym->declared_at);
1813       return false;
1814     }
1815 
1816   gfc_copy_formal_args_intr (sym, isym, NULL);
1817 
1818   sym->attr.pure = isym->pure;
1819   sym->attr.elemental = isym->elemental;
1820 
1821   /* Check it is actually available in the standard settings.  */
1822   if (!gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at))
1823     {
1824       gfc_error ("The intrinsic %qs declared INTRINSIC at %L is not "
1825 		 "available in the current standard settings but %s. Use "
1826 		 "an appropriate %<-std=*%> option or enable "
1827 		 "%<-fall-intrinsics%> in order to use it.",
1828 		 sym->name, &sym->declared_at, symstd);
1829       return false;
1830     }
1831 
1832   return true;
1833 }
1834 
1835 
1836 /* Resolve a procedure expression, like passing it to a called procedure or as
1837    RHS for a procedure pointer assignment.  */
1838 
1839 static bool
1840 resolve_procedure_expression (gfc_expr* expr)
1841 {
1842   gfc_symbol* sym;
1843 
1844   if (expr->expr_type != EXPR_VARIABLE)
1845     return true;
1846   gcc_assert (expr->symtree);
1847 
1848   sym = expr->symtree->n.sym;
1849 
1850   if (sym->attr.intrinsic)
1851     gfc_resolve_intrinsic (sym, &expr->where);
1852 
1853   if (sym->attr.flavor != FL_PROCEDURE
1854       || (sym->attr.function && sym->result == sym))
1855     return true;
1856 
1857   /* A non-RECURSIVE procedure that is used as procedure expression within its
1858      own body is in danger of being called recursively.  */
1859   if (is_illegal_recursion (sym, gfc_current_ns))
1860     gfc_warning (0, "Non-RECURSIVE procedure %qs at %L is possibly calling"
1861 		 " itself recursively.  Declare it RECURSIVE or use"
1862 		 " %<-frecursive%>", sym->name, &expr->where);
1863 
1864   return true;
1865 }
1866 
1867 
1868 /* Check that name is not a derived type.  */
1869 
1870 static bool
1871 is_dt_name (const char *name)
1872 {
1873   gfc_symbol *dt_list, *dt_first;
1874 
1875   dt_list = dt_first = gfc_derived_types;
1876   for (; dt_list; dt_list = dt_list->dt_next)
1877     {
1878       if (strcmp(dt_list->name, name) == 0)
1879 	return true;
1880       if (dt_first == dt_list->dt_next)
1881 	break;
1882     }
1883   return false;
1884 }
1885 
1886 
1887 /* Resolve an actual argument list.  Most of the time, this is just
1888    resolving the expressions in the list.
1889    The exception is that we sometimes have to decide whether arguments
1890    that look like procedure arguments are really simple variable
1891    references.  */
1892 
1893 static bool
1894 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1895 			bool no_formal_args)
1896 {
1897   gfc_symbol *sym;
1898   gfc_symtree *parent_st;
1899   gfc_expr *e;
1900   gfc_component *comp;
1901   int save_need_full_assumed_size;
1902   bool return_value = false;
1903   bool actual_arg_sav = actual_arg, first_actual_arg_sav = first_actual_arg;
1904 
1905   actual_arg = true;
1906   first_actual_arg = true;
1907 
1908   for (; arg; arg = arg->next)
1909     {
1910       e = arg->expr;
1911       if (e == NULL)
1912 	{
1913 	  /* Check the label is a valid branching target.  */
1914 	  if (arg->label)
1915 	    {
1916 	      if (arg->label->defined == ST_LABEL_UNKNOWN)
1917 		{
1918 		  gfc_error ("Label %d referenced at %L is never defined",
1919 			     arg->label->value, &arg->label->where);
1920 		  goto cleanup;
1921 		}
1922 	    }
1923 	  first_actual_arg = false;
1924 	  continue;
1925 	}
1926 
1927       if (e->expr_type == EXPR_VARIABLE
1928 	    && e->symtree->n.sym->attr.generic
1929 	    && no_formal_args
1930 	    && count_specific_procs (e) != 1)
1931 	goto cleanup;
1932 
1933       if (e->ts.type != BT_PROCEDURE)
1934 	{
1935 	  save_need_full_assumed_size = need_full_assumed_size;
1936 	  if (e->expr_type != EXPR_VARIABLE)
1937 	    need_full_assumed_size = 0;
1938 	  if (!gfc_resolve_expr (e))
1939 	    goto cleanup;
1940 	  need_full_assumed_size = save_need_full_assumed_size;
1941 	  goto argument_list;
1942 	}
1943 
1944       /* See if the expression node should really be a variable reference.  */
1945 
1946       sym = e->symtree->n.sym;
1947 
1948       if (sym->attr.flavor == FL_PROCEDURE && is_dt_name (sym->name))
1949 	{
1950 	  gfc_error ("Derived type %qs is used as an actual "
1951 		     "argument at %L", sym->name, &e->where);
1952 	  goto cleanup;
1953 	}
1954 
1955       if (sym->attr.flavor == FL_PROCEDURE
1956 	  || sym->attr.intrinsic
1957 	  || sym->attr.external)
1958 	{
1959 	  int actual_ok;
1960 
1961 	  /* If a procedure is not already determined to be something else
1962 	     check if it is intrinsic.  */
1963 	  if (gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1964 	    sym->attr.intrinsic = 1;
1965 
1966 	  if (sym->attr.proc == PROC_ST_FUNCTION)
1967 	    {
1968 	      gfc_error ("Statement function %qs at %L is not allowed as an "
1969 			 "actual argument", sym->name, &e->where);
1970 	    }
1971 
1972 	  actual_ok = gfc_intrinsic_actual_ok (sym->name,
1973 					       sym->attr.subroutine);
1974 	  if (sym->attr.intrinsic && actual_ok == 0)
1975 	    {
1976 	      gfc_error ("Intrinsic %qs at %L is not allowed as an "
1977 			 "actual argument", sym->name, &e->where);
1978 	    }
1979 
1980 	  if (sym->attr.contained && !sym->attr.use_assoc
1981 	      && sym->ns->proc_name->attr.flavor != FL_MODULE)
1982 	    {
1983 	      if (!gfc_notify_std (GFC_STD_F2008, "Internal procedure %qs is"
1984 				   " used as actual argument at %L",
1985 				   sym->name, &e->where))
1986 		goto cleanup;
1987 	    }
1988 
1989 	  if (sym->attr.elemental && !sym->attr.intrinsic)
1990 	    {
1991 	      gfc_error ("ELEMENTAL non-INTRINSIC procedure %qs is not "
1992 			 "allowed as an actual argument at %L", sym->name,
1993 			 &e->where);
1994 	    }
1995 
1996 	  /* Check if a generic interface has a specific procedure
1997 	    with the same name before emitting an error.  */
1998 	  if (sym->attr.generic && count_specific_procs (e) != 1)
1999 	    goto cleanup;
2000 
2001 	  /* Just in case a specific was found for the expression.  */
2002 	  sym = e->symtree->n.sym;
2003 
2004 	  /* If the symbol is the function that names the current (or
2005 	     parent) scope, then we really have a variable reference.  */
2006 
2007 	  if (gfc_is_function_return_value (sym, sym->ns))
2008 	    goto got_variable;
2009 
2010 	  /* If all else fails, see if we have a specific intrinsic.  */
2011 	  if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
2012 	    {
2013 	      gfc_intrinsic_sym *isym;
2014 
2015 	      isym = gfc_find_function (sym->name);
2016 	      if (isym == NULL || !isym->specific)
2017 		{
2018 		  gfc_error ("Unable to find a specific INTRINSIC procedure "
2019 			     "for the reference %qs at %L", sym->name,
2020 			     &e->where);
2021 		  goto cleanup;
2022 		}
2023 	      sym->ts = isym->ts;
2024 	      sym->attr.intrinsic = 1;
2025 	      sym->attr.function = 1;
2026 	    }
2027 
2028 	  if (!gfc_resolve_expr (e))
2029 	    goto cleanup;
2030 	  goto argument_list;
2031 	}
2032 
2033       /* See if the name is a module procedure in a parent unit.  */
2034 
2035       if (was_declared (sym) || sym->ns->parent == NULL)
2036 	goto got_variable;
2037 
2038       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
2039 	{
2040 	  gfc_error ("Symbol %qs at %L is ambiguous", sym->name, &e->where);
2041 	  goto cleanup;
2042 	}
2043 
2044       if (parent_st == NULL)
2045 	goto got_variable;
2046 
2047       sym = parent_st->n.sym;
2048       e->symtree = parent_st;		/* Point to the right thing.  */
2049 
2050       if (sym->attr.flavor == FL_PROCEDURE
2051 	  || sym->attr.intrinsic
2052 	  || sym->attr.external)
2053 	{
2054 	  if (!gfc_resolve_expr (e))
2055 	    goto cleanup;
2056 	  goto argument_list;
2057 	}
2058 
2059     got_variable:
2060       e->expr_type = EXPR_VARIABLE;
2061       e->ts = sym->ts;
2062       if ((sym->as != NULL && sym->ts.type != BT_CLASS)
2063 	  || (sym->ts.type == BT_CLASS && sym->attr.class_ok
2064 	      && CLASS_DATA (sym)->as))
2065 	{
2066 	  e->rank = sym->ts.type == BT_CLASS
2067 		    ? CLASS_DATA (sym)->as->rank : sym->as->rank;
2068 	  e->ref = gfc_get_ref ();
2069 	  e->ref->type = REF_ARRAY;
2070 	  e->ref->u.ar.type = AR_FULL;
2071 	  e->ref->u.ar.as = sym->ts.type == BT_CLASS
2072 			    ? CLASS_DATA (sym)->as : sym->as;
2073 	}
2074 
2075       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
2076 	 primary.c (match_actual_arg). If above code determines that it
2077 	 is a  variable instead, it needs to be resolved as it was not
2078 	 done at the beginning of this function.  */
2079       save_need_full_assumed_size = need_full_assumed_size;
2080       if (e->expr_type != EXPR_VARIABLE)
2081 	need_full_assumed_size = 0;
2082       if (!gfc_resolve_expr (e))
2083 	goto cleanup;
2084       need_full_assumed_size = save_need_full_assumed_size;
2085 
2086     argument_list:
2087       /* Check argument list functions %VAL, %LOC and %REF.  There is
2088 	 nothing to do for %REF.  */
2089       if (arg->name && arg->name[0] == '%')
2090 	{
2091 	  if (strcmp ("%VAL", arg->name) == 0)
2092 	    {
2093 	      if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
2094 		{
2095 		  gfc_error ("By-value argument at %L is not of numeric "
2096 			     "type", &e->where);
2097 		  goto cleanup;
2098 		}
2099 
2100 	      if (e->rank)
2101 		{
2102 		  gfc_error ("By-value argument at %L cannot be an array or "
2103 			     "an array section", &e->where);
2104 		  goto cleanup;
2105 		}
2106 
2107 	      /* Intrinsics are still PROC_UNKNOWN here.  However,
2108 		 since same file external procedures are not resolvable
2109 		 in gfortran, it is a good deal easier to leave them to
2110 		 intrinsic.c.  */
2111 	      if (ptype != PROC_UNKNOWN
2112 		  && ptype != PROC_DUMMY
2113 		  && ptype != PROC_EXTERNAL
2114 		  && ptype != PROC_MODULE)
2115 		{
2116 		  gfc_error ("By-value argument at %L is not allowed "
2117 			     "in this context", &e->where);
2118 		  goto cleanup;
2119 		}
2120 	    }
2121 
2122 	  /* Statement functions have already been excluded above.  */
2123 	  else if (strcmp ("%LOC", arg->name) == 0
2124 		   && e->ts.type == BT_PROCEDURE)
2125 	    {
2126 	      if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
2127 		{
2128 		  gfc_error ("Passing internal procedure at %L by location "
2129 			     "not allowed", &e->where);
2130 		  goto cleanup;
2131 		}
2132 	    }
2133 	}
2134 
2135       comp = gfc_get_proc_ptr_comp(e);
2136       if (e->expr_type == EXPR_VARIABLE
2137 	  && comp && comp->attr.elemental)
2138 	{
2139 	    gfc_error ("ELEMENTAL procedure pointer component %qs is not "
2140 		       "allowed as an actual argument at %L", comp->name,
2141 		       &e->where);
2142 	}
2143 
2144       /* Fortran 2008, C1237.  */
2145       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
2146 	  && gfc_has_ultimate_pointer (e))
2147 	{
2148 	  gfc_error ("Coindexed actual argument at %L with ultimate pointer "
2149 		     "component", &e->where);
2150 	  goto cleanup;
2151 	}
2152 
2153       first_actual_arg = false;
2154     }
2155 
2156   return_value = true;
2157 
2158 cleanup:
2159   actual_arg = actual_arg_sav;
2160   first_actual_arg = first_actual_arg_sav;
2161 
2162   return return_value;
2163 }
2164 
2165 
2166 /* Do the checks of the actual argument list that are specific to elemental
2167    procedures.  If called with c == NULL, we have a function, otherwise if
2168    expr == NULL, we have a subroutine.  */
2169 
2170 static bool
2171 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
2172 {
2173   gfc_actual_arglist *arg0;
2174   gfc_actual_arglist *arg;
2175   gfc_symbol *esym = NULL;
2176   gfc_intrinsic_sym *isym = NULL;
2177   gfc_expr *e = NULL;
2178   gfc_intrinsic_arg *iformal = NULL;
2179   gfc_formal_arglist *eformal = NULL;
2180   bool formal_optional = false;
2181   bool set_by_optional = false;
2182   int i;
2183   int rank = 0;
2184 
2185   /* Is this an elemental procedure?  */
2186   if (expr && expr->value.function.actual != NULL)
2187     {
2188       if (expr->value.function.esym != NULL
2189 	  && expr->value.function.esym->attr.elemental)
2190 	{
2191 	  arg0 = expr->value.function.actual;
2192 	  esym = expr->value.function.esym;
2193 	}
2194       else if (expr->value.function.isym != NULL
2195 	       && expr->value.function.isym->elemental)
2196 	{
2197 	  arg0 = expr->value.function.actual;
2198 	  isym = expr->value.function.isym;
2199 	}
2200       else
2201 	return true;
2202     }
2203   else if (c && c->ext.actual != NULL)
2204     {
2205       arg0 = c->ext.actual;
2206 
2207       if (c->resolved_sym)
2208 	esym = c->resolved_sym;
2209       else
2210 	esym = c->symtree->n.sym;
2211       gcc_assert (esym);
2212 
2213       if (!esym->attr.elemental)
2214 	return true;
2215     }
2216   else
2217     return true;
2218 
2219   /* The rank of an elemental is the rank of its array argument(s).  */
2220   for (arg = arg0; arg; arg = arg->next)
2221     {
2222       if (arg->expr != NULL && arg->expr->rank != 0)
2223 	{
2224 	  rank = arg->expr->rank;
2225 	  if (arg->expr->expr_type == EXPR_VARIABLE
2226 	      && arg->expr->symtree->n.sym->attr.optional)
2227 	    set_by_optional = true;
2228 
2229 	  /* Function specific; set the result rank and shape.  */
2230 	  if (expr)
2231 	    {
2232 	      expr->rank = rank;
2233 	      if (!expr->shape && arg->expr->shape)
2234 		{
2235 		  expr->shape = gfc_get_shape (rank);
2236 		  for (i = 0; i < rank; i++)
2237 		    mpz_init_set (expr->shape[i], arg->expr->shape[i]);
2238 		}
2239 	    }
2240 	  break;
2241 	}
2242     }
2243 
2244   /* If it is an array, it shall not be supplied as an actual argument
2245      to an elemental procedure unless an array of the same rank is supplied
2246      as an actual argument corresponding to a nonoptional dummy argument of
2247      that elemental procedure(12.4.1.5).  */
2248   formal_optional = false;
2249   if (isym)
2250     iformal = isym->formal;
2251   else
2252     eformal = esym->formal;
2253 
2254   for (arg = arg0; arg; arg = arg->next)
2255     {
2256       if (eformal)
2257 	{
2258 	  if (eformal->sym && eformal->sym->attr.optional)
2259 	    formal_optional = true;
2260 	  eformal = eformal->next;
2261 	}
2262       else if (isym && iformal)
2263 	{
2264 	  if (iformal->optional)
2265 	    formal_optional = true;
2266 	  iformal = iformal->next;
2267 	}
2268       else if (isym)
2269 	formal_optional = true;
2270 
2271       if (pedantic && arg->expr != NULL
2272 	  && arg->expr->expr_type == EXPR_VARIABLE
2273 	  && arg->expr->symtree->n.sym->attr.optional
2274 	  && formal_optional
2275 	  && arg->expr->rank
2276 	  && (set_by_optional || arg->expr->rank != rank)
2277 	  && !(isym && isym->id == GFC_ISYM_CONVERSION))
2278 	{
2279 	  gfc_warning (OPT_Wpedantic,
2280 		       "%qs at %L is an array and OPTIONAL; IF IT IS "
2281 		       "MISSING, it cannot be the actual argument of an "
2282 		       "ELEMENTAL procedure unless there is a non-optional "
2283 		       "argument with the same rank (12.4.1.5)",
2284 		       arg->expr->symtree->n.sym->name, &arg->expr->where);
2285 	}
2286     }
2287 
2288   for (arg = arg0; arg; arg = arg->next)
2289     {
2290       if (arg->expr == NULL || arg->expr->rank == 0)
2291 	continue;
2292 
2293       /* Being elemental, the last upper bound of an assumed size array
2294 	 argument must be present.  */
2295       if (resolve_assumed_size_actual (arg->expr))
2296 	return false;
2297 
2298       /* Elemental procedure's array actual arguments must conform.  */
2299       if (e != NULL)
2300 	{
2301 	  if (!gfc_check_conformance (arg->expr, e, "elemental procedure"))
2302 	    return false;
2303 	}
2304       else
2305 	e = arg->expr;
2306     }
2307 
2308   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
2309      is an array, the intent inout/out variable needs to be also an array.  */
2310   if (rank > 0 && esym && expr == NULL)
2311     for (eformal = esym->formal, arg = arg0; arg && eformal;
2312 	 arg = arg->next, eformal = eformal->next)
2313       if ((eformal->sym->attr.intent == INTENT_OUT
2314 	   || eformal->sym->attr.intent == INTENT_INOUT)
2315 	  && arg->expr && arg->expr->rank == 0)
2316 	{
2317 	  gfc_error ("Actual argument at %L for INTENT(%s) dummy %qs of "
2318 		     "ELEMENTAL subroutine %qs is a scalar, but another "
2319 		     "actual argument is an array", &arg->expr->where,
2320 		     (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
2321 		     : "INOUT", eformal->sym->name, esym->name);
2322 	  return false;
2323 	}
2324   return true;
2325 }
2326 
2327 
2328 /* This function does the checking of references to global procedures
2329    as defined in sections 18.1 and 14.1, respectively, of the Fortran
2330    77 and 95 standards.  It checks for a gsymbol for the name, making
2331    one if it does not already exist.  If it already exists, then the
2332    reference being resolved must correspond to the type of gsymbol.
2333    Otherwise, the new symbol is equipped with the attributes of the
2334    reference.  The corresponding code that is called in creating
2335    global entities is parse.c.
2336 
2337    In addition, for all but -std=legacy, the gsymbols are used to
2338    check the interfaces of external procedures from the same file.
2339    The namespace of the gsymbol is resolved and then, once this is
2340    done the interface is checked.  */
2341 
2342 
2343 static bool
2344 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
2345 {
2346   if (!gsym_ns->proc_name->attr.recursive)
2347     return true;
2348 
2349   if (sym->ns == gsym_ns)
2350     return false;
2351 
2352   if (sym->ns->parent && sym->ns->parent == gsym_ns)
2353     return false;
2354 
2355   return true;
2356 }
2357 
2358 static bool
2359 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
2360 {
2361   if (gsym_ns->entries)
2362     {
2363       gfc_entry_list *entry = gsym_ns->entries;
2364 
2365       for (; entry; entry = entry->next)
2366 	{
2367 	  if (strcmp (sym->name, entry->sym->name) == 0)
2368 	    {
2369 	      if (strcmp (gsym_ns->proc_name->name,
2370 			  sym->ns->proc_name->name) == 0)
2371 		return false;
2372 
2373 	      if (sym->ns->parent
2374 		  && strcmp (gsym_ns->proc_name->name,
2375 			     sym->ns->parent->proc_name->name) == 0)
2376 		return false;
2377 	    }
2378 	}
2379     }
2380   return true;
2381 }
2382 
2383 
2384 /* Check for the requirement of an explicit interface. F08:12.4.2.2.  */
2385 
2386 bool
2387 gfc_explicit_interface_required (gfc_symbol *sym, char *errmsg, int err_len)
2388 {
2389   gfc_formal_arglist *arg = gfc_sym_get_dummy_args (sym);
2390 
2391   for ( ; arg; arg = arg->next)
2392     {
2393       if (!arg->sym)
2394 	continue;
2395 
2396       if (arg->sym->attr.allocatable)  /* (2a)  */
2397 	{
2398 	  strncpy (errmsg, _("allocatable argument"), err_len);
2399 	  return true;
2400 	}
2401       else if (arg->sym->attr.asynchronous)
2402 	{
2403 	  strncpy (errmsg, _("asynchronous argument"), err_len);
2404 	  return true;
2405 	}
2406       else if (arg->sym->attr.optional)
2407 	{
2408 	  strncpy (errmsg, _("optional argument"), err_len);
2409 	  return true;
2410 	}
2411       else if (arg->sym->attr.pointer)
2412 	{
2413 	  strncpy (errmsg, _("pointer argument"), err_len);
2414 	  return true;
2415 	}
2416       else if (arg->sym->attr.target)
2417 	{
2418 	  strncpy (errmsg, _("target argument"), err_len);
2419 	  return true;
2420 	}
2421       else if (arg->sym->attr.value)
2422 	{
2423 	  strncpy (errmsg, _("value argument"), err_len);
2424 	  return true;
2425 	}
2426       else if (arg->sym->attr.volatile_)
2427 	{
2428 	  strncpy (errmsg, _("volatile argument"), err_len);
2429 	  return true;
2430 	}
2431       else if (arg->sym->as && arg->sym->as->type == AS_ASSUMED_SHAPE)  /* (2b)  */
2432 	{
2433 	  strncpy (errmsg, _("assumed-shape argument"), err_len);
2434 	  return true;
2435 	}
2436       else if (arg->sym->as && arg->sym->as->type == AS_ASSUMED_RANK)  /* TS 29113, 6.2.  */
2437 	{
2438 	  strncpy (errmsg, _("assumed-rank argument"), err_len);
2439 	  return true;
2440 	}
2441       else if (arg->sym->attr.codimension)  /* (2c)  */
2442 	{
2443 	  strncpy (errmsg, _("coarray argument"), err_len);
2444 	  return true;
2445 	}
2446       else if (false)  /* (2d) TODO: parametrized derived type  */
2447 	{
2448 	  strncpy (errmsg, _("parametrized derived type argument"), err_len);
2449 	  return true;
2450 	}
2451       else if (arg->sym->ts.type == BT_CLASS)  /* (2e)  */
2452 	{
2453 	  strncpy (errmsg, _("polymorphic argument"), err_len);
2454 	  return true;
2455 	}
2456       else if (arg->sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
2457 	{
2458 	  strncpy (errmsg, _("NO_ARG_CHECK attribute"), err_len);
2459 	  return true;
2460 	}
2461       else if (arg->sym->ts.type == BT_ASSUMED)
2462 	{
2463 	  /* As assumed-type is unlimited polymorphic (cf. above).
2464 	     See also TS 29113, Note 6.1.  */
2465 	  strncpy (errmsg, _("assumed-type argument"), err_len);
2466 	  return true;
2467 	}
2468     }
2469 
2470   if (sym->attr.function)
2471     {
2472       gfc_symbol *res = sym->result ? sym->result : sym;
2473 
2474       if (res->attr.dimension)  /* (3a)  */
2475 	{
2476 	  strncpy (errmsg, _("array result"), err_len);
2477 	  return true;
2478 	}
2479       else if (res->attr.pointer || res->attr.allocatable)  /* (3b)  */
2480 	{
2481 	  strncpy (errmsg, _("pointer or allocatable result"), err_len);
2482 	  return true;
2483 	}
2484       else if (res->ts.type == BT_CHARACTER && res->ts.u.cl
2485 	       && res->ts.u.cl->length
2486 	       && res->ts.u.cl->length->expr_type != EXPR_CONSTANT)  /* (3c)  */
2487 	{
2488 	  strncpy (errmsg, _("result with non-constant character length"), err_len);
2489 	  return true;
2490 	}
2491     }
2492 
2493   if (sym->attr.elemental && !sym->attr.intrinsic)  /* (4)  */
2494     {
2495       strncpy (errmsg, _("elemental procedure"), err_len);
2496       return true;
2497     }
2498   else if (sym->attr.is_bind_c)  /* (5)  */
2499     {
2500       strncpy (errmsg, _("bind(c) procedure"), err_len);
2501       return true;
2502     }
2503 
2504   return false;
2505 }
2506 
2507 
2508 static void
2509 resolve_global_procedure (gfc_symbol *sym, locus *where,
2510 			  gfc_actual_arglist **actual, int sub)
2511 {
2512   gfc_gsymbol * gsym;
2513   gfc_namespace *ns;
2514   enum gfc_symbol_type type;
2515   char reason[200];
2516 
2517   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
2518 
2519   gsym = gfc_get_gsymbol (sym->binding_label ? sym->binding_label : sym->name,
2520 			  sym->binding_label != NULL);
2521 
2522   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2523     gfc_global_used (gsym, where);
2524 
2525   if ((sym->attr.if_source == IFSRC_UNKNOWN
2526        || sym->attr.if_source == IFSRC_IFBODY)
2527       && gsym->type != GSYM_UNKNOWN
2528       && !gsym->binding_label
2529       && gsym->ns
2530       && gsym->ns->proc_name
2531       && not_in_recursive (sym, gsym->ns)
2532       && not_entry_self_reference (sym, gsym->ns))
2533     {
2534       gfc_symbol *def_sym;
2535       def_sym = gsym->ns->proc_name;
2536 
2537       if (gsym->ns->resolved != -1)
2538 	{
2539 
2540 	  /* Resolve the gsymbol namespace if needed.  */
2541 	  if (!gsym->ns->resolved)
2542 	    {
2543 	      gfc_symbol *old_dt_list;
2544 
2545 	      /* Stash away derived types so that the backend_decls
2546 		 do not get mixed up.  */
2547 	      old_dt_list = gfc_derived_types;
2548 	      gfc_derived_types = NULL;
2549 
2550 	      gfc_resolve (gsym->ns);
2551 
2552 	      /* Store the new derived types with the global namespace.  */
2553 	      if (gfc_derived_types)
2554 		gsym->ns->derived_types = gfc_derived_types;
2555 
2556 	      /* Restore the derived types of this namespace.  */
2557 	      gfc_derived_types = old_dt_list;
2558 	    }
2559 
2560 	  /* Make sure that translation for the gsymbol occurs before
2561 	     the procedure currently being resolved.  */
2562 	  ns = gfc_global_ns_list;
2563 	  for (; ns && ns != gsym->ns; ns = ns->sibling)
2564 	    {
2565 	      if (ns->sibling == gsym->ns)
2566 		{
2567 		  ns->sibling = gsym->ns->sibling;
2568 		  gsym->ns->sibling = gfc_global_ns_list;
2569 		  gfc_global_ns_list = gsym->ns;
2570 		  break;
2571 		}
2572 	    }
2573 
2574 	  /* This can happen if a binding name has been specified.  */
2575 	  if (gsym->binding_label && gsym->sym_name != def_sym->name)
2576 	    gfc_find_symbol (gsym->sym_name, gsym->ns, 0, &def_sym);
2577 
2578 	  if (def_sym->attr.entry_master || def_sym->attr.entry)
2579 	    {
2580 	      gfc_entry_list *entry;
2581 	      for (entry = gsym->ns->entries; entry; entry = entry->next)
2582 		if (strcmp (entry->sym->name, sym->name) == 0)
2583 		  {
2584 		    def_sym = entry->sym;
2585 		    break;
2586 		  }
2587 	    }
2588 	}
2589 
2590       if (sym->attr.function && !gfc_compare_types (&sym->ts, &def_sym->ts))
2591 	{
2592 	  gfc_error ("Return type mismatch of function %qs at %L (%s/%s)",
2593 		     sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2594 		     gfc_typename (&def_sym->ts));
2595 	  goto done;
2596 	}
2597 
2598       if (sym->attr.if_source == IFSRC_UNKNOWN
2599 	  && gfc_explicit_interface_required (def_sym, reason, sizeof(reason)))
2600 	{
2601 	  gfc_error ("Explicit interface required for %qs at %L: %s",
2602 		     sym->name, &sym->declared_at, reason);
2603 	  goto done;
2604 	}
2605 
2606       if (!pedantic && (gfc_option.allow_std & GFC_STD_GNU))
2607 	/* Turn erros into warnings with -std=gnu and -std=legacy.  */
2608 	gfc_errors_to_warnings (true);
2609 
2610       if (!gfc_compare_interfaces (sym, def_sym, sym->name, 0, 1,
2611 				   reason, sizeof(reason), NULL, NULL))
2612 	{
2613 	  gfc_error_opt (OPT_Wargument_mismatch,
2614 			 "Interface mismatch in global procedure %qs at %L:"
2615 			 " %s", sym->name, &sym->declared_at, reason);
2616 	  goto done;
2617 	}
2618 
2619       if (!pedantic
2620 	  || ((gfc_option.warn_std & GFC_STD_LEGACY)
2621 	      && !(gfc_option.warn_std & GFC_STD_GNU)))
2622 	gfc_errors_to_warnings (true);
2623 
2624       if (sym->attr.if_source != IFSRC_IFBODY)
2625 	gfc_procedure_use (def_sym, actual, where);
2626     }
2627 
2628 done:
2629   gfc_errors_to_warnings (false);
2630 
2631   if (gsym->type == GSYM_UNKNOWN)
2632     {
2633       gsym->type = type;
2634       gsym->where = *where;
2635     }
2636 
2637   gsym->used = 1;
2638 }
2639 
2640 
2641 /************* Function resolution *************/
2642 
2643 /* Resolve a function call known to be generic.
2644    Section 14.1.2.4.1.  */
2645 
2646 static match
2647 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2648 {
2649   gfc_symbol *s;
2650 
2651   if (sym->attr.generic)
2652     {
2653       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2654       if (s != NULL)
2655 	{
2656 	  expr->value.function.name = s->name;
2657 	  expr->value.function.esym = s;
2658 
2659 	  if (s->ts.type != BT_UNKNOWN)
2660 	    expr->ts = s->ts;
2661 	  else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2662 	    expr->ts = s->result->ts;
2663 
2664 	  if (s->as != NULL)
2665 	    expr->rank = s->as->rank;
2666 	  else if (s->result != NULL && s->result->as != NULL)
2667 	    expr->rank = s->result->as->rank;
2668 
2669 	  gfc_set_sym_referenced (expr->value.function.esym);
2670 
2671 	  return MATCH_YES;
2672 	}
2673 
2674       /* TODO: Need to search for elemental references in generic
2675 	 interface.  */
2676     }
2677 
2678   if (sym->attr.intrinsic)
2679     return gfc_intrinsic_func_interface (expr, 0);
2680 
2681   return MATCH_NO;
2682 }
2683 
2684 
2685 static bool
2686 resolve_generic_f (gfc_expr *expr)
2687 {
2688   gfc_symbol *sym;
2689   match m;
2690   gfc_interface *intr = NULL;
2691 
2692   sym = expr->symtree->n.sym;
2693 
2694   for (;;)
2695     {
2696       m = resolve_generic_f0 (expr, sym);
2697       if (m == MATCH_YES)
2698 	return true;
2699       else if (m == MATCH_ERROR)
2700 	return false;
2701 
2702 generic:
2703       if (!intr)
2704 	for (intr = sym->generic; intr; intr = intr->next)
2705 	  if (gfc_fl_struct (intr->sym->attr.flavor))
2706 	    break;
2707 
2708       if (sym->ns->parent == NULL)
2709 	break;
2710       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2711 
2712       if (sym == NULL)
2713 	break;
2714       if (!generic_sym (sym))
2715 	goto generic;
2716     }
2717 
2718   /* Last ditch attempt.  See if the reference is to an intrinsic
2719      that possesses a matching interface.  14.1.2.4  */
2720   if (sym  && !intr && !gfc_is_intrinsic (sym, 0, expr->where))
2721     {
2722       if (gfc_init_expr_flag)
2723 	gfc_error ("Function %qs in initialization expression at %L "
2724 		   "must be an intrinsic function",
2725 		   expr->symtree->n.sym->name, &expr->where);
2726       else
2727 	gfc_error ("There is no specific function for the generic %qs "
2728 		   "at %L", expr->symtree->n.sym->name, &expr->where);
2729       return false;
2730     }
2731 
2732   if (intr)
2733     {
2734       if (!gfc_convert_to_structure_constructor (expr, intr->sym, NULL,
2735 						 NULL, false))
2736 	return false;
2737       if (!gfc_use_derived (expr->ts.u.derived))
2738 	return false;
2739       return resolve_structure_cons (expr, 0);
2740     }
2741 
2742   m = gfc_intrinsic_func_interface (expr, 0);
2743   if (m == MATCH_YES)
2744     return true;
2745 
2746   if (m == MATCH_NO)
2747     gfc_error ("Generic function %qs at %L is not consistent with a "
2748 	       "specific intrinsic interface", expr->symtree->n.sym->name,
2749 	       &expr->where);
2750 
2751   return false;
2752 }
2753 
2754 
2755 /* Resolve a function call known to be specific.  */
2756 
2757 static match
2758 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2759 {
2760   match m;
2761 
2762   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2763     {
2764       if (sym->attr.dummy)
2765 	{
2766 	  sym->attr.proc = PROC_DUMMY;
2767 	  goto found;
2768 	}
2769 
2770       sym->attr.proc = PROC_EXTERNAL;
2771       goto found;
2772     }
2773 
2774   if (sym->attr.proc == PROC_MODULE
2775       || sym->attr.proc == PROC_ST_FUNCTION
2776       || sym->attr.proc == PROC_INTERNAL)
2777     goto found;
2778 
2779   if (sym->attr.intrinsic)
2780     {
2781       m = gfc_intrinsic_func_interface (expr, 1);
2782       if (m == MATCH_YES)
2783 	return MATCH_YES;
2784       if (m == MATCH_NO)
2785 	gfc_error ("Function %qs at %L is INTRINSIC but is not compatible "
2786 		   "with an intrinsic", sym->name, &expr->where);
2787 
2788       return MATCH_ERROR;
2789     }
2790 
2791   return MATCH_NO;
2792 
2793 found:
2794   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2795 
2796   if (sym->result)
2797     expr->ts = sym->result->ts;
2798   else
2799     expr->ts = sym->ts;
2800   expr->value.function.name = sym->name;
2801   expr->value.function.esym = sym;
2802   /* Prevent crash when sym->ts.u.derived->components is not set due to previous
2803      error(s).  */
2804   if (sym->ts.type == BT_CLASS && !CLASS_DATA (sym))
2805     return MATCH_ERROR;
2806   if (sym->ts.type == BT_CLASS && CLASS_DATA (sym)->as)
2807     expr->rank = CLASS_DATA (sym)->as->rank;
2808   else if (sym->as != NULL)
2809     expr->rank = sym->as->rank;
2810 
2811   return MATCH_YES;
2812 }
2813 
2814 
2815 static bool
2816 resolve_specific_f (gfc_expr *expr)
2817 {
2818   gfc_symbol *sym;
2819   match m;
2820 
2821   sym = expr->symtree->n.sym;
2822 
2823   for (;;)
2824     {
2825       m = resolve_specific_f0 (sym, expr);
2826       if (m == MATCH_YES)
2827 	return true;
2828       if (m == MATCH_ERROR)
2829 	return false;
2830 
2831       if (sym->ns->parent == NULL)
2832 	break;
2833 
2834       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2835 
2836       if (sym == NULL)
2837 	break;
2838     }
2839 
2840   gfc_error ("Unable to resolve the specific function %qs at %L",
2841 	     expr->symtree->n.sym->name, &expr->where);
2842 
2843   return true;
2844 }
2845 
2846 /* Recursively append candidate SYM to CANDIDATES.  Store the number of
2847    candidates in CANDIDATES_LEN.  */
2848 
2849 static void
2850 lookup_function_fuzzy_find_candidates (gfc_symtree *sym,
2851 				       char **&candidates,
2852 				       size_t &candidates_len)
2853 {
2854   gfc_symtree *p;
2855 
2856   if (sym == NULL)
2857     return;
2858   if ((sym->n.sym->ts.type != BT_UNKNOWN || sym->n.sym->attr.external)
2859       && sym->n.sym->attr.flavor == FL_PROCEDURE)
2860     vec_push (candidates, candidates_len, sym->name);
2861 
2862   p = sym->left;
2863   if (p)
2864     lookup_function_fuzzy_find_candidates (p, candidates, candidates_len);
2865 
2866   p = sym->right;
2867   if (p)
2868     lookup_function_fuzzy_find_candidates (p, candidates, candidates_len);
2869 }
2870 
2871 
2872 /* Lookup function FN fuzzily, taking names in SYMROOT into account.  */
2873 
2874 const char*
2875 gfc_lookup_function_fuzzy (const char *fn, gfc_symtree *symroot)
2876 {
2877   char **candidates = NULL;
2878   size_t candidates_len = 0;
2879   lookup_function_fuzzy_find_candidates (symroot, candidates, candidates_len);
2880   return gfc_closest_fuzzy_match (fn, candidates);
2881 }
2882 
2883 
2884 /* Resolve a procedure call not known to be generic nor specific.  */
2885 
2886 static bool
2887 resolve_unknown_f (gfc_expr *expr)
2888 {
2889   gfc_symbol *sym;
2890   gfc_typespec *ts;
2891 
2892   sym = expr->symtree->n.sym;
2893 
2894   if (sym->attr.dummy)
2895     {
2896       sym->attr.proc = PROC_DUMMY;
2897       expr->value.function.name = sym->name;
2898       goto set_type;
2899     }
2900 
2901   /* See if we have an intrinsic function reference.  */
2902 
2903   if (gfc_is_intrinsic (sym, 0, expr->where))
2904     {
2905       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2906 	return true;
2907       return false;
2908     }
2909 
2910   /* The reference is to an external name.  */
2911 
2912   sym->attr.proc = PROC_EXTERNAL;
2913   expr->value.function.name = sym->name;
2914   expr->value.function.esym = expr->symtree->n.sym;
2915 
2916   if (sym->as != NULL)
2917     expr->rank = sym->as->rank;
2918 
2919   /* Type of the expression is either the type of the symbol or the
2920      default type of the symbol.  */
2921 
2922 set_type:
2923   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2924 
2925   if (sym->ts.type != BT_UNKNOWN)
2926     expr->ts = sym->ts;
2927   else
2928     {
2929       ts = gfc_get_default_type (sym->name, sym->ns);
2930 
2931       if (ts->type == BT_UNKNOWN)
2932 	{
2933 	  const char *guessed
2934 	    = gfc_lookup_function_fuzzy (sym->name, sym->ns->sym_root);
2935 	  if (guessed)
2936 	    gfc_error ("Function %qs at %L has no IMPLICIT type"
2937 		       "; did you mean %qs?",
2938 		       sym->name, &expr->where, guessed);
2939 	  else
2940 	    gfc_error ("Function %qs at %L has no IMPLICIT type",
2941 		       sym->name, &expr->where);
2942 	  return false;
2943 	}
2944       else
2945 	expr->ts = *ts;
2946     }
2947 
2948   return true;
2949 }
2950 
2951 
2952 /* Return true, if the symbol is an external procedure.  */
2953 static bool
2954 is_external_proc (gfc_symbol *sym)
2955 {
2956   if (!sym->attr.dummy && !sym->attr.contained
2957 	&& !gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at)
2958 	&& sym->attr.proc != PROC_ST_FUNCTION
2959 	&& !sym->attr.proc_pointer
2960 	&& !sym->attr.use_assoc
2961 	&& sym->name)
2962     return true;
2963 
2964   return false;
2965 }
2966 
2967 
2968 /* Figure out if a function reference is pure or not.  Also set the name
2969    of the function for a potential error message.  Return nonzero if the
2970    function is PURE, zero if not.  */
2971 static int
2972 pure_stmt_function (gfc_expr *, gfc_symbol *);
2973 
2974 int
2975 gfc_pure_function (gfc_expr *e, const char **name)
2976 {
2977   int pure;
2978   gfc_component *comp;
2979 
2980   *name = NULL;
2981 
2982   if (e->symtree != NULL
2983         && e->symtree->n.sym != NULL
2984         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2985     return pure_stmt_function (e, e->symtree->n.sym);
2986 
2987   comp = gfc_get_proc_ptr_comp (e);
2988   if (comp)
2989     {
2990       pure = gfc_pure (comp->ts.interface);
2991       *name = comp->name;
2992     }
2993   else if (e->value.function.esym)
2994     {
2995       pure = gfc_pure (e->value.function.esym);
2996       *name = e->value.function.esym->name;
2997     }
2998   else if (e->value.function.isym)
2999     {
3000       pure = e->value.function.isym->pure
3001 	     || e->value.function.isym->elemental;
3002       *name = e->value.function.isym->name;
3003     }
3004   else
3005     {
3006       /* Implicit functions are not pure.  */
3007       pure = 0;
3008       *name = e->value.function.name;
3009     }
3010 
3011   return pure;
3012 }
3013 
3014 
3015 /* Check if the expression is a reference to an implicitly pure function.  */
3016 
3017 int
3018 gfc_implicit_pure_function (gfc_expr *e)
3019 {
3020   gfc_component *comp = gfc_get_proc_ptr_comp (e);
3021   if (comp)
3022     return gfc_implicit_pure (comp->ts.interface);
3023   else if (e->value.function.esym)
3024     return gfc_implicit_pure (e->value.function.esym);
3025   else
3026     return 0;
3027 }
3028 
3029 
3030 static bool
3031 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
3032 		 int *f ATTRIBUTE_UNUSED)
3033 {
3034   const char *name;
3035 
3036   /* Don't bother recursing into other statement functions
3037      since they will be checked individually for purity.  */
3038   if (e->expr_type != EXPR_FUNCTION
3039 	|| !e->symtree
3040 	|| e->symtree->n.sym == sym
3041 	|| e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
3042     return false;
3043 
3044   return gfc_pure_function (e, &name) ? false : true;
3045 }
3046 
3047 
3048 static int
3049 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
3050 {
3051   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
3052 }
3053 
3054 
3055 /* Check if an impure function is allowed in the current context. */
3056 
3057 static bool check_pure_function (gfc_expr *e)
3058 {
3059   const char *name = NULL;
3060   if (!gfc_pure_function (e, &name) && name)
3061     {
3062       if (forall_flag)
3063 	{
3064 	  gfc_error ("Reference to impure function %qs at %L inside a "
3065 		     "FORALL %s", name, &e->where,
3066 		     forall_flag == 2 ? "mask" : "block");
3067 	  return false;
3068 	}
3069       else if (gfc_do_concurrent_flag)
3070 	{
3071 	  gfc_error ("Reference to impure function %qs at %L inside a "
3072 		     "DO CONCURRENT %s", name, &e->where,
3073 		     gfc_do_concurrent_flag == 2 ? "mask" : "block");
3074 	  return false;
3075 	}
3076       else if (gfc_pure (NULL))
3077 	{
3078 	  gfc_error ("Reference to impure function %qs at %L "
3079 		     "within a PURE procedure", name, &e->where);
3080 	  return false;
3081 	}
3082       if (!gfc_implicit_pure_function (e))
3083 	gfc_unset_implicit_pure (NULL);
3084     }
3085   return true;
3086 }
3087 
3088 
3089 /* Update current procedure's array_outer_dependency flag, considering
3090    a call to procedure SYM.  */
3091 
3092 static void
3093 update_current_proc_array_outer_dependency (gfc_symbol *sym)
3094 {
3095   /* Check to see if this is a sibling function that has not yet
3096      been resolved.  */
3097   gfc_namespace *sibling = gfc_current_ns->sibling;
3098   for (; sibling; sibling = sibling->sibling)
3099     {
3100       if (sibling->proc_name == sym)
3101 	{
3102 	  gfc_resolve (sibling);
3103 	  break;
3104 	}
3105     }
3106 
3107   /* If SYM has references to outer arrays, so has the procedure calling
3108      SYM.  If SYM is a procedure pointer, we can assume the worst.  */
3109   if ((sym->attr.array_outer_dependency || sym->attr.proc_pointer)
3110       && gfc_current_ns->proc_name)
3111     gfc_current_ns->proc_name->attr.array_outer_dependency = 1;
3112 }
3113 
3114 
3115 /* Resolve a function call, which means resolving the arguments, then figuring
3116    out which entity the name refers to.  */
3117 
3118 static bool
3119 resolve_function (gfc_expr *expr)
3120 {
3121   gfc_actual_arglist *arg;
3122   gfc_symbol *sym;
3123   bool t;
3124   int temp;
3125   procedure_type p = PROC_INTRINSIC;
3126   bool no_formal_args;
3127 
3128   sym = NULL;
3129   if (expr->symtree)
3130     sym = expr->symtree->n.sym;
3131 
3132   /* If this is a procedure pointer component, it has already been resolved.  */
3133   if (gfc_is_proc_ptr_comp (expr))
3134     return true;
3135 
3136   /* Avoid re-resolving the arguments of caf_get, which can lead to inserting
3137      another caf_get.  */
3138   if (sym && sym->attr.intrinsic
3139       && (sym->intmod_sym_id == GFC_ISYM_CAF_GET
3140 	  || sym->intmod_sym_id == GFC_ISYM_CAF_SEND))
3141     return true;
3142 
3143   if (sym && sym->attr.intrinsic
3144       && !gfc_resolve_intrinsic (sym, &expr->where))
3145     return false;
3146 
3147   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
3148     {
3149       gfc_error ("%qs at %L is not a function", sym->name, &expr->where);
3150       return false;
3151     }
3152 
3153   /* If this is a deferred TBP with an abstract interface (which may
3154      of course be referenced), expr->value.function.esym will be set.  */
3155   if (sym && sym->attr.abstract && !expr->value.function.esym)
3156     {
3157       gfc_error ("ABSTRACT INTERFACE %qs must not be referenced at %L",
3158 		 sym->name, &expr->where);
3159       return false;
3160     }
3161 
3162   /* If this is a deferred TBP with an abstract interface, its result
3163      cannot be an assumed length character (F2003: C418).  */
3164   if (sym && sym->attr.abstract && sym->attr.function
3165       && sym->result->ts.u.cl
3166       && sym->result->ts.u.cl->length == NULL
3167       && !sym->result->ts.deferred)
3168     {
3169       gfc_error ("ABSTRACT INTERFACE %qs at %L must not have an assumed "
3170 		 "character length result (F2008: C418)", sym->name,
3171 		 &sym->declared_at);
3172       return false;
3173     }
3174 
3175   /* Switch off assumed size checking and do this again for certain kinds
3176      of procedure, once the procedure itself is resolved.  */
3177   need_full_assumed_size++;
3178 
3179   if (expr->symtree && expr->symtree->n.sym)
3180     p = expr->symtree->n.sym->attr.proc;
3181 
3182   if (expr->value.function.isym && expr->value.function.isym->inquiry)
3183     inquiry_argument = true;
3184   no_formal_args = sym && is_external_proc (sym)
3185   		       && gfc_sym_get_dummy_args (sym) == NULL;
3186 
3187   if (!resolve_actual_arglist (expr->value.function.actual,
3188 			       p, no_formal_args))
3189     {
3190       inquiry_argument = false;
3191       return false;
3192     }
3193 
3194   inquiry_argument = false;
3195 
3196   /* Resume assumed_size checking.  */
3197   need_full_assumed_size--;
3198 
3199   /* If the procedure is external, check for usage.  */
3200   if (sym && is_external_proc (sym))
3201     resolve_global_procedure (sym, &expr->where,
3202 			      &expr->value.function.actual, 0);
3203 
3204   if (sym && sym->ts.type == BT_CHARACTER
3205       && sym->ts.u.cl
3206       && sym->ts.u.cl->length == NULL
3207       && !sym->attr.dummy
3208       && !sym->ts.deferred
3209       && expr->value.function.esym == NULL
3210       && !sym->attr.contained)
3211     {
3212       /* Internal procedures are taken care of in resolve_contained_fntype.  */
3213       gfc_error ("Function %qs is declared CHARACTER(*) and cannot "
3214 		 "be used at %L since it is not a dummy argument",
3215 		 sym->name, &expr->where);
3216       return false;
3217     }
3218 
3219   /* See if function is already resolved.  */
3220 
3221   if (expr->value.function.name != NULL
3222       || expr->value.function.isym != NULL)
3223     {
3224       if (expr->ts.type == BT_UNKNOWN)
3225 	expr->ts = sym->ts;
3226       t = true;
3227     }
3228   else
3229     {
3230       /* Apply the rules of section 14.1.2.  */
3231 
3232       switch (procedure_kind (sym))
3233 	{
3234 	case PTYPE_GENERIC:
3235 	  t = resolve_generic_f (expr);
3236 	  break;
3237 
3238 	case PTYPE_SPECIFIC:
3239 	  t = resolve_specific_f (expr);
3240 	  break;
3241 
3242 	case PTYPE_UNKNOWN:
3243 	  t = resolve_unknown_f (expr);
3244 	  break;
3245 
3246 	default:
3247 	  gfc_internal_error ("resolve_function(): bad function type");
3248 	}
3249     }
3250 
3251   /* If the expression is still a function (it might have simplified),
3252      then we check to see if we are calling an elemental function.  */
3253 
3254   if (expr->expr_type != EXPR_FUNCTION)
3255     return t;
3256 
3257   temp = need_full_assumed_size;
3258   need_full_assumed_size = 0;
3259 
3260   if (!resolve_elemental_actual (expr, NULL))
3261     return false;
3262 
3263   if (omp_workshare_flag
3264       && expr->value.function.esym
3265       && ! gfc_elemental (expr->value.function.esym))
3266     {
3267       gfc_error ("User defined non-ELEMENTAL function %qs at %L not allowed "
3268 		 "in WORKSHARE construct", expr->value.function.esym->name,
3269 		 &expr->where);
3270       t = false;
3271     }
3272 
3273 #define GENERIC_ID expr->value.function.isym->id
3274   else if (expr->value.function.actual != NULL
3275 	   && expr->value.function.isym != NULL
3276 	   && GENERIC_ID != GFC_ISYM_LBOUND
3277 	   && GENERIC_ID != GFC_ISYM_LCOBOUND
3278 	   && GENERIC_ID != GFC_ISYM_UCOBOUND
3279 	   && GENERIC_ID != GFC_ISYM_LEN
3280 	   && GENERIC_ID != GFC_ISYM_LOC
3281 	   && GENERIC_ID != GFC_ISYM_C_LOC
3282 	   && GENERIC_ID != GFC_ISYM_PRESENT)
3283     {
3284       /* Array intrinsics must also have the last upper bound of an
3285 	 assumed size array argument.  UBOUND and SIZE have to be
3286 	 excluded from the check if the second argument is anything
3287 	 than a constant.  */
3288 
3289       for (arg = expr->value.function.actual; arg; arg = arg->next)
3290 	{
3291 	  if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3292 	      && arg == expr->value.function.actual
3293 	      && arg->next != NULL && arg->next->expr)
3294 	    {
3295 	      if (arg->next->expr->expr_type != EXPR_CONSTANT)
3296 		break;
3297 
3298 	      if (arg->next->name && strcmp (arg->next->name, "kind") == 0)
3299 		break;
3300 
3301 	      if ((int)mpz_get_si (arg->next->expr->value.integer)
3302 			< arg->expr->rank)
3303 		break;
3304 	    }
3305 
3306 	  if (arg->expr != NULL
3307 	      && arg->expr->rank > 0
3308 	      && resolve_assumed_size_actual (arg->expr))
3309 	    return false;
3310 	}
3311     }
3312 #undef GENERIC_ID
3313 
3314   need_full_assumed_size = temp;
3315 
3316   if (!check_pure_function(expr))
3317     t = false;
3318 
3319   /* Functions without the RECURSIVE attribution are not allowed to
3320    * call themselves.  */
3321   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3322     {
3323       gfc_symbol *esym;
3324       esym = expr->value.function.esym;
3325 
3326       if (is_illegal_recursion (esym, gfc_current_ns))
3327       {
3328 	if (esym->attr.entry && esym->ns->entries)
3329 	  gfc_error ("ENTRY %qs at %L cannot be called recursively, as"
3330 		     " function %qs is not RECURSIVE",
3331 		     esym->name, &expr->where, esym->ns->entries->sym->name);
3332 	else
3333 	  gfc_error ("Function %qs at %L cannot be called recursively, as it"
3334 		     " is not RECURSIVE", esym->name, &expr->where);
3335 
3336 	t = false;
3337       }
3338     }
3339 
3340   /* Character lengths of use associated functions may contains references to
3341      symbols not referenced from the current program unit otherwise.  Make sure
3342      those symbols are marked as referenced.  */
3343 
3344   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3345       && expr->value.function.esym->attr.use_assoc)
3346     {
3347       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3348     }
3349 
3350   /* Make sure that the expression has a typespec that works.  */
3351   if (expr->ts.type == BT_UNKNOWN)
3352     {
3353       if (expr->symtree->n.sym->result
3354 	    && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3355 	    && !expr->symtree->n.sym->result->attr.proc_pointer)
3356 	expr->ts = expr->symtree->n.sym->result->ts;
3357     }
3358 
3359   if (!expr->ref && !expr->value.function.isym)
3360     {
3361       if (expr->value.function.esym)
3362 	update_current_proc_array_outer_dependency (expr->value.function.esym);
3363       else
3364 	update_current_proc_array_outer_dependency (sym);
3365     }
3366   else if (expr->ref)
3367     /* typebound procedure: Assume the worst.  */
3368     gfc_current_ns->proc_name->attr.array_outer_dependency = 1;
3369 
3370   return t;
3371 }
3372 
3373 
3374 /************* Subroutine resolution *************/
3375 
3376 static bool
3377 pure_subroutine (gfc_symbol *sym, const char *name, locus *loc)
3378 {
3379   if (gfc_pure (sym))
3380     return true;
3381 
3382   if (forall_flag)
3383     {
3384       gfc_error ("Subroutine call to %qs in FORALL block at %L is not PURE",
3385 		 name, loc);
3386       return false;
3387     }
3388   else if (gfc_do_concurrent_flag)
3389     {
3390       gfc_error ("Subroutine call to %qs in DO CONCURRENT block at %L is not "
3391 		 "PURE", name, loc);
3392       return false;
3393     }
3394   else if (gfc_pure (NULL))
3395     {
3396       gfc_error ("Subroutine call to %qs at %L is not PURE", name, loc);
3397       return false;
3398     }
3399 
3400   gfc_unset_implicit_pure (NULL);
3401   return true;
3402 }
3403 
3404 
3405 static match
3406 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3407 {
3408   gfc_symbol *s;
3409 
3410   if (sym->attr.generic)
3411     {
3412       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3413       if (s != NULL)
3414 	{
3415 	  c->resolved_sym = s;
3416 	  if (!pure_subroutine (s, s->name, &c->loc))
3417 	    return MATCH_ERROR;
3418 	  return MATCH_YES;
3419 	}
3420 
3421       /* TODO: Need to search for elemental references in generic interface.  */
3422     }
3423 
3424   if (sym->attr.intrinsic)
3425     return gfc_intrinsic_sub_interface (c, 0);
3426 
3427   return MATCH_NO;
3428 }
3429 
3430 
3431 static bool
3432 resolve_generic_s (gfc_code *c)
3433 {
3434   gfc_symbol *sym;
3435   match m;
3436 
3437   sym = c->symtree->n.sym;
3438 
3439   for (;;)
3440     {
3441       m = resolve_generic_s0 (c, sym);
3442       if (m == MATCH_YES)
3443 	return true;
3444       else if (m == MATCH_ERROR)
3445 	return false;
3446 
3447 generic:
3448       if (sym->ns->parent == NULL)
3449 	break;
3450       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3451 
3452       if (sym == NULL)
3453 	break;
3454       if (!generic_sym (sym))
3455 	goto generic;
3456     }
3457 
3458   /* Last ditch attempt.  See if the reference is to an intrinsic
3459      that possesses a matching interface.  14.1.2.4  */
3460   sym = c->symtree->n.sym;
3461 
3462   if (!gfc_is_intrinsic (sym, 1, c->loc))
3463     {
3464       gfc_error ("There is no specific subroutine for the generic %qs at %L",
3465 		 sym->name, &c->loc);
3466       return false;
3467     }
3468 
3469   m = gfc_intrinsic_sub_interface (c, 0);
3470   if (m == MATCH_YES)
3471     return true;
3472   if (m == MATCH_NO)
3473     gfc_error ("Generic subroutine %qs at %L is not consistent with an "
3474 	       "intrinsic subroutine interface", sym->name, &c->loc);
3475 
3476   return false;
3477 }
3478 
3479 
3480 /* Resolve a subroutine call known to be specific.  */
3481 
3482 static match
3483 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3484 {
3485   match m;
3486 
3487   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3488     {
3489       if (sym->attr.dummy)
3490 	{
3491 	  sym->attr.proc = PROC_DUMMY;
3492 	  goto found;
3493 	}
3494 
3495       sym->attr.proc = PROC_EXTERNAL;
3496       goto found;
3497     }
3498 
3499   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3500     goto found;
3501 
3502   if (sym->attr.intrinsic)
3503     {
3504       m = gfc_intrinsic_sub_interface (c, 1);
3505       if (m == MATCH_YES)
3506 	return MATCH_YES;
3507       if (m == MATCH_NO)
3508 	gfc_error ("Subroutine %qs at %L is INTRINSIC but is not compatible "
3509 		   "with an intrinsic", sym->name, &c->loc);
3510 
3511       return MATCH_ERROR;
3512     }
3513 
3514   return MATCH_NO;
3515 
3516 found:
3517   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3518 
3519   c->resolved_sym = sym;
3520   if (!pure_subroutine (sym, sym->name, &c->loc))
3521     return MATCH_ERROR;
3522 
3523   return MATCH_YES;
3524 }
3525 
3526 
3527 static bool
3528 resolve_specific_s (gfc_code *c)
3529 {
3530   gfc_symbol *sym;
3531   match m;
3532 
3533   sym = c->symtree->n.sym;
3534 
3535   for (;;)
3536     {
3537       m = resolve_specific_s0 (c, sym);
3538       if (m == MATCH_YES)
3539 	return true;
3540       if (m == MATCH_ERROR)
3541 	return false;
3542 
3543       if (sym->ns->parent == NULL)
3544 	break;
3545 
3546       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3547 
3548       if (sym == NULL)
3549 	break;
3550     }
3551 
3552   sym = c->symtree->n.sym;
3553   gfc_error ("Unable to resolve the specific subroutine %qs at %L",
3554 	     sym->name, &c->loc);
3555 
3556   return false;
3557 }
3558 
3559 
3560 /* Resolve a subroutine call not known to be generic nor specific.  */
3561 
3562 static bool
3563 resolve_unknown_s (gfc_code *c)
3564 {
3565   gfc_symbol *sym;
3566 
3567   sym = c->symtree->n.sym;
3568 
3569   if (sym->attr.dummy)
3570     {
3571       sym->attr.proc = PROC_DUMMY;
3572       goto found;
3573     }
3574 
3575   /* See if we have an intrinsic function reference.  */
3576 
3577   if (gfc_is_intrinsic (sym, 1, c->loc))
3578     {
3579       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3580 	return true;
3581       return false;
3582     }
3583 
3584   /* The reference is to an external name.  */
3585 
3586 found:
3587   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3588 
3589   c->resolved_sym = sym;
3590 
3591   return pure_subroutine (sym, sym->name, &c->loc);
3592 }
3593 
3594 
3595 /* Resolve a subroutine call.  Although it was tempting to use the same code
3596    for functions, subroutines and functions are stored differently and this
3597    makes things awkward.  */
3598 
3599 static bool
3600 resolve_call (gfc_code *c)
3601 {
3602   bool t;
3603   procedure_type ptype = PROC_INTRINSIC;
3604   gfc_symbol *csym, *sym;
3605   bool no_formal_args;
3606 
3607   csym = c->symtree ? c->symtree->n.sym : NULL;
3608 
3609   if (csym && csym->ts.type != BT_UNKNOWN)
3610     {
3611       gfc_error ("%qs at %L has a type, which is not consistent with "
3612 		 "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3613       return false;
3614     }
3615 
3616   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3617     {
3618       gfc_symtree *st;
3619       gfc_find_sym_tree (c->symtree->name, gfc_current_ns, 1, &st);
3620       sym = st ? st->n.sym : NULL;
3621       if (sym && csym != sym
3622 	      && sym->ns == gfc_current_ns
3623 	      && sym->attr.flavor == FL_PROCEDURE
3624 	      && sym->attr.contained)
3625 	{
3626 	  sym->refs++;
3627 	  if (csym->attr.generic)
3628 	    c->symtree->n.sym = sym;
3629 	  else
3630 	    c->symtree = st;
3631 	  csym = c->symtree->n.sym;
3632 	}
3633     }
3634 
3635   /* If this ia a deferred TBP, c->expr1 will be set.  */
3636   if (!c->expr1 && csym)
3637     {
3638       if (csym->attr.abstract)
3639 	{
3640 	  gfc_error ("ABSTRACT INTERFACE %qs must not be referenced at %L",
3641 		    csym->name, &c->loc);
3642 	  return false;
3643 	}
3644 
3645       /* Subroutines without the RECURSIVE attribution are not allowed to
3646 	 call themselves.  */
3647       if (is_illegal_recursion (csym, gfc_current_ns))
3648 	{
3649 	  if (csym->attr.entry && csym->ns->entries)
3650 	    gfc_error ("ENTRY %qs at %L cannot be called recursively, "
3651 		       "as subroutine %qs is not RECURSIVE",
3652 		       csym->name, &c->loc, csym->ns->entries->sym->name);
3653 	  else
3654 	    gfc_error ("SUBROUTINE %qs at %L cannot be called recursively, "
3655 		       "as it is not RECURSIVE", csym->name, &c->loc);
3656 
3657 	  t = false;
3658 	}
3659     }
3660 
3661   /* Switch off assumed size checking and do this again for certain kinds
3662      of procedure, once the procedure itself is resolved.  */
3663   need_full_assumed_size++;
3664 
3665   if (csym)
3666     ptype = csym->attr.proc;
3667 
3668   no_formal_args = csym && is_external_proc (csym)
3669 			&& gfc_sym_get_dummy_args (csym) == NULL;
3670   if (!resolve_actual_arglist (c->ext.actual, ptype, no_formal_args))
3671     return false;
3672 
3673   /* Resume assumed_size checking.  */
3674   need_full_assumed_size--;
3675 
3676   /* If external, check for usage.  */
3677   if (csym && is_external_proc (csym))
3678     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3679 
3680   t = true;
3681   if (c->resolved_sym == NULL)
3682     {
3683       c->resolved_isym = NULL;
3684       switch (procedure_kind (csym))
3685 	{
3686 	case PTYPE_GENERIC:
3687 	  t = resolve_generic_s (c);
3688 	  break;
3689 
3690 	case PTYPE_SPECIFIC:
3691 	  t = resolve_specific_s (c);
3692 	  break;
3693 
3694 	case PTYPE_UNKNOWN:
3695 	  t = resolve_unknown_s (c);
3696 	  break;
3697 
3698 	default:
3699 	  gfc_internal_error ("resolve_subroutine(): bad function type");
3700 	}
3701     }
3702 
3703   /* Some checks of elemental subroutine actual arguments.  */
3704   if (!resolve_elemental_actual (NULL, c))
3705     return false;
3706 
3707   if (!c->expr1)
3708     update_current_proc_array_outer_dependency (csym);
3709   else
3710     /* Typebound procedure: Assume the worst.  */
3711     gfc_current_ns->proc_name->attr.array_outer_dependency = 1;
3712 
3713   return t;
3714 }
3715 
3716 
3717 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3718    op1->shape and op2->shape are non-NULL return true if their shapes
3719    match.  If both op1->shape and op2->shape are non-NULL return false
3720    if their shapes do not match.  If either op1->shape or op2->shape is
3721    NULL, return true.  */
3722 
3723 static bool
3724 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3725 {
3726   bool t;
3727   int i;
3728 
3729   t = true;
3730 
3731   if (op1->shape != NULL && op2->shape != NULL)
3732     {
3733       for (i = 0; i < op1->rank; i++)
3734 	{
3735 	  if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3736 	   {
3737 	     gfc_error ("Shapes for operands at %L and %L are not conformable",
3738 			&op1->where, &op2->where);
3739 	     t = false;
3740 	     break;
3741 	   }
3742 	}
3743     }
3744 
3745   return t;
3746 }
3747 
3748 /* Convert a logical operator to the corresponding bitwise intrinsic call.
3749    For example A .AND. B becomes IAND(A, B).  */
3750 static gfc_expr *
3751 logical_to_bitwise (gfc_expr *e)
3752 {
3753   gfc_expr *tmp, *op1, *op2;
3754   gfc_isym_id isym;
3755   gfc_actual_arglist *args = NULL;
3756 
3757   gcc_assert (e->expr_type == EXPR_OP);
3758 
3759   isym = GFC_ISYM_NONE;
3760   op1 = e->value.op.op1;
3761   op2 = e->value.op.op2;
3762 
3763   switch (e->value.op.op)
3764     {
3765     case INTRINSIC_NOT:
3766       isym = GFC_ISYM_NOT;
3767       break;
3768     case INTRINSIC_AND:
3769       isym = GFC_ISYM_IAND;
3770       break;
3771     case INTRINSIC_OR:
3772       isym = GFC_ISYM_IOR;
3773       break;
3774     case INTRINSIC_NEQV:
3775       isym = GFC_ISYM_IEOR;
3776       break;
3777     case INTRINSIC_EQV:
3778       /* "Bitwise eqv" is just the complement of NEQV === IEOR.
3779 	 Change the old expression to NEQV, which will get replaced by IEOR,
3780 	 and wrap it in NOT.  */
3781       tmp = gfc_copy_expr (e);
3782       tmp->value.op.op = INTRINSIC_NEQV;
3783       tmp = logical_to_bitwise (tmp);
3784       isym = GFC_ISYM_NOT;
3785       op1 = tmp;
3786       op2 = NULL;
3787       break;
3788     default:
3789       gfc_internal_error ("logical_to_bitwise(): Bad intrinsic");
3790     }
3791 
3792   /* Inherit the original operation's operands as arguments.  */
3793   args = gfc_get_actual_arglist ();
3794   args->expr = op1;
3795   if (op2)
3796     {
3797       args->next = gfc_get_actual_arglist ();
3798       args->next->expr = op2;
3799     }
3800 
3801   /* Convert the expression to a function call.  */
3802   e->expr_type = EXPR_FUNCTION;
3803   e->value.function.actual = args;
3804   e->value.function.isym = gfc_intrinsic_function_by_id (isym);
3805   e->value.function.name = e->value.function.isym->name;
3806   e->value.function.esym = NULL;
3807 
3808   /* Make up a pre-resolved function call symtree if we need to.  */
3809   if (!e->symtree || !e->symtree->n.sym)
3810     {
3811       gfc_symbol *sym;
3812       gfc_get_ha_sym_tree (e->value.function.isym->name, &e->symtree);
3813       sym = e->symtree->n.sym;
3814       sym->result = sym;
3815       sym->attr.flavor = FL_PROCEDURE;
3816       sym->attr.function = 1;
3817       sym->attr.elemental = 1;
3818       sym->attr.pure = 1;
3819       sym->attr.referenced = 1;
3820       gfc_intrinsic_symbol (sym);
3821       gfc_commit_symbol (sym);
3822     }
3823 
3824   args->name = e->value.function.isym->formal->name;
3825   if (e->value.function.isym->formal->next)
3826     args->next->name = e->value.function.isym->formal->next->name;
3827 
3828   return e;
3829 }
3830 
3831 /* Recursively append candidate UOP to CANDIDATES.  Store the number of
3832    candidates in CANDIDATES_LEN.  */
3833 static void
3834 lookup_uop_fuzzy_find_candidates (gfc_symtree *uop,
3835 				  char **&candidates,
3836 				  size_t &candidates_len)
3837 {
3838   gfc_symtree *p;
3839 
3840   if (uop == NULL)
3841     return;
3842 
3843   /* Not sure how to properly filter here.  Use all for a start.
3844      n.uop.op is NULL for empty interface operators (is that legal?) disregard
3845      these as i suppose they don't make terribly sense.  */
3846 
3847   if (uop->n.uop->op != NULL)
3848     vec_push (candidates, candidates_len, uop->name);
3849 
3850   p = uop->left;
3851   if (p)
3852     lookup_uop_fuzzy_find_candidates (p, candidates, candidates_len);
3853 
3854   p = uop->right;
3855   if (p)
3856     lookup_uop_fuzzy_find_candidates (p, candidates, candidates_len);
3857 }
3858 
3859 /* Lookup user-operator OP fuzzily, taking names in UOP into account.  */
3860 
3861 static const char*
3862 lookup_uop_fuzzy (const char *op, gfc_symtree *uop)
3863 {
3864   char **candidates = NULL;
3865   size_t candidates_len = 0;
3866   lookup_uop_fuzzy_find_candidates (uop, candidates, candidates_len);
3867   return gfc_closest_fuzzy_match (op, candidates);
3868 }
3869 
3870 
3871 /* Callback finding an impure function as an operand to an .and. or
3872    .or.  expression.  Remember the last function warned about to
3873    avoid double warnings when recursing.  */
3874 
3875 static int
3876 impure_function_callback (gfc_expr **e, int *walk_subtrees ATTRIBUTE_UNUSED,
3877 			  void *data)
3878 {
3879   gfc_expr *f = *e;
3880   const char *name;
3881   static gfc_expr *last = NULL;
3882   bool *found = (bool *) data;
3883 
3884   if (f->expr_type == EXPR_FUNCTION)
3885     {
3886       *found = 1;
3887       if (f != last && !gfc_pure_function (f, &name)
3888 	  && !gfc_implicit_pure_function (f))
3889 	{
3890 	  if (name)
3891 	    gfc_warning (OPT_Wfunction_elimination,
3892 			 "Impure function %qs at %L might not be evaluated",
3893 			 name, &f->where);
3894 	  else
3895 	    gfc_warning (OPT_Wfunction_elimination,
3896 			 "Impure function at %L might not be evaluated",
3897 			 &f->where);
3898 	}
3899       last = f;
3900     }
3901 
3902   return 0;
3903 }
3904 
3905 
3906 /* Resolve an operator expression node.  This can involve replacing the
3907    operation with a user defined function call.  */
3908 
3909 static bool
3910 resolve_operator (gfc_expr *e)
3911 {
3912   gfc_expr *op1, *op2;
3913   char msg[200];
3914   bool dual_locus_error;
3915   bool t = true;
3916 
3917   /* Resolve all subnodes-- give them types.  */
3918 
3919   switch (e->value.op.op)
3920     {
3921     default:
3922       if (!gfc_resolve_expr (e->value.op.op2))
3923 	return false;
3924 
3925     /* Fall through.  */
3926 
3927     case INTRINSIC_NOT:
3928     case INTRINSIC_UPLUS:
3929     case INTRINSIC_UMINUS:
3930     case INTRINSIC_PARENTHESES:
3931       if (!gfc_resolve_expr (e->value.op.op1))
3932 	return false;
3933       break;
3934     }
3935 
3936   /* Typecheck the new node.  */
3937 
3938   op1 = e->value.op.op1;
3939   op2 = e->value.op.op2;
3940   dual_locus_error = false;
3941 
3942   if ((op1 && op1->expr_type == EXPR_NULL)
3943       || (op2 && op2->expr_type == EXPR_NULL))
3944     {
3945       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3946       goto bad_op;
3947     }
3948 
3949   switch (e->value.op.op)
3950     {
3951     case INTRINSIC_UPLUS:
3952     case INTRINSIC_UMINUS:
3953       if (op1->ts.type == BT_INTEGER
3954 	  || op1->ts.type == BT_REAL
3955 	  || op1->ts.type == BT_COMPLEX)
3956 	{
3957 	  e->ts = op1->ts;
3958 	  break;
3959 	}
3960 
3961       sprintf (msg, _("Operand of unary numeric operator %%<%s%%> at %%L is %s"),
3962 	       gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3963       goto bad_op;
3964 
3965     case INTRINSIC_PLUS:
3966     case INTRINSIC_MINUS:
3967     case INTRINSIC_TIMES:
3968     case INTRINSIC_DIVIDE:
3969     case INTRINSIC_POWER:
3970       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3971 	{
3972 	  gfc_type_convert_binary (e, 1);
3973 	  break;
3974 	}
3975 
3976       if (op1->ts.type == BT_DERIVED || op2->ts.type == BT_DERIVED)
3977 	sprintf (msg,
3978 	       _("Unexpected derived-type entities in binary intrinsic "
3979 		 "numeric operator %%<%s%%> at %%L"),
3980 	       gfc_op2string (e->value.op.op));
3981       else
3982       	sprintf (msg,
3983 	       _("Operands of binary numeric operator %%<%s%%> at %%L are %s/%s"),
3984 	       gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3985 	       gfc_typename (&op2->ts));
3986       goto bad_op;
3987 
3988     case INTRINSIC_CONCAT:
3989       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3990 	  && op1->ts.kind == op2->ts.kind)
3991 	{
3992 	  e->ts.type = BT_CHARACTER;
3993 	  e->ts.kind = op1->ts.kind;
3994 	  break;
3995 	}
3996 
3997       sprintf (msg,
3998 	       _("Operands of string concatenation operator at %%L are %s/%s"),
3999 	       gfc_typename (&op1->ts), gfc_typename (&op2->ts));
4000       goto bad_op;
4001 
4002     case INTRINSIC_AND:
4003     case INTRINSIC_OR:
4004     case INTRINSIC_EQV:
4005     case INTRINSIC_NEQV:
4006       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
4007 	{
4008 	  e->ts.type = BT_LOGICAL;
4009 	  e->ts.kind = gfc_kind_max (op1, op2);
4010 	  if (op1->ts.kind < e->ts.kind)
4011 	    gfc_convert_type (op1, &e->ts, 2);
4012 	  else if (op2->ts.kind < e->ts.kind)
4013 	    gfc_convert_type (op2, &e->ts, 2);
4014 
4015 	  if (flag_frontend_optimize &&
4016 	    (e->value.op.op == INTRINSIC_AND || e->value.op.op == INTRINSIC_OR))
4017 	    {
4018 	      /* Warn about short-circuiting
4019 	         with impure function as second operand.  */
4020 	      bool op2_f = false;
4021 	      gfc_expr_walker (&op2, impure_function_callback, &op2_f);
4022 	    }
4023 	  break;
4024 	}
4025 
4026       /* Logical ops on integers become bitwise ops with -fdec.  */
4027       else if (flag_dec
4028 	       && (op1->ts.type == BT_INTEGER || op2->ts.type == BT_INTEGER))
4029 	{
4030 	  e->ts.type = BT_INTEGER;
4031 	  e->ts.kind = gfc_kind_max (op1, op2);
4032 	  if (op1->ts.type != e->ts.type || op1->ts.kind != e->ts.kind)
4033 	    gfc_convert_type (op1, &e->ts, 1);
4034 	  if (op2->ts.type != e->ts.type || op2->ts.kind != e->ts.kind)
4035 	    gfc_convert_type (op2, &e->ts, 1);
4036 	  e = logical_to_bitwise (e);
4037 	  goto simplify_op;
4038 	}
4039 
4040       sprintf (msg, _("Operands of logical operator %%<%s%%> at %%L are %s/%s"),
4041 	       gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
4042 	       gfc_typename (&op2->ts));
4043 
4044       goto bad_op;
4045 
4046     case INTRINSIC_NOT:
4047       /* Logical ops on integers become bitwise ops with -fdec.  */
4048       if (flag_dec && op1->ts.type == BT_INTEGER)
4049 	{
4050 	  e->ts.type = BT_INTEGER;
4051 	  e->ts.kind = op1->ts.kind;
4052 	  e = logical_to_bitwise (e);
4053 	  goto simplify_op;
4054 	}
4055 
4056       if (op1->ts.type == BT_LOGICAL)
4057 	{
4058 	  e->ts.type = BT_LOGICAL;
4059 	  e->ts.kind = op1->ts.kind;
4060 	  break;
4061 	}
4062 
4063       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
4064 	       gfc_typename (&op1->ts));
4065       goto bad_op;
4066 
4067     case INTRINSIC_GT:
4068     case INTRINSIC_GT_OS:
4069     case INTRINSIC_GE:
4070     case INTRINSIC_GE_OS:
4071     case INTRINSIC_LT:
4072     case INTRINSIC_LT_OS:
4073     case INTRINSIC_LE:
4074     case INTRINSIC_LE_OS:
4075       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
4076 	{
4077 	  strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
4078 	  goto bad_op;
4079 	}
4080 
4081       /* Fall through.  */
4082 
4083     case INTRINSIC_EQ:
4084     case INTRINSIC_EQ_OS:
4085     case INTRINSIC_NE:
4086     case INTRINSIC_NE_OS:
4087       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
4088 	  && op1->ts.kind == op2->ts.kind)
4089 	{
4090 	  e->ts.type = BT_LOGICAL;
4091 	  e->ts.kind = gfc_default_logical_kind;
4092 	  break;
4093 	}
4094 
4095       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
4096 	{
4097 	  gfc_type_convert_binary (e, 1);
4098 
4099 	  e->ts.type = BT_LOGICAL;
4100 	  e->ts.kind = gfc_default_logical_kind;
4101 
4102 	  if (warn_compare_reals)
4103 	    {
4104 	      gfc_intrinsic_op op = e->value.op.op;
4105 
4106 	      /* Type conversion has made sure that the types of op1 and op2
4107 		 agree, so it is only necessary to check the first one.   */
4108 	      if ((op1->ts.type == BT_REAL || op1->ts.type == BT_COMPLEX)
4109 		  && (op == INTRINSIC_EQ || op == INTRINSIC_EQ_OS
4110 		      || op == INTRINSIC_NE || op == INTRINSIC_NE_OS))
4111 		{
4112 		  const char *msg;
4113 
4114 		  if (op == INTRINSIC_EQ || op == INTRINSIC_EQ_OS)
4115 		    msg = "Equality comparison for %s at %L";
4116 		  else
4117 		    msg = "Inequality comparison for %s at %L";
4118 
4119 		  gfc_warning (OPT_Wcompare_reals, msg,
4120 			       gfc_typename (&op1->ts), &op1->where);
4121 		}
4122 	    }
4123 
4124 	  break;
4125 	}
4126 
4127       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
4128 	sprintf (msg,
4129 		 _("Logicals at %%L must be compared with %s instead of %s"),
4130 		 (e->value.op.op == INTRINSIC_EQ
4131 		  || e->value.op.op == INTRINSIC_EQ_OS)
4132 		 ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
4133       else
4134 	sprintf (msg,
4135 		 _("Operands of comparison operator %%<%s%%> at %%L are %s/%s"),
4136 		 gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
4137 		 gfc_typename (&op2->ts));
4138 
4139       goto bad_op;
4140 
4141     case INTRINSIC_USER:
4142       if (e->value.op.uop->op == NULL)
4143 	{
4144 	  const char *name = e->value.op.uop->name;
4145 	  const char *guessed;
4146 	  guessed = lookup_uop_fuzzy (name, e->value.op.uop->ns->uop_root);
4147 	  if (guessed)
4148 	    sprintf (msg, _("Unknown operator %%<%s%%> at %%L; did you mean '%s'?"),
4149 		name, guessed);
4150 	  else
4151 	    sprintf (msg, _("Unknown operator %%<%s%%> at %%L"), name);
4152 	}
4153       else if (op2 == NULL)
4154 	sprintf (msg, _("Operand of user operator %%<%s%%> at %%L is %s"),
4155 		 e->value.op.uop->name, gfc_typename (&op1->ts));
4156       else
4157 	{
4158 	  sprintf (msg, _("Operands of user operator %%<%s%%> at %%L are %s/%s"),
4159 		   e->value.op.uop->name, gfc_typename (&op1->ts),
4160 		   gfc_typename (&op2->ts));
4161 	  e->value.op.uop->op->sym->attr.referenced = 1;
4162 	}
4163 
4164       goto bad_op;
4165 
4166     case INTRINSIC_PARENTHESES:
4167       e->ts = op1->ts;
4168       if (e->ts.type == BT_CHARACTER)
4169 	e->ts.u.cl = op1->ts.u.cl;
4170       break;
4171 
4172     default:
4173       gfc_internal_error ("resolve_operator(): Bad intrinsic");
4174     }
4175 
4176   /* Deal with arrayness of an operand through an operator.  */
4177 
4178   switch (e->value.op.op)
4179     {
4180     case INTRINSIC_PLUS:
4181     case INTRINSIC_MINUS:
4182     case INTRINSIC_TIMES:
4183     case INTRINSIC_DIVIDE:
4184     case INTRINSIC_POWER:
4185     case INTRINSIC_CONCAT:
4186     case INTRINSIC_AND:
4187     case INTRINSIC_OR:
4188     case INTRINSIC_EQV:
4189     case INTRINSIC_NEQV:
4190     case INTRINSIC_EQ:
4191     case INTRINSIC_EQ_OS:
4192     case INTRINSIC_NE:
4193     case INTRINSIC_NE_OS:
4194     case INTRINSIC_GT:
4195     case INTRINSIC_GT_OS:
4196     case INTRINSIC_GE:
4197     case INTRINSIC_GE_OS:
4198     case INTRINSIC_LT:
4199     case INTRINSIC_LT_OS:
4200     case INTRINSIC_LE:
4201     case INTRINSIC_LE_OS:
4202 
4203       if (op1->rank == 0 && op2->rank == 0)
4204 	e->rank = 0;
4205 
4206       if (op1->rank == 0 && op2->rank != 0)
4207 	{
4208 	  e->rank = op2->rank;
4209 
4210 	  if (e->shape == NULL)
4211 	    e->shape = gfc_copy_shape (op2->shape, op2->rank);
4212 	}
4213 
4214       if (op1->rank != 0 && op2->rank == 0)
4215 	{
4216 	  e->rank = op1->rank;
4217 
4218 	  if (e->shape == NULL)
4219 	    e->shape = gfc_copy_shape (op1->shape, op1->rank);
4220 	}
4221 
4222       if (op1->rank != 0 && op2->rank != 0)
4223 	{
4224 	  if (op1->rank == op2->rank)
4225 	    {
4226 	      e->rank = op1->rank;
4227 	      if (e->shape == NULL)
4228 		{
4229 		  t = compare_shapes (op1, op2);
4230 		  if (!t)
4231 		    e->shape = NULL;
4232 		  else
4233 		    e->shape = gfc_copy_shape (op1->shape, op1->rank);
4234 		}
4235 	    }
4236 	  else
4237 	    {
4238 	      /* Allow higher level expressions to work.  */
4239 	      e->rank = 0;
4240 
4241 	      /* Try user-defined operators, and otherwise throw an error.  */
4242 	      dual_locus_error = true;
4243 	      sprintf (msg,
4244 		       _("Inconsistent ranks for operator at %%L and %%L"));
4245 	      goto bad_op;
4246 	    }
4247 	}
4248 
4249       break;
4250 
4251     case INTRINSIC_PARENTHESES:
4252     case INTRINSIC_NOT:
4253     case INTRINSIC_UPLUS:
4254     case INTRINSIC_UMINUS:
4255       /* Simply copy arrayness attribute */
4256       e->rank = op1->rank;
4257 
4258       if (e->shape == NULL)
4259 	e->shape = gfc_copy_shape (op1->shape, op1->rank);
4260 
4261       break;
4262 
4263     default:
4264       break;
4265     }
4266 
4267 simplify_op:
4268 
4269   /* Attempt to simplify the expression.  */
4270   if (t)
4271     {
4272       t = gfc_simplify_expr (e, 0);
4273       /* Some calls do not succeed in simplification and return false
4274 	 even though there is no error; e.g. variable references to
4275 	 PARAMETER arrays.  */
4276       if (!gfc_is_constant_expr (e))
4277 	t = true;
4278     }
4279   return t;
4280 
4281 bad_op:
4282 
4283   {
4284     match m = gfc_extend_expr (e);
4285     if (m == MATCH_YES)
4286       return true;
4287     if (m == MATCH_ERROR)
4288       return false;
4289   }
4290 
4291   if (dual_locus_error)
4292     gfc_error (msg, &op1->where, &op2->where);
4293   else
4294     gfc_error (msg, &e->where);
4295 
4296   return false;
4297 }
4298 
4299 
4300 /************** Array resolution subroutines **************/
4301 
4302 enum compare_result
4303 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN };
4304 
4305 /* Compare two integer expressions.  */
4306 
4307 static compare_result
4308 compare_bound (gfc_expr *a, gfc_expr *b)
4309 {
4310   int i;
4311 
4312   if (a == NULL || a->expr_type != EXPR_CONSTANT
4313       || b == NULL || b->expr_type != EXPR_CONSTANT)
4314     return CMP_UNKNOWN;
4315 
4316   /* If either of the types isn't INTEGER, we must have
4317      raised an error earlier.  */
4318 
4319   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
4320     return CMP_UNKNOWN;
4321 
4322   i = mpz_cmp (a->value.integer, b->value.integer);
4323 
4324   if (i < 0)
4325     return CMP_LT;
4326   if (i > 0)
4327     return CMP_GT;
4328   return CMP_EQ;
4329 }
4330 
4331 
4332 /* Compare an integer expression with an integer.  */
4333 
4334 static compare_result
4335 compare_bound_int (gfc_expr *a, int b)
4336 {
4337   int i;
4338 
4339   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4340     return CMP_UNKNOWN;
4341 
4342   if (a->ts.type != BT_INTEGER)
4343     gfc_internal_error ("compare_bound_int(): Bad expression");
4344 
4345   i = mpz_cmp_si (a->value.integer, b);
4346 
4347   if (i < 0)
4348     return CMP_LT;
4349   if (i > 0)
4350     return CMP_GT;
4351   return CMP_EQ;
4352 }
4353 
4354 
4355 /* Compare an integer expression with a mpz_t.  */
4356 
4357 static compare_result
4358 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4359 {
4360   int i;
4361 
4362   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4363     return CMP_UNKNOWN;
4364 
4365   if (a->ts.type != BT_INTEGER)
4366     gfc_internal_error ("compare_bound_int(): Bad expression");
4367 
4368   i = mpz_cmp (a->value.integer, b);
4369 
4370   if (i < 0)
4371     return CMP_LT;
4372   if (i > 0)
4373     return CMP_GT;
4374   return CMP_EQ;
4375 }
4376 
4377 
4378 /* Compute the last value of a sequence given by a triplet.
4379    Return 0 if it wasn't able to compute the last value, or if the
4380    sequence if empty, and 1 otherwise.  */
4381 
4382 static int
4383 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4384 				gfc_expr *stride, mpz_t last)
4385 {
4386   mpz_t rem;
4387 
4388   if (start == NULL || start->expr_type != EXPR_CONSTANT
4389       || end == NULL || end->expr_type != EXPR_CONSTANT
4390       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4391     return 0;
4392 
4393   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4394       || (stride != NULL && stride->ts.type != BT_INTEGER))
4395     return 0;
4396 
4397   if (stride == NULL || compare_bound_int (stride, 1) == CMP_EQ)
4398     {
4399       if (compare_bound (start, end) == CMP_GT)
4400 	return 0;
4401       mpz_set (last, end->value.integer);
4402       return 1;
4403     }
4404 
4405   if (compare_bound_int (stride, 0) == CMP_GT)
4406     {
4407       /* Stride is positive */
4408       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4409 	return 0;
4410     }
4411   else
4412     {
4413       /* Stride is negative */
4414       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4415 	return 0;
4416     }
4417 
4418   mpz_init (rem);
4419   mpz_sub (rem, end->value.integer, start->value.integer);
4420   mpz_tdiv_r (rem, rem, stride->value.integer);
4421   mpz_sub (last, end->value.integer, rem);
4422   mpz_clear (rem);
4423 
4424   return 1;
4425 }
4426 
4427 
4428 /* Compare a single dimension of an array reference to the array
4429    specification.  */
4430 
4431 static bool
4432 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4433 {
4434   mpz_t last_value;
4435 
4436   if (ar->dimen_type[i] == DIMEN_STAR)
4437     {
4438       gcc_assert (ar->stride[i] == NULL);
4439       /* This implies [*] as [*:] and [*:3] are not possible.  */
4440       if (ar->start[i] == NULL)
4441 	{
4442 	  gcc_assert (ar->end[i] == NULL);
4443 	  return true;
4444 	}
4445     }
4446 
4447 /* Given start, end and stride values, calculate the minimum and
4448    maximum referenced indexes.  */
4449 
4450   switch (ar->dimen_type[i])
4451     {
4452     case DIMEN_VECTOR:
4453     case DIMEN_THIS_IMAGE:
4454       break;
4455 
4456     case DIMEN_STAR:
4457     case DIMEN_ELEMENT:
4458       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4459 	{
4460 	  if (i < as->rank)
4461 	    gfc_warning (0, "Array reference at %L is out of bounds "
4462 			 "(%ld < %ld) in dimension %d", &ar->c_where[i],
4463 			 mpz_get_si (ar->start[i]->value.integer),
4464 			 mpz_get_si (as->lower[i]->value.integer), i+1);
4465 	  else
4466 	    gfc_warning (0, "Array reference at %L is out of bounds "
4467 			 "(%ld < %ld) in codimension %d", &ar->c_where[i],
4468 			 mpz_get_si (ar->start[i]->value.integer),
4469 			 mpz_get_si (as->lower[i]->value.integer),
4470 			 i + 1 - as->rank);
4471 	  return true;
4472 	}
4473       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4474 	{
4475 	  if (i < as->rank)
4476 	    gfc_warning (0, "Array reference at %L is out of bounds "
4477 			 "(%ld > %ld) in dimension %d", &ar->c_where[i],
4478 			 mpz_get_si (ar->start[i]->value.integer),
4479 			 mpz_get_si (as->upper[i]->value.integer), i+1);
4480 	  else
4481 	    gfc_warning (0, "Array reference at %L is out of bounds "
4482 			 "(%ld > %ld) in codimension %d", &ar->c_where[i],
4483 			 mpz_get_si (ar->start[i]->value.integer),
4484 			 mpz_get_si (as->upper[i]->value.integer),
4485 			 i + 1 - as->rank);
4486 	  return true;
4487 	}
4488 
4489       break;
4490 
4491     case DIMEN_RANGE:
4492       {
4493 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4494 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4495 
4496 	compare_result comp_start_end = compare_bound (AR_START, AR_END);
4497 
4498 	/* Check for zero stride, which is not allowed.  */
4499 	if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4500 	  {
4501 	    gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4502 	    return false;
4503 	  }
4504 
4505 	/* if start == len || (stride > 0 && start < len)
4506 			   || (stride < 0 && start > len),
4507 	   then the array section contains at least one element.  In this
4508 	   case, there is an out-of-bounds access if
4509 	   (start < lower || start > upper).  */
4510 	if (compare_bound (AR_START, AR_END) == CMP_EQ
4511 	    || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4512 		 || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4513 	    || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4514 	        && comp_start_end == CMP_GT))
4515 	  {
4516 	    if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4517 	      {
4518 		gfc_warning (0, "Lower array reference at %L is out of bounds "
4519 		       "(%ld < %ld) in dimension %d", &ar->c_where[i],
4520 		       mpz_get_si (AR_START->value.integer),
4521 		       mpz_get_si (as->lower[i]->value.integer), i+1);
4522 		return true;
4523 	      }
4524 	    if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4525 	      {
4526 		gfc_warning (0, "Lower array reference at %L is out of bounds "
4527 		       "(%ld > %ld) in dimension %d", &ar->c_where[i],
4528 		       mpz_get_si (AR_START->value.integer),
4529 		       mpz_get_si (as->upper[i]->value.integer), i+1);
4530 		return true;
4531 	      }
4532 	  }
4533 
4534 	/* If we can compute the highest index of the array section,
4535 	   then it also has to be between lower and upper.  */
4536 	mpz_init (last_value);
4537 	if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4538 					    last_value))
4539 	  {
4540 	    if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4541 	      {
4542 		gfc_warning (0, "Upper array reference at %L is out of bounds "
4543 		       "(%ld < %ld) in dimension %d", &ar->c_where[i],
4544 		       mpz_get_si (last_value),
4545 		       mpz_get_si (as->lower[i]->value.integer), i+1);
4546 	        mpz_clear (last_value);
4547 		return true;
4548 	      }
4549 	    if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4550 	      {
4551 		gfc_warning (0, "Upper array reference at %L is out of bounds "
4552 		       "(%ld > %ld) in dimension %d", &ar->c_where[i],
4553 		       mpz_get_si (last_value),
4554 		       mpz_get_si (as->upper[i]->value.integer), i+1);
4555 	        mpz_clear (last_value);
4556 		return true;
4557 	      }
4558 	  }
4559 	mpz_clear (last_value);
4560 
4561 #undef AR_START
4562 #undef AR_END
4563       }
4564       break;
4565 
4566     default:
4567       gfc_internal_error ("check_dimension(): Bad array reference");
4568     }
4569 
4570   return true;
4571 }
4572 
4573 
4574 /* Compare an array reference with an array specification.  */
4575 
4576 static bool
4577 compare_spec_to_ref (gfc_array_ref *ar)
4578 {
4579   gfc_array_spec *as;
4580   int i;
4581 
4582   as = ar->as;
4583   i = as->rank - 1;
4584   /* TODO: Full array sections are only allowed as actual parameters.  */
4585   if (as->type == AS_ASSUMED_SIZE
4586       && (/*ar->type == AR_FULL
4587 	  ||*/ (ar->type == AR_SECTION
4588 	      && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4589     {
4590       gfc_error ("Rightmost upper bound of assumed size array section "
4591 		 "not specified at %L", &ar->where);
4592       return false;
4593     }
4594 
4595   if (ar->type == AR_FULL)
4596     return true;
4597 
4598   if (as->rank != ar->dimen)
4599     {
4600       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4601 		 &ar->where, ar->dimen, as->rank);
4602       return false;
4603     }
4604 
4605   /* ar->codimen == 0 is a local array.  */
4606   if (as->corank != ar->codimen && ar->codimen != 0)
4607     {
4608       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4609 		 &ar->where, ar->codimen, as->corank);
4610       return false;
4611     }
4612 
4613   for (i = 0; i < as->rank; i++)
4614     if (!check_dimension (i, ar, as))
4615       return false;
4616 
4617   /* Local access has no coarray spec.  */
4618   if (ar->codimen != 0)
4619     for (i = as->rank; i < as->rank + as->corank; i++)
4620       {
4621 	if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate
4622 	    && ar->dimen_type[i] != DIMEN_THIS_IMAGE)
4623 	  {
4624 	    gfc_error ("Coindex of codimension %d must be a scalar at %L",
4625 		       i + 1 - as->rank, &ar->where);
4626 	    return false;
4627 	  }
4628 	if (!check_dimension (i, ar, as))
4629 	  return false;
4630       }
4631 
4632   return true;
4633 }
4634 
4635 
4636 /* Resolve one part of an array index.  */
4637 
4638 static bool
4639 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4640 		     int force_index_integer_kind)
4641 {
4642   gfc_typespec ts;
4643 
4644   if (index == NULL)
4645     return true;
4646 
4647   if (!gfc_resolve_expr (index))
4648     return false;
4649 
4650   if (check_scalar && index->rank != 0)
4651     {
4652       gfc_error ("Array index at %L must be scalar", &index->where);
4653       return false;
4654     }
4655 
4656   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4657     {
4658       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4659 		 &index->where, gfc_basic_typename (index->ts.type));
4660       return false;
4661     }
4662 
4663   if (index->ts.type == BT_REAL)
4664     if (!gfc_notify_std (GFC_STD_LEGACY, "REAL array index at %L",
4665 			 &index->where))
4666       return false;
4667 
4668   if ((index->ts.kind != gfc_index_integer_kind
4669        && force_index_integer_kind)
4670       || index->ts.type != BT_INTEGER)
4671     {
4672       gfc_clear_ts (&ts);
4673       ts.type = BT_INTEGER;
4674       ts.kind = gfc_index_integer_kind;
4675 
4676       gfc_convert_type_warn (index, &ts, 2, 0);
4677     }
4678 
4679   return true;
4680 }
4681 
4682 /* Resolve one part of an array index.  */
4683 
4684 bool
4685 gfc_resolve_index (gfc_expr *index, int check_scalar)
4686 {
4687   return gfc_resolve_index_1 (index, check_scalar, 1);
4688 }
4689 
4690 /* Resolve a dim argument to an intrinsic function.  */
4691 
4692 bool
4693 gfc_resolve_dim_arg (gfc_expr *dim)
4694 {
4695   if (dim == NULL)
4696     return true;
4697 
4698   if (!gfc_resolve_expr (dim))
4699     return false;
4700 
4701   if (dim->rank != 0)
4702     {
4703       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4704       return false;
4705 
4706     }
4707 
4708   if (dim->ts.type != BT_INTEGER)
4709     {
4710       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4711       return false;
4712     }
4713 
4714   if (dim->ts.kind != gfc_index_integer_kind)
4715     {
4716       gfc_typespec ts;
4717 
4718       gfc_clear_ts (&ts);
4719       ts.type = BT_INTEGER;
4720       ts.kind = gfc_index_integer_kind;
4721 
4722       gfc_convert_type_warn (dim, &ts, 2, 0);
4723     }
4724 
4725   return true;
4726 }
4727 
4728 /* Given an expression that contains array references, update those array
4729    references to point to the right array specifications.  While this is
4730    filled in during matching, this information is difficult to save and load
4731    in a module, so we take care of it here.
4732 
4733    The idea here is that the original array reference comes from the
4734    base symbol.  We traverse the list of reference structures, setting
4735    the stored reference to references.  Component references can
4736    provide an additional array specification.  */
4737 
4738 static void
4739 find_array_spec (gfc_expr *e)
4740 {
4741   gfc_array_spec *as;
4742   gfc_component *c;
4743   gfc_ref *ref;
4744   bool class_as = false;
4745 
4746   if (e->symtree->n.sym->ts.type == BT_CLASS)
4747     {
4748       as = CLASS_DATA (e->symtree->n.sym)->as;
4749       class_as = true;
4750     }
4751   else
4752     as = e->symtree->n.sym->as;
4753 
4754   for (ref = e->ref; ref; ref = ref->next)
4755     switch (ref->type)
4756       {
4757       case REF_ARRAY:
4758 	if (as == NULL)
4759 	  gfc_internal_error ("find_array_spec(): Missing spec");
4760 
4761 	ref->u.ar.as = as;
4762 	as = NULL;
4763 	break;
4764 
4765       case REF_COMPONENT:
4766 	c = ref->u.c.component;
4767 	if (c->attr.dimension)
4768 	  {
4769 	    if (as != NULL && !(class_as && as == c->as))
4770 	      gfc_internal_error ("find_array_spec(): unused as(1)");
4771 	    as = c->as;
4772 	  }
4773 
4774 	break;
4775 
4776       case REF_SUBSTRING:
4777       case REF_INQUIRY:
4778 	break;
4779       }
4780 
4781   if (as != NULL)
4782     gfc_internal_error ("find_array_spec(): unused as(2)");
4783 }
4784 
4785 
4786 /* Resolve an array reference.  */
4787 
4788 static bool
4789 resolve_array_ref (gfc_array_ref *ar)
4790 {
4791   int i, check_scalar;
4792   gfc_expr *e;
4793 
4794   for (i = 0; i < ar->dimen + ar->codimen; i++)
4795     {
4796       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4797 
4798       /* Do not force gfc_index_integer_kind for the start.  We can
4799          do fine with any integer kind.  This avoids temporary arrays
4800 	 created for indexing with a vector.  */
4801       if (!gfc_resolve_index_1 (ar->start[i], check_scalar, 0))
4802 	return false;
4803       if (!gfc_resolve_index (ar->end[i], check_scalar))
4804 	return false;
4805       if (!gfc_resolve_index (ar->stride[i], check_scalar))
4806 	return false;
4807 
4808       e = ar->start[i];
4809 
4810       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4811 	switch (e->rank)
4812 	  {
4813 	  case 0:
4814 	    ar->dimen_type[i] = DIMEN_ELEMENT;
4815 	    break;
4816 
4817 	  case 1:
4818 	    ar->dimen_type[i] = DIMEN_VECTOR;
4819 	    if (e->expr_type == EXPR_VARIABLE
4820 		&& e->symtree->n.sym->ts.type == BT_DERIVED)
4821 	      ar->start[i] = gfc_get_parentheses (e);
4822 	    break;
4823 
4824 	  default:
4825 	    gfc_error ("Array index at %L is an array of rank %d",
4826 		       &ar->c_where[i], e->rank);
4827 	    return false;
4828 	  }
4829 
4830       /* Fill in the upper bound, which may be lower than the
4831 	 specified one for something like a(2:10:5), which is
4832 	 identical to a(2:7:5).  Only relevant for strides not equal
4833 	 to one.  Don't try a division by zero.  */
4834       if (ar->dimen_type[i] == DIMEN_RANGE
4835 	  && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4836 	  && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0
4837 	  && mpz_cmp_si (ar->stride[i]->value.integer, 0L) != 0)
4838 	{
4839 	  mpz_t size, end;
4840 
4841 	  if (gfc_ref_dimen_size (ar, i, &size, &end))
4842 	    {
4843 	      if (ar->end[i] == NULL)
4844 		{
4845 		  ar->end[i] =
4846 		    gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4847 					   &ar->where);
4848 		  mpz_set (ar->end[i]->value.integer, end);
4849 		}
4850 	      else if (ar->end[i]->ts.type == BT_INTEGER
4851 		       && ar->end[i]->expr_type == EXPR_CONSTANT)
4852 		{
4853 		  mpz_set (ar->end[i]->value.integer, end);
4854 		}
4855 	      else
4856 		gcc_unreachable ();
4857 
4858 	      mpz_clear (size);
4859 	      mpz_clear (end);
4860 	    }
4861 	}
4862     }
4863 
4864   if (ar->type == AR_FULL)
4865     {
4866       if (ar->as->rank == 0)
4867 	ar->type = AR_ELEMENT;
4868 
4869       /* Make sure array is the same as array(:,:), this way
4870 	 we don't need to special case all the time.  */
4871       ar->dimen = ar->as->rank;
4872       for (i = 0; i < ar->dimen; i++)
4873 	{
4874 	  ar->dimen_type[i] = DIMEN_RANGE;
4875 
4876 	  gcc_assert (ar->start[i] == NULL);
4877 	  gcc_assert (ar->end[i] == NULL);
4878 	  gcc_assert (ar->stride[i] == NULL);
4879 	}
4880     }
4881 
4882   /* If the reference type is unknown, figure out what kind it is.  */
4883 
4884   if (ar->type == AR_UNKNOWN)
4885     {
4886       ar->type = AR_ELEMENT;
4887       for (i = 0; i < ar->dimen; i++)
4888 	if (ar->dimen_type[i] == DIMEN_RANGE
4889 	    || ar->dimen_type[i] == DIMEN_VECTOR)
4890 	  {
4891 	    ar->type = AR_SECTION;
4892 	    break;
4893 	  }
4894     }
4895 
4896   if (!ar->as->cray_pointee && !compare_spec_to_ref (ar))
4897     return false;
4898 
4899   if (ar->as->corank && ar->codimen == 0)
4900     {
4901       int n;
4902       ar->codimen = ar->as->corank;
4903       for (n = ar->dimen; n < ar->dimen + ar->codimen; n++)
4904 	ar->dimen_type[n] = DIMEN_THIS_IMAGE;
4905     }
4906 
4907   return true;
4908 }
4909 
4910 
4911 static bool
4912 resolve_substring (gfc_ref *ref, bool *equal_length)
4913 {
4914   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4915 
4916   if (ref->u.ss.start != NULL)
4917     {
4918       if (!gfc_resolve_expr (ref->u.ss.start))
4919 	return false;
4920 
4921       if (ref->u.ss.start->ts.type != BT_INTEGER)
4922 	{
4923 	  gfc_error ("Substring start index at %L must be of type INTEGER",
4924 		     &ref->u.ss.start->where);
4925 	  return false;
4926 	}
4927 
4928       if (ref->u.ss.start->rank != 0)
4929 	{
4930 	  gfc_error ("Substring start index at %L must be scalar",
4931 		     &ref->u.ss.start->where);
4932 	  return false;
4933 	}
4934 
4935       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4936 	  && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4937 	      || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4938 	{
4939 	  gfc_error ("Substring start index at %L is less than one",
4940 		     &ref->u.ss.start->where);
4941 	  return false;
4942 	}
4943     }
4944 
4945   if (ref->u.ss.end != NULL)
4946     {
4947       if (!gfc_resolve_expr (ref->u.ss.end))
4948 	return false;
4949 
4950       if (ref->u.ss.end->ts.type != BT_INTEGER)
4951 	{
4952 	  gfc_error ("Substring end index at %L must be of type INTEGER",
4953 		     &ref->u.ss.end->where);
4954 	  return false;
4955 	}
4956 
4957       if (ref->u.ss.end->rank != 0)
4958 	{
4959 	  gfc_error ("Substring end index at %L must be scalar",
4960 		     &ref->u.ss.end->where);
4961 	  return false;
4962 	}
4963 
4964       if (ref->u.ss.length != NULL
4965 	  && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4966 	  && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4967 	      || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4968 	{
4969 	  gfc_error ("Substring end index at %L exceeds the string length",
4970 		     &ref->u.ss.start->where);
4971 	  return false;
4972 	}
4973 
4974       if (compare_bound_mpz_t (ref->u.ss.end,
4975 			       gfc_integer_kinds[k].huge) == CMP_GT
4976 	  && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4977 	      || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4978 	{
4979 	  gfc_error ("Substring end index at %L is too large",
4980 		     &ref->u.ss.end->where);
4981 	  return false;
4982 	}
4983       /*  If the substring has the same length as the original
4984 	  variable, the reference itself can be deleted.  */
4985 
4986       if (ref->u.ss.length != NULL
4987 	  && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_EQ
4988 	  && compare_bound_int (ref->u.ss.start, 1) == CMP_EQ)
4989 	*equal_length = true;
4990     }
4991 
4992   return true;
4993 }
4994 
4995 
4996 /* This function supplies missing substring charlens.  */
4997 
4998 void
4999 gfc_resolve_substring_charlen (gfc_expr *e)
5000 {
5001   gfc_ref *char_ref;
5002   gfc_expr *start, *end;
5003   gfc_typespec *ts = NULL;
5004   mpz_t diff;
5005 
5006   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
5007     {
5008       if (char_ref->type == REF_SUBSTRING || char_ref->type == REF_INQUIRY)
5009 	break;
5010       if (char_ref->type == REF_COMPONENT)
5011 	ts = &char_ref->u.c.component->ts;
5012     }
5013 
5014   if (!char_ref || char_ref->type == REF_INQUIRY)
5015     return;
5016 
5017   gcc_assert (char_ref->next == NULL);
5018 
5019   if (e->ts.u.cl)
5020     {
5021       if (e->ts.u.cl->length)
5022 	gfc_free_expr (e->ts.u.cl->length);
5023       else if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym->attr.dummy)
5024 	return;
5025     }
5026 
5027   e->ts.type = BT_CHARACTER;
5028   e->ts.kind = gfc_default_character_kind;
5029 
5030   if (!e->ts.u.cl)
5031     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5032 
5033   if (char_ref->u.ss.start)
5034     start = gfc_copy_expr (char_ref->u.ss.start);
5035   else
5036     start = gfc_get_int_expr (gfc_charlen_int_kind, NULL, 1);
5037 
5038   if (char_ref->u.ss.end)
5039     end = gfc_copy_expr (char_ref->u.ss.end);
5040   else if (e->expr_type == EXPR_VARIABLE)
5041     {
5042       if (!ts)
5043 	ts = &e->symtree->n.sym->ts;
5044       end = gfc_copy_expr (ts->u.cl->length);
5045     }
5046   else
5047     end = NULL;
5048 
5049   if (!start || !end)
5050     {
5051       gfc_free_expr (start);
5052       gfc_free_expr (end);
5053       return;
5054     }
5055 
5056   /* Length = (end - start + 1).
5057      Check first whether it has a constant length.  */
5058   if (gfc_dep_difference (end, start, &diff))
5059     {
5060       gfc_expr *len = gfc_get_constant_expr (BT_INTEGER, gfc_charlen_int_kind,
5061 					     &e->where);
5062 
5063       mpz_add_ui (len->value.integer, diff, 1);
5064       mpz_clear (diff);
5065       e->ts.u.cl->length = len;
5066       /* The check for length < 0 is handled below */
5067     }
5068   else
5069     {
5070       e->ts.u.cl->length = gfc_subtract (end, start);
5071       e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
5072 				    gfc_get_int_expr (gfc_charlen_int_kind,
5073 						      NULL, 1));
5074     }
5075 
5076   /* F2008, 6.4.1:  Both the starting point and the ending point shall
5077      be within the range 1, 2, ..., n unless the starting point exceeds
5078      the ending point, in which case the substring has length zero.  */
5079 
5080   if (mpz_cmp_si (e->ts.u.cl->length->value.integer, 0) < 0)
5081     mpz_set_si (e->ts.u.cl->length->value.integer, 0);
5082 
5083   e->ts.u.cl->length->ts.type = BT_INTEGER;
5084   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5085 
5086   /* Make sure that the length is simplified.  */
5087   gfc_simplify_expr (e->ts.u.cl->length, 1);
5088   gfc_resolve_expr (e->ts.u.cl->length);
5089 }
5090 
5091 
5092 /* Resolve subtype references.  */
5093 
5094 static bool
5095 resolve_ref (gfc_expr *expr)
5096 {
5097   int current_part_dimension, n_components, seen_part_dimension;
5098   gfc_ref *ref, **prev;
5099   bool equal_length;
5100 
5101   for (ref = expr->ref; ref; ref = ref->next)
5102     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
5103       {
5104 	find_array_spec (expr);
5105 	break;
5106       }
5107 
5108   for (prev = &expr->ref; *prev != NULL;
5109        prev = *prev == NULL ? prev : &(*prev)->next)
5110     switch ((*prev)->type)
5111       {
5112       case REF_ARRAY:
5113 	if (!resolve_array_ref (&(*prev)->u.ar))
5114 	  return false;
5115 	break;
5116 
5117       case REF_COMPONENT:
5118       case REF_INQUIRY:
5119 	break;
5120 
5121       case REF_SUBSTRING:
5122 	equal_length = false;
5123 	if (!resolve_substring (*prev, &equal_length))
5124 	  return false;
5125 
5126 	if (expr->expr_type != EXPR_SUBSTRING && equal_length)
5127 	  {
5128 	    /* Remove the reference and move the charlen, if any.  */
5129 	    ref = *prev;
5130 	    *prev = ref->next;
5131 	    ref->next = NULL;
5132 	    expr->ts.u.cl = ref->u.ss.length;
5133 	    ref->u.ss.length = NULL;
5134 	    gfc_free_ref_list (ref);
5135 	  }
5136 	break;
5137       }
5138 
5139   /* Check constraints on part references.  */
5140 
5141   current_part_dimension = 0;
5142   seen_part_dimension = 0;
5143   n_components = 0;
5144 
5145   for (ref = expr->ref; ref; ref = ref->next)
5146     {
5147       switch (ref->type)
5148 	{
5149 	case REF_ARRAY:
5150 	  switch (ref->u.ar.type)
5151 	    {
5152 	    case AR_FULL:
5153 	      /* Coarray scalar.  */
5154 	      if (ref->u.ar.as->rank == 0)
5155 		{
5156 		  current_part_dimension = 0;
5157 		  break;
5158 		}
5159 	      /* Fall through.  */
5160 	    case AR_SECTION:
5161 	      current_part_dimension = 1;
5162 	      break;
5163 
5164 	    case AR_ELEMENT:
5165 	      current_part_dimension = 0;
5166 	      break;
5167 
5168 	    case AR_UNKNOWN:
5169 	      gfc_internal_error ("resolve_ref(): Bad array reference");
5170 	    }
5171 
5172 	  break;
5173 
5174 	case REF_COMPONENT:
5175 	  if (current_part_dimension || seen_part_dimension)
5176 	    {
5177 	      /* F03:C614.  */
5178 	      if (ref->u.c.component->attr.pointer
5179 		  || ref->u.c.component->attr.proc_pointer
5180 		  || (ref->u.c.component->ts.type == BT_CLASS
5181 			&& CLASS_DATA (ref->u.c.component)->attr.pointer))
5182 		{
5183 		  gfc_error ("Component to the right of a part reference "
5184 			     "with nonzero rank must not have the POINTER "
5185 			     "attribute at %L", &expr->where);
5186 		  return false;
5187 		}
5188 	      else if (ref->u.c.component->attr.allocatable
5189 			|| (ref->u.c.component->ts.type == BT_CLASS
5190 			    && CLASS_DATA (ref->u.c.component)->attr.allocatable))
5191 
5192 		{
5193 		  gfc_error ("Component to the right of a part reference "
5194 			     "with nonzero rank must not have the ALLOCATABLE "
5195 			     "attribute at %L", &expr->where);
5196 		  return false;
5197 		}
5198 	    }
5199 
5200 	  n_components++;
5201 	  break;
5202 
5203 	case REF_SUBSTRING:
5204 	case REF_INQUIRY:
5205 	  break;
5206 	}
5207 
5208       if (((ref->type == REF_COMPONENT && n_components > 1)
5209 	   || ref->next == NULL)
5210 	  && current_part_dimension
5211 	  && seen_part_dimension)
5212 	{
5213 	  gfc_error ("Two or more part references with nonzero rank must "
5214 		     "not be specified at %L", &expr->where);
5215 	  return false;
5216 	}
5217 
5218       if (ref->type == REF_COMPONENT)
5219 	{
5220 	  if (current_part_dimension)
5221 	    seen_part_dimension = 1;
5222 
5223 	  /* reset to make sure */
5224 	  current_part_dimension = 0;
5225 	}
5226     }
5227 
5228   return true;
5229 }
5230 
5231 
5232 /* Given an expression, determine its shape.  This is easier than it sounds.
5233    Leaves the shape array NULL if it is not possible to determine the shape.  */
5234 
5235 static void
5236 expression_shape (gfc_expr *e)
5237 {
5238   mpz_t array[GFC_MAX_DIMENSIONS];
5239   int i;
5240 
5241   if (e->rank <= 0 || e->shape != NULL)
5242     return;
5243 
5244   for (i = 0; i < e->rank; i++)
5245     if (!gfc_array_dimen_size (e, i, &array[i]))
5246       goto fail;
5247 
5248   e->shape = gfc_get_shape (e->rank);
5249 
5250   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
5251 
5252   return;
5253 
5254 fail:
5255   for (i--; i >= 0; i--)
5256     mpz_clear (array[i]);
5257 }
5258 
5259 
5260 /* Given a variable expression node, compute the rank of the expression by
5261    examining the base symbol and any reference structures it may have.  */
5262 
5263 void
5264 expression_rank (gfc_expr *e)
5265 {
5266   gfc_ref *ref;
5267   int i, rank;
5268 
5269   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
5270      could lead to serious confusion...  */
5271   gcc_assert (e->expr_type != EXPR_COMPCALL);
5272 
5273   if (e->ref == NULL)
5274     {
5275       if (e->expr_type == EXPR_ARRAY)
5276 	goto done;
5277       /* Constructors can have a rank different from one via RESHAPE().  */
5278 
5279       if (e->symtree == NULL)
5280 	{
5281 	  e->rank = 0;
5282 	  goto done;
5283 	}
5284 
5285       e->rank = (e->symtree->n.sym->as == NULL)
5286 		? 0 : e->symtree->n.sym->as->rank;
5287       goto done;
5288     }
5289 
5290   rank = 0;
5291 
5292   for (ref = e->ref; ref; ref = ref->next)
5293     {
5294       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
5295 	  && ref->u.c.component->attr.function && !ref->next)
5296 	rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
5297 
5298       if (ref->type != REF_ARRAY)
5299 	continue;
5300 
5301       if (ref->u.ar.type == AR_FULL)
5302 	{
5303 	  rank = ref->u.ar.as->rank;
5304 	  break;
5305 	}
5306 
5307       if (ref->u.ar.type == AR_SECTION)
5308 	{
5309 	  /* Figure out the rank of the section.  */
5310 	  if (rank != 0)
5311 	    gfc_internal_error ("expression_rank(): Two array specs");
5312 
5313 	  for (i = 0; i < ref->u.ar.dimen; i++)
5314 	    if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
5315 		|| ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
5316 	      rank++;
5317 
5318 	  break;
5319 	}
5320     }
5321 
5322   e->rank = rank;
5323 
5324 done:
5325   expression_shape (e);
5326 }
5327 
5328 
5329 static void
5330 add_caf_get_intrinsic (gfc_expr *e)
5331 {
5332   gfc_expr *wrapper, *tmp_expr;
5333   gfc_ref *ref;
5334   int n;
5335 
5336   for (ref = e->ref; ref; ref = ref->next)
5337     if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5338       break;
5339   if (ref == NULL)
5340     return;
5341 
5342   for (n = ref->u.ar.dimen; n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
5343     if (ref->u.ar.dimen_type[n] != DIMEN_ELEMENT)
5344       return;
5345 
5346   tmp_expr = XCNEW (gfc_expr);
5347   *tmp_expr = *e;
5348   wrapper = gfc_build_intrinsic_call (gfc_current_ns, GFC_ISYM_CAF_GET,
5349 				      "caf_get", tmp_expr->where, 1, tmp_expr);
5350   wrapper->ts = e->ts;
5351   wrapper->rank = e->rank;
5352   if (e->rank)
5353     wrapper->shape = gfc_copy_shape (e->shape, e->rank);
5354   *e = *wrapper;
5355   free (wrapper);
5356 }
5357 
5358 
5359 static void
5360 remove_caf_get_intrinsic (gfc_expr *e)
5361 {
5362   gcc_assert (e->expr_type == EXPR_FUNCTION && e->value.function.isym
5363 	      && e->value.function.isym->id == GFC_ISYM_CAF_GET);
5364   gfc_expr *e2 = e->value.function.actual->expr;
5365   e->value.function.actual->expr = NULL;
5366   gfc_free_actual_arglist (e->value.function.actual);
5367   gfc_free_shape (&e->shape, e->rank);
5368   *e = *e2;
5369   free (e2);
5370 }
5371 
5372 
5373 /* Resolve a variable expression.  */
5374 
5375 static bool
5376 resolve_variable (gfc_expr *e)
5377 {
5378   gfc_symbol *sym;
5379   bool t;
5380 
5381   t = true;
5382 
5383   if (e->symtree == NULL)
5384     return false;
5385   sym = e->symtree->n.sym;
5386 
5387   /* Use same check as for TYPE(*) below; this check has to be before TYPE(*)
5388      as ts.type is set to BT_ASSUMED in resolve_symbol.  */
5389   if (sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
5390     {
5391       if (!actual_arg || inquiry_argument)
5392 	{
5393 	  gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may only "
5394 		     "be used as actual argument", sym->name, &e->where);
5395 	  return false;
5396 	}
5397     }
5398   /* TS 29113, 407b.  */
5399   else if (e->ts.type == BT_ASSUMED)
5400     {
5401       if (!actual_arg)
5402 	{
5403 	  gfc_error ("Assumed-type variable %s at %L may only be used "
5404 		     "as actual argument", sym->name, &e->where);
5405 	  return false;
5406 	}
5407       else if (inquiry_argument && !first_actual_arg)
5408 	{
5409 	  /* FIXME: It doesn't work reliably as inquiry_argument is not set
5410 	     for all inquiry functions in resolve_function; the reason is
5411 	     that the function-name resolution happens too late in that
5412 	     function.  */
5413 	  gfc_error ("Assumed-type variable %s at %L as actual argument to "
5414 		     "an inquiry function shall be the first argument",
5415 		     sym->name, &e->where);
5416 	  return false;
5417 	}
5418     }
5419   /* TS 29113, C535b.  */
5420   else if ((sym->ts.type == BT_CLASS && sym->attr.class_ok
5421 	    && CLASS_DATA (sym)->as
5422 	    && CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
5423 	   || (sym->ts.type != BT_CLASS && sym->as
5424 	       && sym->as->type == AS_ASSUMED_RANK))
5425     {
5426       if (!actual_arg)
5427 	{
5428 	  gfc_error ("Assumed-rank variable %s at %L may only be used as "
5429 		     "actual argument", sym->name, &e->where);
5430 	  return false;
5431 	}
5432       else if (inquiry_argument && !first_actual_arg)
5433 	{
5434 	  /* FIXME: It doesn't work reliably as inquiry_argument is not set
5435 	     for all inquiry functions in resolve_function; the reason is
5436 	     that the function-name resolution happens too late in that
5437 	     function.  */
5438 	  gfc_error ("Assumed-rank variable %s at %L as actual argument "
5439 		     "to an inquiry function shall be the first argument",
5440 		     sym->name, &e->where);
5441 	  return false;
5442 	}
5443     }
5444 
5445   if ((sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK)) && e->ref
5446       && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
5447 	   && e->ref->next == NULL))
5448     {
5449       gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall not have "
5450 		 "a subobject reference", sym->name, &e->ref->u.ar.where);
5451       return false;
5452     }
5453   /* TS 29113, 407b.  */
5454   else if (e->ts.type == BT_ASSUMED && e->ref
5455 	   && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
5456 		&& e->ref->next == NULL))
5457     {
5458       gfc_error ("Assumed-type variable %s at %L shall not have a subobject "
5459 		 "reference", sym->name, &e->ref->u.ar.where);
5460       return false;
5461     }
5462 
5463   /* TS 29113, C535b.  */
5464   if (((sym->ts.type == BT_CLASS && sym->attr.class_ok
5465 	&& CLASS_DATA (sym)->as
5466 	&& CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
5467        || (sym->ts.type != BT_CLASS && sym->as
5468 	   && sym->as->type == AS_ASSUMED_RANK))
5469       && e->ref
5470       && !(e->ref->type == REF_ARRAY && e->ref->u.ar.type == AR_FULL
5471 	   && e->ref->next == NULL))
5472     {
5473       gfc_error ("Assumed-rank variable %s at %L shall not have a subobject "
5474 		 "reference", sym->name, &e->ref->u.ar.where);
5475       return false;
5476     }
5477 
5478   /* For variables that are used in an associate (target => object) where
5479      the object's basetype is array valued while the target is scalar,
5480      the ts' type of the component refs is still array valued, which
5481      can't be translated that way.  */
5482   if (sym->assoc && e->rank == 0 && e->ref && sym->ts.type == BT_CLASS
5483       && sym->assoc->target && sym->assoc->target->ts.type == BT_CLASS
5484       && CLASS_DATA (sym->assoc->target)->as)
5485     {
5486       gfc_ref *ref = e->ref;
5487       while (ref)
5488 	{
5489 	  switch (ref->type)
5490 	    {
5491 	    case REF_COMPONENT:
5492 	      ref->u.c.sym = sym->ts.u.derived;
5493 	      /* Stop the loop.  */
5494 	      ref = NULL;
5495 	      break;
5496 	    default:
5497 	      ref = ref->next;
5498 	      break;
5499 	    }
5500 	}
5501     }
5502 
5503   /* If this is an associate-name, it may be parsed with an array reference
5504      in error even though the target is scalar.  Fail directly in this case.
5505      TODO Understand why class scalar expressions must be excluded.  */
5506   if (sym->assoc && !(sym->ts.type == BT_CLASS && e->rank == 0))
5507     {
5508       if (sym->ts.type == BT_CLASS)
5509 	gfc_fix_class_refs (e);
5510       if (!sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
5511 	return false;
5512       else if (sym->attr.dimension && (!e->ref || e->ref->type != REF_ARRAY))
5513 	{
5514 	  /* This can happen because the parser did not detect that the
5515 	     associate name is an array and the expression had no array
5516 	     part_ref.  */
5517 	  gfc_ref *ref = gfc_get_ref ();
5518 	  ref->type = REF_ARRAY;
5519 	  ref->u.ar = *gfc_get_array_ref();
5520 	  ref->u.ar.type = AR_FULL;
5521 	  if (sym->as)
5522 	    {
5523 	      ref->u.ar.as = sym->as;
5524 	      ref->u.ar.dimen = sym->as->rank;
5525 	    }
5526 	  ref->next = e->ref;
5527 	  e->ref = ref;
5528 
5529 	}
5530     }
5531 
5532   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.generic)
5533     sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
5534 
5535   /* On the other hand, the parser may not have known this is an array;
5536      in this case, we have to add a FULL reference.  */
5537   if (sym->assoc && sym->attr.dimension && !e->ref)
5538     {
5539       e->ref = gfc_get_ref ();
5540       e->ref->type = REF_ARRAY;
5541       e->ref->u.ar.type = AR_FULL;
5542       e->ref->u.ar.dimen = 0;
5543     }
5544 
5545   /* Like above, but for class types, where the checking whether an array
5546      ref is present is more complicated.  Furthermore make sure not to add
5547      the full array ref to _vptr or _len refs.  */
5548   if (sym->assoc && sym->ts.type == BT_CLASS
5549       && CLASS_DATA (sym)->attr.dimension
5550       && (e->ts.type != BT_DERIVED || !e->ts.u.derived->attr.vtype))
5551     {
5552       gfc_ref *ref, *newref;
5553 
5554       newref = gfc_get_ref ();
5555       newref->type = REF_ARRAY;
5556       newref->u.ar.type = AR_FULL;
5557       newref->u.ar.dimen = 0;
5558       /* Because this is an associate var and the first ref either is a ref to
5559 	 the _data component or not, no traversal of the ref chain is
5560 	 needed.  The array ref needs to be inserted after the _data ref,
5561 	 or when that is not present, which may happend for polymorphic
5562 	 types, then at the first position.  */
5563       ref = e->ref;
5564       if (!ref)
5565 	e->ref = newref;
5566       else if (ref->type == REF_COMPONENT
5567 	       && strcmp ("_data", ref->u.c.component->name) == 0)
5568 	{
5569 	  if (!ref->next || ref->next->type != REF_ARRAY)
5570 	    {
5571 	      newref->next = ref->next;
5572 	      ref->next = newref;
5573 	    }
5574 	  else
5575 	    /* Array ref present already.  */
5576 	    gfc_free_ref_list (newref);
5577 	}
5578       else if (ref->type == REF_ARRAY)
5579 	/* Array ref present already.  */
5580 	gfc_free_ref_list (newref);
5581       else
5582 	{
5583 	  newref->next = ref;
5584 	  e->ref = newref;
5585 	}
5586     }
5587 
5588   if (e->ref && !resolve_ref (e))
5589     return false;
5590 
5591   if (sym->attr.flavor == FL_PROCEDURE
5592       && (!sym->attr.function
5593 	  || (sym->attr.function && sym->result
5594 	      && sym->result->attr.proc_pointer
5595 	      && !sym->result->attr.function)))
5596     {
5597       e->ts.type = BT_PROCEDURE;
5598       goto resolve_procedure;
5599     }
5600 
5601   if (sym->ts.type != BT_UNKNOWN)
5602     gfc_variable_attr (e, &e->ts);
5603   else if (sym->attr.flavor == FL_PROCEDURE
5604 	   && sym->attr.function && sym->result
5605 	   && sym->result->ts.type != BT_UNKNOWN
5606 	   && sym->result->attr.proc_pointer)
5607     e->ts = sym->result->ts;
5608   else
5609     {
5610       /* Must be a simple variable reference.  */
5611       if (!gfc_set_default_type (sym, 1, sym->ns))
5612 	return false;
5613       e->ts = sym->ts;
5614     }
5615 
5616   if (check_assumed_size_reference (sym, e))
5617     return false;
5618 
5619   /* Deal with forward references to entries during gfc_resolve_code, to
5620      satisfy, at least partially, 12.5.2.5.  */
5621   if (gfc_current_ns->entries
5622       && current_entry_id == sym->entry_id
5623       && cs_base
5624       && cs_base->current
5625       && cs_base->current->op != EXEC_ENTRY)
5626     {
5627       gfc_entry_list *entry;
5628       gfc_formal_arglist *formal;
5629       int n;
5630       bool seen, saved_specification_expr;
5631 
5632       /* If the symbol is a dummy...  */
5633       if (sym->attr.dummy && sym->ns == gfc_current_ns)
5634 	{
5635 	  entry = gfc_current_ns->entries;
5636 	  seen = false;
5637 
5638 	  /* ...test if the symbol is a parameter of previous entries.  */
5639 	  for (; entry && entry->id <= current_entry_id; entry = entry->next)
5640 	    for (formal = entry->sym->formal; formal; formal = formal->next)
5641 	      {
5642 		if (formal->sym && sym->name == formal->sym->name)
5643 		  {
5644 		    seen = true;
5645 		    break;
5646 		  }
5647 	      }
5648 
5649 	  /*  If it has not been seen as a dummy, this is an error.  */
5650 	  if (!seen)
5651 	    {
5652 	      if (specification_expr)
5653 		gfc_error ("Variable %qs, used in a specification expression"
5654 			   ", is referenced at %L before the ENTRY statement "
5655 			   "in which it is a parameter",
5656 			   sym->name, &cs_base->current->loc);
5657 	      else
5658 		gfc_error ("Variable %qs is used at %L before the ENTRY "
5659 			   "statement in which it is a parameter",
5660 			   sym->name, &cs_base->current->loc);
5661 	      t = false;
5662 	    }
5663 	}
5664 
5665       /* Now do the same check on the specification expressions.  */
5666       saved_specification_expr = specification_expr;
5667       specification_expr = true;
5668       if (sym->ts.type == BT_CHARACTER
5669 	  && !gfc_resolve_expr (sym->ts.u.cl->length))
5670 	t = false;
5671 
5672       if (sym->as)
5673 	for (n = 0; n < sym->as->rank; n++)
5674 	  {
5675 	     if (!gfc_resolve_expr (sym->as->lower[n]))
5676 	       t = false;
5677 	     if (!gfc_resolve_expr (sym->as->upper[n]))
5678 	       t = false;
5679 	  }
5680       specification_expr = saved_specification_expr;
5681 
5682       if (t)
5683 	/* Update the symbol's entry level.  */
5684 	sym->entry_id = current_entry_id + 1;
5685     }
5686 
5687   /* If a symbol has been host_associated mark it.  This is used latter,
5688      to identify if aliasing is possible via host association.  */
5689   if (sym->attr.flavor == FL_VARIABLE
5690 	&& gfc_current_ns->parent
5691 	&& (gfc_current_ns->parent == sym->ns
5692 	      || (gfc_current_ns->parent->parent
5693 		    && gfc_current_ns->parent->parent == sym->ns)))
5694     sym->attr.host_assoc = 1;
5695 
5696   if (gfc_current_ns->proc_name
5697       && sym->attr.dimension
5698       && (sym->ns != gfc_current_ns
5699 	  || sym->attr.use_assoc
5700 	  || sym->attr.in_common))
5701     gfc_current_ns->proc_name->attr.array_outer_dependency = 1;
5702 
5703 resolve_procedure:
5704   if (t && !resolve_procedure_expression (e))
5705     t = false;
5706 
5707   /* F2008, C617 and C1229.  */
5708   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5709       && gfc_is_coindexed (e))
5710     {
5711       gfc_ref *ref, *ref2 = NULL;
5712 
5713       for (ref = e->ref; ref; ref = ref->next)
5714 	{
5715 	  if (ref->type == REF_COMPONENT)
5716 	    ref2 = ref;
5717 	  if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5718 	    break;
5719 	}
5720 
5721       for ( ; ref; ref = ref->next)
5722 	if (ref->type == REF_COMPONENT)
5723 	  break;
5724 
5725       /* Expression itself is not coindexed object.  */
5726       if (ref && e->ts.type == BT_CLASS)
5727 	{
5728 	  gfc_error ("Polymorphic subobject of coindexed object at %L",
5729 		     &e->where);
5730 	  t = false;
5731 	}
5732 
5733       /* Expression itself is coindexed object.  */
5734       if (ref == NULL)
5735 	{
5736 	  gfc_component *c;
5737 	  c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5738 	  for ( ; c; c = c->next)
5739 	    if (c->attr.allocatable && c->ts.type == BT_CLASS)
5740 	      {
5741 		gfc_error ("Coindexed object with polymorphic allocatable "
5742 			 "subcomponent at %L", &e->where);
5743 		t = false;
5744 		break;
5745 	      }
5746 	}
5747     }
5748 
5749   if (t)
5750     expression_rank (e);
5751 
5752   if (t && flag_coarray == GFC_FCOARRAY_LIB && gfc_is_coindexed (e))
5753     add_caf_get_intrinsic (e);
5754 
5755   /* Simplify cases where access to a parameter array results in a
5756      single constant.  Suppress errors since those will have been
5757      issued before, as warnings.  */
5758   if (e->rank == 0 && sym->as && sym->attr.flavor == FL_PARAMETER)
5759     {
5760       gfc_push_suppress_errors ();
5761       gfc_simplify_expr (e, 1);
5762       gfc_pop_suppress_errors ();
5763     }
5764 
5765   return t;
5766 }
5767 
5768 
5769 /* Checks to see that the correct symbol has been host associated.
5770    The only situation where this arises is that in which a twice
5771    contained function is parsed after the host association is made.
5772    Therefore, on detecting this, change the symbol in the expression
5773    and convert the array reference into an actual arglist if the old
5774    symbol is a variable.  */
5775 static bool
5776 check_host_association (gfc_expr *e)
5777 {
5778   gfc_symbol *sym, *old_sym;
5779   gfc_symtree *st;
5780   int n;
5781   gfc_ref *ref;
5782   gfc_actual_arglist *arg, *tail = NULL;
5783   bool retval = e->expr_type == EXPR_FUNCTION;
5784 
5785   /*  If the expression is the result of substitution in
5786       interface.c(gfc_extend_expr) because there is no way in
5787       which the host association can be wrong.  */
5788   if (e->symtree == NULL
5789 	|| e->symtree->n.sym == NULL
5790 	|| e->user_operator)
5791     return retval;
5792 
5793   old_sym = e->symtree->n.sym;
5794 
5795   if (gfc_current_ns->parent
5796 	&& old_sym->ns != gfc_current_ns)
5797     {
5798       /* Use the 'USE' name so that renamed module symbols are
5799 	 correctly handled.  */
5800       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5801 
5802       if (sym && old_sym != sym
5803 	      && sym->ts.type == old_sym->ts.type
5804 	      && sym->attr.flavor == FL_PROCEDURE
5805 	      && sym->attr.contained)
5806 	{
5807 	  /* Clear the shape, since it might not be valid.  */
5808 	  gfc_free_shape (&e->shape, e->rank);
5809 
5810 	  /* Give the expression the right symtree!  */
5811 	  gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5812 	  gcc_assert (st != NULL);
5813 
5814 	  if (old_sym->attr.flavor == FL_PROCEDURE
5815 		|| e->expr_type == EXPR_FUNCTION)
5816   	    {
5817 	      /* Original was function so point to the new symbol, since
5818 		 the actual argument list is already attached to the
5819 		 expression.  */
5820 	      e->value.function.esym = NULL;
5821 	      e->symtree = st;
5822 	    }
5823 	  else
5824 	    {
5825 	      /* Original was variable so convert array references into
5826 		 an actual arglist. This does not need any checking now
5827 		 since resolve_function will take care of it.  */
5828 	      e->value.function.actual = NULL;
5829 	      e->expr_type = EXPR_FUNCTION;
5830 	      e->symtree = st;
5831 
5832 	      /* Ambiguity will not arise if the array reference is not
5833 		 the last reference.  */
5834 	      for (ref = e->ref; ref; ref = ref->next)
5835 		if (ref->type == REF_ARRAY && ref->next == NULL)
5836 		  break;
5837 
5838 	      gcc_assert (ref->type == REF_ARRAY);
5839 
5840 	      /* Grab the start expressions from the array ref and
5841 		 copy them into actual arguments.  */
5842 	      for (n = 0; n < ref->u.ar.dimen; n++)
5843 		{
5844 		  arg = gfc_get_actual_arglist ();
5845 		  arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5846 		  if (e->value.function.actual == NULL)
5847 		    tail = e->value.function.actual = arg;
5848 	          else
5849 		    {
5850 		      tail->next = arg;
5851 		      tail = arg;
5852 		    }
5853 		}
5854 
5855 	      /* Dump the reference list and set the rank.  */
5856 	      gfc_free_ref_list (e->ref);
5857 	      e->ref = NULL;
5858 	      e->rank = sym->as ? sym->as->rank : 0;
5859 	    }
5860 
5861 	  gfc_resolve_expr (e);
5862 	  sym->refs++;
5863 	}
5864     }
5865   /* This might have changed!  */
5866   return e->expr_type == EXPR_FUNCTION;
5867 }
5868 
5869 
5870 static void
5871 gfc_resolve_character_operator (gfc_expr *e)
5872 {
5873   gfc_expr *op1 = e->value.op.op1;
5874   gfc_expr *op2 = e->value.op.op2;
5875   gfc_expr *e1 = NULL;
5876   gfc_expr *e2 = NULL;
5877 
5878   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5879 
5880   if (op1->ts.u.cl && op1->ts.u.cl->length)
5881     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5882   else if (op1->expr_type == EXPR_CONSTANT)
5883     e1 = gfc_get_int_expr (gfc_charlen_int_kind, NULL,
5884 			   op1->value.character.length);
5885 
5886   if (op2->ts.u.cl && op2->ts.u.cl->length)
5887     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5888   else if (op2->expr_type == EXPR_CONSTANT)
5889     e2 = gfc_get_int_expr (gfc_charlen_int_kind, NULL,
5890 			   op2->value.character.length);
5891 
5892   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5893 
5894   if (!e1 || !e2)
5895     {
5896       gfc_free_expr (e1);
5897       gfc_free_expr (e2);
5898 
5899       return;
5900     }
5901 
5902   e->ts.u.cl->length = gfc_add (e1, e2);
5903   e->ts.u.cl->length->ts.type = BT_INTEGER;
5904   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5905   gfc_simplify_expr (e->ts.u.cl->length, 0);
5906   gfc_resolve_expr (e->ts.u.cl->length);
5907 
5908   return;
5909 }
5910 
5911 
5912 /*  Ensure that an character expression has a charlen and, if possible, a
5913     length expression.  */
5914 
5915 static void
5916 fixup_charlen (gfc_expr *e)
5917 {
5918   /* The cases fall through so that changes in expression type and the need
5919      for multiple fixes are picked up.  In all circumstances, a charlen should
5920      be available for the middle end to hang a backend_decl on.  */
5921   switch (e->expr_type)
5922     {
5923     case EXPR_OP:
5924       gfc_resolve_character_operator (e);
5925       /* FALLTHRU */
5926 
5927     case EXPR_ARRAY:
5928       if (e->expr_type == EXPR_ARRAY)
5929 	gfc_resolve_character_array_constructor (e);
5930       /* FALLTHRU */
5931 
5932     case EXPR_SUBSTRING:
5933       if (!e->ts.u.cl && e->ref)
5934 	gfc_resolve_substring_charlen (e);
5935       /* FALLTHRU */
5936 
5937     default:
5938       if (!e->ts.u.cl)
5939 	e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5940 
5941       break;
5942     }
5943 }
5944 
5945 
5946 /* Update an actual argument to include the passed-object for type-bound
5947    procedures at the right position.  */
5948 
5949 static gfc_actual_arglist*
5950 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5951 		     const char *name)
5952 {
5953   gcc_assert (argpos > 0);
5954 
5955   if (argpos == 1)
5956     {
5957       gfc_actual_arglist* result;
5958 
5959       result = gfc_get_actual_arglist ();
5960       result->expr = po;
5961       result->next = lst;
5962       if (name)
5963         result->name = name;
5964 
5965       return result;
5966     }
5967 
5968   if (lst)
5969     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5970   else
5971     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5972   return lst;
5973 }
5974 
5975 
5976 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5977 
5978 static gfc_expr*
5979 extract_compcall_passed_object (gfc_expr* e)
5980 {
5981   gfc_expr* po;
5982 
5983   if (e->expr_type == EXPR_UNKNOWN)
5984     {
5985       gfc_error ("Error in typebound call at %L",
5986 		 &e->where);
5987       return NULL;
5988     }
5989 
5990   gcc_assert (e->expr_type == EXPR_COMPCALL);
5991 
5992   if (e->value.compcall.base_object)
5993     po = gfc_copy_expr (e->value.compcall.base_object);
5994   else
5995     {
5996       po = gfc_get_expr ();
5997       po->expr_type = EXPR_VARIABLE;
5998       po->symtree = e->symtree;
5999       po->ref = gfc_copy_ref (e->ref);
6000       po->where = e->where;
6001     }
6002 
6003   if (!gfc_resolve_expr (po))
6004     return NULL;
6005 
6006   return po;
6007 }
6008 
6009 
6010 /* Update the arglist of an EXPR_COMPCALL expression to include the
6011    passed-object.  */
6012 
6013 static bool
6014 update_compcall_arglist (gfc_expr* e)
6015 {
6016   gfc_expr* po;
6017   gfc_typebound_proc* tbp;
6018 
6019   tbp = e->value.compcall.tbp;
6020 
6021   if (tbp->error)
6022     return false;
6023 
6024   po = extract_compcall_passed_object (e);
6025   if (!po)
6026     return false;
6027 
6028   if (tbp->nopass || e->value.compcall.ignore_pass)
6029     {
6030       gfc_free_expr (po);
6031       return true;
6032     }
6033 
6034   if (tbp->pass_arg_num <= 0)
6035     return false;
6036 
6037   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
6038 						  tbp->pass_arg_num,
6039 						  tbp->pass_arg);
6040 
6041   return true;
6042 }
6043 
6044 
6045 /* Extract the passed object from a PPC call (a copy of it).  */
6046 
6047 static gfc_expr*
6048 extract_ppc_passed_object (gfc_expr *e)
6049 {
6050   gfc_expr *po;
6051   gfc_ref **ref;
6052 
6053   po = gfc_get_expr ();
6054   po->expr_type = EXPR_VARIABLE;
6055   po->symtree = e->symtree;
6056   po->ref = gfc_copy_ref (e->ref);
6057   po->where = e->where;
6058 
6059   /* Remove PPC reference.  */
6060   ref = &po->ref;
6061   while ((*ref)->next)
6062     ref = &(*ref)->next;
6063   gfc_free_ref_list (*ref);
6064   *ref = NULL;
6065 
6066   if (!gfc_resolve_expr (po))
6067     return NULL;
6068 
6069   return po;
6070 }
6071 
6072 
6073 /* Update the actual arglist of a procedure pointer component to include the
6074    passed-object.  */
6075 
6076 static bool
6077 update_ppc_arglist (gfc_expr* e)
6078 {
6079   gfc_expr* po;
6080   gfc_component *ppc;
6081   gfc_typebound_proc* tb;
6082 
6083   ppc = gfc_get_proc_ptr_comp (e);
6084   if (!ppc)
6085     return false;
6086 
6087   tb = ppc->tb;
6088 
6089   if (tb->error)
6090     return false;
6091   else if (tb->nopass)
6092     return true;
6093 
6094   po = extract_ppc_passed_object (e);
6095   if (!po)
6096     return false;
6097 
6098   /* F08:R739.  */
6099   if (po->rank != 0)
6100     {
6101       gfc_error ("Passed-object at %L must be scalar", &e->where);
6102       return false;
6103     }
6104 
6105   /* F08:C611.  */
6106   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
6107     {
6108       gfc_error ("Base object for procedure-pointer component call at %L is of"
6109 		 " ABSTRACT type %qs", &e->where, po->ts.u.derived->name);
6110       return false;
6111     }
6112 
6113   gcc_assert (tb->pass_arg_num > 0);
6114   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
6115 						  tb->pass_arg_num,
6116 						  tb->pass_arg);
6117 
6118   return true;
6119 }
6120 
6121 
6122 /* Check that the object a TBP is called on is valid, i.e. it must not be
6123    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
6124 
6125 static bool
6126 check_typebound_baseobject (gfc_expr* e)
6127 {
6128   gfc_expr* base;
6129   bool return_value = false;
6130 
6131   base = extract_compcall_passed_object (e);
6132   if (!base)
6133     return false;
6134 
6135   if (base->ts.type != BT_DERIVED && base->ts.type != BT_CLASS)
6136     {
6137       gfc_error ("Error in typebound call at %L", &e->where);
6138       goto cleanup;
6139     }
6140 
6141   if (base->ts.type == BT_CLASS && !gfc_expr_attr (base).class_ok)
6142     return false;
6143 
6144   /* F08:C611.  */
6145   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
6146     {
6147       gfc_error ("Base object for type-bound procedure call at %L is of"
6148 		 " ABSTRACT type %qs", &e->where, base->ts.u.derived->name);
6149       goto cleanup;
6150     }
6151 
6152   /* F08:C1230. If the procedure called is NOPASS,
6153      the base object must be scalar.  */
6154   if (e->value.compcall.tbp->nopass && base->rank != 0)
6155     {
6156       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
6157 		 " be scalar", &e->where);
6158       goto cleanup;
6159     }
6160 
6161   return_value = true;
6162 
6163 cleanup:
6164   gfc_free_expr (base);
6165   return return_value;
6166 }
6167 
6168 
6169 /* Resolve a call to a type-bound procedure, either function or subroutine,
6170    statically from the data in an EXPR_COMPCALL expression.  The adapted
6171    arglist and the target-procedure symtree are returned.  */
6172 
6173 static bool
6174 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
6175 			  gfc_actual_arglist** actual)
6176 {
6177   gcc_assert (e->expr_type == EXPR_COMPCALL);
6178   gcc_assert (!e->value.compcall.tbp->is_generic);
6179 
6180   /* Update the actual arglist for PASS.  */
6181   if (!update_compcall_arglist (e))
6182     return false;
6183 
6184   *actual = e->value.compcall.actual;
6185   *target = e->value.compcall.tbp->u.specific;
6186 
6187   gfc_free_ref_list (e->ref);
6188   e->ref = NULL;
6189   e->value.compcall.actual = NULL;
6190 
6191   /* If we find a deferred typebound procedure, check for derived types
6192      that an overriding typebound procedure has not been missed.  */
6193   if (e->value.compcall.name
6194       && !e->value.compcall.tbp->non_overridable
6195       && e->value.compcall.base_object
6196       && e->value.compcall.base_object->ts.type == BT_DERIVED)
6197     {
6198       gfc_symtree *st;
6199       gfc_symbol *derived;
6200 
6201       /* Use the derived type of the base_object.  */
6202       derived = e->value.compcall.base_object->ts.u.derived;
6203       st = NULL;
6204 
6205       /* If necessary, go through the inheritance chain.  */
6206       while (!st && derived)
6207 	{
6208 	  /* Look for the typebound procedure 'name'.  */
6209 	  if (derived->f2k_derived && derived->f2k_derived->tb_sym_root)
6210 	    st = gfc_find_symtree (derived->f2k_derived->tb_sym_root,
6211 				   e->value.compcall.name);
6212 	  if (!st)
6213 	    derived = gfc_get_derived_super_type (derived);
6214 	}
6215 
6216       /* Now find the specific name in the derived type namespace.  */
6217       if (st && st->n.tb && st->n.tb->u.specific)
6218 	gfc_find_sym_tree (st->n.tb->u.specific->name,
6219 			   derived->ns, 1, &st);
6220       if (st)
6221 	*target = st;
6222     }
6223   return true;
6224 }
6225 
6226 
6227 /* Get the ultimate declared type from an expression.  In addition,
6228    return the last class/derived type reference and the copy of the
6229    reference list.  If check_types is set true, derived types are
6230    identified as well as class references.  */
6231 static gfc_symbol*
6232 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
6233 			gfc_expr *e, bool check_types)
6234 {
6235   gfc_symbol *declared;
6236   gfc_ref *ref;
6237 
6238   declared = NULL;
6239   if (class_ref)
6240     *class_ref = NULL;
6241   if (new_ref)
6242     *new_ref = gfc_copy_ref (e->ref);
6243 
6244   for (ref = e->ref; ref; ref = ref->next)
6245     {
6246       if (ref->type != REF_COMPONENT)
6247 	continue;
6248 
6249       if ((ref->u.c.component->ts.type == BT_CLASS
6250 	     || (check_types && gfc_bt_struct (ref->u.c.component->ts.type)))
6251 	  && ref->u.c.component->attr.flavor != FL_PROCEDURE)
6252 	{
6253 	  declared = ref->u.c.component->ts.u.derived;
6254 	  if (class_ref)
6255 	    *class_ref = ref;
6256 	}
6257     }
6258 
6259   if (declared == NULL)
6260     declared = e->symtree->n.sym->ts.u.derived;
6261 
6262   return declared;
6263 }
6264 
6265 
6266 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
6267    which of the specific bindings (if any) matches the arglist and transform
6268    the expression into a call of that binding.  */
6269 
6270 static bool
6271 resolve_typebound_generic_call (gfc_expr* e, const char **name)
6272 {
6273   gfc_typebound_proc* genproc;
6274   const char* genname;
6275   gfc_symtree *st;
6276   gfc_symbol *derived;
6277 
6278   gcc_assert (e->expr_type == EXPR_COMPCALL);
6279   genname = e->value.compcall.name;
6280   genproc = e->value.compcall.tbp;
6281 
6282   if (!genproc->is_generic)
6283     return true;
6284 
6285   /* Try the bindings on this type and in the inheritance hierarchy.  */
6286   for (; genproc; genproc = genproc->overridden)
6287     {
6288       gfc_tbp_generic* g;
6289 
6290       gcc_assert (genproc->is_generic);
6291       for (g = genproc->u.generic; g; g = g->next)
6292 	{
6293 	  gfc_symbol* target;
6294 	  gfc_actual_arglist* args;
6295 	  bool matches;
6296 
6297 	  gcc_assert (g->specific);
6298 
6299 	  if (g->specific->error)
6300 	    continue;
6301 
6302 	  target = g->specific->u.specific->n.sym;
6303 
6304 	  /* Get the right arglist by handling PASS/NOPASS.  */
6305 	  args = gfc_copy_actual_arglist (e->value.compcall.actual);
6306 	  if (!g->specific->nopass)
6307 	    {
6308 	      gfc_expr* po;
6309 	      po = extract_compcall_passed_object (e);
6310 	      if (!po)
6311 		{
6312 		  gfc_free_actual_arglist (args);
6313 		  return false;
6314 		}
6315 
6316 	      gcc_assert (g->specific->pass_arg_num > 0);
6317 	      gcc_assert (!g->specific->error);
6318 	      args = update_arglist_pass (args, po, g->specific->pass_arg_num,
6319 					  g->specific->pass_arg);
6320 	    }
6321 	  resolve_actual_arglist (args, target->attr.proc,
6322 				  is_external_proc (target)
6323 				  && gfc_sym_get_dummy_args (target) == NULL);
6324 
6325 	  /* Check if this arglist matches the formal.  */
6326 	  matches = gfc_arglist_matches_symbol (&args, target);
6327 
6328 	  /* Clean up and break out of the loop if we've found it.  */
6329 	  gfc_free_actual_arglist (args);
6330 	  if (matches)
6331 	    {
6332 	      e->value.compcall.tbp = g->specific;
6333 	      genname = g->specific_st->name;
6334 	      /* Pass along the name for CLASS methods, where the vtab
6335 		 procedure pointer component has to be referenced.  */
6336 	      if (name)
6337 		*name = genname;
6338 	      goto success;
6339 	    }
6340 	}
6341     }
6342 
6343   /* Nothing matching found!  */
6344   gfc_error ("Found no matching specific binding for the call to the GENERIC"
6345 	     " %qs at %L", genname, &e->where);
6346   return false;
6347 
6348 success:
6349   /* Make sure that we have the right specific instance for the name.  */
6350   derived = get_declared_from_expr (NULL, NULL, e, true);
6351 
6352   st = gfc_find_typebound_proc (derived, NULL, genname, true, &e->where);
6353   if (st)
6354     e->value.compcall.tbp = st->n.tb;
6355 
6356   return true;
6357 }
6358 
6359 
6360 /* Resolve a call to a type-bound subroutine.  */
6361 
6362 static bool
6363 resolve_typebound_call (gfc_code* c, const char **name, bool *overridable)
6364 {
6365   gfc_actual_arglist* newactual;
6366   gfc_symtree* target;
6367 
6368   /* Check that's really a SUBROUTINE.  */
6369   if (!c->expr1->value.compcall.tbp->subroutine)
6370     {
6371       if (!c->expr1->value.compcall.tbp->is_generic
6372 	  && c->expr1->value.compcall.tbp->u.specific
6373 	  && c->expr1->value.compcall.tbp->u.specific->n.sym
6374 	  && c->expr1->value.compcall.tbp->u.specific->n.sym->attr.subroutine)
6375 	c->expr1->value.compcall.tbp->subroutine = 1;
6376       else
6377 	{
6378 	  gfc_error ("%qs at %L should be a SUBROUTINE",
6379 		     c->expr1->value.compcall.name, &c->loc);
6380 	  return false;
6381 	}
6382     }
6383 
6384   if (!check_typebound_baseobject (c->expr1))
6385     return false;
6386 
6387   /* Pass along the name for CLASS methods, where the vtab
6388      procedure pointer component has to be referenced.  */
6389   if (name)
6390     *name = c->expr1->value.compcall.name;
6391 
6392   if (!resolve_typebound_generic_call (c->expr1, name))
6393     return false;
6394 
6395   /* Pass along the NON_OVERRIDABLE attribute of the specific TBP. */
6396   if (overridable)
6397     *overridable = !c->expr1->value.compcall.tbp->non_overridable;
6398 
6399   /* Transform into an ordinary EXEC_CALL for now.  */
6400 
6401   if (!resolve_typebound_static (c->expr1, &target, &newactual))
6402     return false;
6403 
6404   c->ext.actual = newactual;
6405   c->symtree = target;
6406   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
6407 
6408   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
6409 
6410   gfc_free_expr (c->expr1);
6411   c->expr1 = gfc_get_expr ();
6412   c->expr1->expr_type = EXPR_FUNCTION;
6413   c->expr1->symtree = target;
6414   c->expr1->where = c->loc;
6415 
6416   return resolve_call (c);
6417 }
6418 
6419 
6420 /* Resolve a component-call expression.  */
6421 static bool
6422 resolve_compcall (gfc_expr* e, const char **name)
6423 {
6424   gfc_actual_arglist* newactual;
6425   gfc_symtree* target;
6426 
6427   /* Check that's really a FUNCTION.  */
6428   if (!e->value.compcall.tbp->function)
6429     {
6430       gfc_error ("%qs at %L should be a FUNCTION",
6431 		 e->value.compcall.name, &e->where);
6432       return false;
6433     }
6434 
6435   /* These must not be assign-calls!  */
6436   gcc_assert (!e->value.compcall.assign);
6437 
6438   if (!check_typebound_baseobject (e))
6439     return false;
6440 
6441   /* Pass along the name for CLASS methods, where the vtab
6442      procedure pointer component has to be referenced.  */
6443   if (name)
6444     *name = e->value.compcall.name;
6445 
6446   if (!resolve_typebound_generic_call (e, name))
6447     return false;
6448   gcc_assert (!e->value.compcall.tbp->is_generic);
6449 
6450   /* Take the rank from the function's symbol.  */
6451   if (e->value.compcall.tbp->u.specific->n.sym->as)
6452     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
6453 
6454   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
6455      arglist to the TBP's binding target.  */
6456 
6457   if (!resolve_typebound_static (e, &target, &newactual))
6458     return false;
6459 
6460   e->value.function.actual = newactual;
6461   e->value.function.name = NULL;
6462   e->value.function.esym = target->n.sym;
6463   e->value.function.isym = NULL;
6464   e->symtree = target;
6465   e->ts = target->n.sym->ts;
6466   e->expr_type = EXPR_FUNCTION;
6467 
6468   /* Resolution is not necessary if this is a class subroutine; this
6469      function only has to identify the specific proc. Resolution of
6470      the call will be done next in resolve_typebound_call.  */
6471   return gfc_resolve_expr (e);
6472 }
6473 
6474 
6475 static bool resolve_fl_derived (gfc_symbol *sym);
6476 
6477 
6478 /* Resolve a typebound function, or 'method'. First separate all
6479    the non-CLASS references by calling resolve_compcall directly.  */
6480 
6481 static bool
6482 resolve_typebound_function (gfc_expr* e)
6483 {
6484   gfc_symbol *declared;
6485   gfc_component *c;
6486   gfc_ref *new_ref;
6487   gfc_ref *class_ref;
6488   gfc_symtree *st;
6489   const char *name;
6490   gfc_typespec ts;
6491   gfc_expr *expr;
6492   bool overridable;
6493 
6494   st = e->symtree;
6495 
6496   /* Deal with typebound operators for CLASS objects.  */
6497   expr = e->value.compcall.base_object;
6498   overridable = !e->value.compcall.tbp->non_overridable;
6499   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
6500     {
6501       /* If the base_object is not a variable, the corresponding actual
6502 	 argument expression must be stored in e->base_expression so
6503 	 that the corresponding tree temporary can be used as the base
6504 	 object in gfc_conv_procedure_call.  */
6505       if (expr->expr_type != EXPR_VARIABLE)
6506 	{
6507 	  gfc_actual_arglist *args;
6508 
6509 	  for (args= e->value.function.actual; args; args = args->next)
6510 	    {
6511 	      if (expr == args->expr)
6512 		expr = args->expr;
6513 	    }
6514 	}
6515 
6516       /* Since the typebound operators are generic, we have to ensure
6517 	 that any delays in resolution are corrected and that the vtab
6518 	 is present.  */
6519       ts = expr->ts;
6520       declared = ts.u.derived;
6521       c = gfc_find_component (declared, "_vptr", true, true, NULL);
6522       if (c->ts.u.derived == NULL)
6523 	c->ts.u.derived = gfc_find_derived_vtab (declared);
6524 
6525       if (!resolve_compcall (e, &name))
6526 	return false;
6527 
6528       /* Use the generic name if it is there.  */
6529       name = name ? name : e->value.function.esym->name;
6530       e->symtree = expr->symtree;
6531       e->ref = gfc_copy_ref (expr->ref);
6532       get_declared_from_expr (&class_ref, NULL, e, false);
6533 
6534       /* Trim away the extraneous references that emerge from nested
6535 	 use of interface.c (extend_expr).  */
6536       if (class_ref && class_ref->next)
6537 	{
6538 	  gfc_free_ref_list (class_ref->next);
6539 	  class_ref->next = NULL;
6540 	}
6541       else if (e->ref && !class_ref && expr->ts.type != BT_CLASS)
6542 	{
6543 	  gfc_free_ref_list (e->ref);
6544 	  e->ref = NULL;
6545 	}
6546 
6547       gfc_add_vptr_component (e);
6548       gfc_add_component_ref (e, name);
6549       e->value.function.esym = NULL;
6550       if (expr->expr_type != EXPR_VARIABLE)
6551 	e->base_expr = expr;
6552       return true;
6553     }
6554 
6555   if (st == NULL)
6556     return resolve_compcall (e, NULL);
6557 
6558   if (!resolve_ref (e))
6559     return false;
6560 
6561   /* Get the CLASS declared type.  */
6562   declared = get_declared_from_expr (&class_ref, &new_ref, e, true);
6563 
6564   if (!resolve_fl_derived (declared))
6565     return false;
6566 
6567   /* Weed out cases of the ultimate component being a derived type.  */
6568   if ((class_ref && gfc_bt_struct (class_ref->u.c.component->ts.type))
6569 	 || (!class_ref && st->n.sym->ts.type != BT_CLASS))
6570     {
6571       gfc_free_ref_list (new_ref);
6572       return resolve_compcall (e, NULL);
6573     }
6574 
6575   c = gfc_find_component (declared, "_data", true, true, NULL);
6576   declared = c->ts.u.derived;
6577 
6578   /* Treat the call as if it is a typebound procedure, in order to roll
6579      out the correct name for the specific function.  */
6580   if (!resolve_compcall (e, &name))
6581     {
6582       gfc_free_ref_list (new_ref);
6583       return false;
6584     }
6585   ts = e->ts;
6586 
6587   if (overridable)
6588     {
6589       /* Convert the expression to a procedure pointer component call.  */
6590       e->value.function.esym = NULL;
6591       e->symtree = st;
6592 
6593       if (new_ref)
6594 	e->ref = new_ref;
6595 
6596       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
6597       gfc_add_vptr_component (e);
6598       gfc_add_component_ref (e, name);
6599 
6600       /* Recover the typespec for the expression.  This is really only
6601 	necessary for generic procedures, where the additional call
6602 	to gfc_add_component_ref seems to throw the collection of the
6603 	correct typespec.  */
6604       e->ts = ts;
6605     }
6606   else if (new_ref)
6607     gfc_free_ref_list (new_ref);
6608 
6609   return true;
6610 }
6611 
6612 /* Resolve a typebound subroutine, or 'method'. First separate all
6613    the non-CLASS references by calling resolve_typebound_call
6614    directly.  */
6615 
6616 static bool
6617 resolve_typebound_subroutine (gfc_code *code)
6618 {
6619   gfc_symbol *declared;
6620   gfc_component *c;
6621   gfc_ref *new_ref;
6622   gfc_ref *class_ref;
6623   gfc_symtree *st;
6624   const char *name;
6625   gfc_typespec ts;
6626   gfc_expr *expr;
6627   bool overridable;
6628 
6629   st = code->expr1->symtree;
6630 
6631   /* Deal with typebound operators for CLASS objects.  */
6632   expr = code->expr1->value.compcall.base_object;
6633   overridable = !code->expr1->value.compcall.tbp->non_overridable;
6634   if (expr && expr->ts.type == BT_CLASS && code->expr1->value.compcall.name)
6635     {
6636       /* If the base_object is not a variable, the corresponding actual
6637 	 argument expression must be stored in e->base_expression so
6638 	 that the corresponding tree temporary can be used as the base
6639 	 object in gfc_conv_procedure_call.  */
6640       if (expr->expr_type != EXPR_VARIABLE)
6641 	{
6642 	  gfc_actual_arglist *args;
6643 
6644 	  args= code->expr1->value.function.actual;
6645 	  for (; args; args = args->next)
6646 	    if (expr == args->expr)
6647 	      expr = args->expr;
6648 	}
6649 
6650       /* Since the typebound operators are generic, we have to ensure
6651 	 that any delays in resolution are corrected and that the vtab
6652 	 is present.  */
6653       declared = expr->ts.u.derived;
6654       c = gfc_find_component (declared, "_vptr", true, true, NULL);
6655       if (c->ts.u.derived == NULL)
6656 	c->ts.u.derived = gfc_find_derived_vtab (declared);
6657 
6658       if (!resolve_typebound_call (code, &name, NULL))
6659 	return false;
6660 
6661       /* Use the generic name if it is there.  */
6662       name = name ? name : code->expr1->value.function.esym->name;
6663       code->expr1->symtree = expr->symtree;
6664       code->expr1->ref = gfc_copy_ref (expr->ref);
6665 
6666       /* Trim away the extraneous references that emerge from nested
6667 	 use of interface.c (extend_expr).  */
6668       get_declared_from_expr (&class_ref, NULL, code->expr1, false);
6669       if (class_ref && class_ref->next)
6670 	{
6671 	  gfc_free_ref_list (class_ref->next);
6672 	  class_ref->next = NULL;
6673 	}
6674       else if (code->expr1->ref && !class_ref)
6675 	{
6676 	  gfc_free_ref_list (code->expr1->ref);
6677 	  code->expr1->ref = NULL;
6678 	}
6679 
6680       /* Now use the procedure in the vtable.  */
6681       gfc_add_vptr_component (code->expr1);
6682       gfc_add_component_ref (code->expr1, name);
6683       code->expr1->value.function.esym = NULL;
6684       if (expr->expr_type != EXPR_VARIABLE)
6685 	code->expr1->base_expr = expr;
6686       return true;
6687     }
6688 
6689   if (st == NULL)
6690     return resolve_typebound_call (code, NULL, NULL);
6691 
6692   if (!resolve_ref (code->expr1))
6693     return false;
6694 
6695   /* Get the CLASS declared type.  */
6696   get_declared_from_expr (&class_ref, &new_ref, code->expr1, true);
6697 
6698   /* Weed out cases of the ultimate component being a derived type.  */
6699   if ((class_ref && gfc_bt_struct (class_ref->u.c.component->ts.type))
6700 	 || (!class_ref && st->n.sym->ts.type != BT_CLASS))
6701     {
6702       gfc_free_ref_list (new_ref);
6703       return resolve_typebound_call (code, NULL, NULL);
6704     }
6705 
6706   if (!resolve_typebound_call (code, &name, &overridable))
6707     {
6708       gfc_free_ref_list (new_ref);
6709       return false;
6710     }
6711   ts = code->expr1->ts;
6712 
6713   if (overridable)
6714     {
6715       /* Convert the expression to a procedure pointer component call.  */
6716       code->expr1->value.function.esym = NULL;
6717       code->expr1->symtree = st;
6718 
6719       if (new_ref)
6720 	code->expr1->ref = new_ref;
6721 
6722       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
6723       gfc_add_vptr_component (code->expr1);
6724       gfc_add_component_ref (code->expr1, name);
6725 
6726       /* Recover the typespec for the expression.  This is really only
6727 	necessary for generic procedures, where the additional call
6728 	to gfc_add_component_ref seems to throw the collection of the
6729 	correct typespec.  */
6730       code->expr1->ts = ts;
6731     }
6732   else if (new_ref)
6733     gfc_free_ref_list (new_ref);
6734 
6735   return true;
6736 }
6737 
6738 
6739 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
6740 
6741 static bool
6742 resolve_ppc_call (gfc_code* c)
6743 {
6744   gfc_component *comp;
6745 
6746   comp = gfc_get_proc_ptr_comp (c->expr1);
6747   gcc_assert (comp != NULL);
6748 
6749   c->resolved_sym = c->expr1->symtree->n.sym;
6750   c->expr1->expr_type = EXPR_VARIABLE;
6751 
6752   if (!comp->attr.subroutine)
6753     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
6754 
6755   if (!resolve_ref (c->expr1))
6756     return false;
6757 
6758   if (!update_ppc_arglist (c->expr1))
6759     return false;
6760 
6761   c->ext.actual = c->expr1->value.compcall.actual;
6762 
6763   if (!resolve_actual_arglist (c->ext.actual, comp->attr.proc,
6764 			       !(comp->ts.interface
6765 				 && comp->ts.interface->formal)))
6766     return false;
6767 
6768   if (!pure_subroutine (comp->ts.interface, comp->name, &c->expr1->where))
6769     return false;
6770 
6771   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
6772 
6773   return true;
6774 }
6775 
6776 
6777 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
6778 
6779 static bool
6780 resolve_expr_ppc (gfc_expr* e)
6781 {
6782   gfc_component *comp;
6783 
6784   comp = gfc_get_proc_ptr_comp (e);
6785   gcc_assert (comp != NULL);
6786 
6787   /* Convert to EXPR_FUNCTION.  */
6788   e->expr_type = EXPR_FUNCTION;
6789   e->value.function.isym = NULL;
6790   e->value.function.actual = e->value.compcall.actual;
6791   e->ts = comp->ts;
6792   if (comp->as != NULL)
6793     e->rank = comp->as->rank;
6794 
6795   if (!comp->attr.function)
6796     gfc_add_function (&comp->attr, comp->name, &e->where);
6797 
6798   if (!resolve_ref (e))
6799     return false;
6800 
6801   if (!resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
6802 			       !(comp->ts.interface
6803 				 && comp->ts.interface->formal)))
6804     return false;
6805 
6806   if (!update_ppc_arglist (e))
6807     return false;
6808 
6809   if (!check_pure_function(e))
6810     return false;
6811 
6812   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6813 
6814   return true;
6815 }
6816 
6817 
6818 static bool
6819 gfc_is_expandable_expr (gfc_expr *e)
6820 {
6821   gfc_constructor *con;
6822 
6823   if (e->expr_type == EXPR_ARRAY)
6824     {
6825       /* Traverse the constructor looking for variables that are flavor
6826 	 parameter.  Parameters must be expanded since they are fully used at
6827 	 compile time.  */
6828       con = gfc_constructor_first (e->value.constructor);
6829       for (; con; con = gfc_constructor_next (con))
6830 	{
6831 	  if (con->expr->expr_type == EXPR_VARIABLE
6832 	      && con->expr->symtree
6833 	      && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6834 	      || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6835 	    return true;
6836 	  if (con->expr->expr_type == EXPR_ARRAY
6837 	      && gfc_is_expandable_expr (con->expr))
6838 	    return true;
6839 	}
6840     }
6841 
6842   return false;
6843 }
6844 
6845 
6846 /* Sometimes variables in specification expressions of the result
6847    of module procedures in submodules wind up not being the 'real'
6848    dummy.  Find this, if possible, in the namespace of the first
6849    formal argument.  */
6850 
6851 static void
6852 fixup_unique_dummy (gfc_expr *e)
6853 {
6854   gfc_symtree *st = NULL;
6855   gfc_symbol *s = NULL;
6856 
6857   if (e->symtree->n.sym->ns->proc_name
6858       && e->symtree->n.sym->ns->proc_name->formal)
6859     s = e->symtree->n.sym->ns->proc_name->formal->sym;
6860 
6861   if (s != NULL)
6862     st = gfc_find_symtree (s->ns->sym_root, e->symtree->n.sym->name);
6863 
6864   if (st != NULL
6865       && st->n.sym != NULL
6866       && st->n.sym->attr.dummy)
6867     e->symtree = st;
6868 }
6869 
6870 /* Resolve an expression.  That is, make sure that types of operands agree
6871    with their operators, intrinsic operators are converted to function calls
6872    for overloaded types and unresolved function references are resolved.  */
6873 
6874 bool
6875 gfc_resolve_expr (gfc_expr *e)
6876 {
6877   bool t;
6878   bool inquiry_save, actual_arg_save, first_actual_arg_save;
6879 
6880   if (e == NULL)
6881     return true;
6882 
6883   /* inquiry_argument only applies to variables.  */
6884   inquiry_save = inquiry_argument;
6885   actual_arg_save = actual_arg;
6886   first_actual_arg_save = first_actual_arg;
6887 
6888   if (e->expr_type != EXPR_VARIABLE)
6889     {
6890       inquiry_argument = false;
6891       actual_arg = false;
6892       first_actual_arg = false;
6893     }
6894   else if (e->symtree != NULL
6895 	   && *e->symtree->name == '@'
6896 	   && e->symtree->n.sym->attr.dummy)
6897     {
6898       /* Deal with submodule specification expressions that are not
6899 	 found to be referenced in module.c(read_cleanup).  */
6900       fixup_unique_dummy (e);
6901     }
6902 
6903   switch (e->expr_type)
6904     {
6905     case EXPR_OP:
6906       t = resolve_operator (e);
6907       break;
6908 
6909     case EXPR_FUNCTION:
6910     case EXPR_VARIABLE:
6911 
6912       if (check_host_association (e))
6913 	t = resolve_function (e);
6914       else
6915 	t = resolve_variable (e);
6916 
6917       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6918 	  && e->ref->type != REF_SUBSTRING)
6919 	gfc_resolve_substring_charlen (e);
6920 
6921       break;
6922 
6923     case EXPR_COMPCALL:
6924       t = resolve_typebound_function (e);
6925       break;
6926 
6927     case EXPR_SUBSTRING:
6928       t = resolve_ref (e);
6929       break;
6930 
6931     case EXPR_CONSTANT:
6932     case EXPR_NULL:
6933       t = true;
6934       break;
6935 
6936     case EXPR_PPC:
6937       t = resolve_expr_ppc (e);
6938       break;
6939 
6940     case EXPR_ARRAY:
6941       t = false;
6942       if (!resolve_ref (e))
6943 	break;
6944 
6945       t = gfc_resolve_array_constructor (e);
6946       /* Also try to expand a constructor.  */
6947       if (t)
6948 	{
6949 	  expression_rank (e);
6950 	  if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6951 	    gfc_expand_constructor (e, false);
6952 	}
6953 
6954       /* This provides the opportunity for the length of constructors with
6955 	 character valued function elements to propagate the string length
6956 	 to the expression.  */
6957       if (t && e->ts.type == BT_CHARACTER)
6958         {
6959 	  /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6960 	     here rather then add a duplicate test for it above.  */
6961 	  gfc_expand_constructor (e, false);
6962 	  t = gfc_resolve_character_array_constructor (e);
6963 	}
6964 
6965       break;
6966 
6967     case EXPR_STRUCTURE:
6968       t = resolve_ref (e);
6969       if (!t)
6970 	break;
6971 
6972       t = resolve_structure_cons (e, 0);
6973       if (!t)
6974 	break;
6975 
6976       t = gfc_simplify_expr (e, 0);
6977       break;
6978 
6979     default:
6980       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6981     }
6982 
6983   if (e->ts.type == BT_CHARACTER && t && !e->ts.u.cl)
6984     fixup_charlen (e);
6985 
6986   inquiry_argument = inquiry_save;
6987   actual_arg = actual_arg_save;
6988   first_actual_arg = first_actual_arg_save;
6989 
6990   return t;
6991 }
6992 
6993 
6994 /* Resolve an expression from an iterator.  They must be scalar and have
6995    INTEGER or (optionally) REAL type.  */
6996 
6997 static bool
6998 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6999 			   const char *name_msgid)
7000 {
7001   if (!gfc_resolve_expr (expr))
7002     return false;
7003 
7004   if (expr->rank != 0)
7005     {
7006       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
7007       return false;
7008     }
7009 
7010   if (expr->ts.type != BT_INTEGER)
7011     {
7012       if (expr->ts.type == BT_REAL)
7013 	{
7014 	  if (real_ok)
7015 	    return gfc_notify_std (GFC_STD_F95_DEL,
7016 				   "%s at %L must be integer",
7017 				   _(name_msgid), &expr->where);
7018 	  else
7019 	    {
7020 	      gfc_error ("%s at %L must be INTEGER", _(name_msgid),
7021 			 &expr->where);
7022 	      return false;
7023 	    }
7024 	}
7025       else
7026 	{
7027 	  gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
7028 	  return false;
7029 	}
7030     }
7031   return true;
7032 }
7033 
7034 
7035 /* Resolve the expressions in an iterator structure.  If REAL_OK is
7036    false allow only INTEGER type iterators, otherwise allow REAL types.
7037    Set own_scope to true for ac-implied-do and data-implied-do as those
7038    have a separate scope such that, e.g., a INTENT(IN) doesn't apply.  */
7039 
7040 bool
7041 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok, bool own_scope)
7042 {
7043   if (!gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable"))
7044     return false;
7045 
7046   if (!gfc_check_vardef_context (iter->var, false, false, own_scope,
7047 				 _("iterator variable")))
7048     return false;
7049 
7050   if (!gfc_resolve_iterator_expr (iter->start, real_ok,
7051 				  "Start expression in DO loop"))
7052     return false;
7053 
7054   if (!gfc_resolve_iterator_expr (iter->end, real_ok,
7055 				  "End expression in DO loop"))
7056     return false;
7057 
7058   if (!gfc_resolve_iterator_expr (iter->step, real_ok,
7059 				  "Step expression in DO loop"))
7060     return false;
7061 
7062   /* Convert start, end, and step to the same type as var.  */
7063   if (iter->start->ts.kind != iter->var->ts.kind
7064       || iter->start->ts.type != iter->var->ts.type)
7065     gfc_convert_type (iter->start, &iter->var->ts, 1);
7066 
7067   if (iter->end->ts.kind != iter->var->ts.kind
7068       || iter->end->ts.type != iter->var->ts.type)
7069     gfc_convert_type (iter->end, &iter->var->ts, 1);
7070 
7071   if (iter->step->ts.kind != iter->var->ts.kind
7072       || iter->step->ts.type != iter->var->ts.type)
7073     gfc_convert_type (iter->step, &iter->var->ts, 1);
7074 
7075   if (iter->step->expr_type == EXPR_CONSTANT)
7076     {
7077       if ((iter->step->ts.type == BT_INTEGER
7078 	   && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
7079 	  || (iter->step->ts.type == BT_REAL
7080 	      && mpfr_sgn (iter->step->value.real) == 0))
7081 	{
7082 	  gfc_error ("Step expression in DO loop at %L cannot be zero",
7083 		     &iter->step->where);
7084 	  return false;
7085 	}
7086     }
7087 
7088   if (iter->start->expr_type == EXPR_CONSTANT
7089       && iter->end->expr_type == EXPR_CONSTANT
7090       && iter->step->expr_type == EXPR_CONSTANT)
7091     {
7092       int sgn, cmp;
7093       if (iter->start->ts.type == BT_INTEGER)
7094 	{
7095 	  sgn = mpz_cmp_ui (iter->step->value.integer, 0);
7096 	  cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
7097 	}
7098       else
7099 	{
7100 	  sgn = mpfr_sgn (iter->step->value.real);
7101 	  cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
7102 	}
7103       if (warn_zerotrip && ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0)))
7104 	gfc_warning (OPT_Wzerotrip,
7105 		     "DO loop at %L will be executed zero times",
7106 		     &iter->step->where);
7107     }
7108 
7109   if (iter->end->expr_type == EXPR_CONSTANT
7110       && iter->end->ts.type == BT_INTEGER
7111       && iter->step->expr_type == EXPR_CONSTANT
7112       && iter->step->ts.type == BT_INTEGER
7113       && (mpz_cmp_si (iter->step->value.integer, -1L) == 0
7114 	  || mpz_cmp_si (iter->step->value.integer, 1L) == 0))
7115     {
7116       bool is_step_positive = mpz_cmp_ui (iter->step->value.integer, 1) == 0;
7117       int k = gfc_validate_kind (BT_INTEGER, iter->end->ts.kind, false);
7118 
7119       if (is_step_positive
7120 	  && mpz_cmp (iter->end->value.integer, gfc_integer_kinds[k].huge) == 0)
7121 	gfc_warning (OPT_Wundefined_do_loop,
7122 		     "DO loop at %L is undefined as it overflows",
7123 		     &iter->step->where);
7124       else if (!is_step_positive
7125 	       && mpz_cmp (iter->end->value.integer,
7126 			   gfc_integer_kinds[k].min_int) == 0)
7127 	gfc_warning (OPT_Wundefined_do_loop,
7128 		     "DO loop at %L is undefined as it underflows",
7129 		     &iter->step->where);
7130     }
7131 
7132   return true;
7133 }
7134 
7135 
7136 /* Traversal function for find_forall_index.  f == 2 signals that
7137    that variable itself is not to be checked - only the references.  */
7138 
7139 static bool
7140 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
7141 {
7142   if (expr->expr_type != EXPR_VARIABLE)
7143     return false;
7144 
7145   /* A scalar assignment  */
7146   if (!expr->ref || *f == 1)
7147     {
7148       if (expr->symtree->n.sym == sym)
7149 	return true;
7150       else
7151 	return false;
7152     }
7153 
7154   if (*f == 2)
7155     *f = 1;
7156   return false;
7157 }
7158 
7159 
7160 /* Check whether the FORALL index appears in the expression or not.
7161    Returns true if SYM is found in EXPR.  */
7162 
7163 bool
7164 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
7165 {
7166   if (gfc_traverse_expr (expr, sym, forall_index, f))
7167     return true;
7168   else
7169     return false;
7170 }
7171 
7172 
7173 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
7174    to be a scalar INTEGER variable.  The subscripts and stride are scalar
7175    INTEGERs, and if stride is a constant it must be nonzero.
7176    Furthermore "A subscript or stride in a forall-triplet-spec shall
7177    not contain a reference to any index-name in the
7178    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
7179 
7180 static void
7181 resolve_forall_iterators (gfc_forall_iterator *it)
7182 {
7183   gfc_forall_iterator *iter, *iter2;
7184 
7185   for (iter = it; iter; iter = iter->next)
7186     {
7187       if (gfc_resolve_expr (iter->var)
7188 	  && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
7189 	gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
7190 		   &iter->var->where);
7191 
7192       if (gfc_resolve_expr (iter->start)
7193 	  && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
7194 	gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
7195 		   &iter->start->where);
7196       if (iter->var->ts.kind != iter->start->ts.kind)
7197 	gfc_convert_type (iter->start, &iter->var->ts, 1);
7198 
7199       if (gfc_resolve_expr (iter->end)
7200 	  && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
7201 	gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
7202 		   &iter->end->where);
7203       if (iter->var->ts.kind != iter->end->ts.kind)
7204 	gfc_convert_type (iter->end, &iter->var->ts, 1);
7205 
7206       if (gfc_resolve_expr (iter->stride))
7207 	{
7208 	  if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
7209 	    gfc_error ("FORALL stride expression at %L must be a scalar %s",
7210 		       &iter->stride->where, "INTEGER");
7211 
7212 	  if (iter->stride->expr_type == EXPR_CONSTANT
7213 	      && mpz_cmp_ui (iter->stride->value.integer, 0) == 0)
7214 	    gfc_error ("FORALL stride expression at %L cannot be zero",
7215 		       &iter->stride->where);
7216 	}
7217       if (iter->var->ts.kind != iter->stride->ts.kind)
7218 	gfc_convert_type (iter->stride, &iter->var->ts, 1);
7219     }
7220 
7221   for (iter = it; iter; iter = iter->next)
7222     for (iter2 = iter; iter2; iter2 = iter2->next)
7223       {
7224 	if (find_forall_index (iter2->start, iter->var->symtree->n.sym, 0)
7225 	    || find_forall_index (iter2->end, iter->var->symtree->n.sym, 0)
7226 	    || find_forall_index (iter2->stride, iter->var->symtree->n.sym, 0))
7227 	  gfc_error ("FORALL index %qs may not appear in triplet "
7228 		     "specification at %L", iter->var->symtree->name,
7229 		     &iter2->start->where);
7230       }
7231 }
7232 
7233 
7234 /* Given a pointer to a symbol that is a derived type, see if it's
7235    inaccessible, i.e. if it's defined in another module and the components are
7236    PRIVATE.  The search is recursive if necessary.  Returns zero if no
7237    inaccessible components are found, nonzero otherwise.  */
7238 
7239 static int
7240 derived_inaccessible (gfc_symbol *sym)
7241 {
7242   gfc_component *c;
7243 
7244   if (sym->attr.use_assoc && sym->attr.private_comp)
7245     return 1;
7246 
7247   for (c = sym->components; c; c = c->next)
7248     {
7249 	/* Prevent an infinite loop through this function.  */
7250 	if (c->ts.type == BT_DERIVED && c->attr.pointer
7251 	    && sym == c->ts.u.derived)
7252 	  continue;
7253 
7254 	if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
7255 	  return 1;
7256     }
7257 
7258   return 0;
7259 }
7260 
7261 
7262 /* Resolve the argument of a deallocate expression.  The expression must be
7263    a pointer or a full array.  */
7264 
7265 static bool
7266 resolve_deallocate_expr (gfc_expr *e)
7267 {
7268   symbol_attribute attr;
7269   int allocatable, pointer;
7270   gfc_ref *ref;
7271   gfc_symbol *sym;
7272   gfc_component *c;
7273   bool unlimited;
7274 
7275   if (!gfc_resolve_expr (e))
7276     return false;
7277 
7278   if (e->expr_type != EXPR_VARIABLE)
7279     goto bad;
7280 
7281   sym = e->symtree->n.sym;
7282   unlimited = UNLIMITED_POLY(sym);
7283 
7284   if (sym->ts.type == BT_CLASS)
7285     {
7286       allocatable = CLASS_DATA (sym)->attr.allocatable;
7287       pointer = CLASS_DATA (sym)->attr.class_pointer;
7288     }
7289   else
7290     {
7291       allocatable = sym->attr.allocatable;
7292       pointer = sym->attr.pointer;
7293     }
7294   for (ref = e->ref; ref; ref = ref->next)
7295     {
7296       switch (ref->type)
7297 	{
7298 	case REF_ARRAY:
7299 	  if (ref->u.ar.type != AR_FULL
7300 	      && !(ref->u.ar.type == AR_ELEMENT && ref->u.ar.as->rank == 0
7301 	           && ref->u.ar.codimen && gfc_ref_this_image (ref)))
7302 	    allocatable = 0;
7303 	  break;
7304 
7305 	case REF_COMPONENT:
7306 	  c = ref->u.c.component;
7307 	  if (c->ts.type == BT_CLASS)
7308 	    {
7309 	      allocatable = CLASS_DATA (c)->attr.allocatable;
7310 	      pointer = CLASS_DATA (c)->attr.class_pointer;
7311 	    }
7312 	  else
7313 	    {
7314 	      allocatable = c->attr.allocatable;
7315 	      pointer = c->attr.pointer;
7316 	    }
7317 	  break;
7318 
7319 	case REF_SUBSTRING:
7320 	case REF_INQUIRY:
7321 	  allocatable = 0;
7322 	  break;
7323 	}
7324     }
7325 
7326   attr = gfc_expr_attr (e);
7327 
7328   if (allocatable == 0 && attr.pointer == 0 && !unlimited)
7329     {
7330     bad:
7331       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
7332 		 &e->where);
7333       return false;
7334     }
7335 
7336   /* F2008, C644.  */
7337   if (gfc_is_coindexed (e))
7338     {
7339       gfc_error ("Coindexed allocatable object at %L", &e->where);
7340       return false;
7341     }
7342 
7343   if (pointer
7344       && !gfc_check_vardef_context (e, true, true, false,
7345 				    _("DEALLOCATE object")))
7346     return false;
7347   if (!gfc_check_vardef_context (e, false, true, false,
7348 				 _("DEALLOCATE object")))
7349     return false;
7350 
7351   return true;
7352 }
7353 
7354 
7355 /* Returns true if the expression e contains a reference to the symbol sym.  */
7356 static bool
7357 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
7358 {
7359   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
7360     return true;
7361 
7362   return false;
7363 }
7364 
7365 bool
7366 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
7367 {
7368   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
7369 }
7370 
7371 
7372 /* Given the expression node e for an allocatable/pointer of derived type to be
7373    allocated, get the expression node to be initialized afterwards (needed for
7374    derived types with default initializers, and derived types with allocatable
7375    components that need nullification.)  */
7376 
7377 gfc_expr *
7378 gfc_expr_to_initialize (gfc_expr *e)
7379 {
7380   gfc_expr *result;
7381   gfc_ref *ref;
7382   int i;
7383 
7384   result = gfc_copy_expr (e);
7385 
7386   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
7387   for (ref = result->ref; ref; ref = ref->next)
7388     if (ref->type == REF_ARRAY && ref->next == NULL)
7389       {
7390 	ref->u.ar.type = AR_FULL;
7391 
7392 	for (i = 0; i < ref->u.ar.dimen; i++)
7393 	  ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
7394 
7395 	break;
7396       }
7397 
7398   gfc_free_shape (&result->shape, result->rank);
7399 
7400   /* Recalculate rank, shape, etc.  */
7401   gfc_resolve_expr (result);
7402   return result;
7403 }
7404 
7405 
7406 /* If the last ref of an expression is an array ref, return a copy of the
7407    expression with that one removed.  Otherwise, a copy of the original
7408    expression.  This is used for allocate-expressions and pointer assignment
7409    LHS, where there may be an array specification that needs to be stripped
7410    off when using gfc_check_vardef_context.  */
7411 
7412 static gfc_expr*
7413 remove_last_array_ref (gfc_expr* e)
7414 {
7415   gfc_expr* e2;
7416   gfc_ref** r;
7417 
7418   e2 = gfc_copy_expr (e);
7419   for (r = &e2->ref; *r; r = &(*r)->next)
7420     if ((*r)->type == REF_ARRAY && !(*r)->next)
7421       {
7422 	gfc_free_ref_list (*r);
7423 	*r = NULL;
7424 	break;
7425       }
7426 
7427   return e2;
7428 }
7429 
7430 
7431 /* Used in resolve_allocate_expr to check that a allocation-object and
7432    a source-expr are conformable.  This does not catch all possible
7433    cases; in particular a runtime checking is needed.  */
7434 
7435 static bool
7436 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
7437 {
7438   gfc_ref *tail;
7439   for (tail = e2->ref; tail && tail->next; tail = tail->next);
7440 
7441   /* First compare rank.  */
7442   if ((tail && (!tail->u.ar.as || e1->rank != tail->u.ar.as->rank))
7443       || (!tail && e1->rank != e2->rank))
7444     {
7445       gfc_error ("Source-expr at %L must be scalar or have the "
7446 		 "same rank as the allocate-object at %L",
7447 		 &e1->where, &e2->where);
7448       return false;
7449     }
7450 
7451   if (e1->shape)
7452     {
7453       int i;
7454       mpz_t s;
7455 
7456       mpz_init (s);
7457 
7458       for (i = 0; i < e1->rank; i++)
7459 	{
7460 	  if (tail->u.ar.start[i] == NULL)
7461 	    break;
7462 
7463 	  if (tail->u.ar.end[i])
7464 	    {
7465 	      mpz_set (s, tail->u.ar.end[i]->value.integer);
7466 	      mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
7467 	      mpz_add_ui (s, s, 1);
7468 	    }
7469 	  else
7470 	    {
7471 	      mpz_set (s, tail->u.ar.start[i]->value.integer);
7472 	    }
7473 
7474 	  if (mpz_cmp (e1->shape[i], s) != 0)
7475 	    {
7476 	      gfc_error ("Source-expr at %L and allocate-object at %L must "
7477 			 "have the same shape", &e1->where, &e2->where);
7478 	      mpz_clear (s);
7479    	      return false;
7480 	    }
7481 	}
7482 
7483       mpz_clear (s);
7484     }
7485 
7486   return true;
7487 }
7488 
7489 
7490 /* Resolve the expression in an ALLOCATE statement, doing the additional
7491    checks to see whether the expression is OK or not.  The expression must
7492    have a trailing array reference that gives the size of the array.  */
7493 
7494 static bool
7495 resolve_allocate_expr (gfc_expr *e, gfc_code *code, bool *array_alloc_wo_spec)
7496 {
7497   int i, pointer, allocatable, dimension, is_abstract;
7498   int codimension;
7499   bool coindexed;
7500   bool unlimited;
7501   symbol_attribute attr;
7502   gfc_ref *ref, *ref2;
7503   gfc_expr *e2;
7504   gfc_array_ref *ar;
7505   gfc_symbol *sym = NULL;
7506   gfc_alloc *a;
7507   gfc_component *c;
7508   bool t;
7509 
7510   /* Mark the utmost array component as being in allocate to allow DIMEN_STAR
7511      checking of coarrays.  */
7512   for (ref = e->ref; ref; ref = ref->next)
7513     if (ref->next == NULL)
7514       break;
7515 
7516   if (ref && ref->type == REF_ARRAY)
7517     ref->u.ar.in_allocate = true;
7518 
7519   if (!gfc_resolve_expr (e))
7520     goto failure;
7521 
7522   /* Make sure the expression is allocatable or a pointer.  If it is
7523      pointer, the next-to-last reference must be a pointer.  */
7524 
7525   ref2 = NULL;
7526   if (e->symtree)
7527     sym = e->symtree->n.sym;
7528 
7529   /* Check whether ultimate component is abstract and CLASS.  */
7530   is_abstract = 0;
7531 
7532   /* Is the allocate-object unlimited polymorphic?  */
7533   unlimited = UNLIMITED_POLY(e);
7534 
7535   if (e->expr_type != EXPR_VARIABLE)
7536     {
7537       allocatable = 0;
7538       attr = gfc_expr_attr (e);
7539       pointer = attr.pointer;
7540       dimension = attr.dimension;
7541       codimension = attr.codimension;
7542     }
7543   else
7544     {
7545       if (sym->ts.type == BT_CLASS && CLASS_DATA (sym))
7546 	{
7547 	  allocatable = CLASS_DATA (sym)->attr.allocatable;
7548 	  pointer = CLASS_DATA (sym)->attr.class_pointer;
7549 	  dimension = CLASS_DATA (sym)->attr.dimension;
7550 	  codimension = CLASS_DATA (sym)->attr.codimension;
7551 	  is_abstract = CLASS_DATA (sym)->attr.abstract;
7552 	}
7553       else
7554 	{
7555 	  allocatable = sym->attr.allocatable;
7556 	  pointer = sym->attr.pointer;
7557 	  dimension = sym->attr.dimension;
7558 	  codimension = sym->attr.codimension;
7559 	}
7560 
7561       coindexed = false;
7562 
7563       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
7564 	{
7565 	  switch (ref->type)
7566 	    {
7567  	      case REF_ARRAY:
7568                 if (ref->u.ar.codimen > 0)
7569 		  {
7570 		    int n;
7571 		    for (n = ref->u.ar.dimen;
7572 			 n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
7573 		      if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
7574 			{
7575 			  coindexed = true;
7576 			  break;
7577 			}
7578 		   }
7579 
7580 		if (ref->next != NULL)
7581 		  pointer = 0;
7582 		break;
7583 
7584 	      case REF_COMPONENT:
7585 		/* F2008, C644.  */
7586 		if (coindexed)
7587 		  {
7588 		    gfc_error ("Coindexed allocatable object at %L",
7589 			       &e->where);
7590 		    goto failure;
7591 		  }
7592 
7593 		c = ref->u.c.component;
7594 		if (c->ts.type == BT_CLASS)
7595 		  {
7596 		    allocatable = CLASS_DATA (c)->attr.allocatable;
7597 		    pointer = CLASS_DATA (c)->attr.class_pointer;
7598 		    dimension = CLASS_DATA (c)->attr.dimension;
7599 		    codimension = CLASS_DATA (c)->attr.codimension;
7600 		    is_abstract = CLASS_DATA (c)->attr.abstract;
7601 		  }
7602 		else
7603 		  {
7604 		    allocatable = c->attr.allocatable;
7605 		    pointer = c->attr.pointer;
7606 		    dimension = c->attr.dimension;
7607 		    codimension = c->attr.codimension;
7608 		    is_abstract = c->attr.abstract;
7609 		  }
7610 		break;
7611 
7612 	      case REF_SUBSTRING:
7613 	      case REF_INQUIRY:
7614 		allocatable = 0;
7615 		pointer = 0;
7616 		break;
7617 	    }
7618 	}
7619     }
7620 
7621   /* Check for F08:C628.  */
7622   if (allocatable == 0 && pointer == 0 && !unlimited)
7623     {
7624       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
7625 		 &e->where);
7626       goto failure;
7627     }
7628 
7629   /* Some checks for the SOURCE tag.  */
7630   if (code->expr3)
7631     {
7632       /* Check F03:C631.  */
7633       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
7634 	{
7635 	  gfc_error ("Type of entity at %L is type incompatible with "
7636 		     "source-expr at %L", &e->where, &code->expr3->where);
7637 	  goto failure;
7638 	}
7639 
7640       /* Check F03:C632 and restriction following Note 6.18.  */
7641       if (code->expr3->rank > 0 && !conformable_arrays (code->expr3, e))
7642 	goto failure;
7643 
7644       /* Check F03:C633.  */
7645       if (code->expr3->ts.kind != e->ts.kind && !unlimited)
7646 	{
7647 	  gfc_error ("The allocate-object at %L and the source-expr at %L "
7648 		     "shall have the same kind type parameter",
7649 		     &e->where, &code->expr3->where);
7650 	  goto failure;
7651 	}
7652 
7653       /* Check F2008, C642.  */
7654       if (code->expr3->ts.type == BT_DERIVED
7655 	  && ((codimension && gfc_expr_attr (code->expr3).lock_comp)
7656 	      || (code->expr3->ts.u.derived->from_intmod
7657 		     == INTMOD_ISO_FORTRAN_ENV
7658 		  && code->expr3->ts.u.derived->intmod_sym_id
7659 		     == ISOFORTRAN_LOCK_TYPE)))
7660 	{
7661 	  gfc_error ("The source-expr at %L shall neither be of type "
7662 		     "LOCK_TYPE nor have a LOCK_TYPE component if "
7663 		      "allocate-object at %L is a coarray",
7664 		      &code->expr3->where, &e->where);
7665 	  goto failure;
7666 	}
7667 
7668       /* Check TS18508, C702/C703.  */
7669       if (code->expr3->ts.type == BT_DERIVED
7670 	  && ((codimension && gfc_expr_attr (code->expr3).event_comp)
7671 	      || (code->expr3->ts.u.derived->from_intmod
7672 		     == INTMOD_ISO_FORTRAN_ENV
7673 		  && code->expr3->ts.u.derived->intmod_sym_id
7674 		     == ISOFORTRAN_EVENT_TYPE)))
7675 	{
7676 	  gfc_error ("The source-expr at %L shall neither be of type "
7677 		     "EVENT_TYPE nor have a EVENT_TYPE component if "
7678 		      "allocate-object at %L is a coarray",
7679 		      &code->expr3->where, &e->where);
7680 	  goto failure;
7681 	}
7682     }
7683 
7684   /* Check F08:C629.  */
7685   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
7686       && !code->expr3)
7687     {
7688       gcc_assert (e->ts.type == BT_CLASS);
7689       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
7690 		 "type-spec or source-expr", sym->name, &e->where);
7691       goto failure;
7692     }
7693 
7694   /* Check F08:C632.  */
7695   if (code->ext.alloc.ts.type == BT_CHARACTER && !e->ts.deferred
7696       && !UNLIMITED_POLY (e))
7697     {
7698       int cmp;
7699 
7700       if (!e->ts.u.cl->length)
7701 	goto failure;
7702 
7703       cmp = gfc_dep_compare_expr (e->ts.u.cl->length,
7704 				  code->ext.alloc.ts.u.cl->length);
7705       if (cmp == 1 || cmp == -1 || cmp == -3)
7706 	{
7707 	  gfc_error ("Allocating %s at %L with type-spec requires the same "
7708 		     "character-length parameter as in the declaration",
7709 		     sym->name, &e->where);
7710 	  goto failure;
7711 	}
7712     }
7713 
7714   /* In the variable definition context checks, gfc_expr_attr is used
7715      on the expression.  This is fooled by the array specification
7716      present in e, thus we have to eliminate that one temporarily.  */
7717   e2 = remove_last_array_ref (e);
7718   t = true;
7719   if (t && pointer)
7720     t = gfc_check_vardef_context (e2, true, true, false,
7721 				  _("ALLOCATE object"));
7722   if (t)
7723     t = gfc_check_vardef_context (e2, false, true, false,
7724 				  _("ALLOCATE object"));
7725   gfc_free_expr (e2);
7726   if (!t)
7727     goto failure;
7728 
7729   if (e->ts.type == BT_CLASS && CLASS_DATA (e)->attr.dimension
7730 	&& !code->expr3 && code->ext.alloc.ts.type == BT_DERIVED)
7731     {
7732       /* For class arrays, the initialization with SOURCE is done
7733 	 using _copy and trans_call. It is convenient to exploit that
7734 	 when the allocated type is different from the declared type but
7735 	 no SOURCE exists by setting expr3.  */
7736       code->expr3 = gfc_default_initializer (&code->ext.alloc.ts);
7737     }
7738   else if (flag_coarray != GFC_FCOARRAY_LIB && e->ts.type == BT_DERIVED
7739 	   && e->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
7740 	   && e->ts.u.derived->intmod_sym_id == ISOFORTRAN_EVENT_TYPE)
7741     {
7742       /* We have to zero initialize the integer variable.  */
7743       code->expr3 = gfc_get_int_expr (gfc_default_integer_kind, &e->where, 0);
7744     }
7745 
7746   if (e->ts.type == BT_CLASS && !unlimited && !UNLIMITED_POLY (code->expr3))
7747     {
7748       /* Make sure the vtab symbol is present when
7749 	 the module variables are generated.  */
7750       gfc_typespec ts = e->ts;
7751       if (code->expr3)
7752 	ts = code->expr3->ts;
7753       else if (code->ext.alloc.ts.type == BT_DERIVED)
7754 	ts = code->ext.alloc.ts;
7755 
7756       /* Finding the vtab also publishes the type's symbol.  Therefore this
7757 	 statement is necessary.  */
7758       gfc_find_derived_vtab (ts.u.derived);
7759     }
7760   else if (unlimited && !UNLIMITED_POLY (code->expr3))
7761     {
7762       /* Again, make sure the vtab symbol is present when
7763 	 the module variables are generated.  */
7764       gfc_typespec *ts = NULL;
7765       if (code->expr3)
7766 	ts = &code->expr3->ts;
7767       else
7768 	ts = &code->ext.alloc.ts;
7769 
7770       gcc_assert (ts);
7771 
7772       /* Finding the vtab also publishes the type's symbol.  Therefore this
7773 	 statement is necessary.  */
7774       gfc_find_vtab (ts);
7775     }
7776 
7777   if (dimension == 0 && codimension == 0)
7778     goto success;
7779 
7780   /* Make sure the last reference node is an array specification.  */
7781 
7782   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
7783       || (dimension && ref2->u.ar.dimen == 0))
7784     {
7785       /* F08:C633.  */
7786       if (code->expr3)
7787 	{
7788 	  if (!gfc_notify_std (GFC_STD_F2008, "Array specification required "
7789 			       "in ALLOCATE statement at %L", &e->where))
7790 	    goto failure;
7791 	  if (code->expr3->rank != 0)
7792 	    *array_alloc_wo_spec = true;
7793 	  else
7794 	    {
7795 	      gfc_error ("Array specification or array-valued SOURCE= "
7796 			 "expression required in ALLOCATE statement at %L",
7797 			 &e->where);
7798 	      goto failure;
7799 	    }
7800 	}
7801       else
7802 	{
7803 	  gfc_error ("Array specification required in ALLOCATE statement "
7804 		     "at %L", &e->where);
7805 	  goto failure;
7806 	}
7807     }
7808 
7809   /* Make sure that the array section reference makes sense in the
7810      context of an ALLOCATE specification.  */
7811 
7812   ar = &ref2->u.ar;
7813 
7814   if (codimension)
7815     for (i = ar->dimen; i < ar->dimen + ar->codimen; i++)
7816       {
7817 	switch (ar->dimen_type[i])
7818 	  {
7819 	  case DIMEN_THIS_IMAGE:
7820 	    gfc_error ("Coarray specification required in ALLOCATE statement "
7821 		       "at %L", &e->where);
7822 	    goto failure;
7823 
7824 	  case  DIMEN_RANGE:
7825 	    if (ar->start[i] == 0 || ar->end[i] == 0)
7826 	      {
7827 		/* If ar->stride[i] is NULL, we issued a previous error.  */
7828 		if (ar->stride[i] == NULL)
7829 		  gfc_error ("Bad array specification in ALLOCATE statement "
7830 			     "at %L", &e->where);
7831 		goto failure;
7832 	      }
7833 	    else if (gfc_dep_compare_expr (ar->start[i], ar->end[i]) == 1)
7834 	      {
7835 		gfc_error ("Upper cobound is less than lower cobound at %L",
7836 			   &ar->start[i]->where);
7837 		goto failure;
7838 	      }
7839 	    break;
7840 
7841 	  case DIMEN_ELEMENT:
7842 	    if (ar->start[i]->expr_type == EXPR_CONSTANT)
7843 	      {
7844 		gcc_assert (ar->start[i]->ts.type == BT_INTEGER);
7845 		if (mpz_cmp_si (ar->start[i]->value.integer, 1) < 0)
7846 		  {
7847 		    gfc_error ("Upper cobound is less than lower cobound "
7848 			       "of 1 at %L", &ar->start[i]->where);
7849 		    goto failure;
7850 		  }
7851 	      }
7852 	    break;
7853 
7854 	  case DIMEN_STAR:
7855 	    break;
7856 
7857 	  default:
7858 	    gfc_error ("Bad array specification in ALLOCATE statement at %L",
7859 		       &e->where);
7860 	    goto failure;
7861 
7862 	  }
7863       }
7864   for (i = 0; i < ar->dimen; i++)
7865     {
7866       if (ar->type == AR_ELEMENT || ar->type == AR_FULL)
7867 	goto check_symbols;
7868 
7869       switch (ar->dimen_type[i])
7870 	{
7871 	case DIMEN_ELEMENT:
7872 	  break;
7873 
7874 	case DIMEN_RANGE:
7875 	  if (ar->start[i] != NULL
7876 	      && ar->end[i] != NULL
7877 	      && ar->stride[i] == NULL)
7878 	    break;
7879 
7880 	  /* Fall through.  */
7881 
7882 	case DIMEN_UNKNOWN:
7883 	case DIMEN_VECTOR:
7884 	case DIMEN_STAR:
7885 	case DIMEN_THIS_IMAGE:
7886 	  gfc_error ("Bad array specification in ALLOCATE statement at %L",
7887 		     &e->where);
7888 	  goto failure;
7889 	}
7890 
7891 check_symbols:
7892       for (a = code->ext.alloc.list; a; a = a->next)
7893 	{
7894 	  sym = a->expr->symtree->n.sym;
7895 
7896 	  /* TODO - check derived type components.  */
7897 	  if (gfc_bt_struct (sym->ts.type) || sym->ts.type == BT_CLASS)
7898 	    continue;
7899 
7900 	  if ((ar->start[i] != NULL
7901 	       && gfc_find_sym_in_expr (sym, ar->start[i]))
7902 	      || (ar->end[i] != NULL
7903 		  && gfc_find_sym_in_expr (sym, ar->end[i])))
7904 	    {
7905 	      gfc_error ("%qs must not appear in the array specification at "
7906 			 "%L in the same ALLOCATE statement where it is "
7907 			 "itself allocated", sym->name, &ar->where);
7908 	      goto failure;
7909 	    }
7910 	}
7911     }
7912 
7913   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
7914     {
7915       if (ar->dimen_type[i] == DIMEN_ELEMENT
7916 	  || ar->dimen_type[i] == DIMEN_RANGE)
7917 	{
7918 	  if (i == (ar->dimen + ar->codimen - 1))
7919 	    {
7920 	      gfc_error ("Expected '*' in coindex specification in ALLOCATE "
7921 			 "statement at %L", &e->where);
7922 	      goto failure;
7923 	    }
7924 	  continue;
7925 	}
7926 
7927       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
7928 	  && ar->stride[i] == NULL)
7929 	break;
7930 
7931       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
7932 		 &e->where);
7933       goto failure;
7934     }
7935 
7936 success:
7937   return true;
7938 
7939 failure:
7940   return false;
7941 }
7942 
7943 
7944 static void
7945 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
7946 {
7947   gfc_expr *stat, *errmsg, *pe, *qe;
7948   gfc_alloc *a, *p, *q;
7949 
7950   stat = code->expr1;
7951   errmsg = code->expr2;
7952 
7953   /* Check the stat variable.  */
7954   if (stat)
7955     {
7956       gfc_check_vardef_context (stat, false, false, false,
7957 				_("STAT variable"));
7958 
7959       if ((stat->ts.type != BT_INTEGER
7960 	   && !(stat->ref && (stat->ref->type == REF_ARRAY
7961 			      || stat->ref->type == REF_COMPONENT)))
7962 	  || stat->rank > 0)
7963 	gfc_error ("Stat-variable at %L must be a scalar INTEGER "
7964 		   "variable", &stat->where);
7965 
7966       for (p = code->ext.alloc.list; p; p = p->next)
7967 	if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
7968 	  {
7969 	    gfc_ref *ref1, *ref2;
7970 	    bool found = true;
7971 
7972 	    for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
7973 		 ref1 = ref1->next, ref2 = ref2->next)
7974 	      {
7975 		if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7976 		  continue;
7977 		if (ref1->u.c.component->name != ref2->u.c.component->name)
7978 		  {
7979 		    found = false;
7980 		    break;
7981 		  }
7982 	      }
7983 
7984 	    if (found)
7985 	      {
7986 		gfc_error ("Stat-variable at %L shall not be %sd within "
7987 			   "the same %s statement", &stat->where, fcn, fcn);
7988 		break;
7989 	      }
7990 	  }
7991     }
7992 
7993   /* Check the errmsg variable.  */
7994   if (errmsg)
7995     {
7996       if (!stat)
7997 	gfc_warning (0, "ERRMSG at %L is useless without a STAT tag",
7998 		     &errmsg->where);
7999 
8000       gfc_check_vardef_context (errmsg, false, false, false,
8001 				_("ERRMSG variable"));
8002 
8003       /* F18:R928  alloc-opt             is ERRMSG = errmsg-variable
8004 	 F18:R930  errmsg-variable       is scalar-default-char-variable
8005 	 F18:R906  default-char-variable is variable
8006 	 F18:C906  default-char-variable shall be default character.  */
8007       if ((errmsg->ts.type != BT_CHARACTER
8008 	   && !(errmsg->ref
8009 		&& (errmsg->ref->type == REF_ARRAY
8010 		    || errmsg->ref->type == REF_COMPONENT)))
8011 	  || errmsg->rank > 0
8012 	  || errmsg->ts.kind != gfc_default_character_kind)
8013 	gfc_error ("ERRMSG variable at %L shall be a scalar default CHARACTER "
8014 		   "variable", &errmsg->where);
8015 
8016       for (p = code->ext.alloc.list; p; p = p->next)
8017 	if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
8018 	  {
8019 	    gfc_ref *ref1, *ref2;
8020 	    bool found = true;
8021 
8022 	    for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
8023 		 ref1 = ref1->next, ref2 = ref2->next)
8024 	      {
8025 		if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
8026 		  continue;
8027 		if (ref1->u.c.component->name != ref2->u.c.component->name)
8028 		  {
8029 		    found = false;
8030 		    break;
8031 		  }
8032 	      }
8033 
8034 	    if (found)
8035 	      {
8036 		gfc_error ("Errmsg-variable at %L shall not be %sd within "
8037 			   "the same %s statement", &errmsg->where, fcn, fcn);
8038 		break;
8039 	      }
8040 	  }
8041     }
8042 
8043   /* Check that an allocate-object appears only once in the statement.  */
8044 
8045   for (p = code->ext.alloc.list; p; p = p->next)
8046     {
8047       pe = p->expr;
8048       for (q = p->next; q; q = q->next)
8049 	{
8050 	  qe = q->expr;
8051 	  if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
8052 	    {
8053 	      /* This is a potential collision.  */
8054 	      gfc_ref *pr = pe->ref;
8055 	      gfc_ref *qr = qe->ref;
8056 
8057 	      /* Follow the references  until
8058 		 a) They start to differ, in which case there is no error;
8059 		 you can deallocate a%b and a%c in a single statement
8060 		 b) Both of them stop, which is an error
8061 		 c) One of them stops, which is also an error.  */
8062 	      while (1)
8063 		{
8064 		  if (pr == NULL && qr == NULL)
8065 		    {
8066 		      gfc_error ("Allocate-object at %L also appears at %L",
8067 				 &pe->where, &qe->where);
8068 		      break;
8069 		    }
8070 		  else if (pr != NULL && qr == NULL)
8071 		    {
8072 		      gfc_error ("Allocate-object at %L is subobject of"
8073 				 " object at %L", &pe->where, &qe->where);
8074 		      break;
8075 		    }
8076 		  else if (pr == NULL && qr != NULL)
8077 		    {
8078 		      gfc_error ("Allocate-object at %L is subobject of"
8079 				 " object at %L", &qe->where, &pe->where);
8080 		      break;
8081 		    }
8082 		  /* Here, pr != NULL && qr != NULL  */
8083 		  gcc_assert(pr->type == qr->type);
8084 		  if (pr->type == REF_ARRAY)
8085 		    {
8086 		      /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
8087 			 which are legal.  */
8088 		      gcc_assert (qr->type == REF_ARRAY);
8089 
8090 		      if (pr->next && qr->next)
8091 			{
8092 			  int i;
8093 			  gfc_array_ref *par = &(pr->u.ar);
8094 			  gfc_array_ref *qar = &(qr->u.ar);
8095 
8096 			  for (i=0; i<par->dimen; i++)
8097 			    {
8098 			      if ((par->start[i] != NULL
8099 				   || qar->start[i] != NULL)
8100 				  && gfc_dep_compare_expr (par->start[i],
8101 							   qar->start[i]) != 0)
8102 				goto break_label;
8103 			    }
8104 			}
8105 		    }
8106 		  else
8107 		    {
8108 		      if (pr->u.c.component->name != qr->u.c.component->name)
8109 			break;
8110 		    }
8111 
8112 		  pr = pr->next;
8113 		  qr = qr->next;
8114 		}
8115 	    break_label:
8116 	      ;
8117 	    }
8118 	}
8119     }
8120 
8121   if (strcmp (fcn, "ALLOCATE") == 0)
8122     {
8123       bool arr_alloc_wo_spec = false;
8124 
8125       /* Resolving the expr3 in the loop over all objects to allocate would
8126 	 execute loop invariant code for each loop item.  Therefore do it just
8127 	 once here.  */
8128       if (code->expr3 && code->expr3->mold
8129 	  && code->expr3->ts.type == BT_DERIVED)
8130 	{
8131 	  /* Default initialization via MOLD (non-polymorphic).  */
8132 	  gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
8133 	  if (rhs != NULL)
8134 	    {
8135 	      gfc_resolve_expr (rhs);
8136 	      gfc_free_expr (code->expr3);
8137 	      code->expr3 = rhs;
8138 	    }
8139 	}
8140       for (a = code->ext.alloc.list; a; a = a->next)
8141 	resolve_allocate_expr (a->expr, code, &arr_alloc_wo_spec);
8142 
8143       if (arr_alloc_wo_spec && code->expr3)
8144 	{
8145 	  /* Mark the allocate to have to take the array specification
8146 	     from the expr3.  */
8147 	  code->ext.alloc.arr_spec_from_expr3 = 1;
8148 	}
8149     }
8150   else
8151     {
8152       for (a = code->ext.alloc.list; a; a = a->next)
8153 	resolve_deallocate_expr (a->expr);
8154     }
8155 }
8156 
8157 
8158 /************ SELECT CASE resolution subroutines ************/
8159 
8160 /* Callback function for our mergesort variant.  Determines interval
8161    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
8162    op1 > op2.  Assumes we're not dealing with the default case.
8163    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
8164    There are nine situations to check.  */
8165 
8166 static int
8167 compare_cases (const gfc_case *op1, const gfc_case *op2)
8168 {
8169   int retval;
8170 
8171   if (op1->low == NULL) /* op1 = (:L)  */
8172     {
8173       /* op2 = (:N), so overlap.  */
8174       retval = 0;
8175       /* op2 = (M:) or (M:N),  L < M  */
8176       if (op2->low != NULL
8177 	  && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
8178 	retval = -1;
8179     }
8180   else if (op1->high == NULL) /* op1 = (K:)  */
8181     {
8182       /* op2 = (M:), so overlap.  */
8183       retval = 0;
8184       /* op2 = (:N) or (M:N), K > N  */
8185       if (op2->high != NULL
8186 	  && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
8187 	retval = 1;
8188     }
8189   else /* op1 = (K:L)  */
8190     {
8191       if (op2->low == NULL)       /* op2 = (:N), K > N  */
8192 	retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
8193 		 ? 1 : 0;
8194       else if (op2->high == NULL) /* op2 = (M:), L < M  */
8195 	retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
8196 		 ? -1 : 0;
8197       else			/* op2 = (M:N)  */
8198 	{
8199 	  retval =  0;
8200 	  /* L < M  */
8201 	  if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
8202 	    retval =  -1;
8203 	  /* K > N  */
8204 	  else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
8205 	    retval =  1;
8206 	}
8207     }
8208 
8209   return retval;
8210 }
8211 
8212 
8213 /* Merge-sort a double linked case list, detecting overlap in the
8214    process.  LIST is the head of the double linked case list before it
8215    is sorted.  Returns the head of the sorted list if we don't see any
8216    overlap, or NULL otherwise.  */
8217 
8218 static gfc_case *
8219 check_case_overlap (gfc_case *list)
8220 {
8221   gfc_case *p, *q, *e, *tail;
8222   int insize, nmerges, psize, qsize, cmp, overlap_seen;
8223 
8224   /* If the passed list was empty, return immediately.  */
8225   if (!list)
8226     return NULL;
8227 
8228   overlap_seen = 0;
8229   insize = 1;
8230 
8231   /* Loop unconditionally.  The only exit from this loop is a return
8232      statement, when we've finished sorting the case list.  */
8233   for (;;)
8234     {
8235       p = list;
8236       list = NULL;
8237       tail = NULL;
8238 
8239       /* Count the number of merges we do in this pass.  */
8240       nmerges = 0;
8241 
8242       /* Loop while there exists a merge to be done.  */
8243       while (p)
8244 	{
8245 	  int i;
8246 
8247 	  /* Count this merge.  */
8248 	  nmerges++;
8249 
8250 	  /* Cut the list in two pieces by stepping INSIZE places
8251 	     forward in the list, starting from P.  */
8252 	  psize = 0;
8253 	  q = p;
8254 	  for (i = 0; i < insize; i++)
8255 	    {
8256 	      psize++;
8257 	      q = q->right;
8258 	      if (!q)
8259 		break;
8260 	    }
8261 	  qsize = insize;
8262 
8263 	  /* Now we have two lists.  Merge them!  */
8264 	  while (psize > 0 || (qsize > 0 && q != NULL))
8265 	    {
8266 	      /* See from which the next case to merge comes from.  */
8267 	      if (psize == 0)
8268 		{
8269 		  /* P is empty so the next case must come from Q.  */
8270 		  e = q;
8271 		  q = q->right;
8272 		  qsize--;
8273 		}
8274 	      else if (qsize == 0 || q == NULL)
8275 		{
8276 		  /* Q is empty.  */
8277 		  e = p;
8278 		  p = p->right;
8279 		  psize--;
8280 		}
8281 	      else
8282 		{
8283 		  cmp = compare_cases (p, q);
8284 		  if (cmp < 0)
8285 		    {
8286 		      /* The whole case range for P is less than the
8287 			 one for Q.  */
8288 		      e = p;
8289 		      p = p->right;
8290 		      psize--;
8291 		    }
8292 		  else if (cmp > 0)
8293 		    {
8294 		      /* The whole case range for Q is greater than
8295 			 the case range for P.  */
8296 		      e = q;
8297 		      q = q->right;
8298 		      qsize--;
8299 		    }
8300 		  else
8301 		    {
8302 		      /* The cases overlap, or they are the same
8303 			 element in the list.  Either way, we must
8304 			 issue an error and get the next case from P.  */
8305 		      /* FIXME: Sort P and Q by line number.  */
8306 		      gfc_error ("CASE label at %L overlaps with CASE "
8307 				 "label at %L", &p->where, &q->where);
8308 		      overlap_seen = 1;
8309 		      e = p;
8310 		      p = p->right;
8311 		      psize--;
8312 		    }
8313 		}
8314 
8315 		/* Add the next element to the merged list.  */
8316 	      if (tail)
8317 		tail->right = e;
8318 	      else
8319 		list = e;
8320 	      e->left = tail;
8321 	      tail = e;
8322 	    }
8323 
8324 	  /* P has now stepped INSIZE places along, and so has Q.  So
8325 	     they're the same.  */
8326 	  p = q;
8327 	}
8328       tail->right = NULL;
8329 
8330       /* If we have done only one merge or none at all, we've
8331 	 finished sorting the cases.  */
8332       if (nmerges <= 1)
8333 	{
8334 	  if (!overlap_seen)
8335 	    return list;
8336 	  else
8337 	    return NULL;
8338 	}
8339 
8340       /* Otherwise repeat, merging lists twice the size.  */
8341       insize *= 2;
8342     }
8343 }
8344 
8345 
8346 /* Check to see if an expression is suitable for use in a CASE statement.
8347    Makes sure that all case expressions are scalar constants of the same
8348    type.  Return false if anything is wrong.  */
8349 
8350 static bool
8351 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
8352 {
8353   if (e == NULL) return true;
8354 
8355   if (e->ts.type != case_expr->ts.type)
8356     {
8357       gfc_error ("Expression in CASE statement at %L must be of type %s",
8358 		 &e->where, gfc_basic_typename (case_expr->ts.type));
8359       return false;
8360     }
8361 
8362   /* C805 (R808) For a given case-construct, each case-value shall be of
8363      the same type as case-expr.  For character type, length differences
8364      are allowed, but the kind type parameters shall be the same.  */
8365 
8366   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
8367     {
8368       gfc_error ("Expression in CASE statement at %L must be of kind %d",
8369 		 &e->where, case_expr->ts.kind);
8370       return false;
8371     }
8372 
8373   /* Convert the case value kind to that of case expression kind,
8374      if needed */
8375 
8376   if (e->ts.kind != case_expr->ts.kind)
8377     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
8378 
8379   if (e->rank != 0)
8380     {
8381       gfc_error ("Expression in CASE statement at %L must be scalar",
8382 		 &e->where);
8383       return false;
8384     }
8385 
8386   return true;
8387 }
8388 
8389 
8390 /* Given a completely parsed select statement, we:
8391 
8392      - Validate all expressions and code within the SELECT.
8393      - Make sure that the selection expression is not of the wrong type.
8394      - Make sure that no case ranges overlap.
8395      - Eliminate unreachable cases and unreachable code resulting from
8396        removing case labels.
8397 
8398    The standard does allow unreachable cases, e.g. CASE (5:3).  But
8399    they are a hassle for code generation, and to prevent that, we just
8400    cut them out here.  This is not necessary for overlapping cases
8401    because they are illegal and we never even try to generate code.
8402 
8403    We have the additional caveat that a SELECT construct could have
8404    been a computed GOTO in the source code. Fortunately we can fairly
8405    easily work around that here: The case_expr for a "real" SELECT CASE
8406    is in code->expr1, but for a computed GOTO it is in code->expr2. All
8407    we have to do is make sure that the case_expr is a scalar integer
8408    expression.  */
8409 
8410 static void
8411 resolve_select (gfc_code *code, bool select_type)
8412 {
8413   gfc_code *body;
8414   gfc_expr *case_expr;
8415   gfc_case *cp, *default_case, *tail, *head;
8416   int seen_unreachable;
8417   int seen_logical;
8418   int ncases;
8419   bt type;
8420   bool t;
8421 
8422   if (code->expr1 == NULL)
8423     {
8424       /* This was actually a computed GOTO statement.  */
8425       case_expr = code->expr2;
8426       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
8427 	gfc_error ("Selection expression in computed GOTO statement "
8428 		   "at %L must be a scalar integer expression",
8429 		   &case_expr->where);
8430 
8431       /* Further checking is not necessary because this SELECT was built
8432 	 by the compiler, so it should always be OK.  Just move the
8433 	 case_expr from expr2 to expr so that we can handle computed
8434 	 GOTOs as normal SELECTs from here on.  */
8435       code->expr1 = code->expr2;
8436       code->expr2 = NULL;
8437       return;
8438     }
8439 
8440   case_expr = code->expr1;
8441   type = case_expr->ts.type;
8442 
8443   /* F08:C830.  */
8444   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
8445     {
8446       gfc_error ("Argument of SELECT statement at %L cannot be %s",
8447 		 &case_expr->where, gfc_typename (&case_expr->ts));
8448 
8449       /* Punt. Going on here just produce more garbage error messages.  */
8450       return;
8451     }
8452 
8453   /* F08:R842.  */
8454   if (!select_type && case_expr->rank != 0)
8455     {
8456       gfc_error ("Argument of SELECT statement at %L must be a scalar "
8457 		 "expression", &case_expr->where);
8458 
8459       /* Punt.  */
8460       return;
8461     }
8462 
8463   /* Raise a warning if an INTEGER case value exceeds the range of
8464      the case-expr. Later, all expressions will be promoted to the
8465      largest kind of all case-labels.  */
8466 
8467   if (type == BT_INTEGER)
8468     for (body = code->block; body; body = body->block)
8469       for (cp = body->ext.block.case_list; cp; cp = cp->next)
8470 	{
8471 	  if (cp->low
8472 	      && gfc_check_integer_range (cp->low->value.integer,
8473 					  case_expr->ts.kind) != ARITH_OK)
8474 	    gfc_warning (0, "Expression in CASE statement at %L is "
8475 			 "not in the range of %s", &cp->low->where,
8476 			 gfc_typename (&case_expr->ts));
8477 
8478 	  if (cp->high
8479 	      && cp->low != cp->high
8480 	      && gfc_check_integer_range (cp->high->value.integer,
8481 					  case_expr->ts.kind) != ARITH_OK)
8482 	    gfc_warning (0, "Expression in CASE statement at %L is "
8483 			 "not in the range of %s", &cp->high->where,
8484 			 gfc_typename (&case_expr->ts));
8485 	}
8486 
8487   /* PR 19168 has a long discussion concerning a mismatch of the kinds
8488      of the SELECT CASE expression and its CASE values.  Walk the lists
8489      of case values, and if we find a mismatch, promote case_expr to
8490      the appropriate kind.  */
8491 
8492   if (type == BT_LOGICAL || type == BT_INTEGER)
8493     {
8494       for (body = code->block; body; body = body->block)
8495 	{
8496 	  /* Walk the case label list.  */
8497 	  for (cp = body->ext.block.case_list; cp; cp = cp->next)
8498 	    {
8499 	      /* Intercept the DEFAULT case.  It does not have a kind.  */
8500 	      if (cp->low == NULL && cp->high == NULL)
8501 		continue;
8502 
8503 	      /* Unreachable case ranges are discarded, so ignore.  */
8504 	      if (cp->low != NULL && cp->high != NULL
8505 		  && cp->low != cp->high
8506 		  && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
8507 		continue;
8508 
8509 	      if (cp->low != NULL
8510 		  && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
8511 		gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
8512 
8513 	      if (cp->high != NULL
8514 		  && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
8515 		gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
8516 	    }
8517 	 }
8518     }
8519 
8520   /* Assume there is no DEFAULT case.  */
8521   default_case = NULL;
8522   head = tail = NULL;
8523   ncases = 0;
8524   seen_logical = 0;
8525 
8526   for (body = code->block; body; body = body->block)
8527     {
8528       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
8529       t = true;
8530       seen_unreachable = 0;
8531 
8532       /* Walk the case label list, making sure that all case labels
8533 	 are legal.  */
8534       for (cp = body->ext.block.case_list; cp; cp = cp->next)
8535 	{
8536 	  /* Count the number of cases in the whole construct.  */
8537 	  ncases++;
8538 
8539 	  /* Intercept the DEFAULT case.  */
8540 	  if (cp->low == NULL && cp->high == NULL)
8541 	    {
8542 	      if (default_case != NULL)
8543 		{
8544 		  gfc_error ("The DEFAULT CASE at %L cannot be followed "
8545 			     "by a second DEFAULT CASE at %L",
8546 			     &default_case->where, &cp->where);
8547 		  t = false;
8548 		  break;
8549 		}
8550 	      else
8551 		{
8552 		  default_case = cp;
8553 		  continue;
8554 		}
8555 	    }
8556 
8557 	  /* Deal with single value cases and case ranges.  Errors are
8558 	     issued from the validation function.  */
8559 	  if (!validate_case_label_expr (cp->low, case_expr)
8560 	      || !validate_case_label_expr (cp->high, case_expr))
8561 	    {
8562 	      t = false;
8563 	      break;
8564 	    }
8565 
8566 	  if (type == BT_LOGICAL
8567 	      && ((cp->low == NULL || cp->high == NULL)
8568 		  || cp->low != cp->high))
8569 	    {
8570 	      gfc_error ("Logical range in CASE statement at %L is not "
8571 			 "allowed", &cp->low->where);
8572 	      t = false;
8573 	      break;
8574 	    }
8575 
8576 	  if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
8577 	    {
8578 	      int value;
8579 	      value = cp->low->value.logical == 0 ? 2 : 1;
8580 	      if (value & seen_logical)
8581 		{
8582 		  gfc_error ("Constant logical value in CASE statement "
8583 			     "is repeated at %L",
8584 			     &cp->low->where);
8585 		  t = false;
8586 		  break;
8587 		}
8588 	      seen_logical |= value;
8589 	    }
8590 
8591 	  if (cp->low != NULL && cp->high != NULL
8592 	      && cp->low != cp->high
8593 	      && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
8594 	    {
8595 	      if (warn_surprising)
8596 		gfc_warning (OPT_Wsurprising,
8597 			     "Range specification at %L can never be matched",
8598 			     &cp->where);
8599 
8600 	      cp->unreachable = 1;
8601 	      seen_unreachable = 1;
8602 	    }
8603 	  else
8604 	    {
8605 	      /* If the case range can be matched, it can also overlap with
8606 		 other cases.  To make sure it does not, we put it in a
8607 		 double linked list here.  We sort that with a merge sort
8608 		 later on to detect any overlapping cases.  */
8609 	      if (!head)
8610 		{
8611 		  head = tail = cp;
8612 		  head->right = head->left = NULL;
8613 		}
8614 	      else
8615 		{
8616 		  tail->right = cp;
8617 		  tail->right->left = tail;
8618 		  tail = tail->right;
8619 		  tail->right = NULL;
8620 		}
8621 	    }
8622 	}
8623 
8624       /* It there was a failure in the previous case label, give up
8625 	 for this case label list.  Continue with the next block.  */
8626       if (!t)
8627 	continue;
8628 
8629       /* See if any case labels that are unreachable have been seen.
8630 	 If so, we eliminate them.  This is a bit of a kludge because
8631 	 the case lists for a single case statement (label) is a
8632 	 single forward linked lists.  */
8633       if (seen_unreachable)
8634       {
8635 	/* Advance until the first case in the list is reachable.  */
8636 	while (body->ext.block.case_list != NULL
8637 	       && body->ext.block.case_list->unreachable)
8638 	  {
8639 	    gfc_case *n = body->ext.block.case_list;
8640 	    body->ext.block.case_list = body->ext.block.case_list->next;
8641 	    n->next = NULL;
8642 	    gfc_free_case_list (n);
8643 	  }
8644 
8645 	/* Strip all other unreachable cases.  */
8646 	if (body->ext.block.case_list)
8647 	  {
8648 	    for (cp = body->ext.block.case_list; cp && cp->next; cp = cp->next)
8649 	      {
8650 		if (cp->next->unreachable)
8651 		  {
8652 		    gfc_case *n = cp->next;
8653 		    cp->next = cp->next->next;
8654 		    n->next = NULL;
8655 		    gfc_free_case_list (n);
8656 		  }
8657 	      }
8658 	  }
8659       }
8660     }
8661 
8662   /* See if there were overlapping cases.  If the check returns NULL,
8663      there was overlap.  In that case we don't do anything.  If head
8664      is non-NULL, we prepend the DEFAULT case.  The sorted list can
8665      then used during code generation for SELECT CASE constructs with
8666      a case expression of a CHARACTER type.  */
8667   if (head)
8668     {
8669       head = check_case_overlap (head);
8670 
8671       /* Prepend the default_case if it is there.  */
8672       if (head != NULL && default_case)
8673 	{
8674 	  default_case->left = NULL;
8675 	  default_case->right = head;
8676 	  head->left = default_case;
8677 	}
8678     }
8679 
8680   /* Eliminate dead blocks that may be the result if we've seen
8681      unreachable case labels for a block.  */
8682   for (body = code; body && body->block; body = body->block)
8683     {
8684       if (body->block->ext.block.case_list == NULL)
8685 	{
8686 	  /* Cut the unreachable block from the code chain.  */
8687 	  gfc_code *c = body->block;
8688 	  body->block = c->block;
8689 
8690 	  /* Kill the dead block, but not the blocks below it.  */
8691 	  c->block = NULL;
8692 	  gfc_free_statements (c);
8693 	}
8694     }
8695 
8696   /* More than two cases is legal but insane for logical selects.
8697      Issue a warning for it.  */
8698   if (warn_surprising && type == BT_LOGICAL && ncases > 2)
8699     gfc_warning (OPT_Wsurprising,
8700 		 "Logical SELECT CASE block at %L has more that two cases",
8701 		 &code->loc);
8702 }
8703 
8704 
8705 /* Check if a derived type is extensible.  */
8706 
8707 bool
8708 gfc_type_is_extensible (gfc_symbol *sym)
8709 {
8710   return !(sym->attr.is_bind_c || sym->attr.sequence
8711 	   || (sym->attr.is_class
8712 	       && sym->components->ts.u.derived->attr.unlimited_polymorphic));
8713 }
8714 
8715 
8716 static void
8717 resolve_types (gfc_namespace *ns);
8718 
8719 /* Resolve an associate-name:  Resolve target and ensure the type-spec is
8720    correct as well as possibly the array-spec.  */
8721 
8722 static void
8723 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
8724 {
8725   gfc_expr* target;
8726 
8727   gcc_assert (sym->assoc);
8728   gcc_assert (sym->attr.flavor == FL_VARIABLE);
8729 
8730   /* If this is for SELECT TYPE, the target may not yet be set.  In that
8731      case, return.  Resolution will be called later manually again when
8732      this is done.  */
8733   target = sym->assoc->target;
8734   if (!target)
8735     return;
8736   gcc_assert (!sym->assoc->dangling);
8737 
8738   if (resolve_target && !gfc_resolve_expr (target))
8739     return;
8740 
8741   /* For variable targets, we get some attributes from the target.  */
8742   if (target->expr_type == EXPR_VARIABLE)
8743     {
8744       gfc_symbol* tsym;
8745 
8746       gcc_assert (target->symtree);
8747       tsym = target->symtree->n.sym;
8748 
8749       sym->attr.asynchronous = tsym->attr.asynchronous;
8750       sym->attr.volatile_ = tsym->attr.volatile_;
8751 
8752       sym->attr.target = tsym->attr.target
8753 			 || gfc_expr_attr (target).pointer;
8754       if (is_subref_array (target))
8755 	sym->attr.subref_array_pointer = 1;
8756     }
8757 
8758   if (target->expr_type == EXPR_NULL)
8759     {
8760       gfc_error ("Selector at %L cannot be NULL()", &target->where);
8761       return;
8762     }
8763   else if (target->ts.type == BT_UNKNOWN)
8764     {
8765       gfc_error ("Selector at %L has no type", &target->where);
8766       return;
8767     }
8768 
8769   /* Get type if this was not already set.  Note that it can be
8770      some other type than the target in case this is a SELECT TYPE
8771      selector!  So we must not update when the type is already there.  */
8772   if (sym->ts.type == BT_UNKNOWN)
8773     sym->ts = target->ts;
8774 
8775   gcc_assert (sym->ts.type != BT_UNKNOWN);
8776 
8777   /* See if this is a valid association-to-variable.  */
8778   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
8779 			  && !gfc_has_vector_subscript (target));
8780 
8781   /* Finally resolve if this is an array or not.  */
8782   if (sym->attr.dimension && target->rank == 0)
8783     {
8784       /* primary.c makes the assumption that a reference to an associate
8785 	 name followed by a left parenthesis is an array reference.  */
8786       if (sym->ts.type != BT_CHARACTER)
8787 	gfc_error ("Associate-name %qs at %L is used as array",
8788 		   sym->name, &sym->declared_at);
8789       sym->attr.dimension = 0;
8790       return;
8791     }
8792 
8793 
8794   /* We cannot deal with class selectors that need temporaries.  */
8795   if (target->ts.type == BT_CLASS
8796 	&& gfc_ref_needs_temporary_p (target->ref))
8797     {
8798       gfc_error ("CLASS selector at %L needs a temporary which is not "
8799 		 "yet implemented", &target->where);
8800       return;
8801     }
8802 
8803   if (target->ts.type == BT_CLASS)
8804     gfc_fix_class_refs (target);
8805 
8806   if (target->rank != 0)
8807     {
8808       gfc_array_spec *as;
8809       /* The rank may be incorrectly guessed at parsing, therefore make sure
8810 	 it is corrected now.  */
8811       if (sym->ts.type != BT_CLASS && (!sym->as || sym->assoc->rankguessed))
8812 	{
8813 	  if (!sym->as)
8814 	    sym->as = gfc_get_array_spec ();
8815 	  as = sym->as;
8816 	  as->rank = target->rank;
8817 	  as->type = AS_DEFERRED;
8818 	  as->corank = gfc_get_corank (target);
8819 	  sym->attr.dimension = 1;
8820 	  if (as->corank != 0)
8821 	    sym->attr.codimension = 1;
8822 	}
8823       else if (sym->ts.type == BT_CLASS && (!CLASS_DATA (sym)->as || sym->assoc->rankguessed))
8824 	{
8825 	  if (!CLASS_DATA (sym)->as)
8826 	    CLASS_DATA (sym)->as = gfc_get_array_spec ();
8827 	  as = CLASS_DATA (sym)->as;
8828 	  as->rank = target->rank;
8829 	  as->type = AS_DEFERRED;
8830 	  as->corank = gfc_get_corank (target);
8831 	  CLASS_DATA (sym)->attr.dimension = 1;
8832 	  if (as->corank != 0)
8833 	    CLASS_DATA (sym)->attr.codimension = 1;
8834 	}
8835     }
8836   else
8837     {
8838       /* target's rank is 0, but the type of the sym is still array valued,
8839 	 which has to be corrected.  */
8840       if (sym->ts.type == BT_CLASS
8841 	  && CLASS_DATA (sym) && CLASS_DATA (sym)->as)
8842 	{
8843 	  gfc_array_spec *as;
8844 	  symbol_attribute attr;
8845 	  /* The associated variable's type is still the array type
8846 	     correct this now.  */
8847 	  gfc_typespec *ts = &target->ts;
8848 	  gfc_ref *ref;
8849 	  gfc_component *c;
8850 	  for (ref = target->ref; ref != NULL; ref = ref->next)
8851 	    {
8852 	      switch (ref->type)
8853 		{
8854 		case REF_COMPONENT:
8855 		  ts = &ref->u.c.component->ts;
8856 		  break;
8857 		case REF_ARRAY:
8858 		  if (ts->type == BT_CLASS)
8859 		    ts = &ts->u.derived->components->ts;
8860 		  break;
8861 		default:
8862 		  break;
8863 		}
8864 	    }
8865 	  /* Create a scalar instance of the current class type.  Because the
8866 	     rank of a class array goes into its name, the type has to be
8867 	     rebuild.  The alternative of (re-)setting just the attributes
8868 	     and as in the current type, destroys the type also in other
8869 	     places.  */
8870 	  as = NULL;
8871 	  sym->ts = *ts;
8872 	  sym->ts.type = BT_CLASS;
8873 	  attr = CLASS_DATA (sym)->attr;
8874 	  attr.class_ok = 0;
8875 	  attr.associate_var = 1;
8876 	  attr.dimension = attr.codimension = 0;
8877 	  attr.class_pointer = 1;
8878 	  if (!gfc_build_class_symbol (&sym->ts, &attr, &as))
8879 	    gcc_unreachable ();
8880 	  /* Make sure the _vptr is set.  */
8881 	  c = gfc_find_component (sym->ts.u.derived, "_vptr", true, true, NULL);
8882 	  if (c->ts.u.derived == NULL)
8883 	    c->ts.u.derived = gfc_find_derived_vtab (sym->ts.u.derived);
8884 	  CLASS_DATA (sym)->attr.pointer = 1;
8885 	  CLASS_DATA (sym)->attr.class_pointer = 1;
8886 	  gfc_set_sym_referenced (sym->ts.u.derived);
8887 	  gfc_commit_symbol (sym->ts.u.derived);
8888 	  /* _vptr now has the _vtab in it, change it to the _vtype.  */
8889 	  if (c->ts.u.derived->attr.vtab)
8890 	    c->ts.u.derived = c->ts.u.derived->ts.u.derived;
8891 	  c->ts.u.derived->ns->types_resolved = 0;
8892 	  resolve_types (c->ts.u.derived->ns);
8893 	}
8894     }
8895 
8896   /* Mark this as an associate variable.  */
8897   sym->attr.associate_var = 1;
8898 
8899   /* Fix up the type-spec for CHARACTER types.  */
8900   if (sym->ts.type == BT_CHARACTER && !sym->attr.select_type_temporary)
8901     {
8902       if (!sym->ts.u.cl)
8903 	sym->ts.u.cl = target->ts.u.cl;
8904 
8905       if (sym->ts.deferred && target->expr_type == EXPR_VARIABLE
8906 	  && target->symtree->n.sym->attr.dummy
8907 	  && sym->ts.u.cl == target->ts.u.cl)
8908 	{
8909 	  sym->ts.u.cl = gfc_new_charlen (sym->ns, NULL);
8910 	  sym->ts.deferred = 1;
8911 	}
8912 
8913       if (!sym->ts.u.cl->length
8914 	  && !sym->ts.deferred
8915 	  && target->expr_type == EXPR_CONSTANT)
8916 	{
8917 	  sym->ts.u.cl->length =
8918 		gfc_get_int_expr (gfc_charlen_int_kind, NULL,
8919 				  target->value.character.length);
8920 	}
8921       else if ((!sym->ts.u.cl->length
8922 		|| sym->ts.u.cl->length->expr_type != EXPR_CONSTANT)
8923 		&& target->expr_type != EXPR_VARIABLE)
8924 	{
8925 	  sym->ts.u.cl = gfc_new_charlen (sym->ns, NULL);
8926 	  sym->ts.deferred = 1;
8927 
8928 	  /* This is reset in trans-stmt.c after the assignment
8929 	     of the target expression to the associate name.  */
8930 	  sym->attr.allocatable = 1;
8931 	}
8932     }
8933 
8934   /* If the target is a good class object, so is the associate variable.  */
8935   if (sym->ts.type == BT_CLASS && gfc_expr_attr (target).class_ok)
8936     sym->attr.class_ok = 1;
8937 }
8938 
8939 
8940 /* Ensure that SELECT TYPE expressions have the correct rank and a full
8941    array reference, where necessary.  The symbols are artificial and so
8942    the dimension attribute and arrayspec can also be set.  In addition,
8943    sometimes the expr1 arrives as BT_DERIVED, when the symbol is BT_CLASS.
8944    This is corrected here as well.*/
8945 
8946 static void
8947 fixup_array_ref (gfc_expr **expr1, gfc_expr *expr2,
8948 		 int rank, gfc_ref *ref)
8949 {
8950   gfc_ref *nref = (*expr1)->ref;
8951   gfc_symbol *sym1 = (*expr1)->symtree->n.sym;
8952   gfc_symbol *sym2 = expr2 ? expr2->symtree->n.sym : NULL;
8953   (*expr1)->rank = rank;
8954   if (sym1->ts.type == BT_CLASS)
8955     {
8956       if ((*expr1)->ts.type != BT_CLASS)
8957 	(*expr1)->ts = sym1->ts;
8958 
8959       CLASS_DATA (sym1)->attr.dimension = 1;
8960       if (CLASS_DATA (sym1)->as == NULL && sym2)
8961 	CLASS_DATA (sym1)->as
8962 		= gfc_copy_array_spec (CLASS_DATA (sym2)->as);
8963     }
8964   else
8965     {
8966       sym1->attr.dimension = 1;
8967       if (sym1->as == NULL && sym2)
8968 	sym1->as = gfc_copy_array_spec (sym2->as);
8969     }
8970 
8971   for (; nref; nref = nref->next)
8972     if (nref->next == NULL)
8973       break;
8974 
8975   if (ref && nref && nref->type != REF_ARRAY)
8976     nref->next = gfc_copy_ref (ref);
8977   else if (ref && !nref)
8978     (*expr1)->ref = gfc_copy_ref (ref);
8979 }
8980 
8981 
8982 static gfc_expr *
8983 build_loc_call (gfc_expr *sym_expr)
8984 {
8985   gfc_expr *loc_call;
8986   loc_call = gfc_get_expr ();
8987   loc_call->expr_type = EXPR_FUNCTION;
8988   gfc_get_sym_tree ("_loc", gfc_current_ns, &loc_call->symtree, false);
8989   loc_call->symtree->n.sym->attr.flavor = FL_PROCEDURE;
8990   loc_call->symtree->n.sym->attr.intrinsic = 1;
8991   loc_call->symtree->n.sym->result = loc_call->symtree->n.sym;
8992   gfc_commit_symbol (loc_call->symtree->n.sym);
8993   loc_call->ts.type = BT_INTEGER;
8994   loc_call->ts.kind = gfc_index_integer_kind;
8995   loc_call->value.function.isym = gfc_intrinsic_function_by_id (GFC_ISYM_LOC);
8996   loc_call->value.function.actual = gfc_get_actual_arglist ();
8997   loc_call->value.function.actual->expr = sym_expr;
8998   loc_call->where = sym_expr->where;
8999   return loc_call;
9000 }
9001 
9002 /* Resolve a SELECT TYPE statement.  */
9003 
9004 static void
9005 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
9006 {
9007   gfc_symbol *selector_type;
9008   gfc_code *body, *new_st, *if_st, *tail;
9009   gfc_code *class_is = NULL, *default_case = NULL;
9010   gfc_case *c;
9011   gfc_symtree *st;
9012   char name[GFC_MAX_SYMBOL_LEN];
9013   gfc_namespace *ns;
9014   int error = 0;
9015   int rank = 0;
9016   gfc_ref* ref = NULL;
9017   gfc_expr *selector_expr = NULL;
9018 
9019   ns = code->ext.block.ns;
9020   gfc_resolve (ns);
9021 
9022   /* Check for F03:C813.  */
9023   if (code->expr1->ts.type != BT_CLASS
9024       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
9025     {
9026       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
9027 		 "at %L", &code->loc);
9028       return;
9029     }
9030 
9031   if (!code->expr1->symtree->n.sym->attr.class_ok)
9032     return;
9033 
9034   if (code->expr2)
9035     {
9036       gfc_ref *ref2 = NULL;
9037       for (ref = code->expr2->ref; ref != NULL; ref = ref->next)
9038 	 if (ref->type == REF_COMPONENT
9039 	     && ref->u.c.component->ts.type == BT_CLASS)
9040 	   ref2 = ref;
9041 
9042       if (ref2)
9043 	{
9044 	  if (code->expr1->symtree->n.sym->attr.untyped)
9045 	    code->expr1->symtree->n.sym->ts = ref2->u.c.component->ts;
9046 	  selector_type = CLASS_DATA (ref2->u.c.component)->ts.u.derived;
9047 	}
9048       else
9049 	{
9050 	  if (code->expr1->symtree->n.sym->attr.untyped)
9051 	    code->expr1->symtree->n.sym->ts = code->expr2->ts;
9052 	  selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
9053 	}
9054 
9055       if (code->expr2->rank && CLASS_DATA (code->expr1)->as)
9056 	CLASS_DATA (code->expr1)->as->rank = code->expr2->rank;
9057 
9058       /* F2008: C803 The selector expression must not be coindexed.  */
9059       if (gfc_is_coindexed (code->expr2))
9060 	{
9061 	  gfc_error ("Selector at %L must not be coindexed",
9062 		     &code->expr2->where);
9063 	  return;
9064 	}
9065 
9066     }
9067   else
9068     {
9069       selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
9070 
9071       if (gfc_is_coindexed (code->expr1))
9072 	{
9073 	  gfc_error ("Selector at %L must not be coindexed",
9074 		     &code->expr1->where);
9075 	  return;
9076 	}
9077     }
9078 
9079   /* Loop over TYPE IS / CLASS IS cases.  */
9080   for (body = code->block; body; body = body->block)
9081     {
9082       c = body->ext.block.case_list;
9083 
9084       if (!error)
9085 	{
9086 	  /* Check for repeated cases.  */
9087 	  for (tail = code->block; tail; tail = tail->block)
9088 	    {
9089 	      gfc_case *d = tail->ext.block.case_list;
9090 	      if (tail == body)
9091 		break;
9092 
9093 	      if (c->ts.type == d->ts.type
9094 		  && ((c->ts.type == BT_DERIVED
9095 		       && c->ts.u.derived && d->ts.u.derived
9096 		       && !strcmp (c->ts.u.derived->name,
9097 				   d->ts.u.derived->name))
9098 		      || c->ts.type == BT_UNKNOWN
9099 		      || (!(c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
9100 			  && c->ts.kind == d->ts.kind)))
9101 		{
9102 		  gfc_error ("TYPE IS at %L overlaps with TYPE IS at %L",
9103 			     &c->where, &d->where);
9104 		  return;
9105 		}
9106 	    }
9107 	}
9108 
9109       /* Check F03:C815.  */
9110       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
9111 	  && !selector_type->attr.unlimited_polymorphic
9112 	  && !gfc_type_is_extensible (c->ts.u.derived))
9113 	{
9114 	  gfc_error ("Derived type %qs at %L must be extensible",
9115 		     c->ts.u.derived->name, &c->where);
9116 	  error++;
9117 	  continue;
9118 	}
9119 
9120       /* Check F03:C816.  */
9121       if (c->ts.type != BT_UNKNOWN && !selector_type->attr.unlimited_polymorphic
9122 	  && ((c->ts.type != BT_DERIVED && c->ts.type != BT_CLASS)
9123 	      || !gfc_type_is_extension_of (selector_type, c->ts.u.derived)))
9124 	{
9125 	  if (c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
9126 	    gfc_error ("Derived type %qs at %L must be an extension of %qs",
9127 		       c->ts.u.derived->name, &c->where, selector_type->name);
9128 	  else
9129 	    gfc_error ("Unexpected intrinsic type %qs at %L",
9130 		       gfc_basic_typename (c->ts.type), &c->where);
9131 	  error++;
9132 	  continue;
9133 	}
9134 
9135       /* Check F03:C814.  */
9136       if (c->ts.type == BT_CHARACTER
9137 	  && (c->ts.u.cl->length != NULL || c->ts.deferred))
9138 	{
9139 	  gfc_error ("The type-spec at %L shall specify that each length "
9140 		     "type parameter is assumed", &c->where);
9141 	  error++;
9142 	  continue;
9143 	}
9144 
9145       /* Intercept the DEFAULT case.  */
9146       if (c->ts.type == BT_UNKNOWN)
9147 	{
9148 	  /* Check F03:C818.  */
9149 	  if (default_case)
9150 	    {
9151 	      gfc_error ("The DEFAULT CASE at %L cannot be followed "
9152 			 "by a second DEFAULT CASE at %L",
9153 			 &default_case->ext.block.case_list->where, &c->where);
9154 	      error++;
9155 	      continue;
9156 	    }
9157 
9158 	  default_case = body;
9159 	}
9160     }
9161 
9162   if (error > 0)
9163     return;
9164 
9165   /* Transform SELECT TYPE statement to BLOCK and associate selector to
9166      target if present.  If there are any EXIT statements referring to the
9167      SELECT TYPE construct, this is no problem because the gfc_code
9168      reference stays the same and EXIT is equally possible from the BLOCK
9169      it is changed to.  */
9170   code->op = EXEC_BLOCK;
9171   if (code->expr2)
9172     {
9173       gfc_association_list* assoc;
9174 
9175       assoc = gfc_get_association_list ();
9176       assoc->st = code->expr1->symtree;
9177       assoc->target = gfc_copy_expr (code->expr2);
9178       assoc->target->where = code->expr2->where;
9179       /* assoc->variable will be set by resolve_assoc_var.  */
9180 
9181       code->ext.block.assoc = assoc;
9182       code->expr1->symtree->n.sym->assoc = assoc;
9183 
9184       resolve_assoc_var (code->expr1->symtree->n.sym, false);
9185     }
9186   else
9187     code->ext.block.assoc = NULL;
9188 
9189   /* Ensure that the selector rank and arrayspec are available to
9190      correct expressions in which they might be missing.  */
9191   if (code->expr2 && code->expr2->rank)
9192     {
9193       rank = code->expr2->rank;
9194       for (ref = code->expr2->ref; ref; ref = ref->next)
9195 	if (ref->next == NULL)
9196 	  break;
9197       if (ref && ref->type == REF_ARRAY)
9198 	ref = gfc_copy_ref (ref);
9199 
9200       /* Fixup expr1 if necessary.  */
9201       if (rank)
9202 	fixup_array_ref (&code->expr1, code->expr2, rank, ref);
9203     }
9204   else if (code->expr1->rank)
9205     {
9206       rank = code->expr1->rank;
9207       for (ref = code->expr1->ref; ref; ref = ref->next)
9208 	if (ref->next == NULL)
9209 	  break;
9210       if (ref && ref->type == REF_ARRAY)
9211 	ref = gfc_copy_ref (ref);
9212     }
9213 
9214   /* Add EXEC_SELECT to switch on type.  */
9215   new_st = gfc_get_code (code->op);
9216   new_st->expr1 = code->expr1;
9217   new_st->expr2 = code->expr2;
9218   new_st->block = code->block;
9219   code->expr1 = code->expr2 =  NULL;
9220   code->block = NULL;
9221   if (!ns->code)
9222     ns->code = new_st;
9223   else
9224     ns->code->next = new_st;
9225   code = new_st;
9226   code->op = EXEC_SELECT_TYPE;
9227 
9228   /* Use the intrinsic LOC function to generate an integer expression
9229      for the vtable of the selector.  Note that the rank of the selector
9230      expression has to be set to zero.  */
9231   gfc_add_vptr_component (code->expr1);
9232   code->expr1->rank = 0;
9233   code->expr1 = build_loc_call (code->expr1);
9234   selector_expr = code->expr1->value.function.actual->expr;
9235 
9236   /* Loop over TYPE IS / CLASS IS cases.  */
9237   for (body = code->block; body; body = body->block)
9238     {
9239       gfc_symbol *vtab;
9240       gfc_expr *e;
9241       c = body->ext.block.case_list;
9242 
9243       /* Generate an index integer expression for address of the
9244 	 TYPE/CLASS vtable and store it in c->low.  The hash expression
9245 	 is stored in c->high and is used to resolve intrinsic cases.  */
9246       if (c->ts.type != BT_UNKNOWN)
9247 	{
9248 	  if (c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
9249 	    {
9250 	      vtab = gfc_find_derived_vtab (c->ts.u.derived);
9251 	      gcc_assert (vtab);
9252 	      c->high = gfc_get_int_expr (gfc_integer_4_kind, NULL,
9253 					  c->ts.u.derived->hash_value);
9254 	    }
9255 	  else
9256 	    {
9257 	      vtab = gfc_find_vtab (&c->ts);
9258 	      gcc_assert (vtab && CLASS_DATA (vtab)->initializer);
9259 	      e = CLASS_DATA (vtab)->initializer;
9260 	      c->high = gfc_copy_expr (e);
9261 	      if (c->high->ts.kind != gfc_integer_4_kind)
9262 		{
9263 		  gfc_typespec ts;
9264 		  ts.kind = gfc_integer_4_kind;
9265 		  ts.type = BT_INTEGER;
9266 		  gfc_convert_type_warn (c->high, &ts, 2, 0);
9267 		}
9268 	    }
9269 
9270 	  e = gfc_lval_expr_from_sym (vtab);
9271 	  c->low = build_loc_call (e);
9272 	}
9273       else
9274 	continue;
9275 
9276       /* Associate temporary to selector.  This should only be done
9277 	 when this case is actually true, so build a new ASSOCIATE
9278 	 that does precisely this here (instead of using the
9279 	 'global' one).  */
9280 
9281       if (c->ts.type == BT_CLASS)
9282 	sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
9283       else if (c->ts.type == BT_DERIVED)
9284 	sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
9285       else if (c->ts.type == BT_CHARACTER)
9286 	{
9287 	  HOST_WIDE_INT charlen = 0;
9288 	  if (c->ts.u.cl && c->ts.u.cl->length
9289 	      && c->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9290 	    charlen = gfc_mpz_get_hwi (c->ts.u.cl->length->value.integer);
9291 	  snprintf (name, sizeof (name),
9292 		    "__tmp_%s_" HOST_WIDE_INT_PRINT_DEC "_%d",
9293 		    gfc_basic_typename (c->ts.type), charlen, c->ts.kind);
9294 	}
9295       else
9296 	sprintf (name, "__tmp_%s_%d", gfc_basic_typename (c->ts.type),
9297 	         c->ts.kind);
9298 
9299       st = gfc_find_symtree (ns->sym_root, name);
9300       gcc_assert (st->n.sym->assoc);
9301       st->n.sym->assoc->target = gfc_get_variable_expr (selector_expr->symtree);
9302       st->n.sym->assoc->target->where = selector_expr->where;
9303       if (c->ts.type != BT_CLASS && c->ts.type != BT_UNKNOWN)
9304 	{
9305 	  gfc_add_data_component (st->n.sym->assoc->target);
9306 	  /* Fixup the target expression if necessary.  */
9307 	  if (rank)
9308 	    fixup_array_ref (&st->n.sym->assoc->target, NULL, rank, ref);
9309 	}
9310 
9311       new_st = gfc_get_code (EXEC_BLOCK);
9312       new_st->ext.block.ns = gfc_build_block_ns (ns);
9313       new_st->ext.block.ns->code = body->next;
9314       body->next = new_st;
9315 
9316       /* Chain in the new list only if it is marked as dangling.  Otherwise
9317 	 there is a CASE label overlap and this is already used.  Just ignore,
9318 	 the error is diagnosed elsewhere.  */
9319       if (st->n.sym->assoc->dangling)
9320 	{
9321 	  new_st->ext.block.assoc = st->n.sym->assoc;
9322 	  st->n.sym->assoc->dangling = 0;
9323 	}
9324 
9325       resolve_assoc_var (st->n.sym, false);
9326     }
9327 
9328   /* Take out CLASS IS cases for separate treatment.  */
9329   body = code;
9330   while (body && body->block)
9331     {
9332       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
9333 	{
9334 	  /* Add to class_is list.  */
9335 	  if (class_is == NULL)
9336 	    {
9337 	      class_is = body->block;
9338 	      tail = class_is;
9339 	    }
9340 	  else
9341 	    {
9342 	      for (tail = class_is; tail->block; tail = tail->block) ;
9343 	      tail->block = body->block;
9344 	      tail = tail->block;
9345 	    }
9346 	  /* Remove from EXEC_SELECT list.  */
9347 	  body->block = body->block->block;
9348 	  tail->block = NULL;
9349 	}
9350       else
9351 	body = body->block;
9352     }
9353 
9354   if (class_is)
9355     {
9356       gfc_symbol *vtab;
9357 
9358       if (!default_case)
9359 	{
9360 	  /* Add a default case to hold the CLASS IS cases.  */
9361 	  for (tail = code; tail->block; tail = tail->block) ;
9362 	  tail->block = gfc_get_code (EXEC_SELECT_TYPE);
9363 	  tail = tail->block;
9364 	  tail->ext.block.case_list = gfc_get_case ();
9365 	  tail->ext.block.case_list->ts.type = BT_UNKNOWN;
9366 	  tail->next = NULL;
9367 	  default_case = tail;
9368 	}
9369 
9370       /* More than one CLASS IS block?  */
9371       if (class_is->block)
9372 	{
9373 	  gfc_code **c1,*c2;
9374 	  bool swapped;
9375 	  /* Sort CLASS IS blocks by extension level.  */
9376 	  do
9377 	    {
9378 	      swapped = false;
9379 	      for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
9380 		{
9381 		  c2 = (*c1)->block;
9382 		  /* F03:C817 (check for doubles).  */
9383 		  if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
9384 		      == c2->ext.block.case_list->ts.u.derived->hash_value)
9385 		    {
9386 		      gfc_error ("Double CLASS IS block in SELECT TYPE "
9387 				 "statement at %L",
9388 				 &c2->ext.block.case_list->where);
9389 		      return;
9390 		    }
9391 		  if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
9392 		      < c2->ext.block.case_list->ts.u.derived->attr.extension)
9393 		    {
9394 		      /* Swap.  */
9395 		      (*c1)->block = c2->block;
9396 		      c2->block = *c1;
9397 		      *c1 = c2;
9398 		      swapped = true;
9399 		    }
9400 		}
9401 	    }
9402 	  while (swapped);
9403 	}
9404 
9405       /* Generate IF chain.  */
9406       if_st = gfc_get_code (EXEC_IF);
9407       new_st = if_st;
9408       for (body = class_is; body; body = body->block)
9409 	{
9410 	  new_st->block = gfc_get_code (EXEC_IF);
9411 	  new_st = new_st->block;
9412 	  /* Set up IF condition: Call _gfortran_is_extension_of.  */
9413 	  new_st->expr1 = gfc_get_expr ();
9414 	  new_st->expr1->expr_type = EXPR_FUNCTION;
9415 	  new_st->expr1->ts.type = BT_LOGICAL;
9416 	  new_st->expr1->ts.kind = 4;
9417 	  new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
9418 	  new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
9419 	  new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
9420 	  /* Set up arguments.  */
9421 	  new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
9422 	  new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (selector_expr->symtree);
9423 	  new_st->expr1->value.function.actual->expr->where = code->loc;
9424 	  new_st->expr1->where = code->loc;
9425 	  gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
9426 	  vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
9427 	  st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
9428 	  new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
9429 	  new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
9430 	  new_st->expr1->value.function.actual->next->expr->where = code->loc;
9431 	  new_st->next = body->next;
9432 	}
9433 	if (default_case->next)
9434 	  {
9435 	    new_st->block = gfc_get_code (EXEC_IF);
9436 	    new_st = new_st->block;
9437 	    new_st->next = default_case->next;
9438 	  }
9439 
9440 	/* Replace CLASS DEFAULT code by the IF chain.  */
9441 	default_case->next = if_st;
9442     }
9443 
9444   /* Resolve the internal code.  This cannot be done earlier because
9445      it requires that the sym->assoc of selectors is set already.  */
9446   gfc_current_ns = ns;
9447   gfc_resolve_blocks (code->block, gfc_current_ns);
9448   gfc_current_ns = old_ns;
9449 
9450   if (ref)
9451     free (ref);
9452 }
9453 
9454 
9455 /* Resolve a transfer statement. This is making sure that:
9456    -- a derived type being transferred has only non-pointer components
9457    -- a derived type being transferred doesn't have private components, unless
9458       it's being transferred from the module where the type was defined
9459    -- we're not trying to transfer a whole assumed size array.  */
9460 
9461 static void
9462 resolve_transfer (gfc_code *code)
9463 {
9464   gfc_symbol *sym, *derived;
9465   gfc_ref *ref;
9466   gfc_expr *exp;
9467   bool write = false;
9468   bool formatted = false;
9469   gfc_dt *dt = code->ext.dt;
9470   gfc_symbol *dtio_sub = NULL;
9471 
9472   exp = code->expr1;
9473 
9474   while (exp != NULL && exp->expr_type == EXPR_OP
9475 	 && exp->value.op.op == INTRINSIC_PARENTHESES)
9476     exp = exp->value.op.op1;
9477 
9478   if (exp && exp->expr_type == EXPR_NULL
9479       && code->ext.dt)
9480     {
9481       gfc_error ("Invalid context for NULL () intrinsic at %L",
9482 		 &exp->where);
9483       return;
9484     }
9485 
9486   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
9487 		      && exp->expr_type != EXPR_FUNCTION
9488 		      && exp->expr_type != EXPR_STRUCTURE))
9489     return;
9490 
9491   /* If we are reading, the variable will be changed.  Note that
9492      code->ext.dt may be NULL if the TRANSFER is related to
9493      an INQUIRE statement -- but in this case, we are not reading, either.  */
9494   if (dt && dt->dt_io_kind->value.iokind == M_READ
9495       && !gfc_check_vardef_context (exp, false, false, false,
9496 				    _("item in READ")))
9497     return;
9498 
9499   const gfc_typespec *ts = exp->expr_type == EXPR_STRUCTURE
9500 			|| exp->expr_type == EXPR_FUNCTION
9501 			 ? &exp->ts : &exp->symtree->n.sym->ts;
9502 
9503   /* Go to actual component transferred.  */
9504   for (ref = exp->ref; ref; ref = ref->next)
9505     if (ref->type == REF_COMPONENT)
9506       ts = &ref->u.c.component->ts;
9507 
9508   if (dt && dt->dt_io_kind->value.iokind != M_INQUIRE
9509       && (ts->type == BT_DERIVED || ts->type == BT_CLASS))
9510     {
9511       derived = ts->u.derived;
9512 
9513       /* Determine when to use the formatted DTIO procedure.  */
9514       if (dt && (dt->format_expr || dt->format_label))
9515 	formatted = true;
9516 
9517       write = dt->dt_io_kind->value.iokind == M_WRITE
9518 	      || dt->dt_io_kind->value.iokind == M_PRINT;
9519       dtio_sub = gfc_find_specific_dtio_proc (derived, write, formatted);
9520 
9521       if (dtio_sub != NULL && exp->expr_type == EXPR_VARIABLE)
9522 	{
9523 	  dt->udtio = exp;
9524 	  sym = exp->symtree->n.sym->ns->proc_name;
9525 	  /* Check to see if this is a nested DTIO call, with the
9526 	     dummy as the io-list object.  */
9527 	  if (sym && sym == dtio_sub && sym->formal
9528 	      && sym->formal->sym == exp->symtree->n.sym
9529 	      && exp->ref == NULL)
9530 	    {
9531 	      if (!sym->attr.recursive)
9532 		{
9533 		  gfc_error ("DTIO %s procedure at %L must be recursive",
9534 			     sym->name, &sym->declared_at);
9535 		  return;
9536 		}
9537 	    }
9538 	}
9539     }
9540 
9541   if (ts->type == BT_CLASS && dtio_sub == NULL)
9542     {
9543       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
9544                 "it is processed by a defined input/output procedure",
9545                 &code->loc);
9546       return;
9547     }
9548 
9549   if (ts->type == BT_DERIVED)
9550     {
9551       /* Check that transferred derived type doesn't contain POINTER
9552 	 components unless it is processed by a defined input/output
9553 	 procedure".  */
9554       if (ts->u.derived->attr.pointer_comp && dtio_sub == NULL)
9555 	{
9556 	  gfc_error ("Data transfer element at %L cannot have POINTER "
9557 		     "components unless it is processed by a defined "
9558 		     "input/output procedure", &code->loc);
9559 	  return;
9560 	}
9561 
9562       /* F08:C935.  */
9563       if (ts->u.derived->attr.proc_pointer_comp)
9564 	{
9565 	  gfc_error ("Data transfer element at %L cannot have "
9566 		     "procedure pointer components", &code->loc);
9567 	  return;
9568 	}
9569 
9570       if (ts->u.derived->attr.alloc_comp && dtio_sub == NULL)
9571 	{
9572 	  gfc_error ("Data transfer element at %L cannot have ALLOCATABLE "
9573 		     "components unless it is processed by a defined "
9574 		     "input/output procedure", &code->loc);
9575 	  return;
9576 	}
9577 
9578       /* C_PTR and C_FUNPTR have private components which means they cannot
9579          be printed.  However, if -std=gnu and not -pedantic, allow
9580          the component to be printed to help debugging.  */
9581       if (ts->u.derived->ts.f90_type == BT_VOID)
9582 	{
9583 	  if (!gfc_notify_std (GFC_STD_GNU, "Data transfer element at %L "
9584 			       "cannot have PRIVATE components", &code->loc))
9585 	    return;
9586 	}
9587       else if (derived_inaccessible (ts->u.derived) && dtio_sub == NULL)
9588 	{
9589 	  gfc_error ("Data transfer element at %L cannot have "
9590 		     "PRIVATE components unless it is processed by "
9591 		     "a defined input/output procedure", &code->loc);
9592 	  return;
9593 	}
9594     }
9595 
9596   if (exp->expr_type == EXPR_STRUCTURE)
9597     return;
9598 
9599   sym = exp->symtree->n.sym;
9600 
9601   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE && exp->ref
9602       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
9603     {
9604       gfc_error ("Data transfer element at %L cannot be a full reference to "
9605 		 "an assumed-size array", &code->loc);
9606       return;
9607     }
9608 
9609   if (async_io_dt && exp->expr_type == EXPR_VARIABLE)
9610     exp->symtree->n.sym->attr.asynchronous = 1;
9611 }
9612 
9613 
9614 /*********** Toplevel code resolution subroutines ***********/
9615 
9616 /* Find the set of labels that are reachable from this block.  We also
9617    record the last statement in each block.  */
9618 
9619 static void
9620 find_reachable_labels (gfc_code *block)
9621 {
9622   gfc_code *c;
9623 
9624   if (!block)
9625     return;
9626 
9627   cs_base->reachable_labels = bitmap_alloc (&labels_obstack);
9628 
9629   /* Collect labels in this block.  We don't keep those corresponding
9630      to END {IF|SELECT}, these are checked in resolve_branch by going
9631      up through the code_stack.  */
9632   for (c = block; c; c = c->next)
9633     {
9634       if (c->here && c->op != EXEC_END_NESTED_BLOCK)
9635 	bitmap_set_bit (cs_base->reachable_labels, c->here->value);
9636     }
9637 
9638   /* Merge with labels from parent block.  */
9639   if (cs_base->prev)
9640     {
9641       gcc_assert (cs_base->prev->reachable_labels);
9642       bitmap_ior_into (cs_base->reachable_labels,
9643 		       cs_base->prev->reachable_labels);
9644     }
9645 }
9646 
9647 
9648 static void
9649 resolve_lock_unlock_event (gfc_code *code)
9650 {
9651   if (code->expr1->expr_type == EXPR_FUNCTION
9652       && code->expr1->value.function.isym
9653       && code->expr1->value.function.isym->id == GFC_ISYM_CAF_GET)
9654     remove_caf_get_intrinsic (code->expr1);
9655 
9656   if ((code->op == EXEC_LOCK || code->op == EXEC_UNLOCK)
9657       && (code->expr1->ts.type != BT_DERIVED
9658 	  || code->expr1->expr_type != EXPR_VARIABLE
9659 	  || code->expr1->ts.u.derived->from_intmod != INTMOD_ISO_FORTRAN_ENV
9660 	  || code->expr1->ts.u.derived->intmod_sym_id != ISOFORTRAN_LOCK_TYPE
9661 	  || code->expr1->rank != 0
9662 	  || (!gfc_is_coarray (code->expr1) &&
9663 	      !gfc_is_coindexed (code->expr1))))
9664     gfc_error ("Lock variable at %L must be a scalar of type LOCK_TYPE",
9665 	       &code->expr1->where);
9666   else if ((code->op == EXEC_EVENT_POST || code->op == EXEC_EVENT_WAIT)
9667 	   && (code->expr1->ts.type != BT_DERIVED
9668 	       || code->expr1->expr_type != EXPR_VARIABLE
9669 	       || code->expr1->ts.u.derived->from_intmod
9670 		  != INTMOD_ISO_FORTRAN_ENV
9671 	       || code->expr1->ts.u.derived->intmod_sym_id
9672 		  != ISOFORTRAN_EVENT_TYPE
9673 	       || code->expr1->rank != 0))
9674     gfc_error ("Event variable at %L must be a scalar of type EVENT_TYPE",
9675 	       &code->expr1->where);
9676   else if (code->op == EXEC_EVENT_POST && !gfc_is_coarray (code->expr1)
9677 	   && !gfc_is_coindexed (code->expr1))
9678     gfc_error ("Event variable argument at %L must be a coarray or coindexed",
9679 	       &code->expr1->where);
9680   else if (code->op == EXEC_EVENT_WAIT && !gfc_is_coarray (code->expr1))
9681     gfc_error ("Event variable argument at %L must be a coarray but not "
9682 	       "coindexed", &code->expr1->where);
9683 
9684   /* Check STAT.  */
9685   if (code->expr2
9686       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
9687 	  || code->expr2->expr_type != EXPR_VARIABLE))
9688     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
9689 	       &code->expr2->where);
9690 
9691   if (code->expr2
9692       && !gfc_check_vardef_context (code->expr2, false, false, false,
9693 				    _("STAT variable")))
9694     return;
9695 
9696   /* Check ERRMSG.  */
9697   if (code->expr3
9698       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
9699 	  || code->expr3->expr_type != EXPR_VARIABLE))
9700     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
9701 	       &code->expr3->where);
9702 
9703   if (code->expr3
9704       && !gfc_check_vardef_context (code->expr3, false, false, false,
9705 				    _("ERRMSG variable")))
9706     return;
9707 
9708   /* Check for LOCK the ACQUIRED_LOCK.  */
9709   if (code->op != EXEC_EVENT_WAIT && code->expr4
9710       && (code->expr4->ts.type != BT_LOGICAL || code->expr4->rank != 0
9711 	  || code->expr4->expr_type != EXPR_VARIABLE))
9712     gfc_error ("ACQUIRED_LOCK= argument at %L must be a scalar LOGICAL "
9713 	       "variable", &code->expr4->where);
9714 
9715   if (code->op != EXEC_EVENT_WAIT && code->expr4
9716       && !gfc_check_vardef_context (code->expr4, false, false, false,
9717 				    _("ACQUIRED_LOCK variable")))
9718     return;
9719 
9720   /* Check for EVENT WAIT the UNTIL_COUNT.  */
9721   if (code->op == EXEC_EVENT_WAIT && code->expr4)
9722     {
9723       if (!gfc_resolve_expr (code->expr4) || code->expr4->ts.type != BT_INTEGER
9724 	  || code->expr4->rank != 0)
9725 	gfc_error ("UNTIL_COUNT= argument at %L must be a scalar INTEGER "
9726 		   "expression", &code->expr4->where);
9727     }
9728 }
9729 
9730 
9731 static void
9732 resolve_critical (gfc_code *code)
9733 {
9734   gfc_symtree *symtree;
9735   gfc_symbol *lock_type;
9736   char name[GFC_MAX_SYMBOL_LEN];
9737   static int serial = 0;
9738 
9739   if (flag_coarray != GFC_FCOARRAY_LIB)
9740     return;
9741 
9742   symtree = gfc_find_symtree (gfc_current_ns->sym_root,
9743 			      GFC_PREFIX ("lock_type"));
9744   if (symtree)
9745     lock_type = symtree->n.sym;
9746   else
9747     {
9748       if (gfc_get_sym_tree (GFC_PREFIX ("lock_type"), gfc_current_ns, &symtree,
9749 			    false) != 0)
9750 	gcc_unreachable ();
9751       lock_type = symtree->n.sym;
9752       lock_type->attr.flavor = FL_DERIVED;
9753       lock_type->attr.zero_comp = 1;
9754       lock_type->from_intmod = INTMOD_ISO_FORTRAN_ENV;
9755       lock_type->intmod_sym_id = ISOFORTRAN_LOCK_TYPE;
9756     }
9757 
9758   sprintf(name, GFC_PREFIX ("lock_var") "%d",serial++);
9759   if (gfc_get_sym_tree (name, gfc_current_ns, &symtree, false) != 0)
9760     gcc_unreachable ();
9761 
9762   code->resolved_sym = symtree->n.sym;
9763   symtree->n.sym->attr.flavor = FL_VARIABLE;
9764   symtree->n.sym->attr.referenced = 1;
9765   symtree->n.sym->attr.artificial = 1;
9766   symtree->n.sym->attr.codimension = 1;
9767   symtree->n.sym->ts.type = BT_DERIVED;
9768   symtree->n.sym->ts.u.derived = lock_type;
9769   symtree->n.sym->as = gfc_get_array_spec ();
9770   symtree->n.sym->as->corank = 1;
9771   symtree->n.sym->as->type = AS_EXPLICIT;
9772   symtree->n.sym->as->cotype = AS_EXPLICIT;
9773   symtree->n.sym->as->lower[0] = gfc_get_int_expr (gfc_default_integer_kind,
9774 						   NULL, 1);
9775   gfc_commit_symbols();
9776 }
9777 
9778 
9779 static void
9780 resolve_sync (gfc_code *code)
9781 {
9782   /* Check imageset. The * case matches expr1 == NULL.  */
9783   if (code->expr1)
9784     {
9785       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
9786 	gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
9787 		   "INTEGER expression", &code->expr1->where);
9788       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
9789 	  && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
9790 	gfc_error ("Imageset argument at %L must between 1 and num_images()",
9791 		   &code->expr1->where);
9792       else if (code->expr1->expr_type == EXPR_ARRAY
9793 	       && gfc_simplify_expr (code->expr1, 0))
9794 	{
9795 	   gfc_constructor *cons;
9796 	   cons = gfc_constructor_first (code->expr1->value.constructor);
9797 	   for (; cons; cons = gfc_constructor_next (cons))
9798 	     if (cons->expr->expr_type == EXPR_CONSTANT
9799 		 &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
9800 	       gfc_error ("Imageset argument at %L must between 1 and "
9801 			  "num_images()", &cons->expr->where);
9802 	}
9803     }
9804 
9805   /* Check STAT.  */
9806   gfc_resolve_expr (code->expr2);
9807   if (code->expr2
9808       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
9809 	  || code->expr2->expr_type != EXPR_VARIABLE))
9810     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
9811 	       &code->expr2->where);
9812 
9813   /* Check ERRMSG.  */
9814   gfc_resolve_expr (code->expr3);
9815   if (code->expr3
9816       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
9817 	  || code->expr3->expr_type != EXPR_VARIABLE))
9818     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
9819 	       &code->expr3->where);
9820 }
9821 
9822 
9823 /* Given a branch to a label, see if the branch is conforming.
9824    The code node describes where the branch is located.  */
9825 
9826 static void
9827 resolve_branch (gfc_st_label *label, gfc_code *code)
9828 {
9829   code_stack *stack;
9830 
9831   if (label == NULL)
9832     return;
9833 
9834   /* Step one: is this a valid branching target?  */
9835 
9836   if (label->defined == ST_LABEL_UNKNOWN)
9837     {
9838       gfc_error ("Label %d referenced at %L is never defined", label->value,
9839 		 &code->loc);
9840       return;
9841     }
9842 
9843   if (label->defined != ST_LABEL_TARGET && label->defined != ST_LABEL_DO_TARGET)
9844     {
9845       gfc_error ("Statement at %L is not a valid branch target statement "
9846 		 "for the branch statement at %L", &label->where, &code->loc);
9847       return;
9848     }
9849 
9850   /* Step two: make sure this branch is not a branch to itself ;-)  */
9851 
9852   if (code->here == label)
9853     {
9854       gfc_warning (0,
9855 		   "Branch at %L may result in an infinite loop", &code->loc);
9856       return;
9857     }
9858 
9859   /* Step three:  See if the label is in the same block as the
9860      branching statement.  The hard work has been done by setting up
9861      the bitmap reachable_labels.  */
9862 
9863   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
9864     {
9865       /* Check now whether there is a CRITICAL construct; if so, check
9866 	 whether the label is still visible outside of the CRITICAL block,
9867 	 which is invalid.  */
9868       for (stack = cs_base; stack; stack = stack->prev)
9869 	{
9870 	  if (stack->current->op == EXEC_CRITICAL
9871 	      && bitmap_bit_p (stack->reachable_labels, label->value))
9872 	    gfc_error ("GOTO statement at %L leaves CRITICAL construct for "
9873 		      "label at %L", &code->loc, &label->where);
9874 	  else if (stack->current->op == EXEC_DO_CONCURRENT
9875 		   && bitmap_bit_p (stack->reachable_labels, label->value))
9876 	    gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct "
9877 		      "for label at %L", &code->loc, &label->where);
9878 	}
9879 
9880       return;
9881     }
9882 
9883   /* Step four:  If we haven't found the label in the bitmap, it may
9884     still be the label of the END of the enclosing block, in which
9885     case we find it by going up the code_stack.  */
9886 
9887   for (stack = cs_base; stack; stack = stack->prev)
9888     {
9889       if (stack->current->next && stack->current->next->here == label)
9890 	break;
9891       if (stack->current->op == EXEC_CRITICAL)
9892 	{
9893 	  /* Note: A label at END CRITICAL does not leave the CRITICAL
9894 	     construct as END CRITICAL is still part of it.  */
9895 	  gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
9896 		      " at %L", &code->loc, &label->where);
9897 	  return;
9898 	}
9899       else if (stack->current->op == EXEC_DO_CONCURRENT)
9900 	{
9901 	  gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct for "
9902 		     "label at %L", &code->loc, &label->where);
9903 	  return;
9904 	}
9905     }
9906 
9907   if (stack)
9908     {
9909       gcc_assert (stack->current->next->op == EXEC_END_NESTED_BLOCK);
9910       return;
9911     }
9912 
9913   /* The label is not in an enclosing block, so illegal.  This was
9914      allowed in Fortran 66, so we allow it as extension.  No
9915      further checks are necessary in this case.  */
9916   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
9917 		  "as the GOTO statement at %L", &label->where,
9918 		  &code->loc);
9919   return;
9920 }
9921 
9922 
9923 /* Check whether EXPR1 has the same shape as EXPR2.  */
9924 
9925 static bool
9926 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
9927 {
9928   mpz_t shape[GFC_MAX_DIMENSIONS];
9929   mpz_t shape2[GFC_MAX_DIMENSIONS];
9930   bool result = false;
9931   int i;
9932 
9933   /* Compare the rank.  */
9934   if (expr1->rank != expr2->rank)
9935     return result;
9936 
9937   /* Compare the size of each dimension.  */
9938   for (i=0; i<expr1->rank; i++)
9939     {
9940       if (!gfc_array_dimen_size (expr1, i, &shape[i]))
9941 	goto ignore;
9942 
9943       if (!gfc_array_dimen_size (expr2, i, &shape2[i]))
9944 	goto ignore;
9945 
9946       if (mpz_cmp (shape[i], shape2[i]))
9947 	goto over;
9948     }
9949 
9950   /* When either of the two expression is an assumed size array, we
9951      ignore the comparison of dimension sizes.  */
9952 ignore:
9953   result = true;
9954 
9955 over:
9956   gfc_clear_shape (shape, i);
9957   gfc_clear_shape (shape2, i);
9958   return result;
9959 }
9960 
9961 
9962 /* Check whether a WHERE assignment target or a WHERE mask expression
9963    has the same shape as the outmost WHERE mask expression.  */
9964 
9965 static void
9966 resolve_where (gfc_code *code, gfc_expr *mask)
9967 {
9968   gfc_code *cblock;
9969   gfc_code *cnext;
9970   gfc_expr *e = NULL;
9971 
9972   cblock = code->block;
9973 
9974   /* Store the first WHERE mask-expr of the WHERE statement or construct.
9975      In case of nested WHERE, only the outmost one is stored.  */
9976   if (mask == NULL) /* outmost WHERE */
9977     e = cblock->expr1;
9978   else /* inner WHERE */
9979     e = mask;
9980 
9981   while (cblock)
9982     {
9983       if (cblock->expr1)
9984 	{
9985 	  /* Check if the mask-expr has a consistent shape with the
9986 	     outmost WHERE mask-expr.  */
9987 	  if (!resolve_where_shape (cblock->expr1, e))
9988 	    gfc_error ("WHERE mask at %L has inconsistent shape",
9989 		       &cblock->expr1->where);
9990 	 }
9991 
9992       /* the assignment statement of a WHERE statement, or the first
9993 	 statement in where-body-construct of a WHERE construct */
9994       cnext = cblock->next;
9995       while (cnext)
9996 	{
9997 	  switch (cnext->op)
9998 	    {
9999 	    /* WHERE assignment statement */
10000 	    case EXEC_ASSIGN:
10001 
10002 	      /* Check shape consistent for WHERE assignment target.  */
10003 	      if (e && !resolve_where_shape (cnext->expr1, e))
10004 	       gfc_error ("WHERE assignment target at %L has "
10005 			  "inconsistent shape", &cnext->expr1->where);
10006 	      break;
10007 
10008 
10009 	    case EXEC_ASSIGN_CALL:
10010 	      resolve_call (cnext);
10011 	      if (!cnext->resolved_sym->attr.elemental)
10012 		gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
10013 			  &cnext->ext.actual->expr->where);
10014 	      break;
10015 
10016 	    /* WHERE or WHERE construct is part of a where-body-construct */
10017 	    case EXEC_WHERE:
10018 	      resolve_where (cnext, e);
10019 	      break;
10020 
10021 	    default:
10022 	      gfc_error ("Unsupported statement inside WHERE at %L",
10023 			 &cnext->loc);
10024 	    }
10025 	 /* the next statement within the same where-body-construct */
10026 	 cnext = cnext->next;
10027        }
10028     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
10029     cblock = cblock->block;
10030   }
10031 }
10032 
10033 
10034 /* Resolve assignment in FORALL construct.
10035    NVAR is the number of FORALL index variables, and VAR_EXPR records the
10036    FORALL index variables.  */
10037 
10038 static void
10039 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
10040 {
10041   int n;
10042 
10043   for (n = 0; n < nvar; n++)
10044     {
10045       gfc_symbol *forall_index;
10046 
10047       forall_index = var_expr[n]->symtree->n.sym;
10048 
10049       /* Check whether the assignment target is one of the FORALL index
10050 	 variable.  */
10051       if ((code->expr1->expr_type == EXPR_VARIABLE)
10052 	  && (code->expr1->symtree->n.sym == forall_index))
10053 	gfc_error ("Assignment to a FORALL index variable at %L",
10054 		   &code->expr1->where);
10055       else
10056 	{
10057 	  /* If one of the FORALL index variables doesn't appear in the
10058 	     assignment variable, then there could be a many-to-one
10059 	     assignment.  Emit a warning rather than an error because the
10060 	     mask could be resolving this problem.  */
10061 	  if (!find_forall_index (code->expr1, forall_index, 0))
10062 	    gfc_warning (0, "The FORALL with index %qs is not used on the "
10063 			 "left side of the assignment at %L and so might "
10064 			 "cause multiple assignment to this object",
10065 			 var_expr[n]->symtree->name, &code->expr1->where);
10066 	}
10067     }
10068 }
10069 
10070 
10071 /* Resolve WHERE statement in FORALL construct.  */
10072 
10073 static void
10074 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
10075 				  gfc_expr **var_expr)
10076 {
10077   gfc_code *cblock;
10078   gfc_code *cnext;
10079 
10080   cblock = code->block;
10081   while (cblock)
10082     {
10083       /* the assignment statement of a WHERE statement, or the first
10084 	 statement in where-body-construct of a WHERE construct */
10085       cnext = cblock->next;
10086       while (cnext)
10087 	{
10088 	  switch (cnext->op)
10089 	    {
10090 	    /* WHERE assignment statement */
10091 	    case EXEC_ASSIGN:
10092 	      gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
10093 	      break;
10094 
10095 	    /* WHERE operator assignment statement */
10096 	    case EXEC_ASSIGN_CALL:
10097 	      resolve_call (cnext);
10098 	      if (!cnext->resolved_sym->attr.elemental)
10099 		gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
10100 			  &cnext->ext.actual->expr->where);
10101 	      break;
10102 
10103 	    /* WHERE or WHERE construct is part of a where-body-construct */
10104 	    case EXEC_WHERE:
10105 	      gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
10106 	      break;
10107 
10108 	    default:
10109 	      gfc_error ("Unsupported statement inside WHERE at %L",
10110 			 &cnext->loc);
10111 	    }
10112 	  /* the next statement within the same where-body-construct */
10113 	  cnext = cnext->next;
10114 	}
10115       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
10116       cblock = cblock->block;
10117     }
10118 }
10119 
10120 
10121 /* Traverse the FORALL body to check whether the following errors exist:
10122    1. For assignment, check if a many-to-one assignment happens.
10123    2. For WHERE statement, check the WHERE body to see if there is any
10124       many-to-one assignment.  */
10125 
10126 static void
10127 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
10128 {
10129   gfc_code *c;
10130 
10131   c = code->block->next;
10132   while (c)
10133     {
10134       switch (c->op)
10135 	{
10136 	case EXEC_ASSIGN:
10137 	case EXEC_POINTER_ASSIGN:
10138 	  gfc_resolve_assign_in_forall (c, nvar, var_expr);
10139 	  break;
10140 
10141 	case EXEC_ASSIGN_CALL:
10142 	  resolve_call (c);
10143 	  break;
10144 
10145 	/* Because the gfc_resolve_blocks() will handle the nested FORALL,
10146 	   there is no need to handle it here.  */
10147 	case EXEC_FORALL:
10148 	  break;
10149 	case EXEC_WHERE:
10150 	  gfc_resolve_where_code_in_forall(c, nvar, var_expr);
10151 	  break;
10152 	default:
10153 	  break;
10154 	}
10155       /* The next statement in the FORALL body.  */
10156       c = c->next;
10157     }
10158 }
10159 
10160 
10161 /* Counts the number of iterators needed inside a forall construct, including
10162    nested forall constructs. This is used to allocate the needed memory
10163    in gfc_resolve_forall.  */
10164 
10165 static int
10166 gfc_count_forall_iterators (gfc_code *code)
10167 {
10168   int max_iters, sub_iters, current_iters;
10169   gfc_forall_iterator *fa;
10170 
10171   gcc_assert(code->op == EXEC_FORALL);
10172   max_iters = 0;
10173   current_iters = 0;
10174 
10175   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
10176     current_iters ++;
10177 
10178   code = code->block->next;
10179 
10180   while (code)
10181     {
10182       if (code->op == EXEC_FORALL)
10183         {
10184           sub_iters = gfc_count_forall_iterators (code);
10185           if (sub_iters > max_iters)
10186             max_iters = sub_iters;
10187         }
10188       code = code->next;
10189     }
10190 
10191   return current_iters + max_iters;
10192 }
10193 
10194 
10195 /* Given a FORALL construct, first resolve the FORALL iterator, then call
10196    gfc_resolve_forall_body to resolve the FORALL body.  */
10197 
10198 static void
10199 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
10200 {
10201   static gfc_expr **var_expr;
10202   static int total_var = 0;
10203   static int nvar = 0;
10204   int i, old_nvar, tmp;
10205   gfc_forall_iterator *fa;
10206 
10207   old_nvar = nvar;
10208 
10209   if (!gfc_notify_std (GFC_STD_F2018_OBS, "FORALL construct at %L", &code->loc))
10210     return;
10211 
10212   /* Start to resolve a FORALL construct   */
10213   if (forall_save == 0)
10214     {
10215       /* Count the total number of FORALL indices in the nested FORALL
10216          construct in order to allocate the VAR_EXPR with proper size.  */
10217       total_var = gfc_count_forall_iterators (code);
10218 
10219       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
10220       var_expr = XCNEWVEC (gfc_expr *, total_var);
10221     }
10222 
10223   /* The information about FORALL iterator, including FORALL indices start, end
10224      and stride.  An outer FORALL indice cannot appear in start, end or stride.  */
10225   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
10226     {
10227       /* Fortran 20008: C738 (R753).  */
10228       if (fa->var->ref && fa->var->ref->type == REF_ARRAY)
10229 	{
10230 	  gfc_error ("FORALL index-name at %L must be a scalar variable "
10231 		     "of type integer", &fa->var->where);
10232 	  continue;
10233 	}
10234 
10235       /* Check if any outer FORALL index name is the same as the current
10236 	 one.  */
10237       for (i = 0; i < nvar; i++)
10238 	{
10239 	  if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
10240 	    gfc_error ("An outer FORALL construct already has an index "
10241 			"with this name %L", &fa->var->where);
10242 	}
10243 
10244       /* Record the current FORALL index.  */
10245       var_expr[nvar] = gfc_copy_expr (fa->var);
10246 
10247       nvar++;
10248 
10249       /* No memory leak.  */
10250       gcc_assert (nvar <= total_var);
10251     }
10252 
10253   /* Resolve the FORALL body.  */
10254   gfc_resolve_forall_body (code, nvar, var_expr);
10255 
10256   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
10257   gfc_resolve_blocks (code->block, ns);
10258 
10259   tmp = nvar;
10260   nvar = old_nvar;
10261   /* Free only the VAR_EXPRs allocated in this frame.  */
10262   for (i = nvar; i < tmp; i++)
10263      gfc_free_expr (var_expr[i]);
10264 
10265   if (nvar == 0)
10266     {
10267       /* We are in the outermost FORALL construct.  */
10268       gcc_assert (forall_save == 0);
10269 
10270       /* VAR_EXPR is not needed any more.  */
10271       free (var_expr);
10272       total_var = 0;
10273     }
10274 }
10275 
10276 
10277 /* Resolve a BLOCK construct statement.  */
10278 
10279 static void
10280 resolve_block_construct (gfc_code* code)
10281 {
10282   /* Resolve the BLOCK's namespace.  */
10283   gfc_resolve (code->ext.block.ns);
10284 
10285   /* For an ASSOCIATE block, the associations (and their targets) are already
10286      resolved during resolve_symbol.  */
10287 }
10288 
10289 
10290 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
10291    DO code nodes.  */
10292 
10293 void
10294 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
10295 {
10296   bool t;
10297 
10298   for (; b; b = b->block)
10299     {
10300       t = gfc_resolve_expr (b->expr1);
10301       if (!gfc_resolve_expr (b->expr2))
10302 	t = false;
10303 
10304       switch (b->op)
10305 	{
10306 	case EXEC_IF:
10307 	  if (t && b->expr1 != NULL
10308 	      && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
10309 	    gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
10310 		       &b->expr1->where);
10311 	  break;
10312 
10313 	case EXEC_WHERE:
10314 	  if (t
10315 	      && b->expr1 != NULL
10316 	      && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
10317 	    gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
10318 		       &b->expr1->where);
10319 	  break;
10320 
10321 	case EXEC_GOTO:
10322 	  resolve_branch (b->label1, b);
10323 	  break;
10324 
10325 	case EXEC_BLOCK:
10326 	  resolve_block_construct (b);
10327 	  break;
10328 
10329 	case EXEC_SELECT:
10330 	case EXEC_SELECT_TYPE:
10331 	case EXEC_FORALL:
10332 	case EXEC_DO:
10333 	case EXEC_DO_WHILE:
10334 	case EXEC_DO_CONCURRENT:
10335 	case EXEC_CRITICAL:
10336 	case EXEC_READ:
10337 	case EXEC_WRITE:
10338 	case EXEC_IOLENGTH:
10339 	case EXEC_WAIT:
10340 	  break;
10341 
10342 	case EXEC_OMP_ATOMIC:
10343 	case EXEC_OACC_ATOMIC:
10344 	  {
10345 	    gfc_omp_atomic_op aop
10346 	      = (gfc_omp_atomic_op) (b->ext.omp_atomic & GFC_OMP_ATOMIC_MASK);
10347 
10348 	    /* Verify this before calling gfc_resolve_code, which might
10349 	       change it.  */
10350 	    gcc_assert (b->next && b->next->op == EXEC_ASSIGN);
10351 	    gcc_assert (((aop != GFC_OMP_ATOMIC_CAPTURE)
10352 			 && b->next->next == NULL)
10353 			|| ((aop == GFC_OMP_ATOMIC_CAPTURE)
10354 			    && b->next->next != NULL
10355 			    && b->next->next->op == EXEC_ASSIGN
10356 			    && b->next->next->next == NULL));
10357 	  }
10358 	  break;
10359 
10360 	case EXEC_OACC_PARALLEL_LOOP:
10361 	case EXEC_OACC_PARALLEL:
10362 	case EXEC_OACC_KERNELS_LOOP:
10363 	case EXEC_OACC_KERNELS:
10364 	case EXEC_OACC_DATA:
10365 	case EXEC_OACC_HOST_DATA:
10366 	case EXEC_OACC_LOOP:
10367 	case EXEC_OACC_UPDATE:
10368 	case EXEC_OACC_WAIT:
10369 	case EXEC_OACC_CACHE:
10370 	case EXEC_OACC_ENTER_DATA:
10371 	case EXEC_OACC_EXIT_DATA:
10372 	case EXEC_OACC_ROUTINE:
10373 	case EXEC_OMP_CRITICAL:
10374 	case EXEC_OMP_DISTRIBUTE:
10375 	case EXEC_OMP_DISTRIBUTE_PARALLEL_DO:
10376 	case EXEC_OMP_DISTRIBUTE_PARALLEL_DO_SIMD:
10377 	case EXEC_OMP_DISTRIBUTE_SIMD:
10378 	case EXEC_OMP_DO:
10379 	case EXEC_OMP_DO_SIMD:
10380 	case EXEC_OMP_MASTER:
10381 	case EXEC_OMP_ORDERED:
10382 	case EXEC_OMP_PARALLEL:
10383 	case EXEC_OMP_PARALLEL_DO:
10384 	case EXEC_OMP_PARALLEL_DO_SIMD:
10385 	case EXEC_OMP_PARALLEL_SECTIONS:
10386 	case EXEC_OMP_PARALLEL_WORKSHARE:
10387 	case EXEC_OMP_SECTIONS:
10388 	case EXEC_OMP_SIMD:
10389 	case EXEC_OMP_SINGLE:
10390 	case EXEC_OMP_TARGET:
10391 	case EXEC_OMP_TARGET_DATA:
10392 	case EXEC_OMP_TARGET_ENTER_DATA:
10393 	case EXEC_OMP_TARGET_EXIT_DATA:
10394 	case EXEC_OMP_TARGET_PARALLEL:
10395 	case EXEC_OMP_TARGET_PARALLEL_DO:
10396 	case EXEC_OMP_TARGET_PARALLEL_DO_SIMD:
10397 	case EXEC_OMP_TARGET_SIMD:
10398 	case EXEC_OMP_TARGET_TEAMS:
10399 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
10400 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
10401 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
10402 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
10403 	case EXEC_OMP_TARGET_UPDATE:
10404 	case EXEC_OMP_TASK:
10405 	case EXEC_OMP_TASKGROUP:
10406 	case EXEC_OMP_TASKLOOP:
10407 	case EXEC_OMP_TASKLOOP_SIMD:
10408 	case EXEC_OMP_TASKWAIT:
10409 	case EXEC_OMP_TASKYIELD:
10410 	case EXEC_OMP_TEAMS:
10411 	case EXEC_OMP_TEAMS_DISTRIBUTE:
10412 	case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
10413 	case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
10414 	case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
10415 	case EXEC_OMP_WORKSHARE:
10416 	  break;
10417 
10418 	default:
10419 	  gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
10420 	}
10421 
10422       gfc_resolve_code (b->next, ns);
10423     }
10424 }
10425 
10426 
10427 /* Does everything to resolve an ordinary assignment.  Returns true
10428    if this is an interface assignment.  */
10429 static bool
10430 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
10431 {
10432   bool rval = false;
10433   gfc_expr *lhs;
10434   gfc_expr *rhs;
10435   int n;
10436   gfc_ref *ref;
10437   symbol_attribute attr;
10438 
10439   if (gfc_extend_assign (code, ns))
10440     {
10441       gfc_expr** rhsptr;
10442 
10443       if (code->op == EXEC_ASSIGN_CALL)
10444 	{
10445 	  lhs = code->ext.actual->expr;
10446 	  rhsptr = &code->ext.actual->next->expr;
10447 	}
10448       else
10449 	{
10450 	  gfc_actual_arglist* args;
10451 	  gfc_typebound_proc* tbp;
10452 
10453 	  gcc_assert (code->op == EXEC_COMPCALL);
10454 
10455 	  args = code->expr1->value.compcall.actual;
10456 	  lhs = args->expr;
10457 	  rhsptr = &args->next->expr;
10458 
10459 	  tbp = code->expr1->value.compcall.tbp;
10460 	  gcc_assert (!tbp->is_generic);
10461 	}
10462 
10463       /* Make a temporary rhs when there is a default initializer
10464 	 and rhs is the same symbol as the lhs.  */
10465       if ((*rhsptr)->expr_type == EXPR_VARIABLE
10466 	    && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
10467 	    && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
10468 	    && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
10469 	*rhsptr = gfc_get_parentheses (*rhsptr);
10470 
10471       return true;
10472     }
10473 
10474   lhs = code->expr1;
10475   rhs = code->expr2;
10476 
10477   if (rhs->is_boz
10478       && !gfc_notify_std (GFC_STD_GNU, "BOZ literal at %L outside "
10479 			  "a DATA statement and outside INT/REAL/DBLE/CMPLX",
10480 			  &code->loc))
10481     return false;
10482 
10483   /* Handle the case of a BOZ literal on the RHS.  */
10484   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
10485     {
10486       int rc;
10487       if (warn_surprising)
10488 	gfc_warning (OPT_Wsurprising,
10489 		     "BOZ literal at %L is bitwise transferred "
10490 		     "non-integer symbol %qs", &code->loc,
10491 		     lhs->symtree->n.sym->name);
10492 
10493       if (!gfc_convert_boz (rhs, &lhs->ts))
10494 	return false;
10495       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
10496 	{
10497 	  if (rc == ARITH_UNDERFLOW)
10498 	    gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
10499 		       ". This check can be disabled with the option "
10500 		       "%<-fno-range-check%>", &rhs->where);
10501 	  else if (rc == ARITH_OVERFLOW)
10502 	    gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
10503 		       ". This check can be disabled with the option "
10504 		       "%<-fno-range-check%>", &rhs->where);
10505 	  else if (rc == ARITH_NAN)
10506 	    gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
10507 		       ". This check can be disabled with the option "
10508 		       "%<-fno-range-check%>", &rhs->where);
10509 	  return false;
10510 	}
10511     }
10512 
10513   if (lhs->ts.type == BT_CHARACTER
10514 	&& warn_character_truncation)
10515     {
10516       HOST_WIDE_INT llen = 0, rlen = 0;
10517       if (lhs->ts.u.cl != NULL
10518 	    && lhs->ts.u.cl->length != NULL
10519 	    && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
10520 	llen = gfc_mpz_get_hwi (lhs->ts.u.cl->length->value.integer);
10521 
10522       if (rhs->expr_type == EXPR_CONSTANT)
10523  	rlen = rhs->value.character.length;
10524 
10525       else if (rhs->ts.u.cl != NULL
10526 		 && rhs->ts.u.cl->length != NULL
10527 		 && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
10528 	rlen = gfc_mpz_get_hwi (rhs->ts.u.cl->length->value.integer);
10529 
10530       if (rlen && llen && rlen > llen)
10531 	gfc_warning_now (OPT_Wcharacter_truncation,
10532 			 "CHARACTER expression will be truncated "
10533 			 "in assignment (%ld/%ld) at %L",
10534 			 (long) llen, (long) rlen, &code->loc);
10535     }
10536 
10537   /* Ensure that a vector index expression for the lvalue is evaluated
10538      to a temporary if the lvalue symbol is referenced in it.  */
10539   if (lhs->rank)
10540     {
10541       for (ref = lhs->ref; ref; ref= ref->next)
10542 	if (ref->type == REF_ARRAY)
10543 	  {
10544 	    for (n = 0; n < ref->u.ar.dimen; n++)
10545 	      if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
10546 		  && gfc_find_sym_in_expr (lhs->symtree->n.sym,
10547 					   ref->u.ar.start[n]))
10548 		ref->u.ar.start[n]
10549 			= gfc_get_parentheses (ref->u.ar.start[n]);
10550 	  }
10551     }
10552 
10553   if (gfc_pure (NULL))
10554     {
10555       if (lhs->ts.type == BT_DERIVED
10556 	    && lhs->expr_type == EXPR_VARIABLE
10557 	    && lhs->ts.u.derived->attr.pointer_comp
10558 	    && rhs->expr_type == EXPR_VARIABLE
10559 	    && (gfc_impure_variable (rhs->symtree->n.sym)
10560 		|| gfc_is_coindexed (rhs)))
10561 	{
10562 	  /* F2008, C1283.  */
10563 	  if (gfc_is_coindexed (rhs))
10564 	    gfc_error ("Coindexed expression at %L is assigned to "
10565 			"a derived type variable with a POINTER "
10566 			"component in a PURE procedure",
10567 			&rhs->where);
10568 	  else
10569 	    gfc_error ("The impure variable at %L is assigned to "
10570 			"a derived type variable with a POINTER "
10571 			"component in a PURE procedure (12.6)",
10572 			&rhs->where);
10573 	  return rval;
10574 	}
10575 
10576       /* Fortran 2008, C1283.  */
10577       if (gfc_is_coindexed (lhs))
10578 	{
10579 	  gfc_error ("Assignment to coindexed variable at %L in a PURE "
10580 		     "procedure", &rhs->where);
10581 	  return rval;
10582 	}
10583     }
10584 
10585   if (gfc_implicit_pure (NULL))
10586     {
10587       if (lhs->expr_type == EXPR_VARIABLE
10588 	    && lhs->symtree->n.sym != gfc_current_ns->proc_name
10589 	    && lhs->symtree->n.sym->ns != gfc_current_ns)
10590 	gfc_unset_implicit_pure (NULL);
10591 
10592       if (lhs->ts.type == BT_DERIVED
10593 	    && lhs->expr_type == EXPR_VARIABLE
10594 	    && lhs->ts.u.derived->attr.pointer_comp
10595 	    && rhs->expr_type == EXPR_VARIABLE
10596 	    && (gfc_impure_variable (rhs->symtree->n.sym)
10597 		|| gfc_is_coindexed (rhs)))
10598 	gfc_unset_implicit_pure (NULL);
10599 
10600       /* Fortran 2008, C1283.  */
10601       if (gfc_is_coindexed (lhs))
10602 	gfc_unset_implicit_pure (NULL);
10603     }
10604 
10605   /* F2008, 7.2.1.2.  */
10606   attr = gfc_expr_attr (lhs);
10607   if (lhs->ts.type == BT_CLASS && attr.allocatable)
10608     {
10609       if (attr.codimension)
10610 	{
10611 	  gfc_error ("Assignment to polymorphic coarray at %L is not "
10612 		     "permitted", &lhs->where);
10613 	  return false;
10614 	}
10615       if (!gfc_notify_std (GFC_STD_F2008, "Assignment to an allocatable "
10616 			   "polymorphic variable at %L", &lhs->where))
10617 	return false;
10618       if (!flag_realloc_lhs)
10619 	{
10620 	  gfc_error ("Assignment to an allocatable polymorphic variable at %L "
10621 		     "requires %<-frealloc-lhs%>", &lhs->where);
10622 	  return false;
10623 	}
10624     }
10625   else if (lhs->ts.type == BT_CLASS)
10626     {
10627       gfc_error ("Nonallocatable variable must not be polymorphic in intrinsic "
10628 		 "assignment at %L - check that there is a matching specific "
10629 		 "subroutine for '=' operator", &lhs->where);
10630       return false;
10631     }
10632 
10633   bool lhs_coindexed = gfc_is_coindexed (lhs);
10634 
10635   /* F2008, Section 7.2.1.2.  */
10636   if (lhs_coindexed && gfc_has_ultimate_allocatable (lhs))
10637     {
10638       gfc_error ("Coindexed variable must not have an allocatable ultimate "
10639 		 "component in assignment at %L", &lhs->where);
10640       return false;
10641     }
10642 
10643   /* Assign the 'data' of a class object to a derived type.  */
10644   if (lhs->ts.type == BT_DERIVED
10645       && rhs->ts.type == BT_CLASS
10646       && rhs->expr_type != EXPR_ARRAY)
10647     gfc_add_data_component (rhs);
10648 
10649   /* Make sure there is a vtable and, in particular, a _copy for the
10650      rhs type.  */
10651   if (UNLIMITED_POLY (lhs) && lhs->rank && rhs->ts.type != BT_CLASS)
10652     gfc_find_vtab (&rhs->ts);
10653 
10654   bool caf_convert_to_send = flag_coarray == GFC_FCOARRAY_LIB
10655       && (lhs_coindexed
10656 	  || (code->expr2->expr_type == EXPR_FUNCTION
10657 	      && code->expr2->value.function.isym
10658 	      && code->expr2->value.function.isym->id == GFC_ISYM_CAF_GET
10659 	      && (code->expr1->rank == 0 || code->expr2->rank != 0)
10660 	      && !gfc_expr_attr (rhs).allocatable
10661 	      && !gfc_has_vector_subscript (rhs)));
10662 
10663   gfc_check_assign (lhs, rhs, 1, !caf_convert_to_send);
10664 
10665   /* Insert a GFC_ISYM_CAF_SEND intrinsic, when the LHS is a coindexed variable.
10666      Additionally, insert this code when the RHS is a CAF as we then use the
10667      GFC_ISYM_CAF_SEND intrinsic just to avoid a temporary; but do not do so if
10668      the LHS is (re)allocatable or has a vector subscript.  If the LHS is a
10669      noncoindexed array and the RHS is a coindexed scalar, use the normal code
10670      path.  */
10671   if (caf_convert_to_send)
10672     {
10673       if (code->expr2->expr_type == EXPR_FUNCTION
10674 	  && code->expr2->value.function.isym
10675 	  && code->expr2->value.function.isym->id == GFC_ISYM_CAF_GET)
10676 	remove_caf_get_intrinsic (code->expr2);
10677       code->op = EXEC_CALL;
10678       gfc_get_sym_tree (GFC_PREFIX ("caf_send"), ns, &code->symtree, true);
10679       code->resolved_sym = code->symtree->n.sym;
10680       code->resolved_sym->attr.flavor = FL_PROCEDURE;
10681       code->resolved_sym->attr.intrinsic = 1;
10682       code->resolved_sym->attr.subroutine = 1;
10683       code->resolved_isym = gfc_intrinsic_subroutine_by_id (GFC_ISYM_CAF_SEND);
10684       gfc_commit_symbol (code->resolved_sym);
10685       code->ext.actual = gfc_get_actual_arglist ();
10686       code->ext.actual->expr = lhs;
10687       code->ext.actual->next = gfc_get_actual_arglist ();
10688       code->ext.actual->next->expr = rhs;
10689       code->expr1 = NULL;
10690       code->expr2 = NULL;
10691     }
10692 
10693   return false;
10694 }
10695 
10696 
10697 /* Add a component reference onto an expression.  */
10698 
10699 static void
10700 add_comp_ref (gfc_expr *e, gfc_component *c)
10701 {
10702   gfc_ref **ref;
10703   ref = &(e->ref);
10704   while (*ref)
10705     ref = &((*ref)->next);
10706   *ref = gfc_get_ref ();
10707   (*ref)->type = REF_COMPONENT;
10708   (*ref)->u.c.sym = e->ts.u.derived;
10709   (*ref)->u.c.component = c;
10710   e->ts = c->ts;
10711 
10712   /* Add a full array ref, as necessary.  */
10713   if (c->as)
10714     {
10715       gfc_add_full_array_ref (e, c->as);
10716       e->rank = c->as->rank;
10717     }
10718 }
10719 
10720 
10721 /* Build an assignment.  Keep the argument 'op' for future use, so that
10722    pointer assignments can be made.  */
10723 
10724 static gfc_code *
10725 build_assignment (gfc_exec_op op, gfc_expr *expr1, gfc_expr *expr2,
10726 		  gfc_component *comp1, gfc_component *comp2, locus loc)
10727 {
10728   gfc_code *this_code;
10729 
10730   this_code = gfc_get_code (op);
10731   this_code->next = NULL;
10732   this_code->expr1 = gfc_copy_expr (expr1);
10733   this_code->expr2 = gfc_copy_expr (expr2);
10734   this_code->loc = loc;
10735   if (comp1 && comp2)
10736     {
10737       add_comp_ref (this_code->expr1, comp1);
10738       add_comp_ref (this_code->expr2, comp2);
10739     }
10740 
10741   return this_code;
10742 }
10743 
10744 
10745 /* Makes a temporary variable expression based on the characteristics of
10746    a given variable expression.  */
10747 
10748 static gfc_expr*
10749 get_temp_from_expr (gfc_expr *e, gfc_namespace *ns)
10750 {
10751   static int serial = 0;
10752   char name[GFC_MAX_SYMBOL_LEN];
10753   gfc_symtree *tmp;
10754   gfc_array_spec *as;
10755   gfc_array_ref *aref;
10756   gfc_ref *ref;
10757 
10758   sprintf (name, GFC_PREFIX("DA%d"), serial++);
10759   gfc_get_sym_tree (name, ns, &tmp, false);
10760   gfc_add_type (tmp->n.sym, &e->ts, NULL);
10761 
10762   if (e->expr_type == EXPR_CONSTANT && e->ts.type == BT_CHARACTER)
10763     tmp->n.sym->ts.u.cl->length = gfc_get_int_expr (gfc_charlen_int_kind,
10764 						    NULL,
10765 						    e->value.character.length);
10766 
10767   as = NULL;
10768   ref = NULL;
10769   aref = NULL;
10770 
10771   /* Obtain the arrayspec for the temporary.  */
10772    if (e->rank && e->expr_type != EXPR_ARRAY
10773        && e->expr_type != EXPR_FUNCTION
10774        && e->expr_type != EXPR_OP)
10775     {
10776       aref = gfc_find_array_ref (e);
10777       if (e->expr_type == EXPR_VARIABLE
10778 	  && e->symtree->n.sym->as == aref->as)
10779 	as = aref->as;
10780       else
10781 	{
10782 	  for (ref = e->ref; ref; ref = ref->next)
10783 	    if (ref->type == REF_COMPONENT
10784 		&& ref->u.c.component->as == aref->as)
10785 	      {
10786 		as = aref->as;
10787 		break;
10788 	      }
10789 	}
10790     }
10791 
10792   /* Add the attributes and the arrayspec to the temporary.  */
10793   tmp->n.sym->attr = gfc_expr_attr (e);
10794   tmp->n.sym->attr.function = 0;
10795   tmp->n.sym->attr.result = 0;
10796   tmp->n.sym->attr.flavor = FL_VARIABLE;
10797   tmp->n.sym->attr.dummy = 0;
10798   tmp->n.sym->attr.intent = INTENT_UNKNOWN;
10799 
10800   if (as)
10801     {
10802       tmp->n.sym->as = gfc_copy_array_spec (as);
10803       if (!ref)
10804 	ref = e->ref;
10805       if (as->type == AS_DEFERRED)
10806 	tmp->n.sym->attr.allocatable = 1;
10807     }
10808   else if (e->rank && (e->expr_type == EXPR_ARRAY
10809 		       || e->expr_type == EXPR_FUNCTION
10810 		       || e->expr_type == EXPR_OP))
10811     {
10812       tmp->n.sym->as = gfc_get_array_spec ();
10813       tmp->n.sym->as->type = AS_DEFERRED;
10814       tmp->n.sym->as->rank = e->rank;
10815       tmp->n.sym->attr.allocatable = 1;
10816       tmp->n.sym->attr.dimension = 1;
10817     }
10818   else
10819     tmp->n.sym->attr.dimension = 0;
10820 
10821   gfc_set_sym_referenced (tmp->n.sym);
10822   gfc_commit_symbol (tmp->n.sym);
10823   e = gfc_lval_expr_from_sym (tmp->n.sym);
10824 
10825   /* Should the lhs be a section, use its array ref for the
10826      temporary expression.  */
10827   if (aref && aref->type != AR_FULL)
10828     {
10829       gfc_free_ref_list (e->ref);
10830       e->ref = gfc_copy_ref (ref);
10831     }
10832   return e;
10833 }
10834 
10835 
10836 /* Add one line of code to the code chain, making sure that 'head' and
10837    'tail' are appropriately updated.  */
10838 
10839 static void
10840 add_code_to_chain (gfc_code **this_code, gfc_code **head, gfc_code **tail)
10841 {
10842   gcc_assert (this_code);
10843   if (*head == NULL)
10844     *head = *tail = *this_code;
10845   else
10846     *tail = gfc_append_code (*tail, *this_code);
10847   *this_code = NULL;
10848 }
10849 
10850 
10851 /* Counts the potential number of part array references that would
10852    result from resolution of typebound defined assignments.  */
10853 
10854 static int
10855 nonscalar_typebound_assign (gfc_symbol *derived, int depth)
10856 {
10857   gfc_component *c;
10858   int c_depth = 0, t_depth;
10859 
10860   for (c= derived->components; c; c = c->next)
10861     {
10862       if ((!gfc_bt_struct (c->ts.type)
10863 	    || c->attr.pointer
10864 	    || c->attr.allocatable
10865 	    || c->attr.proc_pointer_comp
10866 	    || c->attr.class_pointer
10867 	    || c->attr.proc_pointer)
10868 	  && !c->attr.defined_assign_comp)
10869 	continue;
10870 
10871       if (c->as && c_depth == 0)
10872 	c_depth = 1;
10873 
10874       if (c->ts.u.derived->attr.defined_assign_comp)
10875 	t_depth = nonscalar_typebound_assign (c->ts.u.derived,
10876 					      c->as ? 1 : 0);
10877       else
10878 	t_depth = 0;
10879 
10880       c_depth = t_depth > c_depth ? t_depth : c_depth;
10881     }
10882   return depth + c_depth;
10883 }
10884 
10885 
10886 /* Implement 7.2.1.3 of the F08 standard:
10887    "An intrinsic assignment where the variable is of derived type is
10888    performed as if each component of the variable were assigned from the
10889    corresponding component of expr using pointer assignment (7.2.2) for
10890    each pointer component, defined assignment for each nonpointer
10891    nonallocatable component of a type that has a type-bound defined
10892    assignment consistent with the component, intrinsic assignment for
10893    each other nonpointer nonallocatable component, ..."
10894 
10895    The pointer assignments are taken care of by the intrinsic
10896    assignment of the structure itself.  This function recursively adds
10897    defined assignments where required.  The recursion is accomplished
10898    by calling gfc_resolve_code.
10899 
10900    When the lhs in a defined assignment has intent INOUT, we need a
10901    temporary for the lhs.  In pseudo-code:
10902 
10903    ! Only call function lhs once.
10904       if (lhs is not a constant or an variable)
10905 	  temp_x = expr2
10906           expr2 => temp_x
10907    ! Do the intrinsic assignment
10908       expr1 = expr2
10909    ! Now do the defined assignments
10910       do over components with typebound defined assignment [%cmp]
10911 	#if one component's assignment procedure is INOUT
10912 	  t1 = expr1
10913 	  #if expr2 non-variable
10914 	    temp_x = expr2
10915 	    expr2 => temp_x
10916 	  # endif
10917 	  expr1 = expr2
10918 	  # for each cmp
10919 	    t1%cmp {defined=} expr2%cmp
10920 	    expr1%cmp = t1%cmp
10921 	#else
10922 	  expr1 = expr2
10923 
10924 	# for each cmp
10925 	  expr1%cmp {defined=} expr2%cmp
10926 	#endif
10927    */
10928 
10929 /* The temporary assignments have to be put on top of the additional
10930    code to avoid the result being changed by the intrinsic assignment.
10931    */
10932 static int component_assignment_level = 0;
10933 static gfc_code *tmp_head = NULL, *tmp_tail = NULL;
10934 
10935 static void
10936 generate_component_assignments (gfc_code **code, gfc_namespace *ns)
10937 {
10938   gfc_component *comp1, *comp2;
10939   gfc_code *this_code = NULL, *head = NULL, *tail = NULL;
10940   gfc_expr *t1;
10941   int error_count, depth;
10942 
10943   gfc_get_errors (NULL, &error_count);
10944 
10945   /* Filter out continuing processing after an error.  */
10946   if (error_count
10947       || (*code)->expr1->ts.type != BT_DERIVED
10948       || (*code)->expr2->ts.type != BT_DERIVED)
10949     return;
10950 
10951   /* TODO: Handle more than one part array reference in assignments.  */
10952   depth = nonscalar_typebound_assign ((*code)->expr1->ts.u.derived,
10953 				      (*code)->expr1->rank ? 1 : 0);
10954   if (depth > 1)
10955     {
10956       gfc_warning (0, "TODO: type-bound defined assignment(s) at %L not "
10957 		   "done because multiple part array references would "
10958 		   "occur in intermediate expressions.", &(*code)->loc);
10959       return;
10960     }
10961 
10962   component_assignment_level++;
10963 
10964   /* Create a temporary so that functions get called only once.  */
10965   if ((*code)->expr2->expr_type != EXPR_VARIABLE
10966       && (*code)->expr2->expr_type != EXPR_CONSTANT)
10967     {
10968       gfc_expr *tmp_expr;
10969 
10970       /* Assign the rhs to the temporary.  */
10971       tmp_expr = get_temp_from_expr ((*code)->expr1, ns);
10972       this_code = build_assignment (EXEC_ASSIGN,
10973 				    tmp_expr, (*code)->expr2,
10974 				    NULL, NULL, (*code)->loc);
10975       /* Add the code and substitute the rhs expression.  */
10976       add_code_to_chain (&this_code, &tmp_head, &tmp_tail);
10977       gfc_free_expr ((*code)->expr2);
10978       (*code)->expr2 = tmp_expr;
10979     }
10980 
10981   /* Do the intrinsic assignment.  This is not needed if the lhs is one
10982      of the temporaries generated here, since the intrinsic assignment
10983      to the final result already does this.  */
10984   if ((*code)->expr1->symtree->n.sym->name[2] != '@')
10985     {
10986       this_code = build_assignment (EXEC_ASSIGN,
10987 				    (*code)->expr1, (*code)->expr2,
10988 				    NULL, NULL, (*code)->loc);
10989       add_code_to_chain (&this_code, &head, &tail);
10990     }
10991 
10992   comp1 = (*code)->expr1->ts.u.derived->components;
10993   comp2 = (*code)->expr2->ts.u.derived->components;
10994 
10995   t1 = NULL;
10996   for (; comp1; comp1 = comp1->next, comp2 = comp2->next)
10997     {
10998       bool inout = false;
10999 
11000       /* The intrinsic assignment does the right thing for pointers
11001 	 of all kinds and allocatable components.  */
11002       if (!gfc_bt_struct (comp1->ts.type)
11003 	  || comp1->attr.pointer
11004 	  || comp1->attr.allocatable
11005 	  || comp1->attr.proc_pointer_comp
11006 	  || comp1->attr.class_pointer
11007 	  || comp1->attr.proc_pointer)
11008 	continue;
11009 
11010       /* Make an assigment for this component.  */
11011       this_code = build_assignment (EXEC_ASSIGN,
11012 				    (*code)->expr1, (*code)->expr2,
11013 				    comp1, comp2, (*code)->loc);
11014 
11015       /* Convert the assignment if there is a defined assignment for
11016 	 this type.  Otherwise, using the call from gfc_resolve_code,
11017 	 recurse into its components.  */
11018       gfc_resolve_code (this_code, ns);
11019 
11020       if (this_code->op == EXEC_ASSIGN_CALL)
11021 	{
11022 	  gfc_formal_arglist *dummy_args;
11023 	  gfc_symbol *rsym;
11024 	  /* Check that there is a typebound defined assignment.  If not,
11025 	     then this must be a module defined assignment.  We cannot
11026 	     use the defined_assign_comp attribute here because it must
11027 	     be this derived type that has the defined assignment and not
11028 	     a parent type.  */
11029 	  if (!(comp1->ts.u.derived->f2k_derived
11030 		&& comp1->ts.u.derived->f2k_derived
11031 					->tb_op[INTRINSIC_ASSIGN]))
11032 	    {
11033 	      gfc_free_statements (this_code);
11034 	      this_code = NULL;
11035 	      continue;
11036 	    }
11037 
11038 	  /* If the first argument of the subroutine has intent INOUT
11039 	     a temporary must be generated and used instead.  */
11040 	  rsym = this_code->resolved_sym;
11041 	  dummy_args = gfc_sym_get_dummy_args (rsym);
11042 	  if (dummy_args
11043 	      && dummy_args->sym->attr.intent == INTENT_INOUT)
11044 	    {
11045 	      gfc_code *temp_code;
11046 	      inout = true;
11047 
11048 	      /* Build the temporary required for the assignment and put
11049 		 it at the head of the generated code.  */
11050 	      if (!t1)
11051 		{
11052 		  t1 = get_temp_from_expr ((*code)->expr1, ns);
11053 		  temp_code = build_assignment (EXEC_ASSIGN,
11054 						t1, (*code)->expr1,
11055 				NULL, NULL, (*code)->loc);
11056 
11057 		  /* For allocatable LHS, check whether it is allocated.  Note
11058 		     that allocatable components with defined assignment are
11059 		     not yet support.  See PR 57696.  */
11060 		  if ((*code)->expr1->symtree->n.sym->attr.allocatable)
11061 		    {
11062 		      gfc_code *block;
11063 		      gfc_expr *e =
11064 			gfc_lval_expr_from_sym ((*code)->expr1->symtree->n.sym);
11065 		      block = gfc_get_code (EXEC_IF);
11066 		      block->block = gfc_get_code (EXEC_IF);
11067 		      block->block->expr1
11068 			  = gfc_build_intrinsic_call (ns,
11069 				    GFC_ISYM_ALLOCATED, "allocated",
11070 				    (*code)->loc, 1, e);
11071 		      block->block->next = temp_code;
11072 		      temp_code = block;
11073 		    }
11074 		  add_code_to_chain (&temp_code, &tmp_head, &tmp_tail);
11075 		}
11076 
11077 	      /* Replace the first actual arg with the component of the
11078 		 temporary.  */
11079 	      gfc_free_expr (this_code->ext.actual->expr);
11080 	      this_code->ext.actual->expr = gfc_copy_expr (t1);
11081 	      add_comp_ref (this_code->ext.actual->expr, comp1);
11082 
11083 	      /* If the LHS variable is allocatable and wasn't allocated and
11084                  the temporary is allocatable, pointer assign the address of
11085                  the freshly allocated LHS to the temporary.  */
11086 	      if ((*code)->expr1->symtree->n.sym->attr.allocatable
11087 		  && gfc_expr_attr ((*code)->expr1).allocatable)
11088 		{
11089 		  gfc_code *block;
11090 		  gfc_expr *cond;
11091 
11092 		  cond = gfc_get_expr ();
11093 		  cond->ts.type = BT_LOGICAL;
11094 		  cond->ts.kind = gfc_default_logical_kind;
11095 		  cond->expr_type = EXPR_OP;
11096 		  cond->where = (*code)->loc;
11097 		  cond->value.op.op = INTRINSIC_NOT;
11098 		  cond->value.op.op1 = gfc_build_intrinsic_call (ns,
11099 					  GFC_ISYM_ALLOCATED, "allocated",
11100 					  (*code)->loc, 1, gfc_copy_expr (t1));
11101 		  block = gfc_get_code (EXEC_IF);
11102 		  block->block = gfc_get_code (EXEC_IF);
11103 		  block->block->expr1 = cond;
11104 		  block->block->next = build_assignment (EXEC_POINTER_ASSIGN,
11105 					t1, (*code)->expr1,
11106 					NULL, NULL, (*code)->loc);
11107 		  add_code_to_chain (&block, &head, &tail);
11108 		}
11109 	    }
11110 	}
11111       else if (this_code->op == EXEC_ASSIGN && !this_code->next)
11112 	{
11113 	  /* Don't add intrinsic assignments since they are already
11114 	     effected by the intrinsic assignment of the structure.  */
11115 	  gfc_free_statements (this_code);
11116 	  this_code = NULL;
11117 	  continue;
11118 	}
11119 
11120       add_code_to_chain (&this_code, &head, &tail);
11121 
11122       if (t1 && inout)
11123 	{
11124 	  /* Transfer the value to the final result.  */
11125 	  this_code = build_assignment (EXEC_ASSIGN,
11126 					(*code)->expr1, t1,
11127 					comp1, comp2, (*code)->loc);
11128 	  add_code_to_chain (&this_code, &head, &tail);
11129 	}
11130     }
11131 
11132   /* Put the temporary assignments at the top of the generated code.  */
11133   if (tmp_head && component_assignment_level == 1)
11134     {
11135       gfc_append_code (tmp_head, head);
11136       head = tmp_head;
11137       tmp_head = tmp_tail = NULL;
11138     }
11139 
11140   // If we did a pointer assignment - thus, we need to ensure that the LHS is
11141   // not accidentally deallocated. Hence, nullify t1.
11142   if (t1 && (*code)->expr1->symtree->n.sym->attr.allocatable
11143       && gfc_expr_attr ((*code)->expr1).allocatable)
11144     {
11145       gfc_code *block;
11146       gfc_expr *cond;
11147       gfc_expr *e;
11148 
11149       e = gfc_lval_expr_from_sym ((*code)->expr1->symtree->n.sym);
11150       cond = gfc_build_intrinsic_call (ns, GFC_ISYM_ASSOCIATED, "associated",
11151 				       (*code)->loc, 2, gfc_copy_expr (t1), e);
11152       block = gfc_get_code (EXEC_IF);
11153       block->block = gfc_get_code (EXEC_IF);
11154       block->block->expr1 = cond;
11155       block->block->next = build_assignment (EXEC_POINTER_ASSIGN,
11156 					t1, gfc_get_null_expr (&(*code)->loc),
11157 					NULL, NULL, (*code)->loc);
11158       gfc_append_code (tail, block);
11159       tail = block;
11160     }
11161 
11162   /* Now attach the remaining code chain to the input code.  Step on
11163      to the end of the new code since resolution is complete.  */
11164   gcc_assert ((*code)->op == EXEC_ASSIGN);
11165   tail->next = (*code)->next;
11166   /* Overwrite 'code' because this would place the intrinsic assignment
11167      before the temporary for the lhs is created.  */
11168   gfc_free_expr ((*code)->expr1);
11169   gfc_free_expr ((*code)->expr2);
11170   **code = *head;
11171   if (head != tail)
11172     free (head);
11173   *code = tail;
11174 
11175   component_assignment_level--;
11176 }
11177 
11178 
11179 /* F2008: Pointer function assignments are of the form:
11180 	ptr_fcn (args) = expr
11181    This function breaks these assignments into two statements:
11182 	temporary_pointer => ptr_fcn(args)
11183 	temporary_pointer = expr  */
11184 
11185 static bool
11186 resolve_ptr_fcn_assign (gfc_code **code, gfc_namespace *ns)
11187 {
11188   gfc_expr *tmp_ptr_expr;
11189   gfc_code *this_code;
11190   gfc_component *comp;
11191   gfc_symbol *s;
11192 
11193   if ((*code)->expr1->expr_type != EXPR_FUNCTION)
11194     return false;
11195 
11196   /* Even if standard does not support this feature, continue to build
11197      the two statements to avoid upsetting frontend_passes.c.  */
11198   gfc_notify_std (GFC_STD_F2008, "Pointer procedure assignment at "
11199 		  "%L", &(*code)->loc);
11200 
11201   comp = gfc_get_proc_ptr_comp ((*code)->expr1);
11202 
11203   if (comp)
11204     s = comp->ts.interface;
11205   else
11206     s = (*code)->expr1->symtree->n.sym;
11207 
11208   if (s == NULL || !s->result->attr.pointer)
11209     {
11210       gfc_error ("The function result on the lhs of the assignment at "
11211 		 "%L must have the pointer attribute.",
11212 		 &(*code)->expr1->where);
11213       (*code)->op = EXEC_NOP;
11214       return false;
11215     }
11216 
11217   tmp_ptr_expr = get_temp_from_expr ((*code)->expr2, ns);
11218 
11219   /* get_temp_from_expression is set up for ordinary assignments. To that
11220      end, where array bounds are not known, arrays are made allocatable.
11221      Change the temporary to a pointer here.  */
11222   tmp_ptr_expr->symtree->n.sym->attr.pointer = 1;
11223   tmp_ptr_expr->symtree->n.sym->attr.allocatable = 0;
11224   tmp_ptr_expr->where = (*code)->loc;
11225 
11226   this_code = build_assignment (EXEC_ASSIGN,
11227 				tmp_ptr_expr, (*code)->expr2,
11228 				NULL, NULL, (*code)->loc);
11229   this_code->next = (*code)->next;
11230   (*code)->next = this_code;
11231   (*code)->op = EXEC_POINTER_ASSIGN;
11232   (*code)->expr2 = (*code)->expr1;
11233   (*code)->expr1 = tmp_ptr_expr;
11234 
11235   return true;
11236 }
11237 
11238 
11239 /* Deferred character length assignments from an operator expression
11240    require a temporary because the character length of the lhs can
11241    change in the course of the assignment.  */
11242 
11243 static bool
11244 deferred_op_assign (gfc_code **code, gfc_namespace *ns)
11245 {
11246   gfc_expr *tmp_expr;
11247   gfc_code *this_code;
11248 
11249   if (!((*code)->expr1->ts.type == BT_CHARACTER
11250 	 && (*code)->expr1->ts.deferred && (*code)->expr1->rank
11251 	 && (*code)->expr2->expr_type == EXPR_OP))
11252     return false;
11253 
11254   if (!gfc_check_dependency ((*code)->expr1, (*code)->expr2, 1))
11255     return false;
11256 
11257   if (gfc_expr_attr ((*code)->expr1).pointer)
11258     return false;
11259 
11260   tmp_expr = get_temp_from_expr ((*code)->expr1, ns);
11261   tmp_expr->where = (*code)->loc;
11262 
11263   /* A new charlen is required to ensure that the variable string
11264      length is different to that of the original lhs.  */
11265   tmp_expr->ts.u.cl = gfc_get_charlen();
11266   tmp_expr->symtree->n.sym->ts.u.cl = tmp_expr->ts.u.cl;
11267   tmp_expr->ts.u.cl->next = (*code)->expr2->ts.u.cl->next;
11268   (*code)->expr2->ts.u.cl->next = tmp_expr->ts.u.cl;
11269 
11270   tmp_expr->symtree->n.sym->ts.deferred = 1;
11271 
11272   this_code = build_assignment (EXEC_ASSIGN,
11273 				(*code)->expr1,
11274 				gfc_copy_expr (tmp_expr),
11275 				NULL, NULL, (*code)->loc);
11276 
11277   (*code)->expr1 = tmp_expr;
11278 
11279   this_code->next = (*code)->next;
11280   (*code)->next = this_code;
11281 
11282   return true;
11283 }
11284 
11285 
11286 /* Given a block of code, recursively resolve everything pointed to by this
11287    code block.  */
11288 
11289 void
11290 gfc_resolve_code (gfc_code *code, gfc_namespace *ns)
11291 {
11292   int omp_workshare_save;
11293   int forall_save, do_concurrent_save;
11294   code_stack frame;
11295   bool t;
11296 
11297   frame.prev = cs_base;
11298   frame.head = code;
11299   cs_base = &frame;
11300 
11301   find_reachable_labels (code);
11302 
11303   for (; code; code = code->next)
11304     {
11305       frame.current = code;
11306       forall_save = forall_flag;
11307       do_concurrent_save = gfc_do_concurrent_flag;
11308 
11309       if (code->op == EXEC_FORALL)
11310 	{
11311 	  forall_flag = 1;
11312 	  gfc_resolve_forall (code, ns, forall_save);
11313 	  forall_flag = 2;
11314 	}
11315       else if (code->block)
11316 	{
11317 	  omp_workshare_save = -1;
11318 	  switch (code->op)
11319 	    {
11320 	    case EXEC_OACC_PARALLEL_LOOP:
11321 	    case EXEC_OACC_PARALLEL:
11322 	    case EXEC_OACC_KERNELS_LOOP:
11323 	    case EXEC_OACC_KERNELS:
11324 	    case EXEC_OACC_DATA:
11325 	    case EXEC_OACC_HOST_DATA:
11326 	    case EXEC_OACC_LOOP:
11327 	      gfc_resolve_oacc_blocks (code, ns);
11328 	      break;
11329 	    case EXEC_OMP_PARALLEL_WORKSHARE:
11330 	      omp_workshare_save = omp_workshare_flag;
11331 	      omp_workshare_flag = 1;
11332 	      gfc_resolve_omp_parallel_blocks (code, ns);
11333 	      break;
11334 	    case EXEC_OMP_PARALLEL:
11335 	    case EXEC_OMP_PARALLEL_DO:
11336 	    case EXEC_OMP_PARALLEL_DO_SIMD:
11337 	    case EXEC_OMP_PARALLEL_SECTIONS:
11338 	    case EXEC_OMP_TARGET_PARALLEL:
11339 	    case EXEC_OMP_TARGET_PARALLEL_DO:
11340 	    case EXEC_OMP_TARGET_PARALLEL_DO_SIMD:
11341 	    case EXEC_OMP_TARGET_TEAMS:
11342 	    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
11343 	    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
11344 	    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
11345 	    case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
11346 	    case EXEC_OMP_TASK:
11347 	    case EXEC_OMP_TASKLOOP:
11348 	    case EXEC_OMP_TASKLOOP_SIMD:
11349 	    case EXEC_OMP_TEAMS:
11350 	    case EXEC_OMP_TEAMS_DISTRIBUTE:
11351 	    case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
11352 	    case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
11353 	    case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
11354 	      omp_workshare_save = omp_workshare_flag;
11355 	      omp_workshare_flag = 0;
11356 	      gfc_resolve_omp_parallel_blocks (code, ns);
11357 	      break;
11358 	    case EXEC_OMP_DISTRIBUTE:
11359 	    case EXEC_OMP_DISTRIBUTE_SIMD:
11360 	    case EXEC_OMP_DO:
11361 	    case EXEC_OMP_DO_SIMD:
11362 	    case EXEC_OMP_SIMD:
11363 	    case EXEC_OMP_TARGET_SIMD:
11364 	      gfc_resolve_omp_do_blocks (code, ns);
11365 	      break;
11366 	    case EXEC_SELECT_TYPE:
11367 	      /* Blocks are handled in resolve_select_type because we have
11368 		 to transform the SELECT TYPE into ASSOCIATE first.  */
11369 	      break;
11370             case EXEC_DO_CONCURRENT:
11371 	      gfc_do_concurrent_flag = 1;
11372 	      gfc_resolve_blocks (code->block, ns);
11373 	      gfc_do_concurrent_flag = 2;
11374 	      break;
11375 	    case EXEC_OMP_WORKSHARE:
11376 	      omp_workshare_save = omp_workshare_flag;
11377 	      omp_workshare_flag = 1;
11378 	      /* FALL THROUGH */
11379 	    default:
11380 	      gfc_resolve_blocks (code->block, ns);
11381 	      break;
11382 	    }
11383 
11384 	  if (omp_workshare_save != -1)
11385 	    omp_workshare_flag = omp_workshare_save;
11386 	}
11387 start:
11388       t = true;
11389       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
11390 	t = gfc_resolve_expr (code->expr1);
11391       forall_flag = forall_save;
11392       gfc_do_concurrent_flag = do_concurrent_save;
11393 
11394       if (!gfc_resolve_expr (code->expr2))
11395 	t = false;
11396 
11397       if (code->op == EXEC_ALLOCATE
11398 	  && !gfc_resolve_expr (code->expr3))
11399 	t = false;
11400 
11401       switch (code->op)
11402 	{
11403 	case EXEC_NOP:
11404 	case EXEC_END_BLOCK:
11405 	case EXEC_END_NESTED_BLOCK:
11406 	case EXEC_CYCLE:
11407 	case EXEC_PAUSE:
11408 	case EXEC_STOP:
11409 	case EXEC_ERROR_STOP:
11410 	case EXEC_EXIT:
11411 	case EXEC_CONTINUE:
11412 	case EXEC_DT_END:
11413 	case EXEC_ASSIGN_CALL:
11414 	  break;
11415 
11416 	case EXEC_CRITICAL:
11417 	  resolve_critical (code);
11418 	  break;
11419 
11420 	case EXEC_SYNC_ALL:
11421 	case EXEC_SYNC_IMAGES:
11422 	case EXEC_SYNC_MEMORY:
11423 	  resolve_sync (code);
11424 	  break;
11425 
11426 	case EXEC_LOCK:
11427 	case EXEC_UNLOCK:
11428 	case EXEC_EVENT_POST:
11429 	case EXEC_EVENT_WAIT:
11430 	  resolve_lock_unlock_event (code);
11431 	  break;
11432 
11433 	case EXEC_FAIL_IMAGE:
11434 	case EXEC_FORM_TEAM:
11435 	case EXEC_CHANGE_TEAM:
11436 	case EXEC_END_TEAM:
11437 	case EXEC_SYNC_TEAM:
11438 	  break;
11439 
11440 	case EXEC_ENTRY:
11441 	  /* Keep track of which entry we are up to.  */
11442 	  current_entry_id = code->ext.entry->id;
11443 	  break;
11444 
11445 	case EXEC_WHERE:
11446 	  resolve_where (code, NULL);
11447 	  break;
11448 
11449 	case EXEC_GOTO:
11450 	  if (code->expr1 != NULL)
11451 	    {
11452 	      if (code->expr1->ts.type != BT_INTEGER)
11453 		gfc_error ("ASSIGNED GOTO statement at %L requires an "
11454 			   "INTEGER variable", &code->expr1->where);
11455 	      else if (code->expr1->symtree->n.sym->attr.assign != 1)
11456 		gfc_error ("Variable %qs has not been assigned a target "
11457 			   "label at %L", code->expr1->symtree->n.sym->name,
11458 			   &code->expr1->where);
11459 	    }
11460 	  else
11461 	    resolve_branch (code->label1, code);
11462 	  break;
11463 
11464 	case EXEC_RETURN:
11465 	  if (code->expr1 != NULL
11466 		&& (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
11467 	    gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
11468 		       "INTEGER return specifier", &code->expr1->where);
11469 	  break;
11470 
11471 	case EXEC_INIT_ASSIGN:
11472 	case EXEC_END_PROCEDURE:
11473 	  break;
11474 
11475 	case EXEC_ASSIGN:
11476 	  if (!t)
11477 	    break;
11478 
11479 	  /* Remove a GFC_ISYM_CAF_GET inserted for a coindexed variable on
11480 	     the LHS.  */
11481 	  if (code->expr1->expr_type == EXPR_FUNCTION
11482 	      && code->expr1->value.function.isym
11483 	      && code->expr1->value.function.isym->id == GFC_ISYM_CAF_GET)
11484 	    remove_caf_get_intrinsic (code->expr1);
11485 
11486 	  /* If this is a pointer function in an lvalue variable context,
11487 	     the new code will have to be resolved afresh. This is also the
11488 	     case with an error, where the code is transformed into NOP to
11489 	     prevent ICEs downstream.  */
11490 	  if (resolve_ptr_fcn_assign (&code, ns)
11491 	      || code->op == EXEC_NOP)
11492 	    goto start;
11493 
11494 	  if (!gfc_check_vardef_context (code->expr1, false, false, false,
11495 					 _("assignment")))
11496 	    break;
11497 
11498 	  if (resolve_ordinary_assign (code, ns))
11499 	    {
11500 	      if (code->op == EXEC_COMPCALL)
11501 		goto compcall;
11502 	      else
11503 		goto call;
11504 	    }
11505 
11506 	  /* Check for dependencies in deferred character length array
11507 	     assignments and generate a temporary, if necessary.  */
11508 	  if (code->op == EXEC_ASSIGN && deferred_op_assign (&code, ns))
11509 	    break;
11510 
11511 	  /* F03 7.4.1.3 for non-allocatable, non-pointer components.  */
11512 	  if (code->op != EXEC_CALL && code->expr1->ts.type == BT_DERIVED
11513 	      && code->expr1->ts.u.derived
11514 	      && code->expr1->ts.u.derived->attr.defined_assign_comp)
11515 	    generate_component_assignments (&code, ns);
11516 
11517 	  break;
11518 
11519 	case EXEC_LABEL_ASSIGN:
11520 	  if (code->label1->defined == ST_LABEL_UNKNOWN)
11521 	    gfc_error ("Label %d referenced at %L is never defined",
11522 		       code->label1->value, &code->label1->where);
11523 	  if (t
11524 	      && (code->expr1->expr_type != EXPR_VARIABLE
11525 		  || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
11526 		  || code->expr1->symtree->n.sym->ts.kind
11527 		     != gfc_default_integer_kind
11528 		  || code->expr1->symtree->n.sym->as != NULL))
11529 	    gfc_error ("ASSIGN statement at %L requires a scalar "
11530 		       "default INTEGER variable", &code->expr1->where);
11531 	  break;
11532 
11533 	case EXEC_POINTER_ASSIGN:
11534 	  {
11535 	    gfc_expr* e;
11536 
11537 	    if (!t)
11538 	      break;
11539 
11540 	    /* This is both a variable definition and pointer assignment
11541 	       context, so check both of them.  For rank remapping, a final
11542 	       array ref may be present on the LHS and fool gfc_expr_attr
11543 	       used in gfc_check_vardef_context.  Remove it.  */
11544 	    e = remove_last_array_ref (code->expr1);
11545 	    t = gfc_check_vardef_context (e, true, false, false,
11546 					  _("pointer assignment"));
11547 	    if (t)
11548 	      t = gfc_check_vardef_context (e, false, false, false,
11549 					    _("pointer assignment"));
11550 	    gfc_free_expr (e);
11551 
11552 	    t = gfc_check_pointer_assign (code->expr1, code->expr2, !t) && t;
11553 
11554 	    if (!t)
11555 	      break;
11556 
11557 	    /* Assigning a class object always is a regular assign.  */
11558 	    if (code->expr2->ts.type == BT_CLASS
11559 		&& code->expr1->ts.type == BT_CLASS
11560 		&& !CLASS_DATA (code->expr2)->attr.dimension
11561 		&& !(gfc_expr_attr (code->expr1).proc_pointer
11562 		     && code->expr2->expr_type == EXPR_VARIABLE
11563 		     && code->expr2->symtree->n.sym->attr.flavor
11564 			== FL_PROCEDURE))
11565 	      code->op = EXEC_ASSIGN;
11566 	    break;
11567 	  }
11568 
11569 	case EXEC_ARITHMETIC_IF:
11570 	  {
11571 	    gfc_expr *e = code->expr1;
11572 
11573 	    gfc_resolve_expr (e);
11574 	    if (e->expr_type == EXPR_NULL)
11575 	      gfc_error ("Invalid NULL at %L", &e->where);
11576 
11577 	    if (t && (e->rank > 0
11578 		      || !(e->ts.type == BT_REAL || e->ts.type == BT_INTEGER)))
11579 	      gfc_error ("Arithmetic IF statement at %L requires a scalar "
11580 			 "REAL or INTEGER expression", &e->where);
11581 
11582 	    resolve_branch (code->label1, code);
11583 	    resolve_branch (code->label2, code);
11584 	    resolve_branch (code->label3, code);
11585 	  }
11586 	  break;
11587 
11588 	case EXEC_IF:
11589 	  if (t && code->expr1 != NULL
11590 	      && (code->expr1->ts.type != BT_LOGICAL
11591 		  || code->expr1->rank != 0))
11592 	    gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
11593 		       &code->expr1->where);
11594 	  break;
11595 
11596 	case EXEC_CALL:
11597 	call:
11598 	  resolve_call (code);
11599 	  break;
11600 
11601 	case EXEC_COMPCALL:
11602 	compcall:
11603 	  resolve_typebound_subroutine (code);
11604 	  break;
11605 
11606 	case EXEC_CALL_PPC:
11607 	  resolve_ppc_call (code);
11608 	  break;
11609 
11610 	case EXEC_SELECT:
11611 	  /* Select is complicated. Also, a SELECT construct could be
11612 	     a transformed computed GOTO.  */
11613 	  resolve_select (code, false);
11614 	  break;
11615 
11616 	case EXEC_SELECT_TYPE:
11617 	  resolve_select_type (code, ns);
11618 	  break;
11619 
11620 	case EXEC_BLOCK:
11621 	  resolve_block_construct (code);
11622 	  break;
11623 
11624 	case EXEC_DO:
11625 	  if (code->ext.iterator != NULL)
11626 	    {
11627 	      gfc_iterator *iter = code->ext.iterator;
11628 	      if (gfc_resolve_iterator (iter, true, false))
11629 		gfc_resolve_do_iterator (code, iter->var->symtree->n.sym,
11630 					 true);
11631 	    }
11632 	  break;
11633 
11634 	case EXEC_DO_WHILE:
11635 	  if (code->expr1 == NULL)
11636 	    gfc_internal_error ("gfc_resolve_code(): No expression on "
11637 				"DO WHILE");
11638 	  if (t
11639 	      && (code->expr1->rank != 0
11640 		  || code->expr1->ts.type != BT_LOGICAL))
11641 	    gfc_error ("Exit condition of DO WHILE loop at %L must be "
11642 		       "a scalar LOGICAL expression", &code->expr1->where);
11643 	  break;
11644 
11645 	case EXEC_ALLOCATE:
11646 	  if (t)
11647 	    resolve_allocate_deallocate (code, "ALLOCATE");
11648 
11649 	  break;
11650 
11651 	case EXEC_DEALLOCATE:
11652 	  if (t)
11653 	    resolve_allocate_deallocate (code, "DEALLOCATE");
11654 
11655 	  break;
11656 
11657 	case EXEC_OPEN:
11658 	  if (!gfc_resolve_open (code->ext.open))
11659 	    break;
11660 
11661 	  resolve_branch (code->ext.open->err, code);
11662 	  break;
11663 
11664 	case EXEC_CLOSE:
11665 	  if (!gfc_resolve_close (code->ext.close))
11666 	    break;
11667 
11668 	  resolve_branch (code->ext.close->err, code);
11669 	  break;
11670 
11671 	case EXEC_BACKSPACE:
11672 	case EXEC_ENDFILE:
11673 	case EXEC_REWIND:
11674 	case EXEC_FLUSH:
11675 	  if (!gfc_resolve_filepos (code->ext.filepos, &code->loc))
11676 	    break;
11677 
11678 	  resolve_branch (code->ext.filepos->err, code);
11679 	  break;
11680 
11681 	case EXEC_INQUIRE:
11682 	  if (!gfc_resolve_inquire (code->ext.inquire))
11683 	      break;
11684 
11685 	  resolve_branch (code->ext.inquire->err, code);
11686 	  break;
11687 
11688 	case EXEC_IOLENGTH:
11689 	  gcc_assert (code->ext.inquire != NULL);
11690 	  if (!gfc_resolve_inquire (code->ext.inquire))
11691 	    break;
11692 
11693 	  resolve_branch (code->ext.inquire->err, code);
11694 	  break;
11695 
11696 	case EXEC_WAIT:
11697 	  if (!gfc_resolve_wait (code->ext.wait))
11698 	    break;
11699 
11700 	  resolve_branch (code->ext.wait->err, code);
11701 	  resolve_branch (code->ext.wait->end, code);
11702 	  resolve_branch (code->ext.wait->eor, code);
11703 	  break;
11704 
11705 	case EXEC_READ:
11706 	case EXEC_WRITE:
11707 	  if (!gfc_resolve_dt (code->ext.dt, &code->loc))
11708 	    break;
11709 
11710 	  resolve_branch (code->ext.dt->err, code);
11711 	  resolve_branch (code->ext.dt->end, code);
11712 	  resolve_branch (code->ext.dt->eor, code);
11713 	  break;
11714 
11715 	case EXEC_TRANSFER:
11716 	  resolve_transfer (code);
11717 	  break;
11718 
11719 	case EXEC_DO_CONCURRENT:
11720 	case EXEC_FORALL:
11721 	  resolve_forall_iterators (code->ext.forall_iterator);
11722 
11723 	  if (code->expr1 != NULL
11724 	      && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
11725 	    gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
11726 		       "expression", &code->expr1->where);
11727 	  break;
11728 
11729 	case EXEC_OACC_PARALLEL_LOOP:
11730 	case EXEC_OACC_PARALLEL:
11731 	case EXEC_OACC_KERNELS_LOOP:
11732 	case EXEC_OACC_KERNELS:
11733 	case EXEC_OACC_DATA:
11734 	case EXEC_OACC_HOST_DATA:
11735 	case EXEC_OACC_LOOP:
11736 	case EXEC_OACC_UPDATE:
11737 	case EXEC_OACC_WAIT:
11738 	case EXEC_OACC_CACHE:
11739 	case EXEC_OACC_ENTER_DATA:
11740 	case EXEC_OACC_EXIT_DATA:
11741 	case EXEC_OACC_ATOMIC:
11742 	case EXEC_OACC_DECLARE:
11743 	  gfc_resolve_oacc_directive (code, ns);
11744 	  break;
11745 
11746 	case EXEC_OMP_ATOMIC:
11747 	case EXEC_OMP_BARRIER:
11748 	case EXEC_OMP_CANCEL:
11749 	case EXEC_OMP_CANCELLATION_POINT:
11750 	case EXEC_OMP_CRITICAL:
11751 	case EXEC_OMP_FLUSH:
11752 	case EXEC_OMP_DISTRIBUTE:
11753 	case EXEC_OMP_DISTRIBUTE_PARALLEL_DO:
11754 	case EXEC_OMP_DISTRIBUTE_PARALLEL_DO_SIMD:
11755 	case EXEC_OMP_DISTRIBUTE_SIMD:
11756 	case EXEC_OMP_DO:
11757 	case EXEC_OMP_DO_SIMD:
11758 	case EXEC_OMP_MASTER:
11759 	case EXEC_OMP_ORDERED:
11760 	case EXEC_OMP_SECTIONS:
11761 	case EXEC_OMP_SIMD:
11762 	case EXEC_OMP_SINGLE:
11763 	case EXEC_OMP_TARGET:
11764 	case EXEC_OMP_TARGET_DATA:
11765 	case EXEC_OMP_TARGET_ENTER_DATA:
11766 	case EXEC_OMP_TARGET_EXIT_DATA:
11767 	case EXEC_OMP_TARGET_PARALLEL:
11768 	case EXEC_OMP_TARGET_PARALLEL_DO:
11769 	case EXEC_OMP_TARGET_PARALLEL_DO_SIMD:
11770 	case EXEC_OMP_TARGET_SIMD:
11771 	case EXEC_OMP_TARGET_TEAMS:
11772 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
11773 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
11774 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
11775 	case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
11776 	case EXEC_OMP_TARGET_UPDATE:
11777 	case EXEC_OMP_TASK:
11778 	case EXEC_OMP_TASKGROUP:
11779 	case EXEC_OMP_TASKLOOP:
11780 	case EXEC_OMP_TASKLOOP_SIMD:
11781 	case EXEC_OMP_TASKWAIT:
11782 	case EXEC_OMP_TASKYIELD:
11783 	case EXEC_OMP_TEAMS:
11784 	case EXEC_OMP_TEAMS_DISTRIBUTE:
11785 	case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
11786 	case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
11787 	case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
11788 	case EXEC_OMP_WORKSHARE:
11789 	  gfc_resolve_omp_directive (code, ns);
11790 	  break;
11791 
11792 	case EXEC_OMP_PARALLEL:
11793 	case EXEC_OMP_PARALLEL_DO:
11794 	case EXEC_OMP_PARALLEL_DO_SIMD:
11795 	case EXEC_OMP_PARALLEL_SECTIONS:
11796 	case EXEC_OMP_PARALLEL_WORKSHARE:
11797 	  omp_workshare_save = omp_workshare_flag;
11798 	  omp_workshare_flag = 0;
11799 	  gfc_resolve_omp_directive (code, ns);
11800 	  omp_workshare_flag = omp_workshare_save;
11801 	  break;
11802 
11803 	default:
11804 	  gfc_internal_error ("gfc_resolve_code(): Bad statement code");
11805 	}
11806     }
11807 
11808   cs_base = frame.prev;
11809 }
11810 
11811 
11812 /* Resolve initial values and make sure they are compatible with
11813    the variable.  */
11814 
11815 static void
11816 resolve_values (gfc_symbol *sym)
11817 {
11818   bool t;
11819 
11820   if (sym->value == NULL)
11821     return;
11822 
11823   if (sym->value->expr_type == EXPR_STRUCTURE)
11824     t= resolve_structure_cons (sym->value, 1);
11825   else
11826     t = gfc_resolve_expr (sym->value);
11827 
11828   if (!t)
11829     return;
11830 
11831   gfc_check_assign_symbol (sym, NULL, sym->value);
11832 }
11833 
11834 
11835 /* Verify any BIND(C) derived types in the namespace so we can report errors
11836    for them once, rather than for each variable declared of that type.  */
11837 
11838 static void
11839 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
11840 {
11841   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
11842       && derived_sym->attr.is_bind_c == 1)
11843     verify_bind_c_derived_type (derived_sym);
11844 
11845   return;
11846 }
11847 
11848 
11849 /* Check the interfaces of DTIO procedures associated with derived
11850    type 'sym'.  These procedures can either have typebound bindings or
11851    can appear in DTIO generic interfaces.  */
11852 
11853 static void
11854 gfc_verify_DTIO_procedures (gfc_symbol *sym)
11855 {
11856   if (!sym || sym->attr.flavor != FL_DERIVED)
11857     return;
11858 
11859   gfc_check_dtio_interfaces (sym);
11860 
11861   return;
11862 }
11863 
11864 /* Verify that any binding labels used in a given namespace do not collide
11865    with the names or binding labels of any global symbols.  Multiple INTERFACE
11866    for the same procedure are permitted.  */
11867 
11868 static void
11869 gfc_verify_binding_labels (gfc_symbol *sym)
11870 {
11871   gfc_gsymbol *gsym;
11872   const char *module;
11873 
11874   if (!sym || !sym->attr.is_bind_c || sym->attr.is_iso_c
11875       || sym->attr.flavor == FL_DERIVED || !sym->binding_label)
11876     return;
11877 
11878   gsym = gfc_find_case_gsymbol (gfc_gsym_root, sym->binding_label);
11879 
11880   if (sym->module)
11881     module = sym->module;
11882   else if (sym->ns && sym->ns->proc_name
11883 	   && sym->ns->proc_name->attr.flavor == FL_MODULE)
11884     module = sym->ns->proc_name->name;
11885   else if (sym->ns && sym->ns->parent
11886 	   && sym->ns && sym->ns->parent->proc_name
11887 	   && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
11888     module = sym->ns->parent->proc_name->name;
11889   else
11890     module = NULL;
11891 
11892   if (!gsym
11893       || (!gsym->defined
11894 	  && (gsym->type == GSYM_FUNCTION || gsym->type == GSYM_SUBROUTINE)))
11895     {
11896       if (!gsym)
11897 	gsym = gfc_get_gsymbol (sym->binding_label, true);
11898       gsym->where = sym->declared_at;
11899       gsym->sym_name = sym->name;
11900       gsym->binding_label = sym->binding_label;
11901       gsym->ns = sym->ns;
11902       gsym->mod_name = module;
11903       if (sym->attr.function)
11904         gsym->type = GSYM_FUNCTION;
11905       else if (sym->attr.subroutine)
11906 	gsym->type = GSYM_SUBROUTINE;
11907       /* Mark as variable/procedure as defined, unless its an INTERFACE.  */
11908       gsym->defined = sym->attr.if_source != IFSRC_IFBODY;
11909       return;
11910     }
11911 
11912   if (sym->attr.flavor == FL_VARIABLE && gsym->type != GSYM_UNKNOWN)
11913     {
11914       gfc_error ("Variable %qs with binding label %qs at %L uses the same global "
11915 		 "identifier as entity at %L", sym->name,
11916 		 sym->binding_label, &sym->declared_at, &gsym->where);
11917       /* Clear the binding label to prevent checking multiple times.  */
11918       sym->binding_label = NULL;
11919       return;
11920     }
11921 
11922   if (sym->attr.flavor == FL_VARIABLE && module
11923       && (strcmp (module, gsym->mod_name) != 0
11924 	  || strcmp (sym->name, gsym->sym_name) != 0))
11925     {
11926       /* This can only happen if the variable is defined in a module - if it
11927 	 isn't the same module, reject it.  */
11928       gfc_error ("Variable %qs from module %qs with binding label %qs at %L "
11929 		 "uses the same global identifier as entity at %L from module %qs",
11930 		 sym->name, module, sym->binding_label,
11931 		 &sym->declared_at, &gsym->where, gsym->mod_name);
11932       sym->binding_label = NULL;
11933       return;
11934     }
11935 
11936   if ((sym->attr.function || sym->attr.subroutine)
11937       && ((gsym->type != GSYM_SUBROUTINE && gsym->type != GSYM_FUNCTION)
11938 	   || (gsym->defined && sym->attr.if_source != IFSRC_IFBODY))
11939       && (sym != gsym->ns->proc_name && sym->attr.entry == 0)
11940       && (module != gsym->mod_name
11941 	  || strcmp (gsym->sym_name, sym->name) != 0
11942 	  || (module && strcmp (module, gsym->mod_name) != 0)))
11943     {
11944       /* Print an error if the procedure is defined multiple times; we have to
11945 	 exclude references to the same procedure via module association or
11946 	 multiple checks for the same procedure.  */
11947       gfc_error ("Procedure %qs with binding label %qs at %L uses the same "
11948 		 "global identifier as entity at %L", sym->name,
11949 		 sym->binding_label, &sym->declared_at, &gsym->where);
11950       sym->binding_label = NULL;
11951     }
11952 }
11953 
11954 
11955 /* Resolve an index expression.  */
11956 
11957 static bool
11958 resolve_index_expr (gfc_expr *e)
11959 {
11960   if (!gfc_resolve_expr (e))
11961     return false;
11962 
11963   if (!gfc_simplify_expr (e, 0))
11964     return false;
11965 
11966   if (!gfc_specification_expr (e))
11967     return false;
11968 
11969   return true;
11970 }
11971 
11972 
11973 /* Resolve a charlen structure.  */
11974 
11975 static bool
11976 resolve_charlen (gfc_charlen *cl)
11977 {
11978   int k;
11979   bool saved_specification_expr;
11980 
11981   if (cl->resolved)
11982     return true;
11983 
11984   cl->resolved = 1;
11985   saved_specification_expr = specification_expr;
11986   specification_expr = true;
11987 
11988   if (cl->length_from_typespec)
11989     {
11990       if (!gfc_resolve_expr (cl->length))
11991 	{
11992 	  specification_expr = saved_specification_expr;
11993 	  return false;
11994 	}
11995 
11996       if (!gfc_simplify_expr (cl->length, 0))
11997 	{
11998 	  specification_expr = saved_specification_expr;
11999 	  return false;
12000 	}
12001 
12002       /* cl->length has been resolved.  It should have an integer type.  */
12003       if (cl->length->ts.type != BT_INTEGER)
12004 	{
12005 	  gfc_error ("Scalar INTEGER expression expected at %L",
12006 		     &cl->length->where);
12007 	  return false;
12008 	}
12009     }
12010   else
12011     {
12012       if (!resolve_index_expr (cl->length))
12013 	{
12014 	  specification_expr = saved_specification_expr;
12015 	  return false;
12016 	}
12017     }
12018 
12019   /* F2008, 4.4.3.2:  If the character length parameter value evaluates to
12020      a negative value, the length of character entities declared is zero.  */
12021   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
12022       && mpz_sgn (cl->length->value.integer) < 0)
12023     gfc_replace_expr (cl->length,
12024 		      gfc_get_int_expr (gfc_charlen_int_kind, NULL, 0));
12025 
12026   /* Check that the character length is not too large.  */
12027   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
12028   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
12029       && cl->length->ts.type == BT_INTEGER
12030       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
12031     {
12032       gfc_error ("String length at %L is too large", &cl->length->where);
12033       specification_expr = saved_specification_expr;
12034       return false;
12035     }
12036 
12037   specification_expr = saved_specification_expr;
12038   return true;
12039 }
12040 
12041 
12042 /* Test for non-constant shape arrays.  */
12043 
12044 static bool
12045 is_non_constant_shape_array (gfc_symbol *sym)
12046 {
12047   gfc_expr *e;
12048   int i;
12049   bool not_constant;
12050 
12051   not_constant = false;
12052   if (sym->as != NULL)
12053     {
12054       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
12055 	 has not been simplified; parameter array references.  Do the
12056 	 simplification now.  */
12057       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
12058 	{
12059 	  e = sym->as->lower[i];
12060 	  if (e && (!resolve_index_expr(e)
12061 		    || !gfc_is_constant_expr (e)))
12062 	    not_constant = true;
12063 	  e = sym->as->upper[i];
12064 	  if (e && (!resolve_index_expr(e)
12065 		    || !gfc_is_constant_expr (e)))
12066 	    not_constant = true;
12067 	}
12068     }
12069   return not_constant;
12070 }
12071 
12072 /* Given a symbol and an initialization expression, add code to initialize
12073    the symbol to the function entry.  */
12074 static void
12075 build_init_assign (gfc_symbol *sym, gfc_expr *init)
12076 {
12077   gfc_expr *lval;
12078   gfc_code *init_st;
12079   gfc_namespace *ns = sym->ns;
12080 
12081   /* Search for the function namespace if this is a contained
12082      function without an explicit result.  */
12083   if (sym->attr.function && sym == sym->result
12084       && sym->name != sym->ns->proc_name->name)
12085     {
12086       ns = ns->contained;
12087       for (;ns; ns = ns->sibling)
12088 	if (strcmp (ns->proc_name->name, sym->name) == 0)
12089 	  break;
12090     }
12091 
12092   if (ns == NULL)
12093     {
12094       gfc_free_expr (init);
12095       return;
12096     }
12097 
12098   /* Build an l-value expression for the result.  */
12099   lval = gfc_lval_expr_from_sym (sym);
12100 
12101   /* Add the code at scope entry.  */
12102   init_st = gfc_get_code (EXEC_INIT_ASSIGN);
12103   init_st->next = ns->code;
12104   ns->code = init_st;
12105 
12106   /* Assign the default initializer to the l-value.  */
12107   init_st->loc = sym->declared_at;
12108   init_st->expr1 = lval;
12109   init_st->expr2 = init;
12110 }
12111 
12112 
12113 /* Whether or not we can generate a default initializer for a symbol.  */
12114 
12115 static bool
12116 can_generate_init (gfc_symbol *sym)
12117 {
12118   symbol_attribute *a;
12119   if (!sym)
12120     return false;
12121   a = &sym->attr;
12122 
12123   /* These symbols should never have a default initialization.  */
12124   return !(
12125        a->allocatable
12126     || a->external
12127     || a->pointer
12128     || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
12129         && (CLASS_DATA (sym)->attr.class_pointer
12130             || CLASS_DATA (sym)->attr.proc_pointer))
12131     || a->in_equivalence
12132     || a->in_common
12133     || a->data
12134     || sym->module
12135     || a->cray_pointee
12136     || a->cray_pointer
12137     || sym->assoc
12138     || (!a->referenced && !a->result)
12139     || (a->dummy && a->intent != INTENT_OUT)
12140     || (a->function && sym != sym->result)
12141   );
12142 }
12143 
12144 
12145 /* Assign the default initializer to a derived type variable or result.  */
12146 
12147 static void
12148 apply_default_init (gfc_symbol *sym)
12149 {
12150   gfc_expr *init = NULL;
12151 
12152   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
12153     return;
12154 
12155   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
12156     init = gfc_generate_initializer (&sym->ts, can_generate_init (sym));
12157 
12158   if (init == NULL && sym->ts.type != BT_CLASS)
12159     return;
12160 
12161   build_init_assign (sym, init);
12162   sym->attr.referenced = 1;
12163 }
12164 
12165 
12166 /* Build an initializer for a local. Returns null if the symbol should not have
12167    a default initialization.  */
12168 
12169 static gfc_expr *
12170 build_default_init_expr (gfc_symbol *sym)
12171 {
12172   /* These symbols should never have a default initialization.  */
12173   if (sym->attr.allocatable
12174       || sym->attr.external
12175       || sym->attr.dummy
12176       || sym->attr.pointer
12177       || sym->attr.in_equivalence
12178       || sym->attr.in_common
12179       || sym->attr.data
12180       || sym->module
12181       || sym->attr.cray_pointee
12182       || sym->attr.cray_pointer
12183       || sym->assoc)
12184     return NULL;
12185 
12186   /* Get the appropriate init expression.  */
12187   return gfc_build_default_init_expr (&sym->ts, &sym->declared_at);
12188 }
12189 
12190 /* Add an initialization expression to a local variable.  */
12191 static void
12192 apply_default_init_local (gfc_symbol *sym)
12193 {
12194   gfc_expr *init = NULL;
12195 
12196   /* The symbol should be a variable or a function return value.  */
12197   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
12198       || (sym->attr.function && sym->result != sym))
12199     return;
12200 
12201   /* Try to build the initializer expression.  If we can't initialize
12202      this symbol, then init will be NULL.  */
12203   init = build_default_init_expr (sym);
12204   if (init == NULL)
12205     return;
12206 
12207   /* For saved variables, we don't want to add an initializer at function
12208      entry, so we just add a static initializer. Note that automatic variables
12209      are stack allocated even with -fno-automatic; we have also to exclude
12210      result variable, which are also nonstatic.  */
12211   if (!sym->attr.automatic
12212       && (sym->attr.save || sym->ns->save_all
12213 	  || (flag_max_stack_var_size == 0 && !sym->attr.result
12214 	      && (sym->ns->proc_name && !sym->ns->proc_name->attr.recursive)
12215 	      && (!sym->attr.dimension || !is_non_constant_shape_array (sym)))))
12216     {
12217       /* Don't clobber an existing initializer!  */
12218       gcc_assert (sym->value == NULL);
12219       sym->value = init;
12220       return;
12221     }
12222 
12223   build_init_assign (sym, init);
12224 }
12225 
12226 
12227 /* Resolution of common features of flavors variable and procedure.  */
12228 
12229 static bool
12230 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
12231 {
12232   gfc_array_spec *as;
12233 
12234   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
12235     as = CLASS_DATA (sym)->as;
12236   else
12237     as = sym->as;
12238 
12239   /* Constraints on deferred shape variable.  */
12240   if (as == NULL || as->type != AS_DEFERRED)
12241     {
12242       bool pointer, allocatable, dimension;
12243 
12244       if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
12245 	{
12246 	  pointer = CLASS_DATA (sym)->attr.class_pointer;
12247 	  allocatable = CLASS_DATA (sym)->attr.allocatable;
12248 	  dimension = CLASS_DATA (sym)->attr.dimension;
12249 	}
12250       else
12251 	{
12252 	  pointer = sym->attr.pointer && !sym->attr.select_type_temporary;
12253 	  allocatable = sym->attr.allocatable;
12254 	  dimension = sym->attr.dimension;
12255 	}
12256 
12257       if (allocatable)
12258 	{
12259 	  if (dimension && as->type != AS_ASSUMED_RANK)
12260 	    {
12261 	      gfc_error ("Allocatable array %qs at %L must have a deferred "
12262 			 "shape or assumed rank", sym->name, &sym->declared_at);
12263 	      return false;
12264 	    }
12265 	  else if (!gfc_notify_std (GFC_STD_F2003, "Scalar object "
12266 				    "%qs at %L may not be ALLOCATABLE",
12267 				    sym->name, &sym->declared_at))
12268 	    return false;
12269 	}
12270 
12271       if (pointer && dimension && as->type != AS_ASSUMED_RANK)
12272 	{
12273 	  gfc_error ("Array pointer %qs at %L must have a deferred shape or "
12274 		     "assumed rank", sym->name, &sym->declared_at);
12275 	  return false;
12276 	}
12277     }
12278   else
12279     {
12280       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
12281 	  && sym->ts.type != BT_CLASS && !sym->assoc)
12282 	{
12283 	  gfc_error ("Array %qs at %L cannot have a deferred shape",
12284 		     sym->name, &sym->declared_at);
12285 	  return false;
12286 	 }
12287     }
12288 
12289   /* Constraints on polymorphic variables.  */
12290   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
12291     {
12292       /* F03:C502.  */
12293       if (sym->attr.class_ok
12294 	  && !sym->attr.select_type_temporary
12295 	  && !UNLIMITED_POLY (sym)
12296 	  && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
12297 	{
12298 	  gfc_error ("Type %qs of CLASS variable %qs at %L is not extensible",
12299 		     CLASS_DATA (sym)->ts.u.derived->name, sym->name,
12300 		     &sym->declared_at);
12301 	  return false;
12302 	}
12303 
12304       /* F03:C509.  */
12305       /* Assume that use associated symbols were checked in the module ns.
12306 	 Class-variables that are associate-names are also something special
12307 	 and excepted from the test.  */
12308       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
12309 	{
12310 	  gfc_error ("CLASS variable %qs at %L must be dummy, allocatable "
12311 		     "or pointer", sym->name, &sym->declared_at);
12312 	  return false;
12313 	}
12314     }
12315 
12316   return true;
12317 }
12318 
12319 
12320 /* Additional checks for symbols with flavor variable and derived
12321    type.  To be called from resolve_fl_variable.  */
12322 
12323 static bool
12324 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
12325 {
12326   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
12327 
12328   /* Check to see if a derived type is blocked from being host
12329      associated by the presence of another class I symbol in the same
12330      namespace.  14.6.1.3 of the standard and the discussion on
12331      comp.lang.fortran.  */
12332   if (sym->ns != sym->ts.u.derived->ns
12333       && !sym->ts.u.derived->attr.use_assoc
12334       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
12335     {
12336       gfc_symbol *s;
12337       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
12338       if (s && s->attr.generic)
12339 	s = gfc_find_dt_in_generic (s);
12340       if (s && !gfc_fl_struct (s->attr.flavor))
12341 	{
12342 	  gfc_error ("The type %qs cannot be host associated at %L "
12343 		     "because it is blocked by an incompatible object "
12344 		     "of the same name declared at %L",
12345 		     sym->ts.u.derived->name, &sym->declared_at,
12346 		     &s->declared_at);
12347 	  return false;
12348 	}
12349     }
12350 
12351   /* 4th constraint in section 11.3: "If an object of a type for which
12352      component-initialization is specified (R429) appears in the
12353      specification-part of a module and does not have the ALLOCATABLE
12354      or POINTER attribute, the object shall have the SAVE attribute."
12355 
12356      The check for initializers is performed with
12357      gfc_has_default_initializer because gfc_default_initializer generates
12358      a hidden default for allocatable components.  */
12359   if (!(sym->value || no_init_flag) && sym->ns->proc_name
12360       && sym->ns->proc_name->attr.flavor == FL_MODULE
12361       && !(sym->ns->save_all && !sym->attr.automatic) && !sym->attr.save
12362       && !sym->attr.pointer && !sym->attr.allocatable
12363       && gfc_has_default_initializer (sym->ts.u.derived)
12364       && !gfc_notify_std (GFC_STD_F2008, "Implied SAVE for module variable "
12365 			  "%qs at %L, needed due to the default "
12366 			  "initialization", sym->name, &sym->declared_at))
12367     return false;
12368 
12369   /* Assign default initializer.  */
12370   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
12371       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
12372     sym->value = gfc_generate_initializer (&sym->ts, can_generate_init (sym));
12373 
12374   return true;
12375 }
12376 
12377 
12378 /* F2008, C402 (R401):  A colon shall not be used as a type-param-value
12379    except in the declaration of an entity or component that has the POINTER
12380    or ALLOCATABLE attribute.  */
12381 
12382 static bool
12383 deferred_requirements (gfc_symbol *sym)
12384 {
12385   if (sym->ts.deferred
12386       && !(sym->attr.pointer
12387 	   || sym->attr.allocatable
12388 	   || sym->attr.associate_var
12389 	   || sym->attr.omp_udr_artificial_var))
12390     {
12391       gfc_error ("Entity %qs at %L has a deferred type parameter and "
12392 		 "requires either the POINTER or ALLOCATABLE attribute",
12393 		 sym->name, &sym->declared_at);
12394       return false;
12395     }
12396   return true;
12397 }
12398 
12399 
12400 /* Resolve symbols with flavor variable.  */
12401 
12402 static bool
12403 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
12404 {
12405   const char *auto_save_msg = "Automatic object %qs at %L cannot have the "
12406 			      "SAVE attribute";
12407 
12408   if (!resolve_fl_var_and_proc (sym, mp_flag))
12409     return false;
12410 
12411   /* Set this flag to check that variables are parameters of all entries.
12412      This check is effected by the call to gfc_resolve_expr through
12413      is_non_constant_shape_array.  */
12414   bool saved_specification_expr = specification_expr;
12415   specification_expr = true;
12416 
12417   if (sym->ns->proc_name
12418       && (sym->ns->proc_name->attr.flavor == FL_MODULE
12419 	  || sym->ns->proc_name->attr.is_main_program)
12420       && !sym->attr.use_assoc
12421       && !sym->attr.allocatable
12422       && !sym->attr.pointer
12423       && is_non_constant_shape_array (sym))
12424     {
12425       /* F08:C541. The shape of an array defined in a main program or module
12426        * needs to be constant.  */
12427       gfc_error ("The module or main program array %qs at %L must "
12428 		 "have constant shape", sym->name, &sym->declared_at);
12429       specification_expr = saved_specification_expr;
12430       return false;
12431     }
12432 
12433   /* Constraints on deferred type parameter.  */
12434   if (!deferred_requirements (sym))
12435     return false;
12436 
12437   if (sym->ts.type == BT_CHARACTER && !sym->attr.associate_var)
12438     {
12439       /* Make sure that character string variables with assumed length are
12440 	 dummy arguments.  */
12441       gfc_expr *e = NULL;
12442 
12443       if (sym->ts.u.cl)
12444 	e = sym->ts.u.cl->length;
12445       else
12446 	return false;
12447 
12448       if (e == NULL && !sym->attr.dummy && !sym->attr.result
12449 	  && !sym->ts.deferred && !sym->attr.select_type_temporary
12450 	  && !sym->attr.omp_udr_artificial_var)
12451 	{
12452 	  gfc_error ("Entity with assumed character length at %L must be a "
12453 		     "dummy argument or a PARAMETER", &sym->declared_at);
12454 	  specification_expr = saved_specification_expr;
12455 	  return false;
12456 	}
12457 
12458       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
12459 	{
12460 	  gfc_error (auto_save_msg, sym->name, &sym->declared_at);
12461 	  specification_expr = saved_specification_expr;
12462 	  return false;
12463 	}
12464 
12465       if (!gfc_is_constant_expr (e)
12466 	  && !(e->expr_type == EXPR_VARIABLE
12467 	       && e->symtree->n.sym->attr.flavor == FL_PARAMETER))
12468 	{
12469 	  if (!sym->attr.use_assoc && sym->ns->proc_name
12470 	      && (sym->ns->proc_name->attr.flavor == FL_MODULE
12471 		  || sym->ns->proc_name->attr.is_main_program))
12472 	    {
12473 	      gfc_error ("%qs at %L must have constant character length "
12474 			"in this context", sym->name, &sym->declared_at);
12475 	      specification_expr = saved_specification_expr;
12476 	      return false;
12477 	    }
12478 	  if (sym->attr.in_common)
12479 	    {
12480 	      gfc_error ("COMMON variable %qs at %L must have constant "
12481 			 "character length", sym->name, &sym->declared_at);
12482 	      specification_expr = saved_specification_expr;
12483 	      return false;
12484 	    }
12485 	}
12486     }
12487 
12488   if (sym->value == NULL && sym->attr.referenced)
12489     apply_default_init_local (sym); /* Try to apply a default initialization.  */
12490 
12491   /* Determine if the symbol may not have an initializer.  */
12492   int no_init_flag = 0, automatic_flag = 0;
12493   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
12494       || sym->attr.intrinsic || sym->attr.result)
12495     no_init_flag = 1;
12496   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
12497 	   && is_non_constant_shape_array (sym))
12498     {
12499       no_init_flag = automatic_flag = 1;
12500 
12501       /* Also, they must not have the SAVE attribute.
12502 	 SAVE_IMPLICIT is checked below.  */
12503       if (sym->as && sym->attr.codimension)
12504 	{
12505 	  int corank = sym->as->corank;
12506 	  sym->as->corank = 0;
12507 	  no_init_flag = automatic_flag = is_non_constant_shape_array (sym);
12508 	  sym->as->corank = corank;
12509 	}
12510       if (automatic_flag && sym->attr.save == SAVE_EXPLICIT)
12511 	{
12512 	  gfc_error (auto_save_msg, sym->name, &sym->declared_at);
12513 	  specification_expr = saved_specification_expr;
12514 	  return false;
12515 	}
12516     }
12517 
12518   /* Ensure that any initializer is simplified.  */
12519   if (sym->value)
12520     gfc_simplify_expr (sym->value, 1);
12521 
12522   /* Reject illegal initializers.  */
12523   if (!sym->mark && sym->value)
12524     {
12525       if (sym->attr.allocatable || (sym->ts.type == BT_CLASS
12526 				    && CLASS_DATA (sym)->attr.allocatable))
12527 	gfc_error ("Allocatable %qs at %L cannot have an initializer",
12528 		   sym->name, &sym->declared_at);
12529       else if (sym->attr.external)
12530 	gfc_error ("External %qs at %L cannot have an initializer",
12531 		   sym->name, &sym->declared_at);
12532       else if (sym->attr.dummy
12533 	&& !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
12534 	gfc_error ("Dummy %qs at %L cannot have an initializer",
12535 		   sym->name, &sym->declared_at);
12536       else if (sym->attr.intrinsic)
12537 	gfc_error ("Intrinsic %qs at %L cannot have an initializer",
12538 		   sym->name, &sym->declared_at);
12539       else if (sym->attr.result)
12540 	gfc_error ("Function result %qs at %L cannot have an initializer",
12541 		   sym->name, &sym->declared_at);
12542       else if (automatic_flag)
12543 	gfc_error ("Automatic array %qs at %L cannot have an initializer",
12544 		   sym->name, &sym->declared_at);
12545       else
12546 	goto no_init_error;
12547       specification_expr = saved_specification_expr;
12548       return false;
12549     }
12550 
12551 no_init_error:
12552   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
12553     {
12554       bool res = resolve_fl_variable_derived (sym, no_init_flag);
12555       specification_expr = saved_specification_expr;
12556       return res;
12557     }
12558 
12559   specification_expr = saved_specification_expr;
12560   return true;
12561 }
12562 
12563 
12564 /* Compare the dummy characteristics of a module procedure interface
12565    declaration with the corresponding declaration in a submodule.  */
12566 static gfc_formal_arglist *new_formal;
12567 static char errmsg[200];
12568 
12569 static void
12570 compare_fsyms (gfc_symbol *sym)
12571 {
12572   gfc_symbol *fsym;
12573 
12574   if (sym == NULL || new_formal == NULL)
12575     return;
12576 
12577   fsym = new_formal->sym;
12578 
12579   if (sym == fsym)
12580     return;
12581 
12582   if (strcmp (sym->name, fsym->name) == 0)
12583     {
12584       if (!gfc_check_dummy_characteristics (fsym, sym, true, errmsg, 200))
12585 	gfc_error ("%s at %L", errmsg, &fsym->declared_at);
12586     }
12587 }
12588 
12589 
12590 /* Resolve a procedure.  */
12591 
12592 static bool
12593 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
12594 {
12595   gfc_formal_arglist *arg;
12596 
12597   if (sym->attr.function
12598       && !resolve_fl_var_and_proc (sym, mp_flag))
12599     return false;
12600 
12601   if (sym->ts.type == BT_CHARACTER)
12602     {
12603       gfc_charlen *cl = sym->ts.u.cl;
12604 
12605       if (cl && cl->length && gfc_is_constant_expr (cl->length)
12606 	     && !resolve_charlen (cl))
12607 	return false;
12608 
12609       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12610 	  && sym->attr.proc == PROC_ST_FUNCTION)
12611 	{
12612 	  gfc_error ("Character-valued statement function %qs at %L must "
12613 		     "have constant length", sym->name, &sym->declared_at);
12614 	  return false;
12615 	}
12616     }
12617 
12618   /* Ensure that derived type for are not of a private type.  Internal
12619      module procedures are excluded by 2.2.3.3 - i.e., they are not
12620      externally accessible and can access all the objects accessible in
12621      the host.  */
12622   if (!(sym->ns->parent && sym->ns->parent->proc_name
12623 	&& sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
12624       && gfc_check_symbol_access (sym))
12625     {
12626       gfc_interface *iface;
12627 
12628       for (arg = gfc_sym_get_dummy_args (sym); arg; arg = arg->next)
12629 	{
12630 	  if (arg->sym
12631 	      && arg->sym->ts.type == BT_DERIVED
12632 	      && !arg->sym->ts.u.derived->attr.use_assoc
12633 	      && !gfc_check_symbol_access (arg->sym->ts.u.derived)
12634 	      && !gfc_notify_std (GFC_STD_F2003, "%qs is of a PRIVATE type "
12635 				  "and cannot be a dummy argument"
12636 				  " of %qs, which is PUBLIC at %L",
12637 				  arg->sym->name, sym->name,
12638 				  &sym->declared_at))
12639 	    {
12640 	      /* Stop this message from recurring.  */
12641 	      arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
12642 	      return false;
12643 	    }
12644 	}
12645 
12646       /* PUBLIC interfaces may expose PRIVATE procedures that take types
12647 	 PRIVATE to the containing module.  */
12648       for (iface = sym->generic; iface; iface = iface->next)
12649 	{
12650 	  for (arg = gfc_sym_get_dummy_args (iface->sym); arg; arg = arg->next)
12651 	    {
12652 	      if (arg->sym
12653 		  && arg->sym->ts.type == BT_DERIVED
12654 		  && !arg->sym->ts.u.derived->attr.use_assoc
12655 		  && !gfc_check_symbol_access (arg->sym->ts.u.derived)
12656 		  && !gfc_notify_std (GFC_STD_F2003, "Procedure %qs in "
12657 				      "PUBLIC interface %qs at %L "
12658 				      "takes dummy arguments of %qs which "
12659 				      "is PRIVATE", iface->sym->name,
12660 				      sym->name, &iface->sym->declared_at,
12661 				      gfc_typename(&arg->sym->ts)))
12662 		{
12663 		  /* Stop this message from recurring.  */
12664 		  arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
12665 		  return false;
12666 		}
12667 	     }
12668 	}
12669     }
12670 
12671   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
12672       && !sym->attr.proc_pointer)
12673     {
12674       gfc_error ("Function %qs at %L cannot have an initializer",
12675 		 sym->name, &sym->declared_at);
12676 
12677       /* Make sure no second error is issued for this.  */
12678       sym->value->error = 1;
12679       return false;
12680     }
12681 
12682   /* An external symbol may not have an initializer because it is taken to be
12683      a procedure. Exception: Procedure Pointers.  */
12684   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
12685     {
12686       gfc_error ("External object %qs at %L may not have an initializer",
12687 		 sym->name, &sym->declared_at);
12688       return false;
12689     }
12690 
12691   /* An elemental function is required to return a scalar 12.7.1  */
12692   if (sym->attr.elemental && sym->attr.function
12693       && (sym->as || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)->as)))
12694     {
12695       gfc_error ("ELEMENTAL function %qs at %L must have a scalar "
12696 		 "result", sym->name, &sym->declared_at);
12697       /* Reset so that the error only occurs once.  */
12698       sym->attr.elemental = 0;
12699       return false;
12700     }
12701 
12702   if (sym->attr.proc == PROC_ST_FUNCTION
12703       && (sym->attr.allocatable || sym->attr.pointer))
12704     {
12705       gfc_error ("Statement function %qs at %L may not have pointer or "
12706 		 "allocatable attribute", sym->name, &sym->declared_at);
12707       return false;
12708     }
12709 
12710   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
12711      char-len-param shall not be array-valued, pointer-valued, recursive
12712      or pure.  ....snip... A character value of * may only be used in the
12713      following ways: (i) Dummy arg of procedure - dummy associates with
12714      actual length; (ii) To declare a named constant; or (iii) External
12715      function - but length must be declared in calling scoping unit.  */
12716   if (sym->attr.function
12717       && sym->ts.type == BT_CHARACTER && !sym->ts.deferred
12718       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
12719     {
12720       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
12721 	  || (sym->attr.recursive) || (sym->attr.pure))
12722 	{
12723 	  if (sym->as && sym->as->rank)
12724 	    gfc_error ("CHARACTER(*) function %qs at %L cannot be "
12725 		       "array-valued", sym->name, &sym->declared_at);
12726 
12727 	  if (sym->attr.pointer)
12728 	    gfc_error ("CHARACTER(*) function %qs at %L cannot be "
12729 		       "pointer-valued", sym->name, &sym->declared_at);
12730 
12731 	  if (sym->attr.pure)
12732 	    gfc_error ("CHARACTER(*) function %qs at %L cannot be "
12733 		       "pure", sym->name, &sym->declared_at);
12734 
12735 	  if (sym->attr.recursive)
12736 	    gfc_error ("CHARACTER(*) function %qs at %L cannot be "
12737 		       "recursive", sym->name, &sym->declared_at);
12738 
12739 	  return false;
12740 	}
12741 
12742       /* Appendix B.2 of the standard.  Contained functions give an
12743 	 error anyway.  Deferred character length is an F2003 feature.
12744 	 Don't warn on intrinsic conversion functions, which start
12745 	 with two underscores.  */
12746       if (!sym->attr.contained && !sym->ts.deferred
12747 	  && (sym->name[0] != '_' || sym->name[1] != '_'))
12748 	gfc_notify_std (GFC_STD_F95_OBS,
12749 			"CHARACTER(*) function %qs at %L",
12750 			sym->name, &sym->declared_at);
12751     }
12752 
12753   /* F2008, C1218.  */
12754   if (sym->attr.elemental)
12755     {
12756       if (sym->attr.proc_pointer)
12757 	{
12758 	  gfc_error ("Procedure pointer %qs at %L shall not be elemental",
12759 		     sym->name, &sym->declared_at);
12760 	  return false;
12761 	}
12762       if (sym->attr.dummy)
12763 	{
12764 	  gfc_error ("Dummy procedure %qs at %L shall not be elemental",
12765 		     sym->name, &sym->declared_at);
12766 	  return false;
12767 	}
12768     }
12769 
12770   /* F2018, C15100: "The result of an elemental function shall be scalar,
12771      and shall not have the POINTER or ALLOCATABLE attribute."  The scalar
12772      pointer is tested and caught elsewhere.  */
12773   if (sym->attr.elemental && sym->result
12774       && (sym->result->attr.allocatable || sym->result->attr.pointer))
12775     {
12776       gfc_error ("Function result variable %qs at %L of elemental "
12777 		 "function %qs shall not have an ALLOCATABLE or POINTER "
12778 		 "attribute", sym->result->name,
12779 		 &sym->result->declared_at, sym->name);
12780       return false;
12781     }
12782 
12783   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
12784     {
12785       gfc_formal_arglist *curr_arg;
12786       int has_non_interop_arg = 0;
12787 
12788       if (!verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12789 			      sym->common_block))
12790         {
12791           /* Clear these to prevent looking at them again if there was an
12792              error.  */
12793           sym->attr.is_bind_c = 0;
12794           sym->attr.is_c_interop = 0;
12795           sym->ts.is_c_interop = 0;
12796         }
12797       else
12798         {
12799           /* So far, no errors have been found.  */
12800           sym->attr.is_c_interop = 1;
12801           sym->ts.is_c_interop = 1;
12802         }
12803 
12804       curr_arg = gfc_sym_get_dummy_args (sym);
12805       while (curr_arg != NULL)
12806         {
12807           /* Skip implicitly typed dummy args here.  */
12808 	  if (curr_arg->sym && curr_arg->sym->attr.implicit_type == 0)
12809 	    if (!gfc_verify_c_interop_param (curr_arg->sym))
12810 	      /* If something is found to fail, record the fact so we
12811 		 can mark the symbol for the procedure as not being
12812 		 BIND(C) to try and prevent multiple errors being
12813 		 reported.  */
12814 	      has_non_interop_arg = 1;
12815 
12816           curr_arg = curr_arg->next;
12817         }
12818 
12819       /* See if any of the arguments were not interoperable and if so, clear
12820 	 the procedure symbol to prevent duplicate error messages.  */
12821       if (has_non_interop_arg != 0)
12822 	{
12823 	  sym->attr.is_c_interop = 0;
12824 	  sym->ts.is_c_interop = 0;
12825 	  sym->attr.is_bind_c = 0;
12826 	}
12827     }
12828 
12829   if (!sym->attr.proc_pointer)
12830     {
12831       if (sym->attr.save == SAVE_EXPLICIT)
12832 	{
12833 	  gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
12834 		     "in %qs at %L", sym->name, &sym->declared_at);
12835 	  return false;
12836 	}
12837       if (sym->attr.intent)
12838 	{
12839 	  gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
12840 		     "in %qs at %L", sym->name, &sym->declared_at);
12841 	  return false;
12842 	}
12843       if (sym->attr.subroutine && sym->attr.result)
12844 	{
12845 	  gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
12846 		     "in %qs at %L", sym->name, &sym->declared_at);
12847 	  return false;
12848 	}
12849       if (sym->attr.external && sym->attr.function && !sym->attr.module_procedure
12850 	  && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
12851 	      || sym->attr.contained))
12852 	{
12853 	  gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
12854 		     "in %qs at %L", sym->name, &sym->declared_at);
12855 	  return false;
12856 	}
12857       if (strcmp ("ppr@", sym->name) == 0)
12858 	{
12859 	  gfc_error ("Procedure pointer result %qs at %L "
12860 		     "is missing the pointer attribute",
12861 		     sym->ns->proc_name->name, &sym->declared_at);
12862 	  return false;
12863 	}
12864     }
12865 
12866   /* Assume that a procedure whose body is not known has references
12867      to external arrays.  */
12868   if (sym->attr.if_source != IFSRC_DECL)
12869     sym->attr.array_outer_dependency = 1;
12870 
12871   /* Compare the characteristics of a module procedure with the
12872      interface declaration. Ideally this would be done with
12873      gfc_compare_interfaces but, at present, the formal interface
12874      cannot be copied to the ts.interface.  */
12875   if (sym->attr.module_procedure
12876       && sym->attr.if_source == IFSRC_DECL)
12877     {
12878       gfc_symbol *iface;
12879       char name[2*GFC_MAX_SYMBOL_LEN + 1];
12880       char *module_name;
12881       char *submodule_name;
12882       strcpy (name, sym->ns->proc_name->name);
12883       module_name = strtok (name, ".");
12884       submodule_name = strtok (NULL, ".");
12885 
12886       iface = sym->tlink;
12887       sym->tlink = NULL;
12888 
12889       /* Make sure that the result uses the correct charlen for deferred
12890 	 length results.  */
12891       if (iface && sym->result
12892 	  && iface->ts.type == BT_CHARACTER
12893 	  && iface->ts.deferred)
12894 	sym->result->ts.u.cl = iface->ts.u.cl;
12895 
12896       if (iface == NULL)
12897 	goto check_formal;
12898 
12899       /* Check the procedure characteristics.  */
12900       if (sym->attr.elemental != iface->attr.elemental)
12901 	{
12902 	  gfc_error ("Mismatch in ELEMENTAL attribute between MODULE "
12903 		     "PROCEDURE at %L and its interface in %s",
12904 		     &sym->declared_at, module_name);
12905 	  return false;
12906 	}
12907 
12908       if (sym->attr.pure != iface->attr.pure)
12909 	{
12910 	  gfc_error ("Mismatch in PURE attribute between MODULE "
12911 		     "PROCEDURE at %L and its interface in %s",
12912 		     &sym->declared_at, module_name);
12913 	  return false;
12914 	}
12915 
12916       if (sym->attr.recursive != iface->attr.recursive)
12917 	{
12918 	  gfc_error ("Mismatch in RECURSIVE attribute between MODULE "
12919 		     "PROCEDURE at %L and its interface in %s",
12920 		     &sym->declared_at, module_name);
12921 	  return false;
12922 	}
12923 
12924       /* Check the result characteristics.  */
12925       if (!gfc_check_result_characteristics (sym, iface, errmsg, 200))
12926 	{
12927 	  gfc_error ("%s between the MODULE PROCEDURE declaration "
12928 		     "in MODULE %qs and the declaration at %L in "
12929 		     "(SUB)MODULE %qs",
12930 		     errmsg, module_name, &sym->declared_at,
12931 		     submodule_name ? submodule_name : module_name);
12932 	  return false;
12933 	}
12934 
12935 check_formal:
12936       /* Check the characteristics of the formal arguments.  */
12937       if (sym->formal && sym->formal_ns)
12938 	{
12939 	  for (arg = sym->formal; arg && arg->sym; arg = arg->next)
12940 	    {
12941 	      new_formal = arg;
12942 	      gfc_traverse_ns (sym->formal_ns, compare_fsyms);
12943 	    }
12944 	}
12945     }
12946   return true;
12947 }
12948 
12949 
12950 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
12951    been defined and we now know their defined arguments, check that they fulfill
12952    the requirements of the standard for procedures used as finalizers.  */
12953 
12954 static bool
12955 gfc_resolve_finalizers (gfc_symbol* derived, bool *finalizable)
12956 {
12957   gfc_finalizer* list;
12958   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
12959   bool result = true;
12960   bool seen_scalar = false;
12961   gfc_symbol *vtab;
12962   gfc_component *c;
12963   gfc_symbol *parent = gfc_get_derived_super_type (derived);
12964 
12965   if (parent)
12966     gfc_resolve_finalizers (parent, finalizable);
12967 
12968   /* Ensure that derived-type components have a their finalizers resolved.  */
12969   bool has_final = derived->f2k_derived && derived->f2k_derived->finalizers;
12970   for (c = derived->components; c; c = c->next)
12971     if (c->ts.type == BT_DERIVED
12972 	&& !c->attr.pointer && !c->attr.proc_pointer && !c->attr.allocatable)
12973       {
12974 	bool has_final2 = false;
12975 	if (!gfc_resolve_finalizers (c->ts.u.derived, &has_final2))
12976 	  return false;  /* Error.  */
12977 	has_final = has_final || has_final2;
12978       }
12979   /* Return early if not finalizable.  */
12980   if (!has_final)
12981     {
12982       if (finalizable)
12983 	*finalizable = false;
12984       return true;
12985     }
12986 
12987   /* Walk over the list of finalizer-procedures, check them, and if any one
12988      does not fit in with the standard's definition, print an error and remove
12989      it from the list.  */
12990   prev_link = &derived->f2k_derived->finalizers;
12991   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
12992     {
12993       gfc_formal_arglist *dummy_args;
12994       gfc_symbol* arg;
12995       gfc_finalizer* i;
12996       int my_rank;
12997 
12998       /* Skip this finalizer if we already resolved it.  */
12999       if (list->proc_tree)
13000 	{
13001 	  if (list->proc_tree->n.sym->formal->sym->as == NULL
13002 	      || list->proc_tree->n.sym->formal->sym->as->rank == 0)
13003 	    seen_scalar = true;
13004 	  prev_link = &(list->next);
13005 	  continue;
13006 	}
13007 
13008       /* Check this exists and is a SUBROUTINE.  */
13009       if (!list->proc_sym->attr.subroutine)
13010 	{
13011 	  gfc_error ("FINAL procedure %qs at %L is not a SUBROUTINE",
13012 		     list->proc_sym->name, &list->where);
13013 	  goto error;
13014 	}
13015 
13016       /* We should have exactly one argument.  */
13017       dummy_args = gfc_sym_get_dummy_args (list->proc_sym);
13018       if (!dummy_args || dummy_args->next)
13019 	{
13020 	  gfc_error ("FINAL procedure at %L must have exactly one argument",
13021 		     &list->where);
13022 	  goto error;
13023 	}
13024       arg = dummy_args->sym;
13025 
13026       /* This argument must be of our type.  */
13027       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
13028 	{
13029 	  gfc_error ("Argument of FINAL procedure at %L must be of type %qs",
13030 		     &arg->declared_at, derived->name);
13031 	  goto error;
13032 	}
13033 
13034       /* It must neither be a pointer nor allocatable nor optional.  */
13035       if (arg->attr.pointer)
13036 	{
13037 	  gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
13038 		     &arg->declared_at);
13039 	  goto error;
13040 	}
13041       if (arg->attr.allocatable)
13042 	{
13043 	  gfc_error ("Argument of FINAL procedure at %L must not be"
13044 		     " ALLOCATABLE", &arg->declared_at);
13045 	  goto error;
13046 	}
13047       if (arg->attr.optional)
13048 	{
13049 	  gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
13050 		     &arg->declared_at);
13051 	  goto error;
13052 	}
13053 
13054       /* It must not be INTENT(OUT).  */
13055       if (arg->attr.intent == INTENT_OUT)
13056 	{
13057 	  gfc_error ("Argument of FINAL procedure at %L must not be"
13058 		     " INTENT(OUT)", &arg->declared_at);
13059 	  goto error;
13060 	}
13061 
13062       /* Warn if the procedure is non-scalar and not assumed shape.  */
13063       if (warn_surprising && arg->as && arg->as->rank != 0
13064 	  && arg->as->type != AS_ASSUMED_SHAPE)
13065 	gfc_warning (OPT_Wsurprising,
13066 		     "Non-scalar FINAL procedure at %L should have assumed"
13067 		     " shape argument", &arg->declared_at);
13068 
13069       /* Check that it does not match in kind and rank with a FINAL procedure
13070 	 defined earlier.  To really loop over the *earlier* declarations,
13071 	 we need to walk the tail of the list as new ones were pushed at the
13072 	 front.  */
13073       /* TODO: Handle kind parameters once they are implemented.  */
13074       my_rank = (arg->as ? arg->as->rank : 0);
13075       for (i = list->next; i; i = i->next)
13076 	{
13077 	  gfc_formal_arglist *dummy_args;
13078 
13079 	  /* Argument list might be empty; that is an error signalled earlier,
13080 	     but we nevertheless continued resolving.  */
13081 	  dummy_args = gfc_sym_get_dummy_args (i->proc_sym);
13082 	  if (dummy_args)
13083 	    {
13084 	      gfc_symbol* i_arg = dummy_args->sym;
13085 	      const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
13086 	      if (i_rank == my_rank)
13087 		{
13088 		  gfc_error ("FINAL procedure %qs declared at %L has the same"
13089 			     " rank (%d) as %qs",
13090 			     list->proc_sym->name, &list->where, my_rank,
13091 			     i->proc_sym->name);
13092 		  goto error;
13093 		}
13094 	    }
13095 	}
13096 
13097 	/* Is this the/a scalar finalizer procedure?  */
13098 	if (my_rank == 0)
13099 	  seen_scalar = true;
13100 
13101 	/* Find the symtree for this procedure.  */
13102 	gcc_assert (!list->proc_tree);
13103 	list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
13104 
13105 	prev_link = &list->next;
13106 	continue;
13107 
13108 	/* Remove wrong nodes immediately from the list so we don't risk any
13109 	   troubles in the future when they might fail later expectations.  */
13110 error:
13111 	i = list;
13112 	*prev_link = list->next;
13113 	gfc_free_finalizer (i);
13114 	result = false;
13115     }
13116 
13117   if (result == false)
13118     return false;
13119 
13120   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
13121      were nodes in the list, must have been for arrays.  It is surely a good
13122      idea to have a scalar version there if there's something to finalize.  */
13123   if (warn_surprising && derived->f2k_derived->finalizers && !seen_scalar)
13124     gfc_warning (OPT_Wsurprising,
13125 		 "Only array FINAL procedures declared for derived type %qs"
13126 		 " defined at %L, suggest also scalar one",
13127 		 derived->name, &derived->declared_at);
13128 
13129   vtab = gfc_find_derived_vtab (derived);
13130   c = vtab->ts.u.derived->components->next->next->next->next->next;
13131   gfc_set_sym_referenced (c->initializer->symtree->n.sym);
13132 
13133   if (finalizable)
13134     *finalizable = true;
13135 
13136   return true;
13137 }
13138 
13139 
13140 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
13141 
13142 static bool
13143 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
13144 			     const char* generic_name, locus where)
13145 {
13146   gfc_symbol *sym1, *sym2;
13147   const char *pass1, *pass2;
13148   gfc_formal_arglist *dummy_args;
13149 
13150   gcc_assert (t1->specific && t2->specific);
13151   gcc_assert (!t1->specific->is_generic);
13152   gcc_assert (!t2->specific->is_generic);
13153   gcc_assert (t1->is_operator == t2->is_operator);
13154 
13155   sym1 = t1->specific->u.specific->n.sym;
13156   sym2 = t2->specific->u.specific->n.sym;
13157 
13158   if (sym1 == sym2)
13159     return true;
13160 
13161   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
13162   if (sym1->attr.subroutine != sym2->attr.subroutine
13163       || sym1->attr.function != sym2->attr.function)
13164     {
13165       gfc_error ("%qs and %qs cannot be mixed FUNCTION/SUBROUTINE for"
13166 		 " GENERIC %qs at %L",
13167 		 sym1->name, sym2->name, generic_name, &where);
13168       return false;
13169     }
13170 
13171   /* Determine PASS arguments.  */
13172   if (t1->specific->nopass)
13173     pass1 = NULL;
13174   else if (t1->specific->pass_arg)
13175     pass1 = t1->specific->pass_arg;
13176   else
13177     {
13178       dummy_args = gfc_sym_get_dummy_args (t1->specific->u.specific->n.sym);
13179       if (dummy_args)
13180 	pass1 = dummy_args->sym->name;
13181       else
13182 	pass1 = NULL;
13183     }
13184   if (t2->specific->nopass)
13185     pass2 = NULL;
13186   else if (t2->specific->pass_arg)
13187     pass2 = t2->specific->pass_arg;
13188   else
13189     {
13190       dummy_args = gfc_sym_get_dummy_args (t2->specific->u.specific->n.sym);
13191       if (dummy_args)
13192 	pass2 = dummy_args->sym->name;
13193       else
13194 	pass2 = NULL;
13195     }
13196 
13197   /* Compare the interfaces.  */
13198   if (gfc_compare_interfaces (sym1, sym2, sym2->name, !t1->is_operator, 0,
13199 			      NULL, 0, pass1, pass2))
13200     {
13201       gfc_error ("%qs and %qs for GENERIC %qs at %L are ambiguous",
13202 		 sym1->name, sym2->name, generic_name, &where);
13203       return false;
13204     }
13205 
13206   return true;
13207 }
13208 
13209 
13210 /* Worker function for resolving a generic procedure binding; this is used to
13211    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
13212 
13213    The difference between those cases is finding possible inherited bindings
13214    that are overridden, as one has to look for them in tb_sym_root,
13215    tb_uop_root or tb_op, respectively.  Thus the caller must already find
13216    the super-type and set p->overridden correctly.  */
13217 
13218 static bool
13219 resolve_tb_generic_targets (gfc_symbol* super_type,
13220 			    gfc_typebound_proc* p, const char* name)
13221 {
13222   gfc_tbp_generic* target;
13223   gfc_symtree* first_target;
13224   gfc_symtree* inherited;
13225 
13226   gcc_assert (p && p->is_generic);
13227 
13228   /* Try to find the specific bindings for the symtrees in our target-list.  */
13229   gcc_assert (p->u.generic);
13230   for (target = p->u.generic; target; target = target->next)
13231     if (!target->specific)
13232       {
13233 	gfc_typebound_proc* overridden_tbp;
13234 	gfc_tbp_generic* g;
13235 	const char* target_name;
13236 
13237 	target_name = target->specific_st->name;
13238 
13239 	/* Defined for this type directly.  */
13240 	if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
13241 	  {
13242 	    target->specific = target->specific_st->n.tb;
13243 	    goto specific_found;
13244 	  }
13245 
13246 	/* Look for an inherited specific binding.  */
13247 	if (super_type)
13248 	  {
13249 	    inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
13250 						 true, NULL);
13251 
13252 	    if (inherited)
13253 	      {
13254 		gcc_assert (inherited->n.tb);
13255 		target->specific = inherited->n.tb;
13256 		goto specific_found;
13257 	      }
13258 	  }
13259 
13260 	gfc_error ("Undefined specific binding %qs as target of GENERIC %qs"
13261 		   " at %L", target_name, name, &p->where);
13262 	return false;
13263 
13264 	/* Once we've found the specific binding, check it is not ambiguous with
13265 	   other specifics already found or inherited for the same GENERIC.  */
13266 specific_found:
13267 	gcc_assert (target->specific);
13268 
13269 	/* This must really be a specific binding!  */
13270 	if (target->specific->is_generic)
13271 	  {
13272 	    gfc_error ("GENERIC %qs at %L must target a specific binding,"
13273 		       " %qs is GENERIC, too", name, &p->where, target_name);
13274 	    return false;
13275 	  }
13276 
13277 	/* Check those already resolved on this type directly.  */
13278 	for (g = p->u.generic; g; g = g->next)
13279 	  if (g != target && g->specific
13280 	      && !check_generic_tbp_ambiguity (target, g, name, p->where))
13281 	    return false;
13282 
13283 	/* Check for ambiguity with inherited specific targets.  */
13284 	for (overridden_tbp = p->overridden; overridden_tbp;
13285 	     overridden_tbp = overridden_tbp->overridden)
13286 	  if (overridden_tbp->is_generic)
13287 	    {
13288 	      for (g = overridden_tbp->u.generic; g; g = g->next)
13289 		{
13290 		  gcc_assert (g->specific);
13291 		  if (!check_generic_tbp_ambiguity (target, g, name, p->where))
13292 		    return false;
13293 		}
13294 	    }
13295       }
13296 
13297   /* If we attempt to "overwrite" a specific binding, this is an error.  */
13298   if (p->overridden && !p->overridden->is_generic)
13299     {
13300       gfc_error ("GENERIC %qs at %L cannot overwrite specific binding with"
13301 		 " the same name", name, &p->where);
13302       return false;
13303     }
13304 
13305   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
13306      all must have the same attributes here.  */
13307   first_target = p->u.generic->specific->u.specific;
13308   gcc_assert (first_target);
13309   p->subroutine = first_target->n.sym->attr.subroutine;
13310   p->function = first_target->n.sym->attr.function;
13311 
13312   return true;
13313 }
13314 
13315 
13316 /* Resolve a GENERIC procedure binding for a derived type.  */
13317 
13318 static bool
13319 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
13320 {
13321   gfc_symbol* super_type;
13322 
13323   /* Find the overridden binding if any.  */
13324   st->n.tb->overridden = NULL;
13325   super_type = gfc_get_derived_super_type (derived);
13326   if (super_type)
13327     {
13328       gfc_symtree* overridden;
13329       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
13330 					    true, NULL);
13331 
13332       if (overridden && overridden->n.tb)
13333 	st->n.tb->overridden = overridden->n.tb;
13334     }
13335 
13336   /* Resolve using worker function.  */
13337   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
13338 }
13339 
13340 
13341 /* Retrieve the target-procedure of an operator binding and do some checks in
13342    common for intrinsic and user-defined type-bound operators.  */
13343 
13344 static gfc_symbol*
13345 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
13346 {
13347   gfc_symbol* target_proc;
13348 
13349   gcc_assert (target->specific && !target->specific->is_generic);
13350   target_proc = target->specific->u.specific->n.sym;
13351   gcc_assert (target_proc);
13352 
13353   /* F08:C468. All operator bindings must have a passed-object dummy argument.  */
13354   if (target->specific->nopass)
13355     {
13356       gfc_error ("Type-bound operator at %L cannot be NOPASS", &where);
13357       return NULL;
13358     }
13359 
13360   return target_proc;
13361 }
13362 
13363 
13364 /* Resolve a type-bound intrinsic operator.  */
13365 
13366 static bool
13367 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
13368 				gfc_typebound_proc* p)
13369 {
13370   gfc_symbol* super_type;
13371   gfc_tbp_generic* target;
13372 
13373   /* If there's already an error here, do nothing (but don't fail again).  */
13374   if (p->error)
13375     return true;
13376 
13377   /* Operators should always be GENERIC bindings.  */
13378   gcc_assert (p->is_generic);
13379 
13380   /* Look for an overridden binding.  */
13381   super_type = gfc_get_derived_super_type (derived);
13382   if (super_type && super_type->f2k_derived)
13383     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
13384 						     op, true, NULL);
13385   else
13386     p->overridden = NULL;
13387 
13388   /* Resolve general GENERIC properties using worker function.  */
13389   if (!resolve_tb_generic_targets (super_type, p, gfc_op2string(op)))
13390     goto error;
13391 
13392   /* Check the targets to be procedures of correct interface.  */
13393   for (target = p->u.generic; target; target = target->next)
13394     {
13395       gfc_symbol* target_proc;
13396 
13397       target_proc = get_checked_tb_operator_target (target, p->where);
13398       if (!target_proc)
13399 	goto error;
13400 
13401       if (!gfc_check_operator_interface (target_proc, op, p->where))
13402 	goto error;
13403 
13404       /* Add target to non-typebound operator list.  */
13405       if (!target->specific->deferred && !derived->attr.use_assoc
13406 	  && p->access != ACCESS_PRIVATE && derived->ns == gfc_current_ns)
13407 	{
13408 	  gfc_interface *head, *intr;
13409 
13410 	  /* Preempt 'gfc_check_new_interface' for submodules, where the
13411 	     mechanism for handling module procedures winds up resolving
13412 	     operator interfaces twice and would otherwise cause an error.  */
13413 	  for (intr = derived->ns->op[op]; intr; intr = intr->next)
13414 	    if (intr->sym == target_proc
13415 		&& target_proc->attr.used_in_submodule)
13416 	      return true;
13417 
13418 	  if (!gfc_check_new_interface (derived->ns->op[op],
13419 					target_proc, p->where))
13420 	    return false;
13421 	  head = derived->ns->op[op];
13422 	  intr = gfc_get_interface ();
13423 	  intr->sym = target_proc;
13424 	  intr->where = p->where;
13425 	  intr->next = head;
13426 	  derived->ns->op[op] = intr;
13427 	}
13428     }
13429 
13430   return true;
13431 
13432 error:
13433   p->error = 1;
13434   return false;
13435 }
13436 
13437 
13438 /* Resolve a type-bound user operator (tree-walker callback).  */
13439 
13440 static gfc_symbol* resolve_bindings_derived;
13441 static bool resolve_bindings_result;
13442 
13443 static bool check_uop_procedure (gfc_symbol* sym, locus where);
13444 
13445 static void
13446 resolve_typebound_user_op (gfc_symtree* stree)
13447 {
13448   gfc_symbol* super_type;
13449   gfc_tbp_generic* target;
13450 
13451   gcc_assert (stree && stree->n.tb);
13452 
13453   if (stree->n.tb->error)
13454     return;
13455 
13456   /* Operators should always be GENERIC bindings.  */
13457   gcc_assert (stree->n.tb->is_generic);
13458 
13459   /* Find overridden procedure, if any.  */
13460   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
13461   if (super_type && super_type->f2k_derived)
13462     {
13463       gfc_symtree* overridden;
13464       overridden = gfc_find_typebound_user_op (super_type, NULL,
13465 					       stree->name, true, NULL);
13466 
13467       if (overridden && overridden->n.tb)
13468 	stree->n.tb->overridden = overridden->n.tb;
13469     }
13470   else
13471     stree->n.tb->overridden = NULL;
13472 
13473   /* Resolve basically using worker function.  */
13474   if (!resolve_tb_generic_targets (super_type, stree->n.tb, stree->name))
13475     goto error;
13476 
13477   /* Check the targets to be functions of correct interface.  */
13478   for (target = stree->n.tb->u.generic; target; target = target->next)
13479     {
13480       gfc_symbol* target_proc;
13481 
13482       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
13483       if (!target_proc)
13484 	goto error;
13485 
13486       if (!check_uop_procedure (target_proc, stree->n.tb->where))
13487 	goto error;
13488     }
13489 
13490   return;
13491 
13492 error:
13493   resolve_bindings_result = false;
13494   stree->n.tb->error = 1;
13495 }
13496 
13497 
13498 /* Resolve the type-bound procedures for a derived type.  */
13499 
13500 static void
13501 resolve_typebound_procedure (gfc_symtree* stree)
13502 {
13503   gfc_symbol* proc;
13504   locus where;
13505   gfc_symbol* me_arg;
13506   gfc_symbol* super_type;
13507   gfc_component* comp;
13508 
13509   gcc_assert (stree);
13510 
13511   /* Undefined specific symbol from GENERIC target definition.  */
13512   if (!stree->n.tb)
13513     return;
13514 
13515   if (stree->n.tb->error)
13516     return;
13517 
13518   /* If this is a GENERIC binding, use that routine.  */
13519   if (stree->n.tb->is_generic)
13520     {
13521       if (!resolve_typebound_generic (resolve_bindings_derived, stree))
13522 	goto error;
13523       return;
13524     }
13525 
13526   /* Get the target-procedure to check it.  */
13527   gcc_assert (!stree->n.tb->is_generic);
13528   gcc_assert (stree->n.tb->u.specific);
13529   proc = stree->n.tb->u.specific->n.sym;
13530   where = stree->n.tb->where;
13531 
13532   /* Default access should already be resolved from the parser.  */
13533   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
13534 
13535   if (stree->n.tb->deferred)
13536     {
13537       if (!check_proc_interface (proc, &where))
13538 	goto error;
13539     }
13540   else
13541     {
13542       /* If proc has not been resolved at this point, proc->name may
13543 	 actually be a USE associated entity. See PR fortran/89647. */
13544       if (!proc->resolved
13545 	  && proc->attr.function == 0 && proc->attr.subroutine == 0)
13546 	{
13547 	  gfc_symbol *tmp;
13548 	  gfc_find_symbol (proc->name, gfc_current_ns->parent, 1, &tmp);
13549 	  if (tmp && tmp->attr.use_assoc)
13550 	    {
13551 	      proc->module = tmp->module;
13552 	      proc->attr.proc = tmp->attr.proc;
13553 	      proc->attr.function = tmp->attr.function;
13554 	      proc->attr.subroutine = tmp->attr.subroutine;
13555 	      proc->attr.use_assoc = tmp->attr.use_assoc;
13556 	      proc->ts = tmp->ts;
13557 	      proc->result = tmp->result;
13558 	    }
13559 	}
13560 
13561       /* Check for F08:C465.  */
13562       if ((!proc->attr.subroutine && !proc->attr.function)
13563 	  || (proc->attr.proc != PROC_MODULE
13564 	      && proc->attr.if_source != IFSRC_IFBODY)
13565 	  || proc->attr.abstract)
13566 	{
13567 	  gfc_error ("%qs must be a module procedure or an external "
13568 		     "procedure with an explicit interface at %L",
13569 		     proc->name, &where);
13570 	  goto error;
13571 	}
13572     }
13573 
13574   stree->n.tb->subroutine = proc->attr.subroutine;
13575   stree->n.tb->function = proc->attr.function;
13576 
13577   /* Find the super-type of the current derived type.  We could do this once and
13578      store in a global if speed is needed, but as long as not I believe this is
13579      more readable and clearer.  */
13580   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
13581 
13582   /* If PASS, resolve and check arguments if not already resolved / loaded
13583      from a .mod file.  */
13584   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
13585     {
13586       gfc_formal_arglist *dummy_args;
13587 
13588       dummy_args = gfc_sym_get_dummy_args (proc);
13589       if (stree->n.tb->pass_arg)
13590 	{
13591 	  gfc_formal_arglist *i;
13592 
13593 	  /* If an explicit passing argument name is given, walk the arg-list
13594 	     and look for it.  */
13595 
13596 	  me_arg = NULL;
13597 	  stree->n.tb->pass_arg_num = 1;
13598 	  for (i = dummy_args; i; i = i->next)
13599 	    {
13600 	      if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
13601 		{
13602 		  me_arg = i->sym;
13603 		  break;
13604 		}
13605 	      ++stree->n.tb->pass_arg_num;
13606 	    }
13607 
13608 	  if (!me_arg)
13609 	    {
13610 	      gfc_error ("Procedure %qs with PASS(%s) at %L has no"
13611 			 " argument %qs",
13612 			 proc->name, stree->n.tb->pass_arg, &where,
13613 			 stree->n.tb->pass_arg);
13614 	      goto error;
13615 	    }
13616 	}
13617       else
13618 	{
13619 	  /* Otherwise, take the first one; there should in fact be at least
13620 	     one.  */
13621 	  stree->n.tb->pass_arg_num = 1;
13622 	  if (!dummy_args)
13623 	    {
13624 	      gfc_error ("Procedure %qs with PASS at %L must have at"
13625 			 " least one argument", proc->name, &where);
13626 	      goto error;
13627 	    }
13628 	  me_arg = dummy_args->sym;
13629 	}
13630 
13631       /* Now check that the argument-type matches and the passed-object
13632 	 dummy argument is generally fine.  */
13633 
13634       gcc_assert (me_arg);
13635 
13636       if (me_arg->ts.type != BT_CLASS)
13637 	{
13638 	  gfc_error ("Non-polymorphic passed-object dummy argument of %qs"
13639 		     " at %L", proc->name, &where);
13640 	  goto error;
13641 	}
13642 
13643       if (CLASS_DATA (me_arg)->ts.u.derived
13644 	  != resolve_bindings_derived)
13645 	{
13646 	  gfc_error ("Argument %qs of %qs with PASS(%s) at %L must be of"
13647 		     " the derived-type %qs", me_arg->name, proc->name,
13648 		     me_arg->name, &where, resolve_bindings_derived->name);
13649 	  goto error;
13650 	}
13651 
13652       gcc_assert (me_arg->ts.type == BT_CLASS);
13653       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank != 0)
13654 	{
13655 	  gfc_error ("Passed-object dummy argument of %qs at %L must be"
13656 		     " scalar", proc->name, &where);
13657 	  goto error;
13658 	}
13659       if (CLASS_DATA (me_arg)->attr.allocatable)
13660 	{
13661 	  gfc_error ("Passed-object dummy argument of %qs at %L must not"
13662 		     " be ALLOCATABLE", proc->name, &where);
13663 	  goto error;
13664 	}
13665       if (CLASS_DATA (me_arg)->attr.class_pointer)
13666 	{
13667 	  gfc_error ("Passed-object dummy argument of %qs at %L must not"
13668 		     " be POINTER", proc->name, &where);
13669 	  goto error;
13670 	}
13671     }
13672 
13673   /* If we are extending some type, check that we don't override a procedure
13674      flagged NON_OVERRIDABLE.  */
13675   stree->n.tb->overridden = NULL;
13676   if (super_type)
13677     {
13678       gfc_symtree* overridden;
13679       overridden = gfc_find_typebound_proc (super_type, NULL,
13680 					    stree->name, true, NULL);
13681 
13682       if (overridden)
13683 	{
13684 	  if (overridden->n.tb)
13685 	    stree->n.tb->overridden = overridden->n.tb;
13686 
13687 	  if (!gfc_check_typebound_override (stree, overridden))
13688 	    goto error;
13689 	}
13690     }
13691 
13692   /* See if there's a name collision with a component directly in this type.  */
13693   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
13694     if (!strcmp (comp->name, stree->name))
13695       {
13696 	gfc_error ("Procedure %qs at %L has the same name as a component of"
13697 		   " %qs",
13698 		   stree->name, &where, resolve_bindings_derived->name);
13699 	goto error;
13700       }
13701 
13702   /* Try to find a name collision with an inherited component.  */
13703   if (super_type && gfc_find_component (super_type, stree->name, true, true,
13704                                         NULL))
13705     {
13706       gfc_error ("Procedure %qs at %L has the same name as an inherited"
13707 		 " component of %qs",
13708 		 stree->name, &where, resolve_bindings_derived->name);
13709       goto error;
13710     }
13711 
13712   stree->n.tb->error = 0;
13713   return;
13714 
13715 error:
13716   resolve_bindings_result = false;
13717   stree->n.tb->error = 1;
13718 }
13719 
13720 
13721 static bool
13722 resolve_typebound_procedures (gfc_symbol* derived)
13723 {
13724   int op;
13725   gfc_symbol* super_type;
13726 
13727   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
13728     return true;
13729 
13730   super_type = gfc_get_derived_super_type (derived);
13731   if (super_type)
13732     resolve_symbol (super_type);
13733 
13734   resolve_bindings_derived = derived;
13735   resolve_bindings_result = true;
13736 
13737   if (derived->f2k_derived->tb_sym_root)
13738     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
13739 			  &resolve_typebound_procedure);
13740 
13741   if (derived->f2k_derived->tb_uop_root)
13742     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
13743 			  &resolve_typebound_user_op);
13744 
13745   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
13746     {
13747       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
13748       if (p && !resolve_typebound_intrinsic_op (derived,
13749 						(gfc_intrinsic_op)op, p))
13750 	resolve_bindings_result = false;
13751     }
13752 
13753   return resolve_bindings_result;
13754 }
13755 
13756 
13757 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
13758    to give all identical derived types the same backend_decl.  */
13759 static void
13760 add_dt_to_dt_list (gfc_symbol *derived)
13761 {
13762   if (!derived->dt_next)
13763     {
13764       if (gfc_derived_types)
13765 	{
13766 	  derived->dt_next = gfc_derived_types->dt_next;
13767 	  gfc_derived_types->dt_next = derived;
13768 	}
13769       else
13770 	{
13771 	  derived->dt_next = derived;
13772 	}
13773       gfc_derived_types = derived;
13774     }
13775 }
13776 
13777 
13778 /* Ensure that a derived-type is really not abstract, meaning that every
13779    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
13780 
13781 static bool
13782 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
13783 {
13784   if (!st)
13785     return true;
13786 
13787   if (!ensure_not_abstract_walker (sub, st->left))
13788     return false;
13789   if (!ensure_not_abstract_walker (sub, st->right))
13790     return false;
13791 
13792   if (st->n.tb && st->n.tb->deferred)
13793     {
13794       gfc_symtree* overriding;
13795       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
13796       if (!overriding)
13797 	return false;
13798       gcc_assert (overriding->n.tb);
13799       if (overriding->n.tb->deferred)
13800 	{
13801 	  gfc_error ("Derived-type %qs declared at %L must be ABSTRACT because"
13802 		     " %qs is DEFERRED and not overridden",
13803 		     sub->name, &sub->declared_at, st->name);
13804 	  return false;
13805 	}
13806     }
13807 
13808   return true;
13809 }
13810 
13811 static bool
13812 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
13813 {
13814   /* The algorithm used here is to recursively travel up the ancestry of sub
13815      and for each ancestor-type, check all bindings.  If any of them is
13816      DEFERRED, look it up starting from sub and see if the found (overriding)
13817      binding is not DEFERRED.
13818      This is not the most efficient way to do this, but it should be ok and is
13819      clearer than something sophisticated.  */
13820 
13821   gcc_assert (ancestor && !sub->attr.abstract);
13822 
13823   if (!ancestor->attr.abstract)
13824     return true;
13825 
13826   /* Walk bindings of this ancestor.  */
13827   if (ancestor->f2k_derived)
13828     {
13829       bool t;
13830       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
13831       if (!t)
13832 	return false;
13833     }
13834 
13835   /* Find next ancestor type and recurse on it.  */
13836   ancestor = gfc_get_derived_super_type (ancestor);
13837   if (ancestor)
13838     return ensure_not_abstract (sub, ancestor);
13839 
13840   return true;
13841 }
13842 
13843 
13844 /* This check for typebound defined assignments is done recursively
13845    since the order in which derived types are resolved is not always in
13846    order of the declarations.  */
13847 
13848 static void
13849 check_defined_assignments (gfc_symbol *derived)
13850 {
13851   gfc_component *c;
13852 
13853   for (c = derived->components; c; c = c->next)
13854     {
13855       if (!gfc_bt_struct (c->ts.type)
13856 	  || c->attr.pointer
13857 	  || c->attr.allocatable
13858 	  || c->attr.proc_pointer_comp
13859 	  || c->attr.class_pointer
13860 	  || c->attr.proc_pointer)
13861 	continue;
13862 
13863       if (c->ts.u.derived->attr.defined_assign_comp
13864 	  || (c->ts.u.derived->f2k_derived
13865 	     && c->ts.u.derived->f2k_derived->tb_op[INTRINSIC_ASSIGN]))
13866 	{
13867 	  derived->attr.defined_assign_comp = 1;
13868 	  return;
13869 	}
13870 
13871       check_defined_assignments (c->ts.u.derived);
13872       if (c->ts.u.derived->attr.defined_assign_comp)
13873 	{
13874 	  derived->attr.defined_assign_comp = 1;
13875 	  return;
13876 	}
13877     }
13878 }
13879 
13880 
13881 /* Resolve a single component of a derived type or structure.  */
13882 
13883 static bool
13884 resolve_component (gfc_component *c, gfc_symbol *sym)
13885 {
13886   gfc_symbol *super_type;
13887   symbol_attribute *attr;
13888 
13889   if (c->attr.artificial)
13890     return true;
13891 
13892   /* Do not allow vtype components to be resolved in nameless namespaces
13893      such as block data because the procedure pointers will cause ICEs
13894      and vtables are not needed in these contexts.  */
13895   if (sym->attr.vtype && sym->attr.use_assoc
13896       && sym->ns->proc_name == NULL)
13897     return true;
13898 
13899   /* F2008, C442.  */
13900   if ((!sym->attr.is_class || c != sym->components)
13901       && c->attr.codimension
13902       && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
13903     {
13904       gfc_error ("Coarray component %qs at %L must be allocatable with "
13905                  "deferred shape", c->name, &c->loc);
13906       return false;
13907     }
13908 
13909   /* F2008, C443.  */
13910   if (c->attr.codimension && c->ts.type == BT_DERIVED
13911       && c->ts.u.derived->ts.is_iso_c)
13912     {
13913       gfc_error ("Component %qs at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
13914                  "shall not be a coarray", c->name, &c->loc);
13915       return false;
13916     }
13917 
13918   /* F2008, C444.  */
13919   if (gfc_bt_struct (c->ts.type) && c->ts.u.derived->attr.coarray_comp
13920       && (c->attr.codimension || c->attr.pointer || c->attr.dimension
13921           || c->attr.allocatable))
13922     {
13923       gfc_error ("Component %qs at %L with coarray component "
13924                  "shall be a nonpointer, nonallocatable scalar",
13925                  c->name, &c->loc);
13926       return false;
13927     }
13928 
13929   /* F2008, C448.  */
13930   if (c->ts.type == BT_CLASS)
13931     {
13932       if (CLASS_DATA (c))
13933 	{
13934 	  attr = &(CLASS_DATA (c)->attr);
13935 
13936 	  /* Fix up contiguous attribute.  */
13937 	  if (c->attr.contiguous)
13938 	    attr->contiguous = 1;
13939 	}
13940       else
13941 	attr = NULL;
13942     }
13943   else
13944     attr = &c->attr;
13945 
13946   if (attr && attr->contiguous && (!attr->dimension || !attr->pointer))
13947     {
13948       gfc_error ("Component %qs at %L has the CONTIGUOUS attribute but "
13949                  "is not an array pointer", c->name, &c->loc);
13950       return false;
13951     }
13952 
13953   /* F2003, 15.2.1 - length has to be one.  */
13954   if (sym->attr.is_bind_c && c->ts.type == BT_CHARACTER
13955       && (c->ts.u.cl == NULL || c->ts.u.cl->length == NULL
13956 	  || !gfc_is_constant_expr (c->ts.u.cl->length)
13957 	  || mpz_cmp_si (c->ts.u.cl->length->value.integer, 1) != 0))
13958     {
13959       gfc_error ("Component %qs of BIND(C) type at %L must have length one",
13960 		 c->name, &c->loc);
13961       return false;
13962     }
13963 
13964   if (c->attr.proc_pointer && c->ts.interface)
13965     {
13966       gfc_symbol *ifc = c->ts.interface;
13967 
13968       if (!sym->attr.vtype && !check_proc_interface (ifc, &c->loc))
13969         {
13970           c->tb->error = 1;
13971           return false;
13972         }
13973 
13974       if (ifc->attr.if_source || ifc->attr.intrinsic)
13975         {
13976           /* Resolve interface and copy attributes.  */
13977           if (ifc->formal && !ifc->formal_ns)
13978             resolve_symbol (ifc);
13979           if (ifc->attr.intrinsic)
13980             gfc_resolve_intrinsic (ifc, &ifc->declared_at);
13981 
13982           if (ifc->result)
13983             {
13984               c->ts = ifc->result->ts;
13985               c->attr.allocatable = ifc->result->attr.allocatable;
13986               c->attr.pointer = ifc->result->attr.pointer;
13987               c->attr.dimension = ifc->result->attr.dimension;
13988               c->as = gfc_copy_array_spec (ifc->result->as);
13989               c->attr.class_ok = ifc->result->attr.class_ok;
13990             }
13991           else
13992             {
13993               c->ts = ifc->ts;
13994               c->attr.allocatable = ifc->attr.allocatable;
13995               c->attr.pointer = ifc->attr.pointer;
13996               c->attr.dimension = ifc->attr.dimension;
13997               c->as = gfc_copy_array_spec (ifc->as);
13998               c->attr.class_ok = ifc->attr.class_ok;
13999             }
14000           c->ts.interface = ifc;
14001           c->attr.function = ifc->attr.function;
14002           c->attr.subroutine = ifc->attr.subroutine;
14003 
14004           c->attr.pure = ifc->attr.pure;
14005           c->attr.elemental = ifc->attr.elemental;
14006           c->attr.recursive = ifc->attr.recursive;
14007           c->attr.always_explicit = ifc->attr.always_explicit;
14008           c->attr.ext_attr |= ifc->attr.ext_attr;
14009           /* Copy char length.  */
14010           if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
14011             {
14012               gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
14013               if (cl->length && !cl->resolved
14014                   && !gfc_resolve_expr (cl->length))
14015                 {
14016                   c->tb->error = 1;
14017                   return false;
14018                 }
14019               c->ts.u.cl = cl;
14020             }
14021         }
14022     }
14023   else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
14024     {
14025       /* Since PPCs are not implicitly typed, a PPC without an explicit
14026          interface must be a subroutine.  */
14027       gfc_add_subroutine (&c->attr, c->name, &c->loc);
14028     }
14029 
14030   /* Procedure pointer components: Check PASS arg.  */
14031   if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
14032       && !sym->attr.vtype)
14033     {
14034       gfc_symbol* me_arg;
14035 
14036       if (c->tb->pass_arg)
14037         {
14038           gfc_formal_arglist* i;
14039 
14040           /* If an explicit passing argument name is given, walk the arg-list
14041             and look for it.  */
14042 
14043           me_arg = NULL;
14044           c->tb->pass_arg_num = 1;
14045           for (i = c->ts.interface->formal; i; i = i->next)
14046             {
14047               if (!strcmp (i->sym->name, c->tb->pass_arg))
14048                 {
14049                   me_arg = i->sym;
14050                   break;
14051                 }
14052               c->tb->pass_arg_num++;
14053             }
14054 
14055           if (!me_arg)
14056             {
14057               gfc_error ("Procedure pointer component %qs with PASS(%s) "
14058                          "at %L has no argument %qs", c->name,
14059                          c->tb->pass_arg, &c->loc, c->tb->pass_arg);
14060               c->tb->error = 1;
14061               return false;
14062             }
14063         }
14064       else
14065         {
14066           /* Otherwise, take the first one; there should in fact be at least
14067             one.  */
14068           c->tb->pass_arg_num = 1;
14069           if (!c->ts.interface->formal)
14070             {
14071               gfc_error ("Procedure pointer component %qs with PASS at %L "
14072                          "must have at least one argument",
14073                          c->name, &c->loc);
14074               c->tb->error = 1;
14075               return false;
14076             }
14077           me_arg = c->ts.interface->formal->sym;
14078         }
14079 
14080       /* Now check that the argument-type matches.  */
14081       gcc_assert (me_arg);
14082       if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
14083           || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
14084           || (me_arg->ts.type == BT_CLASS
14085               && CLASS_DATA (me_arg)->ts.u.derived != sym))
14086         {
14087           gfc_error ("Argument %qs of %qs with PASS(%s) at %L must be of"
14088                      " the derived type %qs", me_arg->name, c->name,
14089                      me_arg->name, &c->loc, sym->name);
14090           c->tb->error = 1;
14091           return false;
14092         }
14093 
14094       /* Check for F03:C453.  */
14095       if (CLASS_DATA (me_arg)->attr.dimension)
14096         {
14097           gfc_error ("Argument %qs of %qs with PASS(%s) at %L "
14098                      "must be scalar", me_arg->name, c->name, me_arg->name,
14099                      &c->loc);
14100           c->tb->error = 1;
14101           return false;
14102         }
14103 
14104       if (CLASS_DATA (me_arg)->attr.class_pointer)
14105         {
14106           gfc_error ("Argument %qs of %qs with PASS(%s) at %L "
14107                      "may not have the POINTER attribute", me_arg->name,
14108                      c->name, me_arg->name, &c->loc);
14109           c->tb->error = 1;
14110           return false;
14111         }
14112 
14113       if (CLASS_DATA (me_arg)->attr.allocatable)
14114         {
14115           gfc_error ("Argument %qs of %qs with PASS(%s) at %L "
14116                      "may not be ALLOCATABLE", me_arg->name, c->name,
14117                      me_arg->name, &c->loc);
14118           c->tb->error = 1;
14119           return false;
14120         }
14121 
14122       if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
14123         {
14124           gfc_error ("Non-polymorphic passed-object dummy argument of %qs"
14125                      " at %L", c->name, &c->loc);
14126           return false;
14127         }
14128 
14129     }
14130 
14131   /* Check type-spec if this is not the parent-type component.  */
14132   if (((sym->attr.is_class
14133         && (!sym->components->ts.u.derived->attr.extension
14134             || c != sym->components->ts.u.derived->components))
14135        || (!sym->attr.is_class
14136            && (!sym->attr.extension || c != sym->components)))
14137       && !sym->attr.vtype
14138       && !resolve_typespec_used (&c->ts, &c->loc, c->name))
14139     return false;
14140 
14141   super_type = gfc_get_derived_super_type (sym);
14142 
14143   /* If this type is an extension, set the accessibility of the parent
14144      component.  */
14145   if (super_type
14146       && ((sym->attr.is_class
14147            && c == sym->components->ts.u.derived->components)
14148           || (!sym->attr.is_class && c == sym->components))
14149       && strcmp (super_type->name, c->name) == 0)
14150     c->attr.access = super_type->attr.access;
14151 
14152   /* If this type is an extension, see if this component has the same name
14153      as an inherited type-bound procedure.  */
14154   if (super_type && !sym->attr.is_class
14155       && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
14156     {
14157       gfc_error ("Component %qs of %qs at %L has the same name as an"
14158                  " inherited type-bound procedure",
14159                  c->name, sym->name, &c->loc);
14160       return false;
14161     }
14162 
14163   if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
14164         && !c->ts.deferred)
14165     {
14166      if (c->ts.u.cl->length == NULL
14167          || (!resolve_charlen(c->ts.u.cl))
14168          || !gfc_is_constant_expr (c->ts.u.cl->length))
14169        {
14170          gfc_error ("Character length of component %qs needs to "
14171                     "be a constant specification expression at %L",
14172                     c->name,
14173                     c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
14174          return false;
14175        }
14176     }
14177 
14178   if (c->ts.type == BT_CHARACTER && c->ts.deferred
14179       && !c->attr.pointer && !c->attr.allocatable)
14180     {
14181       gfc_error ("Character component %qs of %qs at %L with deferred "
14182                  "length must be a POINTER or ALLOCATABLE",
14183                  c->name, sym->name, &c->loc);
14184       return false;
14185     }
14186 
14187   /* Add the hidden deferred length field.  */
14188   if (c->ts.type == BT_CHARACTER
14189       && (c->ts.deferred || c->attr.pdt_string)
14190       && !c->attr.function
14191       && !sym->attr.is_class)
14192     {
14193       char name[GFC_MAX_SYMBOL_LEN+9];
14194       gfc_component *strlen;
14195       sprintf (name, "_%s_length", c->name);
14196       strlen = gfc_find_component (sym, name, true, true, NULL);
14197       if (strlen == NULL)
14198         {
14199           if (!gfc_add_component (sym, name, &strlen))
14200             return false;
14201           strlen->ts.type = BT_INTEGER;
14202           strlen->ts.kind = gfc_charlen_int_kind;
14203           strlen->attr.access = ACCESS_PRIVATE;
14204           strlen->attr.artificial = 1;
14205         }
14206     }
14207 
14208   if (c->ts.type == BT_DERIVED
14209       && sym->component_access != ACCESS_PRIVATE
14210       && gfc_check_symbol_access (sym)
14211       && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
14212       && !c->ts.u.derived->attr.use_assoc
14213       && !gfc_check_symbol_access (c->ts.u.derived)
14214       && !gfc_notify_std (GFC_STD_F2003, "the component %qs is a "
14215                           "PRIVATE type and cannot be a component of "
14216                           "%qs, which is PUBLIC at %L", c->name,
14217                           sym->name, &sym->declared_at))
14218     return false;
14219 
14220   if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
14221     {
14222       gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
14223                  "type %s", c->name, &c->loc, sym->name);
14224       return false;
14225     }
14226 
14227   if (sym->attr.sequence)
14228     {
14229       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
14230         {
14231           gfc_error ("Component %s of SEQUENCE type declared at %L does "
14232                      "not have the SEQUENCE attribute",
14233                      c->ts.u.derived->name, &sym->declared_at);
14234           return false;
14235         }
14236     }
14237 
14238   if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.generic)
14239     c->ts.u.derived = gfc_find_dt_in_generic (c->ts.u.derived);
14240   else if (c->ts.type == BT_CLASS && c->attr.class_ok
14241            && CLASS_DATA (c)->ts.u.derived->attr.generic)
14242     CLASS_DATA (c)->ts.u.derived
14243                     = gfc_find_dt_in_generic (CLASS_DATA (c)->ts.u.derived);
14244 
14245   /* If an allocatable component derived type is of the same type as
14246      the enclosing derived type, we need a vtable generating so that
14247      the __deallocate procedure is created.  */
14248   if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
14249        && c->ts.u.derived == sym && c->attr.allocatable == 1)
14250     gfc_find_vtab (&c->ts);
14251 
14252   /* Ensure that all the derived type components are put on the
14253      derived type list; even in formal namespaces, where derived type
14254      pointer components might not have been declared.  */
14255   if (c->ts.type == BT_DERIVED
14256         && c->ts.u.derived
14257         && c->ts.u.derived->components
14258         && c->attr.pointer
14259         && sym != c->ts.u.derived)
14260     add_dt_to_dt_list (c->ts.u.derived);
14261 
14262   if (!gfc_resolve_array_spec (c->as,
14263                                !(c->attr.pointer || c->attr.proc_pointer
14264                                  || c->attr.allocatable)))
14265     return false;
14266 
14267   if (c->initializer && !sym->attr.vtype
14268       && !c->attr.pdt_kind && !c->attr.pdt_len
14269       && !gfc_check_assign_symbol (sym, c, c->initializer))
14270     return false;
14271 
14272   return true;
14273 }
14274 
14275 
14276 /* Be nice about the locus for a structure expression - show the locus of the
14277    first non-null sub-expression if we can.  */
14278 
14279 static locus *
14280 cons_where (gfc_expr *struct_expr)
14281 {
14282   gfc_constructor *cons;
14283 
14284   gcc_assert (struct_expr && struct_expr->expr_type == EXPR_STRUCTURE);
14285 
14286   cons = gfc_constructor_first (struct_expr->value.constructor);
14287   for (; cons; cons = gfc_constructor_next (cons))
14288     {
14289       if (cons->expr && cons->expr->expr_type != EXPR_NULL)
14290         return &cons->expr->where;
14291     }
14292 
14293   return &struct_expr->where;
14294 }
14295 
14296 /* Resolve the components of a structure type. Much less work than derived
14297    types.  */
14298 
14299 static bool
14300 resolve_fl_struct (gfc_symbol *sym)
14301 {
14302   gfc_component *c;
14303   gfc_expr *init = NULL;
14304   bool success;
14305 
14306   /* Make sure UNIONs do not have overlapping initializers.  */
14307   if (sym->attr.flavor == FL_UNION)
14308     {
14309       for (c = sym->components; c; c = c->next)
14310         {
14311           if (init && c->initializer)
14312             {
14313               gfc_error ("Conflicting initializers in union at %L and %L",
14314                          cons_where (init), cons_where (c->initializer));
14315               gfc_free_expr (c->initializer);
14316               c->initializer = NULL;
14317             }
14318           if (init == NULL)
14319             init = c->initializer;
14320         }
14321     }
14322 
14323   success = true;
14324   for (c = sym->components; c; c = c->next)
14325     if (!resolve_component (c, sym))
14326       success = false;
14327 
14328   if (!success)
14329     return false;
14330 
14331   if (sym->components)
14332     add_dt_to_dt_list (sym);
14333 
14334   return true;
14335 }
14336 
14337 
14338 /* Resolve the components of a derived type. This does not have to wait until
14339    resolution stage, but can be done as soon as the dt declaration has been
14340    parsed.  */
14341 
14342 static bool
14343 resolve_fl_derived0 (gfc_symbol *sym)
14344 {
14345   gfc_symbol* super_type;
14346   gfc_component *c;
14347   gfc_formal_arglist *f;
14348   bool success;
14349 
14350   if (sym->attr.unlimited_polymorphic)
14351     return true;
14352 
14353   super_type = gfc_get_derived_super_type (sym);
14354 
14355   /* F2008, C432.  */
14356   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
14357     {
14358       gfc_error ("As extending type %qs at %L has a coarray component, "
14359 		 "parent type %qs shall also have one", sym->name,
14360 		 &sym->declared_at, super_type->name);
14361       return false;
14362     }
14363 
14364   /* Ensure the extended type gets resolved before we do.  */
14365   if (super_type && !resolve_fl_derived0 (super_type))
14366     return false;
14367 
14368   /* An ABSTRACT type must be extensible.  */
14369   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
14370     {
14371       gfc_error ("Non-extensible derived-type %qs at %L must not be ABSTRACT",
14372 		 sym->name, &sym->declared_at);
14373       return false;
14374     }
14375 
14376   c = (sym->attr.is_class) ? sym->components->ts.u.derived->components
14377 			   : sym->components;
14378 
14379   success = true;
14380   for ( ; c != NULL; c = c->next)
14381     if (!resolve_component (c, sym))
14382       success = false;
14383 
14384   if (!success)
14385     return false;
14386 
14387   /* Now add the caf token field, where needed.  */
14388   if (flag_coarray != GFC_FCOARRAY_NONE
14389       && !sym->attr.is_class && !sym->attr.vtype)
14390     {
14391       for (c = sym->components; c; c = c->next)
14392 	if (!c->attr.dimension && !c->attr.codimension
14393 	    && (c->attr.allocatable || c->attr.pointer))
14394 	  {
14395 	    char name[GFC_MAX_SYMBOL_LEN+9];
14396 	    gfc_component *token;
14397 	    sprintf (name, "_caf_%s", c->name);
14398 	    token = gfc_find_component (sym, name, true, true, NULL);
14399 	    if (token == NULL)
14400 	      {
14401 		if (!gfc_add_component (sym, name, &token))
14402 		  return false;
14403 		token->ts.type = BT_VOID;
14404 		token->ts.kind = gfc_default_integer_kind;
14405 		token->attr.access = ACCESS_PRIVATE;
14406 		token->attr.artificial = 1;
14407 		token->attr.caf_token = 1;
14408 	      }
14409 	  }
14410     }
14411 
14412   check_defined_assignments (sym);
14413 
14414   if (!sym->attr.defined_assign_comp && super_type)
14415     sym->attr.defined_assign_comp
14416 			= super_type->attr.defined_assign_comp;
14417 
14418   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
14419      all DEFERRED bindings are overridden.  */
14420   if (super_type && super_type->attr.abstract && !sym->attr.abstract
14421       && !sym->attr.is_class
14422       && !ensure_not_abstract (sym, super_type))
14423     return false;
14424 
14425   /* Check that there is a component for every PDT parameter.  */
14426   if (sym->attr.pdt_template)
14427     {
14428       for (f = sym->formal; f; f = f->next)
14429 	{
14430 	  if (!f->sym)
14431 	    continue;
14432 	  c = gfc_find_component (sym, f->sym->name, true, true, NULL);
14433 	  if (c == NULL)
14434 	    {
14435 	      gfc_error ("Parameterized type %qs does not have a component "
14436 			 "corresponding to parameter %qs at %L", sym->name,
14437 			 f->sym->name, &sym->declared_at);
14438 	      break;
14439 	    }
14440 	}
14441     }
14442 
14443   /* Add derived type to the derived type list.  */
14444   add_dt_to_dt_list (sym);
14445 
14446   return true;
14447 }
14448 
14449 
14450 /* The following procedure does the full resolution of a derived type,
14451    including resolution of all type-bound procedures (if present). In contrast
14452    to 'resolve_fl_derived0' this can only be done after the module has been
14453    parsed completely.  */
14454 
14455 static bool
14456 resolve_fl_derived (gfc_symbol *sym)
14457 {
14458   gfc_symbol *gen_dt = NULL;
14459 
14460   if (sym->attr.unlimited_polymorphic)
14461     return true;
14462 
14463   if (!sym->attr.is_class)
14464     gfc_find_symbol (sym->name, sym->ns, 0, &gen_dt);
14465   if (gen_dt && gen_dt->generic && gen_dt->generic->next
14466       && (!gen_dt->generic->sym->attr.use_assoc
14467 	  || gen_dt->generic->sym->module != gen_dt->generic->next->sym->module)
14468       && !gfc_notify_std (GFC_STD_F2003, "Generic name %qs of function "
14469 			  "%qs at %L being the same name as derived "
14470 			  "type at %L", sym->name,
14471 			  gen_dt->generic->sym == sym
14472 			  ? gen_dt->generic->next->sym->name
14473 			  : gen_dt->generic->sym->name,
14474 			  gen_dt->generic->sym == sym
14475 			  ? &gen_dt->generic->next->sym->declared_at
14476 			  : &gen_dt->generic->sym->declared_at,
14477 			  &sym->declared_at))
14478     return false;
14479 
14480   if (sym->components == NULL && !sym->attr.zero_comp && !sym->attr.use_assoc)
14481     {
14482       gfc_error ("Derived type %qs at %L has not been declared",
14483 		  sym->name, &sym->declared_at);
14484       return false;
14485     }
14486 
14487   /* Resolve the finalizer procedures.  */
14488   if (!gfc_resolve_finalizers (sym, NULL))
14489     return false;
14490 
14491   if (sym->attr.is_class && sym->ts.u.derived == NULL)
14492     {
14493       /* Fix up incomplete CLASS symbols.  */
14494       gfc_component *data = gfc_find_component (sym, "_data", true, true, NULL);
14495       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true, NULL);
14496 
14497       /* Nothing more to do for unlimited polymorphic entities.  */
14498       if (data->ts.u.derived->attr.unlimited_polymorphic)
14499 	return true;
14500       else if (vptr->ts.u.derived == NULL)
14501 	{
14502 	  gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
14503 	  gcc_assert (vtab);
14504 	  vptr->ts.u.derived = vtab->ts.u.derived;
14505 	  if (!resolve_fl_derived0 (vptr->ts.u.derived))
14506 	    return false;
14507 	}
14508     }
14509 
14510   if (!resolve_fl_derived0 (sym))
14511     return false;
14512 
14513   /* Resolve the type-bound procedures.  */
14514   if (!resolve_typebound_procedures (sym))
14515     return false;
14516 
14517   /* Generate module vtables subject to their accessibility and their not
14518      being vtables or pdt templates. If this is not done class declarations
14519      in external procedures wind up with their own version and so SELECT TYPE
14520      fails because the vptrs do not have the same address.  */
14521   if (gfc_option.allow_std & GFC_STD_F2003
14522       && sym->ns->proc_name
14523       && sym->ns->proc_name->attr.flavor == FL_MODULE
14524       && sym->attr.access != ACCESS_PRIVATE
14525       && !(sym->attr.use_assoc || sym->attr.vtype || sym->attr.pdt_template))
14526     {
14527       gfc_symbol *vtab = gfc_find_derived_vtab (sym);
14528       gfc_set_sym_referenced (vtab);
14529     }
14530 
14531   return true;
14532 }
14533 
14534 
14535 static bool
14536 resolve_fl_namelist (gfc_symbol *sym)
14537 {
14538   gfc_namelist *nl;
14539   gfc_symbol *nlsym;
14540 
14541   for (nl = sym->namelist; nl; nl = nl->next)
14542     {
14543       /* Check again, the check in match only works if NAMELIST comes
14544 	 after the decl.  */
14545       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SIZE)
14546      	{
14547 	  gfc_error ("Assumed size array %qs in namelist %qs at %L is not "
14548 		     "allowed", nl->sym->name, sym->name, &sym->declared_at);
14549 	  return false;
14550 	}
14551 
14552       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
14553 	  && !gfc_notify_std (GFC_STD_F2003, "NAMELIST array object %qs "
14554 			      "with assumed shape in namelist %qs at %L",
14555 			      nl->sym->name, sym->name, &sym->declared_at))
14556 	return false;
14557 
14558       if (is_non_constant_shape_array (nl->sym)
14559 	  && !gfc_notify_std (GFC_STD_F2003, "NAMELIST array object %qs "
14560 			      "with nonconstant shape in namelist %qs at %L",
14561 			      nl->sym->name, sym->name, &sym->declared_at))
14562 	return false;
14563 
14564       if (nl->sym->ts.type == BT_CHARACTER
14565 	  && (nl->sym->ts.u.cl->length == NULL
14566 	      || !gfc_is_constant_expr (nl->sym->ts.u.cl->length))
14567 	  && !gfc_notify_std (GFC_STD_F2003, "NAMELIST object %qs with "
14568 			      "nonconstant character length in "
14569 			      "namelist %qs at %L", nl->sym->name,
14570 			      sym->name, &sym->declared_at))
14571 	return false;
14572 
14573     }
14574 
14575   /* Reject PRIVATE objects in a PUBLIC namelist.  */
14576   if (gfc_check_symbol_access (sym))
14577     {
14578       for (nl = sym->namelist; nl; nl = nl->next)
14579 	{
14580 	  if (!nl->sym->attr.use_assoc
14581 	      && !is_sym_host_assoc (nl->sym, sym->ns)
14582 	      && !gfc_check_symbol_access (nl->sym))
14583 	    {
14584 	      gfc_error ("NAMELIST object %qs was declared PRIVATE and "
14585 			 "cannot be member of PUBLIC namelist %qs at %L",
14586 			 nl->sym->name, sym->name, &sym->declared_at);
14587 	      return false;
14588 	    }
14589 
14590 	  if (nl->sym->ts.type == BT_DERIVED
14591 	     && (nl->sym->ts.u.derived->attr.alloc_comp
14592 		 || nl->sym->ts.u.derived->attr.pointer_comp))
14593 	   {
14594 	     if (!gfc_notify_std (GFC_STD_F2003, "NAMELIST object %qs in "
14595 				  "namelist %qs at %L with ALLOCATABLE "
14596 				  "or POINTER components", nl->sym->name,
14597 				  sym->name, &sym->declared_at))
14598 	       return false;
14599 	     return true;
14600 	   }
14601 
14602 	  /* Types with private components that came here by USE-association.  */
14603 	  if (nl->sym->ts.type == BT_DERIVED
14604 	      && derived_inaccessible (nl->sym->ts.u.derived))
14605 	    {
14606 	      gfc_error ("NAMELIST object %qs has use-associated PRIVATE "
14607 			 "components and cannot be member of namelist %qs at %L",
14608 			 nl->sym->name, sym->name, &sym->declared_at);
14609 	      return false;
14610 	    }
14611 
14612 	  /* Types with private components that are defined in the same module.  */
14613 	  if (nl->sym->ts.type == BT_DERIVED
14614 	      && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
14615 	      && nl->sym->ts.u.derived->attr.private_comp)
14616 	    {
14617 	      gfc_error ("NAMELIST object %qs has PRIVATE components and "
14618 			 "cannot be a member of PUBLIC namelist %qs at %L",
14619 			 nl->sym->name, sym->name, &sym->declared_at);
14620 	      return false;
14621 	    }
14622 	}
14623     }
14624 
14625 
14626   /* 14.1.2 A module or internal procedure represent local entities
14627      of the same type as a namelist member and so are not allowed.  */
14628   for (nl = sym->namelist; nl; nl = nl->next)
14629     {
14630       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
14631 	continue;
14632 
14633       if (nl->sym->attr.function && nl->sym == nl->sym->result)
14634 	if ((nl->sym == sym->ns->proc_name)
14635 	       ||
14636 	    (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
14637 	  continue;
14638 
14639       nlsym = NULL;
14640       if (nl->sym->name)
14641 	gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
14642       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
14643 	{
14644 	  gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
14645 		     "attribute in %qs at %L", nlsym->name,
14646 		     &sym->declared_at);
14647 	  return false;
14648 	}
14649     }
14650 
14651   if (async_io_dt)
14652     {
14653       for (nl = sym->namelist; nl; nl = nl->next)
14654 	nl->sym->attr.asynchronous = 1;
14655     }
14656   return true;
14657 }
14658 
14659 
14660 static bool
14661 resolve_fl_parameter (gfc_symbol *sym)
14662 {
14663   /* A parameter array's shape needs to be constant.  */
14664   if (sym->as != NULL
14665       && (sym->as->type == AS_DEFERRED
14666           || is_non_constant_shape_array (sym)))
14667     {
14668       gfc_error ("Parameter array %qs at %L cannot be automatic "
14669 		 "or of deferred shape", sym->name, &sym->declared_at);
14670       return false;
14671     }
14672 
14673   /* Constraints on deferred type parameter.  */
14674   if (!deferred_requirements (sym))
14675     return false;
14676 
14677   /* Make sure a parameter that has been implicitly typed still
14678      matches the implicit type, since PARAMETER statements can precede
14679      IMPLICIT statements.  */
14680   if (sym->attr.implicit_type
14681       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
14682 							     sym->ns)))
14683     {
14684       gfc_error ("Implicitly typed PARAMETER %qs at %L doesn't match a "
14685 		 "later IMPLICIT type", sym->name, &sym->declared_at);
14686       return false;
14687     }
14688 
14689   /* Make sure the types of derived parameters are consistent.  This
14690      type checking is deferred until resolution because the type may
14691      refer to a derived type from the host.  */
14692   if (sym->ts.type == BT_DERIVED
14693       && !gfc_compare_types (&sym->ts, &sym->value->ts))
14694     {
14695       gfc_error ("Incompatible derived type in PARAMETER at %L",
14696 		 &sym->value->where);
14697       return false;
14698     }
14699 
14700   /* F03:C509,C514.  */
14701   if (sym->ts.type == BT_CLASS)
14702     {
14703       gfc_error ("CLASS variable %qs at %L cannot have the PARAMETER attribute",
14704 		 sym->name, &sym->declared_at);
14705       return false;
14706     }
14707 
14708   return true;
14709 }
14710 
14711 
14712 /* Called by resolve_symbol to check PDTs.  */
14713 
14714 static void
14715 resolve_pdt (gfc_symbol* sym)
14716 {
14717   gfc_symbol *derived = NULL;
14718   gfc_actual_arglist *param;
14719   gfc_component *c;
14720   bool const_len_exprs = true;
14721   bool assumed_len_exprs = false;
14722   symbol_attribute *attr;
14723 
14724   if (sym->ts.type == BT_DERIVED)
14725     {
14726       derived = sym->ts.u.derived;
14727       attr = &(sym->attr);
14728     }
14729   else if (sym->ts.type == BT_CLASS)
14730     {
14731       derived = CLASS_DATA (sym)->ts.u.derived;
14732       attr = &(CLASS_DATA (sym)->attr);
14733     }
14734   else
14735     gcc_unreachable ();
14736 
14737   gcc_assert (derived->attr.pdt_type);
14738 
14739   for (param = sym->param_list; param; param = param->next)
14740     {
14741       c = gfc_find_component (derived, param->name, false, true, NULL);
14742       gcc_assert (c);
14743       if (c->attr.pdt_kind)
14744 	continue;
14745 
14746       if (param->expr && !gfc_is_constant_expr (param->expr)
14747 	  && c->attr.pdt_len)
14748 	const_len_exprs = false;
14749       else if (param->spec_type == SPEC_ASSUMED)
14750 	assumed_len_exprs = true;
14751 
14752       if (param->spec_type == SPEC_DEFERRED
14753 	  && !attr->allocatable && !attr->pointer)
14754 	gfc_error ("The object %qs at %L has a deferred LEN "
14755 		   "parameter %qs and is neither allocatable "
14756 		   "nor a pointer", sym->name, &sym->declared_at,
14757 		   param->name);
14758 
14759     }
14760 
14761   if (!const_len_exprs
14762       && (sym->ns->proc_name->attr.is_main_program
14763 	  || sym->ns->proc_name->attr.flavor == FL_MODULE
14764 	  || sym->attr.save != SAVE_NONE))
14765     gfc_error ("The AUTOMATIC object %qs at %L must not have the "
14766 	       "SAVE attribute or be a variable declared in the "
14767 	       "main program, a module or a submodule(F08/C513)",
14768 	       sym->name, &sym->declared_at);
14769 
14770   if (assumed_len_exprs && !(sym->attr.dummy
14771       || sym->attr.select_type_temporary || sym->attr.associate_var))
14772     gfc_error ("The object %qs at %L with ASSUMED type parameters "
14773 	       "must be a dummy or a SELECT TYPE selector(F08/4.2)",
14774 	       sym->name, &sym->declared_at);
14775 }
14776 
14777 
14778 /* Do anything necessary to resolve a symbol.  Right now, we just
14779    assume that an otherwise unknown symbol is a variable.  This sort
14780    of thing commonly happens for symbols in module.  */
14781 
14782 static void
14783 resolve_symbol (gfc_symbol *sym)
14784 {
14785   int check_constant, mp_flag;
14786   gfc_symtree *symtree;
14787   gfc_symtree *this_symtree;
14788   gfc_namespace *ns;
14789   gfc_component *c;
14790   symbol_attribute class_attr;
14791   gfc_array_spec *as;
14792   bool saved_specification_expr;
14793 
14794   if (sym->resolved)
14795     return;
14796   sym->resolved = 1;
14797 
14798   /* No symbol will ever have union type; only components can be unions.
14799      Union type declaration symbols have type BT_UNKNOWN but flavor FL_UNION
14800      (just like derived type declaration symbols have flavor FL_DERIVED). */
14801   gcc_assert (sym->ts.type != BT_UNION);
14802 
14803   /* Coarrayed polymorphic objects with allocatable or pointer components are
14804      yet unsupported for -fcoarray=lib.  */
14805   if (flag_coarray == GFC_FCOARRAY_LIB && sym->ts.type == BT_CLASS
14806       && sym->ts.u.derived && CLASS_DATA (sym)
14807       && CLASS_DATA (sym)->attr.codimension
14808       && (CLASS_DATA (sym)->ts.u.derived->attr.alloc_comp
14809 	  || CLASS_DATA (sym)->ts.u.derived->attr.pointer_comp))
14810     {
14811       gfc_error ("Sorry, allocatable/pointer components in polymorphic (CLASS) "
14812 		 "type coarrays at %L are unsupported", &sym->declared_at);
14813       return;
14814     }
14815 
14816   if (sym->attr.artificial)
14817     return;
14818 
14819   if (sym->attr.unlimited_polymorphic)
14820     return;
14821 
14822   if (sym->attr.flavor == FL_UNKNOWN
14823       || (sym->attr.flavor == FL_PROCEDURE && !sym->attr.intrinsic
14824 	  && !sym->attr.generic && !sym->attr.external
14825 	  && sym->attr.if_source == IFSRC_UNKNOWN
14826 	  && sym->ts.type == BT_UNKNOWN))
14827     {
14828 
14829     /* If we find that a flavorless symbol is an interface in one of the
14830        parent namespaces, find its symtree in this namespace, free the
14831        symbol and set the symtree to point to the interface symbol.  */
14832       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
14833 	{
14834 	  symtree = gfc_find_symtree (ns->sym_root, sym->name);
14835 	  if (symtree && (symtree->n.sym->generic ||
14836 			  (symtree->n.sym->attr.flavor == FL_PROCEDURE
14837 			   && sym->ns->construct_entities)))
14838 	    {
14839 	      this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
14840 					       sym->name);
14841 	      if (this_symtree->n.sym == sym)
14842 		{
14843 		  symtree->n.sym->refs++;
14844 		  gfc_release_symbol (sym);
14845 		  this_symtree->n.sym = symtree->n.sym;
14846 		  return;
14847 		}
14848 	    }
14849 	}
14850 
14851       /* Otherwise give it a flavor according to such attributes as
14852 	 it has.  */
14853       if (sym->attr.flavor == FL_UNKNOWN && sym->attr.external == 0
14854 	  && sym->attr.intrinsic == 0)
14855 	sym->attr.flavor = FL_VARIABLE;
14856       else if (sym->attr.flavor == FL_UNKNOWN)
14857 	{
14858 	  sym->attr.flavor = FL_PROCEDURE;
14859 	  if (sym->attr.dimension)
14860 	    sym->attr.function = 1;
14861 	}
14862     }
14863 
14864   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
14865     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
14866 
14867   if (sym->attr.procedure && sym->attr.if_source != IFSRC_DECL
14868       && !resolve_procedure_interface (sym))
14869     return;
14870 
14871   if (sym->attr.is_protected && !sym->attr.proc_pointer
14872       && (sym->attr.procedure || sym->attr.external))
14873     {
14874       if (sym->attr.external)
14875 	gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
14876 	           "at %L", &sym->declared_at);
14877       else
14878 	gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
14879 	           "at %L", &sym->declared_at);
14880 
14881       return;
14882     }
14883 
14884   if (sym->attr.flavor == FL_DERIVED && !resolve_fl_derived (sym))
14885     return;
14886 
14887   else if ((sym->attr.flavor == FL_STRUCT || sym->attr.flavor == FL_UNION)
14888            && !resolve_fl_struct (sym))
14889     return;
14890 
14891   /* Symbols that are module procedures with results (functions) have
14892      the types and array specification copied for type checking in
14893      procedures that call them, as well as for saving to a module
14894      file.  These symbols can't stand the scrutiny that their results
14895      can.  */
14896   mp_flag = (sym->result != NULL && sym->result != sym);
14897 
14898   /* Make sure that the intrinsic is consistent with its internal
14899      representation. This needs to be done before assigning a default
14900      type to avoid spurious warnings.  */
14901   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
14902       && !gfc_resolve_intrinsic (sym, &sym->declared_at))
14903     return;
14904 
14905   /* Resolve associate names.  */
14906   if (sym->assoc)
14907     resolve_assoc_var (sym, true);
14908 
14909   /* Assign default type to symbols that need one and don't have one.  */
14910   if (sym->ts.type == BT_UNKNOWN)
14911     {
14912       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
14913 	{
14914 	  gfc_set_default_type (sym, 1, NULL);
14915 	}
14916 
14917       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
14918 	  && !sym->attr.function && !sym->attr.subroutine
14919 	  && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
14920 	gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
14921 
14922       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
14923 	{
14924 	  /* The specific case of an external procedure should emit an error
14925 	     in the case that there is no implicit type.  */
14926 	  if (!mp_flag)
14927 	    {
14928 	      if (!sym->attr.mixed_entry_master)
14929 		gfc_set_default_type (sym, sym->attr.external, NULL);
14930 	    }
14931 	  else
14932 	    {
14933 	      /* Result may be in another namespace.  */
14934 	      resolve_symbol (sym->result);
14935 
14936 	      if (!sym->result->attr.proc_pointer)
14937 		{
14938 		  sym->ts = sym->result->ts;
14939 		  sym->as = gfc_copy_array_spec (sym->result->as);
14940 		  sym->attr.dimension = sym->result->attr.dimension;
14941 		  sym->attr.pointer = sym->result->attr.pointer;
14942 		  sym->attr.allocatable = sym->result->attr.allocatable;
14943 		  sym->attr.contiguous = sym->result->attr.contiguous;
14944 		}
14945 	    }
14946 	}
14947     }
14948   else if (mp_flag && sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
14949     {
14950       bool saved_specification_expr = specification_expr;
14951       specification_expr = true;
14952       gfc_resolve_array_spec (sym->result->as, false);
14953       specification_expr = saved_specification_expr;
14954     }
14955 
14956   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
14957     {
14958       as = CLASS_DATA (sym)->as;
14959       class_attr = CLASS_DATA (sym)->attr;
14960       class_attr.pointer = class_attr.class_pointer;
14961     }
14962   else
14963     {
14964       class_attr = sym->attr;
14965       as = sym->as;
14966     }
14967 
14968   /* F2008, C530.  */
14969   if (sym->attr.contiguous
14970       && (!class_attr.dimension
14971 	  || (as->type != AS_ASSUMED_SHAPE && as->type != AS_ASSUMED_RANK
14972 	      && !class_attr.pointer)))
14973     {
14974       gfc_error ("%qs at %L has the CONTIGUOUS attribute but is not an "
14975 		 "array pointer or an assumed-shape or assumed-rank array",
14976 		 sym->name, &sym->declared_at);
14977       return;
14978     }
14979 
14980   /* Assumed size arrays and assumed shape arrays must be dummy
14981      arguments.  Array-spec's of implied-shape should have been resolved to
14982      AS_EXPLICIT already.  */
14983 
14984   if (as)
14985     {
14986       /* If AS_IMPLIED_SHAPE makes it to here, it must be a bad
14987 	 specification expression.  */
14988       if (as->type == AS_IMPLIED_SHAPE)
14989 	{
14990 	  int i;
14991 	  for (i=0; i<as->rank; i++)
14992 	    {
14993 	      if (as->lower[i] != NULL && as->upper[i] == NULL)
14994 		{
14995 		  gfc_error ("Bad specification for assumed size array at %L",
14996 			     &as->lower[i]->where);
14997 		  return;
14998 		}
14999 	    }
15000 	  gcc_unreachable();
15001 	}
15002 
15003       if (((as->type == AS_ASSUMED_SIZE && !as->cp_was_assumed)
15004 	   || as->type == AS_ASSUMED_SHAPE)
15005 	  && !sym->attr.dummy && !sym->attr.select_type_temporary)
15006 	{
15007 	  if (as->type == AS_ASSUMED_SIZE)
15008 	    gfc_error ("Assumed size array at %L must be a dummy argument",
15009 		       &sym->declared_at);
15010 	  else
15011 	    gfc_error ("Assumed shape array at %L must be a dummy argument",
15012 		       &sym->declared_at);
15013 	  return;
15014 	}
15015       /* TS 29113, C535a.  */
15016       if (as->type == AS_ASSUMED_RANK && !sym->attr.dummy
15017 	  && !sym->attr.select_type_temporary)
15018 	{
15019 	  gfc_error ("Assumed-rank array at %L must be a dummy argument",
15020 		     &sym->declared_at);
15021 	  return;
15022 	}
15023       if (as->type == AS_ASSUMED_RANK
15024 	  && (sym->attr.codimension || sym->attr.value))
15025 	{
15026 	  gfc_error ("Assumed-rank array at %L may not have the VALUE or "
15027 		     "CODIMENSION attribute", &sym->declared_at);
15028 	  return;
15029 	}
15030     }
15031 
15032   /* Make sure symbols with known intent or optional are really dummy
15033      variable.  Because of ENTRY statement, this has to be deferred
15034      until resolution time.  */
15035 
15036   if (!sym->attr.dummy
15037       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
15038     {
15039       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
15040       return;
15041     }
15042 
15043   if (sym->attr.value && !sym->attr.dummy)
15044     {
15045       gfc_error ("%qs at %L cannot have the VALUE attribute because "
15046 		 "it is not a dummy argument", sym->name, &sym->declared_at);
15047       return;
15048     }
15049 
15050   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
15051     {
15052       gfc_charlen *cl = sym->ts.u.cl;
15053       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
15054 	{
15055 	  gfc_error ("Character dummy variable %qs at %L with VALUE "
15056 		     "attribute must have constant length",
15057 		     sym->name, &sym->declared_at);
15058 	  return;
15059 	}
15060 
15061       if (sym->ts.is_c_interop
15062 	  && mpz_cmp_si (cl->length->value.integer, 1) != 0)
15063 	{
15064 	  gfc_error ("C interoperable character dummy variable %qs at %L "
15065 		     "with VALUE attribute must have length one",
15066 		     sym->name, &sym->declared_at);
15067 	  return;
15068 	}
15069     }
15070 
15071   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
15072       && sym->ts.u.derived->attr.generic)
15073     {
15074       sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
15075       if (!sym->ts.u.derived)
15076 	{
15077 	  gfc_error ("The derived type %qs at %L is of type %qs, "
15078 		     "which has not been defined", sym->name,
15079 		     &sym->declared_at, sym->ts.u.derived->name);
15080 	  sym->ts.type = BT_UNKNOWN;
15081 	  return;
15082 	}
15083     }
15084 
15085     /* Use the same constraints as TYPE(*), except for the type check
15086        and that only scalars and assumed-size arrays are permitted.  */
15087     if (sym->attr.ext_attr & (1 << EXT_ATTR_NO_ARG_CHECK))
15088       {
15089 	if (!sym->attr.dummy)
15090 	  {
15091 	    gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall be "
15092 		       "a dummy argument", sym->name, &sym->declared_at);
15093 	    return;
15094 	  }
15095 
15096 	if (sym->ts.type != BT_ASSUMED && sym->ts.type != BT_INTEGER
15097 	    && sym->ts.type != BT_REAL && sym->ts.type != BT_LOGICAL
15098 	    && sym->ts.type != BT_COMPLEX)
15099 	  {
15100 	    gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall be "
15101 		       "of type TYPE(*) or of an numeric intrinsic type",
15102 		       sym->name, &sym->declared_at);
15103 	    return;
15104 	  }
15105 
15106       if (sym->attr.allocatable || sym->attr.codimension
15107 	  || sym->attr.pointer || sym->attr.value)
15108 	{
15109 	  gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may not "
15110 		     "have the ALLOCATABLE, CODIMENSION, POINTER or VALUE "
15111 		     "attribute", sym->name, &sym->declared_at);
15112 	  return;
15113 	}
15114 
15115       if (sym->attr.intent == INTENT_OUT)
15116 	{
15117 	  gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute may not "
15118 		     "have the INTENT(OUT) attribute",
15119 		     sym->name, &sym->declared_at);
15120 	  return;
15121 	}
15122       if (sym->attr.dimension && sym->as->type != AS_ASSUMED_SIZE)
15123 	{
15124 	  gfc_error ("Variable %s at %L with NO_ARG_CHECK attribute shall "
15125 		     "either be a scalar or an assumed-size array",
15126 		     sym->name, &sym->declared_at);
15127 	  return;
15128 	}
15129 
15130       /* Set the type to TYPE(*) and add a dimension(*) to ensure
15131 	 NO_ARG_CHECK is correctly handled in trans*.c, e.g. with
15132 	 packing.  */
15133       sym->ts.type = BT_ASSUMED;
15134       sym->as = gfc_get_array_spec ();
15135       sym->as->type = AS_ASSUMED_SIZE;
15136       sym->as->rank = 1;
15137       sym->as->lower[0] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
15138     }
15139   else if (sym->ts.type == BT_ASSUMED)
15140     {
15141       /* TS 29113, C407a.  */
15142       if (!sym->attr.dummy)
15143 	{
15144 	  gfc_error ("Assumed type of variable %s at %L is only permitted "
15145 		     "for dummy variables", sym->name, &sym->declared_at);
15146 	  return;
15147 	}
15148       if (sym->attr.allocatable || sym->attr.codimension
15149 	  || sym->attr.pointer || sym->attr.value)
15150     	{
15151 	  gfc_error ("Assumed-type variable %s at %L may not have the "
15152 		     "ALLOCATABLE, CODIMENSION, POINTER or VALUE attribute",
15153 		     sym->name, &sym->declared_at);
15154 	  return;
15155 	}
15156       if (sym->attr.intent == INTENT_OUT)
15157     	{
15158 	  gfc_error ("Assumed-type variable %s at %L may not have the "
15159 		     "INTENT(OUT) attribute",
15160 		     sym->name, &sym->declared_at);
15161 	  return;
15162 	}
15163       if (sym->attr.dimension && sym->as->type == AS_EXPLICIT)
15164 	{
15165 	  gfc_error ("Assumed-type variable %s at %L shall not be an "
15166 		     "explicit-shape array", sym->name, &sym->declared_at);
15167 	  return;
15168 	}
15169     }
15170 
15171   /* If the symbol is marked as bind(c), that it is declared at module level
15172      scope and verify its type and kind.  Do not do the latter for symbols
15173      that are implicitly typed because that is handled in
15174      gfc_set_default_type.  Handle dummy arguments and procedure definitions
15175      separately.  Also, anything that is use associated is not handled here
15176      but instead is handled in the module it is declared in.  Finally, derived
15177      type definitions are allowed to be BIND(C) since that only implies that
15178      they're interoperable, and they are checked fully for interoperability
15179      when a variable is declared of that type.  */
15180   if (sym->attr.is_bind_c && sym->attr.use_assoc == 0
15181       && sym->attr.dummy == 0 && sym->attr.flavor != FL_PROCEDURE
15182       && sym->attr.flavor != FL_DERIVED)
15183     {
15184       bool t = true;
15185 
15186       /* First, make sure the variable is declared at the
15187 	 module-level scope (J3/04-007, Section 15.3).	*/
15188       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
15189           sym->attr.in_common == 0)
15190 	{
15191 	  gfc_error ("Variable %qs at %L cannot be BIND(C) because it "
15192 		     "is neither a COMMON block nor declared at the "
15193 		     "module level scope", sym->name, &(sym->declared_at));
15194 	  t = false;
15195 	}
15196       else if (sym->ts.type == BT_CHARACTER
15197 	       && (sym->ts.u.cl == NULL || sym->ts.u.cl->length == NULL
15198 		   || !gfc_is_constant_expr (sym->ts.u.cl->length)
15199 		   || mpz_cmp_si (sym->ts.u.cl->length->value.integer, 1) != 0))
15200 	{
15201 	  gfc_error ("BIND(C) Variable %qs at %L must have length one",
15202 		     sym->name, &sym->declared_at);
15203 	  t = false;
15204 	}
15205       else if (sym->common_head != NULL && sym->attr.implicit_type == 0)
15206         {
15207           t = verify_com_block_vars_c_interop (sym->common_head);
15208         }
15209       else if (sym->attr.implicit_type == 0)
15210 	{
15211 	  /* If type() declaration, we need to verify that the components
15212 	     of the given type are all C interoperable, etc.  */
15213 	  if (sym->ts.type == BT_DERIVED &&
15214               sym->ts.u.derived->attr.is_c_interop != 1)
15215             {
15216               /* Make sure the user marked the derived type as BIND(C).  If
15217                  not, call the verify routine.  This could print an error
15218                  for the derived type more than once if multiple variables
15219                  of that type are declared.  */
15220               if (sym->ts.u.derived->attr.is_bind_c != 1)
15221                 verify_bind_c_derived_type (sym->ts.u.derived);
15222               t = false;
15223             }
15224 
15225 	  /* Verify the variable itself as C interoperable if it
15226              is BIND(C).  It is not possible for this to succeed if
15227              the verify_bind_c_derived_type failed, so don't have to handle
15228              any error returned by verify_bind_c_derived_type.  */
15229           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
15230                                  sym->common_block);
15231 	}
15232 
15233       if (!t)
15234         {
15235           /* clear the is_bind_c flag to prevent reporting errors more than
15236              once if something failed.  */
15237           sym->attr.is_bind_c = 0;
15238           return;
15239         }
15240     }
15241 
15242   /* If a derived type symbol has reached this point, without its
15243      type being declared, we have an error.  Notice that most
15244      conditions that produce undefined derived types have already
15245      been dealt with.  However, the likes of:
15246      implicit type(t) (t) ..... call foo (t) will get us here if
15247      the type is not declared in the scope of the implicit
15248      statement. Change the type to BT_UNKNOWN, both because it is so
15249      and to prevent an ICE.  */
15250   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
15251       && sym->ts.u.derived->components == NULL
15252       && !sym->ts.u.derived->attr.zero_comp)
15253     {
15254       gfc_error ("The derived type %qs at %L is of type %qs, "
15255 		 "which has not been defined", sym->name,
15256 		  &sym->declared_at, sym->ts.u.derived->name);
15257       sym->ts.type = BT_UNKNOWN;
15258       return;
15259     }
15260 
15261   /* Make sure that the derived type has been resolved and that the
15262      derived type is visible in the symbol's namespace, if it is a
15263      module function and is not PRIVATE.  */
15264   if (sym->ts.type == BT_DERIVED
15265 	&& sym->ts.u.derived->attr.use_assoc
15266 	&& sym->ns->proc_name
15267 	&& sym->ns->proc_name->attr.flavor == FL_MODULE
15268         && !resolve_fl_derived (sym->ts.u.derived))
15269     return;
15270 
15271   /* Unless the derived-type declaration is use associated, Fortran 95
15272      does not allow public entries of private derived types.
15273      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
15274      161 in 95-006r3.  */
15275   if (sym->ts.type == BT_DERIVED
15276       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
15277       && !sym->ts.u.derived->attr.use_assoc
15278       && gfc_check_symbol_access (sym)
15279       && !gfc_check_symbol_access (sym->ts.u.derived)
15280       && !gfc_notify_std (GFC_STD_F2003, "PUBLIC %s %qs at %L of PRIVATE "
15281 			  "derived type %qs",
15282 			  (sym->attr.flavor == FL_PARAMETER)
15283 			  ? "parameter" : "variable",
15284 			  sym->name, &sym->declared_at,
15285 			  sym->ts.u.derived->name))
15286     return;
15287 
15288   /* F2008, C1302.  */
15289   if (sym->ts.type == BT_DERIVED
15290       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
15291 	   && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
15292 	  || sym->ts.u.derived->attr.lock_comp)
15293       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
15294     {
15295       gfc_error ("Variable %s at %L of type LOCK_TYPE or with subcomponent of "
15296 		 "type LOCK_TYPE must be a coarray", sym->name,
15297 		 &sym->declared_at);
15298       return;
15299     }
15300 
15301   /* TS18508, C702/C703.  */
15302   if (sym->ts.type == BT_DERIVED
15303       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
15304 	   && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_EVENT_TYPE)
15305 	  || sym->ts.u.derived->attr.event_comp)
15306       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
15307     {
15308       gfc_error ("Variable %s at %L of type EVENT_TYPE or with subcomponent of "
15309 		 "type EVENT_TYPE must be a coarray", sym->name,
15310 		 &sym->declared_at);
15311       return;
15312     }
15313 
15314   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
15315      default initialization is defined (5.1.2.4.4).  */
15316   if (sym->ts.type == BT_DERIVED
15317       && sym->attr.dummy
15318       && sym->attr.intent == INTENT_OUT
15319       && sym->as
15320       && sym->as->type == AS_ASSUMED_SIZE)
15321     {
15322       for (c = sym->ts.u.derived->components; c; c = c->next)
15323 	{
15324 	  if (c->initializer)
15325 	    {
15326 	      gfc_error ("The INTENT(OUT) dummy argument %qs at %L is "
15327 			 "ASSUMED SIZE and so cannot have a default initializer",
15328 			 sym->name, &sym->declared_at);
15329 	      return;
15330 	    }
15331 	}
15332     }
15333 
15334   /* F2008, C542.  */
15335   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
15336       && sym->attr.intent == INTENT_OUT && sym->attr.lock_comp)
15337     {
15338       gfc_error ("Dummy argument %qs at %L of LOCK_TYPE shall not be "
15339 		 "INTENT(OUT)", sym->name, &sym->declared_at);
15340       return;
15341     }
15342 
15343   /* TS18508.  */
15344   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
15345       && sym->attr.intent == INTENT_OUT && sym->attr.event_comp)
15346     {
15347       gfc_error ("Dummy argument %qs at %L of EVENT_TYPE shall not be "
15348 		 "INTENT(OUT)", sym->name, &sym->declared_at);
15349       return;
15350     }
15351 
15352   /* F2008, C525.  */
15353   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
15354 	 || (sym->ts.type == BT_CLASS && sym->attr.class_ok
15355 	     && CLASS_DATA (sym)->attr.coarray_comp))
15356        || class_attr.codimension)
15357       && (sym->attr.result || sym->result == sym))
15358     {
15359       gfc_error ("Function result %qs at %L shall not be a coarray or have "
15360 	         "a coarray component", sym->name, &sym->declared_at);
15361       return;
15362     }
15363 
15364   /* F2008, C524.  */
15365   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
15366       && sym->ts.u.derived->ts.is_iso_c)
15367     {
15368       gfc_error ("Variable %qs at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
15369 		 "shall not be a coarray", sym->name, &sym->declared_at);
15370       return;
15371     }
15372 
15373   /* F2008, C525.  */
15374   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
15375 	|| (sym->ts.type == BT_CLASS && sym->attr.class_ok
15376 	    && CLASS_DATA (sym)->attr.coarray_comp))
15377       && (class_attr.codimension || class_attr.pointer || class_attr.dimension
15378 	  || class_attr.allocatable))
15379     {
15380       gfc_error ("Variable %qs at %L with coarray component shall be a "
15381 		 "nonpointer, nonallocatable scalar, which is not a coarray",
15382 		 sym->name, &sym->declared_at);
15383       return;
15384     }
15385 
15386   /* F2008, C526.  The function-result case was handled above.  */
15387   if (class_attr.codimension
15388       && !(class_attr.allocatable || sym->attr.dummy || sym->attr.save
15389 	   || sym->attr.select_type_temporary
15390 	   || sym->attr.associate_var
15391 	   || (sym->ns->save_all && !sym->attr.automatic)
15392 	   || sym->ns->proc_name->attr.flavor == FL_MODULE
15393 	   || sym->ns->proc_name->attr.is_main_program
15394 	   || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
15395     {
15396       gfc_error ("Variable %qs at %L is a coarray and is not ALLOCATABLE, SAVE "
15397 		 "nor a dummy argument", sym->name, &sym->declared_at);
15398       return;
15399     }
15400   /* F2008, C528.  */
15401   else if (class_attr.codimension && !sym->attr.select_type_temporary
15402 	   && !class_attr.allocatable && as && as->cotype == AS_DEFERRED)
15403     {
15404       gfc_error ("Coarray variable %qs at %L shall not have codimensions with "
15405 		 "deferred shape", sym->name, &sym->declared_at);
15406       return;
15407     }
15408   else if (class_attr.codimension && class_attr.allocatable && as
15409 	   && (as->cotype != AS_DEFERRED || as->type != AS_DEFERRED))
15410     {
15411       gfc_error ("Allocatable coarray variable %qs at %L must have "
15412 		 "deferred shape", sym->name, &sym->declared_at);
15413       return;
15414     }
15415 
15416   /* F2008, C541.  */
15417   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
15418 	|| (sym->ts.type == BT_CLASS && sym->attr.class_ok
15419 	    && CLASS_DATA (sym)->attr.coarray_comp))
15420        || (class_attr.codimension && class_attr.allocatable))
15421       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
15422     {
15423       gfc_error ("Variable %qs at %L is INTENT(OUT) and can thus not be an "
15424 		 "allocatable coarray or have coarray components",
15425 		 sym->name, &sym->declared_at);
15426       return;
15427     }
15428 
15429   if (class_attr.codimension && sym->attr.dummy
15430       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
15431     {
15432       gfc_error ("Coarray dummy variable %qs at %L not allowed in BIND(C) "
15433 		 "procedure %qs", sym->name, &sym->declared_at,
15434 		 sym->ns->proc_name->name);
15435       return;
15436     }
15437 
15438   if (sym->ts.type == BT_LOGICAL
15439       && ((sym->attr.function && sym->attr.is_bind_c && sym->result == sym)
15440 	  || ((sym->attr.dummy || sym->attr.result) && sym->ns->proc_name
15441 	      && sym->ns->proc_name->attr.is_bind_c)))
15442     {
15443       int i;
15444       for (i = 0; gfc_logical_kinds[i].kind; i++)
15445         if (gfc_logical_kinds[i].kind == sym->ts.kind)
15446           break;
15447       if (!gfc_logical_kinds[i].c_bool && sym->attr.dummy
15448 	  && !gfc_notify_std (GFC_STD_GNU, "LOGICAL dummy argument %qs at "
15449 			      "%L with non-C_Bool kind in BIND(C) procedure "
15450 			      "%qs", sym->name, &sym->declared_at,
15451 			      sym->ns->proc_name->name))
15452 	return;
15453       else if (!gfc_logical_kinds[i].c_bool
15454 	       && !gfc_notify_std (GFC_STD_GNU, "LOGICAL result variable "
15455 				   "%qs at %L with non-C_Bool kind in "
15456 				   "BIND(C) procedure %qs", sym->name,
15457 				   &sym->declared_at,
15458 				   sym->attr.function ? sym->name
15459 				   : sym->ns->proc_name->name))
15460 	return;
15461     }
15462 
15463   switch (sym->attr.flavor)
15464     {
15465     case FL_VARIABLE:
15466       if (!resolve_fl_variable (sym, mp_flag))
15467 	return;
15468       break;
15469 
15470     case FL_PROCEDURE:
15471       if (sym->formal && !sym->formal_ns)
15472 	{
15473 	  /* Check that none of the arguments are a namelist.  */
15474 	  gfc_formal_arglist *formal = sym->formal;
15475 
15476 	  for (; formal; formal = formal->next)
15477 	    if (formal->sym && formal->sym->attr.flavor == FL_NAMELIST)
15478 	      {
15479 		gfc_error ("Namelist %qs cannot be an argument to "
15480 			   "subroutine or function at %L",
15481 			   formal->sym->name, &sym->declared_at);
15482 		return;
15483 	      }
15484 	}
15485 
15486       if (!resolve_fl_procedure (sym, mp_flag))
15487 	return;
15488       break;
15489 
15490     case FL_NAMELIST:
15491       if (!resolve_fl_namelist (sym))
15492 	return;
15493       break;
15494 
15495     case FL_PARAMETER:
15496       if (!resolve_fl_parameter (sym))
15497 	return;
15498       break;
15499 
15500     default:
15501       break;
15502     }
15503 
15504   /* Resolve array specifier. Check as well some constraints
15505      on COMMON blocks.  */
15506 
15507   check_constant = sym->attr.in_common && !sym->attr.pointer;
15508 
15509   /* Set the formal_arg_flag so that check_conflict will not throw
15510      an error for host associated variables in the specification
15511      expression for an array_valued function.  */
15512   if ((sym->attr.function || sym->attr.result) && sym->as)
15513     formal_arg_flag = true;
15514 
15515   saved_specification_expr = specification_expr;
15516   specification_expr = true;
15517   gfc_resolve_array_spec (sym->as, check_constant);
15518   specification_expr = saved_specification_expr;
15519 
15520   formal_arg_flag = false;
15521 
15522   /* Resolve formal namespaces.  */
15523   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
15524       && !sym->attr.contained && !sym->attr.intrinsic)
15525     gfc_resolve (sym->formal_ns);
15526 
15527   /* Make sure the formal namespace is present.  */
15528   if (sym->formal && !sym->formal_ns)
15529     {
15530       gfc_formal_arglist *formal = sym->formal;
15531       while (formal && !formal->sym)
15532 	formal = formal->next;
15533 
15534       if (formal)
15535 	{
15536 	  sym->formal_ns = formal->sym->ns;
15537           if (sym->ns != formal->sym->ns)
15538 	    sym->formal_ns->refs++;
15539 	}
15540     }
15541 
15542   /* Check threadprivate restrictions.  */
15543   if (sym->attr.threadprivate && !sym->attr.save
15544       && !(sym->ns->save_all && !sym->attr.automatic)
15545       && (!sym->attr.in_common
15546 	  && sym->module == NULL
15547 	  && (sym->ns->proc_name == NULL
15548 	      || sym->ns->proc_name->attr.flavor != FL_MODULE)))
15549     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
15550 
15551   /* Check omp declare target restrictions.  */
15552   if (sym->attr.omp_declare_target
15553       && sym->attr.flavor == FL_VARIABLE
15554       && !sym->attr.save
15555       && !(sym->ns->save_all && !sym->attr.automatic)
15556       && (!sym->attr.in_common
15557 	  && sym->module == NULL
15558 	  && (sym->ns->proc_name == NULL
15559 	      || sym->ns->proc_name->attr.flavor != FL_MODULE)))
15560     gfc_error ("!$OMP DECLARE TARGET variable %qs at %L isn't SAVEd",
15561 	       sym->name, &sym->declared_at);
15562 
15563   /* If we have come this far we can apply default-initializers, as
15564      described in 14.7.5, to those variables that have not already
15565      been assigned one.  */
15566   if (sym->ts.type == BT_DERIVED
15567       && !sym->value
15568       && !sym->attr.allocatable
15569       && !sym->attr.alloc_comp)
15570     {
15571       symbol_attribute *a = &sym->attr;
15572 
15573       if ((!a->save && !a->dummy && !a->pointer
15574 	   && !a->in_common && !a->use_assoc
15575 	   && a->referenced
15576 	   && !((a->function || a->result)
15577 		&& (!a->dimension
15578 		    || sym->ts.u.derived->attr.alloc_comp
15579 		    || sym->ts.u.derived->attr.pointer_comp))
15580 	   && !(a->function && sym != sym->result))
15581 	  || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
15582 	apply_default_init (sym);
15583       else if (a->function && sym->result && a->access != ACCESS_PRIVATE
15584 	       && (sym->ts.u.derived->attr.alloc_comp
15585 		   || sym->ts.u.derived->attr.pointer_comp))
15586 	/* Mark the result symbol to be referenced, when it has allocatable
15587 	   components.  */
15588 	sym->result->attr.referenced = 1;
15589     }
15590 
15591   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
15592       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
15593       && !CLASS_DATA (sym)->attr.class_pointer
15594       && !CLASS_DATA (sym)->attr.allocatable)
15595     apply_default_init (sym);
15596 
15597   /* If this symbol has a type-spec, check it.  */
15598   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
15599       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
15600     if (!resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name))
15601       return;
15602 
15603   if (sym->param_list)
15604     resolve_pdt (sym);
15605 }
15606 
15607 
15608 /************* Resolve DATA statements *************/
15609 
15610 static struct
15611 {
15612   gfc_data_value *vnode;
15613   mpz_t left;
15614 }
15615 values;
15616 
15617 
15618 /* Advance the values structure to point to the next value in the data list.  */
15619 
15620 static bool
15621 next_data_value (void)
15622 {
15623   while (mpz_cmp_ui (values.left, 0) == 0)
15624     {
15625 
15626       if (values.vnode->next == NULL)
15627 	return false;
15628 
15629       values.vnode = values.vnode->next;
15630       mpz_set (values.left, values.vnode->repeat);
15631     }
15632 
15633   return true;
15634 }
15635 
15636 
15637 static bool
15638 check_data_variable (gfc_data_variable *var, locus *where)
15639 {
15640   gfc_expr *e;
15641   mpz_t size;
15642   mpz_t offset;
15643   bool t;
15644   ar_type mark = AR_UNKNOWN;
15645   int i;
15646   mpz_t section_index[GFC_MAX_DIMENSIONS];
15647   gfc_ref *ref;
15648   gfc_array_ref *ar;
15649   gfc_symbol *sym;
15650   int has_pointer;
15651 
15652   if (!gfc_resolve_expr (var->expr))
15653     return false;
15654 
15655   ar = NULL;
15656   mpz_init_set_si (offset, 0);
15657   e = var->expr;
15658 
15659   if (e->expr_type == EXPR_FUNCTION && e->value.function.isym
15660       && e->value.function.isym->id == GFC_ISYM_CAF_GET)
15661     e = e->value.function.actual->expr;
15662 
15663   if (e->expr_type != EXPR_VARIABLE)
15664     {
15665       gfc_error ("Expecting definable entity near %L", where);
15666       return false;
15667     }
15668 
15669   sym = e->symtree->n.sym;
15670 
15671   if (sym->ns->is_block_data && !sym->attr.in_common)
15672     {
15673       gfc_error ("BLOCK DATA element %qs at %L must be in COMMON",
15674 		 sym->name, &sym->declared_at);
15675       return false;
15676     }
15677 
15678   if (e->ref == NULL && sym->as)
15679     {
15680       gfc_error ("DATA array %qs at %L must be specified in a previous"
15681 		 " declaration", sym->name, where);
15682       return false;
15683     }
15684 
15685   if (gfc_is_coindexed (e))
15686     {
15687       gfc_error ("DATA element %qs at %L cannot have a coindex", sym->name,
15688 		 where);
15689       return false;
15690     }
15691 
15692   has_pointer = sym->attr.pointer;
15693 
15694   for (ref = e->ref; ref; ref = ref->next)
15695     {
15696       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
15697 	has_pointer = 1;
15698 
15699       if (has_pointer)
15700 	{
15701 	  if (ref->type == REF_ARRAY && ref->u.ar.type != AR_FULL)
15702 	    {
15703 	      gfc_error ("DATA element %qs at %L is a pointer and so must "
15704 			 "be a full array", sym->name, where);
15705 	      return false;
15706 	    }
15707 
15708 	  if (values.vnode->expr->expr_type == EXPR_CONSTANT)
15709 	    {
15710 	      gfc_error ("DATA object near %L has the pointer attribute "
15711 			 "and the corresponding DATA value is not a valid "
15712 			 "initial-data-target", where);
15713 	      return false;
15714 	    }
15715 	}
15716     }
15717 
15718   if (e->rank == 0 || has_pointer)
15719     {
15720       mpz_init_set_ui (size, 1);
15721       ref = NULL;
15722     }
15723   else
15724     {
15725       ref = e->ref;
15726 
15727       /* Find the array section reference.  */
15728       for (ref = e->ref; ref; ref = ref->next)
15729 	{
15730 	  if (ref->type != REF_ARRAY)
15731 	    continue;
15732 	  if (ref->u.ar.type == AR_ELEMENT)
15733 	    continue;
15734 	  break;
15735 	}
15736       gcc_assert (ref);
15737 
15738       /* Set marks according to the reference pattern.  */
15739       switch (ref->u.ar.type)
15740 	{
15741 	case AR_FULL:
15742 	  mark = AR_FULL;
15743 	  break;
15744 
15745 	case AR_SECTION:
15746 	  ar = &ref->u.ar;
15747 	  /* Get the start position of array section.  */
15748 	  gfc_get_section_index (ar, section_index, &offset);
15749 	  mark = AR_SECTION;
15750 	  break;
15751 
15752 	default:
15753 	  gcc_unreachable ();
15754 	}
15755 
15756       if (!gfc_array_size (e, &size))
15757 	{
15758 	  gfc_error ("Nonconstant array section at %L in DATA statement",
15759 		     where);
15760 	  mpz_clear (offset);
15761 	  return false;
15762 	}
15763     }
15764 
15765   t = true;
15766 
15767   while (mpz_cmp_ui (size, 0) > 0)
15768     {
15769       if (!next_data_value ())
15770 	{
15771 	  gfc_error ("DATA statement at %L has more variables than values",
15772 		     where);
15773 	  t = false;
15774 	  break;
15775 	}
15776 
15777       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
15778       if (!t)
15779 	break;
15780 
15781       /* If we have more than one element left in the repeat count,
15782 	 and we have more than one element left in the target variable,
15783 	 then create a range assignment.  */
15784       /* FIXME: Only done for full arrays for now, since array sections
15785 	 seem tricky.  */
15786       if (mark == AR_FULL && ref && ref->next == NULL
15787 	  && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
15788 	{
15789 	  mpz_t range;
15790 
15791 	  if (mpz_cmp (size, values.left) >= 0)
15792 	    {
15793 	      mpz_init_set (range, values.left);
15794 	      mpz_sub (size, size, values.left);
15795 	      mpz_set_ui (values.left, 0);
15796 	    }
15797 	  else
15798 	    {
15799 	      mpz_init_set (range, size);
15800 	      mpz_sub (values.left, values.left, size);
15801 	      mpz_set_ui (size, 0);
15802 	    }
15803 
15804 	  t = gfc_assign_data_value (var->expr, values.vnode->expr,
15805 				     offset, &range);
15806 
15807 	  mpz_add (offset, offset, range);
15808 	  mpz_clear (range);
15809 
15810 	  if (!t)
15811 	    break;
15812 	}
15813 
15814       /* Assign initial value to symbol.  */
15815       else
15816 	{
15817 	  mpz_sub_ui (values.left, values.left, 1);
15818 	  mpz_sub_ui (size, size, 1);
15819 
15820 	  t = gfc_assign_data_value (var->expr, values.vnode->expr,
15821 				     offset, NULL);
15822 	  if (!t)
15823 	    break;
15824 
15825 	  if (mark == AR_FULL)
15826 	    mpz_add_ui (offset, offset, 1);
15827 
15828 	  /* Modify the array section indexes and recalculate the offset
15829 	     for next element.  */
15830 	  else if (mark == AR_SECTION)
15831 	    gfc_advance_section (section_index, ar, &offset);
15832 	}
15833     }
15834 
15835   if (mark == AR_SECTION)
15836     {
15837       for (i = 0; i < ar->dimen; i++)
15838 	mpz_clear (section_index[i]);
15839     }
15840 
15841   mpz_clear (size);
15842   mpz_clear (offset);
15843 
15844   return t;
15845 }
15846 
15847 
15848 static bool traverse_data_var (gfc_data_variable *, locus *);
15849 
15850 /* Iterate over a list of elements in a DATA statement.  */
15851 
15852 static bool
15853 traverse_data_list (gfc_data_variable *var, locus *where)
15854 {
15855   mpz_t trip;
15856   iterator_stack frame;
15857   gfc_expr *e, *start, *end, *step;
15858   bool retval = true;
15859 
15860   mpz_init (frame.value);
15861   mpz_init (trip);
15862 
15863   start = gfc_copy_expr (var->iter.start);
15864   end = gfc_copy_expr (var->iter.end);
15865   step = gfc_copy_expr (var->iter.step);
15866 
15867   if (!gfc_simplify_expr (start, 1)
15868       || start->expr_type != EXPR_CONSTANT)
15869     {
15870       gfc_error ("start of implied-do loop at %L could not be "
15871 		 "simplified to a constant value", &start->where);
15872       retval = false;
15873       goto cleanup;
15874     }
15875   if (!gfc_simplify_expr (end, 1)
15876       || end->expr_type != EXPR_CONSTANT)
15877     {
15878       gfc_error ("end of implied-do loop at %L could not be "
15879 		 "simplified to a constant value", &start->where);
15880       retval = false;
15881       goto cleanup;
15882     }
15883   if (!gfc_simplify_expr (step, 1)
15884       || step->expr_type != EXPR_CONSTANT)
15885     {
15886       gfc_error ("step of implied-do loop at %L could not be "
15887 		 "simplified to a constant value", &start->where);
15888       retval = false;
15889       goto cleanup;
15890     }
15891 
15892   mpz_set (trip, end->value.integer);
15893   mpz_sub (trip, trip, start->value.integer);
15894   mpz_add (trip, trip, step->value.integer);
15895 
15896   mpz_div (trip, trip, step->value.integer);
15897 
15898   mpz_set (frame.value, start->value.integer);
15899 
15900   frame.prev = iter_stack;
15901   frame.variable = var->iter.var->symtree;
15902   iter_stack = &frame;
15903 
15904   while (mpz_cmp_ui (trip, 0) > 0)
15905     {
15906       if (!traverse_data_var (var->list, where))
15907 	{
15908 	  retval = false;
15909 	  goto cleanup;
15910 	}
15911 
15912       e = gfc_copy_expr (var->expr);
15913       if (!gfc_simplify_expr (e, 1))
15914 	{
15915 	  gfc_free_expr (e);
15916 	  retval = false;
15917 	  goto cleanup;
15918 	}
15919 
15920       mpz_add (frame.value, frame.value, step->value.integer);
15921 
15922       mpz_sub_ui (trip, trip, 1);
15923     }
15924 
15925 cleanup:
15926   mpz_clear (frame.value);
15927   mpz_clear (trip);
15928 
15929   gfc_free_expr (start);
15930   gfc_free_expr (end);
15931   gfc_free_expr (step);
15932 
15933   iter_stack = frame.prev;
15934   return retval;
15935 }
15936 
15937 
15938 /* Type resolve variables in the variable list of a DATA statement.  */
15939 
15940 static bool
15941 traverse_data_var (gfc_data_variable *var, locus *where)
15942 {
15943   bool t;
15944 
15945   for (; var; var = var->next)
15946     {
15947       if (var->expr == NULL)
15948 	t = traverse_data_list (var, where);
15949       else
15950 	t = check_data_variable (var, where);
15951 
15952       if (!t)
15953 	return false;
15954     }
15955 
15956   return true;
15957 }
15958 
15959 
15960 /* Resolve the expressions and iterators associated with a data statement.
15961    This is separate from the assignment checking because data lists should
15962    only be resolved once.  */
15963 
15964 static bool
15965 resolve_data_variables (gfc_data_variable *d)
15966 {
15967   for (; d; d = d->next)
15968     {
15969       if (d->list == NULL)
15970 	{
15971 	  if (!gfc_resolve_expr (d->expr))
15972 	    return false;
15973 	}
15974       else
15975 	{
15976 	  if (!gfc_resolve_iterator (&d->iter, false, true))
15977 	    return false;
15978 
15979 	  if (!resolve_data_variables (d->list))
15980 	    return false;
15981 	}
15982     }
15983 
15984   return true;
15985 }
15986 
15987 
15988 /* Resolve a single DATA statement.  We implement this by storing a pointer to
15989    the value list into static variables, and then recursively traversing the
15990    variables list, expanding iterators and such.  */
15991 
15992 static void
15993 resolve_data (gfc_data *d)
15994 {
15995 
15996   if (!resolve_data_variables (d->var))
15997     return;
15998 
15999   values.vnode = d->value;
16000   if (d->value == NULL)
16001     mpz_set_ui (values.left, 0);
16002   else
16003     mpz_set (values.left, d->value->repeat);
16004 
16005   if (!traverse_data_var (d->var, &d->where))
16006     return;
16007 
16008   /* At this point, we better not have any values left.  */
16009 
16010   if (next_data_value ())
16011     gfc_error ("DATA statement at %L has more values than variables",
16012 	       &d->where);
16013 }
16014 
16015 
16016 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
16017    accessed by host or use association, is a dummy argument to a pure function,
16018    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
16019    is storage associated with any such variable, shall not be used in the
16020    following contexts: (clients of this function).  */
16021 
16022 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
16023    procedure.  Returns zero if assignment is OK, nonzero if there is a
16024    problem.  */
16025 int
16026 gfc_impure_variable (gfc_symbol *sym)
16027 {
16028   gfc_symbol *proc;
16029   gfc_namespace *ns;
16030 
16031   if (sym->attr.use_assoc || sym->attr.in_common)
16032     return 1;
16033 
16034   /* Check if the symbol's ns is inside the pure procedure.  */
16035   for (ns = gfc_current_ns; ns; ns = ns->parent)
16036     {
16037       if (ns == sym->ns)
16038 	break;
16039       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
16040 	return 1;
16041     }
16042 
16043   proc = sym->ns->proc_name;
16044   if (sym->attr.dummy
16045       && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
16046 	  || proc->attr.function))
16047     return 1;
16048 
16049   /* TODO: Sort out what can be storage associated, if anything, and include
16050      it here.  In principle equivalences should be scanned but it does not
16051      seem to be possible to storage associate an impure variable this way.  */
16052   return 0;
16053 }
16054 
16055 
16056 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
16057    current namespace is inside a pure procedure.  */
16058 
16059 int
16060 gfc_pure (gfc_symbol *sym)
16061 {
16062   symbol_attribute attr;
16063   gfc_namespace *ns;
16064 
16065   if (sym == NULL)
16066     {
16067       /* Check if the current namespace or one of its parents
16068 	belongs to a pure procedure.  */
16069       for (ns = gfc_current_ns; ns; ns = ns->parent)
16070 	{
16071 	  sym = ns->proc_name;
16072 	  if (sym == NULL)
16073 	    return 0;
16074 	  attr = sym->attr;
16075 	  if (attr.flavor == FL_PROCEDURE && attr.pure)
16076 	    return 1;
16077 	}
16078       return 0;
16079     }
16080 
16081   attr = sym->attr;
16082 
16083   return attr.flavor == FL_PROCEDURE && attr.pure;
16084 }
16085 
16086 
16087 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
16088    checks if the current namespace is implicitly pure.  Note that this
16089    function returns false for a PURE procedure.  */
16090 
16091 int
16092 gfc_implicit_pure (gfc_symbol *sym)
16093 {
16094   gfc_namespace *ns;
16095 
16096   if (sym == NULL)
16097     {
16098       /* Check if the current procedure is implicit_pure.  Walk up
16099 	 the procedure list until we find a procedure.  */
16100       for (ns = gfc_current_ns; ns; ns = ns->parent)
16101 	{
16102 	  sym = ns->proc_name;
16103 	  if (sym == NULL)
16104 	    return 0;
16105 
16106 	  if (sym->attr.flavor == FL_PROCEDURE)
16107 	    break;
16108 	}
16109     }
16110 
16111   return sym->attr.flavor == FL_PROCEDURE && sym->attr.implicit_pure
16112     && !sym->attr.pure;
16113 }
16114 
16115 
16116 void
16117 gfc_unset_implicit_pure (gfc_symbol *sym)
16118 {
16119   gfc_namespace *ns;
16120 
16121   if (sym == NULL)
16122     {
16123       /* Check if the current procedure is implicit_pure.  Walk up
16124 	 the procedure list until we find a procedure.  */
16125       for (ns = gfc_current_ns; ns; ns = ns->parent)
16126 	{
16127 	  sym = ns->proc_name;
16128 	  if (sym == NULL)
16129 	    return;
16130 
16131 	  if (sym->attr.flavor == FL_PROCEDURE)
16132 	    break;
16133 	}
16134     }
16135 
16136   if (sym->attr.flavor == FL_PROCEDURE)
16137     sym->attr.implicit_pure = 0;
16138   else
16139     sym->attr.pure = 0;
16140 }
16141 
16142 
16143 /* Test whether the current procedure is elemental or not.  */
16144 
16145 int
16146 gfc_elemental (gfc_symbol *sym)
16147 {
16148   symbol_attribute attr;
16149 
16150   if (sym == NULL)
16151     sym = gfc_current_ns->proc_name;
16152   if (sym == NULL)
16153     return 0;
16154   attr = sym->attr;
16155 
16156   return attr.flavor == FL_PROCEDURE && attr.elemental;
16157 }
16158 
16159 
16160 /* Warn about unused labels.  */
16161 
16162 static void
16163 warn_unused_fortran_label (gfc_st_label *label)
16164 {
16165   if (label == NULL)
16166     return;
16167 
16168   warn_unused_fortran_label (label->left);
16169 
16170   if (label->defined == ST_LABEL_UNKNOWN)
16171     return;
16172 
16173   switch (label->referenced)
16174     {
16175     case ST_LABEL_UNKNOWN:
16176       gfc_warning (OPT_Wunused_label, "Label %d at %L defined but not used",
16177 		   label->value, &label->where);
16178       break;
16179 
16180     case ST_LABEL_BAD_TARGET:
16181       gfc_warning (OPT_Wunused_label,
16182 		   "Label %d at %L defined but cannot be used",
16183 		   label->value, &label->where);
16184       break;
16185 
16186     default:
16187       break;
16188     }
16189 
16190   warn_unused_fortran_label (label->right);
16191 }
16192 
16193 
16194 /* Returns the sequence type of a symbol or sequence.  */
16195 
16196 static seq_type
16197 sequence_type (gfc_typespec ts)
16198 {
16199   seq_type result;
16200   gfc_component *c;
16201 
16202   switch (ts.type)
16203   {
16204     case BT_DERIVED:
16205 
16206       if (ts.u.derived->components == NULL)
16207 	return SEQ_NONDEFAULT;
16208 
16209       result = sequence_type (ts.u.derived->components->ts);
16210       for (c = ts.u.derived->components->next; c; c = c->next)
16211 	if (sequence_type (c->ts) != result)
16212 	  return SEQ_MIXED;
16213 
16214       return result;
16215 
16216     case BT_CHARACTER:
16217       if (ts.kind != gfc_default_character_kind)
16218 	  return SEQ_NONDEFAULT;
16219 
16220       return SEQ_CHARACTER;
16221 
16222     case BT_INTEGER:
16223       if (ts.kind != gfc_default_integer_kind)
16224 	  return SEQ_NONDEFAULT;
16225 
16226       return SEQ_NUMERIC;
16227 
16228     case BT_REAL:
16229       if (!(ts.kind == gfc_default_real_kind
16230 	    || ts.kind == gfc_default_double_kind))
16231 	  return SEQ_NONDEFAULT;
16232 
16233       return SEQ_NUMERIC;
16234 
16235     case BT_COMPLEX:
16236       if (ts.kind != gfc_default_complex_kind)
16237 	  return SEQ_NONDEFAULT;
16238 
16239       return SEQ_NUMERIC;
16240 
16241     case BT_LOGICAL:
16242       if (ts.kind != gfc_default_logical_kind)
16243 	  return SEQ_NONDEFAULT;
16244 
16245       return SEQ_NUMERIC;
16246 
16247     default:
16248       return SEQ_NONDEFAULT;
16249   }
16250 }
16251 
16252 
16253 /* Resolve derived type EQUIVALENCE object.  */
16254 
16255 static bool
16256 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
16257 {
16258   gfc_component *c = derived->components;
16259 
16260   if (!derived)
16261     return true;
16262 
16263   /* Shall not be an object of nonsequence derived type.  */
16264   if (!derived->attr.sequence)
16265     {
16266       gfc_error ("Derived type variable %qs at %L must have SEQUENCE "
16267 		 "attribute to be an EQUIVALENCE object", sym->name,
16268 		 &e->where);
16269       return false;
16270     }
16271 
16272   /* Shall not have allocatable components.  */
16273   if (derived->attr.alloc_comp)
16274     {
16275       gfc_error ("Derived type variable %qs at %L cannot have ALLOCATABLE "
16276 		 "components to be an EQUIVALENCE object",sym->name,
16277 		 &e->where);
16278       return false;
16279     }
16280 
16281   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
16282     {
16283       gfc_error ("Derived type variable %qs at %L with default "
16284 		 "initialization cannot be in EQUIVALENCE with a variable "
16285 		 "in COMMON", sym->name, &e->where);
16286       return false;
16287     }
16288 
16289   for (; c ; c = c->next)
16290     {
16291       if (gfc_bt_struct (c->ts.type)
16292 	  && (!resolve_equivalence_derived(c->ts.u.derived, sym, e)))
16293 	return false;
16294 
16295       /* Shall not be an object of sequence derived type containing a pointer
16296 	 in the structure.  */
16297       if (c->attr.pointer)
16298 	{
16299 	  gfc_error ("Derived type variable %qs at %L with pointer "
16300 		     "component(s) cannot be an EQUIVALENCE object",
16301 		     sym->name, &e->where);
16302 	  return false;
16303 	}
16304     }
16305   return true;
16306 }
16307 
16308 
16309 /* Resolve equivalence object.
16310    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
16311    an allocatable array, an object of nonsequence derived type, an object of
16312    sequence derived type containing a pointer at any level of component
16313    selection, an automatic object, a function name, an entry name, a result
16314    name, a named constant, a structure component, or a subobject of any of
16315    the preceding objects.  A substring shall not have length zero.  A
16316    derived type shall not have components with default initialization nor
16317    shall two objects of an equivalence group be initialized.
16318    Either all or none of the objects shall have an protected attribute.
16319    The simple constraints are done in symbol.c(check_conflict) and the rest
16320    are implemented here.  */
16321 
16322 static void
16323 resolve_equivalence (gfc_equiv *eq)
16324 {
16325   gfc_symbol *sym;
16326   gfc_symbol *first_sym;
16327   gfc_expr *e;
16328   gfc_ref *r;
16329   locus *last_where = NULL;
16330   seq_type eq_type, last_eq_type;
16331   gfc_typespec *last_ts;
16332   int object, cnt_protected;
16333   const char *msg;
16334 
16335   last_ts = &eq->expr->symtree->n.sym->ts;
16336 
16337   first_sym = eq->expr->symtree->n.sym;
16338 
16339   cnt_protected = 0;
16340 
16341   for (object = 1; eq; eq = eq->eq, object++)
16342     {
16343       e = eq->expr;
16344 
16345       e->ts = e->symtree->n.sym->ts;
16346       /* match_varspec might not know yet if it is seeing
16347 	 array reference or substring reference, as it doesn't
16348 	 know the types.  */
16349       if (e->ref && e->ref->type == REF_ARRAY)
16350 	{
16351 	  gfc_ref *ref = e->ref;
16352 	  sym = e->symtree->n.sym;
16353 
16354 	  if (sym->attr.dimension)
16355 	    {
16356 	      ref->u.ar.as = sym->as;
16357 	      ref = ref->next;
16358 	    }
16359 
16360 	  /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
16361 	  if (e->ts.type == BT_CHARACTER
16362 	      && ref
16363 	      && ref->type == REF_ARRAY
16364 	      && ref->u.ar.dimen == 1
16365 	      && ref->u.ar.dimen_type[0] == DIMEN_RANGE
16366 	      && ref->u.ar.stride[0] == NULL)
16367 	    {
16368 	      gfc_expr *start = ref->u.ar.start[0];
16369 	      gfc_expr *end = ref->u.ar.end[0];
16370 	      void *mem = NULL;
16371 
16372 	      /* Optimize away the (:) reference.  */
16373 	      if (start == NULL && end == NULL)
16374 		{
16375 		  if (e->ref == ref)
16376 		    e->ref = ref->next;
16377 		  else
16378 		    e->ref->next = ref->next;
16379 		  mem = ref;
16380 		}
16381 	      else
16382 		{
16383 		  ref->type = REF_SUBSTRING;
16384 		  if (start == NULL)
16385 		    start = gfc_get_int_expr (gfc_charlen_int_kind,
16386 					      NULL, 1);
16387 		  ref->u.ss.start = start;
16388 		  if (end == NULL && e->ts.u.cl)
16389 		    end = gfc_copy_expr (e->ts.u.cl->length);
16390 		  ref->u.ss.end = end;
16391 		  ref->u.ss.length = e->ts.u.cl;
16392 		  e->ts.u.cl = NULL;
16393 		}
16394 	      ref = ref->next;
16395 	      free (mem);
16396 	    }
16397 
16398 	  /* Any further ref is an error.  */
16399 	  if (ref)
16400 	    {
16401 	      gcc_assert (ref->type == REF_ARRAY);
16402 	      gfc_error ("Syntax error in EQUIVALENCE statement at %L",
16403 			 &ref->u.ar.where);
16404 	      continue;
16405 	    }
16406 	}
16407 
16408       if (!gfc_resolve_expr (e))
16409 	continue;
16410 
16411       sym = e->symtree->n.sym;
16412 
16413       if (sym->attr.is_protected)
16414 	cnt_protected++;
16415       if (cnt_protected > 0 && cnt_protected != object)
16416        	{
16417 	      gfc_error ("Either all or none of the objects in the "
16418 			 "EQUIVALENCE set at %L shall have the "
16419 			 "PROTECTED attribute",
16420 			 &e->where);
16421 	      break;
16422 	}
16423 
16424       /* Shall not equivalence common block variables in a PURE procedure.  */
16425       if (sym->ns->proc_name
16426 	  && sym->ns->proc_name->attr.pure
16427 	  && sym->attr.in_common)
16428 	{
16429 	  /* Need to check for symbols that may have entered the pure
16430 	     procedure via a USE statement.  */
16431 	  bool saw_sym = false;
16432 	  if (sym->ns->use_stmts)
16433 	    {
16434 	      gfc_use_rename *r;
16435 	      for (r = sym->ns->use_stmts->rename; r; r = r->next)
16436 		if (strcmp(r->use_name, sym->name) == 0) saw_sym = true;
16437 	    }
16438 	  else
16439 	    saw_sym = true;
16440 
16441 	  if (saw_sym)
16442 	    gfc_error ("COMMON block member %qs at %L cannot be an "
16443 		       "EQUIVALENCE object in the pure procedure %qs",
16444 		       sym->name, &e->where, sym->ns->proc_name->name);
16445 	  break;
16446 	}
16447 
16448       /* Shall not be a named constant.  */
16449       if (e->expr_type == EXPR_CONSTANT)
16450 	{
16451 	  gfc_error ("Named constant %qs at %L cannot be an EQUIVALENCE "
16452 		     "object", sym->name, &e->where);
16453 	  continue;
16454 	}
16455 
16456       if (e->ts.type == BT_DERIVED
16457 	  && !resolve_equivalence_derived (e->ts.u.derived, sym, e))
16458 	continue;
16459 
16460       /* Check that the types correspond correctly:
16461 	 Note 5.28:
16462 	 A numeric sequence structure may be equivalenced to another sequence
16463 	 structure, an object of default integer type, default real type, double
16464 	 precision real type, default logical type such that components of the
16465 	 structure ultimately only become associated to objects of the same
16466 	 kind. A character sequence structure may be equivalenced to an object
16467 	 of default character kind or another character sequence structure.
16468 	 Other objects may be equivalenced only to objects of the same type and
16469 	 kind parameters.  */
16470 
16471       /* Identical types are unconditionally OK.  */
16472       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
16473 	goto identical_types;
16474 
16475       last_eq_type = sequence_type (*last_ts);
16476       eq_type = sequence_type (sym->ts);
16477 
16478       /* Since the pair of objects is not of the same type, mixed or
16479 	 non-default sequences can be rejected.  */
16480 
16481       msg = "Sequence %s with mixed components in EQUIVALENCE "
16482 	    "statement at %L with different type objects";
16483       if ((object ==2
16484 	   && last_eq_type == SEQ_MIXED
16485 	   && !gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where))
16486 	  || (eq_type == SEQ_MIXED
16487 	      && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where)))
16488 	continue;
16489 
16490       msg = "Non-default type object or sequence %s in EQUIVALENCE "
16491 	    "statement at %L with objects of different type";
16492       if ((object ==2
16493 	   && last_eq_type == SEQ_NONDEFAULT
16494 	   && !gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where))
16495 	  || (eq_type == SEQ_NONDEFAULT
16496 	      && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where)))
16497 	continue;
16498 
16499       msg ="Non-CHARACTER object %qs in default CHARACTER "
16500 	   "EQUIVALENCE statement at %L";
16501       if (last_eq_type == SEQ_CHARACTER
16502 	  && eq_type != SEQ_CHARACTER
16503 	  && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where))
16504 		continue;
16505 
16506       msg ="Non-NUMERIC object %qs in default NUMERIC "
16507 	   "EQUIVALENCE statement at %L";
16508       if (last_eq_type == SEQ_NUMERIC
16509 	  && eq_type != SEQ_NUMERIC
16510 	  && !gfc_notify_std (GFC_STD_GNU, msg, sym->name, &e->where))
16511 		continue;
16512 
16513   identical_types:
16514       last_ts =&sym->ts;
16515       last_where = &e->where;
16516 
16517       if (!e->ref)
16518 	continue;
16519 
16520       /* Shall not be an automatic array.  */
16521       if (e->ref->type == REF_ARRAY
16522 	  && !gfc_resolve_array_spec (e->ref->u.ar.as, 1))
16523 	{
16524 	  gfc_error ("Array %qs at %L with non-constant bounds cannot be "
16525 		     "an EQUIVALENCE object", sym->name, &e->where);
16526 	  continue;
16527 	}
16528 
16529       r = e->ref;
16530       while (r)
16531 	{
16532 	  /* Shall not be a structure component.  */
16533 	  if (r->type == REF_COMPONENT)
16534 	    {
16535 	      gfc_error ("Structure component %qs at %L cannot be an "
16536 			 "EQUIVALENCE object",
16537 			 r->u.c.component->name, &e->where);
16538 	      break;
16539 	    }
16540 
16541 	  /* A substring shall not have length zero.  */
16542 	  if (r->type == REF_SUBSTRING)
16543 	    {
16544 	      if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
16545 		{
16546 		  gfc_error ("Substring at %L has length zero",
16547 			     &r->u.ss.start->where);
16548 		  break;
16549 		}
16550 	    }
16551 	  r = r->next;
16552 	}
16553     }
16554 }
16555 
16556 
16557 /* Function called by resolve_fntype to flag other symbols used in the
16558    length type parameter specification of function results.  */
16559 
16560 static bool
16561 flag_fn_result_spec (gfc_expr *expr,
16562                      gfc_symbol *sym,
16563                      int *f ATTRIBUTE_UNUSED)
16564 {
16565   gfc_namespace *ns;
16566   gfc_symbol *s;
16567 
16568   if (expr->expr_type == EXPR_VARIABLE)
16569     {
16570       s = expr->symtree->n.sym;
16571       for (ns = s->ns; ns; ns = ns->parent)
16572 	if (!ns->parent)
16573 	  break;
16574 
16575       if (sym == s)
16576 	{
16577 	  gfc_error ("Self reference in character length expression "
16578 		     "for %qs at %L", sym->name, &expr->where);
16579 	  return true;
16580 	}
16581 
16582       if (!s->fn_result_spec
16583 	  && s->attr.flavor == FL_PARAMETER)
16584 	{
16585 	  /* Function contained in a module.... */
16586 	  if (ns->proc_name && ns->proc_name->attr.flavor == FL_MODULE)
16587 	    {
16588 	      gfc_symtree *st;
16589 	      s->fn_result_spec = 1;
16590 	      /* Make sure that this symbol is translated as a module
16591 		 variable.  */
16592 	      st = gfc_get_unique_symtree (ns);
16593 	      st->n.sym = s;
16594 	      s->refs++;
16595 	    }
16596 	  /* ... which is use associated and called.  */
16597 	  else if (s->attr.use_assoc || s->attr.used_in_submodule
16598 			||
16599 		  /* External function matched with an interface.  */
16600 		  (s->ns->proc_name
16601 		   && ((s->ns == ns
16602 			 && s->ns->proc_name->attr.if_source == IFSRC_DECL)
16603 		       || s->ns->proc_name->attr.if_source == IFSRC_IFBODY)
16604 		   && s->ns->proc_name->attr.function))
16605 	    s->fn_result_spec = 1;
16606 	}
16607     }
16608   return false;
16609 }
16610 
16611 
16612 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
16613 
16614 static void
16615 resolve_fntype (gfc_namespace *ns)
16616 {
16617   gfc_entry_list *el;
16618   gfc_symbol *sym;
16619 
16620   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
16621     return;
16622 
16623   /* If there are any entries, ns->proc_name is the entry master
16624      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
16625   if (ns->entries)
16626     sym = ns->entries->sym;
16627   else
16628     sym = ns->proc_name;
16629   if (sym->result == sym
16630       && sym->ts.type == BT_UNKNOWN
16631       && !gfc_set_default_type (sym, 0, NULL)
16632       && !sym->attr.untyped)
16633     {
16634       gfc_error ("Function %qs at %L has no IMPLICIT type",
16635 		 sym->name, &sym->declared_at);
16636       sym->attr.untyped = 1;
16637     }
16638 
16639   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
16640       && !sym->attr.contained
16641       && !gfc_check_symbol_access (sym->ts.u.derived)
16642       && gfc_check_symbol_access (sym))
16643     {
16644       gfc_notify_std (GFC_STD_F2003, "PUBLIC function %qs at "
16645 		      "%L of PRIVATE type %qs", sym->name,
16646 		      &sym->declared_at, sym->ts.u.derived->name);
16647     }
16648 
16649     if (ns->entries)
16650     for (el = ns->entries->next; el; el = el->next)
16651       {
16652 	if (el->sym->result == el->sym
16653 	    && el->sym->ts.type == BT_UNKNOWN
16654 	    && !gfc_set_default_type (el->sym, 0, NULL)
16655 	    && !el->sym->attr.untyped)
16656 	  {
16657 	    gfc_error ("ENTRY %qs at %L has no IMPLICIT type",
16658 		       el->sym->name, &el->sym->declared_at);
16659 	    el->sym->attr.untyped = 1;
16660 	  }
16661       }
16662 
16663   if (sym->ts.type == BT_CHARACTER)
16664     gfc_traverse_expr (sym->ts.u.cl->length, sym, flag_fn_result_spec, 0);
16665 }
16666 
16667 
16668 /* 12.3.2.1.1 Defined operators.  */
16669 
16670 static bool
16671 check_uop_procedure (gfc_symbol *sym, locus where)
16672 {
16673   gfc_formal_arglist *formal;
16674 
16675   if (!sym->attr.function)
16676     {
16677       gfc_error ("User operator procedure %qs at %L must be a FUNCTION",
16678 		 sym->name, &where);
16679       return false;
16680     }
16681 
16682   if (sym->ts.type == BT_CHARACTER
16683       && !((sym->ts.u.cl && sym->ts.u.cl->length) || sym->ts.deferred)
16684       && !(sym->result && ((sym->result->ts.u.cl
16685 	   && sym->result->ts.u.cl->length) || sym->result->ts.deferred)))
16686     {
16687       gfc_error ("User operator procedure %qs at %L cannot be assumed "
16688 		 "character length", sym->name, &where);
16689       return false;
16690     }
16691 
16692   formal = gfc_sym_get_dummy_args (sym);
16693   if (!formal || !formal->sym)
16694     {
16695       gfc_error ("User operator procedure %qs at %L must have at least "
16696 		 "one argument", sym->name, &where);
16697       return false;
16698     }
16699 
16700   if (formal->sym->attr.intent != INTENT_IN)
16701     {
16702       gfc_error ("First argument of operator interface at %L must be "
16703 		 "INTENT(IN)", &where);
16704       return false;
16705     }
16706 
16707   if (formal->sym->attr.optional)
16708     {
16709       gfc_error ("First argument of operator interface at %L cannot be "
16710 		 "optional", &where);
16711       return false;
16712     }
16713 
16714   formal = formal->next;
16715   if (!formal || !formal->sym)
16716     return true;
16717 
16718   if (formal->sym->attr.intent != INTENT_IN)
16719     {
16720       gfc_error ("Second argument of operator interface at %L must be "
16721 		 "INTENT(IN)", &where);
16722       return false;
16723     }
16724 
16725   if (formal->sym->attr.optional)
16726     {
16727       gfc_error ("Second argument of operator interface at %L cannot be "
16728 		 "optional", &where);
16729       return false;
16730     }
16731 
16732   if (formal->next)
16733     {
16734       gfc_error ("Operator interface at %L must have, at most, two "
16735 		 "arguments", &where);
16736       return false;
16737     }
16738 
16739   return true;
16740 }
16741 
16742 static void
16743 gfc_resolve_uops (gfc_symtree *symtree)
16744 {
16745   gfc_interface *itr;
16746 
16747   if (symtree == NULL)
16748     return;
16749 
16750   gfc_resolve_uops (symtree->left);
16751   gfc_resolve_uops (symtree->right);
16752 
16753   for (itr = symtree->n.uop->op; itr; itr = itr->next)
16754     check_uop_procedure (itr->sym, itr->sym->declared_at);
16755 }
16756 
16757 
16758 /* Examine all of the expressions associated with a program unit,
16759    assign types to all intermediate expressions, make sure that all
16760    assignments are to compatible types and figure out which names
16761    refer to which functions or subroutines.  It doesn't check code
16762    block, which is handled by gfc_resolve_code.  */
16763 
16764 static void
16765 resolve_types (gfc_namespace *ns)
16766 {
16767   gfc_namespace *n;
16768   gfc_charlen *cl;
16769   gfc_data *d;
16770   gfc_equiv *eq;
16771   gfc_namespace* old_ns = gfc_current_ns;
16772   bool recursive = ns->proc_name && ns->proc_name->attr.recursive;
16773 
16774   if (ns->types_resolved)
16775     return;
16776 
16777   /* Check that all IMPLICIT types are ok.  */
16778   if (!ns->seen_implicit_none)
16779     {
16780       unsigned letter;
16781       for (letter = 0; letter != GFC_LETTERS; ++letter)
16782 	if (ns->set_flag[letter]
16783 	    && !resolve_typespec_used (&ns->default_type[letter],
16784 				       &ns->implicit_loc[letter], NULL))
16785 	  return;
16786     }
16787 
16788   gfc_current_ns = ns;
16789 
16790   resolve_entries (ns);
16791 
16792   resolve_common_vars (&ns->blank_common, false);
16793   resolve_common_blocks (ns->common_root);
16794 
16795   resolve_contained_functions (ns);
16796 
16797   if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE
16798       && ns->proc_name->attr.if_source == IFSRC_IFBODY)
16799     resolve_formal_arglist (ns->proc_name);
16800 
16801   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
16802 
16803   for (cl = ns->cl_list; cl; cl = cl->next)
16804     resolve_charlen (cl);
16805 
16806   gfc_traverse_ns (ns, resolve_symbol);
16807 
16808   resolve_fntype (ns);
16809 
16810   for (n = ns->contained; n; n = n->sibling)
16811     {
16812       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
16813 	gfc_error ("Contained procedure %qs at %L of a PURE procedure must "
16814 		   "also be PURE", n->proc_name->name,
16815 		   &n->proc_name->declared_at);
16816 
16817       resolve_types (n);
16818     }
16819 
16820   forall_flag = 0;
16821   gfc_do_concurrent_flag = 0;
16822   gfc_check_interfaces (ns);
16823 
16824   gfc_traverse_ns (ns, resolve_values);
16825 
16826   if (ns->save_all || (!flag_automatic && !recursive))
16827     gfc_save_all (ns);
16828 
16829   iter_stack = NULL;
16830   for (d = ns->data; d; d = d->next)
16831     resolve_data (d);
16832 
16833   iter_stack = NULL;
16834   gfc_traverse_ns (ns, gfc_formalize_init_value);
16835 
16836   gfc_traverse_ns (ns, gfc_verify_binding_labels);
16837 
16838   for (eq = ns->equiv; eq; eq = eq->next)
16839     resolve_equivalence (eq);
16840 
16841   /* Warn about unused labels.  */
16842   if (warn_unused_label)
16843     warn_unused_fortran_label (ns->st_labels);
16844 
16845   gfc_resolve_uops (ns->uop_root);
16846 
16847   gfc_traverse_ns (ns, gfc_verify_DTIO_procedures);
16848 
16849   gfc_resolve_omp_declare_simd (ns);
16850 
16851   gfc_resolve_omp_udrs (ns->omp_udr_root);
16852 
16853   ns->types_resolved = 1;
16854 
16855   gfc_current_ns = old_ns;
16856 }
16857 
16858 
16859 /* Call gfc_resolve_code recursively.  */
16860 
16861 static void
16862 resolve_codes (gfc_namespace *ns)
16863 {
16864   gfc_namespace *n;
16865   bitmap_obstack old_obstack;
16866 
16867   if (ns->resolved == 1)
16868     return;
16869 
16870   for (n = ns->contained; n; n = n->sibling)
16871     resolve_codes (n);
16872 
16873   gfc_current_ns = ns;
16874 
16875   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
16876   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
16877     cs_base = NULL;
16878 
16879   /* Set to an out of range value.  */
16880   current_entry_id = -1;
16881 
16882   old_obstack = labels_obstack;
16883   bitmap_obstack_initialize (&labels_obstack);
16884 
16885   gfc_resolve_oacc_declare (ns);
16886   gfc_resolve_oacc_routines (ns);
16887   gfc_resolve_omp_local_vars (ns);
16888   gfc_resolve_code (ns->code, ns);
16889 
16890   bitmap_obstack_release (&labels_obstack);
16891   labels_obstack = old_obstack;
16892 }
16893 
16894 
16895 /* This function is called after a complete program unit has been compiled.
16896    Its purpose is to examine all of the expressions associated with a program
16897    unit, assign types to all intermediate expressions, make sure that all
16898    assignments are to compatible types and figure out which names refer to
16899    which functions or subroutines.  */
16900 
16901 void
16902 gfc_resolve (gfc_namespace *ns)
16903 {
16904   gfc_namespace *old_ns;
16905   code_stack *old_cs_base;
16906   struct gfc_omp_saved_state old_omp_state;
16907 
16908   if (ns->resolved)
16909     return;
16910 
16911   ns->resolved = -1;
16912   old_ns = gfc_current_ns;
16913   old_cs_base = cs_base;
16914 
16915   /* As gfc_resolve can be called during resolution of an OpenMP construct
16916      body, we should clear any state associated to it, so that say NS's
16917      DO loops are not interpreted as OpenMP loops.  */
16918   if (!ns->construct_entities)
16919     gfc_omp_save_and_clear_state (&old_omp_state);
16920 
16921   resolve_types (ns);
16922   component_assignment_level = 0;
16923   resolve_codes (ns);
16924 
16925   gfc_current_ns = old_ns;
16926   cs_base = old_cs_base;
16927   ns->resolved = 1;
16928 
16929   gfc_run_passes (ns);
16930 
16931   if (!ns->construct_entities)
16932     gfc_omp_restore_state (&old_omp_state);
16933 }
16934