re PR fortran/38936 ([F03] ASSOCIATE construct / improved SELECT TYPE (a=>expr))
[platform/upstream/gcc.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "flags.h"
25 #include "gfortran.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "arith.h"  /* For gfc_compare_expr().  */
29 #include "dependency.h"
30 #include "data.h"
31 #include "target-memory.h" /* for gfc_simplify_transfer */
32 #include "constructor.h"
33
34 /* Types used in equivalence statements.  */
35
36 typedef enum seq_type
37 {
38   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
39 }
40 seq_type;
41
42 /* Stack to keep track of the nesting of blocks as we move through the
43    code.  See resolve_branch() and resolve_code().  */
44
45 typedef struct code_stack
46 {
47   struct gfc_code *head, *current;
48   struct code_stack *prev;
49
50   /* This bitmap keeps track of the targets valid for a branch from
51      inside this block except for END {IF|SELECT}s of enclosing
52      blocks.  */
53   bitmap reachable_labels;
54 }
55 code_stack;
56
57 static code_stack *cs_base = NULL;
58
59
60 /* Nonzero if we're inside a FORALL block.  */
61
62 static int forall_flag;
63
64 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
65
66 static int omp_workshare_flag;
67
68 /* Nonzero if we are processing a formal arglist. The corresponding function
69    resets the flag each time that it is read.  */
70 static int formal_arg_flag = 0;
71
72 /* True if we are resolving a specification expression.  */
73 static int specification_expr = 0;
74
75 /* The id of the last entry seen.  */
76 static int current_entry_id;
77
78 /* We use bitmaps to determine if a branch target is valid.  */
79 static bitmap_obstack labels_obstack;
80
81 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
82 static bool inquiry_argument = false;
83
84 int
85 gfc_is_formal_arg (void)
86 {
87   return formal_arg_flag;
88 }
89
90 /* Is the symbol host associated?  */
91 static bool
92 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
93 {
94   for (ns = ns->parent; ns; ns = ns->parent)
95     {      
96       if (sym->ns == ns)
97         return true;
98     }
99
100   return false;
101 }
102
103 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
104    an ABSTRACT derived-type.  If where is not NULL, an error message with that
105    locus is printed, optionally using name.  */
106
107 static gfc_try
108 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
109 {
110   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
111     {
112       if (where)
113         {
114           if (name)
115             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
116                        name, where, ts->u.derived->name);
117           else
118             gfc_error ("ABSTRACT type '%s' used at %L",
119                        ts->u.derived->name, where);
120         }
121
122       return FAILURE;
123     }
124
125   return SUCCESS;
126 }
127
128
129 static void resolve_symbol (gfc_symbol *sym);
130 static gfc_try resolve_intrinsic (gfc_symbol *sym, locus *loc);
131
132
133 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
134
135 static gfc_try
136 resolve_procedure_interface (gfc_symbol *sym)
137 {
138   if (sym->ts.interface == sym)
139     {
140       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
141                  sym->name, &sym->declared_at);
142       return FAILURE;
143     }
144   if (sym->ts.interface->attr.procedure)
145     {
146       gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
147                  "in a later PROCEDURE statement", sym->ts.interface->name,
148                  sym->name, &sym->declared_at);
149       return FAILURE;
150     }
151
152   /* Get the attributes from the interface (now resolved).  */
153   if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
154     {
155       gfc_symbol *ifc = sym->ts.interface;
156       resolve_symbol (ifc);
157
158       if (ifc->attr.intrinsic)
159         resolve_intrinsic (ifc, &ifc->declared_at);
160
161       if (ifc->result)
162         sym->ts = ifc->result->ts;
163       else   
164         sym->ts = ifc->ts;
165       sym->ts.interface = ifc;
166       sym->attr.function = ifc->attr.function;
167       sym->attr.subroutine = ifc->attr.subroutine;
168       gfc_copy_formal_args (sym, ifc);
169
170       sym->attr.allocatable = ifc->attr.allocatable;
171       sym->attr.pointer = ifc->attr.pointer;
172       sym->attr.pure = ifc->attr.pure;
173       sym->attr.elemental = ifc->attr.elemental;
174       sym->attr.dimension = ifc->attr.dimension;
175       sym->attr.contiguous = ifc->attr.contiguous;
176       sym->attr.recursive = ifc->attr.recursive;
177       sym->attr.always_explicit = ifc->attr.always_explicit;
178       sym->attr.ext_attr |= ifc->attr.ext_attr;
179       /* Copy array spec.  */
180       sym->as = gfc_copy_array_spec (ifc->as);
181       if (sym->as)
182         {
183           int i;
184           for (i = 0; i < sym->as->rank; i++)
185             {
186               gfc_expr_replace_symbols (sym->as->lower[i], sym);
187               gfc_expr_replace_symbols (sym->as->upper[i], sym);
188             }
189         }
190       /* Copy char length.  */
191       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
192         {
193           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
194           gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
195           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
196               && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
197             return FAILURE;
198         }
199     }
200   else if (sym->ts.interface->name[0] != '\0')
201     {
202       gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
203                  sym->ts.interface->name, sym->name, &sym->declared_at);
204       return FAILURE;
205     }
206
207   return SUCCESS;
208 }
209
210
211 /* Resolve types of formal argument lists.  These have to be done early so that
212    the formal argument lists of module procedures can be copied to the
213    containing module before the individual procedures are resolved
214    individually.  We also resolve argument lists of procedures in interface
215    blocks because they are self-contained scoping units.
216
217    Since a dummy argument cannot be a non-dummy procedure, the only
218    resort left for untyped names are the IMPLICIT types.  */
219
220 static void
221 resolve_formal_arglist (gfc_symbol *proc)
222 {
223   gfc_formal_arglist *f;
224   gfc_symbol *sym;
225   int i;
226
227   if (proc->result != NULL)
228     sym = proc->result;
229   else
230     sym = proc;
231
232   if (gfc_elemental (proc)
233       || sym->attr.pointer || sym->attr.allocatable
234       || (sym->as && sym->as->rank > 0))
235     {
236       proc->attr.always_explicit = 1;
237       sym->attr.always_explicit = 1;
238     }
239
240   formal_arg_flag = 1;
241
242   for (f = proc->formal; f; f = f->next)
243     {
244       sym = f->sym;
245
246       if (sym == NULL)
247         {
248           /* Alternate return placeholder.  */
249           if (gfc_elemental (proc))
250             gfc_error ("Alternate return specifier in elemental subroutine "
251                        "'%s' at %L is not allowed", proc->name,
252                        &proc->declared_at);
253           if (proc->attr.function)
254             gfc_error ("Alternate return specifier in function "
255                        "'%s' at %L is not allowed", proc->name,
256                        &proc->declared_at);
257           continue;
258         }
259       else if (sym->attr.procedure && sym->ts.interface
260                && sym->attr.if_source != IFSRC_DECL)
261         resolve_procedure_interface (sym);
262
263       if (sym->attr.if_source != IFSRC_UNKNOWN)
264         resolve_formal_arglist (sym);
265
266       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
267         {
268           if (gfc_pure (proc) && !gfc_pure (sym))
269             {
270               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
271                          "also be PURE", sym->name, &sym->declared_at);
272               continue;
273             }
274
275           if (gfc_elemental (proc))
276             {
277               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
278                          "procedure", &sym->declared_at);
279               continue;
280             }
281
282           if (sym->attr.function
283                 && sym->ts.type == BT_UNKNOWN
284                 && sym->attr.intrinsic)
285             {
286               gfc_intrinsic_sym *isym;
287               isym = gfc_find_function (sym->name);
288               if (isym == NULL || !isym->specific)
289                 {
290                   gfc_error ("Unable to find a specific INTRINSIC procedure "
291                              "for the reference '%s' at %L", sym->name,
292                              &sym->declared_at);
293                 }
294               sym->ts = isym->ts;
295             }
296
297           continue;
298         }
299
300       if (sym->ts.type == BT_UNKNOWN)
301         {
302           if (!sym->attr.function || sym->result == sym)
303             gfc_set_default_type (sym, 1, sym->ns);
304         }
305
306       gfc_resolve_array_spec (sym->as, 0);
307
308       /* We can't tell if an array with dimension (:) is assumed or deferred
309          shape until we know if it has the pointer or allocatable attributes.
310       */
311       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
312           && !(sym->attr.pointer || sym->attr.allocatable))
313         {
314           sym->as->type = AS_ASSUMED_SHAPE;
315           for (i = 0; i < sym->as->rank; i++)
316             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
317                                                   NULL, 1);
318         }
319
320       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
321           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
322           || sym->attr.optional)
323         {
324           proc->attr.always_explicit = 1;
325           if (proc->result)
326             proc->result->attr.always_explicit = 1;
327         }
328
329       /* If the flavor is unknown at this point, it has to be a variable.
330          A procedure specification would have already set the type.  */
331
332       if (sym->attr.flavor == FL_UNKNOWN)
333         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
334
335       if (gfc_pure (proc) && !sym->attr.pointer
336           && sym->attr.flavor != FL_PROCEDURE)
337         {
338           if (proc->attr.function && sym->attr.intent != INTENT_IN)
339             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
340                        "INTENT(IN)", sym->name, proc->name,
341                        &sym->declared_at);
342
343           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
344             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
345                        "have its INTENT specified", sym->name, proc->name,
346                        &sym->declared_at);
347         }
348
349       if (gfc_elemental (proc))
350         {
351           /* F2008, C1289.  */
352           if (sym->attr.codimension)
353             {
354               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
355                          "procedure", sym->name, &sym->declared_at);
356               continue;
357             }
358
359           if (sym->as != NULL)
360             {
361               gfc_error ("Argument '%s' of elemental procedure at %L must "
362                          "be scalar", sym->name, &sym->declared_at);
363               continue;
364             }
365
366           if (sym->attr.allocatable)
367             {
368               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
369                          "have the ALLOCATABLE attribute", sym->name,
370                          &sym->declared_at);
371               continue;
372             }
373
374           if (sym->attr.pointer)
375             {
376               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
377                          "have the POINTER attribute", sym->name,
378                          &sym->declared_at);
379               continue;
380             }
381
382           if (sym->attr.flavor == FL_PROCEDURE)
383             {
384               gfc_error ("Dummy procedure '%s' not allowed in elemental "
385                          "procedure '%s' at %L", sym->name, proc->name,
386                          &sym->declared_at);
387               continue;
388             }
389
390           if (sym->attr.intent == INTENT_UNKNOWN)
391             {
392               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
393                          "have its INTENT specified", sym->name, proc->name,
394                          &sym->declared_at);
395               continue;
396             }
397         }
398
399       /* Each dummy shall be specified to be scalar.  */
400       if (proc->attr.proc == PROC_ST_FUNCTION)
401         {
402           if (sym->as != NULL)
403             {
404               gfc_error ("Argument '%s' of statement function at %L must "
405                          "be scalar", sym->name, &sym->declared_at);
406               continue;
407             }
408
409           if (sym->ts.type == BT_CHARACTER)
410             {
411               gfc_charlen *cl = sym->ts.u.cl;
412               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
413                 {
414                   gfc_error ("Character-valued argument '%s' of statement "
415                              "function at %L must have constant length",
416                              sym->name, &sym->declared_at);
417                   continue;
418                 }
419             }
420         }
421     }
422   formal_arg_flag = 0;
423 }
424
425
426 /* Work function called when searching for symbols that have argument lists
427    associated with them.  */
428
429 static void
430 find_arglists (gfc_symbol *sym)
431 {
432   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
433     return;
434
435   resolve_formal_arglist (sym);
436 }
437
438
439 /* Given a namespace, resolve all formal argument lists within the namespace.
440  */
441
442 static void
443 resolve_formal_arglists (gfc_namespace *ns)
444 {
445   if (ns == NULL)
446     return;
447
448   gfc_traverse_ns (ns, find_arglists);
449 }
450
451
452 static void
453 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
454 {
455   gfc_try t;
456
457   /* If this namespace is not a function or an entry master function,
458      ignore it.  */
459   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
460       || sym->attr.entry_master)
461     return;
462
463   /* Try to find out of what the return type is.  */
464   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
465     {
466       t = gfc_set_default_type (sym->result, 0, ns);
467
468       if (t == FAILURE && !sym->result->attr.untyped)
469         {
470           if (sym->result == sym)
471             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
472                        sym->name, &sym->declared_at);
473           else if (!sym->result->attr.proc_pointer)
474             gfc_error ("Result '%s' of contained function '%s' at %L has "
475                        "no IMPLICIT type", sym->result->name, sym->name,
476                        &sym->result->declared_at);
477           sym->result->attr.untyped = 1;
478         }
479     }
480
481   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
482      type, lists the only ways a character length value of * can be used:
483      dummy arguments of procedures, named constants, and function results
484      in external functions.  Internal function results and results of module
485      procedures are not on this list, ergo, not permitted.  */
486
487   if (sym->result->ts.type == BT_CHARACTER)
488     {
489       gfc_charlen *cl = sym->result->ts.u.cl;
490       if (!cl || !cl->length)
491         {
492           /* See if this is a module-procedure and adapt error message
493              accordingly.  */
494           bool module_proc;
495           gcc_assert (ns->parent && ns->parent->proc_name);
496           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
497
498           gfc_error ("Character-valued %s '%s' at %L must not be"
499                      " assumed length",
500                      module_proc ? _("module procedure")
501                                  : _("internal function"),
502                      sym->name, &sym->declared_at);
503         }
504     }
505 }
506
507
508 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
509    introduce duplicates.  */
510
511 static void
512 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
513 {
514   gfc_formal_arglist *f, *new_arglist;
515   gfc_symbol *new_sym;
516
517   for (; new_args != NULL; new_args = new_args->next)
518     {
519       new_sym = new_args->sym;
520       /* See if this arg is already in the formal argument list.  */
521       for (f = proc->formal; f; f = f->next)
522         {
523           if (new_sym == f->sym)
524             break;
525         }
526
527       if (f)
528         continue;
529
530       /* Add a new argument.  Argument order is not important.  */
531       new_arglist = gfc_get_formal_arglist ();
532       new_arglist->sym = new_sym;
533       new_arglist->next = proc->formal;
534       proc->formal  = new_arglist;
535     }
536 }
537
538
539 /* Flag the arguments that are not present in all entries.  */
540
541 static void
542 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
543 {
544   gfc_formal_arglist *f, *head;
545   head = new_args;
546
547   for (f = proc->formal; f; f = f->next)
548     {
549       if (f->sym == NULL)
550         continue;
551
552       for (new_args = head; new_args; new_args = new_args->next)
553         {
554           if (new_args->sym == f->sym)
555             break;
556         }
557
558       if (new_args)
559         continue;
560
561       f->sym->attr.not_always_present = 1;
562     }
563 }
564
565
566 /* Resolve alternate entry points.  If a symbol has multiple entry points we
567    create a new master symbol for the main routine, and turn the existing
568    symbol into an entry point.  */
569
570 static void
571 resolve_entries (gfc_namespace *ns)
572 {
573   gfc_namespace *old_ns;
574   gfc_code *c;
575   gfc_symbol *proc;
576   gfc_entry_list *el;
577   char name[GFC_MAX_SYMBOL_LEN + 1];
578   static int master_count = 0;
579
580   if (ns->proc_name == NULL)
581     return;
582
583   /* No need to do anything if this procedure doesn't have alternate entry
584      points.  */
585   if (!ns->entries)
586     return;
587
588   /* We may already have resolved alternate entry points.  */
589   if (ns->proc_name->attr.entry_master)
590     return;
591
592   /* If this isn't a procedure something has gone horribly wrong.  */
593   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
594
595   /* Remember the current namespace.  */
596   old_ns = gfc_current_ns;
597
598   gfc_current_ns = ns;
599
600   /* Add the main entry point to the list of entry points.  */
601   el = gfc_get_entry_list ();
602   el->sym = ns->proc_name;
603   el->id = 0;
604   el->next = ns->entries;
605   ns->entries = el;
606   ns->proc_name->attr.entry = 1;
607
608   /* If it is a module function, it needs to be in the right namespace
609      so that gfc_get_fake_result_decl can gather up the results. The
610      need for this arose in get_proc_name, where these beasts were
611      left in their own namespace, to keep prior references linked to
612      the entry declaration.*/
613   if (ns->proc_name->attr.function
614       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
615     el->sym->ns = ns;
616
617   /* Do the same for entries where the master is not a module
618      procedure.  These are retained in the module namespace because
619      of the module procedure declaration.  */
620   for (el = el->next; el; el = el->next)
621     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
622           && el->sym->attr.mod_proc)
623       el->sym->ns = ns;
624   el = ns->entries;
625
626   /* Add an entry statement for it.  */
627   c = gfc_get_code ();
628   c->op = EXEC_ENTRY;
629   c->ext.entry = el;
630   c->next = ns->code;
631   ns->code = c;
632
633   /* Create a new symbol for the master function.  */
634   /* Give the internal function a unique name (within this file).
635      Also include the function name so the user has some hope of figuring
636      out what is going on.  */
637   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
638             master_count++, ns->proc_name->name);
639   gfc_get_ha_symbol (name, &proc);
640   gcc_assert (proc != NULL);
641
642   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
643   if (ns->proc_name->attr.subroutine)
644     gfc_add_subroutine (&proc->attr, proc->name, NULL);
645   else
646     {
647       gfc_symbol *sym;
648       gfc_typespec *ts, *fts;
649       gfc_array_spec *as, *fas;
650       gfc_add_function (&proc->attr, proc->name, NULL);
651       proc->result = proc;
652       fas = ns->entries->sym->as;
653       fas = fas ? fas : ns->entries->sym->result->as;
654       fts = &ns->entries->sym->result->ts;
655       if (fts->type == BT_UNKNOWN)
656         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
657       for (el = ns->entries->next; el; el = el->next)
658         {
659           ts = &el->sym->result->ts;
660           as = el->sym->as;
661           as = as ? as : el->sym->result->as;
662           if (ts->type == BT_UNKNOWN)
663             ts = gfc_get_default_type (el->sym->result->name, NULL);
664
665           if (! gfc_compare_types (ts, fts)
666               || (el->sym->result->attr.dimension
667                   != ns->entries->sym->result->attr.dimension)
668               || (el->sym->result->attr.pointer
669                   != ns->entries->sym->result->attr.pointer))
670             break;
671           else if (as && fas && ns->entries->sym->result != el->sym->result
672                       && gfc_compare_array_spec (as, fas) == 0)
673             gfc_error ("Function %s at %L has entries with mismatched "
674                        "array specifications", ns->entries->sym->name,
675                        &ns->entries->sym->declared_at);
676           /* The characteristics need to match and thus both need to have
677              the same string length, i.e. both len=*, or both len=4.
678              Having both len=<variable> is also possible, but difficult to
679              check at compile time.  */
680           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
681                    && (((ts->u.cl->length && !fts->u.cl->length)
682                         ||(!ts->u.cl->length && fts->u.cl->length))
683                        || (ts->u.cl->length
684                            && ts->u.cl->length->expr_type
685                               != fts->u.cl->length->expr_type)
686                        || (ts->u.cl->length
687                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
688                            && mpz_cmp (ts->u.cl->length->value.integer,
689                                        fts->u.cl->length->value.integer) != 0)))
690             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
691                             "entries returning variables of different "
692                             "string lengths", ns->entries->sym->name,
693                             &ns->entries->sym->declared_at);
694         }
695
696       if (el == NULL)
697         {
698           sym = ns->entries->sym->result;
699           /* All result types the same.  */
700           proc->ts = *fts;
701           if (sym->attr.dimension)
702             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
703           if (sym->attr.pointer)
704             gfc_add_pointer (&proc->attr, NULL);
705         }
706       else
707         {
708           /* Otherwise the result will be passed through a union by
709              reference.  */
710           proc->attr.mixed_entry_master = 1;
711           for (el = ns->entries; el; el = el->next)
712             {
713               sym = el->sym->result;
714               if (sym->attr.dimension)
715                 {
716                   if (el == ns->entries)
717                     gfc_error ("FUNCTION result %s can't be an array in "
718                                "FUNCTION %s at %L", sym->name,
719                                ns->entries->sym->name, &sym->declared_at);
720                   else
721                     gfc_error ("ENTRY result %s can't be an array in "
722                                "FUNCTION %s at %L", sym->name,
723                                ns->entries->sym->name, &sym->declared_at);
724                 }
725               else if (sym->attr.pointer)
726                 {
727                   if (el == ns->entries)
728                     gfc_error ("FUNCTION result %s can't be a POINTER in "
729                                "FUNCTION %s at %L", sym->name,
730                                ns->entries->sym->name, &sym->declared_at);
731                   else
732                     gfc_error ("ENTRY result %s can't be a POINTER in "
733                                "FUNCTION %s at %L", sym->name,
734                                ns->entries->sym->name, &sym->declared_at);
735                 }
736               else
737                 {
738                   ts = &sym->ts;
739                   if (ts->type == BT_UNKNOWN)
740                     ts = gfc_get_default_type (sym->name, NULL);
741                   switch (ts->type)
742                     {
743                     case BT_INTEGER:
744                       if (ts->kind == gfc_default_integer_kind)
745                         sym = NULL;
746                       break;
747                     case BT_REAL:
748                       if (ts->kind == gfc_default_real_kind
749                           || ts->kind == gfc_default_double_kind)
750                         sym = NULL;
751                       break;
752                     case BT_COMPLEX:
753                       if (ts->kind == gfc_default_complex_kind)
754                         sym = NULL;
755                       break;
756                     case BT_LOGICAL:
757                       if (ts->kind == gfc_default_logical_kind)
758                         sym = NULL;
759                       break;
760                     case BT_UNKNOWN:
761                       /* We will issue error elsewhere.  */
762                       sym = NULL;
763                       break;
764                     default:
765                       break;
766                     }
767                   if (sym)
768                     {
769                       if (el == ns->entries)
770                         gfc_error ("FUNCTION result %s can't be of type %s "
771                                    "in FUNCTION %s at %L", sym->name,
772                                    gfc_typename (ts), ns->entries->sym->name,
773                                    &sym->declared_at);
774                       else
775                         gfc_error ("ENTRY result %s can't be of type %s "
776                                    "in FUNCTION %s at %L", sym->name,
777                                    gfc_typename (ts), ns->entries->sym->name,
778                                    &sym->declared_at);
779                     }
780                 }
781             }
782         }
783     }
784   proc->attr.access = ACCESS_PRIVATE;
785   proc->attr.entry_master = 1;
786
787   /* Merge all the entry point arguments.  */
788   for (el = ns->entries; el; el = el->next)
789     merge_argument_lists (proc, el->sym->formal);
790
791   /* Check the master formal arguments for any that are not
792      present in all entry points.  */
793   for (el = ns->entries; el; el = el->next)
794     check_argument_lists (proc, el->sym->formal);
795
796   /* Use the master function for the function body.  */
797   ns->proc_name = proc;
798
799   /* Finalize the new symbols.  */
800   gfc_commit_symbols ();
801
802   /* Restore the original namespace.  */
803   gfc_current_ns = old_ns;
804 }
805
806
807 /* Resolve common variables.  */
808 static void
809 resolve_common_vars (gfc_symbol *sym, bool named_common)
810 {
811   gfc_symbol *csym = sym;
812
813   for (; csym; csym = csym->common_next)
814     {
815       if (csym->value || csym->attr.data)
816         {
817           if (!csym->ns->is_block_data)
818             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
819                             "but only in BLOCK DATA initialization is "
820                             "allowed", csym->name, &csym->declared_at);
821           else if (!named_common)
822             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
823                             "in a blank COMMON but initialization is only "
824                             "allowed in named common blocks", csym->name,
825                             &csym->declared_at);
826         }
827
828       if (csym->ts.type != BT_DERIVED)
829         continue;
830
831       if (!(csym->ts.u.derived->attr.sequence
832             || csym->ts.u.derived->attr.is_bind_c))
833         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
834                        "has neither the SEQUENCE nor the BIND(C) "
835                        "attribute", csym->name, &csym->declared_at);
836       if (csym->ts.u.derived->attr.alloc_comp)
837         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
838                        "has an ultimate component that is "
839                        "allocatable", csym->name, &csym->declared_at);
840       if (gfc_has_default_initializer (csym->ts.u.derived))
841         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
842                        "may not have default initializer", csym->name,
843                        &csym->declared_at);
844
845       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
846         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
847     }
848 }
849
850 /* Resolve common blocks.  */
851 static void
852 resolve_common_blocks (gfc_symtree *common_root)
853 {
854   gfc_symbol *sym;
855
856   if (common_root == NULL)
857     return;
858
859   if (common_root->left)
860     resolve_common_blocks (common_root->left);
861   if (common_root->right)
862     resolve_common_blocks (common_root->right);
863
864   resolve_common_vars (common_root->n.common->head, true);
865
866   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
867   if (sym == NULL)
868     return;
869
870   if (sym->attr.flavor == FL_PARAMETER)
871     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
872                sym->name, &common_root->n.common->where, &sym->declared_at);
873
874   if (sym->attr.intrinsic)
875     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
876                sym->name, &common_root->n.common->where);
877   else if (sym->attr.result
878            || gfc_is_function_return_value (sym, gfc_current_ns))
879     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
880                     "that is also a function result", sym->name,
881                     &common_root->n.common->where);
882   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
883            && sym->attr.proc != PROC_ST_FUNCTION)
884     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
885                     "that is also a global procedure", sym->name,
886                     &common_root->n.common->where);
887 }
888
889
890 /* Resolve contained function types.  Because contained functions can call one
891    another, they have to be worked out before any of the contained procedures
892    can be resolved.
893
894    The good news is that if a function doesn't already have a type, the only
895    way it can get one is through an IMPLICIT type or a RESULT variable, because
896    by definition contained functions are contained namespace they're contained
897    in, not in a sibling or parent namespace.  */
898
899 static void
900 resolve_contained_functions (gfc_namespace *ns)
901 {
902   gfc_namespace *child;
903   gfc_entry_list *el;
904
905   resolve_formal_arglists (ns);
906
907   for (child = ns->contained; child; child = child->sibling)
908     {
909       /* Resolve alternate entry points first.  */
910       resolve_entries (child);
911
912       /* Then check function return types.  */
913       resolve_contained_fntype (child->proc_name, child);
914       for (el = child->entries; el; el = el->next)
915         resolve_contained_fntype (el->sym, child);
916     }
917 }
918
919
920 /* Resolve all of the elements of a structure constructor and make sure that
921    the types are correct. The 'init' flag indicates that the given
922    constructor is an initializer.  */
923
924 static gfc_try
925 resolve_structure_cons (gfc_expr *expr, int init)
926 {
927   gfc_constructor *cons;
928   gfc_component *comp;
929   gfc_try t;
930   symbol_attribute a;
931
932   t = SUCCESS;
933   cons = gfc_constructor_first (expr->value.constructor);
934   /* A constructor may have references if it is the result of substituting a
935      parameter variable.  In this case we just pull out the component we
936      want.  */
937   if (expr->ref)
938     comp = expr->ref->u.c.sym->components;
939   else
940     comp = expr->ts.u.derived->components;
941
942   /* See if the user is trying to invoke a structure constructor for one of
943      the iso_c_binding derived types.  */
944   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
945       && expr->ts.u.derived->ts.is_iso_c && cons
946       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
947     {
948       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
949                  expr->ts.u.derived->name, &(expr->where));
950       return FAILURE;
951     }
952
953   /* Return if structure constructor is c_null_(fun)prt.  */
954   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
955       && expr->ts.u.derived->ts.is_iso_c && cons
956       && cons->expr && cons->expr->expr_type == EXPR_NULL)
957     return SUCCESS;
958
959   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
960     {
961       int rank;
962
963       if (!cons->expr)
964         continue;
965
966       if (gfc_resolve_expr (cons->expr) == FAILURE)
967         {
968           t = FAILURE;
969           continue;
970         }
971
972       rank = comp->as ? comp->as->rank : 0;
973       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
974           && (comp->attr.allocatable || cons->expr->rank))
975         {
976           gfc_error ("The rank of the element in the derived type "
977                      "constructor at %L does not match that of the "
978                      "component (%d/%d)", &cons->expr->where,
979                      cons->expr->rank, rank);
980           t = FAILURE;
981         }
982
983       /* If we don't have the right type, try to convert it.  */
984
985       if (!comp->attr.proc_pointer &&
986           !gfc_compare_types (&cons->expr->ts, &comp->ts))
987         {
988           t = FAILURE;
989           if (strcmp (comp->name, "$extends") == 0)
990             {
991               /* Can afford to be brutal with the $extends initializer.
992                  The derived type can get lost because it is PRIVATE
993                  but it is not usage constrained by the standard.  */
994               cons->expr->ts = comp->ts;
995               t = SUCCESS;
996             }
997           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
998             gfc_error ("The element in the derived type constructor at %L, "
999                        "for pointer component '%s', is %s but should be %s",
1000                        &cons->expr->where, comp->name,
1001                        gfc_basic_typename (cons->expr->ts.type),
1002                        gfc_basic_typename (comp->ts.type));
1003           else
1004             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1005         }
1006
1007       /* For strings, the length of the constructor should be the same as
1008          the one of the structure, ensure this if the lengths are known at
1009          compile time and when we are dealing with PARAMETER or structure
1010          constructors.  */
1011       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1012           && comp->ts.u.cl->length
1013           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1014           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1015           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1016           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1017                       comp->ts.u.cl->length->value.integer) != 0)
1018         {
1019           if (cons->expr->expr_type == EXPR_VARIABLE
1020               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1021             {
1022               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1023                  to make use of the gfc_resolve_character_array_constructor
1024                  machinery.  The expression is later simplified away to
1025                  an array of string literals.  */
1026               gfc_expr *para = cons->expr;
1027               cons->expr = gfc_get_expr ();
1028               cons->expr->ts = para->ts;
1029               cons->expr->where = para->where;
1030               cons->expr->expr_type = EXPR_ARRAY;
1031               cons->expr->rank = para->rank;
1032               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1033               gfc_constructor_append_expr (&cons->expr->value.constructor,
1034                                            para, &cons->expr->where);
1035             }
1036           if (cons->expr->expr_type == EXPR_ARRAY)
1037             {
1038               gfc_constructor *p;
1039               p = gfc_constructor_first (cons->expr->value.constructor);
1040               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1041                 {
1042                   gfc_charlen *cl, *cl2;
1043
1044                   cl2 = NULL;
1045                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1046                     {
1047                       if (cl == cons->expr->ts.u.cl)
1048                         break;
1049                       cl2 = cl;
1050                     }
1051
1052                   gcc_assert (cl);
1053
1054                   if (cl2)
1055                     cl2->next = cl->next;
1056
1057                   gfc_free_expr (cl->length);
1058                   gfc_free (cl);
1059                 }
1060
1061               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1062               cons->expr->ts.u.cl->length_from_typespec = true;
1063               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1064               gfc_resolve_character_array_constructor (cons->expr);
1065             }
1066         }
1067
1068       if (cons->expr->expr_type == EXPR_NULL
1069           && !(comp->attr.pointer || comp->attr.allocatable
1070                || comp->attr.proc_pointer
1071                || (comp->ts.type == BT_CLASS
1072                    && (CLASS_DATA (comp)->attr.class_pointer
1073                        || CLASS_DATA (comp)->attr.allocatable))))
1074         {
1075           t = FAILURE;
1076           gfc_error ("The NULL in the derived type constructor at %L is "
1077                      "being applied to component '%s', which is neither "
1078                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1079                      comp->name);
1080         }
1081
1082       if (!comp->attr.pointer || cons->expr->expr_type == EXPR_NULL)
1083         continue;
1084
1085       a = gfc_expr_attr (cons->expr);
1086
1087       if (!a.pointer && !a.target)
1088         {
1089           t = FAILURE;
1090           gfc_error ("The element in the derived type constructor at %L, "
1091                      "for pointer component '%s' should be a POINTER or "
1092                      "a TARGET", &cons->expr->where, comp->name);
1093         }
1094
1095       if (init)
1096         {
1097           /* F08:C461. Additional checks for pointer initialization.  */
1098           if (a.allocatable)
1099             {
1100               t = FAILURE;
1101               gfc_error ("Pointer initialization target at %L "
1102                          "must not be ALLOCATABLE ", &cons->expr->where);
1103             }
1104           if (!a.save)
1105             {
1106               t = FAILURE;
1107               gfc_error ("Pointer initialization target at %L "
1108                          "must have the SAVE attribute", &cons->expr->where);
1109             }
1110         }
1111
1112       /* F2003, C1272 (3).  */
1113       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1114           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1115               || gfc_is_coindexed (cons->expr)))
1116         {
1117           t = FAILURE;
1118           gfc_error ("Invalid expression in the derived type constructor for "
1119                      "pointer component '%s' at %L in PURE procedure",
1120                      comp->name, &cons->expr->where);
1121         }
1122
1123     }
1124
1125   return t;
1126 }
1127
1128
1129 /****************** Expression name resolution ******************/
1130
1131 /* Returns 0 if a symbol was not declared with a type or
1132    attribute declaration statement, nonzero otherwise.  */
1133
1134 static int
1135 was_declared (gfc_symbol *sym)
1136 {
1137   symbol_attribute a;
1138
1139   a = sym->attr;
1140
1141   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1142     return 1;
1143
1144   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1145       || a.optional || a.pointer || a.save || a.target || a.volatile_
1146       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1147       || a.asynchronous || a.codimension)
1148     return 1;
1149
1150   return 0;
1151 }
1152
1153
1154 /* Determine if a symbol is generic or not.  */
1155
1156 static int
1157 generic_sym (gfc_symbol *sym)
1158 {
1159   gfc_symbol *s;
1160
1161   if (sym->attr.generic ||
1162       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1163     return 1;
1164
1165   if (was_declared (sym) || sym->ns->parent == NULL)
1166     return 0;
1167
1168   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1169   
1170   if (s != NULL)
1171     {
1172       if (s == sym)
1173         return 0;
1174       else
1175         return generic_sym (s);
1176     }
1177
1178   return 0;
1179 }
1180
1181
1182 /* Determine if a symbol is specific or not.  */
1183
1184 static int
1185 specific_sym (gfc_symbol *sym)
1186 {
1187   gfc_symbol *s;
1188
1189   if (sym->attr.if_source == IFSRC_IFBODY
1190       || sym->attr.proc == PROC_MODULE
1191       || sym->attr.proc == PROC_INTERNAL
1192       || sym->attr.proc == PROC_ST_FUNCTION
1193       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1194       || sym->attr.external)
1195     return 1;
1196
1197   if (was_declared (sym) || sym->ns->parent == NULL)
1198     return 0;
1199
1200   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1201
1202   return (s == NULL) ? 0 : specific_sym (s);
1203 }
1204
1205
1206 /* Figure out if the procedure is specific, generic or unknown.  */
1207
1208 typedef enum
1209 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1210 proc_type;
1211
1212 static proc_type
1213 procedure_kind (gfc_symbol *sym)
1214 {
1215   if (generic_sym (sym))
1216     return PTYPE_GENERIC;
1217
1218   if (specific_sym (sym))
1219     return PTYPE_SPECIFIC;
1220
1221   return PTYPE_UNKNOWN;
1222 }
1223
1224 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1225    is nonzero when matching actual arguments.  */
1226
1227 static int need_full_assumed_size = 0;
1228
1229 static bool
1230 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1231 {
1232   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1233       return false;
1234
1235   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1236      What should it be?  */
1237   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1238           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1239                && (e->ref->u.ar.type == AR_FULL))
1240     {
1241       gfc_error ("The upper bound in the last dimension must "
1242                  "appear in the reference to the assumed size "
1243                  "array '%s' at %L", sym->name, &e->where);
1244       return true;
1245     }
1246   return false;
1247 }
1248
1249
1250 /* Look for bad assumed size array references in argument expressions
1251   of elemental and array valued intrinsic procedures.  Since this is
1252   called from procedure resolution functions, it only recurses at
1253   operators.  */
1254
1255 static bool
1256 resolve_assumed_size_actual (gfc_expr *e)
1257 {
1258   if (e == NULL)
1259    return false;
1260
1261   switch (e->expr_type)
1262     {
1263     case EXPR_VARIABLE:
1264       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1265         return true;
1266       break;
1267
1268     case EXPR_OP:
1269       if (resolve_assumed_size_actual (e->value.op.op1)
1270           || resolve_assumed_size_actual (e->value.op.op2))
1271         return true;
1272       break;
1273
1274     default:
1275       break;
1276     }
1277   return false;
1278 }
1279
1280
1281 /* Check a generic procedure, passed as an actual argument, to see if
1282    there is a matching specific name.  If none, it is an error, and if
1283    more than one, the reference is ambiguous.  */
1284 static int
1285 count_specific_procs (gfc_expr *e)
1286 {
1287   int n;
1288   gfc_interface *p;
1289   gfc_symbol *sym;
1290         
1291   n = 0;
1292   sym = e->symtree->n.sym;
1293
1294   for (p = sym->generic; p; p = p->next)
1295     if (strcmp (sym->name, p->sym->name) == 0)
1296       {
1297         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1298                                        sym->name);
1299         n++;
1300       }
1301
1302   if (n > 1)
1303     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1304                &e->where);
1305
1306   if (n == 0)
1307     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1308                "argument at %L", sym->name, &e->where);
1309
1310   return n;
1311 }
1312
1313
1314 /* See if a call to sym could possibly be a not allowed RECURSION because of
1315    a missing RECURIVE declaration.  This means that either sym is the current
1316    context itself, or sym is the parent of a contained procedure calling its
1317    non-RECURSIVE containing procedure.
1318    This also works if sym is an ENTRY.  */
1319
1320 static bool
1321 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1322 {
1323   gfc_symbol* proc_sym;
1324   gfc_symbol* context_proc;
1325   gfc_namespace* real_context;
1326
1327   if (sym->attr.flavor == FL_PROGRAM)
1328     return false;
1329
1330   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1331
1332   /* If we've got an ENTRY, find real procedure.  */
1333   if (sym->attr.entry && sym->ns->entries)
1334     proc_sym = sym->ns->entries->sym;
1335   else
1336     proc_sym = sym;
1337
1338   /* If sym is RECURSIVE, all is well of course.  */
1339   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1340     return false;
1341
1342   /* Find the context procedure's "real" symbol if it has entries.
1343      We look for a procedure symbol, so recurse on the parents if we don't
1344      find one (like in case of a BLOCK construct).  */
1345   for (real_context = context; ; real_context = real_context->parent)
1346     {
1347       /* We should find something, eventually!  */
1348       gcc_assert (real_context);
1349
1350       context_proc = (real_context->entries ? real_context->entries->sym
1351                                             : real_context->proc_name);
1352
1353       /* In some special cases, there may not be a proc_name, like for this
1354          invalid code:
1355          real(bad_kind()) function foo () ...
1356          when checking the call to bad_kind ().
1357          In these cases, we simply return here and assume that the
1358          call is ok.  */
1359       if (!context_proc)
1360         return false;
1361
1362       if (context_proc->attr.flavor != FL_LABEL)
1363         break;
1364     }
1365
1366   /* A call from sym's body to itself is recursion, of course.  */
1367   if (context_proc == proc_sym)
1368     return true;
1369
1370   /* The same is true if context is a contained procedure and sym the
1371      containing one.  */
1372   if (context_proc->attr.contained)
1373     {
1374       gfc_symbol* parent_proc;
1375
1376       gcc_assert (context->parent);
1377       parent_proc = (context->parent->entries ? context->parent->entries->sym
1378                                               : context->parent->proc_name);
1379
1380       if (parent_proc == proc_sym)
1381         return true;
1382     }
1383
1384   return false;
1385 }
1386
1387
1388 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1389    its typespec and formal argument list.  */
1390
1391 static gfc_try
1392 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1393 {
1394   gfc_intrinsic_sym* isym;
1395   const char* symstd;
1396
1397   if (sym->formal)
1398     return SUCCESS;
1399
1400   /* We already know this one is an intrinsic, so we don't call
1401      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1402      gfc_find_subroutine directly to check whether it is a function or
1403      subroutine.  */
1404
1405   if ((isym = gfc_find_function (sym->name)))
1406     {
1407       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1408           && !sym->attr.implicit_type)
1409         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1410                       " ignored", sym->name, &sym->declared_at);
1411
1412       if (!sym->attr.function &&
1413           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1414         return FAILURE;
1415
1416       sym->ts = isym->ts;
1417     }
1418   else if ((isym = gfc_find_subroutine (sym->name)))
1419     {
1420       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1421         {
1422           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1423                       " specifier", sym->name, &sym->declared_at);
1424           return FAILURE;
1425         }
1426
1427       if (!sym->attr.subroutine &&
1428           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1429         return FAILURE;
1430     }
1431   else
1432     {
1433       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1434                  &sym->declared_at);
1435       return FAILURE;
1436     }
1437
1438   gfc_copy_formal_args_intr (sym, isym);
1439
1440   /* Check it is actually available in the standard settings.  */
1441   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1442       == FAILURE)
1443     {
1444       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1445                  " available in the current standard settings but %s.  Use"
1446                  " an appropriate -std=* option or enable -fall-intrinsics"
1447                  " in order to use it.",
1448                  sym->name, &sym->declared_at, symstd);
1449       return FAILURE;
1450     }
1451
1452   return SUCCESS;
1453 }
1454
1455
1456 /* Resolve a procedure expression, like passing it to a called procedure or as
1457    RHS for a procedure pointer assignment.  */
1458
1459 static gfc_try
1460 resolve_procedure_expression (gfc_expr* expr)
1461 {
1462   gfc_symbol* sym;
1463
1464   if (expr->expr_type != EXPR_VARIABLE)
1465     return SUCCESS;
1466   gcc_assert (expr->symtree);
1467
1468   sym = expr->symtree->n.sym;
1469
1470   if (sym->attr.intrinsic)
1471     resolve_intrinsic (sym, &expr->where);
1472
1473   if (sym->attr.flavor != FL_PROCEDURE
1474       || (sym->attr.function && sym->result == sym))
1475     return SUCCESS;
1476
1477   /* A non-RECURSIVE procedure that is used as procedure expression within its
1478      own body is in danger of being called recursively.  */
1479   if (is_illegal_recursion (sym, gfc_current_ns))
1480     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1481                  " itself recursively.  Declare it RECURSIVE or use"
1482                  " -frecursive", sym->name, &expr->where);
1483   
1484   return SUCCESS;
1485 }
1486
1487
1488 /* Resolve an actual argument list.  Most of the time, this is just
1489    resolving the expressions in the list.
1490    The exception is that we sometimes have to decide whether arguments
1491    that look like procedure arguments are really simple variable
1492    references.  */
1493
1494 static gfc_try
1495 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1496                         bool no_formal_args)
1497 {
1498   gfc_symbol *sym;
1499   gfc_symtree *parent_st;
1500   gfc_expr *e;
1501   int save_need_full_assumed_size;
1502   gfc_component *comp;
1503
1504   for (; arg; arg = arg->next)
1505     {
1506       e = arg->expr;
1507       if (e == NULL)
1508         {
1509           /* Check the label is a valid branching target.  */
1510           if (arg->label)
1511             {
1512               if (arg->label->defined == ST_LABEL_UNKNOWN)
1513                 {
1514                   gfc_error ("Label %d referenced at %L is never defined",
1515                              arg->label->value, &arg->label->where);
1516                   return FAILURE;
1517                 }
1518             }
1519           continue;
1520         }
1521
1522       if (gfc_is_proc_ptr_comp (e, &comp))
1523         {
1524           e->ts = comp->ts;
1525           if (e->expr_type == EXPR_PPC)
1526             {
1527               if (comp->as != NULL)
1528                 e->rank = comp->as->rank;
1529               e->expr_type = EXPR_FUNCTION;
1530             }
1531           if (gfc_resolve_expr (e) == FAILURE)                          
1532             return FAILURE; 
1533           goto argument_list;
1534         }
1535
1536       if (e->expr_type == EXPR_VARIABLE
1537             && e->symtree->n.sym->attr.generic
1538             && no_formal_args
1539             && count_specific_procs (e) != 1)
1540         return FAILURE;
1541
1542       if (e->ts.type != BT_PROCEDURE)
1543         {
1544           save_need_full_assumed_size = need_full_assumed_size;
1545           if (e->expr_type != EXPR_VARIABLE)
1546             need_full_assumed_size = 0;
1547           if (gfc_resolve_expr (e) != SUCCESS)
1548             return FAILURE;
1549           need_full_assumed_size = save_need_full_assumed_size;
1550           goto argument_list;
1551         }
1552
1553       /* See if the expression node should really be a variable reference.  */
1554
1555       sym = e->symtree->n.sym;
1556
1557       if (sym->attr.flavor == FL_PROCEDURE
1558           || sym->attr.intrinsic
1559           || sym->attr.external)
1560         {
1561           int actual_ok;
1562
1563           /* If a procedure is not already determined to be something else
1564              check if it is intrinsic.  */
1565           if (!sym->attr.intrinsic
1566               && !(sym->attr.external || sym->attr.use_assoc
1567                    || sym->attr.if_source == IFSRC_IFBODY)
1568               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1569             sym->attr.intrinsic = 1;
1570
1571           if (sym->attr.proc == PROC_ST_FUNCTION)
1572             {
1573               gfc_error ("Statement function '%s' at %L is not allowed as an "
1574                          "actual argument", sym->name, &e->where);
1575             }
1576
1577           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1578                                                sym->attr.subroutine);
1579           if (sym->attr.intrinsic && actual_ok == 0)
1580             {
1581               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1582                          "actual argument", sym->name, &e->where);
1583             }
1584
1585           if (sym->attr.contained && !sym->attr.use_assoc
1586               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1587             {
1588               gfc_error ("Internal procedure '%s' is not allowed as an "
1589                          "actual argument at %L", sym->name, &e->where);
1590             }
1591
1592           if (sym->attr.elemental && !sym->attr.intrinsic)
1593             {
1594               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1595                          "allowed as an actual argument at %L", sym->name,
1596                          &e->where);
1597             }
1598
1599           /* Check if a generic interface has a specific procedure
1600             with the same name before emitting an error.  */
1601           if (sym->attr.generic && count_specific_procs (e) != 1)
1602             return FAILURE;
1603           
1604           /* Just in case a specific was found for the expression.  */
1605           sym = e->symtree->n.sym;
1606
1607           /* If the symbol is the function that names the current (or
1608              parent) scope, then we really have a variable reference.  */
1609
1610           if (gfc_is_function_return_value (sym, sym->ns))
1611             goto got_variable;
1612
1613           /* If all else fails, see if we have a specific intrinsic.  */
1614           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1615             {
1616               gfc_intrinsic_sym *isym;
1617
1618               isym = gfc_find_function (sym->name);
1619               if (isym == NULL || !isym->specific)
1620                 {
1621                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1622                              "for the reference '%s' at %L", sym->name,
1623                              &e->where);
1624                   return FAILURE;
1625                 }
1626               sym->ts = isym->ts;
1627               sym->attr.intrinsic = 1;
1628               sym->attr.function = 1;
1629             }
1630
1631           if (gfc_resolve_expr (e) == FAILURE)
1632             return FAILURE;
1633           goto argument_list;
1634         }
1635
1636       /* See if the name is a module procedure in a parent unit.  */
1637
1638       if (was_declared (sym) || sym->ns->parent == NULL)
1639         goto got_variable;
1640
1641       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1642         {
1643           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1644           return FAILURE;
1645         }
1646
1647       if (parent_st == NULL)
1648         goto got_variable;
1649
1650       sym = parent_st->n.sym;
1651       e->symtree = parent_st;           /* Point to the right thing.  */
1652
1653       if (sym->attr.flavor == FL_PROCEDURE
1654           || sym->attr.intrinsic
1655           || sym->attr.external)
1656         {
1657           if (gfc_resolve_expr (e) == FAILURE)
1658             return FAILURE;
1659           goto argument_list;
1660         }
1661
1662     got_variable:
1663       e->expr_type = EXPR_VARIABLE;
1664       e->ts = sym->ts;
1665       if (sym->as != NULL)
1666         {
1667           e->rank = sym->as->rank;
1668           e->ref = gfc_get_ref ();
1669           e->ref->type = REF_ARRAY;
1670           e->ref->u.ar.type = AR_FULL;
1671           e->ref->u.ar.as = sym->as;
1672         }
1673
1674       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1675          primary.c (match_actual_arg). If above code determines that it
1676          is a  variable instead, it needs to be resolved as it was not
1677          done at the beginning of this function.  */
1678       save_need_full_assumed_size = need_full_assumed_size;
1679       if (e->expr_type != EXPR_VARIABLE)
1680         need_full_assumed_size = 0;
1681       if (gfc_resolve_expr (e) != SUCCESS)
1682         return FAILURE;
1683       need_full_assumed_size = save_need_full_assumed_size;
1684
1685     argument_list:
1686       /* Check argument list functions %VAL, %LOC and %REF.  There is
1687          nothing to do for %REF.  */
1688       if (arg->name && arg->name[0] == '%')
1689         {
1690           if (strncmp ("%VAL", arg->name, 4) == 0)
1691             {
1692               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1693                 {
1694                   gfc_error ("By-value argument at %L is not of numeric "
1695                              "type", &e->where);
1696                   return FAILURE;
1697                 }
1698
1699               if (e->rank)
1700                 {
1701                   gfc_error ("By-value argument at %L cannot be an array or "
1702                              "an array section", &e->where);
1703                 return FAILURE;
1704                 }
1705
1706               /* Intrinsics are still PROC_UNKNOWN here.  However,
1707                  since same file external procedures are not resolvable
1708                  in gfortran, it is a good deal easier to leave them to
1709                  intrinsic.c.  */
1710               if (ptype != PROC_UNKNOWN
1711                   && ptype != PROC_DUMMY
1712                   && ptype != PROC_EXTERNAL
1713                   && ptype != PROC_MODULE)
1714                 {
1715                   gfc_error ("By-value argument at %L is not allowed "
1716                              "in this context", &e->where);
1717                   return FAILURE;
1718                 }
1719             }
1720
1721           /* Statement functions have already been excluded above.  */
1722           else if (strncmp ("%LOC", arg->name, 4) == 0
1723                    && e->ts.type == BT_PROCEDURE)
1724             {
1725               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1726                 {
1727                   gfc_error ("Passing internal procedure at %L by location "
1728                              "not allowed", &e->where);
1729                   return FAILURE;
1730                 }
1731             }
1732         }
1733
1734       /* Fortran 2008, C1237.  */
1735       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1736           && gfc_has_ultimate_pointer (e))
1737         {
1738           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1739                      "component", &e->where);
1740           return FAILURE;
1741         }
1742     }
1743
1744   return SUCCESS;
1745 }
1746
1747
1748 /* Do the checks of the actual argument list that are specific to elemental
1749    procedures.  If called with c == NULL, we have a function, otherwise if
1750    expr == NULL, we have a subroutine.  */
1751
1752 static gfc_try
1753 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1754 {
1755   gfc_actual_arglist *arg0;
1756   gfc_actual_arglist *arg;
1757   gfc_symbol *esym = NULL;
1758   gfc_intrinsic_sym *isym = NULL;
1759   gfc_expr *e = NULL;
1760   gfc_intrinsic_arg *iformal = NULL;
1761   gfc_formal_arglist *eformal = NULL;
1762   bool formal_optional = false;
1763   bool set_by_optional = false;
1764   int i;
1765   int rank = 0;
1766
1767   /* Is this an elemental procedure?  */
1768   if (expr && expr->value.function.actual != NULL)
1769     {
1770       if (expr->value.function.esym != NULL
1771           && expr->value.function.esym->attr.elemental)
1772         {
1773           arg0 = expr->value.function.actual;
1774           esym = expr->value.function.esym;
1775         }
1776       else if (expr->value.function.isym != NULL
1777                && expr->value.function.isym->elemental)
1778         {
1779           arg0 = expr->value.function.actual;
1780           isym = expr->value.function.isym;
1781         }
1782       else
1783         return SUCCESS;
1784     }
1785   else if (c && c->ext.actual != NULL)
1786     {
1787       arg0 = c->ext.actual;
1788       
1789       if (c->resolved_sym)
1790         esym = c->resolved_sym;
1791       else
1792         esym = c->symtree->n.sym;
1793       gcc_assert (esym);
1794
1795       if (!esym->attr.elemental)
1796         return SUCCESS;
1797     }
1798   else
1799     return SUCCESS;
1800
1801   /* The rank of an elemental is the rank of its array argument(s).  */
1802   for (arg = arg0; arg; arg = arg->next)
1803     {
1804       if (arg->expr != NULL && arg->expr->rank > 0)
1805         {
1806           rank = arg->expr->rank;
1807           if (arg->expr->expr_type == EXPR_VARIABLE
1808               && arg->expr->symtree->n.sym->attr.optional)
1809             set_by_optional = true;
1810
1811           /* Function specific; set the result rank and shape.  */
1812           if (expr)
1813             {
1814               expr->rank = rank;
1815               if (!expr->shape && arg->expr->shape)
1816                 {
1817                   expr->shape = gfc_get_shape (rank);
1818                   for (i = 0; i < rank; i++)
1819                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1820                 }
1821             }
1822           break;
1823         }
1824     }
1825
1826   /* If it is an array, it shall not be supplied as an actual argument
1827      to an elemental procedure unless an array of the same rank is supplied
1828      as an actual argument corresponding to a nonoptional dummy argument of
1829      that elemental procedure(12.4.1.5).  */
1830   formal_optional = false;
1831   if (isym)
1832     iformal = isym->formal;
1833   else
1834     eformal = esym->formal;
1835
1836   for (arg = arg0; arg; arg = arg->next)
1837     {
1838       if (eformal)
1839         {
1840           if (eformal->sym && eformal->sym->attr.optional)
1841             formal_optional = true;
1842           eformal = eformal->next;
1843         }
1844       else if (isym && iformal)
1845         {
1846           if (iformal->optional)
1847             formal_optional = true;
1848           iformal = iformal->next;
1849         }
1850       else if (isym)
1851         formal_optional = true;
1852
1853       if (pedantic && arg->expr != NULL
1854           && arg->expr->expr_type == EXPR_VARIABLE
1855           && arg->expr->symtree->n.sym->attr.optional
1856           && formal_optional
1857           && arg->expr->rank
1858           && (set_by_optional || arg->expr->rank != rank)
1859           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1860         {
1861           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1862                        "MISSING, it cannot be the actual argument of an "
1863                        "ELEMENTAL procedure unless there is a non-optional "
1864                        "argument with the same rank (12.4.1.5)",
1865                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1866           return FAILURE;
1867         }
1868     }
1869
1870   for (arg = arg0; arg; arg = arg->next)
1871     {
1872       if (arg->expr == NULL || arg->expr->rank == 0)
1873         continue;
1874
1875       /* Being elemental, the last upper bound of an assumed size array
1876          argument must be present.  */
1877       if (resolve_assumed_size_actual (arg->expr))
1878         return FAILURE;
1879
1880       /* Elemental procedure's array actual arguments must conform.  */
1881       if (e != NULL)
1882         {
1883           if (gfc_check_conformance (arg->expr, e,
1884                                      "elemental procedure") == FAILURE)
1885             return FAILURE;
1886         }
1887       else
1888         e = arg->expr;
1889     }
1890
1891   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1892      is an array, the intent inout/out variable needs to be also an array.  */
1893   if (rank > 0 && esym && expr == NULL)
1894     for (eformal = esym->formal, arg = arg0; arg && eformal;
1895          arg = arg->next, eformal = eformal->next)
1896       if ((eformal->sym->attr.intent == INTENT_OUT
1897            || eformal->sym->attr.intent == INTENT_INOUT)
1898           && arg->expr && arg->expr->rank == 0)
1899         {
1900           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1901                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1902                      "actual argument is an array", &arg->expr->where,
1903                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1904                      : "INOUT", eformal->sym->name, esym->name);
1905           return FAILURE;
1906         }
1907   return SUCCESS;
1908 }
1909
1910
1911 /* Go through each actual argument in ACTUAL and see if it can be
1912    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1913    function being called, or NULL if not known.  */
1914
1915 static void
1916 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1917 {
1918   gfc_actual_arglist *ap;
1919   gfc_expr *expr;
1920
1921   for (ap = actual; ap; ap = ap->next)
1922     if (ap->expr
1923         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1924         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1925                                          NOT_ELEMENTAL))
1926       ap->expr->inline_noncopying_intrinsic = 1;
1927 }
1928
1929
1930 /* This function does the checking of references to global procedures
1931    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1932    77 and 95 standards.  It checks for a gsymbol for the name, making
1933    one if it does not already exist.  If it already exists, then the
1934    reference being resolved must correspond to the type of gsymbol.
1935    Otherwise, the new symbol is equipped with the attributes of the
1936    reference.  The corresponding code that is called in creating
1937    global entities is parse.c.
1938
1939    In addition, for all but -std=legacy, the gsymbols are used to
1940    check the interfaces of external procedures from the same file.
1941    The namespace of the gsymbol is resolved and then, once this is
1942    done the interface is checked.  */
1943
1944
1945 static bool
1946 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1947 {
1948   if (!gsym_ns->proc_name->attr.recursive)
1949     return true;
1950
1951   if (sym->ns == gsym_ns)
1952     return false;
1953
1954   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1955     return false;
1956
1957   return true;
1958 }
1959
1960 static bool
1961 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1962 {
1963   if (gsym_ns->entries)
1964     {
1965       gfc_entry_list *entry = gsym_ns->entries;
1966
1967       for (; entry; entry = entry->next)
1968         {
1969           if (strcmp (sym->name, entry->sym->name) == 0)
1970             {
1971               if (strcmp (gsym_ns->proc_name->name,
1972                           sym->ns->proc_name->name) == 0)
1973                 return false;
1974
1975               if (sym->ns->parent
1976                   && strcmp (gsym_ns->proc_name->name,
1977                              sym->ns->parent->proc_name->name) == 0)
1978                 return false;
1979             }
1980         }
1981     }
1982   return true;
1983 }
1984
1985 static void
1986 resolve_global_procedure (gfc_symbol *sym, locus *where,
1987                           gfc_actual_arglist **actual, int sub)
1988 {
1989   gfc_gsymbol * gsym;
1990   gfc_namespace *ns;
1991   enum gfc_symbol_type type;
1992
1993   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1994
1995   gsym = gfc_get_gsymbol (sym->name);
1996
1997   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1998     gfc_global_used (gsym, where);
1999
2000   if (gfc_option.flag_whole_file
2001         && (sym->attr.if_source == IFSRC_UNKNOWN
2002             || sym->attr.if_source == IFSRC_IFBODY)
2003         && gsym->type != GSYM_UNKNOWN
2004         && gsym->ns
2005         && gsym->ns->resolved != -1
2006         && gsym->ns->proc_name
2007         && not_in_recursive (sym, gsym->ns)
2008         && not_entry_self_reference (sym, gsym->ns))
2009     {
2010       gfc_symbol *def_sym;
2011
2012       /* Resolve the gsymbol namespace if needed.  */
2013       if (!gsym->ns->resolved)
2014         {
2015           gfc_dt_list *old_dt_list;
2016
2017           /* Stash away derived types so that the backend_decls do not
2018              get mixed up.  */
2019           old_dt_list = gfc_derived_types;
2020           gfc_derived_types = NULL;
2021
2022           gfc_resolve (gsym->ns);
2023
2024           /* Store the new derived types with the global namespace.  */
2025           if (gfc_derived_types)
2026             gsym->ns->derived_types = gfc_derived_types;
2027
2028           /* Restore the derived types of this namespace.  */
2029           gfc_derived_types = old_dt_list;
2030         }
2031
2032       /* Make sure that translation for the gsymbol occurs before
2033          the procedure currently being resolved.  */
2034       ns = gfc_global_ns_list;
2035       for (; ns && ns != gsym->ns; ns = ns->sibling)
2036         {
2037           if (ns->sibling == gsym->ns)
2038             {
2039               ns->sibling = gsym->ns->sibling;
2040               gsym->ns->sibling = gfc_global_ns_list;
2041               gfc_global_ns_list = gsym->ns;
2042               break;
2043             }
2044         }
2045
2046       def_sym = gsym->ns->proc_name;
2047       if (def_sym->attr.entry_master)
2048         {
2049           gfc_entry_list *entry;
2050           for (entry = gsym->ns->entries; entry; entry = entry->next)
2051             if (strcmp (entry->sym->name, sym->name) == 0)
2052               {
2053                 def_sym = entry->sym;
2054                 break;
2055               }
2056         }
2057
2058       /* Differences in constant character lengths.  */
2059       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2060         {
2061           long int l1 = 0, l2 = 0;
2062           gfc_charlen *cl1 = sym->ts.u.cl;
2063           gfc_charlen *cl2 = def_sym->ts.u.cl;
2064
2065           if (cl1 != NULL
2066               && cl1->length != NULL
2067               && cl1->length->expr_type == EXPR_CONSTANT)
2068             l1 = mpz_get_si (cl1->length->value.integer);
2069
2070           if (cl2 != NULL
2071               && cl2->length != NULL
2072               && cl2->length->expr_type == EXPR_CONSTANT)
2073             l2 = mpz_get_si (cl2->length->value.integer);
2074
2075           if (l1 && l2 && l1 != l2)
2076             gfc_error ("Character length mismatch in return type of "
2077                        "function '%s' at %L (%ld/%ld)", sym->name,
2078                        &sym->declared_at, l1, l2);
2079         }
2080
2081      /* Type mismatch of function return type and expected type.  */
2082      if (sym->attr.function
2083          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2084         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2085                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2086                    gfc_typename (&def_sym->ts));
2087
2088       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2089         {
2090           gfc_formal_arglist *arg = def_sym->formal;
2091           for ( ; arg; arg = arg->next)
2092             if (!arg->sym)
2093               continue;
2094             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2095             else if (arg->sym->attr.allocatable
2096                      || arg->sym->attr.asynchronous
2097                      || arg->sym->attr.optional
2098                      || arg->sym->attr.pointer
2099                      || arg->sym->attr.target
2100                      || arg->sym->attr.value
2101                      || arg->sym->attr.volatile_)
2102               {
2103                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2104                            "has an attribute that requires an explicit "
2105                            "interface for this procedure", arg->sym->name,
2106                            sym->name, &sym->declared_at);
2107                 break;
2108               }
2109             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2110             else if (arg->sym && arg->sym->as
2111                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2112               {
2113                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2114                            "argument '%s' must have an explicit interface",
2115                            sym->name, &sym->declared_at, arg->sym->name);
2116                 break;
2117               }
2118             /* F2008, 12.4.2.2 (2c)  */
2119             else if (arg->sym->attr.codimension)
2120               {
2121                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2122                            "'%s' must have an explicit interface",
2123                            sym->name, &sym->declared_at, arg->sym->name);
2124                 break;
2125               }
2126             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2127             else if (false) /* TODO: is a parametrized derived type  */
2128               {
2129                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2130                            "type argument '%s' must have an explicit "
2131                            "interface", sym->name, &sym->declared_at,
2132                            arg->sym->name);
2133                 break;
2134               }
2135             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2136             else if (arg->sym->ts.type == BT_CLASS)
2137               {
2138                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2139                            "argument '%s' must have an explicit interface",
2140                            sym->name, &sym->declared_at, arg->sym->name);
2141                 break;
2142               }
2143         }
2144
2145       if (def_sym->attr.function)
2146         {
2147           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2148           if (def_sym->as && def_sym->as->rank
2149               && (!sym->as || sym->as->rank != def_sym->as->rank))
2150             gfc_error ("The reference to function '%s' at %L either needs an "
2151                        "explicit INTERFACE or the rank is incorrect", sym->name,
2152                        where);
2153
2154           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2155           if ((def_sym->result->attr.pointer
2156                || def_sym->result->attr.allocatable)
2157                && (sym->attr.if_source != IFSRC_IFBODY
2158                    || def_sym->result->attr.pointer
2159                         != sym->result->attr.pointer
2160                    || def_sym->result->attr.allocatable
2161                         != sym->result->attr.allocatable))
2162             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2163                        "result must have an explicit interface", sym->name,
2164                        where);
2165
2166           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2167           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2168               && def_sym->ts.u.cl->length != NULL)
2169             {
2170               gfc_charlen *cl = sym->ts.u.cl;
2171
2172               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2173                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2174                 {
2175                   gfc_error ("Nonconstant character-length function '%s' at %L "
2176                              "must have an explicit interface", sym->name,
2177                              &sym->declared_at);
2178                 }
2179             }
2180         }
2181
2182       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2183       if (def_sym->attr.elemental && !sym->attr.elemental)
2184         {
2185           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2186                      "interface", sym->name, &sym->declared_at);
2187         }
2188
2189       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2190       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2191         {
2192           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2193                      "an explicit interface", sym->name, &sym->declared_at);
2194         }
2195
2196       if (gfc_option.flag_whole_file == 1
2197           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2198               && !(gfc_option.warn_std & GFC_STD_GNU)))
2199         gfc_errors_to_warnings (1);
2200
2201       if (sym->attr.if_source != IFSRC_IFBODY)  
2202         gfc_procedure_use (def_sym, actual, where);
2203
2204       gfc_errors_to_warnings (0);
2205     }
2206
2207   if (gsym->type == GSYM_UNKNOWN)
2208     {
2209       gsym->type = type;
2210       gsym->where = *where;
2211     }
2212
2213   gsym->used = 1;
2214 }
2215
2216
2217 /************* Function resolution *************/
2218
2219 /* Resolve a function call known to be generic.
2220    Section 14.1.2.4.1.  */
2221
2222 static match
2223 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2224 {
2225   gfc_symbol *s;
2226
2227   if (sym->attr.generic)
2228     {
2229       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2230       if (s != NULL)
2231         {
2232           expr->value.function.name = s->name;
2233           expr->value.function.esym = s;
2234
2235           if (s->ts.type != BT_UNKNOWN)
2236             expr->ts = s->ts;
2237           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2238             expr->ts = s->result->ts;
2239
2240           if (s->as != NULL)
2241             expr->rank = s->as->rank;
2242           else if (s->result != NULL && s->result->as != NULL)
2243             expr->rank = s->result->as->rank;
2244
2245           gfc_set_sym_referenced (expr->value.function.esym);
2246
2247           return MATCH_YES;
2248         }
2249
2250       /* TODO: Need to search for elemental references in generic
2251          interface.  */
2252     }
2253
2254   if (sym->attr.intrinsic)
2255     return gfc_intrinsic_func_interface (expr, 0);
2256
2257   return MATCH_NO;
2258 }
2259
2260
2261 static gfc_try
2262 resolve_generic_f (gfc_expr *expr)
2263 {
2264   gfc_symbol *sym;
2265   match m;
2266
2267   sym = expr->symtree->n.sym;
2268
2269   for (;;)
2270     {
2271       m = resolve_generic_f0 (expr, sym);
2272       if (m == MATCH_YES)
2273         return SUCCESS;
2274       else if (m == MATCH_ERROR)
2275         return FAILURE;
2276
2277 generic:
2278       if (sym->ns->parent == NULL)
2279         break;
2280       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2281
2282       if (sym == NULL)
2283         break;
2284       if (!generic_sym (sym))
2285         goto generic;
2286     }
2287
2288   /* Last ditch attempt.  See if the reference is to an intrinsic
2289      that possesses a matching interface.  14.1.2.4  */
2290   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
2291     {
2292       gfc_error ("There is no specific function for the generic '%s' at %L",
2293                  expr->symtree->n.sym->name, &expr->where);
2294       return FAILURE;
2295     }
2296
2297   m = gfc_intrinsic_func_interface (expr, 0);
2298   if (m == MATCH_YES)
2299     return SUCCESS;
2300   if (m == MATCH_NO)
2301     gfc_error ("Generic function '%s' at %L is not consistent with a "
2302                "specific intrinsic interface", expr->symtree->n.sym->name,
2303                &expr->where);
2304
2305   return FAILURE;
2306 }
2307
2308
2309 /* Resolve a function call known to be specific.  */
2310
2311 static match
2312 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2313 {
2314   match m;
2315
2316   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2317     {
2318       if (sym->attr.dummy)
2319         {
2320           sym->attr.proc = PROC_DUMMY;
2321           goto found;
2322         }
2323
2324       sym->attr.proc = PROC_EXTERNAL;
2325       goto found;
2326     }
2327
2328   if (sym->attr.proc == PROC_MODULE
2329       || sym->attr.proc == PROC_ST_FUNCTION
2330       || sym->attr.proc == PROC_INTERNAL)
2331     goto found;
2332
2333   if (sym->attr.intrinsic)
2334     {
2335       m = gfc_intrinsic_func_interface (expr, 1);
2336       if (m == MATCH_YES)
2337         return MATCH_YES;
2338       if (m == MATCH_NO)
2339         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2340                    "with an intrinsic", sym->name, &expr->where);
2341
2342       return MATCH_ERROR;
2343     }
2344
2345   return MATCH_NO;
2346
2347 found:
2348   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2349
2350   if (sym->result)
2351     expr->ts = sym->result->ts;
2352   else
2353     expr->ts = sym->ts;
2354   expr->value.function.name = sym->name;
2355   expr->value.function.esym = sym;
2356   if (sym->as != NULL)
2357     expr->rank = sym->as->rank;
2358
2359   return MATCH_YES;
2360 }
2361
2362
2363 static gfc_try
2364 resolve_specific_f (gfc_expr *expr)
2365 {
2366   gfc_symbol *sym;
2367   match m;
2368
2369   sym = expr->symtree->n.sym;
2370
2371   for (;;)
2372     {
2373       m = resolve_specific_f0 (sym, expr);
2374       if (m == MATCH_YES)
2375         return SUCCESS;
2376       if (m == MATCH_ERROR)
2377         return FAILURE;
2378
2379       if (sym->ns->parent == NULL)
2380         break;
2381
2382       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2383
2384       if (sym == NULL)
2385         break;
2386     }
2387
2388   gfc_error ("Unable to resolve the specific function '%s' at %L",
2389              expr->symtree->n.sym->name, &expr->where);
2390
2391   return SUCCESS;
2392 }
2393
2394
2395 /* Resolve a procedure call not known to be generic nor specific.  */
2396
2397 static gfc_try
2398 resolve_unknown_f (gfc_expr *expr)
2399 {
2400   gfc_symbol *sym;
2401   gfc_typespec *ts;
2402
2403   sym = expr->symtree->n.sym;
2404
2405   if (sym->attr.dummy)
2406     {
2407       sym->attr.proc = PROC_DUMMY;
2408       expr->value.function.name = sym->name;
2409       goto set_type;
2410     }
2411
2412   /* See if we have an intrinsic function reference.  */
2413
2414   if (gfc_is_intrinsic (sym, 0, expr->where))
2415     {
2416       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2417         return SUCCESS;
2418       return FAILURE;
2419     }
2420
2421   /* The reference is to an external name.  */
2422
2423   sym->attr.proc = PROC_EXTERNAL;
2424   expr->value.function.name = sym->name;
2425   expr->value.function.esym = expr->symtree->n.sym;
2426
2427   if (sym->as != NULL)
2428     expr->rank = sym->as->rank;
2429
2430   /* Type of the expression is either the type of the symbol or the
2431      default type of the symbol.  */
2432
2433 set_type:
2434   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2435
2436   if (sym->ts.type != BT_UNKNOWN)
2437     expr->ts = sym->ts;
2438   else
2439     {
2440       ts = gfc_get_default_type (sym->name, sym->ns);
2441
2442       if (ts->type == BT_UNKNOWN)
2443         {
2444           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2445                      sym->name, &expr->where);
2446           return FAILURE;
2447         }
2448       else
2449         expr->ts = *ts;
2450     }
2451
2452   return SUCCESS;
2453 }
2454
2455
2456 /* Return true, if the symbol is an external procedure.  */
2457 static bool
2458 is_external_proc (gfc_symbol *sym)
2459 {
2460   if (!sym->attr.dummy && !sym->attr.contained
2461         && !(sym->attr.intrinsic
2462               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2463         && sym->attr.proc != PROC_ST_FUNCTION
2464         && !sym->attr.proc_pointer
2465         && !sym->attr.use_assoc
2466         && sym->name)
2467     return true;
2468
2469   return false;
2470 }
2471
2472
2473 /* Figure out if a function reference is pure or not.  Also set the name
2474    of the function for a potential error message.  Return nonzero if the
2475    function is PURE, zero if not.  */
2476 static int
2477 pure_stmt_function (gfc_expr *, gfc_symbol *);
2478
2479 static int
2480 pure_function (gfc_expr *e, const char **name)
2481 {
2482   int pure;
2483
2484   *name = NULL;
2485
2486   if (e->symtree != NULL
2487         && e->symtree->n.sym != NULL
2488         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2489     return pure_stmt_function (e, e->symtree->n.sym);
2490
2491   if (e->value.function.esym)
2492     {
2493       pure = gfc_pure (e->value.function.esym);
2494       *name = e->value.function.esym->name;
2495     }
2496   else if (e->value.function.isym)
2497     {
2498       pure = e->value.function.isym->pure
2499              || e->value.function.isym->elemental;
2500       *name = e->value.function.isym->name;
2501     }
2502   else
2503     {
2504       /* Implicit functions are not pure.  */
2505       pure = 0;
2506       *name = e->value.function.name;
2507     }
2508
2509   return pure;
2510 }
2511
2512
2513 static bool
2514 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2515                  int *f ATTRIBUTE_UNUSED)
2516 {
2517   const char *name;
2518
2519   /* Don't bother recursing into other statement functions
2520      since they will be checked individually for purity.  */
2521   if (e->expr_type != EXPR_FUNCTION
2522         || !e->symtree
2523         || e->symtree->n.sym == sym
2524         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2525     return false;
2526
2527   return pure_function (e, &name) ? false : true;
2528 }
2529
2530
2531 static int
2532 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2533 {
2534   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2535 }
2536
2537
2538 static gfc_try
2539 is_scalar_expr_ptr (gfc_expr *expr)
2540 {
2541   gfc_try retval = SUCCESS;
2542   gfc_ref *ref;
2543   int start;
2544   int end;
2545
2546   /* See if we have a gfc_ref, which means we have a substring, array
2547      reference, or a component.  */
2548   if (expr->ref != NULL)
2549     {
2550       ref = expr->ref;
2551       while (ref->next != NULL)
2552         ref = ref->next;
2553
2554       switch (ref->type)
2555         {
2556         case REF_SUBSTRING:
2557           if (ref->u.ss.length != NULL 
2558               && ref->u.ss.length->length != NULL
2559               && ref->u.ss.start
2560               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2561               && ref->u.ss.end
2562               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2563             {
2564               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2565               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2566               if (end - start + 1 != 1)
2567                 retval = FAILURE;
2568             }
2569           else
2570             retval = FAILURE;
2571           break;
2572         case REF_ARRAY:
2573           if (ref->u.ar.type == AR_ELEMENT)
2574             retval = SUCCESS;
2575           else if (ref->u.ar.type == AR_FULL)
2576             {
2577               /* The user can give a full array if the array is of size 1.  */
2578               if (ref->u.ar.as != NULL
2579                   && ref->u.ar.as->rank == 1
2580                   && ref->u.ar.as->type == AS_EXPLICIT
2581                   && ref->u.ar.as->lower[0] != NULL
2582                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2583                   && ref->u.ar.as->upper[0] != NULL
2584                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2585                 {
2586                   /* If we have a character string, we need to check if
2587                      its length is one.  */
2588                   if (expr->ts.type == BT_CHARACTER)
2589                     {
2590                       if (expr->ts.u.cl == NULL
2591                           || expr->ts.u.cl->length == NULL
2592                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2593                           != 0)
2594                         retval = FAILURE;
2595                     }
2596                   else
2597                     {
2598                       /* We have constant lower and upper bounds.  If the
2599                          difference between is 1, it can be considered a
2600                          scalar.  */
2601                       start = (int) mpz_get_si
2602                                 (ref->u.ar.as->lower[0]->value.integer);
2603                       end = (int) mpz_get_si
2604                                 (ref->u.ar.as->upper[0]->value.integer);
2605                       if (end - start + 1 != 1)
2606                         retval = FAILURE;
2607                    }
2608                 }
2609               else
2610                 retval = FAILURE;
2611             }
2612           else
2613             retval = FAILURE;
2614           break;
2615         default:
2616           retval = SUCCESS;
2617           break;
2618         }
2619     }
2620   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2621     {
2622       /* Character string.  Make sure it's of length 1.  */
2623       if (expr->ts.u.cl == NULL
2624           || expr->ts.u.cl->length == NULL
2625           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2626         retval = FAILURE;
2627     }
2628   else if (expr->rank != 0)
2629     retval = FAILURE;
2630
2631   return retval;
2632 }
2633
2634
2635 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2636    and, in the case of c_associated, set the binding label based on
2637    the arguments.  */
2638
2639 static gfc_try
2640 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2641                           gfc_symbol **new_sym)
2642 {
2643   char name[GFC_MAX_SYMBOL_LEN + 1];
2644   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2645   int optional_arg = 0;
2646   gfc_try retval = SUCCESS;
2647   gfc_symbol *args_sym;
2648   gfc_typespec *arg_ts;
2649   symbol_attribute arg_attr;
2650
2651   if (args->expr->expr_type == EXPR_CONSTANT
2652       || args->expr->expr_type == EXPR_OP
2653       || args->expr->expr_type == EXPR_NULL)
2654     {
2655       gfc_error ("Argument to '%s' at %L is not a variable",
2656                  sym->name, &(args->expr->where));
2657       return FAILURE;
2658     }
2659
2660   args_sym = args->expr->symtree->n.sym;
2661
2662   /* The typespec for the actual arg should be that stored in the expr
2663      and not necessarily that of the expr symbol (args_sym), because
2664      the actual expression could be a part-ref of the expr symbol.  */
2665   arg_ts = &(args->expr->ts);
2666   arg_attr = gfc_expr_attr (args->expr);
2667     
2668   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2669     {
2670       /* If the user gave two args then they are providing something for
2671          the optional arg (the second cptr).  Therefore, set the name and
2672          binding label to the c_associated for two cptrs.  Otherwise,
2673          set c_associated to expect one cptr.  */
2674       if (args->next)
2675         {
2676           /* two args.  */
2677           sprintf (name, "%s_2", sym->name);
2678           sprintf (binding_label, "%s_2", sym->binding_label);
2679           optional_arg = 1;
2680         }
2681       else
2682         {
2683           /* one arg.  */
2684           sprintf (name, "%s_1", sym->name);
2685           sprintf (binding_label, "%s_1", sym->binding_label);
2686           optional_arg = 0;
2687         }
2688
2689       /* Get a new symbol for the version of c_associated that
2690          will get called.  */
2691       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2692     }
2693   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2694            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2695     {
2696       sprintf (name, "%s", sym->name);
2697       sprintf (binding_label, "%s", sym->binding_label);
2698
2699       /* Error check the call.  */
2700       if (args->next != NULL)
2701         {
2702           gfc_error_now ("More actual than formal arguments in '%s' "
2703                          "call at %L", name, &(args->expr->where));
2704           retval = FAILURE;
2705         }
2706       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2707         {
2708           /* Make sure we have either the target or pointer attribute.  */
2709           if (!arg_attr.target && !arg_attr.pointer)
2710             {
2711               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2712                              "a TARGET or an associated pointer",
2713                              args_sym->name,
2714                              sym->name, &(args->expr->where));
2715               retval = FAILURE;
2716             }
2717
2718           /* See if we have interoperable type and type param.  */
2719           if (verify_c_interop (arg_ts) == SUCCESS
2720               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2721             {
2722               if (args_sym->attr.target == 1)
2723                 {
2724                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2725                      has the target attribute and is interoperable.  */
2726                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2727                      allocatable variable that has the TARGET attribute and
2728                      is not an array of zero size.  */
2729                   if (args_sym->attr.allocatable == 1)
2730                     {
2731                       if (args_sym->attr.dimension != 0 
2732                           && (args_sym->as && args_sym->as->rank == 0))
2733                         {
2734                           gfc_error_now ("Allocatable variable '%s' used as a "
2735                                          "parameter to '%s' at %L must not be "
2736                                          "an array of zero size",
2737                                          args_sym->name, sym->name,
2738                                          &(args->expr->where));
2739                           retval = FAILURE;
2740                         }
2741                     }
2742                   else
2743                     {
2744                       /* A non-allocatable target variable with C
2745                          interoperable type and type parameters must be
2746                          interoperable.  */
2747                       if (args_sym && args_sym->attr.dimension)
2748                         {
2749                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2750                             {
2751                               gfc_error ("Assumed-shape array '%s' at %L "
2752                                          "cannot be an argument to the "
2753                                          "procedure '%s' because "
2754                                          "it is not C interoperable",
2755                                          args_sym->name,
2756                                          &(args->expr->where), sym->name);
2757                               retval = FAILURE;
2758                             }
2759                           else if (args_sym->as->type == AS_DEFERRED)
2760                             {
2761                               gfc_error ("Deferred-shape array '%s' at %L "
2762                                          "cannot be an argument to the "
2763                                          "procedure '%s' because "
2764                                          "it is not C interoperable",
2765                                          args_sym->name,
2766                                          &(args->expr->where), sym->name);
2767                               retval = FAILURE;
2768                             }
2769                         }
2770                               
2771                       /* Make sure it's not a character string.  Arrays of
2772                          any type should be ok if the variable is of a C
2773                          interoperable type.  */
2774                       if (arg_ts->type == BT_CHARACTER)
2775                         if (arg_ts->u.cl != NULL
2776                             && (arg_ts->u.cl->length == NULL
2777                                 || arg_ts->u.cl->length->expr_type
2778                                    != EXPR_CONSTANT
2779                                 || mpz_cmp_si
2780                                     (arg_ts->u.cl->length->value.integer, 1)
2781                                    != 0)
2782                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2783                           {
2784                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2785                                            "at %L must have a length of 1",
2786                                            args_sym->name, sym->name,
2787                                            &(args->expr->where));
2788                             retval = FAILURE;
2789                           }
2790                     }
2791                 }
2792               else if (arg_attr.pointer
2793                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2794                 {
2795                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2796                      scalar pointer.  */
2797                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2798                                  "associated scalar POINTER", args_sym->name,
2799                                  sym->name, &(args->expr->where));
2800                   retval = FAILURE;
2801                 }
2802             }
2803           else
2804             {
2805               /* The parameter is not required to be C interoperable.  If it
2806                  is not C interoperable, it must be a nonpolymorphic scalar
2807                  with no length type parameters.  It still must have either
2808                  the pointer or target attribute, and it can be
2809                  allocatable (but must be allocated when c_loc is called).  */
2810               if (args->expr->rank != 0 
2811                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2812                 {
2813                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2814                                  "scalar", args_sym->name, sym->name,
2815                                  &(args->expr->where));
2816                   retval = FAILURE;
2817                 }
2818               else if (arg_ts->type == BT_CHARACTER 
2819                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2820                 {
2821                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2822                                  "%L must have a length of 1",
2823                                  args_sym->name, sym->name,
2824                                  &(args->expr->where));
2825                   retval = FAILURE;
2826                 }
2827               else if (arg_ts->type == BT_CLASS)
2828                 {
2829                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2830                                  "polymorphic", args_sym->name, sym->name,
2831                                  &(args->expr->where));
2832                   retval = FAILURE;
2833                 }
2834             }
2835         }
2836       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2837         {
2838           if (args_sym->attr.flavor != FL_PROCEDURE)
2839             {
2840               /* TODO: Update this error message to allow for procedure
2841                  pointers once they are implemented.  */
2842               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2843                              "procedure",
2844                              args_sym->name, sym->name,
2845                              &(args->expr->where));
2846               retval = FAILURE;
2847             }
2848           else if (args_sym->attr.is_bind_c != 1)
2849             {
2850               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2851                              "BIND(C)",
2852                              args_sym->name, sym->name,
2853                              &(args->expr->where));
2854               retval = FAILURE;
2855             }
2856         }
2857       
2858       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2859       *new_sym = sym;
2860     }
2861   else
2862     {
2863       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2864                           "iso_c_binding function: '%s'!\n", sym->name);
2865     }
2866
2867   return retval;
2868 }
2869
2870
2871 /* Resolve a function call, which means resolving the arguments, then figuring
2872    out which entity the name refers to.  */
2873 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2874    to INTENT(OUT) or INTENT(INOUT).  */
2875
2876 static gfc_try
2877 resolve_function (gfc_expr *expr)
2878 {
2879   gfc_actual_arglist *arg;
2880   gfc_symbol *sym;
2881   const char *name;
2882   gfc_try t;
2883   int temp;
2884   procedure_type p = PROC_INTRINSIC;
2885   bool no_formal_args;
2886
2887   sym = NULL;
2888   if (expr->symtree)
2889     sym = expr->symtree->n.sym;
2890
2891   /* If this is a procedure pointer component, it has already been resolved.  */
2892   if (gfc_is_proc_ptr_comp (expr, NULL))
2893     return SUCCESS;
2894   
2895   if (sym && sym->attr.intrinsic
2896       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2897     return FAILURE;
2898
2899   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2900     {
2901       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2902       return FAILURE;
2903     }
2904
2905   /* If this ia a deferred TBP with an abstract interface (which may
2906      of course be referenced), expr->value.function.esym will be set.  */
2907   if (sym && sym->attr.abstract && !expr->value.function.esym)
2908     {
2909       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2910                  sym->name, &expr->where);
2911       return FAILURE;
2912     }
2913
2914   /* Switch off assumed size checking and do this again for certain kinds
2915      of procedure, once the procedure itself is resolved.  */
2916   need_full_assumed_size++;
2917
2918   if (expr->symtree && expr->symtree->n.sym)
2919     p = expr->symtree->n.sym->attr.proc;
2920
2921   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2922     inquiry_argument = true;
2923   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2924
2925   if (resolve_actual_arglist (expr->value.function.actual,
2926                               p, no_formal_args) == FAILURE)
2927     {
2928       inquiry_argument = false;
2929       return FAILURE;
2930     }
2931
2932   inquiry_argument = false;
2933  
2934   /* Need to setup the call to the correct c_associated, depending on
2935      the number of cptrs to user gives to compare.  */
2936   if (sym && sym->attr.is_iso_c == 1)
2937     {
2938       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2939           == FAILURE)
2940         return FAILURE;
2941       
2942       /* Get the symtree for the new symbol (resolved func).
2943          the old one will be freed later, when it's no longer used.  */
2944       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2945     }
2946   
2947   /* Resume assumed_size checking.  */
2948   need_full_assumed_size--;
2949
2950   /* If the procedure is external, check for usage.  */
2951   if (sym && is_external_proc (sym))
2952     resolve_global_procedure (sym, &expr->where,
2953                               &expr->value.function.actual, 0);
2954
2955   if (sym && sym->ts.type == BT_CHARACTER
2956       && sym->ts.u.cl
2957       && sym->ts.u.cl->length == NULL
2958       && !sym->attr.dummy
2959       && expr->value.function.esym == NULL
2960       && !sym->attr.contained)
2961     {
2962       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2963       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2964                  "be used at %L since it is not a dummy argument",
2965                  sym->name, &expr->where);
2966       return FAILURE;
2967     }
2968
2969   /* See if function is already resolved.  */
2970
2971   if (expr->value.function.name != NULL)
2972     {
2973       if (expr->ts.type == BT_UNKNOWN)
2974         expr->ts = sym->ts;
2975       t = SUCCESS;
2976     }
2977   else
2978     {
2979       /* Apply the rules of section 14.1.2.  */
2980
2981       switch (procedure_kind (sym))
2982         {
2983         case PTYPE_GENERIC:
2984           t = resolve_generic_f (expr);
2985           break;
2986
2987         case PTYPE_SPECIFIC:
2988           t = resolve_specific_f (expr);
2989           break;
2990
2991         case PTYPE_UNKNOWN:
2992           t = resolve_unknown_f (expr);
2993           break;
2994
2995         default:
2996           gfc_internal_error ("resolve_function(): bad function type");
2997         }
2998     }
2999
3000   /* If the expression is still a function (it might have simplified),
3001      then we check to see if we are calling an elemental function.  */
3002
3003   if (expr->expr_type != EXPR_FUNCTION)
3004     return t;
3005
3006   temp = need_full_assumed_size;
3007   need_full_assumed_size = 0;
3008
3009   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3010     return FAILURE;
3011
3012   if (omp_workshare_flag
3013       && expr->value.function.esym
3014       && ! gfc_elemental (expr->value.function.esym))
3015     {
3016       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3017                  "in WORKSHARE construct", expr->value.function.esym->name,
3018                  &expr->where);
3019       t = FAILURE;
3020     }
3021
3022 #define GENERIC_ID expr->value.function.isym->id
3023   else if (expr->value.function.actual != NULL
3024            && expr->value.function.isym != NULL
3025            && GENERIC_ID != GFC_ISYM_LBOUND
3026            && GENERIC_ID != GFC_ISYM_LEN
3027            && GENERIC_ID != GFC_ISYM_LOC
3028            && GENERIC_ID != GFC_ISYM_PRESENT)
3029     {
3030       /* Array intrinsics must also have the last upper bound of an
3031          assumed size array argument.  UBOUND and SIZE have to be
3032          excluded from the check if the second argument is anything
3033          than a constant.  */
3034
3035       for (arg = expr->value.function.actual; arg; arg = arg->next)
3036         {
3037           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3038               && arg->next != NULL && arg->next->expr)
3039             {
3040               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3041                 break;
3042
3043               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3044                 break;
3045
3046               if ((int)mpz_get_si (arg->next->expr->value.integer)
3047                         < arg->expr->rank)
3048                 break;
3049             }
3050
3051           if (arg->expr != NULL
3052               && arg->expr->rank > 0
3053               && resolve_assumed_size_actual (arg->expr))
3054             return FAILURE;
3055         }
3056     }
3057 #undef GENERIC_ID
3058
3059   need_full_assumed_size = temp;
3060   name = NULL;
3061
3062   if (!pure_function (expr, &name) && name)
3063     {
3064       if (forall_flag)
3065         {
3066           gfc_error ("reference to non-PURE function '%s' at %L inside a "
3067                      "FORALL %s", name, &expr->where,
3068                      forall_flag == 2 ? "mask" : "block");
3069           t = FAILURE;
3070         }
3071       else if (gfc_pure (NULL))
3072         {
3073           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3074                      "procedure within a PURE procedure", name, &expr->where);
3075           t = FAILURE;
3076         }
3077     }
3078
3079   /* Functions without the RECURSIVE attribution are not allowed to
3080    * call themselves.  */
3081   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3082     {
3083       gfc_symbol *esym;
3084       esym = expr->value.function.esym;
3085
3086       if (is_illegal_recursion (esym, gfc_current_ns))
3087       {
3088         if (esym->attr.entry && esym->ns->entries)
3089           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3090                      " function '%s' is not RECURSIVE",
3091                      esym->name, &expr->where, esym->ns->entries->sym->name);
3092         else
3093           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3094                      " is not RECURSIVE", esym->name, &expr->where);
3095
3096         t = FAILURE;
3097       }
3098     }
3099
3100   /* Character lengths of use associated functions may contains references to
3101      symbols not referenced from the current program unit otherwise.  Make sure
3102      those symbols are marked as referenced.  */
3103
3104   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3105       && expr->value.function.esym->attr.use_assoc)
3106     {
3107       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3108     }
3109
3110   if (t == SUCCESS
3111         && !((expr->value.function.esym
3112                 && expr->value.function.esym->attr.elemental)
3113                         ||
3114              (expr->value.function.isym
3115                 && expr->value.function.isym->elemental)))
3116     find_noncopying_intrinsics (expr->value.function.esym,
3117                                 expr->value.function.actual);
3118
3119   /* Make sure that the expression has a typespec that works.  */
3120   if (expr->ts.type == BT_UNKNOWN)
3121     {
3122       if (expr->symtree->n.sym->result
3123             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3124             && !expr->symtree->n.sym->result->attr.proc_pointer)
3125         expr->ts = expr->symtree->n.sym->result->ts;
3126     }
3127
3128   return t;
3129 }
3130
3131
3132 /************* Subroutine resolution *************/
3133
3134 static void
3135 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3136 {
3137   if (gfc_pure (sym))
3138     return;
3139
3140   if (forall_flag)
3141     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3142                sym->name, &c->loc);
3143   else if (gfc_pure (NULL))
3144     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3145                &c->loc);
3146 }
3147
3148
3149 static match
3150 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3151 {
3152   gfc_symbol *s;
3153
3154   if (sym->attr.generic)
3155     {
3156       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3157       if (s != NULL)
3158         {
3159           c->resolved_sym = s;
3160           pure_subroutine (c, s);
3161           return MATCH_YES;
3162         }
3163
3164       /* TODO: Need to search for elemental references in generic interface.  */
3165     }
3166
3167   if (sym->attr.intrinsic)
3168     return gfc_intrinsic_sub_interface (c, 0);
3169
3170   return MATCH_NO;
3171 }
3172
3173
3174 static gfc_try
3175 resolve_generic_s (gfc_code *c)
3176 {
3177   gfc_symbol *sym;
3178   match m;
3179
3180   sym = c->symtree->n.sym;
3181
3182   for (;;)
3183     {
3184       m = resolve_generic_s0 (c, sym);
3185       if (m == MATCH_YES)
3186         return SUCCESS;
3187       else if (m == MATCH_ERROR)
3188         return FAILURE;
3189
3190 generic:
3191       if (sym->ns->parent == NULL)
3192         break;
3193       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3194
3195       if (sym == NULL)
3196         break;
3197       if (!generic_sym (sym))
3198         goto generic;
3199     }
3200
3201   /* Last ditch attempt.  See if the reference is to an intrinsic
3202      that possesses a matching interface.  14.1.2.4  */
3203   sym = c->symtree->n.sym;
3204
3205   if (!gfc_is_intrinsic (sym, 1, c->loc))
3206     {
3207       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3208                  sym->name, &c->loc);
3209       return FAILURE;
3210     }
3211
3212   m = gfc_intrinsic_sub_interface (c, 0);
3213   if (m == MATCH_YES)
3214     return SUCCESS;
3215   if (m == MATCH_NO)
3216     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3217                "intrinsic subroutine interface", sym->name, &c->loc);
3218
3219   return FAILURE;
3220 }
3221
3222
3223 /* Set the name and binding label of the subroutine symbol in the call
3224    expression represented by 'c' to include the type and kind of the
3225    second parameter.  This function is for resolving the appropriate
3226    version of c_f_pointer() and c_f_procpointer().  For example, a
3227    call to c_f_pointer() for a default integer pointer could have a
3228    name of c_f_pointer_i4.  If no second arg exists, which is an error
3229    for these two functions, it defaults to the generic symbol's name
3230    and binding label.  */
3231
3232 static void
3233 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3234                     char *name, char *binding_label)
3235 {
3236   gfc_expr *arg = NULL;
3237   char type;
3238   int kind;
3239
3240   /* The second arg of c_f_pointer and c_f_procpointer determines
3241      the type and kind for the procedure name.  */
3242   arg = c->ext.actual->next->expr;
3243
3244   if (arg != NULL)
3245     {
3246       /* Set up the name to have the given symbol's name,
3247          plus the type and kind.  */
3248       /* a derived type is marked with the type letter 'u' */
3249       if (arg->ts.type == BT_DERIVED)
3250         {
3251           type = 'd';
3252           kind = 0; /* set the kind as 0 for now */
3253         }
3254       else
3255         {
3256           type = gfc_type_letter (arg->ts.type);
3257           kind = arg->ts.kind;
3258         }
3259
3260       if (arg->ts.type == BT_CHARACTER)
3261         /* Kind info for character strings not needed.  */
3262         kind = 0;
3263
3264       sprintf (name, "%s_%c%d", sym->name, type, kind);
3265       /* Set up the binding label as the given symbol's label plus
3266          the type and kind.  */
3267       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
3268     }
3269   else
3270     {
3271       /* If the second arg is missing, set the name and label as
3272          was, cause it should at least be found, and the missing
3273          arg error will be caught by compare_parameters().  */
3274       sprintf (name, "%s", sym->name);
3275       sprintf (binding_label, "%s", sym->binding_label);
3276     }
3277    
3278   return;
3279 }
3280
3281
3282 /* Resolve a generic version of the iso_c_binding procedure given
3283    (sym) to the specific one based on the type and kind of the
3284    argument(s).  Currently, this function resolves c_f_pointer() and
3285    c_f_procpointer based on the type and kind of the second argument
3286    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3287    Upon successfully exiting, c->resolved_sym will hold the resolved
3288    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3289    otherwise.  */
3290
3291 match
3292 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3293 {
3294   gfc_symbol *new_sym;
3295   /* this is fine, since we know the names won't use the max */
3296   char name[GFC_MAX_SYMBOL_LEN + 1];
3297   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
3298   /* default to success; will override if find error */
3299   match m = MATCH_YES;
3300
3301   /* Make sure the actual arguments are in the necessary order (based on the 
3302      formal args) before resolving.  */
3303   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3304
3305   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3306       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3307     {
3308       set_name_and_label (c, sym, name, binding_label);
3309       
3310       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3311         {
3312           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3313             {
3314               /* Make sure we got a third arg if the second arg has non-zero
3315                  rank.  We must also check that the type and rank are
3316                  correct since we short-circuit this check in
3317                  gfc_procedure_use() (called above to sort actual args).  */
3318               if (c->ext.actual->next->expr->rank != 0)
3319                 {
3320                   if(c->ext.actual->next->next == NULL 
3321                      || c->ext.actual->next->next->expr == NULL)
3322                     {
3323                       m = MATCH_ERROR;
3324                       gfc_error ("Missing SHAPE parameter for call to %s "
3325                                  "at %L", sym->name, &(c->loc));
3326                     }
3327                   else if (c->ext.actual->next->next->expr->ts.type
3328                            != BT_INTEGER
3329                            || c->ext.actual->next->next->expr->rank != 1)
3330                     {
3331                       m = MATCH_ERROR;
3332                       gfc_error ("SHAPE parameter for call to %s at %L must "
3333                                  "be a rank 1 INTEGER array", sym->name,
3334                                  &(c->loc));
3335                     }
3336                 }
3337             }
3338         }
3339       
3340       if (m != MATCH_ERROR)
3341         {
3342           /* the 1 means to add the optional arg to formal list */
3343           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3344          
3345           /* for error reporting, say it's declared where the original was */
3346           new_sym->declared_at = sym->declared_at;
3347         }
3348     }
3349   else
3350     {
3351       /* no differences for c_loc or c_funloc */
3352       new_sym = sym;
3353     }
3354
3355   /* set the resolved symbol */
3356   if (m != MATCH_ERROR)
3357     c->resolved_sym = new_sym;
3358   else
3359     c->resolved_sym = sym;
3360   
3361   return m;
3362 }
3363
3364
3365 /* Resolve a subroutine call known to be specific.  */
3366
3367 static match
3368 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3369 {
3370   match m;
3371
3372   if(sym->attr.is_iso_c)
3373     {
3374       m = gfc_iso_c_sub_interface (c,sym);
3375       return m;
3376     }
3377   
3378   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3379     {
3380       if (sym->attr.dummy)
3381         {
3382           sym->attr.proc = PROC_DUMMY;
3383           goto found;
3384         }
3385
3386       sym->attr.proc = PROC_EXTERNAL;
3387       goto found;
3388     }
3389
3390   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3391     goto found;
3392
3393   if (sym->attr.intrinsic)
3394     {
3395       m = gfc_intrinsic_sub_interface (c, 1);
3396       if (m == MATCH_YES)
3397         return MATCH_YES;
3398       if (m == MATCH_NO)
3399         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3400                    "with an intrinsic", sym->name, &c->loc);
3401
3402       return MATCH_ERROR;
3403     }
3404
3405   return MATCH_NO;
3406
3407 found:
3408   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3409
3410   c->resolved_sym = sym;
3411   pure_subroutine (c, sym);
3412
3413   return MATCH_YES;
3414 }
3415
3416
3417 static gfc_try
3418 resolve_specific_s (gfc_code *c)
3419 {
3420   gfc_symbol *sym;
3421   match m;
3422
3423   sym = c->symtree->n.sym;
3424
3425   for (;;)
3426     {
3427       m = resolve_specific_s0 (c, sym);
3428       if (m == MATCH_YES)
3429         return SUCCESS;
3430       if (m == MATCH_ERROR)
3431         return FAILURE;
3432
3433       if (sym->ns->parent == NULL)
3434         break;
3435
3436       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3437
3438       if (sym == NULL)
3439         break;
3440     }
3441
3442   sym = c->symtree->n.sym;
3443   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3444              sym->name, &c->loc);
3445
3446   return FAILURE;
3447 }
3448
3449
3450 /* Resolve a subroutine call not known to be generic nor specific.  */
3451
3452 static gfc_try
3453 resolve_unknown_s (gfc_code *c)
3454 {
3455   gfc_symbol *sym;
3456
3457   sym = c->symtree->n.sym;
3458
3459   if (sym->attr.dummy)
3460     {
3461       sym->attr.proc = PROC_DUMMY;
3462       goto found;
3463     }
3464
3465   /* See if we have an intrinsic function reference.  */
3466
3467   if (gfc_is_intrinsic (sym, 1, c->loc))
3468     {
3469       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3470         return SUCCESS;
3471       return FAILURE;
3472     }
3473
3474   /* The reference is to an external name.  */
3475
3476 found:
3477   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3478
3479   c->resolved_sym = sym;
3480
3481   pure_subroutine (c, sym);
3482
3483   return SUCCESS;
3484 }
3485
3486
3487 /* Resolve a subroutine call.  Although it was tempting to use the same code
3488    for functions, subroutines and functions are stored differently and this
3489    makes things awkward.  */
3490
3491 static gfc_try
3492 resolve_call (gfc_code *c)
3493 {
3494   gfc_try t;
3495   procedure_type ptype = PROC_INTRINSIC;
3496   gfc_symbol *csym, *sym;
3497   bool no_formal_args;
3498
3499   csym = c->symtree ? c->symtree->n.sym : NULL;
3500
3501   if (csym && csym->ts.type != BT_UNKNOWN)
3502     {
3503       gfc_error ("'%s' at %L has a type, which is not consistent with "
3504                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3505       return FAILURE;
3506     }
3507
3508   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3509     {
3510       gfc_symtree *st;
3511       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3512       sym = st ? st->n.sym : NULL;
3513       if (sym && csym != sym
3514               && sym->ns == gfc_current_ns
3515               && sym->attr.flavor == FL_PROCEDURE
3516               && sym->attr.contained)
3517         {
3518           sym->refs++;
3519           if (csym->attr.generic)
3520             c->symtree->n.sym = sym;
3521           else
3522             c->symtree = st;
3523           csym = c->symtree->n.sym;
3524         }
3525     }
3526
3527   /* If this ia a deferred TBP with an abstract interface
3528      (which may of course be referenced), c->expr1 will be set.  */
3529   if (csym && csym->attr.abstract && !c->expr1)
3530     {
3531       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3532                  csym->name, &c->loc);
3533       return FAILURE;
3534     }
3535
3536   /* Subroutines without the RECURSIVE attribution are not allowed to
3537    * call themselves.  */
3538   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3539     {
3540       if (csym->attr.entry && csym->ns->entries)
3541         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3542                    " subroutine '%s' is not RECURSIVE",
3543                    csym->name, &c->loc, csym->ns->entries->sym->name);
3544       else
3545         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3546                    " is not RECURSIVE", csym->name, &c->loc);
3547
3548       t = FAILURE;
3549     }
3550
3551   /* Switch off assumed size checking and do this again for certain kinds
3552      of procedure, once the procedure itself is resolved.  */
3553   need_full_assumed_size++;
3554
3555   if (csym)
3556     ptype = csym->attr.proc;
3557
3558   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3559   if (resolve_actual_arglist (c->ext.actual, ptype,
3560                               no_formal_args) == FAILURE)
3561     return FAILURE;
3562
3563   /* Resume assumed_size checking.  */
3564   need_full_assumed_size--;
3565
3566   /* If external, check for usage.  */
3567   if (csym && is_external_proc (csym))
3568     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3569
3570   t = SUCCESS;
3571   if (c->resolved_sym == NULL)
3572     {
3573       c->resolved_isym = NULL;
3574       switch (procedure_kind (csym))
3575         {
3576         case PTYPE_GENERIC:
3577           t = resolve_generic_s (c);
3578           break;
3579
3580         case PTYPE_SPECIFIC:
3581           t = resolve_specific_s (c);
3582           break;
3583
3584         case PTYPE_UNKNOWN:
3585           t = resolve_unknown_s (c);
3586           break;
3587
3588         default:
3589           gfc_internal_error ("resolve_subroutine(): bad function type");
3590         }
3591     }
3592
3593   /* Some checks of elemental subroutine actual arguments.  */
3594   if (resolve_elemental_actual (NULL, c) == FAILURE)
3595     return FAILURE;
3596
3597   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3598     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3599   return t;
3600 }
3601
3602
3603 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3604    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3605    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3606    if their shapes do not match.  If either op1->shape or op2->shape is
3607    NULL, return SUCCESS.  */
3608
3609 static gfc_try
3610 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3611 {
3612   gfc_try t;
3613   int i;
3614
3615   t = SUCCESS;
3616
3617   if (op1->shape != NULL && op2->shape != NULL)
3618     {
3619       for (i = 0; i < op1->rank; i++)
3620         {
3621           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3622            {
3623              gfc_error ("Shapes for operands at %L and %L are not conformable",
3624                          &op1->where, &op2->where);
3625              t = FAILURE;
3626              break;
3627            }
3628         }
3629     }
3630
3631   return t;
3632 }
3633
3634
3635 /* Resolve an operator expression node.  This can involve replacing the
3636    operation with a user defined function call.  */
3637
3638 static gfc_try
3639 resolve_operator (gfc_expr *e)
3640 {
3641   gfc_expr *op1, *op2;
3642   char msg[200];
3643   bool dual_locus_error;
3644   gfc_try t;
3645
3646   /* Resolve all subnodes-- give them types.  */
3647
3648   switch (e->value.op.op)
3649     {
3650     default:
3651       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3652         return FAILURE;
3653
3654     /* Fall through...  */
3655
3656     case INTRINSIC_NOT:
3657     case INTRINSIC_UPLUS:
3658     case INTRINSIC_UMINUS:
3659     case INTRINSIC_PARENTHESES:
3660       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3661         return FAILURE;
3662       break;
3663     }
3664
3665   /* Typecheck the new node.  */
3666
3667   op1 = e->value.op.op1;
3668   op2 = e->value.op.op2;
3669   dual_locus_error = false;
3670
3671   if ((op1 && op1->expr_type == EXPR_NULL)
3672       || (op2 && op2->expr_type == EXPR_NULL))
3673     {
3674       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3675       goto bad_op;
3676     }
3677
3678   switch (e->value.op.op)
3679     {
3680     case INTRINSIC_UPLUS:
3681     case INTRINSIC_UMINUS:
3682       if (op1->ts.type == BT_INTEGER
3683           || op1->ts.type == BT_REAL
3684           || op1->ts.type == BT_COMPLEX)
3685         {
3686           e->ts = op1->ts;
3687           break;
3688         }
3689
3690       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3691                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3692       goto bad_op;
3693
3694     case INTRINSIC_PLUS:
3695     case INTRINSIC_MINUS:
3696     case INTRINSIC_TIMES:
3697     case INTRINSIC_DIVIDE:
3698     case INTRINSIC_POWER:
3699       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3700         {
3701           gfc_type_convert_binary (e, 1);
3702           break;
3703         }
3704
3705       sprintf (msg,
3706                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3707                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3708                gfc_typename (&op2->ts));
3709       goto bad_op;
3710
3711     case INTRINSIC_CONCAT:
3712       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3713           && op1->ts.kind == op2->ts.kind)
3714         {
3715           e->ts.type = BT_CHARACTER;
3716           e->ts.kind = op1->ts.kind;
3717           break;
3718         }
3719
3720       sprintf (msg,
3721                _("Operands of string concatenation operator at %%L are %s/%s"),
3722                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3723       goto bad_op;
3724
3725     case INTRINSIC_AND:
3726     case INTRINSIC_OR:
3727     case INTRINSIC_EQV:
3728     case INTRINSIC_NEQV:
3729       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3730         {
3731           e->ts.type = BT_LOGICAL;
3732           e->ts.kind = gfc_kind_max (op1, op2);
3733           if (op1->ts.kind < e->ts.kind)
3734             gfc_convert_type (op1, &e->ts, 2);
3735           else if (op2->ts.kind < e->ts.kind)
3736             gfc_convert_type (op2, &e->ts, 2);
3737           break;
3738         }
3739
3740       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3741                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3742                gfc_typename (&op2->ts));
3743
3744       goto bad_op;
3745
3746     case INTRINSIC_NOT:
3747       if (op1->ts.type == BT_LOGICAL)
3748         {
3749           e->ts.type = BT_LOGICAL;
3750           e->ts.kind = op1->ts.kind;
3751           break;
3752         }
3753
3754       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3755                gfc_typename (&op1->ts));
3756       goto bad_op;
3757
3758     case INTRINSIC_GT:
3759     case INTRINSIC_GT_OS:
3760     case INTRINSIC_GE:
3761     case INTRINSIC_GE_OS:
3762     case INTRINSIC_LT:
3763     case INTRINSIC_LT_OS:
3764     case INTRINSIC_LE:
3765     case INTRINSIC_LE_OS:
3766       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3767         {
3768           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3769           goto bad_op;
3770         }
3771
3772       /* Fall through...  */
3773
3774     case INTRINSIC_EQ:
3775     case INTRINSIC_EQ_OS:
3776     case INTRINSIC_NE:
3777     case INTRINSIC_NE_OS:
3778       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3779           && op1->ts.kind == op2->ts.kind)
3780         {
3781           e->ts.type = BT_LOGICAL;
3782           e->ts.kind = gfc_default_logical_kind;
3783           break;
3784         }
3785
3786       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3787         {
3788           gfc_type_convert_binary (e, 1);
3789
3790           e->ts.type = BT_LOGICAL;
3791           e->ts.kind = gfc_default_logical_kind;
3792           break;
3793         }
3794
3795       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3796         sprintf (msg,
3797                  _("Logicals at %%L must be compared with %s instead of %s"),
3798                  (e->value.op.op == INTRINSIC_EQ 
3799                   || e->value.op.op == INTRINSIC_EQ_OS)
3800                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3801       else
3802         sprintf (msg,
3803                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3804                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3805                  gfc_typename (&op2->ts));
3806
3807       goto bad_op;
3808
3809     case INTRINSIC_USER:
3810       if (e->value.op.uop->op == NULL)
3811         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3812       else if (op2 == NULL)
3813         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3814                  e->value.op.uop->name, gfc_typename (&op1->ts));
3815       else
3816         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3817                  e->value.op.uop->name, gfc_typename (&op1->ts),
3818                  gfc_typename (&op2->ts));
3819
3820       goto bad_op;
3821
3822     case INTRINSIC_PARENTHESES:
3823       e->ts = op1->ts;
3824       if (e->ts.type == BT_CHARACTER)
3825         e->ts.u.cl = op1->ts.u.cl;
3826       break;
3827
3828     default:
3829       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3830     }
3831
3832   /* Deal with arrayness of an operand through an operator.  */
3833
3834   t = SUCCESS;
3835
3836   switch (e->value.op.op)
3837     {
3838     case INTRINSIC_PLUS:
3839     case INTRINSIC_MINUS:
3840     case INTRINSIC_TIMES:
3841     case INTRINSIC_DIVIDE:
3842     case INTRINSIC_POWER:
3843     case INTRINSIC_CONCAT:
3844     case INTRINSIC_AND:
3845     case INTRINSIC_OR:
3846     case INTRINSIC_EQV:
3847     case INTRINSIC_NEQV:
3848     case INTRINSIC_EQ:
3849     case INTRINSIC_EQ_OS:
3850     case INTRINSIC_NE:
3851     case INTRINSIC_NE_OS:
3852     case INTRINSIC_GT:
3853     case INTRINSIC_GT_OS:
3854     case INTRINSIC_GE:
3855     case INTRINSIC_GE_OS:
3856     case INTRINSIC_LT:
3857     case INTRINSIC_LT_OS:
3858     case INTRINSIC_LE:
3859     case INTRINSIC_LE_OS:
3860
3861       if (op1->rank == 0 && op2->rank == 0)
3862         e->rank = 0;
3863
3864       if (op1->rank == 0 && op2->rank != 0)
3865         {
3866           e->rank = op2->rank;
3867
3868           if (e->shape == NULL)
3869             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3870         }
3871
3872       if (op1->rank != 0 && op2->rank == 0)
3873         {
3874           e->rank = op1->rank;
3875
3876           if (e->shape == NULL)
3877             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3878         }
3879
3880       if (op1->rank != 0 && op2->rank != 0)
3881         {
3882           if (op1->rank == op2->rank)
3883             {
3884               e->rank = op1->rank;
3885               if (e->shape == NULL)
3886                 {
3887                   t = compare_shapes (op1, op2);
3888                   if (t == FAILURE)
3889                     e->shape = NULL;
3890                   else
3891                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
3892                 }
3893             }
3894           else
3895             {
3896               /* Allow higher level expressions to work.  */
3897               e->rank = 0;
3898
3899               /* Try user-defined operators, and otherwise throw an error.  */
3900               dual_locus_error = true;
3901               sprintf (msg,
3902                        _("Inconsistent ranks for operator at %%L and %%L"));
3903               goto bad_op;
3904             }
3905         }
3906
3907       break;
3908
3909     case INTRINSIC_PARENTHESES:
3910     case INTRINSIC_NOT:
3911     case INTRINSIC_UPLUS:
3912     case INTRINSIC_UMINUS:
3913       /* Simply copy arrayness attribute */
3914       e->rank = op1->rank;
3915
3916       if (e->shape == NULL)
3917         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3918
3919       break;
3920
3921     default:
3922       break;
3923     }
3924
3925   /* Attempt to simplify the expression.  */
3926   if (t == SUCCESS)
3927     {
3928       t = gfc_simplify_expr (e, 0);
3929       /* Some calls do not succeed in simplification and return FAILURE
3930          even though there is no error; e.g. variable references to
3931          PARAMETER arrays.  */
3932       if (!gfc_is_constant_expr (e))
3933         t = SUCCESS;
3934     }
3935   return t;
3936
3937 bad_op:
3938
3939   {
3940     bool real_error;
3941     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3942       return SUCCESS;
3943
3944     if (real_error)
3945       return FAILURE;
3946   }
3947
3948   if (dual_locus_error)
3949     gfc_error (msg, &op1->where, &op2->where);
3950   else
3951     gfc_error (msg, &e->where);
3952
3953   return FAILURE;
3954 }
3955
3956
3957 /************** Array resolution subroutines **************/
3958
3959 typedef enum
3960 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3961 comparison;
3962
3963 /* Compare two integer expressions.  */
3964
3965 static comparison
3966 compare_bound (gfc_expr *a, gfc_expr *b)
3967 {
3968   int i;
3969
3970   if (a == NULL || a->expr_type != EXPR_CONSTANT
3971       || b == NULL || b->expr_type != EXPR_CONSTANT)
3972     return CMP_UNKNOWN;
3973
3974   /* If either of the types isn't INTEGER, we must have
3975      raised an error earlier.  */
3976
3977   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3978     return CMP_UNKNOWN;
3979
3980   i = mpz_cmp (a->value.integer, b->value.integer);
3981
3982   if (i < 0)
3983     return CMP_LT;
3984   if (i > 0)
3985     return CMP_GT;
3986   return CMP_EQ;
3987 }
3988
3989
3990 /* Compare an integer expression with an integer.  */
3991
3992 static comparison
3993 compare_bound_int (gfc_expr *a, int b)
3994 {
3995   int i;
3996
3997   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3998     return CMP_UNKNOWN;
3999
4000   if (a->ts.type != BT_INTEGER)
4001     gfc_internal_error ("compare_bound_int(): Bad expression");
4002
4003   i = mpz_cmp_si (a->value.integer, b);
4004
4005   if (i < 0)
4006     return CMP_LT;
4007   if (i > 0)
4008     return CMP_GT;
4009   return CMP_EQ;
4010 }
4011
4012
4013 /* Compare an integer expression with a mpz_t.  */
4014
4015 static comparison
4016 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4017 {
4018   int i;
4019
4020   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4021     return CMP_UNKNOWN;
4022
4023   if (a->ts.type != BT_INTEGER)
4024     gfc_internal_error ("compare_bound_int(): Bad expression");
4025
4026   i = mpz_cmp (a->value.integer, b);
4027
4028   if (i < 0)
4029     return CMP_LT;
4030   if (i > 0)
4031     return CMP_GT;
4032   return CMP_EQ;
4033 }
4034
4035
4036 /* Compute the last value of a sequence given by a triplet.  
4037    Return 0 if it wasn't able to compute the last value, or if the
4038    sequence if empty, and 1 otherwise.  */
4039
4040 static int
4041 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4042                                 gfc_expr *stride, mpz_t last)
4043 {
4044   mpz_t rem;
4045
4046   if (start == NULL || start->expr_type != EXPR_CONSTANT
4047       || end == NULL || end->expr_type != EXPR_CONSTANT
4048       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4049     return 0;
4050
4051   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4052       || (stride != NULL && stride->ts.type != BT_INTEGER))
4053     return 0;
4054
4055   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4056     {
4057       if (compare_bound (start, end) == CMP_GT)
4058         return 0;
4059       mpz_set (last, end->value.integer);
4060       return 1;
4061     }
4062
4063   if (compare_bound_int (stride, 0) == CMP_GT)
4064     {
4065       /* Stride is positive */
4066       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4067         return 0;
4068     }
4069   else
4070     {
4071       /* Stride is negative */
4072       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4073         return 0;
4074     }
4075
4076   mpz_init (rem);
4077   mpz_sub (rem, end->value.integer, start->value.integer);
4078   mpz_tdiv_r (rem, rem, stride->value.integer);
4079   mpz_sub (last, end->value.integer, rem);
4080   mpz_clear (rem);
4081
4082   return 1;
4083 }
4084
4085
4086 /* Compare a single dimension of an array reference to the array
4087    specification.  */
4088
4089 static gfc_try
4090 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4091 {
4092   mpz_t last_value;
4093
4094   if (ar->dimen_type[i] == DIMEN_STAR)
4095     {
4096       gcc_assert (ar->stride[i] == NULL);
4097       /* This implies [*] as [*:] and [*:3] are not possible.  */
4098       if (ar->start[i] == NULL)
4099         {
4100           gcc_assert (ar->end[i] == NULL);
4101           return SUCCESS;
4102         }
4103     }
4104
4105 /* Given start, end and stride values, calculate the minimum and
4106    maximum referenced indexes.  */
4107
4108   switch (ar->dimen_type[i])
4109     {
4110     case DIMEN_VECTOR:
4111       break;
4112
4113     case DIMEN_STAR:
4114     case DIMEN_ELEMENT:
4115       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4116         {
4117           if (i < as->rank)
4118             gfc_warning ("Array reference at %L is out of bounds "
4119                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4120                          mpz_get_si (ar->start[i]->value.integer),
4121                          mpz_get_si (as->lower[i]->value.integer), i+1);
4122           else
4123             gfc_warning ("Array reference at %L is out of bounds "
4124                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4125                          mpz_get_si (ar->start[i]->value.integer),
4126                          mpz_get_si (as->lower[i]->value.integer),
4127                          i + 1 - as->rank);
4128           return SUCCESS;
4129         }
4130       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4131         {
4132           if (i < as->rank)
4133             gfc_warning ("Array reference at %L is out of bounds "
4134                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4135                          mpz_get_si (ar->start[i]->value.integer),
4136                          mpz_get_si (as->upper[i]->value.integer), i+1);
4137           else
4138             gfc_warning ("Array reference at %L is out of bounds "
4139                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4140                          mpz_get_si (ar->start[i]->value.integer),
4141                          mpz_get_si (as->upper[i]->value.integer),
4142                          i + 1 - as->rank);
4143           return SUCCESS;
4144         }
4145
4146       break;
4147
4148     case DIMEN_RANGE:
4149       {
4150 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4151 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4152
4153         comparison comp_start_end = compare_bound (AR_START, AR_END);
4154
4155         /* Check for zero stride, which is not allowed.  */
4156         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4157           {
4158             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4159             return FAILURE;
4160           }
4161
4162         /* if start == len || (stride > 0 && start < len)
4163                            || (stride < 0 && start > len),
4164            then the array section contains at least one element.  In this
4165            case, there is an out-of-bounds access if
4166            (start < lower || start > upper).  */
4167         if (compare_bound (AR_START, AR_END) == CMP_EQ
4168             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4169                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4170             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4171                 && comp_start_end == CMP_GT))
4172           {
4173             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4174               {
4175                 gfc_warning ("Lower array reference at %L is out of bounds "
4176                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4177                        mpz_get_si (AR_START->value.integer),
4178                        mpz_get_si (as->lower[i]->value.integer), i+1);
4179                 return SUCCESS;
4180               }
4181             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4182               {
4183                 gfc_warning ("Lower array reference at %L is out of bounds "
4184                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4185                        mpz_get_si (AR_START->value.integer),
4186                        mpz_get_si (as->upper[i]->value.integer), i+1);
4187                 return SUCCESS;
4188               }
4189           }
4190
4191         /* If we can compute the highest index of the array section,
4192            then it also has to be between lower and upper.  */
4193         mpz_init (last_value);
4194         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4195                                             last_value))
4196           {
4197             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4198               {
4199                 gfc_warning ("Upper array reference at %L is out of bounds "
4200                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4201                        mpz_get_si (last_value),
4202                        mpz_get_si (as->lower[i]->value.integer), i+1);
4203                 mpz_clear (last_value);
4204                 return SUCCESS;
4205               }
4206             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4207               {
4208                 gfc_warning ("Upper array reference at %L is out of bounds "
4209                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4210                        mpz_get_si (last_value),
4211                        mpz_get_si (as->upper[i]->value.integer), i+1);
4212                 mpz_clear (last_value);
4213                 return SUCCESS;
4214               }
4215           }
4216         mpz_clear (last_value);
4217
4218 #undef AR_START
4219 #undef AR_END
4220       }
4221       break;
4222
4223     default:
4224       gfc_internal_error ("check_dimension(): Bad array reference");
4225     }
4226
4227   return SUCCESS;
4228 }
4229
4230
4231 /* Compare an array reference with an array specification.  */
4232
4233 static gfc_try
4234 compare_spec_to_ref (gfc_array_ref *ar)
4235 {
4236   gfc_array_spec *as;
4237   int i;
4238
4239   as = ar->as;
4240   i = as->rank - 1;
4241   /* TODO: Full array sections are only allowed as actual parameters.  */
4242   if (as->type == AS_ASSUMED_SIZE
4243       && (/*ar->type == AR_FULL
4244           ||*/ (ar->type == AR_SECTION
4245               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4246     {
4247       gfc_error ("Rightmost upper bound of assumed size array section "
4248                  "not specified at %L", &ar->where);
4249       return FAILURE;
4250     }
4251
4252   if (ar->type == AR_FULL)
4253     return SUCCESS;
4254
4255   if (as->rank != ar->dimen)
4256     {
4257       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4258                  &ar->where, ar->dimen, as->rank);
4259       return FAILURE;
4260     }
4261
4262   /* ar->codimen == 0 is a local array.  */
4263   if (as->corank != ar->codimen && ar->codimen != 0)
4264     {
4265       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4266                  &ar->where, ar->codimen, as->corank);
4267       return FAILURE;
4268     }
4269
4270   for (i = 0; i < as->rank; i++)
4271     if (check_dimension (i, ar, as) == FAILURE)
4272       return FAILURE;
4273
4274   /* Local access has no coarray spec.  */
4275   if (ar->codimen != 0)
4276     for (i = as->rank; i < as->rank + as->corank; i++)
4277       {
4278         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate)
4279           {
4280             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4281                        i + 1 - as->rank, &ar->where);
4282             return FAILURE;
4283           }
4284         if (check_dimension (i, ar, as) == FAILURE)
4285           return FAILURE;
4286       }
4287
4288   return SUCCESS;
4289 }
4290
4291
4292 /* Resolve one part of an array index.  */
4293
4294 static gfc_try
4295 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4296                      int force_index_integer_kind)
4297 {
4298   gfc_typespec ts;
4299
4300   if (index == NULL)
4301     return SUCCESS;
4302
4303   if (gfc_resolve_expr (index) == FAILURE)
4304     return FAILURE;
4305
4306   if (check_scalar && index->rank != 0)
4307     {
4308       gfc_error ("Array index at %L must be scalar", &index->where);
4309       return FAILURE;
4310     }
4311
4312   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4313     {
4314       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4315                  &index->where, gfc_basic_typename (index->ts.type));
4316       return FAILURE;
4317     }
4318
4319   if (index->ts.type == BT_REAL)
4320     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4321                         &index->where) == FAILURE)
4322       return FAILURE;
4323
4324   if ((index->ts.kind != gfc_index_integer_kind
4325        && force_index_integer_kind)
4326       || index->ts.type != BT_INTEGER)
4327     {
4328       gfc_clear_ts (&ts);
4329       ts.type = BT_INTEGER;
4330       ts.kind = gfc_index_integer_kind;
4331
4332       gfc_convert_type_warn (index, &ts, 2, 0);
4333     }
4334
4335   return SUCCESS;
4336 }
4337
4338 /* Resolve one part of an array index.  */
4339
4340 gfc_try
4341 gfc_resolve_index (gfc_expr *index, int check_scalar)
4342 {
4343   return gfc_resolve_index_1 (index, check_scalar, 1);
4344 }
4345
4346 /* Resolve a dim argument to an intrinsic function.  */
4347
4348 gfc_try
4349 gfc_resolve_dim_arg (gfc_expr *dim)
4350 {
4351   if (dim == NULL)
4352     return SUCCESS;
4353
4354   if (gfc_resolve_expr (dim) == FAILURE)
4355     return FAILURE;
4356
4357   if (dim->rank != 0)
4358     {
4359       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4360       return FAILURE;
4361
4362     }
4363
4364   if (dim->ts.type != BT_INTEGER)
4365     {
4366       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4367       return FAILURE;
4368     }
4369
4370   if (dim->ts.kind != gfc_index_integer_kind)
4371     {
4372       gfc_typespec ts;
4373
4374       gfc_clear_ts (&ts);
4375       ts.type = BT_INTEGER;
4376       ts.kind = gfc_index_integer_kind;
4377
4378       gfc_convert_type_warn (dim, &ts, 2, 0);
4379     }
4380
4381   return SUCCESS;
4382 }
4383
4384 /* Given an expression that contains array references, update those array
4385    references to point to the right array specifications.  While this is
4386    filled in during matching, this information is difficult to save and load
4387    in a module, so we take care of it here.
4388
4389    The idea here is that the original array reference comes from the
4390    base symbol.  We traverse the list of reference structures, setting
4391    the stored reference to references.  Component references can
4392    provide an additional array specification.  */
4393
4394 static void
4395 find_array_spec (gfc_expr *e)
4396 {
4397   gfc_array_spec *as;
4398   gfc_component *c;
4399   gfc_symbol *derived;
4400   gfc_ref *ref;
4401
4402   if (e->symtree->n.sym->ts.type == BT_CLASS)
4403     as = CLASS_DATA (e->symtree->n.sym)->as;
4404   else
4405     as = e->symtree->n.sym->as;
4406   derived = NULL;
4407
4408   for (ref = e->ref; ref; ref = ref->next)
4409     switch (ref->type)
4410       {
4411       case REF_ARRAY:
4412         if (as == NULL)
4413           gfc_internal_error ("find_array_spec(): Missing spec");
4414
4415         ref->u.ar.as = as;
4416         as = NULL;
4417         break;
4418
4419       case REF_COMPONENT:
4420         if (derived == NULL)
4421           derived = e->symtree->n.sym->ts.u.derived;
4422
4423         if (derived->attr.is_class)
4424           derived = derived->components->ts.u.derived;
4425
4426         c = derived->components;
4427
4428         for (; c; c = c->next)
4429           if (c == ref->u.c.component)
4430             {
4431               /* Track the sequence of component references.  */
4432               if (c->ts.type == BT_DERIVED)
4433                 derived = c->ts.u.derived;
4434               break;
4435             }
4436
4437         if (c == NULL)
4438           gfc_internal_error ("find_array_spec(): Component not found");
4439
4440         if (c->attr.dimension)
4441           {
4442             if (as != NULL)
4443               gfc_internal_error ("find_array_spec(): unused as(1)");
4444             as = c->as;
4445           }
4446
4447         break;
4448
4449       case REF_SUBSTRING:
4450         break;
4451       }
4452
4453   if (as != NULL)
4454     gfc_internal_error ("find_array_spec(): unused as(2)");
4455 }
4456
4457
4458 /* Resolve an array reference.  */
4459
4460 static gfc_try
4461 resolve_array_ref (gfc_array_ref *ar)
4462 {
4463   int i, check_scalar;
4464   gfc_expr *e;
4465
4466   for (i = 0; i < ar->dimen + ar->codimen; i++)
4467     {
4468       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4469
4470       /* Do not force gfc_index_integer_kind for the start.  We can
4471          do fine with any integer kind.  This avoids temporary arrays
4472          created for indexing with a vector.  */
4473       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4474         return FAILURE;
4475       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4476         return FAILURE;
4477       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4478         return FAILURE;
4479
4480       e = ar->start[i];
4481
4482       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4483         switch (e->rank)
4484           {
4485           case 0:
4486             ar->dimen_type[i] = DIMEN_ELEMENT;
4487             break;
4488
4489           case 1:
4490             ar->dimen_type[i] = DIMEN_VECTOR;
4491             if (e->expr_type == EXPR_VARIABLE
4492                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4493               ar->start[i] = gfc_get_parentheses (e);
4494             break;
4495
4496           default:
4497             gfc_error ("Array index at %L is an array of rank %d",
4498                        &ar->c_where[i], e->rank);
4499             return FAILURE;
4500           }
4501
4502       /* Fill in the upper bound, which may be lower than the
4503          specified one for something like a(2:10:5), which is
4504          identical to a(2:7:5).  Only relevant for strides not equal
4505          to one.  */
4506       if (ar->dimen_type[i] == DIMEN_RANGE
4507           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4508           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0)
4509         {
4510           mpz_t size, end;
4511
4512           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4513             {
4514               if (ar->end[i] == NULL)
4515                 {
4516                   ar->end[i] =
4517                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4518                                            &ar->where);
4519                   mpz_set (ar->end[i]->value.integer, end);
4520                 }
4521               else if (ar->end[i]->ts.type == BT_INTEGER
4522                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4523                 {
4524                   mpz_set (ar->end[i]->value.integer, end);
4525                 }
4526               else
4527                 gcc_unreachable ();
4528
4529               mpz_clear (size);
4530               mpz_clear (end);
4531             }
4532         }
4533     }
4534
4535   if (ar->type == AR_FULL && ar->as->rank == 0)
4536     ar->type = AR_ELEMENT;
4537
4538   /* If the reference type is unknown, figure out what kind it is.  */
4539
4540   if (ar->type == AR_UNKNOWN)
4541     {
4542       ar->type = AR_ELEMENT;
4543       for (i = 0; i < ar->dimen; i++)
4544         if (ar->dimen_type[i] == DIMEN_RANGE
4545             || ar->dimen_type[i] == DIMEN_VECTOR)
4546           {
4547             ar->type = AR_SECTION;
4548             break;
4549           }
4550     }
4551
4552   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4553     return FAILURE;
4554
4555   return SUCCESS;
4556 }
4557
4558
4559 static gfc_try
4560 resolve_substring (gfc_ref *ref)
4561 {
4562   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4563
4564   if (ref->u.ss.start != NULL)
4565     {
4566       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4567         return FAILURE;
4568
4569       if (ref->u.ss.start->ts.type != BT_INTEGER)
4570         {
4571           gfc_error ("Substring start index at %L must be of type INTEGER",
4572                      &ref->u.ss.start->where);
4573           return FAILURE;
4574         }
4575
4576       if (ref->u.ss.start->rank != 0)
4577         {
4578           gfc_error ("Substring start index at %L must be scalar",
4579                      &ref->u.ss.start->where);
4580           return FAILURE;
4581         }
4582
4583       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4584           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4585               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4586         {
4587           gfc_error ("Substring start index at %L is less than one",
4588                      &ref->u.ss.start->where);
4589           return FAILURE;
4590         }
4591     }
4592
4593   if (ref->u.ss.end != NULL)
4594     {
4595       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4596         return FAILURE;
4597
4598       if (ref->u.ss.end->ts.type != BT_INTEGER)
4599         {
4600           gfc_error ("Substring end index at %L must be of type INTEGER",
4601                      &ref->u.ss.end->where);
4602           return FAILURE;
4603         }
4604
4605       if (ref->u.ss.end->rank != 0)
4606         {
4607           gfc_error ("Substring end index at %L must be scalar",
4608                      &ref->u.ss.end->where);
4609           return FAILURE;
4610         }
4611
4612       if (ref->u.ss.length != NULL
4613           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4614           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4615               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4616         {
4617           gfc_error ("Substring end index at %L exceeds the string length",
4618                      &ref->u.ss.start->where);
4619           return FAILURE;
4620         }
4621
4622       if (compare_bound_mpz_t (ref->u.ss.end,
4623                                gfc_integer_kinds[k].huge) == CMP_GT
4624           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4625               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4626         {
4627           gfc_error ("Substring end index at %L is too large",
4628                      &ref->u.ss.end->where);
4629           return FAILURE;
4630         }
4631     }
4632
4633   return SUCCESS;
4634 }
4635
4636
4637 /* This function supplies missing substring charlens.  */
4638
4639 void
4640 gfc_resolve_substring_charlen (gfc_expr *e)
4641 {
4642   gfc_ref *char_ref;
4643   gfc_expr *start, *end;
4644
4645   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4646     if (char_ref->type == REF_SUBSTRING)
4647       break;
4648
4649   if (!char_ref)
4650     return;
4651
4652   gcc_assert (char_ref->next == NULL);
4653
4654   if (e->ts.u.cl)
4655     {
4656       if (e->ts.u.cl->length)
4657         gfc_free_expr (e->ts.u.cl->length);
4658       else if (e->expr_type == EXPR_VARIABLE
4659                  && e->symtree->n.sym->attr.dummy)
4660         return;
4661     }
4662
4663   e->ts.type = BT_CHARACTER;
4664   e->ts.kind = gfc_default_character_kind;
4665
4666   if (!e->ts.u.cl)
4667     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4668
4669   if (char_ref->u.ss.start)
4670     start = gfc_copy_expr (char_ref->u.ss.start);
4671   else
4672     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4673
4674   if (char_ref->u.ss.end)
4675     end = gfc_copy_expr (char_ref->u.ss.end);
4676   else if (e->expr_type == EXPR_VARIABLE)
4677     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4678   else
4679     end = NULL;
4680
4681   if (!start || !end)
4682     return;
4683
4684   /* Length = (end - start +1).  */
4685   e->ts.u.cl->length = gfc_subtract (end, start);
4686   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4687                                 gfc_get_int_expr (gfc_default_integer_kind,
4688                                                   NULL, 1));
4689
4690   e->ts.u.cl->length->ts.type = BT_INTEGER;
4691   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4692
4693   /* Make sure that the length is simplified.  */
4694   gfc_simplify_expr (e->ts.u.cl->length, 1);
4695   gfc_resolve_expr (e->ts.u.cl->length);
4696 }
4697
4698
4699 /* Resolve subtype references.  */
4700
4701 static gfc_try
4702 resolve_ref (gfc_expr *expr)
4703 {
4704   int current_part_dimension, n_components, seen_part_dimension;
4705   gfc_ref *ref;
4706
4707   for (ref = expr->ref; ref; ref = ref->next)
4708     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4709       {
4710         find_array_spec (expr);
4711         break;
4712       }
4713
4714   for (ref = expr->ref; ref; ref = ref->next)
4715     switch (ref->type)
4716       {
4717       case REF_ARRAY:
4718         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4719           return FAILURE;
4720         break;
4721
4722       case REF_COMPONENT:
4723         break;
4724
4725       case REF_SUBSTRING:
4726         resolve_substring (ref);
4727         break;
4728       }
4729
4730   /* Check constraints on part references.  */
4731
4732   current_part_dimension = 0;
4733   seen_part_dimension = 0;
4734   n_components = 0;
4735
4736   for (ref = expr->ref; ref; ref = ref->next)
4737     {
4738       switch (ref->type)
4739         {
4740         case REF_ARRAY:
4741           switch (ref->u.ar.type)
4742             {
4743             case AR_FULL:
4744               /* Coarray scalar.  */
4745               if (ref->u.ar.as->rank == 0)
4746                 {
4747                   current_part_dimension = 0;
4748                   break;
4749                 }
4750               /* Fall through.  */
4751             case AR_SECTION:
4752               current_part_dimension = 1;
4753               break;
4754
4755             case AR_ELEMENT:
4756               current_part_dimension = 0;
4757               break;
4758
4759             case AR_UNKNOWN:
4760               gfc_internal_error ("resolve_ref(): Bad array reference");
4761             }
4762
4763           break;
4764
4765         case REF_COMPONENT:
4766           if (current_part_dimension || seen_part_dimension)
4767             {
4768               /* F03:C614.  */
4769               if (ref->u.c.component->attr.pointer
4770                   || ref->u.c.component->attr.proc_pointer)
4771                 {
4772                   gfc_error ("Component to the right of a part reference "
4773                              "with nonzero rank must not have the POINTER "
4774                              "attribute at %L", &expr->where);
4775                   return FAILURE;
4776                 }
4777               else if (ref->u.c.component->attr.allocatable)
4778                 {
4779                   gfc_error ("Component to the right of a part reference "
4780                              "with nonzero rank must not have the ALLOCATABLE "
4781                              "attribute at %L", &expr->where);
4782                   return FAILURE;
4783                 }
4784             }
4785
4786           n_components++;
4787           break;
4788
4789         case REF_SUBSTRING:
4790           break;
4791         }
4792
4793       if (((ref->type == REF_COMPONENT && n_components > 1)
4794            || ref->next == NULL)
4795           && current_part_dimension
4796           && seen_part_dimension)
4797         {
4798           gfc_error ("Two or more part references with nonzero rank must "
4799                      "not be specified at %L", &expr->where);
4800           return FAILURE;
4801         }
4802
4803       if (ref->type == REF_COMPONENT)
4804         {
4805           if (current_part_dimension)
4806             seen_part_dimension = 1;
4807
4808           /* reset to make sure */
4809           current_part_dimension = 0;
4810         }
4811     }
4812
4813   return SUCCESS;
4814 }
4815
4816
4817 /* Given an expression, determine its shape.  This is easier than it sounds.
4818    Leaves the shape array NULL if it is not possible to determine the shape.  */
4819
4820 static void
4821 expression_shape (gfc_expr *e)
4822 {
4823   mpz_t array[GFC_MAX_DIMENSIONS];
4824   int i;
4825
4826   if (e->rank == 0 || e->shape != NULL)
4827     return;
4828
4829   for (i = 0; i < e->rank; i++)
4830     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4831       goto fail;
4832
4833   e->shape = gfc_get_shape (e->rank);
4834
4835   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4836
4837   return;
4838
4839 fail:
4840   for (i--; i >= 0; i--)
4841     mpz_clear (array[i]);
4842 }
4843
4844
4845 /* Given a variable expression node, compute the rank of the expression by
4846    examining the base symbol and any reference structures it may have.  */
4847
4848 static void
4849 expression_rank (gfc_expr *e)
4850 {
4851   gfc_ref *ref;
4852   int i, rank;
4853
4854   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4855      could lead to serious confusion...  */
4856   gcc_assert (e->expr_type != EXPR_COMPCALL);
4857
4858   if (e->ref == NULL)
4859     {
4860       if (e->expr_type == EXPR_ARRAY)
4861         goto done;
4862       /* Constructors can have a rank different from one via RESHAPE().  */
4863
4864       if (e->symtree == NULL)
4865         {
4866           e->rank = 0;
4867           goto done;
4868         }
4869
4870       e->rank = (e->symtree->n.sym->as == NULL)
4871                 ? 0 : e->symtree->n.sym->as->rank;
4872       goto done;
4873     }
4874
4875   rank = 0;
4876
4877   for (ref = e->ref; ref; ref = ref->next)
4878     {
4879       if (ref->type != REF_ARRAY)
4880         continue;
4881
4882       if (ref->u.ar.type == AR_FULL)
4883         {
4884           rank = ref->u.ar.as->rank;
4885           break;
4886         }
4887
4888       if (ref->u.ar.type == AR_SECTION)
4889         {
4890           /* Figure out the rank of the section.  */
4891           if (rank != 0)
4892             gfc_internal_error ("expression_rank(): Two array specs");
4893
4894           for (i = 0; i < ref->u.ar.dimen; i++)
4895             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4896                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4897               rank++;
4898
4899           break;
4900         }
4901     }
4902
4903   e->rank = rank;
4904
4905 done:
4906   expression_shape (e);
4907 }
4908
4909
4910 /* Resolve a variable expression.  */
4911
4912 static gfc_try
4913 resolve_variable (gfc_expr *e)
4914 {
4915   gfc_symbol *sym;
4916   gfc_try t;
4917
4918   t = SUCCESS;
4919
4920   if (e->symtree == NULL)
4921     return FAILURE;
4922   sym = e->symtree->n.sym;
4923
4924   /* If this is an associate-name, it may be parsed with an array reference
4925      in error even though the target is scalar.  Fail directly in this case.  */
4926   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
4927     return FAILURE;
4928
4929   /* On the other hand, the parser may not have known this is an array;
4930      in this case, we have to add a FULL reference.  */
4931   if (sym->assoc && sym->attr.dimension && !e->ref)
4932     {
4933       e->ref = gfc_get_ref ();
4934       e->ref->type = REF_ARRAY;
4935       e->ref->u.ar.type = AR_FULL;
4936       e->ref->u.ar.dimen = 0;
4937     }
4938
4939   if (e->ref && resolve_ref (e) == FAILURE)
4940     return FAILURE;
4941
4942   if (sym->attr.flavor == FL_PROCEDURE
4943       && (!sym->attr.function
4944           || (sym->attr.function && sym->result
4945               && sym->result->attr.proc_pointer
4946               && !sym->result->attr.function)))
4947     {
4948       e->ts.type = BT_PROCEDURE;
4949       goto resolve_procedure;
4950     }
4951
4952   if (sym->ts.type != BT_UNKNOWN)
4953     gfc_variable_attr (e, &e->ts);
4954   else
4955     {
4956       /* Must be a simple variable reference.  */
4957       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4958         return FAILURE;
4959       e->ts = sym->ts;
4960     }
4961
4962   if (check_assumed_size_reference (sym, e))
4963     return FAILURE;
4964
4965   /* Deal with forward references to entries during resolve_code, to
4966      satisfy, at least partially, 12.5.2.5.  */
4967   if (gfc_current_ns->entries
4968       && current_entry_id == sym->entry_id
4969       && cs_base
4970       && cs_base->current
4971       && cs_base->current->op != EXEC_ENTRY)
4972     {
4973       gfc_entry_list *entry;
4974       gfc_formal_arglist *formal;
4975       int n;
4976       bool seen;
4977
4978       /* If the symbol is a dummy...  */
4979       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4980         {
4981           entry = gfc_current_ns->entries;
4982           seen = false;
4983
4984           /* ...test if the symbol is a parameter of previous entries.  */
4985           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4986             for (formal = entry->sym->formal; formal; formal = formal->next)
4987               {
4988                 if (formal->sym && sym->name == formal->sym->name)
4989                   seen = true;
4990               }
4991
4992           /*  If it has not been seen as a dummy, this is an error.  */
4993           if (!seen)
4994             {
4995               if (specification_expr)
4996                 gfc_error ("Variable '%s', used in a specification expression"
4997                            ", is referenced at %L before the ENTRY statement "
4998                            "in which it is a parameter",
4999                            sym->name, &cs_base->current->loc);
5000               else
5001                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5002                            "statement in which it is a parameter",
5003                            sym->name, &cs_base->current->loc);
5004               t = FAILURE;
5005             }
5006         }
5007
5008       /* Now do the same check on the specification expressions.  */
5009       specification_expr = 1;
5010       if (sym->ts.type == BT_CHARACTER
5011           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5012         t = FAILURE;
5013
5014       if (sym->as)
5015         for (n = 0; n < sym->as->rank; n++)
5016           {
5017              specification_expr = 1;
5018              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5019                t = FAILURE;
5020              specification_expr = 1;
5021              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5022                t = FAILURE;
5023           }
5024       specification_expr = 0;
5025
5026       if (t == SUCCESS)
5027         /* Update the symbol's entry level.  */
5028         sym->entry_id = current_entry_id + 1;
5029     }
5030
5031   /* If a symbol has been host_associated mark it.  This is used latter,
5032      to identify if aliasing is possible via host association.  */
5033   if (sym->attr.flavor == FL_VARIABLE
5034         && gfc_current_ns->parent
5035         && (gfc_current_ns->parent == sym->ns
5036               || (gfc_current_ns->parent->parent
5037                     && gfc_current_ns->parent->parent == sym->ns)))
5038     sym->attr.host_assoc = 1;
5039
5040 resolve_procedure:
5041   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5042     t = FAILURE;
5043
5044   /* F2008, C617 and C1229.  */
5045   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5046       && gfc_is_coindexed (e))
5047     {
5048       gfc_ref *ref, *ref2 = NULL;
5049
5050       if (e->ts.type == BT_CLASS)
5051         {
5052           gfc_error ("Polymorphic subobject of coindexed object at %L",
5053                      &e->where);
5054           t = FAILURE;
5055         }
5056
5057       for (ref = e->ref; ref; ref = ref->next)
5058         {
5059           if (ref->type == REF_COMPONENT)
5060             ref2 = ref;
5061           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5062             break;
5063         }
5064
5065       for ( ; ref; ref = ref->next)
5066         if (ref->type == REF_COMPONENT)
5067           break;
5068
5069       /* Expression itself is coindexed object.  */
5070       if (ref == NULL)
5071         {
5072           gfc_component *c;
5073           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5074           for ( ; c; c = c->next)
5075             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5076               {
5077                 gfc_error ("Coindexed object with polymorphic allocatable "
5078                          "subcomponent at %L", &e->where);
5079                 t = FAILURE;
5080                 break;
5081               }
5082         }
5083     }
5084
5085   return t;
5086 }
5087
5088
5089 /* Checks to see that the correct symbol has been host associated.
5090    The only situation where this arises is that in which a twice
5091    contained function is parsed after the host association is made.
5092    Therefore, on detecting this, change the symbol in the expression
5093    and convert the array reference into an actual arglist if the old
5094    symbol is a variable.  */
5095 static bool
5096 check_host_association (gfc_expr *e)
5097 {
5098   gfc_symbol *sym, *old_sym;
5099   gfc_symtree *st;
5100   int n;
5101   gfc_ref *ref;
5102   gfc_actual_arglist *arg, *tail = NULL;
5103   bool retval = e->expr_type == EXPR_FUNCTION;
5104
5105   /*  If the expression is the result of substitution in
5106       interface.c(gfc_extend_expr) because there is no way in
5107       which the host association can be wrong.  */
5108   if (e->symtree == NULL
5109         || e->symtree->n.sym == NULL
5110         || e->user_operator)
5111     return retval;
5112
5113   old_sym = e->symtree->n.sym;
5114
5115   if (gfc_current_ns->parent
5116         && old_sym->ns != gfc_current_ns)
5117     {
5118       /* Use the 'USE' name so that renamed module symbols are
5119          correctly handled.  */
5120       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5121
5122       if (sym && old_sym != sym
5123               && sym->ts.type == old_sym->ts.type
5124               && sym->attr.flavor == FL_PROCEDURE
5125               && sym->attr.contained)
5126         {
5127           /* Clear the shape, since it might not be valid.  */
5128           if (e->shape != NULL)
5129             {
5130               for (n = 0; n < e->rank; n++)
5131                 mpz_clear (e->shape[n]);
5132
5133               gfc_free (e->shape);
5134             }
5135
5136           /* Give the expression the right symtree!  */
5137           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5138           gcc_assert (st != NULL);
5139
5140           if (old_sym->attr.flavor == FL_PROCEDURE
5141                 || e->expr_type == EXPR_FUNCTION)
5142             {
5143               /* Original was function so point to the new symbol, since
5144                  the actual argument list is already attached to the
5145                  expression. */
5146               e->value.function.esym = NULL;
5147               e->symtree = st;
5148             }
5149           else
5150             {
5151               /* Original was variable so convert array references into
5152                  an actual arglist. This does not need any checking now
5153                  since gfc_resolve_function will take care of it.  */
5154               e->value.function.actual = NULL;
5155               e->expr_type = EXPR_FUNCTION;
5156               e->symtree = st;
5157
5158               /* Ambiguity will not arise if the array reference is not
5159                  the last reference.  */
5160               for (ref = e->ref; ref; ref = ref->next)
5161                 if (ref->type == REF_ARRAY && ref->next == NULL)
5162                   break;
5163
5164               gcc_assert (ref->type == REF_ARRAY);
5165
5166               /* Grab the start expressions from the array ref and
5167                  copy them into actual arguments.  */
5168               for (n = 0; n < ref->u.ar.dimen; n++)
5169                 {
5170                   arg = gfc_get_actual_arglist ();
5171                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5172                   if (e->value.function.actual == NULL)
5173                     tail = e->value.function.actual = arg;
5174                   else
5175                     {
5176                       tail->next = arg;
5177                       tail = arg;
5178                     }
5179                 }
5180
5181               /* Dump the reference list and set the rank.  */
5182               gfc_free_ref_list (e->ref);
5183               e->ref = NULL;
5184               e->rank = sym->as ? sym->as->rank : 0;
5185             }
5186
5187           gfc_resolve_expr (e);
5188           sym->refs++;
5189         }
5190     }
5191   /* This might have changed!  */
5192   return e->expr_type == EXPR_FUNCTION;
5193 }
5194
5195
5196 static void
5197 gfc_resolve_character_operator (gfc_expr *e)
5198 {
5199   gfc_expr *op1 = e->value.op.op1;
5200   gfc_expr *op2 = e->value.op.op2;
5201   gfc_expr *e1 = NULL;
5202   gfc_expr *e2 = NULL;
5203
5204   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5205
5206   if (op1->ts.u.cl && op1->ts.u.cl->length)
5207     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5208   else if (op1->expr_type == EXPR_CONSTANT)
5209     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5210                            op1->value.character.length);
5211
5212   if (op2->ts.u.cl && op2->ts.u.cl->length)
5213     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5214   else if (op2->expr_type == EXPR_CONSTANT)
5215     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5216                            op2->value.character.length);
5217
5218   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5219
5220   if (!e1 || !e2)
5221     return;
5222
5223   e->ts.u.cl->length = gfc_add (e1, e2);
5224   e->ts.u.cl->length->ts.type = BT_INTEGER;
5225   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5226   gfc_simplify_expr (e->ts.u.cl->length, 0);
5227   gfc_resolve_expr (e->ts.u.cl->length);
5228
5229   return;
5230 }
5231
5232
5233 /*  Ensure that an character expression has a charlen and, if possible, a
5234     length expression.  */
5235
5236 static void
5237 fixup_charlen (gfc_expr *e)
5238 {
5239   /* The cases fall through so that changes in expression type and the need
5240      for multiple fixes are picked up.  In all circumstances, a charlen should
5241      be available for the middle end to hang a backend_decl on.  */
5242   switch (e->expr_type)
5243     {
5244     case EXPR_OP:
5245       gfc_resolve_character_operator (e);
5246
5247     case EXPR_ARRAY:
5248       if (e->expr_type == EXPR_ARRAY)
5249         gfc_resolve_character_array_constructor (e);
5250
5251     case EXPR_SUBSTRING:
5252       if (!e->ts.u.cl && e->ref)
5253         gfc_resolve_substring_charlen (e);
5254
5255     default:
5256       if (!e->ts.u.cl)
5257         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5258
5259       break;
5260     }
5261 }
5262
5263
5264 /* Update an actual argument to include the passed-object for type-bound
5265    procedures at the right position.  */
5266
5267 static gfc_actual_arglist*
5268 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5269                      const char *name)
5270 {
5271   gcc_assert (argpos > 0);
5272
5273   if (argpos == 1)
5274     {
5275       gfc_actual_arglist* result;
5276
5277       result = gfc_get_actual_arglist ();
5278       result->expr = po;
5279       result->next = lst;
5280       if (name)
5281         result->name = name;
5282
5283       return result;
5284     }
5285
5286   if (lst)
5287     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5288   else
5289     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5290   return lst;
5291 }
5292
5293
5294 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5295
5296 static gfc_expr*
5297 extract_compcall_passed_object (gfc_expr* e)
5298 {
5299   gfc_expr* po;
5300
5301   gcc_assert (e->expr_type == EXPR_COMPCALL);
5302
5303   if (e->value.compcall.base_object)
5304     po = gfc_copy_expr (e->value.compcall.base_object);
5305   else
5306     {
5307       po = gfc_get_expr ();
5308       po->expr_type = EXPR_VARIABLE;
5309       po->symtree = e->symtree;
5310       po->ref = gfc_copy_ref (e->ref);
5311       po->where = e->where;
5312     }
5313
5314   if (gfc_resolve_expr (po) == FAILURE)
5315     return NULL;
5316
5317   return po;
5318 }
5319
5320
5321 /* Update the arglist of an EXPR_COMPCALL expression to include the
5322    passed-object.  */
5323
5324 static gfc_try
5325 update_compcall_arglist (gfc_expr* e)
5326 {
5327   gfc_expr* po;
5328   gfc_typebound_proc* tbp;
5329
5330   tbp = e->value.compcall.tbp;
5331
5332   if (tbp->error)
5333     return FAILURE;
5334
5335   po = extract_compcall_passed_object (e);
5336   if (!po)
5337     return FAILURE;
5338
5339   if (tbp->nopass || e->value.compcall.ignore_pass)
5340     {
5341       gfc_free_expr (po);
5342       return SUCCESS;
5343     }
5344
5345   gcc_assert (tbp->pass_arg_num > 0);
5346   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5347                                                   tbp->pass_arg_num,
5348                                                   tbp->pass_arg);
5349
5350   return SUCCESS;
5351 }
5352
5353
5354 /* Extract the passed object from a PPC call (a copy of it).  */
5355
5356 static gfc_expr*
5357 extract_ppc_passed_object (gfc_expr *e)
5358 {
5359   gfc_expr *po;
5360   gfc_ref **ref;
5361
5362   po = gfc_get_expr ();
5363   po->expr_type = EXPR_VARIABLE;
5364   po->symtree = e->symtree;
5365   po->ref = gfc_copy_ref (e->ref);
5366   po->where = e->where;
5367
5368   /* Remove PPC reference.  */
5369   ref = &po->ref;
5370   while ((*ref)->next)
5371     ref = &(*ref)->next;
5372   gfc_free_ref_list (*ref);
5373   *ref = NULL;
5374
5375   if (gfc_resolve_expr (po) == FAILURE)
5376     return NULL;
5377
5378   return po;
5379 }
5380
5381
5382 /* Update the actual arglist of a procedure pointer component to include the
5383    passed-object.  */
5384
5385 static gfc_try
5386 update_ppc_arglist (gfc_expr* e)
5387 {
5388   gfc_expr* po;
5389   gfc_component *ppc;
5390   gfc_typebound_proc* tb;
5391
5392   if (!gfc_is_proc_ptr_comp (e, &ppc))
5393     return FAILURE;
5394
5395   tb = ppc->tb;
5396
5397   if (tb->error)
5398     return FAILURE;
5399   else if (tb->nopass)
5400     return SUCCESS;
5401
5402   po = extract_ppc_passed_object (e);
5403   if (!po)
5404     return FAILURE;
5405
5406   if (po->rank > 0)
5407     {
5408       gfc_error ("Passed-object at %L must be scalar", &e->where);
5409       return FAILURE;
5410     }
5411
5412   gcc_assert (tb->pass_arg_num > 0);
5413   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5414                                                   tb->pass_arg_num,
5415                                                   tb->pass_arg);
5416
5417   return SUCCESS;
5418 }
5419
5420
5421 /* Check that the object a TBP is called on is valid, i.e. it must not be
5422    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5423
5424 static gfc_try
5425 check_typebound_baseobject (gfc_expr* e)
5426 {
5427   gfc_expr* base;
5428
5429   base = extract_compcall_passed_object (e);
5430   if (!base)
5431     return FAILURE;
5432
5433   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5434
5435   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5436     {
5437       gfc_error ("Base object for type-bound procedure call at %L is of"
5438                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5439       return FAILURE;
5440     }
5441
5442   /* If the procedure called is NOPASS, the base object must be scalar.  */
5443   if (e->value.compcall.tbp->nopass && base->rank > 0)
5444     {
5445       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5446                  " be scalar", &e->where);
5447       return FAILURE;
5448     }
5449
5450   /* FIXME: Remove once PR 41177 (this problem) is fixed completely.  */
5451   if (base->rank > 0)
5452     {
5453       gfc_error ("Non-scalar base object at %L currently not implemented",
5454                  &e->where);
5455       return FAILURE;
5456     }
5457
5458   return SUCCESS;
5459 }
5460
5461
5462 /* Resolve a call to a type-bound procedure, either function or subroutine,
5463    statically from the data in an EXPR_COMPCALL expression.  The adapted
5464    arglist and the target-procedure symtree are returned.  */
5465
5466 static gfc_try
5467 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5468                           gfc_actual_arglist** actual)
5469 {
5470   gcc_assert (e->expr_type == EXPR_COMPCALL);
5471   gcc_assert (!e->value.compcall.tbp->is_generic);
5472
5473   /* Update the actual arglist for PASS.  */
5474   if (update_compcall_arglist (e) == FAILURE)
5475     return FAILURE;
5476
5477   *actual = e->value.compcall.actual;
5478   *target = e->value.compcall.tbp->u.specific;
5479
5480   gfc_free_ref_list (e->ref);
5481   e->ref = NULL;
5482   e->value.compcall.actual = NULL;
5483
5484   return SUCCESS;
5485 }
5486
5487
5488 /* Get the ultimate declared type from an expression.  In addition,
5489    return the last class/derived type reference and the copy of the
5490    reference list.  */
5491 static gfc_symbol*
5492 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5493                         gfc_expr *e)
5494 {
5495   gfc_symbol *declared;
5496   gfc_ref *ref;
5497
5498   declared = NULL;
5499   if (class_ref)
5500     *class_ref = NULL;
5501   if (new_ref)
5502     *new_ref = gfc_copy_ref (e->ref);
5503
5504   for (ref = e->ref; ref; ref = ref->next)
5505     {
5506       if (ref->type != REF_COMPONENT)
5507         continue;
5508
5509       if (ref->u.c.component->ts.type == BT_CLASS
5510             || ref->u.c.component->ts.type == BT_DERIVED)
5511         {
5512           declared = ref->u.c.component->ts.u.derived;
5513           if (class_ref)
5514             *class_ref = ref;
5515         }
5516     }
5517
5518   if (declared == NULL)
5519     declared = e->symtree->n.sym->ts.u.derived;
5520
5521   return declared;
5522 }
5523
5524
5525 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5526    which of the specific bindings (if any) matches the arglist and transform
5527    the expression into a call of that binding.  */
5528
5529 static gfc_try
5530 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5531 {
5532   gfc_typebound_proc* genproc;
5533   const char* genname;
5534   gfc_symtree *st;
5535   gfc_symbol *derived;
5536
5537   gcc_assert (e->expr_type == EXPR_COMPCALL);
5538   genname = e->value.compcall.name;
5539   genproc = e->value.compcall.tbp;
5540
5541   if (!genproc->is_generic)
5542     return SUCCESS;
5543
5544   /* Try the bindings on this type and in the inheritance hierarchy.  */
5545   for (; genproc; genproc = genproc->overridden)
5546     {
5547       gfc_tbp_generic* g;
5548
5549       gcc_assert (genproc->is_generic);
5550       for (g = genproc->u.generic; g; g = g->next)
5551         {
5552           gfc_symbol* target;
5553           gfc_actual_arglist* args;
5554           bool matches;
5555
5556           gcc_assert (g->specific);
5557
5558           if (g->specific->error)
5559             continue;
5560
5561           target = g->specific->u.specific->n.sym;
5562
5563           /* Get the right arglist by handling PASS/NOPASS.  */
5564           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5565           if (!g->specific->nopass)
5566             {
5567               gfc_expr* po;
5568               po = extract_compcall_passed_object (e);
5569               if (!po)
5570                 return FAILURE;
5571
5572               gcc_assert (g->specific->pass_arg_num > 0);
5573               gcc_assert (!g->specific->error);
5574               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5575                                           g->specific->pass_arg);
5576             }
5577           resolve_actual_arglist (args, target->attr.proc,
5578                                   is_external_proc (target) && !target->formal);
5579
5580           /* Check if this arglist matches the formal.  */
5581           matches = gfc_arglist_matches_symbol (&args, target);
5582
5583           /* Clean up and break out of the loop if we've found it.  */
5584           gfc_free_actual_arglist (args);
5585           if (matches)
5586             {
5587               e->value.compcall.tbp = g->specific;
5588               genname = g->specific_st->name;
5589               /* Pass along the name for CLASS methods, where the vtab
5590                  procedure pointer component has to be referenced.  */
5591               if (name)
5592                 *name = genname;
5593               goto success;
5594             }
5595         }
5596     }
5597
5598   /* Nothing matching found!  */
5599   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5600              " '%s' at %L", genname, &e->where);
5601   return FAILURE;
5602
5603 success:
5604   /* Make sure that we have the right specific instance for the name.  */
5605   derived = get_declared_from_expr (NULL, NULL, e);
5606
5607   st = gfc_find_typebound_proc (derived, NULL, genname, false, &e->where);
5608   if (st)
5609     e->value.compcall.tbp = st->n.tb;
5610
5611   return SUCCESS;
5612 }
5613
5614
5615 /* Resolve a call to a type-bound subroutine.  */
5616
5617 static gfc_try
5618 resolve_typebound_call (gfc_code* c, const char **name)
5619 {
5620   gfc_actual_arglist* newactual;
5621   gfc_symtree* target;
5622
5623   /* Check that's really a SUBROUTINE.  */
5624   if (!c->expr1->value.compcall.tbp->subroutine)
5625     {
5626       gfc_error ("'%s' at %L should be a SUBROUTINE",
5627                  c->expr1->value.compcall.name, &c->loc);
5628       return FAILURE;
5629     }
5630
5631   if (check_typebound_baseobject (c->expr1) == FAILURE)
5632     return FAILURE;
5633
5634   /* Pass along the name for CLASS methods, where the vtab
5635      procedure pointer component has to be referenced.  */
5636   if (name)
5637     *name = c->expr1->value.compcall.name;
5638
5639   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5640     return FAILURE;
5641
5642   /* Transform into an ordinary EXEC_CALL for now.  */
5643
5644   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5645     return FAILURE;
5646
5647   c->ext.actual = newactual;
5648   c->symtree = target;
5649   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5650
5651   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5652
5653   gfc_free_expr (c->expr1);
5654   c->expr1 = gfc_get_expr ();
5655   c->expr1->expr_type = EXPR_FUNCTION;
5656   c->expr1->symtree = target;
5657   c->expr1->where = c->loc;
5658
5659   return resolve_call (c);
5660 }
5661
5662
5663 /* Resolve a component-call expression.  */
5664 static gfc_try
5665 resolve_compcall (gfc_expr* e, const char **name)
5666 {
5667   gfc_actual_arglist* newactual;
5668   gfc_symtree* target;
5669
5670   /* Check that's really a FUNCTION.  */
5671   if (!e->value.compcall.tbp->function)
5672     {
5673       gfc_error ("'%s' at %L should be a FUNCTION",
5674                  e->value.compcall.name, &e->where);
5675       return FAILURE;
5676     }
5677
5678   /* These must not be assign-calls!  */
5679   gcc_assert (!e->value.compcall.assign);
5680
5681   if (check_typebound_baseobject (e) == FAILURE)
5682     return FAILURE;
5683
5684   /* Pass along the name for CLASS methods, where the vtab
5685      procedure pointer component has to be referenced.  */
5686   if (name)
5687     *name = e->value.compcall.name;
5688
5689   if (resolve_typebound_generic_call (e, name) == FAILURE)
5690     return FAILURE;
5691   gcc_assert (!e->value.compcall.tbp->is_generic);
5692
5693   /* Take the rank from the function's symbol.  */
5694   if (e->value.compcall.tbp->u.specific->n.sym->as)
5695     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5696
5697   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5698      arglist to the TBP's binding target.  */
5699
5700   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5701     return FAILURE;
5702
5703   e->value.function.actual = newactual;
5704   e->value.function.name = NULL;
5705   e->value.function.esym = target->n.sym;
5706   e->value.function.isym = NULL;
5707   e->symtree = target;
5708   e->ts = target->n.sym->ts;
5709   e->expr_type = EXPR_FUNCTION;
5710
5711   /* Resolution is not necessary if this is a class subroutine; this
5712      function only has to identify the specific proc. Resolution of
5713      the call will be done next in resolve_typebound_call.  */
5714   return gfc_resolve_expr (e);
5715 }
5716
5717
5718
5719 /* Resolve a typebound function, or 'method'. First separate all
5720    the non-CLASS references by calling resolve_compcall directly.  */
5721
5722 static gfc_try
5723 resolve_typebound_function (gfc_expr* e)
5724 {
5725   gfc_symbol *declared;
5726   gfc_component *c;
5727   gfc_ref *new_ref;
5728   gfc_ref *class_ref;
5729   gfc_symtree *st;
5730   const char *name;
5731   gfc_typespec ts;
5732   gfc_expr *expr;
5733
5734   st = e->symtree;
5735
5736   /* Deal with typebound operators for CLASS objects.  */
5737   expr = e->value.compcall.base_object;
5738   if (expr && expr->symtree->n.sym->ts.type == BT_CLASS
5739         && e->value.compcall.name)
5740     {
5741       /* Since the typebound operators are generic, we have to ensure
5742          that any delays in resolution are corrected and that the vtab
5743          is present.  */
5744       ts = expr->symtree->n.sym->ts;
5745       declared = ts.u.derived;
5746       c = gfc_find_component (declared, "$vptr", true, true);
5747       if (c->ts.u.derived == NULL)
5748         c->ts.u.derived = gfc_find_derived_vtab (declared);
5749
5750       if (resolve_compcall (e, &name) == FAILURE)
5751         return FAILURE;
5752
5753       /* Use the generic name if it is there.  */
5754       name = name ? name : e->value.function.esym->name;
5755       e->symtree = expr->symtree;
5756       expr->symtree->n.sym->ts.u.derived = declared;
5757       gfc_add_component_ref (e, "$vptr");
5758       gfc_add_component_ref (e, name);
5759       e->value.function.esym = NULL;
5760       return SUCCESS;
5761     }
5762
5763   if (st == NULL)
5764     return resolve_compcall (e, NULL);
5765
5766   if (resolve_ref (e) == FAILURE)
5767     return FAILURE;
5768
5769   /* Get the CLASS declared type.  */
5770   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5771
5772   /* Weed out cases of the ultimate component being a derived type.  */
5773   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5774          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5775     {
5776       gfc_free_ref_list (new_ref);
5777       return resolve_compcall (e, NULL);
5778     }
5779
5780   c = gfc_find_component (declared, "$data", true, true);
5781   declared = c->ts.u.derived;
5782
5783   /* Treat the call as if it is a typebound procedure, in order to roll
5784      out the correct name for the specific function.  */
5785   if (resolve_compcall (e, &name) == FAILURE)
5786     return FAILURE;
5787   ts = e->ts;
5788
5789   /* Then convert the expression to a procedure pointer component call.  */
5790   e->value.function.esym = NULL;
5791   e->symtree = st;
5792
5793   if (new_ref)  
5794     e->ref = new_ref;
5795
5796   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5797   gfc_add_component_ref (e, "$vptr");
5798   gfc_add_component_ref (e, name);
5799
5800   /* Recover the typespec for the expression.  This is really only
5801      necessary for generic procedures, where the additional call
5802      to gfc_add_component_ref seems to throw the collection of the
5803      correct typespec.  */
5804   e->ts = ts;
5805   return SUCCESS;
5806 }
5807
5808 /* Resolve a typebound subroutine, or 'method'. First separate all
5809    the non-CLASS references by calling resolve_typebound_call
5810    directly.  */
5811
5812 static gfc_try
5813 resolve_typebound_subroutine (gfc_code *code)
5814 {
5815   gfc_symbol *declared;
5816   gfc_component *c;
5817   gfc_ref *new_ref;
5818   gfc_ref *class_ref;
5819   gfc_symtree *st;
5820   const char *name;
5821   gfc_typespec ts;
5822   gfc_expr *expr;
5823
5824   st = code->expr1->symtree;
5825
5826   /* Deal with typebound operators for CLASS objects.  */
5827   expr = code->expr1->value.compcall.base_object;
5828   if (expr && expr->symtree->n.sym->ts.type == BT_CLASS
5829         && code->expr1->value.compcall.name)
5830     {
5831       /* Since the typebound operators are generic, we have to ensure
5832          that any delays in resolution are corrected and that the vtab
5833          is present.  */
5834       ts = expr->symtree->n.sym->ts;
5835       declared = ts.u.derived;
5836       c = gfc_find_component (declared, "$vptr", true, true);
5837       if (c->ts.u.derived == NULL)
5838         c->ts.u.derived = gfc_find_derived_vtab (declared);
5839
5840       if (resolve_typebound_call (code, &name) == FAILURE)
5841         return FAILURE;
5842
5843       /* Use the generic name if it is there.  */
5844       name = name ? name : code->expr1->value.function.esym->name;
5845       code->expr1->symtree = expr->symtree;
5846       expr->symtree->n.sym->ts.u.derived = declared;
5847       gfc_add_component_ref (code->expr1, "$vptr");
5848       gfc_add_component_ref (code->expr1, name);
5849       code->expr1->value.function.esym = NULL;
5850       return SUCCESS;
5851     }
5852
5853   if (st == NULL)
5854     return resolve_typebound_call (code, NULL);
5855
5856   if (resolve_ref (code->expr1) == FAILURE)
5857     return FAILURE;
5858
5859   /* Get the CLASS declared type.  */
5860   get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5861
5862   /* Weed out cases of the ultimate component being a derived type.  */
5863   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5864          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5865     {
5866       gfc_free_ref_list (new_ref);
5867       return resolve_typebound_call (code, NULL);
5868     }
5869
5870   if (resolve_typebound_call (code, &name) == FAILURE)
5871     return FAILURE;
5872   ts = code->expr1->ts;
5873
5874   /* Then convert the expression to a procedure pointer component call.  */
5875   code->expr1->value.function.esym = NULL;
5876   code->expr1->symtree = st;
5877
5878   if (new_ref)
5879     code->expr1->ref = new_ref;
5880
5881   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5882   gfc_add_component_ref (code->expr1, "$vptr");
5883   gfc_add_component_ref (code->expr1, name);
5884
5885   /* Recover the typespec for the expression.  This is really only
5886      necessary for generic procedures, where the additional call
5887      to gfc_add_component_ref seems to throw the collection of the
5888      correct typespec.  */
5889   code->expr1->ts = ts;
5890   return SUCCESS;
5891 }
5892
5893
5894 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5895
5896 static gfc_try
5897 resolve_ppc_call (gfc_code* c)
5898 {
5899   gfc_component *comp;
5900   bool b;
5901
5902   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5903   gcc_assert (b);
5904
5905   c->resolved_sym = c->expr1->symtree->n.sym;
5906   c->expr1->expr_type = EXPR_VARIABLE;
5907
5908   if (!comp->attr.subroutine)
5909     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5910
5911   if (resolve_ref (c->expr1) == FAILURE)
5912     return FAILURE;
5913
5914   if (update_ppc_arglist (c->expr1) == FAILURE)
5915     return FAILURE;
5916
5917   c->ext.actual = c->expr1->value.compcall.actual;
5918
5919   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5920                               comp->formal == NULL) == FAILURE)
5921     return FAILURE;
5922
5923   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5924
5925   return SUCCESS;
5926 }
5927
5928
5929 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5930
5931 static gfc_try
5932 resolve_expr_ppc (gfc_expr* e)
5933 {
5934   gfc_component *comp;
5935   bool b;
5936
5937   b = gfc_is_proc_ptr_comp (e, &comp);
5938   gcc_assert (b);
5939
5940   /* Convert to EXPR_FUNCTION.  */
5941   e->expr_type = EXPR_FUNCTION;
5942   e->value.function.isym = NULL;
5943   e->value.function.actual = e->value.compcall.actual;
5944   e->ts = comp->ts;
5945   if (comp->as != NULL)
5946     e->rank = comp->as->rank;
5947
5948   if (!comp->attr.function)
5949     gfc_add_function (&comp->attr, comp->name, &e->where);
5950
5951   if (resolve_ref (e) == FAILURE)
5952     return FAILURE;
5953
5954   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
5955                               comp->formal == NULL) == FAILURE)
5956     return FAILURE;
5957
5958   if (update_ppc_arglist (e) == FAILURE)
5959     return FAILURE;
5960
5961   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
5962
5963   return SUCCESS;
5964 }
5965
5966
5967 static bool
5968 gfc_is_expandable_expr (gfc_expr *e)
5969 {
5970   gfc_constructor *con;
5971
5972   if (e->expr_type == EXPR_ARRAY)
5973     {
5974       /* Traverse the constructor looking for variables that are flavor
5975          parameter.  Parameters must be expanded since they are fully used at
5976          compile time.  */
5977       con = gfc_constructor_first (e->value.constructor);
5978       for (; con; con = gfc_constructor_next (con))
5979         {
5980           if (con->expr->expr_type == EXPR_VARIABLE
5981               && con->expr->symtree
5982               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
5983               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
5984             return true;
5985           if (con->expr->expr_type == EXPR_ARRAY
5986               && gfc_is_expandable_expr (con->expr))
5987             return true;
5988         }
5989     }
5990
5991   return false;
5992 }
5993
5994 /* Resolve an expression.  That is, make sure that types of operands agree
5995    with their operators, intrinsic operators are converted to function calls
5996    for overloaded types and unresolved function references are resolved.  */
5997
5998 gfc_try
5999 gfc_resolve_expr (gfc_expr *e)
6000 {
6001   gfc_try t;
6002   bool inquiry_save;
6003
6004   if (e == NULL)
6005     return SUCCESS;
6006
6007   /* inquiry_argument only applies to variables.  */
6008   inquiry_save = inquiry_argument;
6009   if (e->expr_type != EXPR_VARIABLE)
6010     inquiry_argument = false;
6011
6012   switch (e->expr_type)
6013     {
6014     case EXPR_OP:
6015       t = resolve_operator (e);
6016       break;
6017
6018     case EXPR_FUNCTION:
6019     case EXPR_VARIABLE:
6020
6021       if (check_host_association (e))
6022         t = resolve_function (e);
6023       else
6024         {
6025           t = resolve_variable (e);
6026           if (t == SUCCESS)
6027             expression_rank (e);
6028         }
6029
6030       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6031           && e->ref->type != REF_SUBSTRING)
6032         gfc_resolve_substring_charlen (e);
6033
6034       break;
6035
6036     case EXPR_COMPCALL:
6037       t = resolve_typebound_function (e);
6038       break;
6039
6040     case EXPR_SUBSTRING:
6041       t = resolve_ref (e);
6042       break;
6043
6044     case EXPR_CONSTANT:
6045     case EXPR_NULL:
6046       t = SUCCESS;
6047       break;
6048
6049     case EXPR_PPC:
6050       t = resolve_expr_ppc (e);
6051       break;
6052
6053     case EXPR_ARRAY:
6054       t = FAILURE;
6055       if (resolve_ref (e) == FAILURE)
6056         break;
6057
6058       t = gfc_resolve_array_constructor (e);
6059       /* Also try to expand a constructor.  */
6060       if (t == SUCCESS)
6061         {
6062           expression_rank (e);
6063           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6064             gfc_expand_constructor (e, false);
6065         }
6066
6067       /* This provides the opportunity for the length of constructors with
6068          character valued function elements to propagate the string length
6069          to the expression.  */
6070       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6071         {
6072           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6073              here rather then add a duplicate test for it above.  */ 
6074           gfc_expand_constructor (e, false);
6075           t = gfc_resolve_character_array_constructor (e);
6076         }
6077
6078       break;
6079
6080     case EXPR_STRUCTURE:
6081       t = resolve_ref (e);
6082       if (t == FAILURE)
6083         break;
6084
6085       t = resolve_structure_cons (e, 0);
6086       if (t == FAILURE)
6087         break;
6088
6089       t = gfc_simplify_expr (e, 0);
6090       break;
6091
6092     default:
6093       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6094     }
6095
6096   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6097     fixup_charlen (e);
6098
6099   inquiry_argument = inquiry_save;
6100
6101   return t;
6102 }
6103
6104
6105 /* Resolve an expression from an iterator.  They must be scalar and have
6106    INTEGER or (optionally) REAL type.  */
6107
6108 static gfc_try
6109 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6110                            const char *name_msgid)
6111 {
6112   if (gfc_resolve_expr (expr) == FAILURE)
6113     return FAILURE;
6114
6115   if (expr->rank != 0)
6116     {
6117       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6118       return FAILURE;
6119     }
6120
6121   if (expr->ts.type != BT_INTEGER)
6122     {
6123       if (expr->ts.type == BT_REAL)
6124         {
6125           if (real_ok)
6126             return gfc_notify_std (GFC_STD_F95_DEL,
6127                                    "Deleted feature: %s at %L must be integer",
6128                                    _(name_msgid), &expr->where);
6129           else
6130             {
6131               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6132                          &expr->where);
6133               return FAILURE;
6134             }
6135         }
6136       else
6137         {
6138           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6139           return FAILURE;
6140         }
6141     }
6142   return SUCCESS;
6143 }
6144
6145
6146 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6147    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6148
6149 gfc_try
6150 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6151 {
6152   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6153       == FAILURE)
6154     return FAILURE;
6155
6156   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
6157     {
6158       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
6159                  &iter->var->where);
6160       return FAILURE;
6161     }
6162
6163   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6164                                  "Start expression in DO loop") == FAILURE)
6165     return FAILURE;
6166
6167   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6168                                  "End expression in DO loop") == FAILURE)
6169     return FAILURE;
6170
6171   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6172                                  "Step expression in DO loop") == FAILURE)
6173     return FAILURE;
6174
6175   if (iter->step->expr_type == EXPR_CONSTANT)
6176     {
6177       if ((iter->step->ts.type == BT_INTEGER
6178            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6179           || (iter->step->ts.type == BT_REAL
6180               && mpfr_sgn (iter->step->value.real) == 0))
6181         {
6182           gfc_error ("Step expression in DO loop at %L cannot be zero",
6183                      &iter->step->where);
6184           return FAILURE;
6185         }
6186     }
6187
6188   /* Convert start, end, and step to the same type as var.  */
6189   if (iter->start->ts.kind != iter->var->ts.kind
6190       || iter->start->ts.type != iter->var->ts.type)
6191     gfc_convert_type (iter->start, &iter->var->ts, 2);
6192
6193   if (iter->end->ts.kind != iter->var->ts.kind
6194       || iter->end->ts.type != iter->var->ts.type)
6195     gfc_convert_type (iter->end, &iter->var->ts, 2);
6196
6197   if (iter->step->ts.kind != iter->var->ts.kind
6198       || iter->step->ts.type != iter->var->ts.type)
6199     gfc_convert_type (iter->step, &iter->var->ts, 2);
6200
6201   if (iter->start->expr_type == EXPR_CONSTANT
6202       && iter->end->expr_type == EXPR_CONSTANT
6203       && iter->step->expr_type == EXPR_CONSTANT)
6204     {
6205       int sgn, cmp;
6206       if (iter->start->ts.type == BT_INTEGER)
6207         {
6208           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6209           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6210         }
6211       else
6212         {
6213           sgn = mpfr_sgn (iter->step->value.real);
6214           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6215         }
6216       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6217         gfc_warning ("DO loop at %L will be executed zero times",
6218                      &iter->step->where);
6219     }
6220
6221   return SUCCESS;
6222 }
6223
6224
6225 /* Traversal function for find_forall_index.  f == 2 signals that
6226    that variable itself is not to be checked - only the references.  */
6227
6228 static bool
6229 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6230 {
6231   if (expr->expr_type != EXPR_VARIABLE)
6232     return false;
6233   
6234   /* A scalar assignment  */
6235   if (!expr->ref || *f == 1)
6236     {
6237       if (expr->symtree->n.sym == sym)
6238         return true;
6239       else
6240         return false;
6241     }
6242
6243   if (*f == 2)
6244     *f = 1;
6245   return false;
6246 }
6247
6248
6249 /* Check whether the FORALL index appears in the expression or not.
6250    Returns SUCCESS if SYM is found in EXPR.  */
6251
6252 gfc_try
6253 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6254 {
6255   if (gfc_traverse_expr (expr, sym, forall_index, f))
6256     return SUCCESS;
6257   else
6258     return FAILURE;
6259 }
6260
6261
6262 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6263    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6264    INTEGERs, and if stride is a constant it must be nonzero.
6265    Furthermore "A subscript or stride in a forall-triplet-spec shall
6266    not contain a reference to any index-name in the
6267    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6268
6269 static void
6270 resolve_forall_iterators (gfc_forall_iterator *it)
6271 {
6272   gfc_forall_iterator *iter, *iter2;
6273
6274   for (iter = it; iter; iter = iter->next)
6275     {
6276       if (gfc_resolve_expr (iter->var) == SUCCESS
6277           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6278         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6279                    &iter->var->where);
6280
6281       if (gfc_resolve_expr (iter->start) == SUCCESS
6282           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6283         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6284                    &iter->start->where);
6285       if (iter->var->ts.kind != iter->start->ts.kind)
6286         gfc_convert_type (iter->start, &iter->var->ts, 2);
6287
6288       if (gfc_resolve_expr (iter->end) == SUCCESS
6289           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6290         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6291                    &iter->end->where);
6292       if (iter->var->ts.kind != iter->end->ts.kind)
6293         gfc_convert_type (iter->end, &iter->var->ts, 2);
6294
6295       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6296         {
6297           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6298             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6299                        &iter->stride->where, "INTEGER");
6300
6301           if (iter->stride->expr_type == EXPR_CONSTANT
6302               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6303             gfc_error ("FORALL stride expression at %L cannot be zero",
6304                        &iter->stride->where);
6305         }
6306       if (iter->var->ts.kind != iter->stride->ts.kind)
6307         gfc_convert_type (iter->stride, &iter->var->ts, 2);
6308     }
6309
6310   for (iter = it; iter; iter = iter->next)
6311     for (iter2 = iter; iter2; iter2 = iter2->next)
6312       {
6313         if (find_forall_index (iter2->start,
6314                                iter->var->symtree->n.sym, 0) == SUCCESS
6315             || find_forall_index (iter2->end,
6316                                   iter->var->symtree->n.sym, 0) == SUCCESS
6317             || find_forall_index (iter2->stride,
6318                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6319           gfc_error ("FORALL index '%s' may not appear in triplet "
6320                      "specification at %L", iter->var->symtree->name,
6321                      &iter2->start->where);
6322       }
6323 }
6324
6325
6326 /* Given a pointer to a symbol that is a derived type, see if it's
6327    inaccessible, i.e. if it's defined in another module and the components are
6328    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6329    inaccessible components are found, nonzero otherwise.  */
6330
6331 static int
6332 derived_inaccessible (gfc_symbol *sym)
6333 {
6334   gfc_component *c;
6335
6336   if (sym->attr.use_assoc && sym->attr.private_comp)
6337     return 1;
6338
6339   for (c = sym->components; c; c = c->next)
6340     {
6341         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6342           return 1;
6343     }
6344
6345   return 0;
6346 }
6347
6348
6349 /* Resolve the argument of a deallocate expression.  The expression must be
6350    a pointer or a full array.  */
6351
6352 static gfc_try
6353 resolve_deallocate_expr (gfc_expr *e)
6354 {
6355   symbol_attribute attr;
6356   int allocatable, pointer, check_intent_in;
6357   gfc_ref *ref;
6358   gfc_symbol *sym;
6359   gfc_component *c;
6360
6361   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6362   check_intent_in = 1;
6363
6364   if (gfc_resolve_expr (e) == FAILURE)
6365     return FAILURE;
6366
6367   if (e->expr_type != EXPR_VARIABLE)
6368     goto bad;
6369
6370   sym = e->symtree->n.sym;
6371
6372   if (sym->ts.type == BT_CLASS)
6373     {
6374       allocatable = CLASS_DATA (sym)->attr.allocatable;
6375       pointer = CLASS_DATA (sym)->attr.class_pointer;
6376     }
6377   else
6378     {
6379       allocatable = sym->attr.allocatable;
6380       pointer = sym->attr.pointer;
6381     }
6382   for (ref = e->ref; ref; ref = ref->next)
6383     {
6384       if (pointer)
6385         check_intent_in = 0;
6386
6387       switch (ref->type)
6388         {
6389         case REF_ARRAY:
6390           if (ref->u.ar.type != AR_FULL)
6391             allocatable = 0;
6392           break;
6393
6394         case REF_COMPONENT:
6395           c = ref->u.c.component;
6396           if (c->ts.type == BT_CLASS)
6397             {
6398               allocatable = CLASS_DATA (c)->attr.allocatable;
6399               pointer = CLASS_DATA (c)->attr.class_pointer;
6400             }
6401           else
6402             {
6403               allocatable = c->attr.allocatable;
6404               pointer = c->attr.pointer;
6405             }
6406           break;
6407
6408         case REF_SUBSTRING:
6409           allocatable = 0;
6410           break;
6411         }
6412     }
6413
6414   attr = gfc_expr_attr (e);
6415
6416   if (allocatable == 0 && attr.pointer == 0)
6417     {
6418     bad:
6419       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6420                  &e->where);
6421       return FAILURE;
6422     }
6423
6424   if (check_intent_in && sym->attr.intent == INTENT_IN)
6425     {
6426       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
6427                  sym->name, &e->where);
6428       return FAILURE;
6429     }
6430
6431   if (e->ts.type == BT_CLASS)
6432     {
6433       /* Only deallocate the DATA component.  */
6434       gfc_add_component_ref (e, "$data");
6435     }
6436
6437   return SUCCESS;
6438 }
6439
6440
6441 /* Returns true if the expression e contains a reference to the symbol sym.  */
6442 static bool
6443 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6444 {
6445   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6446     return true;
6447
6448   return false;
6449 }
6450
6451 bool
6452 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6453 {
6454   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6455 }
6456
6457
6458 /* Given the expression node e for an allocatable/pointer of derived type to be
6459    allocated, get the expression node to be initialized afterwards (needed for
6460    derived types with default initializers, and derived types with allocatable
6461    components that need nullification.)  */
6462
6463 gfc_expr *
6464 gfc_expr_to_initialize (gfc_expr *e)
6465 {
6466   gfc_expr *result;
6467   gfc_ref *ref;
6468   int i;
6469
6470   result = gfc_copy_expr (e);
6471
6472   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6473   for (ref = result->ref; ref; ref = ref->next)
6474     if (ref->type == REF_ARRAY && ref->next == NULL)
6475       {
6476         ref->u.ar.type = AR_FULL;
6477
6478         for (i = 0; i < ref->u.ar.dimen; i++)
6479           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6480
6481         result->rank = ref->u.ar.dimen;
6482         break;
6483       }
6484
6485   return result;
6486 }
6487
6488
6489 /* Used in resolve_allocate_expr to check that a allocation-object and
6490    a source-expr are conformable.  This does not catch all possible 
6491    cases; in particular a runtime checking is needed.  */
6492
6493 static gfc_try
6494 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6495 {
6496   gfc_ref *tail;
6497   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6498   
6499   /* First compare rank.  */
6500   if (tail && e1->rank != tail->u.ar.as->rank)
6501     {
6502       gfc_error ("Source-expr at %L must be scalar or have the "
6503                  "same rank as the allocate-object at %L",
6504                  &e1->where, &e2->where);
6505       return FAILURE;
6506     }
6507
6508   if (e1->shape)
6509     {
6510       int i;
6511       mpz_t s;
6512
6513       mpz_init (s);
6514
6515       for (i = 0; i < e1->rank; i++)
6516         {
6517           if (tail->u.ar.end[i])
6518             {
6519               mpz_set (s, tail->u.ar.end[i]->value.integer);
6520               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6521               mpz_add_ui (s, s, 1);
6522             }
6523           else
6524             {
6525               mpz_set (s, tail->u.ar.start[i]->value.integer);
6526             }
6527
6528           if (mpz_cmp (e1->shape[i], s) != 0)
6529             {
6530               gfc_error ("Source-expr at %L and allocate-object at %L must "
6531                          "have the same shape", &e1->where, &e2->where);
6532               mpz_clear (s);
6533               return FAILURE;
6534             }
6535         }
6536
6537       mpz_clear (s);
6538     }
6539
6540   return SUCCESS;
6541 }
6542
6543
6544 /* Resolve the expression in an ALLOCATE statement, doing the additional
6545    checks to see whether the expression is OK or not.  The expression must
6546    have a trailing array reference that gives the size of the array.  */
6547
6548 static gfc_try
6549 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6550 {
6551   int i, pointer, allocatable, dimension, check_intent_in, is_abstract;
6552   int codimension;
6553   symbol_attribute attr;
6554   gfc_ref *ref, *ref2;
6555   gfc_array_ref *ar;
6556   gfc_symbol *sym = NULL;
6557   gfc_alloc *a;
6558   gfc_component *c;
6559
6560   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6561   check_intent_in = 1;
6562
6563   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6564      checking of coarrays.  */
6565   for (ref = e->ref; ref; ref = ref->next)
6566     if (ref->next == NULL)
6567       break;
6568
6569   if (ref && ref->type == REF_ARRAY)
6570     ref->u.ar.in_allocate = true;
6571
6572   if (gfc_resolve_expr (e) == FAILURE)
6573     goto failure;
6574
6575   /* Make sure the expression is allocatable or a pointer.  If it is
6576      pointer, the next-to-last reference must be a pointer.  */
6577
6578   ref2 = NULL;
6579   if (e->symtree)
6580     sym = e->symtree->n.sym;
6581
6582   /* Check whether ultimate component is abstract and CLASS.  */
6583   is_abstract = 0;
6584
6585   if (e->expr_type != EXPR_VARIABLE)
6586     {
6587       allocatable = 0;
6588       attr = gfc_expr_attr (e);
6589       pointer = attr.pointer;
6590       dimension = attr.dimension;
6591       codimension = attr.codimension;
6592     }
6593   else
6594     {
6595       if (sym->ts.type == BT_CLASS)
6596         {
6597           allocatable = CLASS_DATA (sym)->attr.allocatable;
6598           pointer = CLASS_DATA (sym)->attr.class_pointer;
6599           dimension = CLASS_DATA (sym)->attr.dimension;
6600           codimension = CLASS_DATA (sym)->attr.codimension;
6601           is_abstract = CLASS_DATA (sym)->attr.abstract;
6602         }
6603       else
6604         {
6605           allocatable = sym->attr.allocatable;
6606           pointer = sym->attr.pointer;
6607           dimension = sym->attr.dimension;
6608           codimension = sym->attr.codimension;
6609         }
6610
6611       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6612         {
6613           if (pointer)
6614             check_intent_in = 0;
6615
6616           switch (ref->type)
6617             {
6618               case REF_ARRAY:
6619                 if (ref->next != NULL)
6620                   pointer = 0;
6621                 break;
6622
6623               case REF_COMPONENT:
6624                 /* F2008, C644.  */
6625                 if (gfc_is_coindexed (e))
6626                   {
6627                     gfc_error ("Coindexed allocatable object at %L",
6628                                &e->where);
6629                     goto failure;
6630                   }
6631
6632                 c = ref->u.c.component;
6633                 if (c->ts.type == BT_CLASS)
6634                   {
6635                     allocatable = CLASS_DATA (c)->attr.allocatable;
6636                     pointer = CLASS_DATA (c)->attr.class_pointer;
6637                     dimension = CLASS_DATA (c)->attr.dimension;
6638                     codimension = CLASS_DATA (c)->attr.codimension;
6639                     is_abstract = CLASS_DATA (c)->attr.abstract;
6640                   }
6641                 else
6642                   {
6643                     allocatable = c->attr.allocatable;
6644                     pointer = c->attr.pointer;
6645                     dimension = c->attr.dimension;
6646                     codimension = c->attr.codimension;
6647                     is_abstract = c->attr.abstract;
6648                   }
6649                 break;
6650
6651               case REF_SUBSTRING:
6652                 allocatable = 0;
6653                 pointer = 0;
6654                 break;
6655             }
6656         }
6657     }
6658
6659   if (allocatable == 0 && pointer == 0)
6660     {
6661       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6662                  &e->where);
6663       goto failure;
6664     }
6665
6666   /* Some checks for the SOURCE tag.  */
6667   if (code->expr3)
6668     {
6669       /* Check F03:C631.  */
6670       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6671         {
6672           gfc_error ("Type of entity at %L is type incompatible with "
6673                       "source-expr at %L", &e->where, &code->expr3->where);
6674           goto failure;
6675         }
6676
6677       /* Check F03:C632 and restriction following Note 6.18.  */
6678       if (code->expr3->rank > 0
6679           && conformable_arrays (code->expr3, e) == FAILURE)
6680         goto failure;
6681
6682       /* Check F03:C633.  */
6683       if (code->expr3->ts.kind != e->ts.kind)
6684         {
6685           gfc_error ("The allocate-object at %L and the source-expr at %L "
6686                       "shall have the same kind type parameter",
6687                       &e->where, &code->expr3->where);
6688           goto failure;
6689         }
6690     }
6691
6692   /* Check F08:C629.  */
6693   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6694       && !code->expr3)
6695     {
6696       gcc_assert (e->ts.type == BT_CLASS);
6697       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6698                  "type-spec or source-expr", sym->name, &e->where);
6699       goto failure;
6700     }
6701
6702   if (check_intent_in && sym->attr.intent == INTENT_IN)
6703     {
6704       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
6705                  sym->name, &e->where);
6706       goto failure;
6707     }
6708     
6709   if (!code->expr3 || code->expr3->mold)
6710     {
6711       /* Add default initializer for those derived types that need them.  */
6712       gfc_expr *init_e = NULL;
6713       gfc_typespec ts;
6714
6715       if (code->ext.alloc.ts.type == BT_DERIVED)
6716         ts = code->ext.alloc.ts;
6717       else if (code->expr3)
6718         ts = code->expr3->ts;
6719       else
6720         ts = e->ts;
6721
6722       if (ts.type == BT_DERIVED)
6723         init_e = gfc_default_initializer (&ts);
6724       /* FIXME: Use default init of dynamic type (cf. PR 44541).  */
6725       else if (e->ts.type == BT_CLASS)
6726         init_e = gfc_default_initializer (&ts.u.derived->components->ts);
6727
6728       if (init_e)
6729         {
6730           gfc_code *init_st = gfc_get_code ();
6731           init_st->loc = code->loc;
6732           init_st->op = EXEC_INIT_ASSIGN;
6733           init_st->expr1 = gfc_expr_to_initialize (e);
6734           init_st->expr2 = init_e;
6735           init_st->next = code->next;
6736           code->next = init_st;
6737         }
6738     }
6739
6740   if (e->ts.type == BT_CLASS)
6741     {
6742       /* Make sure the vtab symbol is present when
6743          the module variables are generated.  */
6744       gfc_typespec ts = e->ts;
6745       if (code->expr3)
6746         ts = code->expr3->ts;
6747       else if (code->ext.alloc.ts.type == BT_DERIVED)
6748         ts = code->ext.alloc.ts;
6749       gfc_find_derived_vtab (ts.u.derived);
6750     }
6751
6752   if (pointer || (dimension == 0 && codimension == 0))
6753     goto success;
6754
6755   /* Make sure the next-to-last reference node is an array specification.  */
6756
6757   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6758       || (dimension && ref2->u.ar.dimen == 0))
6759     {
6760       gfc_error ("Array specification required in ALLOCATE statement "
6761                  "at %L", &e->where);
6762       goto failure;
6763     }
6764
6765   /* Make sure that the array section reference makes sense in the
6766     context of an ALLOCATE specification.  */
6767
6768   ar = &ref2->u.ar;
6769
6770   if (codimension && ar->codimen == 0)
6771     {
6772       gfc_error ("Coarray specification required in ALLOCATE statement "
6773                  "at %L", &e->where);
6774       goto failure;
6775     }
6776
6777   for (i = 0; i < ar->dimen; i++)
6778     {
6779       if (ref2->u.ar.type == AR_ELEMENT)
6780         goto check_symbols;
6781
6782       switch (ar->dimen_type[i])
6783         {
6784         case DIMEN_ELEMENT:
6785           break;
6786
6787         case DIMEN_RANGE:
6788           if (ar->start[i] != NULL
6789               && ar->end[i] != NULL
6790               && ar->stride[i] == NULL)
6791             break;
6792
6793           /* Fall Through...  */
6794
6795         case DIMEN_UNKNOWN:
6796         case DIMEN_VECTOR:
6797         case DIMEN_STAR:
6798           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6799                      &e->where);
6800           goto failure;
6801         }
6802
6803 check_symbols:
6804       for (a = code->ext.alloc.list; a; a = a->next)
6805         {
6806           sym = a->expr->symtree->n.sym;
6807
6808           /* TODO - check derived type components.  */
6809           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6810             continue;
6811
6812           if ((ar->start[i] != NULL
6813                && gfc_find_sym_in_expr (sym, ar->start[i]))
6814               || (ar->end[i] != NULL
6815                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6816             {
6817               gfc_error ("'%s' must not appear in the array specification at "
6818                          "%L in the same ALLOCATE statement where it is "
6819                          "itself allocated", sym->name, &ar->where);
6820               goto failure;
6821             }
6822         }
6823     }
6824
6825   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6826     {
6827       if (ar->dimen_type[i] == DIMEN_ELEMENT
6828           || ar->dimen_type[i] == DIMEN_RANGE)
6829         {
6830           if (i == (ar->dimen + ar->codimen - 1))
6831             {
6832               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6833                          "statement at %L", &e->where);
6834               goto failure;
6835             }
6836           break;
6837         }
6838
6839       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6840           && ar->stride[i] == NULL)
6841         break;
6842
6843       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6844                  &e->where);
6845       goto failure;
6846     }
6847
6848   if (codimension && ar->as->rank == 0)
6849     {
6850       gfc_error ("Sorry, allocatable scalar coarrays are not yet supported "
6851                  "at %L", &e->where);
6852       goto failure;
6853     }
6854
6855 success:
6856   return SUCCESS;
6857
6858 failure:
6859   return FAILURE;
6860 }
6861
6862 static void
6863 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6864 {
6865   gfc_expr *stat, *errmsg, *pe, *qe;
6866   gfc_alloc *a, *p, *q;
6867
6868   stat = code->expr1 ? code->expr1 : NULL;
6869
6870   errmsg = code->expr2 ? code->expr2 : NULL;
6871
6872   /* Check the stat variable.  */
6873   if (stat)
6874     {
6875       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
6876         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
6877                    stat->symtree->n.sym->name, &stat->where);
6878
6879       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
6880         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
6881                    &stat->where);
6882
6883       if ((stat->ts.type != BT_INTEGER
6884            && !(stat->ref && (stat->ref->type == REF_ARRAY
6885                               || stat->ref->type == REF_COMPONENT)))
6886           || stat->rank > 0)
6887         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6888                    "variable", &stat->where);
6889
6890       for (p = code->ext.alloc.list; p; p = p->next)
6891         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6892           {
6893             gfc_ref *ref1, *ref2;
6894             bool found = true;
6895
6896             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
6897                  ref1 = ref1->next, ref2 = ref2->next)
6898               {
6899                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
6900                   continue;
6901                 if (ref1->u.c.component->name != ref2->u.c.component->name)
6902                   {
6903                     found = false;
6904                     break;
6905                   }
6906               }
6907
6908             if (found)
6909               {
6910                 gfc_error ("Stat-variable at %L shall not be %sd within "
6911                            "the same %s statement", &stat->where, fcn, fcn);
6912                 break;
6913               }
6914           }
6915     }
6916
6917   /* Check the errmsg variable.  */
6918   if (errmsg)
6919     {
6920       if (!stat)
6921         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6922                      &errmsg->where);
6923
6924       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
6925         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
6926                    errmsg->symtree->n.sym->name, &errmsg->where);
6927
6928       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
6929         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
6930                    &errmsg->where);
6931
6932       if ((errmsg->ts.type != BT_CHARACTER
6933            && !(errmsg->ref
6934                 && (errmsg->ref->type == REF_ARRAY
6935                     || errmsg->ref->type == REF_COMPONENT)))
6936           || errmsg->rank > 0 )
6937         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6938                    "variable", &errmsg->where);
6939
6940       for (p = code->ext.alloc.list; p; p = p->next)
6941         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6942           {
6943             gfc_ref *ref1, *ref2;
6944             bool found = true;
6945
6946             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
6947                  ref1 = ref1->next, ref2 = ref2->next)
6948               {
6949                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
6950                   continue;
6951                 if (ref1->u.c.component->name != ref2->u.c.component->name)
6952                   {
6953                     found = false;
6954                     break;
6955                   }
6956               }
6957
6958             if (found)
6959               {
6960                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
6961                            "the same %s statement", &errmsg->where, fcn, fcn);
6962                 break;
6963               }
6964           }
6965     }
6966
6967   /* Check that an allocate-object appears only once in the statement.  
6968      FIXME: Checking derived types is disabled.  */
6969   for (p = code->ext.alloc.list; p; p = p->next)
6970     {
6971       pe = p->expr;
6972       if ((pe->ref && pe->ref->type != REF_COMPONENT)
6973            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
6974         {
6975           for (q = p->next; q; q = q->next)
6976             {
6977               qe = q->expr;
6978               if ((qe->ref && qe->ref->type != REF_COMPONENT)
6979                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
6980                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
6981                 gfc_error ("Allocate-object at %L also appears at %L",
6982                            &pe->where, &qe->where);
6983             }
6984         }
6985     }
6986
6987   if (strcmp (fcn, "ALLOCATE") == 0)
6988     {
6989       for (a = code->ext.alloc.list; a; a = a->next)
6990         resolve_allocate_expr (a->expr, code);
6991     }
6992   else
6993     {
6994       for (a = code->ext.alloc.list; a; a = a->next)
6995         resolve_deallocate_expr (a->expr);
6996     }
6997 }
6998
6999
7000 /************ SELECT CASE resolution subroutines ************/
7001
7002 /* Callback function for our mergesort variant.  Determines interval
7003    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7004    op1 > op2.  Assumes we're not dealing with the default case.  
7005    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7006    There are nine situations to check.  */
7007
7008 static int
7009 compare_cases (const gfc_case *op1, const gfc_case *op2)
7010 {
7011   int retval;
7012
7013   if (op1->low == NULL) /* op1 = (:L)  */
7014     {
7015       /* op2 = (:N), so overlap.  */
7016       retval = 0;
7017       /* op2 = (M:) or (M:N),  L < M  */
7018       if (op2->low != NULL
7019           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7020         retval = -1;
7021     }
7022   else if (op1->high == NULL) /* op1 = (K:)  */
7023     {
7024       /* op2 = (M:), so overlap.  */
7025       retval = 0;
7026       /* op2 = (:N) or (M:N), K > N  */
7027       if (op2->high != NULL
7028           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7029         retval = 1;
7030     }
7031   else /* op1 = (K:L)  */
7032     {
7033       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7034         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7035                  ? 1 : 0;
7036       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7037         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7038                  ? -1 : 0;
7039       else                      /* op2 = (M:N)  */
7040         {
7041           retval =  0;
7042           /* L < M  */
7043           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7044             retval =  -1;
7045           /* K > N  */
7046           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7047             retval =  1;
7048         }
7049     }
7050
7051   return retval;
7052 }
7053
7054
7055 /* Merge-sort a double linked case list, detecting overlap in the
7056    process.  LIST is the head of the double linked case list before it
7057    is sorted.  Returns the head of the sorted list if we don't see any
7058    overlap, or NULL otherwise.  */
7059
7060 static gfc_case *
7061 check_case_overlap (gfc_case *list)
7062 {
7063   gfc_case *p, *q, *e, *tail;
7064   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7065
7066   /* If the passed list was empty, return immediately.  */
7067   if (!list)
7068     return NULL;
7069
7070   overlap_seen = 0;
7071   insize = 1;
7072
7073   /* Loop unconditionally.  The only exit from this loop is a return
7074      statement, when we've finished sorting the case list.  */
7075   for (;;)
7076     {
7077       p = list;
7078       list = NULL;
7079       tail = NULL;
7080
7081       /* Count the number of merges we do in this pass.  */
7082       nmerges = 0;
7083
7084       /* Loop while there exists a merge to be done.  */
7085       while (p)
7086         {
7087           int i;
7088
7089           /* Count this merge.  */
7090           nmerges++;
7091
7092           /* Cut the list in two pieces by stepping INSIZE places
7093              forward in the list, starting from P.  */
7094           psize = 0;
7095           q = p;
7096           for (i = 0; i < insize; i++)
7097             {
7098               psize++;
7099               q = q->right;
7100               if (!q)
7101                 break;
7102             }
7103           qsize = insize;
7104
7105           /* Now we have two lists.  Merge them!  */
7106           while (psize > 0 || (qsize > 0 && q != NULL))
7107             {
7108               /* See from which the next case to merge comes from.  */
7109               if (psize == 0)
7110                 {
7111                   /* P is empty so the next case must come from Q.  */
7112                   e = q;
7113                   q = q->right;
7114                   qsize--;
7115                 }
7116               else if (qsize == 0 || q == NULL)
7117                 {
7118                   /* Q is empty.  */
7119                   e = p;
7120                   p = p->right;
7121                   psize--;
7122                 }
7123               else
7124                 {
7125                   cmp = compare_cases (p, q);
7126                   if (cmp < 0)
7127                     {
7128                       /* The whole case range for P is less than the
7129                          one for Q.  */
7130                       e = p;
7131                       p = p->right;
7132                       psize--;
7133                     }
7134                   else if (cmp > 0)
7135                     {
7136                       /* The whole case range for Q is greater than
7137                          the case range for P.  */
7138                       e = q;
7139                       q = q->right;
7140                       qsize--;
7141                     }
7142                   else
7143                     {
7144                       /* The cases overlap, or they are the same
7145                          element in the list.  Either way, we must
7146                          issue an error and get the next case from P.  */
7147                       /* FIXME: Sort P and Q by line number.  */
7148                       gfc_error ("CASE label at %L overlaps with CASE "
7149                                  "label at %L", &p->where, &q->where);
7150                       overlap_seen = 1;
7151                       e = p;
7152                       p = p->right;
7153                       psize--;
7154                     }
7155                 }
7156
7157                 /* Add the next element to the merged list.  */
7158               if (tail)
7159                 tail->right = e;
7160               else
7161                 list = e;
7162               e->left = tail;
7163               tail = e;
7164             }
7165
7166           /* P has now stepped INSIZE places along, and so has Q.  So
7167              they're the same.  */
7168           p = q;
7169         }
7170       tail->right = NULL;
7171
7172       /* If we have done only one merge or none at all, we've
7173          finished sorting the cases.  */
7174       if (nmerges <= 1)
7175         {
7176           if (!overlap_seen)
7177             return list;
7178           else
7179             return NULL;
7180         }
7181
7182       /* Otherwise repeat, merging lists twice the size.  */
7183       insize *= 2;
7184     }
7185 }
7186
7187
7188 /* Check to see if an expression is suitable for use in a CASE statement.
7189    Makes sure that all case expressions are scalar constants of the same
7190    type.  Return FAILURE if anything is wrong.  */
7191
7192 static gfc_try
7193 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7194 {
7195   if (e == NULL) return SUCCESS;
7196
7197   if (e->ts.type != case_expr->ts.type)
7198     {
7199       gfc_error ("Expression in CASE statement at %L must be of type %s",
7200                  &e->where, gfc_basic_typename (case_expr->ts.type));
7201       return FAILURE;
7202     }
7203
7204   /* C805 (R808) For a given case-construct, each case-value shall be of
7205      the same type as case-expr.  For character type, length differences
7206      are allowed, but the kind type parameters shall be the same.  */
7207
7208   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7209     {
7210       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7211                  &e->where, case_expr->ts.kind);
7212       return FAILURE;
7213     }
7214
7215   /* Convert the case value kind to that of case expression kind,
7216      if needed */
7217
7218   if (e->ts.kind != case_expr->ts.kind)
7219     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7220
7221   if (e->rank != 0)
7222     {
7223       gfc_error ("Expression in CASE statement at %L must be scalar",
7224                  &e->where);
7225       return FAILURE;
7226     }
7227
7228   return SUCCESS;
7229 }
7230
7231
7232 /* Given a completely parsed select statement, we:
7233
7234      - Validate all expressions and code within the SELECT.
7235      - Make sure that the selection expression is not of the wrong type.
7236      - Make sure that no case ranges overlap.
7237      - Eliminate unreachable cases and unreachable code resulting from
7238        removing case labels.
7239
7240    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7241    they are a hassle for code generation, and to prevent that, we just
7242    cut them out here.  This is not necessary for overlapping cases
7243    because they are illegal and we never even try to generate code.
7244
7245    We have the additional caveat that a SELECT construct could have
7246    been a computed GOTO in the source code. Fortunately we can fairly
7247    easily work around that here: The case_expr for a "real" SELECT CASE
7248    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7249    we have to do is make sure that the case_expr is a scalar integer
7250    expression.  */
7251
7252 static void
7253 resolve_select (gfc_code *code)
7254 {
7255   gfc_code *body;
7256   gfc_expr *case_expr;
7257   gfc_case *cp, *default_case, *tail, *head;
7258   int seen_unreachable;
7259   int seen_logical;
7260   int ncases;
7261   bt type;
7262   gfc_try t;
7263
7264   if (code->expr1 == NULL)
7265     {
7266       /* This was actually a computed GOTO statement.  */
7267       case_expr = code->expr2;
7268       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7269         gfc_error ("Selection expression in computed GOTO statement "
7270                    "at %L must be a scalar integer expression",
7271                    &case_expr->where);
7272
7273       /* Further checking is not necessary because this SELECT was built
7274          by the compiler, so it should always be OK.  Just move the
7275          case_expr from expr2 to expr so that we can handle computed
7276          GOTOs as normal SELECTs from here on.  */
7277       code->expr1 = code->expr2;
7278       code->expr2 = NULL;
7279       return;
7280     }
7281
7282   case_expr = code->expr1;
7283
7284   type = case_expr->ts.type;
7285   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7286     {
7287       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7288                  &case_expr->where, gfc_typename (&case_expr->ts));
7289
7290       /* Punt. Going on here just produce more garbage error messages.  */
7291       return;
7292     }
7293
7294   if (case_expr->rank != 0)
7295     {
7296       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7297                  "expression", &case_expr->where);
7298
7299       /* Punt.  */
7300       return;
7301     }
7302
7303
7304   /* Raise a warning if an INTEGER case value exceeds the range of
7305      the case-expr. Later, all expressions will be promoted to the
7306      largest kind of all case-labels.  */
7307
7308   if (type == BT_INTEGER)
7309     for (body = code->block; body; body = body->block)
7310       for (cp = body->ext.case_list; cp; cp = cp->next)
7311         {
7312           if (cp->low
7313               && gfc_check_integer_range (cp->low->value.integer,
7314                                           case_expr->ts.kind) != ARITH_OK)
7315             gfc_warning ("Expression in CASE statement at %L is "
7316                          "not in the range of %s", &cp->low->where,
7317                          gfc_typename (&case_expr->ts));
7318
7319           if (cp->high
7320               && cp->low != cp->high
7321               && gfc_check_integer_range (cp->high->value.integer,
7322                                           case_expr->ts.kind) != ARITH_OK)
7323             gfc_warning ("Expression in CASE statement at %L is "
7324                          "not in the range of %s", &cp->high->where,
7325                          gfc_typename (&case_expr->ts));
7326         }
7327
7328   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7329      of the SELECT CASE expression and its CASE values.  Walk the lists
7330      of case values, and if we find a mismatch, promote case_expr to
7331      the appropriate kind.  */
7332
7333   if (type == BT_LOGICAL || type == BT_INTEGER)
7334     {
7335       for (body = code->block; body; body = body->block)
7336         {
7337           /* Walk the case label list.  */
7338           for (cp = body->ext.case_list; cp; cp = cp->next)
7339             {
7340               /* Intercept the DEFAULT case.  It does not have a kind.  */
7341               if (cp->low == NULL && cp->high == NULL)
7342                 continue;
7343
7344               /* Unreachable case ranges are discarded, so ignore.  */
7345               if (cp->low != NULL && cp->high != NULL
7346                   && cp->low != cp->high
7347                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7348                 continue;
7349
7350               if (cp->low != NULL
7351                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7352                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7353
7354               if (cp->high != NULL
7355                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7356                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7357             }
7358          }
7359     }
7360
7361   /* Assume there is no DEFAULT case.  */
7362   default_case = NULL;
7363   head = tail = NULL;
7364   ncases = 0;
7365   seen_logical = 0;
7366
7367   for (body = code->block; body; body = body->block)
7368     {
7369       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7370       t = SUCCESS;
7371       seen_unreachable = 0;
7372
7373       /* Walk the case label list, making sure that all case labels
7374          are legal.  */
7375       for (cp = body->ext.case_list; cp; cp = cp->next)
7376         {
7377           /* Count the number of cases in the whole construct.  */
7378           ncases++;
7379
7380           /* Intercept the DEFAULT case.  */
7381           if (cp->low == NULL && cp->high == NULL)
7382             {
7383               if (default_case != NULL)
7384                 {
7385                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7386                              "by a second DEFAULT CASE at %L",
7387                              &default_case->where, &cp->where);
7388                   t = FAILURE;
7389                   break;
7390                 }
7391               else
7392                 {
7393                   default_case = cp;
7394                   continue;
7395                 }
7396             }
7397
7398           /* Deal with single value cases and case ranges.  Errors are
7399              issued from the validation function.  */
7400           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7401               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7402             {
7403               t = FAILURE;
7404               break;
7405             }
7406
7407           if (type == BT_LOGICAL
7408               && ((cp->low == NULL || cp->high == NULL)
7409                   || cp->low != cp->high))
7410             {
7411               gfc_error ("Logical range in CASE statement at %L is not "
7412                          "allowed", &cp->low->where);
7413               t = FAILURE;
7414               break;
7415             }
7416
7417           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7418             {
7419               int value;
7420               value = cp->low->value.logical == 0 ? 2 : 1;
7421               if (value & seen_logical)
7422                 {
7423                   gfc_error ("Constant logical value in CASE statement "
7424                              "is repeated at %L",
7425                              &cp->low->where);
7426                   t = FAILURE;
7427                   break;
7428                 }
7429               seen_logical |= value;
7430             }
7431
7432           if (cp->low != NULL && cp->high != NULL
7433               && cp->low != cp->high
7434               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7435             {
7436               if (gfc_option.warn_surprising)
7437                 gfc_warning ("Range specification at %L can never "
7438                              "be matched", &cp->where);
7439
7440               cp->unreachable = 1;
7441               seen_unreachable = 1;
7442             }
7443           else
7444             {
7445               /* If the case range can be matched, it can also overlap with
7446                  other cases.  To make sure it does not, we put it in a
7447                  double linked list here.  We sort that with a merge sort
7448                  later on to detect any overlapping cases.  */
7449               if (!head)
7450                 {
7451                   head = tail = cp;
7452                   head->right = head->left = NULL;
7453                 }
7454               else
7455                 {
7456                   tail->right = cp;
7457                   tail->right->left = tail;
7458                   tail = tail->right;
7459                   tail->right = NULL;
7460                 }
7461             }
7462         }
7463
7464       /* It there was a failure in the previous case label, give up
7465          for this case label list.  Continue with the next block.  */
7466       if (t == FAILURE)
7467         continue;
7468
7469       /* See if any case labels that are unreachable have been seen.
7470          If so, we eliminate them.  This is a bit of a kludge because
7471          the case lists for a single case statement (label) is a
7472          single forward linked lists.  */
7473       if (seen_unreachable)
7474       {
7475         /* Advance until the first case in the list is reachable.  */
7476         while (body->ext.case_list != NULL
7477                && body->ext.case_list->unreachable)
7478           {
7479             gfc_case *n = body->ext.case_list;
7480             body->ext.case_list = body->ext.case_list->next;
7481             n->next = NULL;
7482             gfc_free_case_list (n);
7483           }
7484
7485         /* Strip all other unreachable cases.  */
7486         if (body->ext.case_list)
7487           {
7488             for (cp = body->ext.case_list; cp->next; cp = cp->next)
7489               {
7490                 if (cp->next->unreachable)
7491                   {
7492                     gfc_case *n = cp->next;
7493                     cp->next = cp->next->next;
7494                     n->next = NULL;
7495                     gfc_free_case_list (n);
7496                   }
7497               }
7498           }
7499       }
7500     }
7501
7502   /* See if there were overlapping cases.  If the check returns NULL,
7503      there was overlap.  In that case we don't do anything.  If head
7504      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7505      then used during code generation for SELECT CASE constructs with
7506      a case expression of a CHARACTER type.  */
7507   if (head)
7508     {
7509       head = check_case_overlap (head);
7510
7511       /* Prepend the default_case if it is there.  */
7512       if (head != NULL && default_case)
7513         {
7514           default_case->left = NULL;
7515           default_case->right = head;
7516           head->left = default_case;
7517         }
7518     }
7519
7520   /* Eliminate dead blocks that may be the result if we've seen
7521      unreachable case labels for a block.  */
7522   for (body = code; body && body->block; body = body->block)
7523     {
7524       if (body->block->ext.case_list == NULL)
7525         {
7526           /* Cut the unreachable block from the code chain.  */
7527           gfc_code *c = body->block;
7528           body->block = c->block;
7529
7530           /* Kill the dead block, but not the blocks below it.  */
7531           c->block = NULL;
7532           gfc_free_statements (c);
7533         }
7534     }
7535
7536   /* More than two cases is legal but insane for logical selects.
7537      Issue a warning for it.  */
7538   if (gfc_option.warn_surprising && type == BT_LOGICAL
7539       && ncases > 2)
7540     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7541                  &code->loc);
7542 }
7543
7544
7545 /* Check if a derived type is extensible.  */
7546
7547 bool
7548 gfc_type_is_extensible (gfc_symbol *sym)
7549 {
7550   return !(sym->attr.is_bind_c || sym->attr.sequence);
7551 }
7552
7553
7554 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7555    correct as well as possibly the array-spec.  */
7556
7557 static void
7558 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7559 {
7560   gfc_expr* target;
7561   bool to_var;
7562
7563   gcc_assert (sym->assoc);
7564   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7565
7566   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7567      case, return.  Resolution will be called later manually again when
7568      this is done.  */
7569   target = sym->assoc->target;
7570   if (!target)
7571     return;
7572   gcc_assert (!sym->assoc->dangling);
7573
7574   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7575     return;
7576
7577   /* For variable targets, we get some attributes from the target.  */
7578   if (target->expr_type == EXPR_VARIABLE)
7579     {
7580       gfc_symbol* tsym;
7581
7582       gcc_assert (target->symtree);
7583       tsym = target->symtree->n.sym;
7584
7585       sym->attr.asynchronous = tsym->attr.asynchronous;
7586       sym->attr.volatile_ = tsym->attr.volatile_;
7587
7588       sym->attr.target = (tsym->attr.target || tsym->attr.pointer);
7589     }
7590
7591   sym->ts = target->ts;
7592   gcc_assert (sym->ts.type != BT_UNKNOWN);
7593
7594   /* See if this is a valid association-to-variable.  */
7595   to_var = (target->expr_type == EXPR_VARIABLE
7596             && !gfc_has_vector_subscript (target));
7597   if (sym->assoc->variable && !to_var)
7598     {
7599       if (target->expr_type == EXPR_VARIABLE)
7600         gfc_error ("'%s' at %L associated to vector-indexed target can not"
7601                    " be used in a variable definition context",
7602                    sym->name, &sym->declared_at);
7603       else
7604         gfc_error ("'%s' at %L associated to expression can not"
7605                    " be used in a variable definition context",
7606                    sym->name, &sym->declared_at);
7607
7608       return;
7609     }
7610   sym->assoc->variable = to_var;
7611
7612   /* Finally resolve if this is an array or not.  */
7613   if (sym->attr.dimension && target->rank == 0)
7614     {
7615       gfc_error ("Associate-name '%s' at %L is used as array",
7616                  sym->name, &sym->declared_at);
7617       sym->attr.dimension = 0;
7618       return;
7619     }
7620   if (target->rank > 0)
7621     sym->attr.dimension = 1;
7622
7623   if (sym->attr.dimension)
7624     {
7625       sym->as = gfc_get_array_spec ();
7626       sym->as->rank = target->rank;
7627       sym->as->type = AS_DEFERRED;
7628
7629       /* Target must not be coindexed, thus the associate-variable
7630          has no corank.  */
7631       sym->as->corank = 0;
7632     }
7633 }
7634
7635
7636 /* Resolve a SELECT TYPE statement.  */
7637
7638 static void
7639 resolve_select_type (gfc_code *code)
7640 {
7641   gfc_symbol *selector_type;
7642   gfc_code *body, *new_st, *if_st, *tail;
7643   gfc_code *class_is = NULL, *default_case = NULL;
7644   gfc_case *c;
7645   gfc_symtree *st;
7646   char name[GFC_MAX_SYMBOL_LEN];
7647   gfc_namespace *ns;
7648   int error = 0;
7649
7650   ns = code->ext.block.ns;
7651   gfc_resolve (ns);
7652
7653   /* Check for F03:C813.  */
7654   if (code->expr1->ts.type != BT_CLASS
7655       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7656     {
7657       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7658                  "at %L", &code->loc);
7659       return;
7660     }
7661
7662   if (code->expr2)
7663     {
7664       if (code->expr1->symtree->n.sym->attr.untyped)
7665         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7666       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7667     }
7668   else
7669     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7670
7671   /* Loop over TYPE IS / CLASS IS cases.  */
7672   for (body = code->block; body; body = body->block)
7673     {
7674       c = body->ext.case_list;
7675
7676       /* Check F03:C815.  */
7677       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7678           && !gfc_type_is_extensible (c->ts.u.derived))
7679         {
7680           gfc_error ("Derived type '%s' at %L must be extensible",
7681                      c->ts.u.derived->name, &c->where);
7682           error++;
7683           continue;
7684         }
7685
7686       /* Check F03:C816.  */
7687       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7688           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7689         {
7690           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7691                      c->ts.u.derived->name, &c->where, selector_type->name);
7692           error++;
7693           continue;
7694         }
7695
7696       /* Intercept the DEFAULT case.  */
7697       if (c->ts.type == BT_UNKNOWN)
7698         {
7699           /* Check F03:C818.  */
7700           if (default_case)
7701             {
7702               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7703                          "by a second DEFAULT CASE at %L",
7704                          &default_case->ext.case_list->where, &c->where);
7705               error++;
7706               continue;
7707             }
7708           else
7709             default_case = body;
7710         }
7711     }
7712     
7713   if (error > 0)
7714     return;
7715
7716   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7717      target if present.  */
7718   code->op = EXEC_BLOCK;
7719   if (code->expr2)
7720     {
7721       gfc_association_list* assoc;
7722
7723       assoc = gfc_get_association_list ();
7724       assoc->st = code->expr1->symtree;
7725       assoc->target = gfc_copy_expr (code->expr2);
7726       /* assoc->variable will be set by resolve_assoc_var.  */
7727       
7728       code->ext.block.assoc = assoc;
7729       code->expr1->symtree->n.sym->assoc = assoc;
7730
7731       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7732     }
7733   else
7734     code->ext.block.assoc = NULL;
7735
7736   /* Add EXEC_SELECT to switch on type.  */
7737   new_st = gfc_get_code ();
7738   new_st->op = code->op;
7739   new_st->expr1 = code->expr1;
7740   new_st->expr2 = code->expr2;
7741   new_st->block = code->block;
7742   code->expr1 = code->expr2 =  NULL;
7743   code->block = NULL;
7744   if (!ns->code)
7745     ns->code = new_st;
7746   else
7747     ns->code->next = new_st;
7748   code = new_st;
7749   code->op = EXEC_SELECT;
7750   gfc_add_component_ref (code->expr1, "$vptr");
7751   gfc_add_component_ref (code->expr1, "$hash");
7752
7753   /* Loop over TYPE IS / CLASS IS cases.  */
7754   for (body = code->block; body; body = body->block)
7755     {
7756       c = body->ext.case_list;
7757
7758       if (c->ts.type == BT_DERIVED)
7759         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7760                                              c->ts.u.derived->hash_value);
7761
7762       else if (c->ts.type == BT_UNKNOWN)
7763         continue;
7764
7765       /* Associate temporary to selector.  This should only be done
7766          when this case is actually true, so build a new ASSOCIATE
7767          that does precisely this here (instead of using the
7768          'global' one).  */
7769
7770       if (c->ts.type == BT_CLASS)
7771         sprintf (name, "tmp$class$%s", c->ts.u.derived->name);
7772       else
7773         sprintf (name, "tmp$type$%s", c->ts.u.derived->name);
7774       st = gfc_find_symtree (ns->sym_root, name);
7775       gcc_assert (st->n.sym->assoc);
7776       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
7777       if (c->ts.type == BT_DERIVED)
7778         gfc_add_component_ref (st->n.sym->assoc->target, "$data");
7779
7780       new_st = gfc_get_code ();
7781       new_st->op = EXEC_BLOCK;
7782       new_st->ext.block.ns = gfc_build_block_ns (ns);
7783       new_st->ext.block.ns->code = body->next;
7784       body->next = new_st;
7785
7786       /* Chain in the new list only if it is marked as dangling.  Otherwise
7787          there is a CASE label overlap and this is already used.  Just ignore,
7788          the error is diagonsed elsewhere.  */
7789       if (st->n.sym->assoc->dangling)
7790         {
7791           new_st->ext.block.assoc = st->n.sym->assoc;
7792           st->n.sym->assoc->dangling = 0;
7793         }
7794
7795       resolve_assoc_var (st->n.sym, false);
7796     }
7797     
7798   /* Take out CLASS IS cases for separate treatment.  */
7799   body = code;
7800   while (body && body->block)
7801     {
7802       if (body->block->ext.case_list->ts.type == BT_CLASS)
7803         {
7804           /* Add to class_is list.  */
7805           if (class_is == NULL)
7806             { 
7807               class_is = body->block;
7808               tail = class_is;
7809             }
7810           else
7811             {
7812               for (tail = class_is; tail->block; tail = tail->block) ;
7813               tail->block = body->block;
7814               tail = tail->block;
7815             }
7816           /* Remove from EXEC_SELECT list.  */
7817           body->block = body->block->block;
7818           tail->block = NULL;
7819         }
7820       else
7821         body = body->block;
7822     }
7823
7824   if (class_is)
7825     {
7826       gfc_symbol *vtab;
7827       
7828       if (!default_case)
7829         {
7830           /* Add a default case to hold the CLASS IS cases.  */
7831           for (tail = code; tail->block; tail = tail->block) ;
7832           tail->block = gfc_get_code ();
7833           tail = tail->block;
7834           tail->op = EXEC_SELECT_TYPE;
7835           tail->ext.case_list = gfc_get_case ();
7836           tail->ext.case_list->ts.type = BT_UNKNOWN;
7837           tail->next = NULL;
7838           default_case = tail;
7839         }
7840
7841       /* More than one CLASS IS block?  */
7842       if (class_is->block)
7843         {
7844           gfc_code **c1,*c2;
7845           bool swapped;
7846           /* Sort CLASS IS blocks by extension level.  */
7847           do
7848             {
7849               swapped = false;
7850               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
7851                 {
7852                   c2 = (*c1)->block;
7853                   /* F03:C817 (check for doubles).  */
7854                   if ((*c1)->ext.case_list->ts.u.derived->hash_value
7855                       == c2->ext.case_list->ts.u.derived->hash_value)
7856                     {
7857                       gfc_error ("Double CLASS IS block in SELECT TYPE "
7858                                  "statement at %L", &c2->ext.case_list->where);
7859                       return;
7860                     }
7861                   if ((*c1)->ext.case_list->ts.u.derived->attr.extension
7862                       < c2->ext.case_list->ts.u.derived->attr.extension)
7863                     {
7864                       /* Swap.  */
7865                       (*c1)->block = c2->block;
7866                       c2->block = *c1;
7867                       *c1 = c2;
7868                       swapped = true;
7869                     }
7870                 }
7871             }
7872           while (swapped);
7873         }
7874         
7875       /* Generate IF chain.  */
7876       if_st = gfc_get_code ();
7877       if_st->op = EXEC_IF;
7878       new_st = if_st;
7879       for (body = class_is; body; body = body->block)
7880         {
7881           new_st->block = gfc_get_code ();
7882           new_st = new_st->block;
7883           new_st->op = EXEC_IF;
7884           /* Set up IF condition: Call _gfortran_is_extension_of.  */
7885           new_st->expr1 = gfc_get_expr ();
7886           new_st->expr1->expr_type = EXPR_FUNCTION;
7887           new_st->expr1->ts.type = BT_LOGICAL;
7888           new_st->expr1->ts.kind = 4;
7889           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
7890           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
7891           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
7892           /* Set up arguments.  */
7893           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
7894           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
7895           gfc_add_component_ref (new_st->expr1->value.function.actual->expr, "$vptr");
7896           vtab = gfc_find_derived_vtab (body->ext.case_list->ts.u.derived);
7897           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
7898           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
7899           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
7900           new_st->next = body->next;
7901         }
7902         if (default_case->next)
7903           {
7904             new_st->block = gfc_get_code ();
7905             new_st = new_st->block;
7906             new_st->op = EXEC_IF;
7907             new_st->next = default_case->next;
7908           }
7909           
7910         /* Replace CLASS DEFAULT code by the IF chain.  */
7911         default_case->next = if_st;
7912     }
7913
7914   resolve_select (code);
7915
7916 }
7917
7918
7919 /* Resolve a transfer statement. This is making sure that:
7920    -- a derived type being transferred has only non-pointer components
7921    -- a derived type being transferred doesn't have private components, unless 
7922       it's being transferred from the module where the type was defined
7923    -- we're not trying to transfer a whole assumed size array.  */
7924
7925 static void
7926 resolve_transfer (gfc_code *code)
7927 {
7928   gfc_typespec *ts;
7929   gfc_symbol *sym;
7930   gfc_ref *ref;
7931   gfc_expr *exp;
7932
7933   exp = code->expr1;
7934
7935   while (exp != NULL && exp->expr_type == EXPR_OP
7936          && exp->value.op.op == INTRINSIC_PARENTHESES)
7937     exp = exp->value.op.op1;
7938
7939   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
7940                       && exp->expr_type != EXPR_FUNCTION))
7941     return;
7942
7943   sym = exp->symtree->n.sym;
7944   ts = &sym->ts;
7945
7946   /* Go to actual component transferred.  */
7947   for (ref = code->expr1->ref; ref; ref = ref->next)
7948     if (ref->type == REF_COMPONENT)
7949       ts = &ref->u.c.component->ts;
7950
7951   if (ts->type == BT_DERIVED)
7952     {
7953       /* Check that transferred derived type doesn't contain POINTER
7954          components.  */
7955       if (ts->u.derived->attr.pointer_comp)
7956         {
7957           gfc_error ("Data transfer element at %L cannot have "
7958                      "POINTER components", &code->loc);
7959           return;
7960         }
7961
7962       if (ts->u.derived->attr.alloc_comp)
7963         {
7964           gfc_error ("Data transfer element at %L cannot have "
7965                      "ALLOCATABLE components", &code->loc);
7966           return;
7967         }
7968
7969       if (derived_inaccessible (ts->u.derived))
7970         {
7971           gfc_error ("Data transfer element at %L cannot have "
7972                      "PRIVATE components",&code->loc);
7973           return;
7974         }
7975     }
7976
7977   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
7978       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
7979     {
7980       gfc_error ("Data transfer element at %L cannot be a full reference to "
7981                  "an assumed-size array", &code->loc);
7982       return;
7983     }
7984 }
7985
7986
7987 /*********** Toplevel code resolution subroutines ***********/
7988
7989 /* Find the set of labels that are reachable from this block.  We also
7990    record the last statement in each block.  */
7991      
7992 static void
7993 find_reachable_labels (gfc_code *block)
7994 {
7995   gfc_code *c;
7996
7997   if (!block)
7998     return;
7999
8000   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8001
8002   /* Collect labels in this block.  We don't keep those corresponding
8003      to END {IF|SELECT}, these are checked in resolve_branch by going
8004      up through the code_stack.  */
8005   for (c = block; c; c = c->next)
8006     {
8007       if (c->here && c->op != EXEC_END_BLOCK)
8008         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8009     }
8010
8011   /* Merge with labels from parent block.  */
8012   if (cs_base->prev)
8013     {
8014       gcc_assert (cs_base->prev->reachable_labels);
8015       bitmap_ior_into (cs_base->reachable_labels,
8016                        cs_base->prev->reachable_labels);
8017     }
8018 }
8019
8020
8021 static void
8022 resolve_sync (gfc_code *code)
8023 {
8024   /* Check imageset. The * case matches expr1 == NULL.  */
8025   if (code->expr1)
8026     {
8027       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8028         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8029                    "INTEGER expression", &code->expr1->where);
8030       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8031           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8032         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8033                    &code->expr1->where);
8034       else if (code->expr1->expr_type == EXPR_ARRAY
8035                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8036         {
8037            gfc_constructor *cons;
8038            cons = gfc_constructor_first (code->expr1->value.constructor);
8039            for (; cons; cons = gfc_constructor_next (cons))
8040              if (cons->expr->expr_type == EXPR_CONSTANT
8041                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8042                gfc_error ("Imageset argument at %L must between 1 and "
8043                           "num_images()", &cons->expr->where);
8044         }
8045     }
8046
8047   /* Check STAT.  */
8048   if (code->expr2
8049       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8050           || code->expr2->expr_type != EXPR_VARIABLE))
8051     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8052                &code->expr2->where);
8053
8054   /* Check ERRMSG.  */
8055   if (code->expr3
8056       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8057           || code->expr3->expr_type != EXPR_VARIABLE))
8058     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8059                &code->expr3->where);
8060 }
8061
8062
8063 /* Given a branch to a label, see if the branch is conforming.
8064    The code node describes where the branch is located.  */
8065
8066 static void
8067 resolve_branch (gfc_st_label *label, gfc_code *code)
8068 {
8069   code_stack *stack;
8070
8071   if (label == NULL)
8072     return;
8073
8074   /* Step one: is this a valid branching target?  */
8075
8076   if (label->defined == ST_LABEL_UNKNOWN)
8077     {
8078       gfc_error ("Label %d referenced at %L is never defined", label->value,
8079                  &label->where);
8080       return;
8081     }
8082
8083   if (label->defined != ST_LABEL_TARGET)
8084     {
8085       gfc_error ("Statement at %L is not a valid branch target statement "
8086                  "for the branch statement at %L", &label->where, &code->loc);
8087       return;
8088     }
8089
8090   /* Step two: make sure this branch is not a branch to itself ;-)  */
8091
8092   if (code->here == label)
8093     {
8094       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8095       return;
8096     }
8097
8098   /* Step three:  See if the label is in the same block as the
8099      branching statement.  The hard work has been done by setting up
8100      the bitmap reachable_labels.  */
8101
8102   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8103     {
8104       /* Check now whether there is a CRITICAL construct; if so, check
8105          whether the label is still visible outside of the CRITICAL block,
8106          which is invalid.  */
8107       for (stack = cs_base; stack; stack = stack->prev)
8108         if (stack->current->op == EXEC_CRITICAL
8109             && bitmap_bit_p (stack->reachable_labels, label->value))
8110           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8111                       " at %L", &code->loc, &label->where);
8112
8113       return;
8114     }
8115
8116   /* Step four:  If we haven't found the label in the bitmap, it may
8117     still be the label of the END of the enclosing block, in which
8118     case we find it by going up the code_stack.  */
8119
8120   for (stack = cs_base; stack; stack = stack->prev)
8121     {
8122       if (stack->current->next && stack->current->next->here == label)
8123         break;
8124       if (stack->current->op == EXEC_CRITICAL)
8125         {
8126           /* Note: A label at END CRITICAL does not leave the CRITICAL
8127              construct as END CRITICAL is still part of it.  */
8128           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8129                       " at %L", &code->loc, &label->where);
8130           return;
8131         }
8132     }
8133
8134   if (stack)
8135     {
8136       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
8137       return;
8138     }
8139
8140   /* The label is not in an enclosing block, so illegal.  This was
8141      allowed in Fortran 66, so we allow it as extension.  No
8142      further checks are necessary in this case.  */
8143   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8144                   "as the GOTO statement at %L", &label->where,
8145                   &code->loc);
8146   return;
8147 }
8148
8149
8150 /* Check whether EXPR1 has the same shape as EXPR2.  */
8151
8152 static gfc_try
8153 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8154 {
8155   mpz_t shape[GFC_MAX_DIMENSIONS];
8156   mpz_t shape2[GFC_MAX_DIMENSIONS];
8157   gfc_try result = FAILURE;
8158   int i;
8159
8160   /* Compare the rank.  */
8161   if (expr1->rank != expr2->rank)
8162     return result;
8163
8164   /* Compare the size of each dimension.  */
8165   for (i=0; i<expr1->rank; i++)
8166     {
8167       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8168         goto ignore;
8169
8170       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8171         goto ignore;
8172
8173       if (mpz_cmp (shape[i], shape2[i]))
8174         goto over;
8175     }
8176
8177   /* When either of the two expression is an assumed size array, we
8178      ignore the comparison of dimension sizes.  */
8179 ignore:
8180   result = SUCCESS;
8181
8182 over:
8183   for (i--; i >= 0; i--)
8184     {
8185       mpz_clear (shape[i]);
8186       mpz_clear (shape2[i]);
8187     }
8188   return result;
8189 }
8190
8191
8192 /* Check whether a WHERE assignment target or a WHERE mask expression
8193    has the same shape as the outmost WHERE mask expression.  */
8194
8195 static void
8196 resolve_where (gfc_code *code, gfc_expr *mask)
8197 {
8198   gfc_code *cblock;
8199   gfc_code *cnext;
8200   gfc_expr *e = NULL;
8201
8202   cblock = code->block;
8203
8204   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8205      In case of nested WHERE, only the outmost one is stored.  */
8206   if (mask == NULL) /* outmost WHERE */
8207     e = cblock->expr1;
8208   else /* inner WHERE */
8209     e = mask;
8210
8211   while (cblock)
8212     {
8213       if (cblock->expr1)
8214         {
8215           /* Check if the mask-expr has a consistent shape with the
8216              outmost WHERE mask-expr.  */
8217           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8218             gfc_error ("WHERE mask at %L has inconsistent shape",
8219                        &cblock->expr1->where);
8220          }
8221
8222       /* the assignment statement of a WHERE statement, or the first
8223          statement in where-body-construct of a WHERE construct */
8224       cnext = cblock->next;
8225       while (cnext)
8226         {
8227           switch (cnext->op)
8228             {
8229             /* WHERE assignment statement */
8230             case EXEC_ASSIGN:
8231
8232               /* Check shape consistent for WHERE assignment target.  */
8233               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8234                gfc_error ("WHERE assignment target at %L has "
8235                           "inconsistent shape", &cnext->expr1->where);
8236               break;
8237
8238   
8239             case EXEC_ASSIGN_CALL:
8240               resolve_call (cnext);
8241               if (!cnext->resolved_sym->attr.elemental)
8242                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8243                           &cnext->ext.actual->expr->where);
8244               break;
8245
8246             /* WHERE or WHERE construct is part of a where-body-construct */
8247             case EXEC_WHERE:
8248               resolve_where (cnext, e);
8249               break;
8250
8251             default:
8252               gfc_error ("Unsupported statement inside WHERE at %L",
8253                          &cnext->loc);
8254             }
8255          /* the next statement within the same where-body-construct */
8256          cnext = cnext->next;
8257        }
8258     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8259     cblock = cblock->block;
8260   }
8261 }
8262
8263
8264 /* Resolve assignment in FORALL construct.
8265    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8266    FORALL index variables.  */
8267
8268 static void
8269 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8270 {
8271   int n;
8272
8273   for (n = 0; n < nvar; n++)
8274     {
8275       gfc_symbol *forall_index;
8276
8277       forall_index = var_expr[n]->symtree->n.sym;
8278
8279       /* Check whether the assignment target is one of the FORALL index
8280          variable.  */
8281       if ((code->expr1->expr_type == EXPR_VARIABLE)
8282           && (code->expr1->symtree->n.sym == forall_index))
8283         gfc_error ("Assignment to a FORALL index variable at %L",
8284                    &code->expr1->where);
8285       else
8286         {
8287           /* If one of the FORALL index variables doesn't appear in the
8288              assignment variable, then there could be a many-to-one
8289              assignment.  Emit a warning rather than an error because the
8290              mask could be resolving this problem.  */
8291           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8292             gfc_warning ("The FORALL with index '%s' is not used on the "
8293                          "left side of the assignment at %L and so might "
8294                          "cause multiple assignment to this object",
8295                          var_expr[n]->symtree->name, &code->expr1->where);
8296         }
8297     }
8298 }
8299
8300
8301 /* Resolve WHERE statement in FORALL construct.  */
8302
8303 static void
8304 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8305                                   gfc_expr **var_expr)
8306 {
8307   gfc_code *cblock;
8308   gfc_code *cnext;
8309
8310   cblock = code->block;
8311   while (cblock)
8312     {
8313       /* the assignment statement of a WHERE statement, or the first
8314          statement in where-body-construct of a WHERE construct */
8315       cnext = cblock->next;
8316       while (cnext)
8317         {
8318           switch (cnext->op)
8319             {
8320             /* WHERE assignment statement */
8321             case EXEC_ASSIGN:
8322               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8323               break;
8324   
8325             /* WHERE operator assignment statement */
8326             case EXEC_ASSIGN_CALL:
8327               resolve_call (cnext);
8328               if (!cnext->resolved_sym->attr.elemental)
8329                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8330                           &cnext->ext.actual->expr->where);
8331               break;
8332
8333             /* WHERE or WHERE construct is part of a where-body-construct */
8334             case EXEC_WHERE:
8335               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8336               break;
8337
8338             default:
8339               gfc_error ("Unsupported statement inside WHERE at %L",
8340                          &cnext->loc);
8341             }
8342           /* the next statement within the same where-body-construct */
8343           cnext = cnext->next;
8344         }
8345       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8346       cblock = cblock->block;
8347     }
8348 }
8349
8350
8351 /* Traverse the FORALL body to check whether the following errors exist:
8352    1. For assignment, check if a many-to-one assignment happens.
8353    2. For WHERE statement, check the WHERE body to see if there is any
8354       many-to-one assignment.  */
8355
8356 static void
8357 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8358 {
8359   gfc_code *c;
8360
8361   c = code->block->next;
8362   while (c)
8363     {
8364       switch (c->op)
8365         {
8366         case EXEC_ASSIGN:
8367         case EXEC_POINTER_ASSIGN:
8368           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8369           break;
8370
8371         case EXEC_ASSIGN_CALL:
8372           resolve_call (c);
8373           break;
8374
8375         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8376            there is no need to handle it here.  */
8377         case EXEC_FORALL:
8378           break;
8379         case EXEC_WHERE:
8380           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8381           break;
8382         default:
8383           break;
8384         }
8385       /* The next statement in the FORALL body.  */
8386       c = c->next;
8387     }
8388 }
8389
8390
8391 /* Counts the number of iterators needed inside a forall construct, including
8392    nested forall constructs. This is used to allocate the needed memory 
8393    in gfc_resolve_forall.  */
8394
8395 static int 
8396 gfc_count_forall_iterators (gfc_code *code)
8397 {
8398   int max_iters, sub_iters, current_iters;
8399   gfc_forall_iterator *fa;
8400
8401   gcc_assert(code->op == EXEC_FORALL);
8402   max_iters = 0;
8403   current_iters = 0;
8404
8405   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8406     current_iters ++;
8407   
8408   code = code->block->next;
8409
8410   while (code)
8411     {          
8412       if (code->op == EXEC_FORALL)
8413         {
8414           sub_iters = gfc_count_forall_iterators (code);
8415           if (sub_iters > max_iters)
8416             max_iters = sub_iters;
8417         }
8418       code = code->next;
8419     }
8420
8421   return current_iters + max_iters;
8422 }
8423
8424
8425 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8426    gfc_resolve_forall_body to resolve the FORALL body.  */
8427
8428 static void
8429 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8430 {
8431   static gfc_expr **var_expr;
8432   static int total_var = 0;
8433   static int nvar = 0;
8434   int old_nvar, tmp;
8435   gfc_forall_iterator *fa;
8436   int i;
8437
8438   old_nvar = nvar;
8439
8440   /* Start to resolve a FORALL construct   */
8441   if (forall_save == 0)
8442     {
8443       /* Count the total number of FORALL index in the nested FORALL
8444          construct in order to allocate the VAR_EXPR with proper size.  */
8445       total_var = gfc_count_forall_iterators (code);
8446
8447       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8448       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
8449     }
8450
8451   /* The information about FORALL iterator, including FORALL index start, end
8452      and stride. The FORALL index can not appear in start, end or stride.  */
8453   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8454     {
8455       /* Check if any outer FORALL index name is the same as the current
8456          one.  */
8457       for (i = 0; i < nvar; i++)
8458         {
8459           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8460             {
8461               gfc_error ("An outer FORALL construct already has an index "
8462                          "with this name %L", &fa->var->where);
8463             }
8464         }
8465
8466       /* Record the current FORALL index.  */
8467       var_expr[nvar] = gfc_copy_expr (fa->var);
8468
8469       nvar++;
8470
8471       /* No memory leak.  */
8472       gcc_assert (nvar <= total_var);
8473     }
8474
8475   /* Resolve the FORALL body.  */
8476   gfc_resolve_forall_body (code, nvar, var_expr);
8477
8478   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8479   gfc_resolve_blocks (code->block, ns);
8480
8481   tmp = nvar;
8482   nvar = old_nvar;
8483   /* Free only the VAR_EXPRs allocated in this frame.  */
8484   for (i = nvar; i < tmp; i++)
8485      gfc_free_expr (var_expr[i]);
8486
8487   if (nvar == 0)
8488     {
8489       /* We are in the outermost FORALL construct.  */
8490       gcc_assert (forall_save == 0);
8491
8492       /* VAR_EXPR is not needed any more.  */
8493       gfc_free (var_expr);
8494       total_var = 0;
8495     }
8496 }
8497
8498
8499 /* Resolve a BLOCK construct statement.  */
8500
8501 static void
8502 resolve_block_construct (gfc_code* code)
8503 {
8504   /* Resolve the BLOCK's namespace.  */
8505   gfc_resolve (code->ext.block.ns);
8506
8507   /* For an ASSOCIATE block, the associations (and their targets) are already
8508      resolved during resolve_symbol.  */
8509 }
8510
8511
8512 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8513    DO code nodes.  */
8514
8515 static void resolve_code (gfc_code *, gfc_namespace *);
8516
8517 void
8518 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8519 {
8520   gfc_try t;
8521
8522   for (; b; b = b->block)
8523     {
8524       t = gfc_resolve_expr (b->expr1);
8525       if (gfc_resolve_expr (b->expr2) == FAILURE)
8526         t = FAILURE;
8527
8528       switch (b->op)
8529         {
8530         case EXEC_IF:
8531           if (t == SUCCESS && b->expr1 != NULL
8532               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8533             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8534                        &b->expr1->where);
8535           break;
8536
8537         case EXEC_WHERE:
8538           if (t == SUCCESS
8539               && b->expr1 != NULL
8540               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8541             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8542                        &b->expr1->where);
8543           break;
8544
8545         case EXEC_GOTO:
8546           resolve_branch (b->label1, b);
8547           break;
8548
8549         case EXEC_BLOCK:
8550           resolve_block_construct (b);
8551           break;
8552
8553         case EXEC_SELECT:
8554         case EXEC_SELECT_TYPE:
8555         case EXEC_FORALL:
8556         case EXEC_DO:
8557         case EXEC_DO_WHILE:
8558         case EXEC_CRITICAL:
8559         case EXEC_READ:
8560         case EXEC_WRITE:
8561         case EXEC_IOLENGTH:
8562         case EXEC_WAIT:
8563           break;
8564
8565         case EXEC_OMP_ATOMIC:
8566         case EXEC_OMP_CRITICAL:
8567         case EXEC_OMP_DO:
8568         case EXEC_OMP_MASTER:
8569         case EXEC_OMP_ORDERED:
8570         case EXEC_OMP_PARALLEL:
8571         case EXEC_OMP_PARALLEL_DO:
8572         case EXEC_OMP_PARALLEL_SECTIONS:
8573         case EXEC_OMP_PARALLEL_WORKSHARE:
8574         case EXEC_OMP_SECTIONS:
8575         case EXEC_OMP_SINGLE:
8576         case EXEC_OMP_TASK:
8577         case EXEC_OMP_TASKWAIT:
8578         case EXEC_OMP_WORKSHARE:
8579           break;
8580
8581         default:
8582           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8583         }
8584
8585       resolve_code (b->next, ns);
8586     }
8587 }
8588
8589
8590 /* Does everything to resolve an ordinary assignment.  Returns true
8591    if this is an interface assignment.  */
8592 static bool
8593 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8594 {
8595   bool rval = false;
8596   gfc_expr *lhs;
8597   gfc_expr *rhs;
8598   int llen = 0;
8599   int rlen = 0;
8600   int n;
8601   gfc_ref *ref;
8602
8603   if (gfc_extend_assign (code, ns) == SUCCESS)
8604     {
8605       gfc_expr** rhsptr;
8606
8607       if (code->op == EXEC_ASSIGN_CALL)
8608         {
8609           lhs = code->ext.actual->expr;
8610           rhsptr = &code->ext.actual->next->expr;
8611         }
8612       else
8613         {
8614           gfc_actual_arglist* args;
8615           gfc_typebound_proc* tbp;
8616
8617           gcc_assert (code->op == EXEC_COMPCALL);
8618
8619           args = code->expr1->value.compcall.actual;
8620           lhs = args->expr;
8621           rhsptr = &args->next->expr;
8622
8623           tbp = code->expr1->value.compcall.tbp;
8624           gcc_assert (!tbp->is_generic);
8625         }
8626
8627       /* Make a temporary rhs when there is a default initializer
8628          and rhs is the same symbol as the lhs.  */
8629       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8630             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8631             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8632             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8633         *rhsptr = gfc_get_parentheses (*rhsptr);
8634
8635       return true;
8636     }
8637
8638   lhs = code->expr1;
8639   rhs = code->expr2;
8640
8641   if (rhs->is_boz
8642       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8643                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8644                          &code->loc) == FAILURE)
8645     return false;
8646
8647   /* Handle the case of a BOZ literal on the RHS.  */
8648   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8649     {
8650       int rc;
8651       if (gfc_option.warn_surprising)
8652         gfc_warning ("BOZ literal at %L is bitwise transferred "
8653                      "non-integer symbol '%s'", &code->loc,
8654                      lhs->symtree->n.sym->name);
8655
8656       if (!gfc_convert_boz (rhs, &lhs->ts))
8657         return false;
8658       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8659         {
8660           if (rc == ARITH_UNDERFLOW)
8661             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8662                        ". This check can be disabled with the option "
8663                        "-fno-range-check", &rhs->where);
8664           else if (rc == ARITH_OVERFLOW)
8665             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8666                        ". This check can be disabled with the option "
8667                        "-fno-range-check", &rhs->where);
8668           else if (rc == ARITH_NAN)
8669             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8670                        ". This check can be disabled with the option "
8671                        "-fno-range-check", &rhs->where);
8672           return false;
8673         }
8674     }
8675
8676
8677   if (lhs->ts.type == BT_CHARACTER
8678         && gfc_option.warn_character_truncation)
8679     {
8680       if (lhs->ts.u.cl != NULL
8681             && lhs->ts.u.cl->length != NULL
8682             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8683         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8684
8685       if (rhs->expr_type == EXPR_CONSTANT)
8686         rlen = rhs->value.character.length;
8687
8688       else if (rhs->ts.u.cl != NULL
8689                  && rhs->ts.u.cl->length != NULL
8690                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8691         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8692
8693       if (rlen && llen && rlen > llen)
8694         gfc_warning_now ("CHARACTER expression will be truncated "
8695                          "in assignment (%d/%d) at %L",
8696                          llen, rlen, &code->loc);
8697     }
8698
8699   /* Ensure that a vector index expression for the lvalue is evaluated
8700      to a temporary if the lvalue symbol is referenced in it.  */
8701   if (lhs->rank)
8702     {
8703       for (ref = lhs->ref; ref; ref= ref->next)
8704         if (ref->type == REF_ARRAY)
8705           {
8706             for (n = 0; n < ref->u.ar.dimen; n++)
8707               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8708                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8709                                            ref->u.ar.start[n]))
8710                 ref->u.ar.start[n]
8711                         = gfc_get_parentheses (ref->u.ar.start[n]);
8712           }
8713     }
8714
8715   if (gfc_pure (NULL))
8716     {
8717       if (gfc_impure_variable (lhs->symtree->n.sym))
8718         {
8719           gfc_error ("Cannot assign to variable '%s' in PURE "
8720                      "procedure at %L",
8721                       lhs->symtree->n.sym->name,
8722                       &lhs->where);
8723           return rval;
8724         }
8725
8726       if (lhs->ts.type == BT_DERIVED
8727             && lhs->expr_type == EXPR_VARIABLE
8728             && lhs->ts.u.derived->attr.pointer_comp
8729             && rhs->expr_type == EXPR_VARIABLE
8730             && (gfc_impure_variable (rhs->symtree->n.sym)
8731                 || gfc_is_coindexed (rhs)))
8732         {
8733           /* F2008, C1283.  */
8734           if (gfc_is_coindexed (rhs))
8735             gfc_error ("Coindexed expression at %L is assigned to "
8736                         "a derived type variable with a POINTER "
8737                         "component in a PURE procedure",
8738                         &rhs->where);
8739           else
8740             gfc_error ("The impure variable at %L is assigned to "
8741                         "a derived type variable with a POINTER "
8742                         "component in a PURE procedure (12.6)",
8743                         &rhs->where);
8744           return rval;
8745         }
8746
8747       /* Fortran 2008, C1283.  */
8748       if (gfc_is_coindexed (lhs))
8749         {
8750           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8751                      "procedure", &rhs->where);
8752           return rval;
8753         }
8754     }
8755
8756   /* F03:7.4.1.2.  */
8757   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
8758      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
8759   if (lhs->ts.type == BT_CLASS)
8760     {
8761       gfc_error ("Variable must not be polymorphic in assignment at %L",
8762                  &lhs->where);
8763       return false;
8764     }
8765
8766   /* F2008, Section 7.2.1.2.  */
8767   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
8768     {
8769       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
8770                  "component in assignment at %L", &lhs->where);
8771       return false;
8772     }
8773
8774   gfc_check_assign (lhs, rhs, 1);
8775   return false;
8776 }
8777
8778
8779 /* Given a block of code, recursively resolve everything pointed to by this
8780    code block.  */
8781
8782 static void
8783 resolve_code (gfc_code *code, gfc_namespace *ns)
8784 {
8785   int omp_workshare_save;
8786   int forall_save;
8787   code_stack frame;
8788   gfc_try t;
8789
8790   frame.prev = cs_base;
8791   frame.head = code;
8792   cs_base = &frame;
8793
8794   find_reachable_labels (code);
8795
8796   for (; code; code = code->next)
8797     {
8798       frame.current = code;
8799       forall_save = forall_flag;
8800
8801       if (code->op == EXEC_FORALL)
8802         {
8803           forall_flag = 1;
8804           gfc_resolve_forall (code, ns, forall_save);
8805           forall_flag = 2;
8806         }
8807       else if (code->block)
8808         {
8809           omp_workshare_save = -1;
8810           switch (code->op)
8811             {
8812             case EXEC_OMP_PARALLEL_WORKSHARE:
8813               omp_workshare_save = omp_workshare_flag;
8814               omp_workshare_flag = 1;
8815               gfc_resolve_omp_parallel_blocks (code, ns);
8816               break;
8817             case EXEC_OMP_PARALLEL:
8818             case EXEC_OMP_PARALLEL_DO:
8819             case EXEC_OMP_PARALLEL_SECTIONS:
8820             case EXEC_OMP_TASK:
8821               omp_workshare_save = omp_workshare_flag;
8822               omp_workshare_flag = 0;
8823               gfc_resolve_omp_parallel_blocks (code, ns);
8824               break;
8825             case EXEC_OMP_DO:
8826               gfc_resolve_omp_do_blocks (code, ns);
8827               break;
8828             case EXEC_SELECT_TYPE:
8829               gfc_current_ns = code->ext.block.ns;
8830               gfc_resolve_blocks (code->block, gfc_current_ns);
8831               gfc_current_ns = ns;
8832               break;
8833             case EXEC_OMP_WORKSHARE:
8834               omp_workshare_save = omp_workshare_flag;
8835               omp_workshare_flag = 1;
8836               /* FALLTHROUGH */
8837             default:
8838               gfc_resolve_blocks (code->block, ns);
8839               break;
8840             }
8841
8842           if (omp_workshare_save != -1)
8843             omp_workshare_flag = omp_workshare_save;
8844         }
8845
8846       t = SUCCESS;
8847       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
8848         t = gfc_resolve_expr (code->expr1);
8849       forall_flag = forall_save;
8850
8851       if (gfc_resolve_expr (code->expr2) == FAILURE)
8852         t = FAILURE;
8853
8854       if (code->op == EXEC_ALLOCATE
8855           && gfc_resolve_expr (code->expr3) == FAILURE)
8856         t = FAILURE;
8857
8858       switch (code->op)
8859         {
8860         case EXEC_NOP:
8861         case EXEC_END_BLOCK:
8862         case EXEC_CYCLE:
8863         case EXEC_PAUSE:
8864         case EXEC_STOP:
8865         case EXEC_ERROR_STOP:
8866         case EXEC_EXIT:
8867         case EXEC_CONTINUE:
8868         case EXEC_DT_END:
8869         case EXEC_ASSIGN_CALL:
8870         case EXEC_CRITICAL:
8871           break;
8872
8873         case EXEC_SYNC_ALL:
8874         case EXEC_SYNC_IMAGES:
8875         case EXEC_SYNC_MEMORY:
8876           resolve_sync (code);
8877           break;
8878
8879         case EXEC_ENTRY:
8880           /* Keep track of which entry we are up to.  */
8881           current_entry_id = code->ext.entry->id;
8882           break;
8883
8884         case EXEC_WHERE:
8885           resolve_where (code, NULL);
8886           break;
8887
8888         case EXEC_GOTO:
8889           if (code->expr1 != NULL)
8890             {
8891               if (code->expr1->ts.type != BT_INTEGER)
8892                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
8893                            "INTEGER variable", &code->expr1->where);
8894               else if (code->expr1->symtree->n.sym->attr.assign != 1)
8895                 gfc_error ("Variable '%s' has not been assigned a target "
8896                            "label at %L", code->expr1->symtree->n.sym->name,
8897                            &code->expr1->where);
8898             }
8899           else
8900             resolve_branch (code->label1, code);
8901           break;
8902
8903         case EXEC_RETURN:
8904           if (code->expr1 != NULL
8905                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
8906             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
8907                        "INTEGER return specifier", &code->expr1->where);
8908           break;
8909
8910         case EXEC_INIT_ASSIGN:
8911         case EXEC_END_PROCEDURE:
8912           break;
8913
8914         case EXEC_ASSIGN:
8915           if (t == FAILURE)
8916             break;
8917
8918           if (resolve_ordinary_assign (code, ns))
8919             {
8920               if (code->op == EXEC_COMPCALL)
8921                 goto compcall;
8922               else
8923                 goto call;
8924             }
8925           break;
8926
8927         case EXEC_LABEL_ASSIGN:
8928           if (code->label1->defined == ST_LABEL_UNKNOWN)
8929             gfc_error ("Label %d referenced at %L is never defined",
8930                        code->label1->value, &code->label1->where);
8931           if (t == SUCCESS
8932               && (code->expr1->expr_type != EXPR_VARIABLE
8933                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
8934                   || code->expr1->symtree->n.sym->ts.kind
8935                      != gfc_default_integer_kind
8936                   || code->expr1->symtree->n.sym->as != NULL))
8937             gfc_error ("ASSIGN statement at %L requires a scalar "
8938                        "default INTEGER variable", &code->expr1->where);
8939           break;
8940
8941         case EXEC_POINTER_ASSIGN:
8942           if (t == FAILURE)
8943             break;
8944
8945           gfc_check_pointer_assign (code->expr1, code->expr2);
8946           break;
8947
8948         case EXEC_ARITHMETIC_IF:
8949           if (t == SUCCESS
8950               && code->expr1->ts.type != BT_INTEGER
8951               && code->expr1->ts.type != BT_REAL)
8952             gfc_error ("Arithmetic IF statement at %L requires a numeric "
8953                        "expression", &code->expr1->where);
8954
8955           resolve_branch (code->label1, code);
8956           resolve_branch (code->label2, code);
8957           resolve_branch (code->label3, code);
8958           break;
8959
8960         case EXEC_IF:
8961           if (t == SUCCESS && code->expr1 != NULL
8962               && (code->expr1->ts.type != BT_LOGICAL
8963                   || code->expr1->rank != 0))
8964             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8965                        &code->expr1->where);
8966           break;
8967
8968         case EXEC_CALL:
8969         call:
8970           resolve_call (code);
8971           break;
8972
8973         case EXEC_COMPCALL:
8974         compcall:
8975           resolve_typebound_subroutine (code);
8976           break;
8977
8978         case EXEC_CALL_PPC:
8979           resolve_ppc_call (code);
8980           break;
8981
8982         case EXEC_SELECT:
8983           /* Select is complicated. Also, a SELECT construct could be
8984              a transformed computed GOTO.  */
8985           resolve_select (code);
8986           break;
8987
8988         case EXEC_SELECT_TYPE:
8989           resolve_select_type (code);
8990           break;
8991
8992         case EXEC_BLOCK:
8993           resolve_block_construct (code);
8994           break;
8995
8996         case EXEC_DO:
8997           if (code->ext.iterator != NULL)
8998             {
8999               gfc_iterator *iter = code->ext.iterator;
9000               if (gfc_resolve_iterator (iter, true) != FAILURE)
9001                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9002             }
9003           break;
9004
9005         case EXEC_DO_WHILE:
9006           if (code->expr1 == NULL)
9007             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9008           if (t == SUCCESS
9009               && (code->expr1->rank != 0
9010                   || code->expr1->ts.type != BT_LOGICAL))
9011             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9012                        "a scalar LOGICAL expression", &code->expr1->where);
9013           break;
9014
9015         case EXEC_ALLOCATE:
9016           if (t == SUCCESS)
9017             resolve_allocate_deallocate (code, "ALLOCATE");
9018
9019           break;
9020
9021         case EXEC_DEALLOCATE:
9022           if (t == SUCCESS)
9023             resolve_allocate_deallocate (code, "DEALLOCATE");
9024
9025           break;
9026
9027         case EXEC_OPEN:
9028           if (gfc_resolve_open (code->ext.open) == FAILURE)
9029             break;
9030
9031           resolve_branch (code->ext.open->err, code);
9032           break;
9033
9034         case EXEC_CLOSE:
9035           if (gfc_resolve_close (code->ext.close) == FAILURE)
9036             break;
9037
9038           resolve_branch (code->ext.close->err, code);
9039           break;
9040
9041         case EXEC_BACKSPACE:
9042         case EXEC_ENDFILE:
9043         case EXEC_REWIND:
9044         case EXEC_FLUSH:
9045           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9046             break;
9047
9048           resolve_branch (code->ext.filepos->err, code);
9049           break;
9050
9051         case EXEC_INQUIRE:
9052           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9053               break;
9054
9055           resolve_branch (code->ext.inquire->err, code);
9056           break;
9057
9058         case EXEC_IOLENGTH:
9059           gcc_assert (code->ext.inquire != NULL);
9060           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9061             break;
9062
9063           resolve_branch (code->ext.inquire->err, code);
9064           break;
9065
9066         case EXEC_WAIT:
9067           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9068             break;
9069
9070           resolve_branch (code->ext.wait->err, code);
9071           resolve_branch (code->ext.wait->end, code);
9072           resolve_branch (code->ext.wait->eor, code);
9073           break;
9074
9075         case EXEC_READ:
9076         case EXEC_WRITE:
9077           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9078             break;
9079
9080           resolve_branch (code->ext.dt->err, code);
9081           resolve_branch (code->ext.dt->end, code);
9082           resolve_branch (code->ext.dt->eor, code);
9083           break;
9084
9085         case EXEC_TRANSFER:
9086           resolve_transfer (code);
9087           break;
9088
9089         case EXEC_FORALL:
9090           resolve_forall_iterators (code->ext.forall_iterator);
9091
9092           if (code->expr1 != NULL && code->expr1->ts.type != BT_LOGICAL)
9093             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
9094                        "expression", &code->expr1->where);
9095           break;
9096
9097         case EXEC_OMP_ATOMIC:
9098         case EXEC_OMP_BARRIER:
9099         case EXEC_OMP_CRITICAL:
9100         case EXEC_OMP_FLUSH:
9101         case EXEC_OMP_DO:
9102         case EXEC_OMP_MASTER:
9103         case EXEC_OMP_ORDERED:
9104         case EXEC_OMP_SECTIONS:
9105         case EXEC_OMP_SINGLE:
9106         case EXEC_OMP_TASKWAIT:
9107         case EXEC_OMP_WORKSHARE:
9108           gfc_resolve_omp_directive (code, ns);
9109           break;
9110
9111         case EXEC_OMP_PARALLEL:
9112         case EXEC_OMP_PARALLEL_DO:
9113         case EXEC_OMP_PARALLEL_SECTIONS:
9114         case EXEC_OMP_PARALLEL_WORKSHARE:
9115         case EXEC_OMP_TASK:
9116           omp_workshare_save = omp_workshare_flag;
9117           omp_workshare_flag = 0;
9118           gfc_resolve_omp_directive (code, ns);
9119           omp_workshare_flag = omp_workshare_save;
9120           break;
9121
9122         default:
9123           gfc_internal_error ("resolve_code(): Bad statement code");
9124         }
9125     }
9126
9127   cs_base = frame.prev;
9128 }
9129
9130
9131 /* Resolve initial values and make sure they are compatible with
9132    the variable.  */
9133
9134 static void
9135 resolve_values (gfc_symbol *sym)
9136 {
9137   gfc_try t;
9138
9139   if (sym->value == NULL)
9140     return;
9141
9142   if (sym->value->expr_type == EXPR_STRUCTURE)
9143     t= resolve_structure_cons (sym->value, 1);
9144   else 
9145     t = gfc_resolve_expr (sym->value);
9146
9147   if (t == FAILURE)
9148     return;
9149
9150   gfc_check_assign_symbol (sym, sym->value);
9151 }
9152
9153
9154 /* Verify the binding labels for common blocks that are BIND(C).  The label
9155    for a BIND(C) common block must be identical in all scoping units in which
9156    the common block is declared.  Further, the binding label can not collide
9157    with any other global entity in the program.  */
9158
9159 static void
9160 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9161 {
9162   if (comm_block_tree->n.common->is_bind_c == 1)
9163     {
9164       gfc_gsymbol *binding_label_gsym;
9165       gfc_gsymbol *comm_name_gsym;
9166
9167       /* See if a global symbol exists by the common block's name.  It may
9168          be NULL if the common block is use-associated.  */
9169       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9170                                          comm_block_tree->n.common->name);
9171       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9172         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9173                    "with the global entity '%s' at %L",
9174                    comm_block_tree->n.common->binding_label,
9175                    comm_block_tree->n.common->name,
9176                    &(comm_block_tree->n.common->where),
9177                    comm_name_gsym->name, &(comm_name_gsym->where));
9178       else if (comm_name_gsym != NULL
9179                && strcmp (comm_name_gsym->name,
9180                           comm_block_tree->n.common->name) == 0)
9181         {
9182           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9183              as expected.  */
9184           if (comm_name_gsym->binding_label == NULL)
9185             /* No binding label for common block stored yet; save this one.  */
9186             comm_name_gsym->binding_label =
9187               comm_block_tree->n.common->binding_label;
9188           else
9189             if (strcmp (comm_name_gsym->binding_label,
9190                         comm_block_tree->n.common->binding_label) != 0)
9191               {
9192                 /* Common block names match but binding labels do not.  */
9193                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9194                            "does not match the binding label '%s' for common "
9195                            "block '%s' at %L",
9196                            comm_block_tree->n.common->binding_label,
9197                            comm_block_tree->n.common->name,
9198                            &(comm_block_tree->n.common->where),
9199                            comm_name_gsym->binding_label,
9200                            comm_name_gsym->name,
9201                            &(comm_name_gsym->where));
9202                 return;
9203               }
9204         }
9205
9206       /* There is no binding label (NAME="") so we have nothing further to
9207          check and nothing to add as a global symbol for the label.  */
9208       if (comm_block_tree->n.common->binding_label[0] == '\0' )
9209         return;
9210       
9211       binding_label_gsym =
9212         gfc_find_gsymbol (gfc_gsym_root,
9213                           comm_block_tree->n.common->binding_label);
9214       if (binding_label_gsym == NULL)
9215         {
9216           /* Need to make a global symbol for the binding label to prevent
9217              it from colliding with another.  */
9218           binding_label_gsym =
9219             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9220           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9221           binding_label_gsym->type = GSYM_COMMON;
9222         }
9223       else
9224         {
9225           /* If comm_name_gsym is NULL, the name common block is use
9226              associated and the name could be colliding.  */
9227           if (binding_label_gsym->type != GSYM_COMMON)
9228             gfc_error ("Binding label '%s' for common block '%s' at %L "
9229                        "collides with the global entity '%s' at %L",
9230                        comm_block_tree->n.common->binding_label,
9231                        comm_block_tree->n.common->name,
9232                        &(comm_block_tree->n.common->where),
9233                        binding_label_gsym->name,
9234                        &(binding_label_gsym->where));
9235           else if (comm_name_gsym != NULL
9236                    && (strcmp (binding_label_gsym->name,
9237                                comm_name_gsym->binding_label) != 0)
9238                    && (strcmp (binding_label_gsym->sym_name,
9239                                comm_name_gsym->name) != 0))
9240             gfc_error ("Binding label '%s' for common block '%s' at %L "
9241                        "collides with global entity '%s' at %L",
9242                        binding_label_gsym->name, binding_label_gsym->sym_name,
9243                        &(comm_block_tree->n.common->where),
9244                        comm_name_gsym->name, &(comm_name_gsym->where));
9245         }
9246     }
9247   
9248   return;
9249 }
9250
9251
9252 /* Verify any BIND(C) derived types in the namespace so we can report errors
9253    for them once, rather than for each variable declared of that type.  */
9254
9255 static void
9256 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9257 {
9258   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9259       && derived_sym->attr.is_bind_c == 1)
9260     verify_bind_c_derived_type (derived_sym);
9261   
9262   return;
9263 }
9264
9265
9266 /* Verify that any binding labels used in a given namespace do not collide 
9267    with the names or binding labels of any global symbols.  */
9268
9269 static void
9270 gfc_verify_binding_labels (gfc_symbol *sym)
9271 {
9272   int has_error = 0;
9273   
9274   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
9275       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
9276     {
9277       gfc_gsymbol *bind_c_sym;
9278
9279       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9280       if (bind_c_sym != NULL 
9281           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9282         {
9283           if (sym->attr.if_source == IFSRC_DECL 
9284               && (bind_c_sym->type != GSYM_SUBROUTINE 
9285                   && bind_c_sym->type != GSYM_FUNCTION) 
9286               && ((sym->attr.contained == 1 
9287                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
9288                   || (sym->attr.use_assoc == 1 
9289                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9290             {
9291               /* Make sure global procedures don't collide with anything.  */
9292               gfc_error ("Binding label '%s' at %L collides with the global "
9293                          "entity '%s' at %L", sym->binding_label,
9294                          &(sym->declared_at), bind_c_sym->name,
9295                          &(bind_c_sym->where));
9296               has_error = 1;
9297             }
9298           else if (sym->attr.contained == 0 
9299                    && (sym->attr.if_source == IFSRC_IFBODY 
9300                        && sym->attr.flavor == FL_PROCEDURE) 
9301                    && (bind_c_sym->sym_name != NULL 
9302                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9303             {
9304               /* Make sure procedures in interface bodies don't collide.  */
9305               gfc_error ("Binding label '%s' in interface body at %L collides "
9306                          "with the global entity '%s' at %L",
9307                          sym->binding_label,
9308                          &(sym->declared_at), bind_c_sym->name,
9309                          &(bind_c_sym->where));
9310               has_error = 1;
9311             }
9312           else if (sym->attr.contained == 0 
9313                    && sym->attr.if_source == IFSRC_UNKNOWN)
9314             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9315                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
9316                 || sym->attr.use_assoc == 0)
9317               {
9318                 gfc_error ("Binding label '%s' at %L collides with global "
9319                            "entity '%s' at %L", sym->binding_label,
9320                            &(sym->declared_at), bind_c_sym->name,
9321                            &(bind_c_sym->where));
9322                 has_error = 1;
9323               }
9324
9325           if (has_error != 0)
9326             /* Clear the binding label to prevent checking multiple times.  */
9327             sym->binding_label[0] = '\0';
9328         }
9329       else if (bind_c_sym == NULL)
9330         {
9331           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9332           bind_c_sym->where = sym->declared_at;
9333           bind_c_sym->sym_name = sym->name;
9334
9335           if (sym->attr.use_assoc == 1)
9336             bind_c_sym->mod_name = sym->module;
9337           else
9338             if (sym->ns->proc_name != NULL)
9339               bind_c_sym->mod_name = sym->ns->proc_name->name;
9340
9341           if (sym->attr.contained == 0)
9342             {
9343               if (sym->attr.subroutine)
9344                 bind_c_sym->type = GSYM_SUBROUTINE;
9345               else if (sym->attr.function)
9346                 bind_c_sym->type = GSYM_FUNCTION;
9347             }
9348         }
9349     }
9350   return;
9351 }
9352
9353
9354 /* Resolve an index expression.  */
9355
9356 static gfc_try
9357 resolve_index_expr (gfc_expr *e)
9358 {
9359   if (gfc_resolve_expr (e) == FAILURE)
9360     return FAILURE;
9361
9362   if (gfc_simplify_expr (e, 0) == FAILURE)
9363     return FAILURE;
9364
9365   if (gfc_specification_expr (e) == FAILURE)
9366     return FAILURE;
9367
9368   return SUCCESS;
9369 }
9370
9371 /* Resolve a charlen structure.  */
9372
9373 static gfc_try
9374 resolve_charlen (gfc_charlen *cl)
9375 {
9376   int i, k;
9377
9378   if (cl->resolved)
9379     return SUCCESS;
9380
9381   cl->resolved = 1;
9382
9383   specification_expr = 1;
9384
9385   if (resolve_index_expr (cl->length) == FAILURE)
9386     {
9387       specification_expr = 0;
9388       return FAILURE;
9389     }
9390
9391   /* "If the character length parameter value evaluates to a negative
9392      value, the length of character entities declared is zero."  */
9393   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9394     {
9395       if (gfc_option.warn_surprising)
9396         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9397                          " the length has been set to zero",
9398                          &cl->length->where, i);
9399       gfc_replace_expr (cl->length,
9400                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9401     }
9402
9403   /* Check that the character length is not too large.  */
9404   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9405   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9406       && cl->length->ts.type == BT_INTEGER
9407       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9408     {
9409       gfc_error ("String length at %L is too large", &cl->length->where);
9410       return FAILURE;
9411     }
9412
9413   return SUCCESS;
9414 }
9415
9416
9417 /* Test for non-constant shape arrays.  */
9418
9419 static bool
9420 is_non_constant_shape_array (gfc_symbol *sym)
9421 {
9422   gfc_expr *e;
9423   int i;
9424   bool not_constant;
9425
9426   not_constant = false;
9427   if (sym->as != NULL)
9428     {
9429       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9430          has not been simplified; parameter array references.  Do the
9431          simplification now.  */
9432       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9433         {
9434           e = sym->as->lower[i];
9435           if (e && (resolve_index_expr (e) == FAILURE
9436                     || !gfc_is_constant_expr (e)))
9437             not_constant = true;
9438           e = sym->as->upper[i];
9439           if (e && (resolve_index_expr (e) == FAILURE
9440                     || !gfc_is_constant_expr (e)))
9441             not_constant = true;
9442         }
9443     }
9444   return not_constant;
9445 }
9446
9447 /* Given a symbol and an initialization expression, add code to initialize
9448    the symbol to the function entry.  */
9449 static void
9450 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9451 {
9452   gfc_expr *lval;
9453   gfc_code *init_st;
9454   gfc_namespace *ns = sym->ns;
9455
9456   /* Search for the function namespace if this is a contained
9457      function without an explicit result.  */
9458   if (sym->attr.function && sym == sym->result
9459       && sym->name != sym->ns->proc_name->name)
9460     {
9461       ns = ns->contained;
9462       for (;ns; ns = ns->sibling)
9463         if (strcmp (ns->proc_name->name, sym->name) == 0)
9464           break;
9465     }
9466
9467   if (ns == NULL)
9468     {
9469       gfc_free_expr (init);
9470       return;
9471     }
9472
9473   /* Build an l-value expression for the result.  */
9474   lval = gfc_lval_expr_from_sym (sym);
9475
9476   /* Add the code at scope entry.  */
9477   init_st = gfc_get_code ();
9478   init_st->next = ns->code;
9479   ns->code = init_st;
9480
9481   /* Assign the default initializer to the l-value.  */
9482   init_st->loc = sym->declared_at;
9483   init_st->op = EXEC_INIT_ASSIGN;
9484   init_st->expr1 = lval;
9485   init_st->expr2 = init;
9486 }
9487
9488 /* Assign the default initializer to a derived type variable or result.  */
9489
9490 static void
9491 apply_default_init (gfc_symbol *sym)
9492 {
9493   gfc_expr *init = NULL;
9494
9495   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9496     return;
9497
9498   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
9499     init = gfc_default_initializer (&sym->ts);
9500
9501   if (init == NULL)
9502     return;
9503
9504   build_init_assign (sym, init);
9505 }
9506
9507 /* Build an initializer for a local integer, real, complex, logical, or
9508    character variable, based on the command line flags finit-local-zero,
9509    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9510    null if the symbol should not have a default initialization.  */
9511 static gfc_expr *
9512 build_default_init_expr (gfc_symbol *sym)
9513 {
9514   int char_len;
9515   gfc_expr *init_expr;
9516   int i;
9517
9518   /* These symbols should never have a default initialization.  */
9519   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
9520       || sym->attr.external
9521       || sym->attr.dummy
9522       || sym->attr.pointer
9523       || sym->attr.in_equivalence
9524       || sym->attr.in_common
9525       || sym->attr.data
9526       || sym->module
9527       || sym->attr.cray_pointee
9528       || sym->attr.cray_pointer)
9529     return NULL;
9530
9531   /* Now we'll try to build an initializer expression.  */
9532   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
9533                                      &sym->declared_at);
9534
9535   /* We will only initialize integers, reals, complex, logicals, and
9536      characters, and only if the corresponding command-line flags
9537      were set.  Otherwise, we free init_expr and return null.  */
9538   switch (sym->ts.type)
9539     {    
9540     case BT_INTEGER:
9541       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9542         mpz_set_si (init_expr->value.integer, 
9543                          gfc_option.flag_init_integer_value);
9544       else
9545         {
9546           gfc_free_expr (init_expr);
9547           init_expr = NULL;
9548         }
9549       break;
9550
9551     case BT_REAL:
9552       switch (gfc_option.flag_init_real)
9553         {
9554         case GFC_INIT_REAL_SNAN:
9555           init_expr->is_snan = 1;
9556           /* Fall through.  */
9557         case GFC_INIT_REAL_NAN:
9558           mpfr_set_nan (init_expr->value.real);
9559           break;
9560
9561         case GFC_INIT_REAL_INF:
9562           mpfr_set_inf (init_expr->value.real, 1);
9563           break;
9564
9565         case GFC_INIT_REAL_NEG_INF:
9566           mpfr_set_inf (init_expr->value.real, -1);
9567           break;
9568
9569         case GFC_INIT_REAL_ZERO:
9570           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9571           break;
9572
9573         default:
9574           gfc_free_expr (init_expr);
9575           init_expr = NULL;
9576           break;
9577         }
9578       break;
9579           
9580     case BT_COMPLEX:
9581       switch (gfc_option.flag_init_real)
9582         {
9583         case GFC_INIT_REAL_SNAN:
9584           init_expr->is_snan = 1;
9585           /* Fall through.  */
9586         case GFC_INIT_REAL_NAN:
9587           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9588           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9589           break;
9590
9591         case GFC_INIT_REAL_INF:
9592           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
9593           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
9594           break;
9595
9596         case GFC_INIT_REAL_NEG_INF:
9597           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9598           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9599           break;
9600
9601         case GFC_INIT_REAL_ZERO:
9602           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9603           break;
9604
9605         default:
9606           gfc_free_expr (init_expr);
9607           init_expr = NULL;
9608           break;
9609         }
9610       break;
9611           
9612     case BT_LOGICAL:
9613       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9614         init_expr->value.logical = 0;
9615       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9616         init_expr->value.logical = 1;
9617       else
9618         {
9619           gfc_free_expr (init_expr);
9620           init_expr = NULL;
9621         }
9622       break;
9623           
9624     case BT_CHARACTER:
9625       /* For characters, the length must be constant in order to 
9626          create a default initializer.  */
9627       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9628           && sym->ts.u.cl->length
9629           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9630         {
9631           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9632           init_expr->value.character.length = char_len;
9633           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9634           for (i = 0; i < char_len; i++)
9635             init_expr->value.character.string[i]
9636               = (unsigned char) gfc_option.flag_init_character_value;
9637         }
9638       else
9639         {
9640           gfc_free_expr (init_expr);
9641           init_expr = NULL;
9642         }
9643       break;
9644           
9645     default:
9646      gfc_free_expr (init_expr);
9647      init_expr = NULL;
9648     }
9649   return init_expr;
9650 }
9651
9652 /* Add an initialization expression to a local variable.  */
9653 static void
9654 apply_default_init_local (gfc_symbol *sym)
9655 {
9656   gfc_expr *init = NULL;
9657
9658   /* The symbol should be a variable or a function return value.  */
9659   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9660       || (sym->attr.function && sym->result != sym))
9661     return;
9662
9663   /* Try to build the initializer expression.  If we can't initialize
9664      this symbol, then init will be NULL.  */
9665   init = build_default_init_expr (sym);
9666   if (init == NULL)
9667     return;
9668
9669   /* For saved variables, we don't want to add an initializer at 
9670      function entry, so we just add a static initializer.  */
9671   if (sym->attr.save || sym->ns->save_all 
9672       || gfc_option.flag_max_stack_var_size == 0)
9673     {
9674       /* Don't clobber an existing initializer!  */
9675       gcc_assert (sym->value == NULL);
9676       sym->value = init;
9677       return;
9678     }
9679
9680   build_init_assign (sym, init);
9681 }
9682
9683 /* Resolution of common features of flavors variable and procedure.  */
9684
9685 static gfc_try
9686 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9687 {
9688   /* Constraints on deferred shape variable.  */
9689   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9690     {
9691       if (sym->attr.allocatable)
9692         {
9693           if (sym->attr.dimension)
9694             {
9695               gfc_error ("Allocatable array '%s' at %L must have "
9696                          "a deferred shape", sym->name, &sym->declared_at);
9697               return FAILURE;
9698             }
9699           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9700                                    "may not be ALLOCATABLE", sym->name,
9701                                    &sym->declared_at) == FAILURE)
9702             return FAILURE;
9703         }
9704
9705       if (sym->attr.pointer && sym->attr.dimension)
9706         {
9707           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
9708                      sym->name, &sym->declared_at);
9709           return FAILURE;
9710         }
9711     }
9712   else
9713     {
9714       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
9715           && !sym->attr.dummy && sym->ts.type != BT_CLASS && !sym->assoc)
9716         {
9717           gfc_error ("Array '%s' at %L cannot have a deferred shape",
9718                      sym->name, &sym->declared_at);
9719           return FAILURE;
9720          }
9721     }
9722
9723   /* Constraints on polymorphic variables.  */
9724   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
9725     {
9726       /* F03:C502.  */
9727       if (sym->attr.class_ok
9728           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
9729         {
9730           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
9731                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
9732                      &sym->declared_at);
9733           return FAILURE;
9734         }
9735
9736       /* F03:C509.  */
9737       /* Assume that use associated symbols were checked in the module ns.
9738          Class-variables that are associate-names are also something special
9739          and excepted from the test.  */
9740       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
9741         {
9742           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
9743                      "or pointer", sym->name, &sym->declared_at);
9744           return FAILURE;
9745         }
9746     }
9747     
9748   return SUCCESS;
9749 }
9750
9751
9752 /* Additional checks for symbols with flavor variable and derived
9753    type.  To be called from resolve_fl_variable.  */
9754
9755 static gfc_try
9756 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
9757 {
9758   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
9759
9760   /* Check to see if a derived type is blocked from being host
9761      associated by the presence of another class I symbol in the same
9762      namespace.  14.6.1.3 of the standard and the discussion on
9763      comp.lang.fortran.  */
9764   if (sym->ns != sym->ts.u.derived->ns
9765       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
9766     {
9767       gfc_symbol *s;
9768       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
9769       if (s && s->attr.flavor != FL_DERIVED)
9770         {
9771           gfc_error ("The type '%s' cannot be host associated at %L "
9772                      "because it is blocked by an incompatible object "
9773                      "of the same name declared at %L",
9774                      sym->ts.u.derived->name, &sym->declared_at,
9775                      &s->declared_at);
9776           return FAILURE;
9777         }
9778     }
9779
9780   /* 4th constraint in section 11.3: "If an object of a type for which
9781      component-initialization is specified (R429) appears in the
9782      specification-part of a module and does not have the ALLOCATABLE
9783      or POINTER attribute, the object shall have the SAVE attribute."
9784
9785      The check for initializers is performed with
9786      gfc_has_default_initializer because gfc_default_initializer generates
9787      a hidden default for allocatable components.  */
9788   if (!(sym->value || no_init_flag) && sym->ns->proc_name
9789       && sym->ns->proc_name->attr.flavor == FL_MODULE
9790       && !sym->ns->save_all && !sym->attr.save
9791       && !sym->attr.pointer && !sym->attr.allocatable
9792       && gfc_has_default_initializer (sym->ts.u.derived)
9793       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
9794                          "module variable '%s' at %L, needed due to "
9795                          "the default initialization", sym->name,
9796                          &sym->declared_at) == FAILURE)
9797     return FAILURE;
9798
9799   /* Assign default initializer.  */
9800   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
9801       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
9802     {
9803       sym->value = gfc_default_initializer (&sym->ts);
9804     }
9805
9806   return SUCCESS;
9807 }
9808
9809
9810 /* Resolve symbols with flavor variable.  */
9811
9812 static gfc_try
9813 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
9814 {
9815   int no_init_flag, automatic_flag;
9816   gfc_expr *e;
9817   const char *auto_save_msg;
9818
9819   auto_save_msg = "Automatic object '%s' at %L cannot have the "
9820                   "SAVE attribute";
9821
9822   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9823     return FAILURE;
9824
9825   /* Set this flag to check that variables are parameters of all entries.
9826      This check is effected by the call to gfc_resolve_expr through
9827      is_non_constant_shape_array.  */
9828   specification_expr = 1;
9829
9830   if (sym->ns->proc_name
9831       && (sym->ns->proc_name->attr.flavor == FL_MODULE
9832           || sym->ns->proc_name->attr.is_main_program)
9833       && !sym->attr.use_assoc
9834       && !sym->attr.allocatable
9835       && !sym->attr.pointer
9836       && is_non_constant_shape_array (sym))
9837     {
9838       /* The shape of a main program or module array needs to be
9839          constant.  */
9840       gfc_error ("The module or main program array '%s' at %L must "
9841                  "have constant shape", sym->name, &sym->declared_at);
9842       specification_expr = 0;
9843       return FAILURE;
9844     }
9845
9846   if (sym->ts.type == BT_CHARACTER)
9847     {
9848       /* Make sure that character string variables with assumed length are
9849          dummy arguments.  */
9850       e = sym->ts.u.cl->length;
9851       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
9852         {
9853           gfc_error ("Entity with assumed character length at %L must be a "
9854                      "dummy argument or a PARAMETER", &sym->declared_at);
9855           return FAILURE;
9856         }
9857
9858       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
9859         {
9860           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9861           return FAILURE;
9862         }
9863
9864       if (!gfc_is_constant_expr (e)
9865           && !(e->expr_type == EXPR_VARIABLE
9866                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
9867           && sym->ns->proc_name
9868           && (sym->ns->proc_name->attr.flavor == FL_MODULE
9869               || sym->ns->proc_name->attr.is_main_program)
9870           && !sym->attr.use_assoc)
9871         {
9872           gfc_error ("'%s' at %L must have constant character length "
9873                      "in this context", sym->name, &sym->declared_at);
9874           return FAILURE;
9875         }
9876     }
9877
9878   if (sym->value == NULL && sym->attr.referenced)
9879     apply_default_init_local (sym); /* Try to apply a default initialization.  */
9880
9881   /* Determine if the symbol may not have an initializer.  */
9882   no_init_flag = automatic_flag = 0;
9883   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
9884       || sym->attr.intrinsic || sym->attr.result)
9885     no_init_flag = 1;
9886   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
9887            && is_non_constant_shape_array (sym))
9888     {
9889       no_init_flag = automatic_flag = 1;
9890
9891       /* Also, they must not have the SAVE attribute.
9892          SAVE_IMPLICIT is checked below.  */
9893       if (sym->attr.save == SAVE_EXPLICIT)
9894         {
9895           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9896           return FAILURE;
9897         }
9898     }
9899
9900   /* Ensure that any initializer is simplified.  */
9901   if (sym->value)
9902     gfc_simplify_expr (sym->value, 1);
9903
9904   /* Reject illegal initializers.  */
9905   if (!sym->mark && sym->value)
9906     {
9907       if (sym->attr.allocatable)
9908         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
9909                    sym->name, &sym->declared_at);
9910       else if (sym->attr.external)
9911         gfc_error ("External '%s' at %L cannot have an initializer",
9912                    sym->name, &sym->declared_at);
9913       else if (sym->attr.dummy
9914         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
9915         gfc_error ("Dummy '%s' at %L cannot have an initializer",
9916                    sym->name, &sym->declared_at);
9917       else if (sym->attr.intrinsic)
9918         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
9919                    sym->name, &sym->declared_at);
9920       else if (sym->attr.result)
9921         gfc_error ("Function result '%s' at %L cannot have an initializer",
9922                    sym->name, &sym->declared_at);
9923       else if (automatic_flag)
9924         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
9925                    sym->name, &sym->declared_at);
9926       else
9927         goto no_init_error;
9928       return FAILURE;
9929     }
9930
9931 no_init_error:
9932   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
9933     return resolve_fl_variable_derived (sym, no_init_flag);
9934
9935   return SUCCESS;
9936 }
9937
9938
9939 /* Resolve a procedure.  */
9940
9941 static gfc_try
9942 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
9943 {
9944   gfc_formal_arglist *arg;
9945
9946   if (sym->attr.function
9947       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9948     return FAILURE;
9949
9950   if (sym->ts.type == BT_CHARACTER)
9951     {
9952       gfc_charlen *cl = sym->ts.u.cl;
9953
9954       if (cl && cl->length && gfc_is_constant_expr (cl->length)
9955              && resolve_charlen (cl) == FAILURE)
9956         return FAILURE;
9957
9958       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
9959           && sym->attr.proc == PROC_ST_FUNCTION)
9960         {
9961           gfc_error ("Character-valued statement function '%s' at %L must "
9962                      "have constant length", sym->name, &sym->declared_at);
9963           return FAILURE;
9964         }
9965     }
9966
9967   /* Ensure that derived type for are not of a private type.  Internal
9968      module procedures are excluded by 2.2.3.3 - i.e., they are not
9969      externally accessible and can access all the objects accessible in
9970      the host.  */
9971   if (!(sym->ns->parent
9972         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
9973       && gfc_check_access(sym->attr.access, sym->ns->default_access))
9974     {
9975       gfc_interface *iface;
9976
9977       for (arg = sym->formal; arg; arg = arg->next)
9978         {
9979           if (arg->sym
9980               && arg->sym->ts.type == BT_DERIVED
9981               && !arg->sym->ts.u.derived->attr.use_assoc
9982               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9983                                     arg->sym->ts.u.derived->ns->default_access)
9984               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
9985                                  "PRIVATE type and cannot be a dummy argument"
9986                                  " of '%s', which is PUBLIC at %L",
9987                                  arg->sym->name, sym->name, &sym->declared_at)
9988                  == FAILURE)
9989             {
9990               /* Stop this message from recurring.  */
9991               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9992               return FAILURE;
9993             }
9994         }
9995
9996       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9997          PRIVATE to the containing module.  */
9998       for (iface = sym->generic; iface; iface = iface->next)
9999         {
10000           for (arg = iface->sym->formal; arg; arg = arg->next)
10001             {
10002               if (arg->sym
10003                   && arg->sym->ts.type == BT_DERIVED
10004                   && !arg->sym->ts.u.derived->attr.use_assoc
10005                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10006                                         arg->sym->ts.u.derived->ns->default_access)
10007                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10008                                      "'%s' in PUBLIC interface '%s' at %L "
10009                                      "takes dummy arguments of '%s' which is "
10010                                      "PRIVATE", iface->sym->name, sym->name,
10011                                      &iface->sym->declared_at,
10012                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10013                 {
10014                   /* Stop this message from recurring.  */
10015                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10016                   return FAILURE;
10017                 }
10018              }
10019         }
10020
10021       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10022          PRIVATE to the containing module.  */
10023       for (iface = sym->generic; iface; iface = iface->next)
10024         {
10025           for (arg = iface->sym->formal; arg; arg = arg->next)
10026             {
10027               if (arg->sym
10028                   && arg->sym->ts.type == BT_DERIVED
10029                   && !arg->sym->ts.u.derived->attr.use_assoc
10030                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10031                                         arg->sym->ts.u.derived->ns->default_access)
10032                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10033                                      "'%s' in PUBLIC interface '%s' at %L "
10034                                      "takes dummy arguments of '%s' which is "
10035                                      "PRIVATE", iface->sym->name, sym->name,
10036                                      &iface->sym->declared_at,
10037                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10038                 {
10039                   /* Stop this message from recurring.  */
10040                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10041                   return FAILURE;
10042                 }
10043              }
10044         }
10045     }
10046
10047   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10048       && !sym->attr.proc_pointer)
10049     {
10050       gfc_error ("Function '%s' at %L cannot have an initializer",
10051                  sym->name, &sym->declared_at);
10052       return FAILURE;
10053     }
10054
10055   /* An external symbol may not have an initializer because it is taken to be
10056      a procedure. Exception: Procedure Pointers.  */
10057   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10058     {
10059       gfc_error ("External object '%s' at %L may not have an initializer",
10060                  sym->name, &sym->declared_at);
10061       return FAILURE;
10062     }
10063
10064   /* An elemental function is required to return a scalar 12.7.1  */
10065   if (sym->attr.elemental && sym->attr.function && sym->as)
10066     {
10067       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10068                  "result", sym->name, &sym->declared_at);
10069       /* Reset so that the error only occurs once.  */
10070       sym->attr.elemental = 0;
10071       return FAILURE;
10072     }
10073
10074   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10075      char-len-param shall not be array-valued, pointer-valued, recursive
10076      or pure.  ....snip... A character value of * may only be used in the
10077      following ways: (i) Dummy arg of procedure - dummy associates with
10078      actual length; (ii) To declare a named constant; or (iii) External
10079      function - but length must be declared in calling scoping unit.  */
10080   if (sym->attr.function
10081       && sym->ts.type == BT_CHARACTER
10082       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10083     {
10084       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10085           || (sym->attr.recursive) || (sym->attr.pure))
10086         {
10087           if (sym->as && sym->as->rank)
10088             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10089                        "array-valued", sym->name, &sym->declared_at);
10090
10091           if (sym->attr.pointer)
10092             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10093                        "pointer-valued", sym->name, &sym->declared_at);
10094
10095           if (sym->attr.pure)
10096             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10097                        "pure", sym->name, &sym->declared_at);
10098
10099           if (sym->attr.recursive)
10100             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10101                        "recursive", sym->name, &sym->declared_at);
10102
10103           return FAILURE;
10104         }
10105
10106       /* Appendix B.2 of the standard.  Contained functions give an
10107          error anyway.  Fixed-form is likely to be F77/legacy.  */
10108       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
10109         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10110                         "CHARACTER(*) function '%s' at %L",
10111                         sym->name, &sym->declared_at);
10112     }
10113
10114   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10115     {
10116       gfc_formal_arglist *curr_arg;
10117       int has_non_interop_arg = 0;
10118
10119       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10120                              sym->common_block) == FAILURE)
10121         {
10122           /* Clear these to prevent looking at them again if there was an
10123              error.  */
10124           sym->attr.is_bind_c = 0;
10125           sym->attr.is_c_interop = 0;
10126           sym->ts.is_c_interop = 0;
10127         }
10128       else
10129         {
10130           /* So far, no errors have been found.  */
10131           sym->attr.is_c_interop = 1;
10132           sym->ts.is_c_interop = 1;
10133         }
10134       
10135       curr_arg = sym->formal;
10136       while (curr_arg != NULL)
10137         {
10138           /* Skip implicitly typed dummy args here.  */
10139           if (curr_arg->sym->attr.implicit_type == 0)
10140             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
10141               /* If something is found to fail, record the fact so we
10142                  can mark the symbol for the procedure as not being
10143                  BIND(C) to try and prevent multiple errors being
10144                  reported.  */
10145               has_non_interop_arg = 1;
10146           
10147           curr_arg = curr_arg->next;
10148         }
10149
10150       /* See if any of the arguments were not interoperable and if so, clear
10151          the procedure symbol to prevent duplicate error messages.  */
10152       if (has_non_interop_arg != 0)
10153         {
10154           sym->attr.is_c_interop = 0;
10155           sym->ts.is_c_interop = 0;
10156           sym->attr.is_bind_c = 0;
10157         }
10158     }
10159   
10160   if (!sym->attr.proc_pointer)
10161     {
10162       if (sym->attr.save == SAVE_EXPLICIT)
10163         {
10164           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10165                      "in '%s' at %L", sym->name, &sym->declared_at);
10166           return FAILURE;
10167         }
10168       if (sym->attr.intent)
10169         {
10170           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10171                      "in '%s' at %L", sym->name, &sym->declared_at);
10172           return FAILURE;
10173         }
10174       if (sym->attr.subroutine && sym->attr.result)
10175         {
10176           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10177                      "in '%s' at %L", sym->name, &sym->declared_at);
10178           return FAILURE;
10179         }
10180       if (sym->attr.external && sym->attr.function
10181           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10182               || sym->attr.contained))
10183         {
10184           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10185                      "in '%s' at %L", sym->name, &sym->declared_at);
10186           return FAILURE;
10187         }
10188       if (strcmp ("ppr@", sym->name) == 0)
10189         {
10190           gfc_error ("Procedure pointer result '%s' at %L "
10191                      "is missing the pointer attribute",
10192                      sym->ns->proc_name->name, &sym->declared_at);
10193           return FAILURE;
10194         }
10195     }
10196
10197   return SUCCESS;
10198 }
10199
10200
10201 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10202    been defined and we now know their defined arguments, check that they fulfill
10203    the requirements of the standard for procedures used as finalizers.  */
10204
10205 static gfc_try
10206 gfc_resolve_finalizers (gfc_symbol* derived)
10207 {
10208   gfc_finalizer* list;
10209   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10210   gfc_try result = SUCCESS;
10211   bool seen_scalar = false;
10212
10213   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10214     return SUCCESS;
10215
10216   /* Walk over the list of finalizer-procedures, check them, and if any one
10217      does not fit in with the standard's definition, print an error and remove
10218      it from the list.  */
10219   prev_link = &derived->f2k_derived->finalizers;
10220   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10221     {
10222       gfc_symbol* arg;
10223       gfc_finalizer* i;
10224       int my_rank;
10225
10226       /* Skip this finalizer if we already resolved it.  */
10227       if (list->proc_tree)
10228         {
10229           prev_link = &(list->next);
10230           continue;
10231         }
10232
10233       /* Check this exists and is a SUBROUTINE.  */
10234       if (!list->proc_sym->attr.subroutine)
10235         {
10236           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10237                      list->proc_sym->name, &list->where);
10238           goto error;
10239         }
10240
10241       /* We should have exactly one argument.  */
10242       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10243         {
10244           gfc_error ("FINAL procedure at %L must have exactly one argument",
10245                      &list->where);
10246           goto error;
10247         }
10248       arg = list->proc_sym->formal->sym;
10249
10250       /* This argument must be of our type.  */
10251       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10252         {
10253           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10254                      &arg->declared_at, derived->name);
10255           goto error;
10256         }
10257
10258       /* It must neither be a pointer nor allocatable nor optional.  */
10259       if (arg->attr.pointer)
10260         {
10261           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10262                      &arg->declared_at);
10263           goto error;
10264         }
10265       if (arg->attr.allocatable)
10266         {
10267           gfc_error ("Argument of FINAL procedure at %L must not be"
10268                      " ALLOCATABLE", &arg->declared_at);
10269           goto error;
10270         }
10271       if (arg->attr.optional)
10272         {
10273           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10274                      &arg->declared_at);
10275           goto error;
10276         }
10277
10278       /* It must not be INTENT(OUT).  */
10279       if (arg->attr.intent == INTENT_OUT)
10280         {
10281           gfc_error ("Argument of FINAL procedure at %L must not be"
10282                      " INTENT(OUT)", &arg->declared_at);
10283           goto error;
10284         }
10285
10286       /* Warn if the procedure is non-scalar and not assumed shape.  */
10287       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10288           && arg->as->type != AS_ASSUMED_SHAPE)
10289         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10290                      " shape argument", &arg->declared_at);
10291
10292       /* Check that it does not match in kind and rank with a FINAL procedure
10293          defined earlier.  To really loop over the *earlier* declarations,
10294          we need to walk the tail of the list as new ones were pushed at the
10295          front.  */
10296       /* TODO: Handle kind parameters once they are implemented.  */
10297       my_rank = (arg->as ? arg->as->rank : 0);
10298       for (i = list->next; i; i = i->next)
10299         {
10300           /* Argument list might be empty; that is an error signalled earlier,
10301              but we nevertheless continued resolving.  */
10302           if (i->proc_sym->formal)
10303             {
10304               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10305               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10306               if (i_rank == my_rank)
10307                 {
10308                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10309                              " rank (%d) as '%s'",
10310                              list->proc_sym->name, &list->where, my_rank, 
10311                              i->proc_sym->name);
10312                   goto error;
10313                 }
10314             }
10315         }
10316
10317         /* Is this the/a scalar finalizer procedure?  */
10318         if (!arg->as || arg->as->rank == 0)
10319           seen_scalar = true;
10320
10321         /* Find the symtree for this procedure.  */
10322         gcc_assert (!list->proc_tree);
10323         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10324
10325         prev_link = &list->next;
10326         continue;
10327
10328         /* Remove wrong nodes immediately from the list so we don't risk any
10329            troubles in the future when they might fail later expectations.  */
10330 error:
10331         result = FAILURE;
10332         i = list;
10333         *prev_link = list->next;
10334         gfc_free_finalizer (i);
10335     }
10336
10337   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10338      were nodes in the list, must have been for arrays.  It is surely a good
10339      idea to have a scalar version there if there's something to finalize.  */
10340   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10341     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10342                  " defined at %L, suggest also scalar one",
10343                  derived->name, &derived->declared_at);
10344
10345   /* TODO:  Remove this error when finalization is finished.  */
10346   gfc_error ("Finalization at %L is not yet implemented",
10347              &derived->declared_at);
10348
10349   return result;
10350 }
10351
10352
10353 /* Check that it is ok for the typebound procedure proc to override the
10354    procedure old.  */
10355
10356 static gfc_try
10357 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
10358 {
10359   locus where;
10360   const gfc_symbol* proc_target;
10361   const gfc_symbol* old_target;
10362   unsigned proc_pass_arg, old_pass_arg, argpos;
10363   gfc_formal_arglist* proc_formal;
10364   gfc_formal_arglist* old_formal;
10365
10366   /* This procedure should only be called for non-GENERIC proc.  */
10367   gcc_assert (!proc->n.tb->is_generic);
10368
10369   /* If the overwritten procedure is GENERIC, this is an error.  */
10370   if (old->n.tb->is_generic)
10371     {
10372       gfc_error ("Can't overwrite GENERIC '%s' at %L",
10373                  old->name, &proc->n.tb->where);
10374       return FAILURE;
10375     }
10376
10377   where = proc->n.tb->where;
10378   proc_target = proc->n.tb->u.specific->n.sym;
10379   old_target = old->n.tb->u.specific->n.sym;
10380
10381   /* Check that overridden binding is not NON_OVERRIDABLE.  */
10382   if (old->n.tb->non_overridable)
10383     {
10384       gfc_error ("'%s' at %L overrides a procedure binding declared"
10385                  " NON_OVERRIDABLE", proc->name, &where);
10386       return FAILURE;
10387     }
10388
10389   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
10390   if (!old->n.tb->deferred && proc->n.tb->deferred)
10391     {
10392       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
10393                  " non-DEFERRED binding", proc->name, &where);
10394       return FAILURE;
10395     }
10396
10397   /* If the overridden binding is PURE, the overriding must be, too.  */
10398   if (old_target->attr.pure && !proc_target->attr.pure)
10399     {
10400       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
10401                  proc->name, &where);
10402       return FAILURE;
10403     }
10404
10405   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
10406      is not, the overriding must not be either.  */
10407   if (old_target->attr.elemental && !proc_target->attr.elemental)
10408     {
10409       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
10410                  " ELEMENTAL", proc->name, &where);
10411       return FAILURE;
10412     }
10413   if (!old_target->attr.elemental && proc_target->attr.elemental)
10414     {
10415       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
10416                  " be ELEMENTAL, either", proc->name, &where);
10417       return FAILURE;
10418     }
10419
10420   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
10421      SUBROUTINE.  */
10422   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
10423     {
10424       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
10425                  " SUBROUTINE", proc->name, &where);
10426       return FAILURE;
10427     }
10428
10429   /* If the overridden binding is a FUNCTION, the overriding must also be a
10430      FUNCTION and have the same characteristics.  */
10431   if (old_target->attr.function)
10432     {
10433       if (!proc_target->attr.function)
10434         {
10435           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
10436                      " FUNCTION", proc->name, &where);
10437           return FAILURE;
10438         }
10439
10440       /* FIXME:  Do more comprehensive checking (including, for instance, the
10441          rank and array-shape).  */
10442       gcc_assert (proc_target->result && old_target->result);
10443       if (!gfc_compare_types (&proc_target->result->ts,
10444                               &old_target->result->ts))
10445         {
10446           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
10447                      " matching result types", proc->name, &where);
10448           return FAILURE;
10449         }
10450     }
10451
10452   /* If the overridden binding is PUBLIC, the overriding one must not be
10453      PRIVATE.  */
10454   if (old->n.tb->access == ACCESS_PUBLIC
10455       && proc->n.tb->access == ACCESS_PRIVATE)
10456     {
10457       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
10458                  " PRIVATE", proc->name, &where);
10459       return FAILURE;
10460     }
10461
10462   /* Compare the formal argument lists of both procedures.  This is also abused
10463      to find the position of the passed-object dummy arguments of both
10464      bindings as at least the overridden one might not yet be resolved and we
10465      need those positions in the check below.  */
10466   proc_pass_arg = old_pass_arg = 0;
10467   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
10468     proc_pass_arg = 1;
10469   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
10470     old_pass_arg = 1;
10471   argpos = 1;
10472   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
10473        proc_formal && old_formal;
10474        proc_formal = proc_formal->next, old_formal = old_formal->next)
10475     {
10476       if (proc->n.tb->pass_arg
10477           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
10478         proc_pass_arg = argpos;
10479       if (old->n.tb->pass_arg
10480           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
10481         old_pass_arg = argpos;
10482
10483       /* Check that the names correspond.  */
10484       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
10485         {
10486           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
10487                      " to match the corresponding argument of the overridden"
10488                      " procedure", proc_formal->sym->name, proc->name, &where,
10489                      old_formal->sym->name);
10490           return FAILURE;
10491         }
10492
10493       /* Check that the types correspond if neither is the passed-object
10494          argument.  */
10495       /* FIXME:  Do more comprehensive testing here.  */
10496       if (proc_pass_arg != argpos && old_pass_arg != argpos
10497           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
10498         {
10499           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
10500                      "in respect to the overridden procedure",
10501                      proc_formal->sym->name, proc->name, &where);
10502           return FAILURE;
10503         }
10504
10505       ++argpos;
10506     }
10507   if (proc_formal || old_formal)
10508     {
10509       gfc_error ("'%s' at %L must have the same number of formal arguments as"
10510                  " the overridden procedure", proc->name, &where);
10511       return FAILURE;
10512     }
10513
10514   /* If the overridden binding is NOPASS, the overriding one must also be
10515      NOPASS.  */
10516   if (old->n.tb->nopass && !proc->n.tb->nopass)
10517     {
10518       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
10519                  " NOPASS", proc->name, &where);
10520       return FAILURE;
10521     }
10522
10523   /* If the overridden binding is PASS(x), the overriding one must also be
10524      PASS and the passed-object dummy arguments must correspond.  */
10525   if (!old->n.tb->nopass)
10526     {
10527       if (proc->n.tb->nopass)
10528         {
10529           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
10530                      " PASS", proc->name, &where);
10531           return FAILURE;
10532         }
10533
10534       if (proc_pass_arg != old_pass_arg)
10535         {
10536           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
10537                      " the same position as the passed-object dummy argument of"
10538                      " the overridden procedure", proc->name, &where);
10539           return FAILURE;
10540         }
10541     }
10542
10543   return SUCCESS;
10544 }
10545
10546
10547 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10548
10549 static gfc_try
10550 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10551                              const char* generic_name, locus where)
10552 {
10553   gfc_symbol* sym1;
10554   gfc_symbol* sym2;
10555
10556   gcc_assert (t1->specific && t2->specific);
10557   gcc_assert (!t1->specific->is_generic);
10558   gcc_assert (!t2->specific->is_generic);
10559
10560   sym1 = t1->specific->u.specific->n.sym;
10561   sym2 = t2->specific->u.specific->n.sym;
10562
10563   if (sym1 == sym2)
10564     return SUCCESS;
10565
10566   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10567   if (sym1->attr.subroutine != sym2->attr.subroutine
10568       || sym1->attr.function != sym2->attr.function)
10569     {
10570       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10571                  " GENERIC '%s' at %L",
10572                  sym1->name, sym2->name, generic_name, &where);
10573       return FAILURE;
10574     }
10575
10576   /* Compare the interfaces.  */
10577   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10578     {
10579       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10580                  sym1->name, sym2->name, generic_name, &where);
10581       return FAILURE;
10582     }
10583
10584   return SUCCESS;
10585 }
10586
10587
10588 /* Worker function for resolving a generic procedure binding; this is used to
10589    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10590
10591    The difference between those cases is finding possible inherited bindings
10592    that are overridden, as one has to look for them in tb_sym_root,
10593    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10594    the super-type and set p->overridden correctly.  */
10595
10596 static gfc_try
10597 resolve_tb_generic_targets (gfc_symbol* super_type,
10598                             gfc_typebound_proc* p, const char* name)
10599 {
10600   gfc_tbp_generic* target;
10601   gfc_symtree* first_target;
10602   gfc_symtree* inherited;
10603
10604   gcc_assert (p && p->is_generic);
10605
10606   /* Try to find the specific bindings for the symtrees in our target-list.  */
10607   gcc_assert (p->u.generic);
10608   for (target = p->u.generic; target; target = target->next)
10609     if (!target->specific)
10610       {
10611         gfc_typebound_proc* overridden_tbp;
10612         gfc_tbp_generic* g;
10613         const char* target_name;
10614
10615         target_name = target->specific_st->name;
10616
10617         /* Defined for this type directly.  */
10618         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
10619           {
10620             target->specific = target->specific_st->n.tb;
10621             goto specific_found;
10622           }
10623
10624         /* Look for an inherited specific binding.  */
10625         if (super_type)
10626           {
10627             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10628                                                  true, NULL);
10629
10630             if (inherited)
10631               {
10632                 gcc_assert (inherited->n.tb);
10633                 target->specific = inherited->n.tb;
10634                 goto specific_found;
10635               }
10636           }
10637
10638         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10639                    " at %L", target_name, name, &p->where);
10640         return FAILURE;
10641
10642         /* Once we've found the specific binding, check it is not ambiguous with
10643            other specifics already found or inherited for the same GENERIC.  */
10644 specific_found:
10645         gcc_assert (target->specific);
10646
10647         /* This must really be a specific binding!  */
10648         if (target->specific->is_generic)
10649           {
10650             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10651                        " '%s' is GENERIC, too", name, &p->where, target_name);
10652             return FAILURE;
10653           }
10654
10655         /* Check those already resolved on this type directly.  */
10656         for (g = p->u.generic; g; g = g->next)
10657           if (g != target && g->specific
10658               && check_generic_tbp_ambiguity (target, g, name, p->where)
10659                   == FAILURE)
10660             return FAILURE;
10661
10662         /* Check for ambiguity with inherited specific targets.  */
10663         for (overridden_tbp = p->overridden; overridden_tbp;
10664              overridden_tbp = overridden_tbp->overridden)
10665           if (overridden_tbp->is_generic)
10666             {
10667               for (g = overridden_tbp->u.generic; g; g = g->next)
10668                 {
10669                   gcc_assert (g->specific);
10670                   if (check_generic_tbp_ambiguity (target, g,
10671                                                    name, p->where) == FAILURE)
10672                     return FAILURE;
10673                 }
10674             }
10675       }
10676
10677   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10678   if (p->overridden && !p->overridden->is_generic)
10679     {
10680       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10681                  " the same name", name, &p->where);
10682       return FAILURE;
10683     }
10684
10685   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10686      all must have the same attributes here.  */
10687   first_target = p->u.generic->specific->u.specific;
10688   gcc_assert (first_target);
10689   p->subroutine = first_target->n.sym->attr.subroutine;
10690   p->function = first_target->n.sym->attr.function;
10691
10692   return SUCCESS;
10693 }
10694
10695
10696 /* Resolve a GENERIC procedure binding for a derived type.  */
10697
10698 static gfc_try
10699 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10700 {
10701   gfc_symbol* super_type;
10702
10703   /* Find the overridden binding if any.  */
10704   st->n.tb->overridden = NULL;
10705   super_type = gfc_get_derived_super_type (derived);
10706   if (super_type)
10707     {
10708       gfc_symtree* overridden;
10709       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10710                                             true, NULL);
10711
10712       if (overridden && overridden->n.tb)
10713         st->n.tb->overridden = overridden->n.tb;
10714     }
10715
10716   /* Resolve using worker function.  */
10717   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10718 }
10719
10720
10721 /* Retrieve the target-procedure of an operator binding and do some checks in
10722    common for intrinsic and user-defined type-bound operators.  */
10723
10724 static gfc_symbol*
10725 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10726 {
10727   gfc_symbol* target_proc;
10728
10729   gcc_assert (target->specific && !target->specific->is_generic);
10730   target_proc = target->specific->u.specific->n.sym;
10731   gcc_assert (target_proc);
10732
10733   /* All operator bindings must have a passed-object dummy argument.  */
10734   if (target->specific->nopass)
10735     {
10736       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10737       return NULL;
10738     }
10739
10740   return target_proc;
10741 }
10742
10743
10744 /* Resolve a type-bound intrinsic operator.  */
10745
10746 static gfc_try
10747 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10748                                 gfc_typebound_proc* p)
10749 {
10750   gfc_symbol* super_type;
10751   gfc_tbp_generic* target;
10752   
10753   /* If there's already an error here, do nothing (but don't fail again).  */
10754   if (p->error)
10755     return SUCCESS;
10756
10757   /* Operators should always be GENERIC bindings.  */
10758   gcc_assert (p->is_generic);
10759
10760   /* Look for an overridden binding.  */
10761   super_type = gfc_get_derived_super_type (derived);
10762   if (super_type && super_type->f2k_derived)
10763     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10764                                                      op, true, NULL);
10765   else
10766     p->overridden = NULL;
10767
10768   /* Resolve general GENERIC properties using worker function.  */
10769   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10770     goto error;
10771
10772   /* Check the targets to be procedures of correct interface.  */
10773   for (target = p->u.generic; target; target = target->next)
10774     {
10775       gfc_symbol* target_proc;
10776
10777       target_proc = get_checked_tb_operator_target (target, p->where);
10778       if (!target_proc)
10779         goto error;
10780
10781       if (!gfc_check_operator_interface (target_proc, op, p->where))
10782         goto error;
10783     }
10784
10785   return SUCCESS;
10786
10787 error:
10788   p->error = 1;
10789   return FAILURE;
10790 }
10791
10792
10793 /* Resolve a type-bound user operator (tree-walker callback).  */
10794
10795 static gfc_symbol* resolve_bindings_derived;
10796 static gfc_try resolve_bindings_result;
10797
10798 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10799
10800 static void
10801 resolve_typebound_user_op (gfc_symtree* stree)
10802 {
10803   gfc_symbol* super_type;
10804   gfc_tbp_generic* target;
10805
10806   gcc_assert (stree && stree->n.tb);
10807
10808   if (stree->n.tb->error)
10809     return;
10810
10811   /* Operators should always be GENERIC bindings.  */
10812   gcc_assert (stree->n.tb->is_generic);
10813
10814   /* Find overridden procedure, if any.  */
10815   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10816   if (super_type && super_type->f2k_derived)
10817     {
10818       gfc_symtree* overridden;
10819       overridden = gfc_find_typebound_user_op (super_type, NULL,
10820                                                stree->name, true, NULL);
10821
10822       if (overridden && overridden->n.tb)
10823         stree->n.tb->overridden = overridden->n.tb;
10824     }
10825   else
10826     stree->n.tb->overridden = NULL;
10827
10828   /* Resolve basically using worker function.  */
10829   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10830         == FAILURE)
10831     goto error;
10832
10833   /* Check the targets to be functions of correct interface.  */
10834   for (target = stree->n.tb->u.generic; target; target = target->next)
10835     {
10836       gfc_symbol* target_proc;
10837
10838       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
10839       if (!target_proc)
10840         goto error;
10841
10842       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
10843         goto error;
10844     }
10845
10846   return;
10847
10848 error:
10849   resolve_bindings_result = FAILURE;
10850   stree->n.tb->error = 1;
10851 }
10852
10853
10854 /* Resolve the type-bound procedures for a derived type.  */
10855
10856 static void
10857 resolve_typebound_procedure (gfc_symtree* stree)
10858 {
10859   gfc_symbol* proc;
10860   locus where;
10861   gfc_symbol* me_arg;
10862   gfc_symbol* super_type;
10863   gfc_component* comp;
10864
10865   gcc_assert (stree);
10866
10867   /* Undefined specific symbol from GENERIC target definition.  */
10868   if (!stree->n.tb)
10869     return;
10870
10871   if (stree->n.tb->error)
10872     return;
10873
10874   /* If this is a GENERIC binding, use that routine.  */
10875   if (stree->n.tb->is_generic)
10876     {
10877       if (resolve_typebound_generic (resolve_bindings_derived, stree)
10878             == FAILURE)
10879         goto error;
10880       return;
10881     }
10882
10883   /* Get the target-procedure to check it.  */
10884   gcc_assert (!stree->n.tb->is_generic);
10885   gcc_assert (stree->n.tb->u.specific);
10886   proc = stree->n.tb->u.specific->n.sym;
10887   where = stree->n.tb->where;
10888
10889   /* Default access should already be resolved from the parser.  */
10890   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
10891
10892   /* It should be a module procedure or an external procedure with explicit
10893      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
10894   if ((!proc->attr.subroutine && !proc->attr.function)
10895       || (proc->attr.proc != PROC_MODULE
10896           && proc->attr.if_source != IFSRC_IFBODY)
10897       || (proc->attr.abstract && !stree->n.tb->deferred))
10898     {
10899       gfc_error ("'%s' must be a module procedure or an external procedure with"
10900                  " an explicit interface at %L", proc->name, &where);
10901       goto error;
10902     }
10903   stree->n.tb->subroutine = proc->attr.subroutine;
10904   stree->n.tb->function = proc->attr.function;
10905
10906   /* Find the super-type of the current derived type.  We could do this once and
10907      store in a global if speed is needed, but as long as not I believe this is
10908      more readable and clearer.  */
10909   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10910
10911   /* If PASS, resolve and check arguments if not already resolved / loaded
10912      from a .mod file.  */
10913   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
10914     {
10915       if (stree->n.tb->pass_arg)
10916         {
10917           gfc_formal_arglist* i;
10918
10919           /* If an explicit passing argument name is given, walk the arg-list
10920              and look for it.  */
10921
10922           me_arg = NULL;
10923           stree->n.tb->pass_arg_num = 1;
10924           for (i = proc->formal; i; i = i->next)
10925             {
10926               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
10927                 {
10928                   me_arg = i->sym;
10929                   break;
10930                 }
10931               ++stree->n.tb->pass_arg_num;
10932             }
10933
10934           if (!me_arg)
10935             {
10936               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
10937                          " argument '%s'",
10938                          proc->name, stree->n.tb->pass_arg, &where,
10939                          stree->n.tb->pass_arg);
10940               goto error;
10941             }
10942         }
10943       else
10944         {
10945           /* Otherwise, take the first one; there should in fact be at least
10946              one.  */
10947           stree->n.tb->pass_arg_num = 1;
10948           if (!proc->formal)
10949             {
10950               gfc_error ("Procedure '%s' with PASS at %L must have at"
10951                          " least one argument", proc->name, &where);
10952               goto error;
10953             }
10954           me_arg = proc->formal->sym;
10955         }
10956
10957       /* Now check that the argument-type matches and the passed-object
10958          dummy argument is generally fine.  */
10959
10960       gcc_assert (me_arg);
10961
10962       if (me_arg->ts.type != BT_CLASS)
10963         {
10964           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10965                      " at %L", proc->name, &where);
10966           goto error;
10967         }
10968
10969       if (CLASS_DATA (me_arg)->ts.u.derived
10970           != resolve_bindings_derived)
10971         {
10972           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10973                      " the derived-type '%s'", me_arg->name, proc->name,
10974                      me_arg->name, &where, resolve_bindings_derived->name);
10975           goto error;
10976         }
10977   
10978       gcc_assert (me_arg->ts.type == BT_CLASS);
10979       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
10980         {
10981           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
10982                      " scalar", proc->name, &where);
10983           goto error;
10984         }
10985       if (CLASS_DATA (me_arg)->attr.allocatable)
10986         {
10987           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10988                      " be ALLOCATABLE", proc->name, &where);
10989           goto error;
10990         }
10991       if (CLASS_DATA (me_arg)->attr.class_pointer)
10992         {
10993           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10994                      " be POINTER", proc->name, &where);
10995           goto error;
10996         }
10997     }
10998
10999   /* If we are extending some type, check that we don't override a procedure
11000      flagged NON_OVERRIDABLE.  */
11001   stree->n.tb->overridden = NULL;
11002   if (super_type)
11003     {
11004       gfc_symtree* overridden;
11005       overridden = gfc_find_typebound_proc (super_type, NULL,
11006                                             stree->name, true, NULL);
11007
11008       if (overridden && overridden->n.tb)
11009         stree->n.tb->overridden = overridden->n.tb;
11010
11011       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
11012         goto error;
11013     }
11014
11015   /* See if there's a name collision with a component directly in this type.  */
11016   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11017     if (!strcmp (comp->name, stree->name))
11018       {
11019         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11020                    " '%s'",
11021                    stree->name, &where, resolve_bindings_derived->name);
11022         goto error;
11023       }
11024
11025   /* Try to find a name collision with an inherited component.  */
11026   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11027     {
11028       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11029                  " component of '%s'",
11030                  stree->name, &where, resolve_bindings_derived->name);
11031       goto error;
11032     }
11033
11034   stree->n.tb->error = 0;
11035   return;
11036
11037 error:
11038   resolve_bindings_result = FAILURE;
11039   stree->n.tb->error = 1;
11040 }
11041
11042 static gfc_try
11043 resolve_typebound_procedures (gfc_symbol* derived)
11044 {
11045   int op;
11046
11047   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11048     return SUCCESS;
11049
11050   resolve_bindings_derived = derived;
11051   resolve_bindings_result = SUCCESS;
11052
11053   if (derived->f2k_derived->tb_sym_root)
11054     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11055                           &resolve_typebound_procedure);
11056
11057   if (derived->f2k_derived->tb_uop_root)
11058     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11059                           &resolve_typebound_user_op);
11060
11061   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11062     {
11063       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11064       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11065                                                p) == FAILURE)
11066         resolve_bindings_result = FAILURE;
11067     }
11068
11069   return resolve_bindings_result;
11070 }
11071
11072
11073 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11074    to give all identical derived types the same backend_decl.  */
11075 static void
11076 add_dt_to_dt_list (gfc_symbol *derived)
11077 {
11078   gfc_dt_list *dt_list;
11079
11080   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11081     if (derived == dt_list->derived)
11082       break;
11083
11084   if (dt_list == NULL)
11085     {
11086       dt_list = gfc_get_dt_list ();
11087       dt_list->next = gfc_derived_types;
11088       dt_list->derived = derived;
11089       gfc_derived_types = dt_list;
11090     }
11091 }
11092
11093
11094 /* Ensure that a derived-type is really not abstract, meaning that every
11095    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11096
11097 static gfc_try
11098 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11099 {
11100   if (!st)
11101     return SUCCESS;
11102
11103   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11104     return FAILURE;
11105   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11106     return FAILURE;
11107
11108   if (st->n.tb && st->n.tb->deferred)
11109     {
11110       gfc_symtree* overriding;
11111       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11112       if (!overriding)
11113         return FAILURE;
11114       gcc_assert (overriding->n.tb);
11115       if (overriding->n.tb->deferred)
11116         {
11117           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11118                      " '%s' is DEFERRED and not overridden",
11119                      sub->name, &sub->declared_at, st->name);
11120           return FAILURE;
11121         }
11122     }
11123
11124   return SUCCESS;
11125 }
11126
11127 static gfc_try
11128 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11129 {
11130   /* The algorithm used here is to recursively travel up the ancestry of sub
11131      and for each ancestor-type, check all bindings.  If any of them is
11132      DEFERRED, look it up starting from sub and see if the found (overriding)
11133      binding is not DEFERRED.
11134      This is not the most efficient way to do this, but it should be ok and is
11135      clearer than something sophisticated.  */
11136
11137   gcc_assert (ancestor && !sub->attr.abstract);
11138   
11139   if (!ancestor->attr.abstract)
11140     return SUCCESS;
11141
11142   /* Walk bindings of this ancestor.  */
11143   if (ancestor->f2k_derived)
11144     {
11145       gfc_try t;
11146       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11147       if (t == FAILURE)
11148         return FAILURE;
11149     }
11150
11151   /* Find next ancestor type and recurse on it.  */
11152   ancestor = gfc_get_derived_super_type (ancestor);
11153   if (ancestor)
11154     return ensure_not_abstract (sub, ancestor);
11155
11156   return SUCCESS;
11157 }
11158
11159
11160 /* Resolve the components of a derived type.  */
11161
11162 static gfc_try
11163 resolve_fl_derived (gfc_symbol *sym)
11164 {
11165   gfc_symbol* super_type;
11166   gfc_component *c;
11167
11168   super_type = gfc_get_derived_super_type (sym);
11169   
11170   if (sym->attr.is_class && sym->ts.u.derived == NULL)
11171     {
11172       /* Fix up incomplete CLASS symbols.  */
11173       gfc_component *data = gfc_find_component (sym, "$data", true, true);
11174       gfc_component *vptr = gfc_find_component (sym, "$vptr", true, true);
11175       if (vptr->ts.u.derived == NULL)
11176         {
11177           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
11178           gcc_assert (vtab);
11179           vptr->ts.u.derived = vtab->ts.u.derived;
11180         }
11181     }
11182
11183   /* F2008, C432. */
11184   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11185     {
11186       gfc_error ("As extending type '%s' at %L has a coarray component, "
11187                  "parent type '%s' shall also have one", sym->name,
11188                  &sym->declared_at, super_type->name);
11189       return FAILURE;
11190     }
11191
11192   /* Ensure the extended type gets resolved before we do.  */
11193   if (super_type && resolve_fl_derived (super_type) == FAILURE)
11194     return FAILURE;
11195
11196   /* An ABSTRACT type must be extensible.  */
11197   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11198     {
11199       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11200                  sym->name, &sym->declared_at);
11201       return FAILURE;
11202     }
11203
11204   for (c = sym->components; c != NULL; c = c->next)
11205     {
11206       /* F2008, C442.  */
11207       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
11208           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11209         {
11210           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11211                      "deferred shape", c->name, &c->loc);
11212           return FAILURE;
11213         }
11214
11215       /* F2008, C443.  */
11216       if (c->attr.codimension && c->ts.type == BT_DERIVED
11217           && c->ts.u.derived->ts.is_iso_c)
11218         {
11219           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11220                      "shall not be a coarray", c->name, &c->loc);
11221           return FAILURE;
11222         }
11223
11224       /* F2008, C444.  */
11225       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11226           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11227               || c->attr.allocatable))
11228         {
11229           gfc_error ("Component '%s' at %L with coarray component "
11230                      "shall be a nonpointer, nonallocatable scalar",
11231                      c->name, &c->loc);
11232           return FAILURE;
11233         }
11234
11235       /* F2008, C448.  */
11236       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11237         {
11238           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11239                      "is not an array pointer", c->name, &c->loc);
11240           return FAILURE;
11241         }
11242
11243       if (c->attr.proc_pointer && c->ts.interface)
11244         {
11245           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11246             gfc_error ("Interface '%s', used by procedure pointer component "
11247                        "'%s' at %L, is declared in a later PROCEDURE statement",
11248                        c->ts.interface->name, c->name, &c->loc);
11249
11250           /* Get the attributes from the interface (now resolved).  */
11251           if (c->ts.interface->attr.if_source
11252               || c->ts.interface->attr.intrinsic)
11253             {
11254               gfc_symbol *ifc = c->ts.interface;
11255
11256               if (ifc->formal && !ifc->formal_ns)
11257                 resolve_symbol (ifc);
11258
11259               if (ifc->attr.intrinsic)
11260                 resolve_intrinsic (ifc, &ifc->declared_at);
11261
11262               if (ifc->result)
11263                 {
11264                   c->ts = ifc->result->ts;
11265                   c->attr.allocatable = ifc->result->attr.allocatable;
11266                   c->attr.pointer = ifc->result->attr.pointer;
11267                   c->attr.dimension = ifc->result->attr.dimension;
11268                   c->as = gfc_copy_array_spec (ifc->result->as);
11269                 }
11270               else
11271                 {   
11272                   c->ts = ifc->ts;
11273                   c->attr.allocatable = ifc->attr.allocatable;
11274                   c->attr.pointer = ifc->attr.pointer;
11275                   c->attr.dimension = ifc->attr.dimension;
11276                   c->as = gfc_copy_array_spec (ifc->as);
11277                 }
11278               c->ts.interface = ifc;
11279               c->attr.function = ifc->attr.function;
11280               c->attr.subroutine = ifc->attr.subroutine;
11281               gfc_copy_formal_args_ppc (c, ifc);
11282
11283               c->attr.pure = ifc->attr.pure;
11284               c->attr.elemental = ifc->attr.elemental;
11285               c->attr.recursive = ifc->attr.recursive;
11286               c->attr.always_explicit = ifc->attr.always_explicit;
11287               c->attr.ext_attr |= ifc->attr.ext_attr;
11288               /* Replace symbols in array spec.  */
11289               if (c->as)
11290                 {
11291                   int i;
11292                   for (i = 0; i < c->as->rank; i++)
11293                     {
11294                       gfc_expr_replace_comp (c->as->lower[i], c);
11295                       gfc_expr_replace_comp (c->as->upper[i], c);
11296                     }
11297                 }
11298               /* Copy char length.  */
11299               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11300                 {
11301                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11302                   gfc_expr_replace_comp (cl->length, c);
11303                   if (cl->length && !cl->resolved
11304                         && gfc_resolve_expr (cl->length) == FAILURE)
11305                     return FAILURE;
11306                   c->ts.u.cl = cl;
11307                 }
11308             }
11309           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11310             {
11311               gfc_error ("Interface '%s' of procedure pointer component "
11312                          "'%s' at %L must be explicit", c->ts.interface->name,
11313                          c->name, &c->loc);
11314               return FAILURE;
11315             }
11316         }
11317       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11318         {
11319           /* Since PPCs are not implicitly typed, a PPC without an explicit
11320              interface must be a subroutine.  */
11321           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11322         }
11323
11324       /* Procedure pointer components: Check PASS arg.  */
11325       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11326           && !sym->attr.vtype)
11327         {
11328           gfc_symbol* me_arg;
11329
11330           if (c->tb->pass_arg)
11331             {
11332               gfc_formal_arglist* i;
11333
11334               /* If an explicit passing argument name is given, walk the arg-list
11335                 and look for it.  */
11336
11337               me_arg = NULL;
11338               c->tb->pass_arg_num = 1;
11339               for (i = c->formal; i; i = i->next)
11340                 {
11341                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11342                     {
11343                       me_arg = i->sym;
11344                       break;
11345                     }
11346                   c->tb->pass_arg_num++;
11347                 }
11348
11349               if (!me_arg)
11350                 {
11351                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11352                              "at %L has no argument '%s'", c->name,
11353                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11354                   c->tb->error = 1;
11355                   return FAILURE;
11356                 }
11357             }
11358           else
11359             {
11360               /* Otherwise, take the first one; there should in fact be at least
11361                 one.  */
11362               c->tb->pass_arg_num = 1;
11363               if (!c->formal)
11364                 {
11365                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11366                              "must have at least one argument",
11367                              c->name, &c->loc);
11368                   c->tb->error = 1;
11369                   return FAILURE;
11370                 }
11371               me_arg = c->formal->sym;
11372             }
11373
11374           /* Now check that the argument-type matches.  */
11375           gcc_assert (me_arg);
11376           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11377               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11378               || (me_arg->ts.type == BT_CLASS
11379                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11380             {
11381               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11382                          " the derived type '%s'", me_arg->name, c->name,
11383                          me_arg->name, &c->loc, sym->name);
11384               c->tb->error = 1;
11385               return FAILURE;
11386             }
11387
11388           /* Check for C453.  */
11389           if (me_arg->attr.dimension)
11390             {
11391               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11392                          "must be scalar", me_arg->name, c->name, me_arg->name,
11393                          &c->loc);
11394               c->tb->error = 1;
11395               return FAILURE;
11396             }
11397
11398           if (me_arg->attr.pointer)
11399             {
11400               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11401                          "may not have the POINTER attribute", me_arg->name,
11402                          c->name, me_arg->name, &c->loc);
11403               c->tb->error = 1;
11404               return FAILURE;
11405             }
11406
11407           if (me_arg->attr.allocatable)
11408             {
11409               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11410                          "may not be ALLOCATABLE", me_arg->name, c->name,
11411                          me_arg->name, &c->loc);
11412               c->tb->error = 1;
11413               return FAILURE;
11414             }
11415
11416           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11417             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11418                        " at %L", c->name, &c->loc);
11419
11420         }
11421
11422       /* Check type-spec if this is not the parent-type component.  */
11423       if ((!sym->attr.extension || c != sym->components)
11424           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11425         return FAILURE;
11426
11427       /* If this type is an extension, set the accessibility of the parent
11428          component.  */
11429       if (super_type && c == sym->components
11430           && strcmp (super_type->name, c->name) == 0)
11431         c->attr.access = super_type->attr.access;
11432       
11433       /* If this type is an extension, see if this component has the same name
11434          as an inherited type-bound procedure.  */
11435       if (super_type && !sym->attr.is_class
11436           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11437         {
11438           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11439                      " inherited type-bound procedure",
11440                      c->name, sym->name, &c->loc);
11441           return FAILURE;
11442         }
11443
11444       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
11445         {
11446          if (c->ts.u.cl->length == NULL
11447              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11448              || !gfc_is_constant_expr (c->ts.u.cl->length))
11449            {
11450              gfc_error ("Character length of component '%s' needs to "
11451                         "be a constant specification expression at %L",
11452                         c->name,
11453                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11454              return FAILURE;
11455            }
11456         }
11457
11458       if (c->ts.type == BT_DERIVED
11459           && sym->component_access != ACCESS_PRIVATE
11460           && gfc_check_access (sym->attr.access, sym->ns->default_access)
11461           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11462           && !c->ts.u.derived->attr.use_assoc
11463           && !gfc_check_access (c->ts.u.derived->attr.access,
11464                                 c->ts.u.derived->ns->default_access)
11465           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11466                              "is a PRIVATE type and cannot be a component of "
11467                              "'%s', which is PUBLIC at %L", c->name,
11468                              sym->name, &sym->declared_at) == FAILURE)
11469         return FAILURE;
11470
11471       if (sym->attr.sequence)
11472         {
11473           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11474             {
11475               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11476                          "not have the SEQUENCE attribute",
11477                          c->ts.u.derived->name, &sym->declared_at);
11478               return FAILURE;
11479             }
11480         }
11481
11482       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && c->attr.pointer
11483           && c->ts.u.derived->components == NULL
11484           && !c->ts.u.derived->attr.zero_comp)
11485         {
11486           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11487                      "that has not been declared", c->name, sym->name,
11488                      &c->loc);
11489           return FAILURE;
11490         }
11491
11492       if (c->ts.type == BT_CLASS && CLASS_DATA (c)->attr.class_pointer
11493           && CLASS_DATA (c)->ts.u.derived->components == NULL
11494           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11495         {
11496           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11497                      "that has not been declared", c->name, sym->name,
11498                      &c->loc);
11499           return FAILURE;
11500         }
11501
11502       /* C437.  */
11503       if (c->ts.type == BT_CLASS
11504           && !(CLASS_DATA (c)->attr.class_pointer
11505                || CLASS_DATA (c)->attr.allocatable))
11506         {
11507           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11508                      "or pointer", c->name, &c->loc);
11509           return FAILURE;
11510         }
11511
11512       /* Ensure that all the derived type components are put on the
11513          derived type list; even in formal namespaces, where derived type
11514          pointer components might not have been declared.  */
11515       if (c->ts.type == BT_DERIVED
11516             && c->ts.u.derived
11517             && c->ts.u.derived->components
11518             && c->attr.pointer
11519             && sym != c->ts.u.derived)
11520         add_dt_to_dt_list (c->ts.u.derived);
11521
11522       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11523                                            || c->attr.proc_pointer
11524                                            || c->attr.allocatable)) == FAILURE)
11525         return FAILURE;
11526     }
11527
11528   /* Resolve the type-bound procedures.  */
11529   if (resolve_typebound_procedures (sym) == FAILURE)
11530     return FAILURE;
11531
11532   /* Resolve the finalizer procedures.  */
11533   if (gfc_resolve_finalizers (sym) == FAILURE)
11534     return FAILURE;
11535
11536   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11537      all DEFERRED bindings are overridden.  */
11538   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11539       && !sym->attr.is_class
11540       && ensure_not_abstract (sym, super_type) == FAILURE)
11541     return FAILURE;
11542
11543   /* Add derived type to the derived type list.  */
11544   add_dt_to_dt_list (sym);
11545
11546   return SUCCESS;
11547 }
11548
11549
11550 static gfc_try
11551 resolve_fl_namelist (gfc_symbol *sym)
11552 {
11553   gfc_namelist *nl;
11554   gfc_symbol *nlsym;
11555
11556   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11557   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
11558     {
11559       for (nl = sym->namelist; nl; nl = nl->next)
11560         {
11561           if (!nl->sym->attr.use_assoc
11562               && !is_sym_host_assoc (nl->sym, sym->ns)
11563               && !gfc_check_access(nl->sym->attr.access,
11564                                 nl->sym->ns->default_access))
11565             {
11566               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11567                          "cannot be member of PUBLIC namelist '%s' at %L",
11568                          nl->sym->name, sym->name, &sym->declared_at);
11569               return FAILURE;
11570             }
11571
11572           /* Types with private components that came here by USE-association.  */
11573           if (nl->sym->ts.type == BT_DERIVED
11574               && derived_inaccessible (nl->sym->ts.u.derived))
11575             {
11576               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11577                          "components and cannot be member of namelist '%s' at %L",
11578                          nl->sym->name, sym->name, &sym->declared_at);
11579               return FAILURE;
11580             }
11581
11582           /* Types with private components that are defined in the same module.  */
11583           if (nl->sym->ts.type == BT_DERIVED
11584               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11585               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
11586                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
11587                                         nl->sym->ns->default_access))
11588             {
11589               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11590                          "cannot be a member of PUBLIC namelist '%s' at %L",
11591                          nl->sym->name, sym->name, &sym->declared_at);
11592               return FAILURE;
11593             }
11594         }
11595     }
11596
11597   for (nl = sym->namelist; nl; nl = nl->next)
11598     {
11599       /* Reject namelist arrays of assumed shape.  */
11600       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11601           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
11602                              "must not have assumed shape in namelist "
11603                              "'%s' at %L", nl->sym->name, sym->name,
11604                              &sym->declared_at) == FAILURE)
11605             return FAILURE;
11606
11607       /* Reject namelist arrays that are not constant shape.  */
11608       if (is_non_constant_shape_array (nl->sym))
11609         {
11610           gfc_error ("NAMELIST array object '%s' must have constant "
11611                      "shape in namelist '%s' at %L", nl->sym->name,
11612                      sym->name, &sym->declared_at);
11613           return FAILURE;
11614         }
11615
11616       /* Namelist objects cannot have allocatable or pointer components.  */
11617       if (nl->sym->ts.type != BT_DERIVED)
11618         continue;
11619
11620       if (nl->sym->ts.u.derived->attr.alloc_comp)
11621         {
11622           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11623                      "have ALLOCATABLE components",
11624                      nl->sym->name, sym->name, &sym->declared_at);
11625           return FAILURE;
11626         }
11627
11628       if (nl->sym->ts.u.derived->attr.pointer_comp)
11629         {
11630           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11631                      "have POINTER components", 
11632                      nl->sym->name, sym->name, &sym->declared_at);
11633           return FAILURE;
11634         }
11635     }
11636
11637
11638   /* 14.1.2 A module or internal procedure represent local entities
11639      of the same type as a namelist member and so are not allowed.  */
11640   for (nl = sym->namelist; nl; nl = nl->next)
11641     {
11642       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11643         continue;
11644
11645       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11646         if ((nl->sym == sym->ns->proc_name)
11647                ||
11648             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11649           continue;
11650
11651       nlsym = NULL;
11652       if (nl->sym && nl->sym->name)
11653         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11654       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11655         {
11656           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11657                      "attribute in '%s' at %L", nlsym->name,
11658                      &sym->declared_at);
11659           return FAILURE;
11660         }
11661     }
11662
11663   return SUCCESS;
11664 }
11665
11666
11667 static gfc_try
11668 resolve_fl_parameter (gfc_symbol *sym)
11669 {
11670   /* A parameter array's shape needs to be constant.  */
11671   if (sym->as != NULL 
11672       && (sym->as->type == AS_DEFERRED
11673           || is_non_constant_shape_array (sym)))
11674     {
11675       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11676                  "or of deferred shape", sym->name, &sym->declared_at);
11677       return FAILURE;
11678     }
11679
11680   /* Make sure a parameter that has been implicitly typed still
11681      matches the implicit type, since PARAMETER statements can precede
11682      IMPLICIT statements.  */
11683   if (sym->attr.implicit_type
11684       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11685                                                              sym->ns)))
11686     {
11687       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11688                  "later IMPLICIT type", sym->name, &sym->declared_at);
11689       return FAILURE;
11690     }
11691
11692   /* Make sure the types of derived parameters are consistent.  This
11693      type checking is deferred until resolution because the type may
11694      refer to a derived type from the host.  */
11695   if (sym->ts.type == BT_DERIVED
11696       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11697     {
11698       gfc_error ("Incompatible derived type in PARAMETER at %L",
11699                  &sym->value->where);
11700       return FAILURE;
11701     }
11702   return SUCCESS;
11703 }
11704
11705
11706 /* Do anything necessary to resolve a symbol.  Right now, we just
11707    assume that an otherwise unknown symbol is a variable.  This sort
11708    of thing commonly happens for symbols in module.  */
11709
11710 static void
11711 resolve_symbol (gfc_symbol *sym)
11712 {
11713   int check_constant, mp_flag;
11714   gfc_symtree *symtree;
11715   gfc_symtree *this_symtree;
11716   gfc_namespace *ns;
11717   gfc_component *c;
11718
11719   /* Avoid double resolution of function result symbols.  */
11720   if ((sym->result || sym->attr.result) && !sym->attr.dummy
11721       && (sym->ns != gfc_current_ns))
11722     return;
11723   
11724   if (sym->attr.flavor == FL_UNKNOWN)
11725     {
11726
11727     /* If we find that a flavorless symbol is an interface in one of the
11728        parent namespaces, find its symtree in this namespace, free the
11729        symbol and set the symtree to point to the interface symbol.  */
11730       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11731         {
11732           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11733           if (symtree && symtree->n.sym->generic)
11734             {
11735               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11736                                                sym->name);
11737               gfc_release_symbol (sym);
11738               symtree->n.sym->refs++;
11739               this_symtree->n.sym = symtree->n.sym;
11740               return;
11741             }
11742         }
11743
11744       /* Otherwise give it a flavor according to such attributes as
11745          it has.  */
11746       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11747         sym->attr.flavor = FL_VARIABLE;
11748       else
11749         {
11750           sym->attr.flavor = FL_PROCEDURE;
11751           if (sym->attr.dimension)
11752             sym->attr.function = 1;
11753         }
11754     }
11755
11756   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11757     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11758
11759   if (sym->attr.procedure && sym->ts.interface
11760       && sym->attr.if_source != IFSRC_DECL
11761       && resolve_procedure_interface (sym) == FAILURE)
11762     return;
11763
11764   if (sym->attr.is_protected && !sym->attr.proc_pointer
11765       && (sym->attr.procedure || sym->attr.external))
11766     {
11767       if (sym->attr.external)
11768         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
11769                    "at %L", &sym->declared_at);
11770       else
11771         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
11772                    "at %L", &sym->declared_at);
11773
11774       return;
11775     }
11776
11777
11778   /* F2008, C530. */
11779   if (sym->attr.contiguous
11780       && (!sym->attr.dimension || (sym->as->type != AS_ASSUMED_SHAPE
11781                                    && !sym->attr.pointer)))
11782     {
11783       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
11784                   "array pointer or an assumed-shape array", sym->name,
11785                   &sym->declared_at);
11786       return;
11787     }
11788
11789   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11790     return;
11791
11792   /* Symbols that are module procedures with results (functions) have
11793      the types and array specification copied for type checking in
11794      procedures that call them, as well as for saving to a module
11795      file.  These symbols can't stand the scrutiny that their results
11796      can.  */
11797   mp_flag = (sym->result != NULL && sym->result != sym);
11798
11799   /* Make sure that the intrinsic is consistent with its internal 
11800      representation. This needs to be done before assigning a default 
11801      type to avoid spurious warnings.  */
11802   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11803       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11804     return;
11805
11806   /* Resolve associate names.  */
11807   if (sym->assoc)
11808     resolve_assoc_var (sym, true);
11809
11810   /* Assign default type to symbols that need one and don't have one.  */
11811   if (sym->ts.type == BT_UNKNOWN)
11812     {
11813       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
11814         gfc_set_default_type (sym, 1, NULL);
11815
11816       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
11817           && !sym->attr.function && !sym->attr.subroutine
11818           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
11819         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
11820
11821       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
11822         {
11823           /* The specific case of an external procedure should emit an error
11824              in the case that there is no implicit type.  */
11825           if (!mp_flag)
11826             gfc_set_default_type (sym, sym->attr.external, NULL);
11827           else
11828             {
11829               /* Result may be in another namespace.  */
11830               resolve_symbol (sym->result);
11831
11832               if (!sym->result->attr.proc_pointer)
11833                 {
11834                   sym->ts = sym->result->ts;
11835                   sym->as = gfc_copy_array_spec (sym->result->as);
11836                   sym->attr.dimension = sym->result->attr.dimension;
11837                   sym->attr.pointer = sym->result->attr.pointer;
11838                   sym->attr.allocatable = sym->result->attr.allocatable;
11839                   sym->attr.contiguous = sym->result->attr.contiguous;
11840                 }
11841             }
11842         }
11843     }
11844
11845   /* Assumed size arrays and assumed shape arrays must be dummy
11846      arguments.  Array-spec's of implied-shape should have been resolved to
11847      AS_EXPLICIT already.  */
11848
11849   if (sym->as)
11850     {
11851       gcc_assert (sym->as->type != AS_IMPLIED_SHAPE);
11852       if (((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
11853            || sym->as->type == AS_ASSUMED_SHAPE)
11854           && sym->attr.dummy == 0)
11855         {
11856           if (sym->as->type == AS_ASSUMED_SIZE)
11857             gfc_error ("Assumed size array at %L must be a dummy argument",
11858                        &sym->declared_at);
11859           else
11860             gfc_error ("Assumed shape array at %L must be a dummy argument",
11861                        &sym->declared_at);
11862           return;
11863         }
11864     }
11865
11866   /* Make sure symbols with known intent or optional are really dummy
11867      variable.  Because of ENTRY statement, this has to be deferred
11868      until resolution time.  */
11869
11870   if (!sym->attr.dummy
11871       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
11872     {
11873       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
11874       return;
11875     }
11876
11877   if (sym->attr.value && !sym->attr.dummy)
11878     {
11879       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
11880                  "it is not a dummy argument", sym->name, &sym->declared_at);
11881       return;
11882     }
11883
11884   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
11885     {
11886       gfc_charlen *cl = sym->ts.u.cl;
11887       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
11888         {
11889           gfc_error ("Character dummy variable '%s' at %L with VALUE "
11890                      "attribute must have constant length",
11891                      sym->name, &sym->declared_at);
11892           return;
11893         }
11894
11895       if (sym->ts.is_c_interop
11896           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
11897         {
11898           gfc_error ("C interoperable character dummy variable '%s' at %L "
11899                      "with VALUE attribute must have length one",
11900                      sym->name, &sym->declared_at);
11901           return;
11902         }
11903     }
11904
11905   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
11906      do this for something that was implicitly typed because that is handled
11907      in gfc_set_default_type.  Handle dummy arguments and procedure
11908      definitions separately.  Also, anything that is use associated is not
11909      handled here but instead is handled in the module it is declared in.
11910      Finally, derived type definitions are allowed to be BIND(C) since that
11911      only implies that they're interoperable, and they are checked fully for
11912      interoperability when a variable is declared of that type.  */
11913   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
11914       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
11915       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
11916     {
11917       gfc_try t = SUCCESS;
11918       
11919       /* First, make sure the variable is declared at the
11920          module-level scope (J3/04-007, Section 15.3).  */
11921       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
11922           sym->attr.in_common == 0)
11923         {
11924           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
11925                      "is neither a COMMON block nor declared at the "
11926                      "module level scope", sym->name, &(sym->declared_at));
11927           t = FAILURE;
11928         }
11929       else if (sym->common_head != NULL)
11930         {
11931           t = verify_com_block_vars_c_interop (sym->common_head);
11932         }
11933       else
11934         {
11935           /* If type() declaration, we need to verify that the components
11936              of the given type are all C interoperable, etc.  */
11937           if (sym->ts.type == BT_DERIVED &&
11938               sym->ts.u.derived->attr.is_c_interop != 1)
11939             {
11940               /* Make sure the user marked the derived type as BIND(C).  If
11941                  not, call the verify routine.  This could print an error
11942                  for the derived type more than once if multiple variables
11943                  of that type are declared.  */
11944               if (sym->ts.u.derived->attr.is_bind_c != 1)
11945                 verify_bind_c_derived_type (sym->ts.u.derived);
11946               t = FAILURE;
11947             }
11948           
11949           /* Verify the variable itself as C interoperable if it
11950              is BIND(C).  It is not possible for this to succeed if
11951              the verify_bind_c_derived_type failed, so don't have to handle
11952              any error returned by verify_bind_c_derived_type.  */
11953           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
11954                                  sym->common_block);
11955         }
11956
11957       if (t == FAILURE)
11958         {
11959           /* clear the is_bind_c flag to prevent reporting errors more than
11960              once if something failed.  */
11961           sym->attr.is_bind_c = 0;
11962           return;
11963         }
11964     }
11965
11966   /* If a derived type symbol has reached this point, without its
11967      type being declared, we have an error.  Notice that most
11968      conditions that produce undefined derived types have already
11969      been dealt with.  However, the likes of:
11970      implicit type(t) (t) ..... call foo (t) will get us here if
11971      the type is not declared in the scope of the implicit
11972      statement. Change the type to BT_UNKNOWN, both because it is so
11973      and to prevent an ICE.  */
11974   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
11975       && !sym->ts.u.derived->attr.zero_comp)
11976     {
11977       gfc_error ("The derived type '%s' at %L is of type '%s', "
11978                  "which has not been defined", sym->name,
11979                   &sym->declared_at, sym->ts.u.derived->name);
11980       sym->ts.type = BT_UNKNOWN;
11981       return;
11982     }
11983
11984   /* Make sure that the derived type has been resolved and that the
11985      derived type is visible in the symbol's namespace, if it is a
11986      module function and is not PRIVATE.  */
11987   if (sym->ts.type == BT_DERIVED
11988         && sym->ts.u.derived->attr.use_assoc
11989         && sym->ns->proc_name
11990         && sym->ns->proc_name->attr.flavor == FL_MODULE)
11991     {
11992       gfc_symbol *ds;
11993
11994       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
11995         return;
11996
11997       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
11998       if (!ds && sym->attr.function
11999             && gfc_check_access (sym->attr.access, sym->ns->default_access))
12000         {
12001           symtree = gfc_new_symtree (&sym->ns->sym_root,
12002                                      sym->ts.u.derived->name);
12003           symtree->n.sym = sym->ts.u.derived;
12004           sym->ts.u.derived->refs++;
12005         }
12006     }
12007
12008   /* Unless the derived-type declaration is use associated, Fortran 95
12009      does not allow public entries of private derived types.
12010      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12011      161 in 95-006r3.  */
12012   if (sym->ts.type == BT_DERIVED
12013       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12014       && !sym->ts.u.derived->attr.use_assoc
12015       && gfc_check_access (sym->attr.access, sym->ns->default_access)
12016       && !gfc_check_access (sym->ts.u.derived->attr.access,
12017                             sym->ts.u.derived->ns->default_access)
12018       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12019                          "of PRIVATE derived type '%s'",
12020                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12021                          : "variable", sym->name, &sym->declared_at,
12022                          sym->ts.u.derived->name) == FAILURE)
12023     return;
12024
12025   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12026      default initialization is defined (5.1.2.4.4).  */
12027   if (sym->ts.type == BT_DERIVED
12028       && sym->attr.dummy
12029       && sym->attr.intent == INTENT_OUT
12030       && sym->as
12031       && sym->as->type == AS_ASSUMED_SIZE)
12032     {
12033       for (c = sym->ts.u.derived->components; c; c = c->next)
12034         {
12035           if (c->initializer)
12036             {
12037               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12038                          "ASSUMED SIZE and so cannot have a default initializer",
12039                          sym->name, &sym->declared_at);
12040               return;
12041             }
12042         }
12043     }
12044
12045   /* F2008, C526.  */
12046   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12047        || sym->attr.codimension)
12048       && sym->attr.result)
12049     gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12050                "a coarray component", sym->name, &sym->declared_at);
12051
12052   /* F2008, C524.  */
12053   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12054       && sym->ts.u.derived->ts.is_iso_c)
12055     gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12056                "shall not be a coarray", sym->name, &sym->declared_at);
12057
12058   /* F2008, C525.  */
12059   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
12060       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
12061           || sym->attr.allocatable))
12062     gfc_error ("Variable '%s' at %L with coarray component "
12063                "shall be a nonpointer, nonallocatable scalar",
12064                sym->name, &sym->declared_at);
12065
12066   /* F2008, C526.  The function-result case was handled above.  */
12067   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12068        || sym->attr.codimension)
12069       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
12070            || sym->ns->proc_name->attr.flavor == FL_MODULE
12071            || sym->ns->proc_name->attr.is_main_program
12072            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12073     gfc_error ("Variable '%s' at %L is a coarray or has a coarray "
12074                "component and is not ALLOCATABLE, SAVE nor a "
12075                "dummy argument", sym->name, &sym->declared_at);
12076   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
12077   else if (sym->attr.codimension && !sym->attr.allocatable
12078       && sym->as && sym->as->cotype == AS_DEFERRED)
12079     gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12080                 "deferred shape", sym->name, &sym->declared_at);
12081   else if (sym->attr.codimension && sym->attr.allocatable
12082       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
12083     gfc_error ("Allocatable coarray variable '%s' at %L must have "
12084                "deferred shape", sym->name, &sym->declared_at);
12085
12086
12087   /* F2008, C541.  */
12088   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12089        || (sym->attr.codimension && sym->attr.allocatable))
12090       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12091     gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12092                "allocatable coarray or have coarray components",
12093                sym->name, &sym->declared_at);
12094
12095   if (sym->attr.codimension && sym->attr.dummy
12096       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12097     gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12098                "procedure '%s'", sym->name, &sym->declared_at,
12099                sym->ns->proc_name->name);
12100
12101   switch (sym->attr.flavor)
12102     {
12103     case FL_VARIABLE:
12104       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12105         return;
12106       break;
12107
12108     case FL_PROCEDURE:
12109       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12110         return;
12111       break;
12112
12113     case FL_NAMELIST:
12114       if (resolve_fl_namelist (sym) == FAILURE)
12115         return;
12116       break;
12117
12118     case FL_PARAMETER:
12119       if (resolve_fl_parameter (sym) == FAILURE)
12120         return;
12121       break;
12122
12123     default:
12124       break;
12125     }
12126
12127   /* Resolve array specifier. Check as well some constraints
12128      on COMMON blocks.  */
12129
12130   check_constant = sym->attr.in_common && !sym->attr.pointer;
12131
12132   /* Set the formal_arg_flag so that check_conflict will not throw
12133      an error for host associated variables in the specification
12134      expression for an array_valued function.  */
12135   if (sym->attr.function && sym->as)
12136     formal_arg_flag = 1;
12137
12138   gfc_resolve_array_spec (sym->as, check_constant);
12139
12140   formal_arg_flag = 0;
12141
12142   /* Resolve formal namespaces.  */
12143   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12144       && !sym->attr.contained && !sym->attr.intrinsic)
12145     gfc_resolve (sym->formal_ns);
12146
12147   /* Make sure the formal namespace is present.  */
12148   if (sym->formal && !sym->formal_ns)
12149     {
12150       gfc_formal_arglist *formal = sym->formal;
12151       while (formal && !formal->sym)
12152         formal = formal->next;
12153
12154       if (formal)
12155         {
12156           sym->formal_ns = formal->sym->ns;
12157           sym->formal_ns->refs++;
12158         }
12159     }
12160
12161   /* Check threadprivate restrictions.  */
12162   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12163       && (!sym->attr.in_common
12164           && sym->module == NULL
12165           && (sym->ns->proc_name == NULL
12166               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12167     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12168
12169   /* If we have come this far we can apply default-initializers, as
12170      described in 14.7.5, to those variables that have not already
12171      been assigned one.  */
12172   if (sym->ts.type == BT_DERIVED
12173       && sym->attr.referenced
12174       && sym->ns == gfc_current_ns
12175       && !sym->value
12176       && !sym->attr.allocatable
12177       && !sym->attr.alloc_comp)
12178     {
12179       symbol_attribute *a = &sym->attr;
12180
12181       if ((!a->save && !a->dummy && !a->pointer
12182            && !a->in_common && !a->use_assoc
12183            && !(a->function && sym != sym->result))
12184           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12185         apply_default_init (sym);
12186     }
12187
12188   /* If this symbol has a type-spec, check it.  */
12189   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12190       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12191     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12192           == FAILURE)
12193       return;
12194 }
12195
12196
12197 /************* Resolve DATA statements *************/
12198
12199 static struct
12200 {
12201   gfc_data_value *vnode;
12202   mpz_t left;
12203 }
12204 values;
12205
12206
12207 /* Advance the values structure to point to the next value in the data list.  */
12208
12209 static gfc_try
12210 next_data_value (void)
12211 {
12212   while (mpz_cmp_ui (values.left, 0) == 0)
12213     {
12214
12215       if (values.vnode->next == NULL)
12216         return FAILURE;
12217
12218       values.vnode = values.vnode->next;
12219       mpz_set (values.left, values.vnode->repeat);
12220     }
12221
12222   return SUCCESS;
12223 }
12224
12225
12226 static gfc_try
12227 check_data_variable (gfc_data_variable *var, locus *where)
12228 {
12229   gfc_expr *e;
12230   mpz_t size;
12231   mpz_t offset;
12232   gfc_try t;
12233   ar_type mark = AR_UNKNOWN;
12234   int i;
12235   mpz_t section_index[GFC_MAX_DIMENSIONS];
12236   gfc_ref *ref;
12237   gfc_array_ref *ar;
12238   gfc_symbol *sym;
12239   int has_pointer;
12240
12241   if (gfc_resolve_expr (var->expr) == FAILURE)
12242     return FAILURE;
12243
12244   ar = NULL;
12245   mpz_init_set_si (offset, 0);
12246   e = var->expr;
12247
12248   if (e->expr_type != EXPR_VARIABLE)
12249     gfc_internal_error ("check_data_variable(): Bad expression");
12250
12251   sym = e->symtree->n.sym;
12252
12253   if (sym->ns->is_block_data && !sym->attr.in_common)
12254     {
12255       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12256                  sym->name, &sym->declared_at);
12257     }
12258
12259   if (e->ref == NULL && sym->as)
12260     {
12261       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12262                  " declaration", sym->name, where);
12263       return FAILURE;
12264     }
12265
12266   has_pointer = sym->attr.pointer;
12267
12268   for (ref = e->ref; ref; ref = ref->next)
12269     {
12270       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12271         has_pointer = 1;
12272
12273       if (ref->type == REF_ARRAY && ref->u.ar.codimen)
12274         {
12275           gfc_error ("DATA element '%s' at %L cannot have a coindex",
12276                      sym->name, where);
12277           return FAILURE;
12278         }
12279
12280       if (has_pointer
12281             && ref->type == REF_ARRAY
12282             && ref->u.ar.type != AR_FULL)
12283           {
12284             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12285                         "be a full array", sym->name, where);
12286             return FAILURE;
12287           }
12288     }
12289
12290   if (e->rank == 0 || has_pointer)
12291     {
12292       mpz_init_set_ui (size, 1);
12293       ref = NULL;
12294     }
12295   else
12296     {
12297       ref = e->ref;
12298
12299       /* Find the array section reference.  */
12300       for (ref = e->ref; ref; ref = ref->next)
12301         {
12302           if (ref->type != REF_ARRAY)
12303             continue;
12304           if (ref->u.ar.type == AR_ELEMENT)
12305             continue;
12306           break;
12307         }
12308       gcc_assert (ref);
12309
12310       /* Set marks according to the reference pattern.  */
12311       switch (ref->u.ar.type)
12312         {
12313         case AR_FULL:
12314           mark = AR_FULL;
12315           break;
12316
12317         case AR_SECTION:
12318           ar = &ref->u.ar;
12319           /* Get the start position of array section.  */
12320           gfc_get_section_index (ar, section_index, &offset);
12321           mark = AR_SECTION;
12322           break;
12323
12324         default:
12325           gcc_unreachable ();
12326         }
12327
12328       if (gfc_array_size (e, &size) == FAILURE)
12329         {
12330           gfc_error ("Nonconstant array section at %L in DATA statement",
12331                      &e->where);
12332           mpz_clear (offset);
12333           return FAILURE;
12334         }
12335     }
12336
12337   t = SUCCESS;
12338
12339   while (mpz_cmp_ui (size, 0) > 0)
12340     {
12341       if (next_data_value () == FAILURE)
12342         {
12343           gfc_error ("DATA statement at %L has more variables than values",
12344                      where);
12345           t = FAILURE;
12346           break;
12347         }
12348
12349       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12350       if (t == FAILURE)
12351         break;
12352
12353       /* If we have more than one element left in the repeat count,
12354          and we have more than one element left in the target variable,
12355          then create a range assignment.  */
12356       /* FIXME: Only done for full arrays for now, since array sections
12357          seem tricky.  */
12358       if (mark == AR_FULL && ref && ref->next == NULL
12359           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12360         {
12361           mpz_t range;
12362
12363           if (mpz_cmp (size, values.left) >= 0)
12364             {
12365               mpz_init_set (range, values.left);
12366               mpz_sub (size, size, values.left);
12367               mpz_set_ui (values.left, 0);
12368             }
12369           else
12370             {
12371               mpz_init_set (range, size);
12372               mpz_sub (values.left, values.left, size);
12373               mpz_set_ui (size, 0);
12374             }
12375
12376           t = gfc_assign_data_value_range (var->expr, values.vnode->expr,
12377                                            offset, range);
12378
12379           mpz_add (offset, offset, range);
12380           mpz_clear (range);
12381
12382           if (t == FAILURE)
12383             break;
12384         }
12385
12386       /* Assign initial value to symbol.  */
12387       else
12388         {
12389           mpz_sub_ui (values.left, values.left, 1);
12390           mpz_sub_ui (size, size, 1);
12391
12392           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
12393           if (t == FAILURE)
12394             break;
12395
12396           if (mark == AR_FULL)
12397             mpz_add_ui (offset, offset, 1);
12398
12399           /* Modify the array section indexes and recalculate the offset
12400              for next element.  */
12401           else if (mark == AR_SECTION)
12402             gfc_advance_section (section_index, ar, &offset);
12403         }
12404     }
12405
12406   if (mark == AR_SECTION)
12407     {
12408       for (i = 0; i < ar->dimen; i++)
12409         mpz_clear (section_index[i]);
12410     }
12411
12412   mpz_clear (size);
12413   mpz_clear (offset);
12414
12415   return t;
12416 }
12417
12418
12419 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
12420
12421 /* Iterate over a list of elements in a DATA statement.  */
12422
12423 static gfc_try
12424 traverse_data_list (gfc_data_variable *var, locus *where)
12425 {
12426   mpz_t trip;
12427   iterator_stack frame;
12428   gfc_expr *e, *start, *end, *step;
12429   gfc_try retval = SUCCESS;
12430
12431   mpz_init (frame.value);
12432   mpz_init (trip);
12433
12434   start = gfc_copy_expr (var->iter.start);
12435   end = gfc_copy_expr (var->iter.end);
12436   step = gfc_copy_expr (var->iter.step);
12437
12438   if (gfc_simplify_expr (start, 1) == FAILURE
12439       || start->expr_type != EXPR_CONSTANT)
12440     {
12441       gfc_error ("start of implied-do loop at %L could not be "
12442                  "simplified to a constant value", &start->where);
12443       retval = FAILURE;
12444       goto cleanup;
12445     }
12446   if (gfc_simplify_expr (end, 1) == FAILURE
12447       || end->expr_type != EXPR_CONSTANT)
12448     {
12449       gfc_error ("end of implied-do loop at %L could not be "
12450                  "simplified to a constant value", &start->where);
12451       retval = FAILURE;
12452       goto cleanup;
12453     }
12454   if (gfc_simplify_expr (step, 1) == FAILURE
12455       || step->expr_type != EXPR_CONSTANT)
12456     {
12457       gfc_error ("step of implied-do loop at %L could not be "
12458                  "simplified to a constant value", &start->where);
12459       retval = FAILURE;
12460       goto cleanup;
12461     }
12462
12463   mpz_set (trip, end->value.integer);
12464   mpz_sub (trip, trip, start->value.integer);
12465   mpz_add (trip, trip, step->value.integer);
12466
12467   mpz_div (trip, trip, step->value.integer);
12468
12469   mpz_set (frame.value, start->value.integer);
12470
12471   frame.prev = iter_stack;
12472   frame.variable = var->iter.var->symtree;
12473   iter_stack = &frame;
12474
12475   while (mpz_cmp_ui (trip, 0) > 0)
12476     {
12477       if (traverse_data_var (var->list, where) == FAILURE)
12478         {
12479           retval = FAILURE;
12480           goto cleanup;
12481         }
12482
12483       e = gfc_copy_expr (var->expr);
12484       if (gfc_simplify_expr (e, 1) == FAILURE)
12485         {
12486           gfc_free_expr (e);
12487           retval = FAILURE;
12488           goto cleanup;
12489         }
12490
12491       mpz_add (frame.value, frame.value, step->value.integer);
12492
12493       mpz_sub_ui (trip, trip, 1);
12494     }
12495
12496 cleanup:
12497   mpz_clear (frame.value);
12498   mpz_clear (trip);
12499
12500   gfc_free_expr (start);
12501   gfc_free_expr (end);
12502   gfc_free_expr (step);
12503
12504   iter_stack = frame.prev;
12505   return retval;
12506 }
12507
12508
12509 /* Type resolve variables in the variable list of a DATA statement.  */
12510
12511 static gfc_try
12512 traverse_data_var (gfc_data_variable *var, locus *where)
12513 {
12514   gfc_try t;
12515
12516   for (; var; var = var->next)
12517     {
12518       if (var->expr == NULL)
12519         t = traverse_data_list (var, where);
12520       else
12521         t = check_data_variable (var, where);
12522
12523       if (t == FAILURE)
12524         return FAILURE;
12525     }
12526
12527   return SUCCESS;
12528 }
12529
12530
12531 /* Resolve the expressions and iterators associated with a data statement.
12532    This is separate from the assignment checking because data lists should
12533    only be resolved once.  */
12534
12535 static gfc_try
12536 resolve_data_variables (gfc_data_variable *d)
12537 {
12538   for (; d; d = d->next)
12539     {
12540       if (d->list == NULL)
12541         {
12542           if (gfc_resolve_expr (d->expr) == FAILURE)
12543             return FAILURE;
12544         }
12545       else
12546         {
12547           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12548             return FAILURE;
12549
12550           if (resolve_data_variables (d->list) == FAILURE)
12551             return FAILURE;
12552         }
12553     }
12554
12555   return SUCCESS;
12556 }
12557
12558
12559 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12560    the value list into static variables, and then recursively traversing the
12561    variables list, expanding iterators and such.  */
12562
12563 static void
12564 resolve_data (gfc_data *d)
12565 {
12566
12567   if (resolve_data_variables (d->var) == FAILURE)
12568     return;
12569
12570   values.vnode = d->value;
12571   if (d->value == NULL)
12572     mpz_set_ui (values.left, 0);
12573   else
12574     mpz_set (values.left, d->value->repeat);
12575
12576   if (traverse_data_var (d->var, &d->where) == FAILURE)
12577     return;
12578
12579   /* At this point, we better not have any values left.  */
12580
12581   if (next_data_value () == SUCCESS)
12582     gfc_error ("DATA statement at %L has more values than variables",
12583                &d->where);
12584 }
12585
12586
12587 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12588    accessed by host or use association, is a dummy argument to a pure function,
12589    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12590    is storage associated with any such variable, shall not be used in the
12591    following contexts: (clients of this function).  */
12592
12593 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12594    procedure.  Returns zero if assignment is OK, nonzero if there is a
12595    problem.  */
12596 int
12597 gfc_impure_variable (gfc_symbol *sym)
12598 {
12599   gfc_symbol *proc;
12600   gfc_namespace *ns;
12601
12602   if (sym->attr.use_assoc || sym->attr.in_common)
12603     return 1;
12604
12605   /* Check if the symbol's ns is inside the pure procedure.  */
12606   for (ns = gfc_current_ns; ns; ns = ns->parent)
12607     {
12608       if (ns == sym->ns)
12609         break;
12610       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12611         return 1;
12612     }
12613
12614   proc = sym->ns->proc_name;
12615   if (sym->attr.dummy && gfc_pure (proc)
12616         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12617                 ||
12618              proc->attr.function))
12619     return 1;
12620
12621   /* TODO: Sort out what can be storage associated, if anything, and include
12622      it here.  In principle equivalences should be scanned but it does not
12623      seem to be possible to storage associate an impure variable this way.  */
12624   return 0;
12625 }
12626
12627
12628 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12629    current namespace is inside a pure procedure.  */
12630
12631 int
12632 gfc_pure (gfc_symbol *sym)
12633 {
12634   symbol_attribute attr;
12635   gfc_namespace *ns;
12636
12637   if (sym == NULL)
12638     {
12639       /* Check if the current namespace or one of its parents
12640         belongs to a pure procedure.  */
12641       for (ns = gfc_current_ns; ns; ns = ns->parent)
12642         {
12643           sym = ns->proc_name;
12644           if (sym == NULL)
12645             return 0;
12646           attr = sym->attr;
12647           if (attr.flavor == FL_PROCEDURE && attr.pure)
12648             return 1;
12649         }
12650       return 0;
12651     }
12652
12653   attr = sym->attr;
12654
12655   return attr.flavor == FL_PROCEDURE && attr.pure;
12656 }
12657
12658
12659 /* Test whether the current procedure is elemental or not.  */
12660
12661 int
12662 gfc_elemental (gfc_symbol *sym)
12663 {
12664   symbol_attribute attr;
12665
12666   if (sym == NULL)
12667     sym = gfc_current_ns->proc_name;
12668   if (sym == NULL)
12669     return 0;
12670   attr = sym->attr;
12671
12672   return attr.flavor == FL_PROCEDURE && attr.elemental;
12673 }
12674
12675
12676 /* Warn about unused labels.  */
12677
12678 static void
12679 warn_unused_fortran_label (gfc_st_label *label)
12680 {
12681   if (label == NULL)
12682     return;
12683
12684   warn_unused_fortran_label (label->left);
12685
12686   if (label->defined == ST_LABEL_UNKNOWN)
12687     return;
12688
12689   switch (label->referenced)
12690     {
12691     case ST_LABEL_UNKNOWN:
12692       gfc_warning ("Label %d at %L defined but not used", label->value,
12693                    &label->where);
12694       break;
12695
12696     case ST_LABEL_BAD_TARGET:
12697       gfc_warning ("Label %d at %L defined but cannot be used",
12698                    label->value, &label->where);
12699       break;
12700
12701     default:
12702       break;
12703     }
12704
12705   warn_unused_fortran_label (label->right);
12706 }
12707
12708
12709 /* Returns the sequence type of a symbol or sequence.  */
12710
12711 static seq_type
12712 sequence_type (gfc_typespec ts)
12713 {
12714   seq_type result;
12715   gfc_component *c;
12716
12717   switch (ts.type)
12718   {
12719     case BT_DERIVED:
12720
12721       if (ts.u.derived->components == NULL)
12722         return SEQ_NONDEFAULT;
12723
12724       result = sequence_type (ts.u.derived->components->ts);
12725       for (c = ts.u.derived->components->next; c; c = c->next)
12726         if (sequence_type (c->ts) != result)
12727           return SEQ_MIXED;
12728
12729       return result;
12730
12731     case BT_CHARACTER:
12732       if (ts.kind != gfc_default_character_kind)
12733           return SEQ_NONDEFAULT;
12734
12735       return SEQ_CHARACTER;
12736
12737     case BT_INTEGER:
12738       if (ts.kind != gfc_default_integer_kind)
12739           return SEQ_NONDEFAULT;
12740
12741       return SEQ_NUMERIC;
12742
12743     case BT_REAL:
12744       if (!(ts.kind == gfc_default_real_kind
12745             || ts.kind == gfc_default_double_kind))
12746           return SEQ_NONDEFAULT;
12747
12748       return SEQ_NUMERIC;
12749
12750     case BT_COMPLEX:
12751       if (ts.kind != gfc_default_complex_kind)
12752           return SEQ_NONDEFAULT;
12753
12754       return SEQ_NUMERIC;
12755
12756     case BT_LOGICAL:
12757       if (ts.kind != gfc_default_logical_kind)
12758           return SEQ_NONDEFAULT;
12759
12760       return SEQ_NUMERIC;
12761
12762     default:
12763       return SEQ_NONDEFAULT;
12764   }
12765 }
12766
12767
12768 /* Resolve derived type EQUIVALENCE object.  */
12769
12770 static gfc_try
12771 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
12772 {
12773   gfc_component *c = derived->components;
12774
12775   if (!derived)
12776     return SUCCESS;
12777
12778   /* Shall not be an object of nonsequence derived type.  */
12779   if (!derived->attr.sequence)
12780     {
12781       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
12782                  "attribute to be an EQUIVALENCE object", sym->name,
12783                  &e->where);
12784       return FAILURE;
12785     }
12786
12787   /* Shall not have allocatable components.  */
12788   if (derived->attr.alloc_comp)
12789     {
12790       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
12791                  "components to be an EQUIVALENCE object",sym->name,
12792                  &e->where);
12793       return FAILURE;
12794     }
12795
12796   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
12797     {
12798       gfc_error ("Derived type variable '%s' at %L with default "
12799                  "initialization cannot be in EQUIVALENCE with a variable "
12800                  "in COMMON", sym->name, &e->where);
12801       return FAILURE;
12802     }
12803
12804   for (; c ; c = c->next)
12805     {
12806       if (c->ts.type == BT_DERIVED
12807           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
12808         return FAILURE;
12809
12810       /* Shall not be an object of sequence derived type containing a pointer
12811          in the structure.  */
12812       if (c->attr.pointer)
12813         {
12814           gfc_error ("Derived type variable '%s' at %L with pointer "
12815                      "component(s) cannot be an EQUIVALENCE object",
12816                      sym->name, &e->where);
12817           return FAILURE;
12818         }
12819     }
12820   return SUCCESS;
12821 }
12822
12823
12824 /* Resolve equivalence object. 
12825    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
12826    an allocatable array, an object of nonsequence derived type, an object of
12827    sequence derived type containing a pointer at any level of component
12828    selection, an automatic object, a function name, an entry name, a result
12829    name, a named constant, a structure component, or a subobject of any of
12830    the preceding objects.  A substring shall not have length zero.  A
12831    derived type shall not have components with default initialization nor
12832    shall two objects of an equivalence group be initialized.
12833    Either all or none of the objects shall have an protected attribute.
12834    The simple constraints are done in symbol.c(check_conflict) and the rest
12835    are implemented here.  */
12836
12837 static void
12838 resolve_equivalence (gfc_equiv *eq)
12839 {
12840   gfc_symbol *sym;
12841   gfc_symbol *first_sym;
12842   gfc_expr *e;
12843   gfc_ref *r;
12844   locus *last_where = NULL;
12845   seq_type eq_type, last_eq_type;
12846   gfc_typespec *last_ts;
12847   int object, cnt_protected;
12848   const char *msg;
12849
12850   last_ts = &eq->expr->symtree->n.sym->ts;
12851
12852   first_sym = eq->expr->symtree->n.sym;
12853
12854   cnt_protected = 0;
12855
12856   for (object = 1; eq; eq = eq->eq, object++)
12857     {
12858       e = eq->expr;
12859
12860       e->ts = e->symtree->n.sym->ts;
12861       /* match_varspec might not know yet if it is seeing
12862          array reference or substring reference, as it doesn't
12863          know the types.  */
12864       if (e->ref && e->ref->type == REF_ARRAY)
12865         {
12866           gfc_ref *ref = e->ref;
12867           sym = e->symtree->n.sym;
12868
12869           if (sym->attr.dimension)
12870             {
12871               ref->u.ar.as = sym->as;
12872               ref = ref->next;
12873             }
12874
12875           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
12876           if (e->ts.type == BT_CHARACTER
12877               && ref
12878               && ref->type == REF_ARRAY
12879               && ref->u.ar.dimen == 1
12880               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
12881               && ref->u.ar.stride[0] == NULL)
12882             {
12883               gfc_expr *start = ref->u.ar.start[0];
12884               gfc_expr *end = ref->u.ar.end[0];
12885               void *mem = NULL;
12886
12887               /* Optimize away the (:) reference.  */
12888               if (start == NULL && end == NULL)
12889                 {
12890                   if (e->ref == ref)
12891                     e->ref = ref->next;
12892                   else
12893                     e->ref->next = ref->next;
12894                   mem = ref;
12895                 }
12896               else
12897                 {
12898                   ref->type = REF_SUBSTRING;
12899                   if (start == NULL)
12900                     start = gfc_get_int_expr (gfc_default_integer_kind,
12901                                               NULL, 1);
12902                   ref->u.ss.start = start;
12903                   if (end == NULL && e->ts.u.cl)
12904                     end = gfc_copy_expr (e->ts.u.cl->length);
12905                   ref->u.ss.end = end;
12906                   ref->u.ss.length = e->ts.u.cl;
12907                   e->ts.u.cl = NULL;
12908                 }
12909               ref = ref->next;
12910               gfc_free (mem);
12911             }
12912
12913           /* Any further ref is an error.  */
12914           if (ref)
12915             {
12916               gcc_assert (ref->type == REF_ARRAY);
12917               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
12918                          &ref->u.ar.where);
12919               continue;
12920             }
12921         }
12922
12923       if (gfc_resolve_expr (e) == FAILURE)
12924         continue;
12925
12926       sym = e->symtree->n.sym;
12927
12928       if (sym->attr.is_protected)
12929         cnt_protected++;
12930       if (cnt_protected > 0 && cnt_protected != object)
12931         {
12932               gfc_error ("Either all or none of the objects in the "
12933                          "EQUIVALENCE set at %L shall have the "
12934                          "PROTECTED attribute",
12935                          &e->where);
12936               break;
12937         }
12938
12939       /* Shall not equivalence common block variables in a PURE procedure.  */
12940       if (sym->ns->proc_name
12941           && sym->ns->proc_name->attr.pure
12942           && sym->attr.in_common)
12943         {
12944           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
12945                      "object in the pure procedure '%s'",
12946                      sym->name, &e->where, sym->ns->proc_name->name);
12947           break;
12948         }
12949
12950       /* Shall not be a named constant.  */
12951       if (e->expr_type == EXPR_CONSTANT)
12952         {
12953           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
12954                      "object", sym->name, &e->where);
12955           continue;
12956         }
12957
12958       if (e->ts.type == BT_DERIVED
12959           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
12960         continue;
12961
12962       /* Check that the types correspond correctly:
12963          Note 5.28:
12964          A numeric sequence structure may be equivalenced to another sequence
12965          structure, an object of default integer type, default real type, double
12966          precision real type, default logical type such that components of the
12967          structure ultimately only become associated to objects of the same
12968          kind. A character sequence structure may be equivalenced to an object
12969          of default character kind or another character sequence structure.
12970          Other objects may be equivalenced only to objects of the same type and
12971          kind parameters.  */
12972
12973       /* Identical types are unconditionally OK.  */
12974       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
12975         goto identical_types;
12976
12977       last_eq_type = sequence_type (*last_ts);
12978       eq_type = sequence_type (sym->ts);
12979
12980       /* Since the pair of objects is not of the same type, mixed or
12981          non-default sequences can be rejected.  */
12982
12983       msg = "Sequence %s with mixed components in EQUIVALENCE "
12984             "statement at %L with different type objects";
12985       if ((object ==2
12986            && last_eq_type == SEQ_MIXED
12987            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
12988               == FAILURE)
12989           || (eq_type == SEQ_MIXED
12990               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12991                                  &e->where) == FAILURE))
12992         continue;
12993
12994       msg = "Non-default type object or sequence %s in EQUIVALENCE "
12995             "statement at %L with objects of different type";
12996       if ((object ==2
12997            && last_eq_type == SEQ_NONDEFAULT
12998            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
12999                               last_where) == FAILURE)
13000           || (eq_type == SEQ_NONDEFAULT
13001               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13002                                  &e->where) == FAILURE))
13003         continue;
13004
13005       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13006            "EQUIVALENCE statement at %L";
13007       if (last_eq_type == SEQ_CHARACTER
13008           && eq_type != SEQ_CHARACTER
13009           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13010                              &e->where) == FAILURE)
13011                 continue;
13012
13013       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13014            "EQUIVALENCE statement at %L";
13015       if (last_eq_type == SEQ_NUMERIC
13016           && eq_type != SEQ_NUMERIC
13017           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13018                              &e->where) == FAILURE)
13019                 continue;
13020
13021   identical_types:
13022       last_ts =&sym->ts;
13023       last_where = &e->where;
13024
13025       if (!e->ref)
13026         continue;
13027
13028       /* Shall not be an automatic array.  */
13029       if (e->ref->type == REF_ARRAY
13030           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13031         {
13032           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13033                      "an EQUIVALENCE object", sym->name, &e->where);
13034           continue;
13035         }
13036
13037       r = e->ref;
13038       while (r)
13039         {
13040           /* Shall not be a structure component.  */
13041           if (r->type == REF_COMPONENT)
13042             {
13043               gfc_error ("Structure component '%s' at %L cannot be an "
13044                          "EQUIVALENCE object",
13045                          r->u.c.component->name, &e->where);
13046               break;
13047             }
13048
13049           /* A substring shall not have length zero.  */
13050           if (r->type == REF_SUBSTRING)
13051             {
13052               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13053                 {
13054                   gfc_error ("Substring at %L has length zero",
13055                              &r->u.ss.start->where);
13056                   break;
13057                 }
13058             }
13059           r = r->next;
13060         }
13061     }
13062 }
13063
13064
13065 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13066
13067 static void
13068 resolve_fntype (gfc_namespace *ns)
13069 {
13070   gfc_entry_list *el;
13071   gfc_symbol *sym;
13072
13073   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13074     return;
13075
13076   /* If there are any entries, ns->proc_name is the entry master
13077      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13078   if (ns->entries)
13079     sym = ns->entries->sym;
13080   else
13081     sym = ns->proc_name;
13082   if (sym->result == sym
13083       && sym->ts.type == BT_UNKNOWN
13084       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13085       && !sym->attr.untyped)
13086     {
13087       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13088                  sym->name, &sym->declared_at);
13089       sym->attr.untyped = 1;
13090     }
13091
13092   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13093       && !sym->attr.contained
13094       && !gfc_check_access (sym->ts.u.derived->attr.access,
13095                             sym->ts.u.derived->ns->default_access)
13096       && gfc_check_access (sym->attr.access, sym->ns->default_access))
13097     {
13098       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13099                       "%L of PRIVATE type '%s'", sym->name,
13100                       &sym->declared_at, sym->ts.u.derived->name);
13101     }
13102
13103     if (ns->entries)
13104     for (el = ns->entries->next; el; el = el->next)
13105       {
13106         if (el->sym->result == el->sym
13107             && el->sym->ts.type == BT_UNKNOWN
13108             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13109             && !el->sym->attr.untyped)
13110           {
13111             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13112                        el->sym->name, &el->sym->declared_at);
13113             el->sym->attr.untyped = 1;
13114           }
13115       }
13116 }
13117
13118
13119 /* 12.3.2.1.1 Defined operators.  */
13120
13121 static gfc_try
13122 check_uop_procedure (gfc_symbol *sym, locus where)
13123 {
13124   gfc_formal_arglist *formal;
13125
13126   if (!sym->attr.function)
13127     {
13128       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13129                  sym->name, &where);
13130       return FAILURE;
13131     }
13132
13133   if (sym->ts.type == BT_CHARACTER
13134       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13135       && !(sym->result && sym->result->ts.u.cl
13136            && sym->result->ts.u.cl->length))
13137     {
13138       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13139                  "character length", sym->name, &where);
13140       return FAILURE;
13141     }
13142
13143   formal = sym->formal;
13144   if (!formal || !formal->sym)
13145     {
13146       gfc_error ("User operator procedure '%s' at %L must have at least "
13147                  "one argument", sym->name, &where);
13148       return FAILURE;
13149     }
13150
13151   if (formal->sym->attr.intent != INTENT_IN)
13152     {
13153       gfc_error ("First argument of operator interface at %L must be "
13154                  "INTENT(IN)", &where);
13155       return FAILURE;
13156     }
13157
13158   if (formal->sym->attr.optional)
13159     {
13160       gfc_error ("First argument of operator interface at %L cannot be "
13161                  "optional", &where);
13162       return FAILURE;
13163     }
13164
13165   formal = formal->next;
13166   if (!formal || !formal->sym)
13167     return SUCCESS;
13168
13169   if (formal->sym->attr.intent != INTENT_IN)
13170     {
13171       gfc_error ("Second argument of operator interface at %L must be "
13172                  "INTENT(IN)", &where);
13173       return FAILURE;
13174     }
13175
13176   if (formal->sym->attr.optional)
13177     {
13178       gfc_error ("Second argument of operator interface at %L cannot be "
13179                  "optional", &where);
13180       return FAILURE;
13181     }
13182
13183   if (formal->next)
13184     {
13185       gfc_error ("Operator interface at %L must have, at most, two "
13186                  "arguments", &where);
13187       return FAILURE;
13188     }
13189
13190   return SUCCESS;
13191 }
13192
13193 static void
13194 gfc_resolve_uops (gfc_symtree *symtree)
13195 {
13196   gfc_interface *itr;
13197
13198   if (symtree == NULL)
13199     return;
13200
13201   gfc_resolve_uops (symtree->left);
13202   gfc_resolve_uops (symtree->right);
13203
13204   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13205     check_uop_procedure (itr->sym, itr->sym->declared_at);
13206 }
13207
13208
13209 /* Examine all of the expressions associated with a program unit,
13210    assign types to all intermediate expressions, make sure that all
13211    assignments are to compatible types and figure out which names
13212    refer to which functions or subroutines.  It doesn't check code
13213    block, which is handled by resolve_code.  */
13214
13215 static void
13216 resolve_types (gfc_namespace *ns)
13217 {
13218   gfc_namespace *n;
13219   gfc_charlen *cl;
13220   gfc_data *d;
13221   gfc_equiv *eq;
13222   gfc_namespace* old_ns = gfc_current_ns;
13223
13224   /* Check that all IMPLICIT types are ok.  */
13225   if (!ns->seen_implicit_none)
13226     {
13227       unsigned letter;
13228       for (letter = 0; letter != GFC_LETTERS; ++letter)
13229         if (ns->set_flag[letter]
13230             && resolve_typespec_used (&ns->default_type[letter],
13231                                       &ns->implicit_loc[letter],
13232                                       NULL) == FAILURE)
13233           return;
13234     }
13235
13236   gfc_current_ns = ns;
13237
13238   resolve_entries (ns);
13239
13240   resolve_common_vars (ns->blank_common.head, false);
13241   resolve_common_blocks (ns->common_root);
13242
13243   resolve_contained_functions (ns);
13244
13245   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13246
13247   for (cl = ns->cl_list; cl; cl = cl->next)
13248     resolve_charlen (cl);
13249
13250   gfc_traverse_ns (ns, resolve_symbol);
13251
13252   resolve_fntype (ns);
13253
13254   for (n = ns->contained; n; n = n->sibling)
13255     {
13256       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13257         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13258                    "also be PURE", n->proc_name->name,
13259                    &n->proc_name->declared_at);
13260
13261       resolve_types (n);
13262     }
13263
13264   forall_flag = 0;
13265   gfc_check_interfaces (ns);
13266
13267   gfc_traverse_ns (ns, resolve_values);
13268
13269   if (ns->save_all)
13270     gfc_save_all (ns);
13271
13272   iter_stack = NULL;
13273   for (d = ns->data; d; d = d->next)
13274     resolve_data (d);
13275
13276   iter_stack = NULL;
13277   gfc_traverse_ns (ns, gfc_formalize_init_value);
13278
13279   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13280
13281   if (ns->common_root != NULL)
13282     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13283
13284   for (eq = ns->equiv; eq; eq = eq->next)
13285     resolve_equivalence (eq);
13286
13287   /* Warn about unused labels.  */
13288   if (warn_unused_label)
13289     warn_unused_fortran_label (ns->st_labels);
13290
13291   gfc_resolve_uops (ns->uop_root);
13292
13293   gfc_current_ns = old_ns;
13294 }
13295
13296
13297 /* Call resolve_code recursively.  */
13298
13299 static void
13300 resolve_codes (gfc_namespace *ns)
13301 {
13302   gfc_namespace *n;
13303   bitmap_obstack old_obstack;
13304
13305   for (n = ns->contained; n; n = n->sibling)
13306     resolve_codes (n);
13307
13308   gfc_current_ns = ns;
13309
13310   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13311   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13312     cs_base = NULL;
13313
13314   /* Set to an out of range value.  */
13315   current_entry_id = -1;
13316
13317   old_obstack = labels_obstack;
13318   bitmap_obstack_initialize (&labels_obstack);
13319
13320   resolve_code (ns->code, ns);
13321
13322   bitmap_obstack_release (&labels_obstack);
13323   labels_obstack = old_obstack;
13324 }
13325
13326
13327 /* This function is called after a complete program unit has been compiled.
13328    Its purpose is to examine all of the expressions associated with a program
13329    unit, assign types to all intermediate expressions, make sure that all
13330    assignments are to compatible types and figure out which names refer to
13331    which functions or subroutines.  */
13332
13333 void
13334 gfc_resolve (gfc_namespace *ns)
13335 {
13336   gfc_namespace *old_ns;
13337   code_stack *old_cs_base;
13338
13339   if (ns->resolved)
13340     return;
13341
13342   ns->resolved = -1;
13343   old_ns = gfc_current_ns;
13344   old_cs_base = cs_base;
13345
13346   resolve_types (ns);
13347   resolve_codes (ns);
13348
13349   gfc_current_ns = old_ns;
13350   cs_base = old_cs_base;
13351   ns->resolved = 1;
13352
13353   gfc_run_passes (ns);
13354 }