OSDN Git Service

2010-08-30 Janus Weil <janus@gcc.gnu.org>
[pf3gnuchains/gcc-fork.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
934   if (expr->ts.type == BT_DERIVED)
935     resolve_symbol (expr->ts.u.derived);
936
937   cons = gfc_constructor_first (expr->value.constructor);
938   /* A constructor may have references if it is the result of substituting a
939      parameter variable.  In this case we just pull out the component we
940      want.  */
941   if (expr->ref)
942     comp = expr->ref->u.c.sym->components;
943   else
944     comp = expr->ts.u.derived->components;
945
946   /* See if the user is trying to invoke a structure constructor for one of
947      the iso_c_binding derived types.  */
948   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
949       && expr->ts.u.derived->ts.is_iso_c && cons
950       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
951     {
952       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
953                  expr->ts.u.derived->name, &(expr->where));
954       return FAILURE;
955     }
956
957   /* Return if structure constructor is c_null_(fun)prt.  */
958   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
959       && expr->ts.u.derived->ts.is_iso_c && cons
960       && cons->expr && cons->expr->expr_type == EXPR_NULL)
961     return SUCCESS;
962
963   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
964     {
965       int rank;
966
967       if (!cons->expr)
968         continue;
969
970       if (gfc_resolve_expr (cons->expr) == FAILURE)
971         {
972           t = FAILURE;
973           continue;
974         }
975
976       rank = comp->as ? comp->as->rank : 0;
977       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
978           && (comp->attr.allocatable || cons->expr->rank))
979         {
980           gfc_error ("The rank of the element in the derived type "
981                      "constructor at %L does not match that of the "
982                      "component (%d/%d)", &cons->expr->where,
983                      cons->expr->rank, rank);
984           t = FAILURE;
985         }
986
987       /* If we don't have the right type, try to convert it.  */
988
989       if (!comp->attr.proc_pointer &&
990           !gfc_compare_types (&cons->expr->ts, &comp->ts))
991         {
992           t = FAILURE;
993           if (strcmp (comp->name, "$extends") == 0)
994             {
995               /* Can afford to be brutal with the $extends initializer.
996                  The derived type can get lost because it is PRIVATE
997                  but it is not usage constrained by the standard.  */
998               cons->expr->ts = comp->ts;
999               t = SUCCESS;
1000             }
1001           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1002             gfc_error ("The element in the derived type constructor at %L, "
1003                        "for pointer component '%s', is %s but should be %s",
1004                        &cons->expr->where, comp->name,
1005                        gfc_basic_typename (cons->expr->ts.type),
1006                        gfc_basic_typename (comp->ts.type));
1007           else
1008             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1009         }
1010
1011       /* For strings, the length of the constructor should be the same as
1012          the one of the structure, ensure this if the lengths are known at
1013          compile time and when we are dealing with PARAMETER or structure
1014          constructors.  */
1015       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1016           && comp->ts.u.cl->length
1017           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1018           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1019           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1020           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1021                       comp->ts.u.cl->length->value.integer) != 0)
1022         {
1023           if (cons->expr->expr_type == EXPR_VARIABLE
1024               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1025             {
1026               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1027                  to make use of the gfc_resolve_character_array_constructor
1028                  machinery.  The expression is later simplified away to
1029                  an array of string literals.  */
1030               gfc_expr *para = cons->expr;
1031               cons->expr = gfc_get_expr ();
1032               cons->expr->ts = para->ts;
1033               cons->expr->where = para->where;
1034               cons->expr->expr_type = EXPR_ARRAY;
1035               cons->expr->rank = para->rank;
1036               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1037               gfc_constructor_append_expr (&cons->expr->value.constructor,
1038                                            para, &cons->expr->where);
1039             }
1040           if (cons->expr->expr_type == EXPR_ARRAY)
1041             {
1042               gfc_constructor *p;
1043               p = gfc_constructor_first (cons->expr->value.constructor);
1044               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1045                 {
1046                   gfc_charlen *cl, *cl2;
1047
1048                   cl2 = NULL;
1049                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1050                     {
1051                       if (cl == cons->expr->ts.u.cl)
1052                         break;
1053                       cl2 = cl;
1054                     }
1055
1056                   gcc_assert (cl);
1057
1058                   if (cl2)
1059                     cl2->next = cl->next;
1060
1061                   gfc_free_expr (cl->length);
1062                   gfc_free (cl);
1063                 }
1064
1065               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1066               cons->expr->ts.u.cl->length_from_typespec = true;
1067               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1068               gfc_resolve_character_array_constructor (cons->expr);
1069             }
1070         }
1071
1072       if (cons->expr->expr_type == EXPR_NULL
1073           && !(comp->attr.pointer || comp->attr.allocatable
1074                || comp->attr.proc_pointer
1075                || (comp->ts.type == BT_CLASS
1076                    && (CLASS_DATA (comp)->attr.class_pointer
1077                        || CLASS_DATA (comp)->attr.allocatable))))
1078         {
1079           t = FAILURE;
1080           gfc_error ("The NULL in the derived type constructor at %L is "
1081                      "being applied to component '%s', which is neither "
1082                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1083                      comp->name);
1084         }
1085
1086       if (!comp->attr.pointer || comp->attr.proc_pointer
1087           || cons->expr->expr_type == EXPR_NULL)
1088         continue;
1089
1090       a = gfc_expr_attr (cons->expr);
1091
1092       if (!a.pointer && !a.target)
1093         {
1094           t = FAILURE;
1095           gfc_error ("The element in the derived type constructor at %L, "
1096                      "for pointer component '%s' should be a POINTER or "
1097                      "a TARGET", &cons->expr->where, comp->name);
1098         }
1099
1100       if (init)
1101         {
1102           /* F08:C461. Additional checks for pointer initialization.  */
1103           if (a.allocatable)
1104             {
1105               t = FAILURE;
1106               gfc_error ("Pointer initialization target at %L "
1107                          "must not be ALLOCATABLE ", &cons->expr->where);
1108             }
1109           if (!a.save)
1110             {
1111               t = FAILURE;
1112               gfc_error ("Pointer initialization target at %L "
1113                          "must have the SAVE attribute", &cons->expr->where);
1114             }
1115         }
1116
1117       /* F2003, C1272 (3).  */
1118       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1119           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1120               || gfc_is_coindexed (cons->expr)))
1121         {
1122           t = FAILURE;
1123           gfc_error ("Invalid expression in the derived type constructor for "
1124                      "pointer component '%s' at %L in PURE procedure",
1125                      comp->name, &cons->expr->where);
1126         }
1127
1128     }
1129
1130   return t;
1131 }
1132
1133
1134 /****************** Expression name resolution ******************/
1135
1136 /* Returns 0 if a symbol was not declared with a type or
1137    attribute declaration statement, nonzero otherwise.  */
1138
1139 static int
1140 was_declared (gfc_symbol *sym)
1141 {
1142   symbol_attribute a;
1143
1144   a = sym->attr;
1145
1146   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1147     return 1;
1148
1149   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1150       || a.optional || a.pointer || a.save || a.target || a.volatile_
1151       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1152       || a.asynchronous || a.codimension)
1153     return 1;
1154
1155   return 0;
1156 }
1157
1158
1159 /* Determine if a symbol is generic or not.  */
1160
1161 static int
1162 generic_sym (gfc_symbol *sym)
1163 {
1164   gfc_symbol *s;
1165
1166   if (sym->attr.generic ||
1167       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1168     return 1;
1169
1170   if (was_declared (sym) || sym->ns->parent == NULL)
1171     return 0;
1172
1173   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1174   
1175   if (s != NULL)
1176     {
1177       if (s == sym)
1178         return 0;
1179       else
1180         return generic_sym (s);
1181     }
1182
1183   return 0;
1184 }
1185
1186
1187 /* Determine if a symbol is specific or not.  */
1188
1189 static int
1190 specific_sym (gfc_symbol *sym)
1191 {
1192   gfc_symbol *s;
1193
1194   if (sym->attr.if_source == IFSRC_IFBODY
1195       || sym->attr.proc == PROC_MODULE
1196       || sym->attr.proc == PROC_INTERNAL
1197       || sym->attr.proc == PROC_ST_FUNCTION
1198       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1199       || sym->attr.external)
1200     return 1;
1201
1202   if (was_declared (sym) || sym->ns->parent == NULL)
1203     return 0;
1204
1205   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1206
1207   return (s == NULL) ? 0 : specific_sym (s);
1208 }
1209
1210
1211 /* Figure out if the procedure is specific, generic or unknown.  */
1212
1213 typedef enum
1214 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1215 proc_type;
1216
1217 static proc_type
1218 procedure_kind (gfc_symbol *sym)
1219 {
1220   if (generic_sym (sym))
1221     return PTYPE_GENERIC;
1222
1223   if (specific_sym (sym))
1224     return PTYPE_SPECIFIC;
1225
1226   return PTYPE_UNKNOWN;
1227 }
1228
1229 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1230    is nonzero when matching actual arguments.  */
1231
1232 static int need_full_assumed_size = 0;
1233
1234 static bool
1235 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1236 {
1237   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1238       return false;
1239
1240   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1241      What should it be?  */
1242   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1243           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1244                && (e->ref->u.ar.type == AR_FULL))
1245     {
1246       gfc_error ("The upper bound in the last dimension must "
1247                  "appear in the reference to the assumed size "
1248                  "array '%s' at %L", sym->name, &e->where);
1249       return true;
1250     }
1251   return false;
1252 }
1253
1254
1255 /* Look for bad assumed size array references in argument expressions
1256   of elemental and array valued intrinsic procedures.  Since this is
1257   called from procedure resolution functions, it only recurses at
1258   operators.  */
1259
1260 static bool
1261 resolve_assumed_size_actual (gfc_expr *e)
1262 {
1263   if (e == NULL)
1264    return false;
1265
1266   switch (e->expr_type)
1267     {
1268     case EXPR_VARIABLE:
1269       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1270         return true;
1271       break;
1272
1273     case EXPR_OP:
1274       if (resolve_assumed_size_actual (e->value.op.op1)
1275           || resolve_assumed_size_actual (e->value.op.op2))
1276         return true;
1277       break;
1278
1279     default:
1280       break;
1281     }
1282   return false;
1283 }
1284
1285
1286 /* Check a generic procedure, passed as an actual argument, to see if
1287    there is a matching specific name.  If none, it is an error, and if
1288    more than one, the reference is ambiguous.  */
1289 static int
1290 count_specific_procs (gfc_expr *e)
1291 {
1292   int n;
1293   gfc_interface *p;
1294   gfc_symbol *sym;
1295         
1296   n = 0;
1297   sym = e->symtree->n.sym;
1298
1299   for (p = sym->generic; p; p = p->next)
1300     if (strcmp (sym->name, p->sym->name) == 0)
1301       {
1302         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1303                                        sym->name);
1304         n++;
1305       }
1306
1307   if (n > 1)
1308     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1309                &e->where);
1310
1311   if (n == 0)
1312     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1313                "argument at %L", sym->name, &e->where);
1314
1315   return n;
1316 }
1317
1318
1319 /* See if a call to sym could possibly be a not allowed RECURSION because of
1320    a missing RECURIVE declaration.  This means that either sym is the current
1321    context itself, or sym is the parent of a contained procedure calling its
1322    non-RECURSIVE containing procedure.
1323    This also works if sym is an ENTRY.  */
1324
1325 static bool
1326 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1327 {
1328   gfc_symbol* proc_sym;
1329   gfc_symbol* context_proc;
1330   gfc_namespace* real_context;
1331
1332   if (sym->attr.flavor == FL_PROGRAM)
1333     return false;
1334
1335   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1336
1337   /* If we've got an ENTRY, find real procedure.  */
1338   if (sym->attr.entry && sym->ns->entries)
1339     proc_sym = sym->ns->entries->sym;
1340   else
1341     proc_sym = sym;
1342
1343   /* If sym is RECURSIVE, all is well of course.  */
1344   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1345     return false;
1346
1347   /* Find the context procedure's "real" symbol if it has entries.
1348      We look for a procedure symbol, so recurse on the parents if we don't
1349      find one (like in case of a BLOCK construct).  */
1350   for (real_context = context; ; real_context = real_context->parent)
1351     {
1352       /* We should find something, eventually!  */
1353       gcc_assert (real_context);
1354
1355       context_proc = (real_context->entries ? real_context->entries->sym
1356                                             : real_context->proc_name);
1357
1358       /* In some special cases, there may not be a proc_name, like for this
1359          invalid code:
1360          real(bad_kind()) function foo () ...
1361          when checking the call to bad_kind ().
1362          In these cases, we simply return here and assume that the
1363          call is ok.  */
1364       if (!context_proc)
1365         return false;
1366
1367       if (context_proc->attr.flavor != FL_LABEL)
1368         break;
1369     }
1370
1371   /* A call from sym's body to itself is recursion, of course.  */
1372   if (context_proc == proc_sym)
1373     return true;
1374
1375   /* The same is true if context is a contained procedure and sym the
1376      containing one.  */
1377   if (context_proc->attr.contained)
1378     {
1379       gfc_symbol* parent_proc;
1380
1381       gcc_assert (context->parent);
1382       parent_proc = (context->parent->entries ? context->parent->entries->sym
1383                                               : context->parent->proc_name);
1384
1385       if (parent_proc == proc_sym)
1386         return true;
1387     }
1388
1389   return false;
1390 }
1391
1392
1393 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1394    its typespec and formal argument list.  */
1395
1396 static gfc_try
1397 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1398 {
1399   gfc_intrinsic_sym* isym;
1400   const char* symstd;
1401
1402   if (sym->formal)
1403     return SUCCESS;
1404
1405   /* We already know this one is an intrinsic, so we don't call
1406      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1407      gfc_find_subroutine directly to check whether it is a function or
1408      subroutine.  */
1409
1410   if ((isym = gfc_find_function (sym->name)))
1411     {
1412       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1413           && !sym->attr.implicit_type)
1414         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1415                       " ignored", sym->name, &sym->declared_at);
1416
1417       if (!sym->attr.function &&
1418           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1419         return FAILURE;
1420
1421       sym->ts = isym->ts;
1422     }
1423   else if ((isym = gfc_find_subroutine (sym->name)))
1424     {
1425       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1426         {
1427           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1428                       " specifier", sym->name, &sym->declared_at);
1429           return FAILURE;
1430         }
1431
1432       if (!sym->attr.subroutine &&
1433           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1434         return FAILURE;
1435     }
1436   else
1437     {
1438       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1439                  &sym->declared_at);
1440       return FAILURE;
1441     }
1442
1443   gfc_copy_formal_args_intr (sym, isym);
1444
1445   /* Check it is actually available in the standard settings.  */
1446   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1447       == FAILURE)
1448     {
1449       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1450                  " available in the current standard settings but %s.  Use"
1451                  " an appropriate -std=* option or enable -fall-intrinsics"
1452                  " in order to use it.",
1453                  sym->name, &sym->declared_at, symstd);
1454       return FAILURE;
1455     }
1456
1457   return SUCCESS;
1458 }
1459
1460
1461 /* Resolve a procedure expression, like passing it to a called procedure or as
1462    RHS for a procedure pointer assignment.  */
1463
1464 static gfc_try
1465 resolve_procedure_expression (gfc_expr* expr)
1466 {
1467   gfc_symbol* sym;
1468
1469   if (expr->expr_type != EXPR_VARIABLE)
1470     return SUCCESS;
1471   gcc_assert (expr->symtree);
1472
1473   sym = expr->symtree->n.sym;
1474
1475   if (sym->attr.intrinsic)
1476     resolve_intrinsic (sym, &expr->where);
1477
1478   if (sym->attr.flavor != FL_PROCEDURE
1479       || (sym->attr.function && sym->result == sym))
1480     return SUCCESS;
1481
1482   /* A non-RECURSIVE procedure that is used as procedure expression within its
1483      own body is in danger of being called recursively.  */
1484   if (is_illegal_recursion (sym, gfc_current_ns))
1485     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1486                  " itself recursively.  Declare it RECURSIVE or use"
1487                  " -frecursive", sym->name, &expr->where);
1488   
1489   return SUCCESS;
1490 }
1491
1492
1493 /* Resolve an actual argument list.  Most of the time, this is just
1494    resolving the expressions in the list.
1495    The exception is that we sometimes have to decide whether arguments
1496    that look like procedure arguments are really simple variable
1497    references.  */
1498
1499 static gfc_try
1500 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1501                         bool no_formal_args)
1502 {
1503   gfc_symbol *sym;
1504   gfc_symtree *parent_st;
1505   gfc_expr *e;
1506   int save_need_full_assumed_size;
1507   gfc_component *comp;
1508
1509   for (; arg; arg = arg->next)
1510     {
1511       e = arg->expr;
1512       if (e == NULL)
1513         {
1514           /* Check the label is a valid branching target.  */
1515           if (arg->label)
1516             {
1517               if (arg->label->defined == ST_LABEL_UNKNOWN)
1518                 {
1519                   gfc_error ("Label %d referenced at %L is never defined",
1520                              arg->label->value, &arg->label->where);
1521                   return FAILURE;
1522                 }
1523             }
1524           continue;
1525         }
1526
1527       if (gfc_is_proc_ptr_comp (e, &comp))
1528         {
1529           e->ts = comp->ts;
1530           if (e->expr_type == EXPR_PPC)
1531             {
1532               if (comp->as != NULL)
1533                 e->rank = comp->as->rank;
1534               e->expr_type = EXPR_FUNCTION;
1535             }
1536           if (gfc_resolve_expr (e) == FAILURE)                          
1537             return FAILURE; 
1538           goto argument_list;
1539         }
1540
1541       if (e->expr_type == EXPR_VARIABLE
1542             && e->symtree->n.sym->attr.generic
1543             && no_formal_args
1544             && count_specific_procs (e) != 1)
1545         return FAILURE;
1546
1547       if (e->ts.type != BT_PROCEDURE)
1548         {
1549           save_need_full_assumed_size = need_full_assumed_size;
1550           if (e->expr_type != EXPR_VARIABLE)
1551             need_full_assumed_size = 0;
1552           if (gfc_resolve_expr (e) != SUCCESS)
1553             return FAILURE;
1554           need_full_assumed_size = save_need_full_assumed_size;
1555           goto argument_list;
1556         }
1557
1558       /* See if the expression node should really be a variable reference.  */
1559
1560       sym = e->symtree->n.sym;
1561
1562       if (sym->attr.flavor == FL_PROCEDURE
1563           || sym->attr.intrinsic
1564           || sym->attr.external)
1565         {
1566           int actual_ok;
1567
1568           /* If a procedure is not already determined to be something else
1569              check if it is intrinsic.  */
1570           if (!sym->attr.intrinsic
1571               && !(sym->attr.external || sym->attr.use_assoc
1572                    || sym->attr.if_source == IFSRC_IFBODY)
1573               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1574             sym->attr.intrinsic = 1;
1575
1576           if (sym->attr.proc == PROC_ST_FUNCTION)
1577             {
1578               gfc_error ("Statement function '%s' at %L is not allowed as an "
1579                          "actual argument", sym->name, &e->where);
1580             }
1581
1582           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1583                                                sym->attr.subroutine);
1584           if (sym->attr.intrinsic && actual_ok == 0)
1585             {
1586               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1587                          "actual argument", sym->name, &e->where);
1588             }
1589
1590           if (sym->attr.contained && !sym->attr.use_assoc
1591               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1592             {
1593               gfc_error ("Internal procedure '%s' is not allowed as an "
1594                          "actual argument at %L", sym->name, &e->where);
1595             }
1596
1597           if (sym->attr.elemental && !sym->attr.intrinsic)
1598             {
1599               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1600                          "allowed as an actual argument at %L", sym->name,
1601                          &e->where);
1602             }
1603
1604           /* Check if a generic interface has a specific procedure
1605             with the same name before emitting an error.  */
1606           if (sym->attr.generic && count_specific_procs (e) != 1)
1607             return FAILURE;
1608           
1609           /* Just in case a specific was found for the expression.  */
1610           sym = e->symtree->n.sym;
1611
1612           /* If the symbol is the function that names the current (or
1613              parent) scope, then we really have a variable reference.  */
1614
1615           if (gfc_is_function_return_value (sym, sym->ns))
1616             goto got_variable;
1617
1618           /* If all else fails, see if we have a specific intrinsic.  */
1619           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1620             {
1621               gfc_intrinsic_sym *isym;
1622
1623               isym = gfc_find_function (sym->name);
1624               if (isym == NULL || !isym->specific)
1625                 {
1626                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1627                              "for the reference '%s' at %L", sym->name,
1628                              &e->where);
1629                   return FAILURE;
1630                 }
1631               sym->ts = isym->ts;
1632               sym->attr.intrinsic = 1;
1633               sym->attr.function = 1;
1634             }
1635
1636           if (gfc_resolve_expr (e) == FAILURE)
1637             return FAILURE;
1638           goto argument_list;
1639         }
1640
1641       /* See if the name is a module procedure in a parent unit.  */
1642
1643       if (was_declared (sym) || sym->ns->parent == NULL)
1644         goto got_variable;
1645
1646       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1647         {
1648           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1649           return FAILURE;
1650         }
1651
1652       if (parent_st == NULL)
1653         goto got_variable;
1654
1655       sym = parent_st->n.sym;
1656       e->symtree = parent_st;           /* Point to the right thing.  */
1657
1658       if (sym->attr.flavor == FL_PROCEDURE
1659           || sym->attr.intrinsic
1660           || sym->attr.external)
1661         {
1662           if (gfc_resolve_expr (e) == FAILURE)
1663             return FAILURE;
1664           goto argument_list;
1665         }
1666
1667     got_variable:
1668       e->expr_type = EXPR_VARIABLE;
1669       e->ts = sym->ts;
1670       if (sym->as != NULL)
1671         {
1672           e->rank = sym->as->rank;
1673           e->ref = gfc_get_ref ();
1674           e->ref->type = REF_ARRAY;
1675           e->ref->u.ar.type = AR_FULL;
1676           e->ref->u.ar.as = sym->as;
1677         }
1678
1679       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1680          primary.c (match_actual_arg). If above code determines that it
1681          is a  variable instead, it needs to be resolved as it was not
1682          done at the beginning of this function.  */
1683       save_need_full_assumed_size = need_full_assumed_size;
1684       if (e->expr_type != EXPR_VARIABLE)
1685         need_full_assumed_size = 0;
1686       if (gfc_resolve_expr (e) != SUCCESS)
1687         return FAILURE;
1688       need_full_assumed_size = save_need_full_assumed_size;
1689
1690     argument_list:
1691       /* Check argument list functions %VAL, %LOC and %REF.  There is
1692          nothing to do for %REF.  */
1693       if (arg->name && arg->name[0] == '%')
1694         {
1695           if (strncmp ("%VAL", arg->name, 4) == 0)
1696             {
1697               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1698                 {
1699                   gfc_error ("By-value argument at %L is not of numeric "
1700                              "type", &e->where);
1701                   return FAILURE;
1702                 }
1703
1704               if (e->rank)
1705                 {
1706                   gfc_error ("By-value argument at %L cannot be an array or "
1707                              "an array section", &e->where);
1708                 return FAILURE;
1709                 }
1710
1711               /* Intrinsics are still PROC_UNKNOWN here.  However,
1712                  since same file external procedures are not resolvable
1713                  in gfortran, it is a good deal easier to leave them to
1714                  intrinsic.c.  */
1715               if (ptype != PROC_UNKNOWN
1716                   && ptype != PROC_DUMMY
1717                   && ptype != PROC_EXTERNAL
1718                   && ptype != PROC_MODULE)
1719                 {
1720                   gfc_error ("By-value argument at %L is not allowed "
1721                              "in this context", &e->where);
1722                   return FAILURE;
1723                 }
1724             }
1725
1726           /* Statement functions have already been excluded above.  */
1727           else if (strncmp ("%LOC", arg->name, 4) == 0
1728                    && e->ts.type == BT_PROCEDURE)
1729             {
1730               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1731                 {
1732                   gfc_error ("Passing internal procedure at %L by location "
1733                              "not allowed", &e->where);
1734                   return FAILURE;
1735                 }
1736             }
1737         }
1738
1739       /* Fortran 2008, C1237.  */
1740       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1741           && gfc_has_ultimate_pointer (e))
1742         {
1743           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1744                      "component", &e->where);
1745           return FAILURE;
1746         }
1747     }
1748
1749   return SUCCESS;
1750 }
1751
1752
1753 /* Do the checks of the actual argument list that are specific to elemental
1754    procedures.  If called with c == NULL, we have a function, otherwise if
1755    expr == NULL, we have a subroutine.  */
1756
1757 static gfc_try
1758 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1759 {
1760   gfc_actual_arglist *arg0;
1761   gfc_actual_arglist *arg;
1762   gfc_symbol *esym = NULL;
1763   gfc_intrinsic_sym *isym = NULL;
1764   gfc_expr *e = NULL;
1765   gfc_intrinsic_arg *iformal = NULL;
1766   gfc_formal_arglist *eformal = NULL;
1767   bool formal_optional = false;
1768   bool set_by_optional = false;
1769   int i;
1770   int rank = 0;
1771
1772   /* Is this an elemental procedure?  */
1773   if (expr && expr->value.function.actual != NULL)
1774     {
1775       if (expr->value.function.esym != NULL
1776           && expr->value.function.esym->attr.elemental)
1777         {
1778           arg0 = expr->value.function.actual;
1779           esym = expr->value.function.esym;
1780         }
1781       else if (expr->value.function.isym != NULL
1782                && expr->value.function.isym->elemental)
1783         {
1784           arg0 = expr->value.function.actual;
1785           isym = expr->value.function.isym;
1786         }
1787       else
1788         return SUCCESS;
1789     }
1790   else if (c && c->ext.actual != NULL)
1791     {
1792       arg0 = c->ext.actual;
1793       
1794       if (c->resolved_sym)
1795         esym = c->resolved_sym;
1796       else
1797         esym = c->symtree->n.sym;
1798       gcc_assert (esym);
1799
1800       if (!esym->attr.elemental)
1801         return SUCCESS;
1802     }
1803   else
1804     return SUCCESS;
1805
1806   /* The rank of an elemental is the rank of its array argument(s).  */
1807   for (arg = arg0; arg; arg = arg->next)
1808     {
1809       if (arg->expr != NULL && arg->expr->rank > 0)
1810         {
1811           rank = arg->expr->rank;
1812           if (arg->expr->expr_type == EXPR_VARIABLE
1813               && arg->expr->symtree->n.sym->attr.optional)
1814             set_by_optional = true;
1815
1816           /* Function specific; set the result rank and shape.  */
1817           if (expr)
1818             {
1819               expr->rank = rank;
1820               if (!expr->shape && arg->expr->shape)
1821                 {
1822                   expr->shape = gfc_get_shape (rank);
1823                   for (i = 0; i < rank; i++)
1824                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1825                 }
1826             }
1827           break;
1828         }
1829     }
1830
1831   /* If it is an array, it shall not be supplied as an actual argument
1832      to an elemental procedure unless an array of the same rank is supplied
1833      as an actual argument corresponding to a nonoptional dummy argument of
1834      that elemental procedure(12.4.1.5).  */
1835   formal_optional = false;
1836   if (isym)
1837     iformal = isym->formal;
1838   else
1839     eformal = esym->formal;
1840
1841   for (arg = arg0; arg; arg = arg->next)
1842     {
1843       if (eformal)
1844         {
1845           if (eformal->sym && eformal->sym->attr.optional)
1846             formal_optional = true;
1847           eformal = eformal->next;
1848         }
1849       else if (isym && iformal)
1850         {
1851           if (iformal->optional)
1852             formal_optional = true;
1853           iformal = iformal->next;
1854         }
1855       else if (isym)
1856         formal_optional = true;
1857
1858       if (pedantic && arg->expr != NULL
1859           && arg->expr->expr_type == EXPR_VARIABLE
1860           && arg->expr->symtree->n.sym->attr.optional
1861           && formal_optional
1862           && arg->expr->rank
1863           && (set_by_optional || arg->expr->rank != rank)
1864           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1865         {
1866           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1867                        "MISSING, it cannot be the actual argument of an "
1868                        "ELEMENTAL procedure unless there is a non-optional "
1869                        "argument with the same rank (12.4.1.5)",
1870                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1871           return FAILURE;
1872         }
1873     }
1874
1875   for (arg = arg0; arg; arg = arg->next)
1876     {
1877       if (arg->expr == NULL || arg->expr->rank == 0)
1878         continue;
1879
1880       /* Being elemental, the last upper bound of an assumed size array
1881          argument must be present.  */
1882       if (resolve_assumed_size_actual (arg->expr))
1883         return FAILURE;
1884
1885       /* Elemental procedure's array actual arguments must conform.  */
1886       if (e != NULL)
1887         {
1888           if (gfc_check_conformance (arg->expr, e,
1889                                      "elemental procedure") == FAILURE)
1890             return FAILURE;
1891         }
1892       else
1893         e = arg->expr;
1894     }
1895
1896   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1897      is an array, the intent inout/out variable needs to be also an array.  */
1898   if (rank > 0 && esym && expr == NULL)
1899     for (eformal = esym->formal, arg = arg0; arg && eformal;
1900          arg = arg->next, eformal = eformal->next)
1901       if ((eformal->sym->attr.intent == INTENT_OUT
1902            || eformal->sym->attr.intent == INTENT_INOUT)
1903           && arg->expr && arg->expr->rank == 0)
1904         {
1905           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1906                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1907                      "actual argument is an array", &arg->expr->where,
1908                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1909                      : "INOUT", eformal->sym->name, esym->name);
1910           return FAILURE;
1911         }
1912   return SUCCESS;
1913 }
1914
1915
1916 /* Go through each actual argument in ACTUAL and see if it can be
1917    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1918    function being called, or NULL if not known.  */
1919
1920 static void
1921 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1922 {
1923   gfc_actual_arglist *ap;
1924   gfc_expr *expr;
1925
1926   for (ap = actual; ap; ap = ap->next)
1927     if (ap->expr
1928         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1929         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1930                                          NOT_ELEMENTAL))
1931       ap->expr->inline_noncopying_intrinsic = 1;
1932 }
1933
1934
1935 /* This function does the checking of references to global procedures
1936    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1937    77 and 95 standards.  It checks for a gsymbol for the name, making
1938    one if it does not already exist.  If it already exists, then the
1939    reference being resolved must correspond to the type of gsymbol.
1940    Otherwise, the new symbol is equipped with the attributes of the
1941    reference.  The corresponding code that is called in creating
1942    global entities is parse.c.
1943
1944    In addition, for all but -std=legacy, the gsymbols are used to
1945    check the interfaces of external procedures from the same file.
1946    The namespace of the gsymbol is resolved and then, once this is
1947    done the interface is checked.  */
1948
1949
1950 static bool
1951 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1952 {
1953   if (!gsym_ns->proc_name->attr.recursive)
1954     return true;
1955
1956   if (sym->ns == gsym_ns)
1957     return false;
1958
1959   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1960     return false;
1961
1962   return true;
1963 }
1964
1965 static bool
1966 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1967 {
1968   if (gsym_ns->entries)
1969     {
1970       gfc_entry_list *entry = gsym_ns->entries;
1971
1972       for (; entry; entry = entry->next)
1973         {
1974           if (strcmp (sym->name, entry->sym->name) == 0)
1975             {
1976               if (strcmp (gsym_ns->proc_name->name,
1977                           sym->ns->proc_name->name) == 0)
1978                 return false;
1979
1980               if (sym->ns->parent
1981                   && strcmp (gsym_ns->proc_name->name,
1982                              sym->ns->parent->proc_name->name) == 0)
1983                 return false;
1984             }
1985         }
1986     }
1987   return true;
1988 }
1989
1990 static void
1991 resolve_global_procedure (gfc_symbol *sym, locus *where,
1992                           gfc_actual_arglist **actual, int sub)
1993 {
1994   gfc_gsymbol * gsym;
1995   gfc_namespace *ns;
1996   enum gfc_symbol_type type;
1997
1998   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1999
2000   gsym = gfc_get_gsymbol (sym->name);
2001
2002   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2003     gfc_global_used (gsym, where);
2004
2005   if (gfc_option.flag_whole_file
2006         && (sym->attr.if_source == IFSRC_UNKNOWN
2007             || sym->attr.if_source == IFSRC_IFBODY)
2008         && gsym->type != GSYM_UNKNOWN
2009         && gsym->ns
2010         && gsym->ns->resolved != -1
2011         && gsym->ns->proc_name
2012         && not_in_recursive (sym, gsym->ns)
2013         && not_entry_self_reference (sym, gsym->ns))
2014     {
2015       gfc_symbol *def_sym;
2016
2017       /* Resolve the gsymbol namespace if needed.  */
2018       if (!gsym->ns->resolved)
2019         {
2020           gfc_dt_list *old_dt_list;
2021
2022           /* Stash away derived types so that the backend_decls do not
2023              get mixed up.  */
2024           old_dt_list = gfc_derived_types;
2025           gfc_derived_types = NULL;
2026
2027           gfc_resolve (gsym->ns);
2028
2029           /* Store the new derived types with the global namespace.  */
2030           if (gfc_derived_types)
2031             gsym->ns->derived_types = gfc_derived_types;
2032
2033           /* Restore the derived types of this namespace.  */
2034           gfc_derived_types = old_dt_list;
2035         }
2036
2037       /* Make sure that translation for the gsymbol occurs before
2038          the procedure currently being resolved.  */
2039       ns = gfc_global_ns_list;
2040       for (; ns && ns != gsym->ns; ns = ns->sibling)
2041         {
2042           if (ns->sibling == gsym->ns)
2043             {
2044               ns->sibling = gsym->ns->sibling;
2045               gsym->ns->sibling = gfc_global_ns_list;
2046               gfc_global_ns_list = gsym->ns;
2047               break;
2048             }
2049         }
2050
2051       def_sym = gsym->ns->proc_name;
2052       if (def_sym->attr.entry_master)
2053         {
2054           gfc_entry_list *entry;
2055           for (entry = gsym->ns->entries; entry; entry = entry->next)
2056             if (strcmp (entry->sym->name, sym->name) == 0)
2057               {
2058                 def_sym = entry->sym;
2059                 break;
2060               }
2061         }
2062
2063       /* Differences in constant character lengths.  */
2064       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2065         {
2066           long int l1 = 0, l2 = 0;
2067           gfc_charlen *cl1 = sym->ts.u.cl;
2068           gfc_charlen *cl2 = def_sym->ts.u.cl;
2069
2070           if (cl1 != NULL
2071               && cl1->length != NULL
2072               && cl1->length->expr_type == EXPR_CONSTANT)
2073             l1 = mpz_get_si (cl1->length->value.integer);
2074
2075           if (cl2 != NULL
2076               && cl2->length != NULL
2077               && cl2->length->expr_type == EXPR_CONSTANT)
2078             l2 = mpz_get_si (cl2->length->value.integer);
2079
2080           if (l1 && l2 && l1 != l2)
2081             gfc_error ("Character length mismatch in return type of "
2082                        "function '%s' at %L (%ld/%ld)", sym->name,
2083                        &sym->declared_at, l1, l2);
2084         }
2085
2086      /* Type mismatch of function return type and expected type.  */
2087      if (sym->attr.function
2088          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2089         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2090                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2091                    gfc_typename (&def_sym->ts));
2092
2093       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2094         {
2095           gfc_formal_arglist *arg = def_sym->formal;
2096           for ( ; arg; arg = arg->next)
2097             if (!arg->sym)
2098               continue;
2099             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2100             else if (arg->sym->attr.allocatable
2101                      || arg->sym->attr.asynchronous
2102                      || arg->sym->attr.optional
2103                      || arg->sym->attr.pointer
2104                      || arg->sym->attr.target
2105                      || arg->sym->attr.value
2106                      || arg->sym->attr.volatile_)
2107               {
2108                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2109                            "has an attribute that requires an explicit "
2110                            "interface for this procedure", arg->sym->name,
2111                            sym->name, &sym->declared_at);
2112                 break;
2113               }
2114             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2115             else if (arg->sym && arg->sym->as
2116                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2117               {
2118                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2119                            "argument '%s' must have an explicit interface",
2120                            sym->name, &sym->declared_at, arg->sym->name);
2121                 break;
2122               }
2123             /* F2008, 12.4.2.2 (2c)  */
2124             else if (arg->sym->attr.codimension)
2125               {
2126                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2127                            "'%s' must have an explicit interface",
2128                            sym->name, &sym->declared_at, arg->sym->name);
2129                 break;
2130               }
2131             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2132             else if (false) /* TODO: is a parametrized derived type  */
2133               {
2134                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2135                            "type argument '%s' must have an explicit "
2136                            "interface", sym->name, &sym->declared_at,
2137                            arg->sym->name);
2138                 break;
2139               }
2140             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2141             else if (arg->sym->ts.type == BT_CLASS)
2142               {
2143                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2144                            "argument '%s' must have an explicit interface",
2145                            sym->name, &sym->declared_at, arg->sym->name);
2146                 break;
2147               }
2148         }
2149
2150       if (def_sym->attr.function)
2151         {
2152           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2153           if (def_sym->as && def_sym->as->rank
2154               && (!sym->as || sym->as->rank != def_sym->as->rank))
2155             gfc_error ("The reference to function '%s' at %L either needs an "
2156                        "explicit INTERFACE or the rank is incorrect", sym->name,
2157                        where);
2158
2159           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2160           if ((def_sym->result->attr.pointer
2161                || def_sym->result->attr.allocatable)
2162                && (sym->attr.if_source != IFSRC_IFBODY
2163                    || def_sym->result->attr.pointer
2164                         != sym->result->attr.pointer
2165                    || def_sym->result->attr.allocatable
2166                         != sym->result->attr.allocatable))
2167             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2168                        "result must have an explicit interface", sym->name,
2169                        where);
2170
2171           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2172           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2173               && def_sym->ts.u.cl->length != NULL)
2174             {
2175               gfc_charlen *cl = sym->ts.u.cl;
2176
2177               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2178                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2179                 {
2180                   gfc_error ("Nonconstant character-length function '%s' at %L "
2181                              "must have an explicit interface", sym->name,
2182                              &sym->declared_at);
2183                 }
2184             }
2185         }
2186
2187       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2188       if (def_sym->attr.elemental && !sym->attr.elemental)
2189         {
2190           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2191                      "interface", sym->name, &sym->declared_at);
2192         }
2193
2194       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2195       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2196         {
2197           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2198                      "an explicit interface", sym->name, &sym->declared_at);
2199         }
2200
2201       if (gfc_option.flag_whole_file == 1
2202           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2203               && !(gfc_option.warn_std & GFC_STD_GNU)))
2204         gfc_errors_to_warnings (1);
2205
2206       if (sym->attr.if_source != IFSRC_IFBODY)  
2207         gfc_procedure_use (def_sym, actual, where);
2208
2209       gfc_errors_to_warnings (0);
2210     }
2211
2212   if (gsym->type == GSYM_UNKNOWN)
2213     {
2214       gsym->type = type;
2215       gsym->where = *where;
2216     }
2217
2218   gsym->used = 1;
2219 }
2220
2221
2222 /************* Function resolution *************/
2223
2224 /* Resolve a function call known to be generic.
2225    Section 14.1.2.4.1.  */
2226
2227 static match
2228 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2229 {
2230   gfc_symbol *s;
2231
2232   if (sym->attr.generic)
2233     {
2234       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2235       if (s != NULL)
2236         {
2237           expr->value.function.name = s->name;
2238           expr->value.function.esym = s;
2239
2240           if (s->ts.type != BT_UNKNOWN)
2241             expr->ts = s->ts;
2242           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2243             expr->ts = s->result->ts;
2244
2245           if (s->as != NULL)
2246             expr->rank = s->as->rank;
2247           else if (s->result != NULL && s->result->as != NULL)
2248             expr->rank = s->result->as->rank;
2249
2250           gfc_set_sym_referenced (expr->value.function.esym);
2251
2252           return MATCH_YES;
2253         }
2254
2255       /* TODO: Need to search for elemental references in generic
2256          interface.  */
2257     }
2258
2259   if (sym->attr.intrinsic)
2260     return gfc_intrinsic_func_interface (expr, 0);
2261
2262   return MATCH_NO;
2263 }
2264
2265
2266 static gfc_try
2267 resolve_generic_f (gfc_expr *expr)
2268 {
2269   gfc_symbol *sym;
2270   match m;
2271
2272   sym = expr->symtree->n.sym;
2273
2274   for (;;)
2275     {
2276       m = resolve_generic_f0 (expr, sym);
2277       if (m == MATCH_YES)
2278         return SUCCESS;
2279       else if (m == MATCH_ERROR)
2280         return FAILURE;
2281
2282 generic:
2283       if (sym->ns->parent == NULL)
2284         break;
2285       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2286
2287       if (sym == NULL)
2288         break;
2289       if (!generic_sym (sym))
2290         goto generic;
2291     }
2292
2293   /* Last ditch attempt.  See if the reference is to an intrinsic
2294      that possesses a matching interface.  14.1.2.4  */
2295   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
2296     {
2297       gfc_error ("There is no specific function for the generic '%s' at %L",
2298                  expr->symtree->n.sym->name, &expr->where);
2299       return FAILURE;
2300     }
2301
2302   m = gfc_intrinsic_func_interface (expr, 0);
2303   if (m == MATCH_YES)
2304     return SUCCESS;
2305   if (m == MATCH_NO)
2306     gfc_error ("Generic function '%s' at %L is not consistent with a "
2307                "specific intrinsic interface", expr->symtree->n.sym->name,
2308                &expr->where);
2309
2310   return FAILURE;
2311 }
2312
2313
2314 /* Resolve a function call known to be specific.  */
2315
2316 static match
2317 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2318 {
2319   match m;
2320
2321   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2322     {
2323       if (sym->attr.dummy)
2324         {
2325           sym->attr.proc = PROC_DUMMY;
2326           goto found;
2327         }
2328
2329       sym->attr.proc = PROC_EXTERNAL;
2330       goto found;
2331     }
2332
2333   if (sym->attr.proc == PROC_MODULE
2334       || sym->attr.proc == PROC_ST_FUNCTION
2335       || sym->attr.proc == PROC_INTERNAL)
2336     goto found;
2337
2338   if (sym->attr.intrinsic)
2339     {
2340       m = gfc_intrinsic_func_interface (expr, 1);
2341       if (m == MATCH_YES)
2342         return MATCH_YES;
2343       if (m == MATCH_NO)
2344         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2345                    "with an intrinsic", sym->name, &expr->where);
2346
2347       return MATCH_ERROR;
2348     }
2349
2350   return MATCH_NO;
2351
2352 found:
2353   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2354
2355   if (sym->result)
2356     expr->ts = sym->result->ts;
2357   else
2358     expr->ts = sym->ts;
2359   expr->value.function.name = sym->name;
2360   expr->value.function.esym = sym;
2361   if (sym->as != NULL)
2362     expr->rank = sym->as->rank;
2363
2364   return MATCH_YES;
2365 }
2366
2367
2368 static gfc_try
2369 resolve_specific_f (gfc_expr *expr)
2370 {
2371   gfc_symbol *sym;
2372   match m;
2373
2374   sym = expr->symtree->n.sym;
2375
2376   for (;;)
2377     {
2378       m = resolve_specific_f0 (sym, expr);
2379       if (m == MATCH_YES)
2380         return SUCCESS;
2381       if (m == MATCH_ERROR)
2382         return FAILURE;
2383
2384       if (sym->ns->parent == NULL)
2385         break;
2386
2387       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2388
2389       if (sym == NULL)
2390         break;
2391     }
2392
2393   gfc_error ("Unable to resolve the specific function '%s' at %L",
2394              expr->symtree->n.sym->name, &expr->where);
2395
2396   return SUCCESS;
2397 }
2398
2399
2400 /* Resolve a procedure call not known to be generic nor specific.  */
2401
2402 static gfc_try
2403 resolve_unknown_f (gfc_expr *expr)
2404 {
2405   gfc_symbol *sym;
2406   gfc_typespec *ts;
2407
2408   sym = expr->symtree->n.sym;
2409
2410   if (sym->attr.dummy)
2411     {
2412       sym->attr.proc = PROC_DUMMY;
2413       expr->value.function.name = sym->name;
2414       goto set_type;
2415     }
2416
2417   /* See if we have an intrinsic function reference.  */
2418
2419   if (gfc_is_intrinsic (sym, 0, expr->where))
2420     {
2421       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2422         return SUCCESS;
2423       return FAILURE;
2424     }
2425
2426   /* The reference is to an external name.  */
2427
2428   sym->attr.proc = PROC_EXTERNAL;
2429   expr->value.function.name = sym->name;
2430   expr->value.function.esym = expr->symtree->n.sym;
2431
2432   if (sym->as != NULL)
2433     expr->rank = sym->as->rank;
2434
2435   /* Type of the expression is either the type of the symbol or the
2436      default type of the symbol.  */
2437
2438 set_type:
2439   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2440
2441   if (sym->ts.type != BT_UNKNOWN)
2442     expr->ts = sym->ts;
2443   else
2444     {
2445       ts = gfc_get_default_type (sym->name, sym->ns);
2446
2447       if (ts->type == BT_UNKNOWN)
2448         {
2449           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2450                      sym->name, &expr->where);
2451           return FAILURE;
2452         }
2453       else
2454         expr->ts = *ts;
2455     }
2456
2457   return SUCCESS;
2458 }
2459
2460
2461 /* Return true, if the symbol is an external procedure.  */
2462 static bool
2463 is_external_proc (gfc_symbol *sym)
2464 {
2465   if (!sym->attr.dummy && !sym->attr.contained
2466         && !(sym->attr.intrinsic
2467               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2468         && sym->attr.proc != PROC_ST_FUNCTION
2469         && !sym->attr.proc_pointer
2470         && !sym->attr.use_assoc
2471         && sym->name)
2472     return true;
2473
2474   return false;
2475 }
2476
2477
2478 /* Figure out if a function reference is pure or not.  Also set the name
2479    of the function for a potential error message.  Return nonzero if the
2480    function is PURE, zero if not.  */
2481 static int
2482 pure_stmt_function (gfc_expr *, gfc_symbol *);
2483
2484 static int
2485 pure_function (gfc_expr *e, const char **name)
2486 {
2487   int pure;
2488
2489   *name = NULL;
2490
2491   if (e->symtree != NULL
2492         && e->symtree->n.sym != NULL
2493         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2494     return pure_stmt_function (e, e->symtree->n.sym);
2495
2496   if (e->value.function.esym)
2497     {
2498       pure = gfc_pure (e->value.function.esym);
2499       *name = e->value.function.esym->name;
2500     }
2501   else if (e->value.function.isym)
2502     {
2503       pure = e->value.function.isym->pure
2504              || e->value.function.isym->elemental;
2505       *name = e->value.function.isym->name;
2506     }
2507   else
2508     {
2509       /* Implicit functions are not pure.  */
2510       pure = 0;
2511       *name = e->value.function.name;
2512     }
2513
2514   return pure;
2515 }
2516
2517
2518 static bool
2519 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2520                  int *f ATTRIBUTE_UNUSED)
2521 {
2522   const char *name;
2523
2524   /* Don't bother recursing into other statement functions
2525      since they will be checked individually for purity.  */
2526   if (e->expr_type != EXPR_FUNCTION
2527         || !e->symtree
2528         || e->symtree->n.sym == sym
2529         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2530     return false;
2531
2532   return pure_function (e, &name) ? false : true;
2533 }
2534
2535
2536 static int
2537 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2538 {
2539   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2540 }
2541
2542
2543 static gfc_try
2544 is_scalar_expr_ptr (gfc_expr *expr)
2545 {
2546   gfc_try retval = SUCCESS;
2547   gfc_ref *ref;
2548   int start;
2549   int end;
2550
2551   /* See if we have a gfc_ref, which means we have a substring, array
2552      reference, or a component.  */
2553   if (expr->ref != NULL)
2554     {
2555       ref = expr->ref;
2556       while (ref->next != NULL)
2557         ref = ref->next;
2558
2559       switch (ref->type)
2560         {
2561         case REF_SUBSTRING:
2562           if (ref->u.ss.length != NULL 
2563               && ref->u.ss.length->length != NULL
2564               && ref->u.ss.start
2565               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2566               && ref->u.ss.end
2567               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2568             {
2569               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2570               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2571               if (end - start + 1 != 1)
2572                 retval = FAILURE;
2573             }
2574           else
2575             retval = FAILURE;
2576           break;
2577         case REF_ARRAY:
2578           if (ref->u.ar.type == AR_ELEMENT)
2579             retval = SUCCESS;
2580           else if (ref->u.ar.type == AR_FULL)
2581             {
2582               /* The user can give a full array if the array is of size 1.  */
2583               if (ref->u.ar.as != NULL
2584                   && ref->u.ar.as->rank == 1
2585                   && ref->u.ar.as->type == AS_EXPLICIT
2586                   && ref->u.ar.as->lower[0] != NULL
2587                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2588                   && ref->u.ar.as->upper[0] != NULL
2589                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2590                 {
2591                   /* If we have a character string, we need to check if
2592                      its length is one.  */
2593                   if (expr->ts.type == BT_CHARACTER)
2594                     {
2595                       if (expr->ts.u.cl == NULL
2596                           || expr->ts.u.cl->length == NULL
2597                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2598                           != 0)
2599                         retval = FAILURE;
2600                     }
2601                   else
2602                     {
2603                       /* We have constant lower and upper bounds.  If the
2604                          difference between is 1, it can be considered a
2605                          scalar.  */
2606                       start = (int) mpz_get_si
2607                                 (ref->u.ar.as->lower[0]->value.integer);
2608                       end = (int) mpz_get_si
2609                                 (ref->u.ar.as->upper[0]->value.integer);
2610                       if (end - start + 1 != 1)
2611                         retval = FAILURE;
2612                    }
2613                 }
2614               else
2615                 retval = FAILURE;
2616             }
2617           else
2618             retval = FAILURE;
2619           break;
2620         default:
2621           retval = SUCCESS;
2622           break;
2623         }
2624     }
2625   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2626     {
2627       /* Character string.  Make sure it's of length 1.  */
2628       if (expr->ts.u.cl == NULL
2629           || expr->ts.u.cl->length == NULL
2630           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2631         retval = FAILURE;
2632     }
2633   else if (expr->rank != 0)
2634     retval = FAILURE;
2635
2636   return retval;
2637 }
2638
2639
2640 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2641    and, in the case of c_associated, set the binding label based on
2642    the arguments.  */
2643
2644 static gfc_try
2645 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2646                           gfc_symbol **new_sym)
2647 {
2648   char name[GFC_MAX_SYMBOL_LEN + 1];
2649   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2650   int optional_arg = 0;
2651   gfc_try retval = SUCCESS;
2652   gfc_symbol *args_sym;
2653   gfc_typespec *arg_ts;
2654   symbol_attribute arg_attr;
2655
2656   if (args->expr->expr_type == EXPR_CONSTANT
2657       || args->expr->expr_type == EXPR_OP
2658       || args->expr->expr_type == EXPR_NULL)
2659     {
2660       gfc_error ("Argument to '%s' at %L is not a variable",
2661                  sym->name, &(args->expr->where));
2662       return FAILURE;
2663     }
2664
2665   args_sym = args->expr->symtree->n.sym;
2666
2667   /* The typespec for the actual arg should be that stored in the expr
2668      and not necessarily that of the expr symbol (args_sym), because
2669      the actual expression could be a part-ref of the expr symbol.  */
2670   arg_ts = &(args->expr->ts);
2671   arg_attr = gfc_expr_attr (args->expr);
2672     
2673   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2674     {
2675       /* If the user gave two args then they are providing something for
2676          the optional arg (the second cptr).  Therefore, set the name and
2677          binding label to the c_associated for two cptrs.  Otherwise,
2678          set c_associated to expect one cptr.  */
2679       if (args->next)
2680         {
2681           /* two args.  */
2682           sprintf (name, "%s_2", sym->name);
2683           sprintf (binding_label, "%s_2", sym->binding_label);
2684           optional_arg = 1;
2685         }
2686       else
2687         {
2688           /* one arg.  */
2689           sprintf (name, "%s_1", sym->name);
2690           sprintf (binding_label, "%s_1", sym->binding_label);
2691           optional_arg = 0;
2692         }
2693
2694       /* Get a new symbol for the version of c_associated that
2695          will get called.  */
2696       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2697     }
2698   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2699            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2700     {
2701       sprintf (name, "%s", sym->name);
2702       sprintf (binding_label, "%s", sym->binding_label);
2703
2704       /* Error check the call.  */
2705       if (args->next != NULL)
2706         {
2707           gfc_error_now ("More actual than formal arguments in '%s' "
2708                          "call at %L", name, &(args->expr->where));
2709           retval = FAILURE;
2710         }
2711       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2712         {
2713           /* Make sure we have either the target or pointer attribute.  */
2714           if (!arg_attr.target && !arg_attr.pointer)
2715             {
2716               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2717                              "a TARGET or an associated pointer",
2718                              args_sym->name,
2719                              sym->name, &(args->expr->where));
2720               retval = FAILURE;
2721             }
2722
2723           /* See if we have interoperable type and type param.  */
2724           if (verify_c_interop (arg_ts) == SUCCESS
2725               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2726             {
2727               if (args_sym->attr.target == 1)
2728                 {
2729                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2730                      has the target attribute and is interoperable.  */
2731                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2732                      allocatable variable that has the TARGET attribute and
2733                      is not an array of zero size.  */
2734                   if (args_sym->attr.allocatable == 1)
2735                     {
2736                       if (args_sym->attr.dimension != 0 
2737                           && (args_sym->as && args_sym->as->rank == 0))
2738                         {
2739                           gfc_error_now ("Allocatable variable '%s' used as a "
2740                                          "parameter to '%s' at %L must not be "
2741                                          "an array of zero size",
2742                                          args_sym->name, sym->name,
2743                                          &(args->expr->where));
2744                           retval = FAILURE;
2745                         }
2746                     }
2747                   else
2748                     {
2749                       /* A non-allocatable target variable with C
2750                          interoperable type and type parameters must be
2751                          interoperable.  */
2752                       if (args_sym && args_sym->attr.dimension)
2753                         {
2754                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2755                             {
2756                               gfc_error ("Assumed-shape array '%s' at %L "
2757                                          "cannot be an argument to the "
2758                                          "procedure '%s' because "
2759                                          "it is not C interoperable",
2760                                          args_sym->name,
2761                                          &(args->expr->where), sym->name);
2762                               retval = FAILURE;
2763                             }
2764                           else if (args_sym->as->type == AS_DEFERRED)
2765                             {
2766                               gfc_error ("Deferred-shape array '%s' at %L "
2767                                          "cannot be an argument to the "
2768                                          "procedure '%s' because "
2769                                          "it is not C interoperable",
2770                                          args_sym->name,
2771                                          &(args->expr->where), sym->name);
2772                               retval = FAILURE;
2773                             }
2774                         }
2775                               
2776                       /* Make sure it's not a character string.  Arrays of
2777                          any type should be ok if the variable is of a C
2778                          interoperable type.  */
2779                       if (arg_ts->type == BT_CHARACTER)
2780                         if (arg_ts->u.cl != NULL
2781                             && (arg_ts->u.cl->length == NULL
2782                                 || arg_ts->u.cl->length->expr_type
2783                                    != EXPR_CONSTANT
2784                                 || mpz_cmp_si
2785                                     (arg_ts->u.cl->length->value.integer, 1)
2786                                    != 0)
2787                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2788                           {
2789                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2790                                            "at %L must have a length of 1",
2791                                            args_sym->name, sym->name,
2792                                            &(args->expr->where));
2793                             retval = FAILURE;
2794                           }
2795                     }
2796                 }
2797               else if (arg_attr.pointer
2798                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2799                 {
2800                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2801                      scalar pointer.  */
2802                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2803                                  "associated scalar POINTER", args_sym->name,
2804                                  sym->name, &(args->expr->where));
2805                   retval = FAILURE;
2806                 }
2807             }
2808           else
2809             {
2810               /* The parameter is not required to be C interoperable.  If it
2811                  is not C interoperable, it must be a nonpolymorphic scalar
2812                  with no length type parameters.  It still must have either
2813                  the pointer or target attribute, and it can be
2814                  allocatable (but must be allocated when c_loc is called).  */
2815               if (args->expr->rank != 0 
2816                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2817                 {
2818                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2819                                  "scalar", args_sym->name, sym->name,
2820                                  &(args->expr->where));
2821                   retval = FAILURE;
2822                 }
2823               else if (arg_ts->type == BT_CHARACTER 
2824                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2825                 {
2826                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2827                                  "%L must have a length of 1",
2828                                  args_sym->name, sym->name,
2829                                  &(args->expr->where));
2830                   retval = FAILURE;
2831                 }
2832               else if (arg_ts->type == BT_CLASS)
2833                 {
2834                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2835                                  "polymorphic", args_sym->name, sym->name,
2836                                  &(args->expr->where));
2837                   retval = FAILURE;
2838                 }
2839             }
2840         }
2841       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2842         {
2843           if (args_sym->attr.flavor != FL_PROCEDURE)
2844             {
2845               /* TODO: Update this error message to allow for procedure
2846                  pointers once they are implemented.  */
2847               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2848                              "procedure",
2849                              args_sym->name, sym->name,
2850                              &(args->expr->where));
2851               retval = FAILURE;
2852             }
2853           else if (args_sym->attr.is_bind_c != 1)
2854             {
2855               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2856                              "BIND(C)",
2857                              args_sym->name, sym->name,
2858                              &(args->expr->where));
2859               retval = FAILURE;
2860             }
2861         }
2862       
2863       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2864       *new_sym = sym;
2865     }
2866   else
2867     {
2868       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2869                           "iso_c_binding function: '%s'!\n", sym->name);
2870     }
2871
2872   return retval;
2873 }
2874
2875
2876 /* Resolve a function call, which means resolving the arguments, then figuring
2877    out which entity the name refers to.  */
2878 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2879    to INTENT(OUT) or INTENT(INOUT).  */
2880
2881 static gfc_try
2882 resolve_function (gfc_expr *expr)
2883 {
2884   gfc_actual_arglist *arg;
2885   gfc_symbol *sym;
2886   const char *name;
2887   gfc_try t;
2888   int temp;
2889   procedure_type p = PROC_INTRINSIC;
2890   bool no_formal_args;
2891
2892   sym = NULL;
2893   if (expr->symtree)
2894     sym = expr->symtree->n.sym;
2895
2896   /* If this is a procedure pointer component, it has already been resolved.  */
2897   if (gfc_is_proc_ptr_comp (expr, NULL))
2898     return SUCCESS;
2899   
2900   if (sym && sym->attr.intrinsic
2901       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2902     return FAILURE;
2903
2904   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2905     {
2906       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2907       return FAILURE;
2908     }
2909
2910   /* If this ia a deferred TBP with an abstract interface (which may
2911      of course be referenced), expr->value.function.esym will be set.  */
2912   if (sym && sym->attr.abstract && !expr->value.function.esym)
2913     {
2914       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2915                  sym->name, &expr->where);
2916       return FAILURE;
2917     }
2918
2919   /* Switch off assumed size checking and do this again for certain kinds
2920      of procedure, once the procedure itself is resolved.  */
2921   need_full_assumed_size++;
2922
2923   if (expr->symtree && expr->symtree->n.sym)
2924     p = expr->symtree->n.sym->attr.proc;
2925
2926   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2927     inquiry_argument = true;
2928   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2929
2930   if (resolve_actual_arglist (expr->value.function.actual,
2931                               p, no_formal_args) == FAILURE)
2932     {
2933       inquiry_argument = false;
2934       return FAILURE;
2935     }
2936
2937   inquiry_argument = false;
2938  
2939   /* Need to setup the call to the correct c_associated, depending on
2940      the number of cptrs to user gives to compare.  */
2941   if (sym && sym->attr.is_iso_c == 1)
2942     {
2943       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2944           == FAILURE)
2945         return FAILURE;
2946       
2947       /* Get the symtree for the new symbol (resolved func).
2948          the old one will be freed later, when it's no longer used.  */
2949       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2950     }
2951   
2952   /* Resume assumed_size checking.  */
2953   need_full_assumed_size--;
2954
2955   /* If the procedure is external, check for usage.  */
2956   if (sym && is_external_proc (sym))
2957     resolve_global_procedure (sym, &expr->where,
2958                               &expr->value.function.actual, 0);
2959
2960   if (sym && sym->ts.type == BT_CHARACTER
2961       && sym->ts.u.cl
2962       && sym->ts.u.cl->length == NULL
2963       && !sym->attr.dummy
2964       && expr->value.function.esym == NULL
2965       && !sym->attr.contained)
2966     {
2967       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2968       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2969                  "be used at %L since it is not a dummy argument",
2970                  sym->name, &expr->where);
2971       return FAILURE;
2972     }
2973
2974   /* See if function is already resolved.  */
2975
2976   if (expr->value.function.name != NULL)
2977     {
2978       if (expr->ts.type == BT_UNKNOWN)
2979         expr->ts = sym->ts;
2980       t = SUCCESS;
2981     }
2982   else
2983     {
2984       /* Apply the rules of section 14.1.2.  */
2985
2986       switch (procedure_kind (sym))
2987         {
2988         case PTYPE_GENERIC:
2989           t = resolve_generic_f (expr);
2990           break;
2991
2992         case PTYPE_SPECIFIC:
2993           t = resolve_specific_f (expr);
2994           break;
2995
2996         case PTYPE_UNKNOWN:
2997           t = resolve_unknown_f (expr);
2998           break;
2999
3000         default:
3001           gfc_internal_error ("resolve_function(): bad function type");
3002         }
3003     }
3004
3005   /* If the expression is still a function (it might have simplified),
3006      then we check to see if we are calling an elemental function.  */
3007
3008   if (expr->expr_type != EXPR_FUNCTION)
3009     return t;
3010
3011   temp = need_full_assumed_size;
3012   need_full_assumed_size = 0;
3013
3014   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3015     return FAILURE;
3016
3017   if (omp_workshare_flag
3018       && expr->value.function.esym
3019       && ! gfc_elemental (expr->value.function.esym))
3020     {
3021       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3022                  "in WORKSHARE construct", expr->value.function.esym->name,
3023                  &expr->where);
3024       t = FAILURE;
3025     }
3026
3027 #define GENERIC_ID expr->value.function.isym->id
3028   else if (expr->value.function.actual != NULL
3029            && expr->value.function.isym != NULL
3030            && GENERIC_ID != GFC_ISYM_LBOUND
3031            && GENERIC_ID != GFC_ISYM_LEN
3032            && GENERIC_ID != GFC_ISYM_LOC
3033            && GENERIC_ID != GFC_ISYM_PRESENT)
3034     {
3035       /* Array intrinsics must also have the last upper bound of an
3036          assumed size array argument.  UBOUND and SIZE have to be
3037          excluded from the check if the second argument is anything
3038          than a constant.  */
3039
3040       for (arg = expr->value.function.actual; arg; arg = arg->next)
3041         {
3042           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3043               && arg->next != NULL && arg->next->expr)
3044             {
3045               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3046                 break;
3047
3048               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3049                 break;
3050
3051               if ((int)mpz_get_si (arg->next->expr->value.integer)
3052                         < arg->expr->rank)
3053                 break;
3054             }
3055
3056           if (arg->expr != NULL
3057               && arg->expr->rank > 0
3058               && resolve_assumed_size_actual (arg->expr))
3059             return FAILURE;
3060         }
3061     }
3062 #undef GENERIC_ID
3063
3064   need_full_assumed_size = temp;
3065   name = NULL;
3066
3067   if (!pure_function (expr, &name) && name)
3068     {
3069       if (forall_flag)
3070         {
3071           gfc_error ("reference to non-PURE function '%s' at %L inside a "
3072                      "FORALL %s", name, &expr->where,
3073                      forall_flag == 2 ? "mask" : "block");
3074           t = FAILURE;
3075         }
3076       else if (gfc_pure (NULL))
3077         {
3078           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3079                      "procedure within a PURE procedure", name, &expr->where);
3080           t = FAILURE;
3081         }
3082     }
3083
3084   /* Functions without the RECURSIVE attribution are not allowed to
3085    * call themselves.  */
3086   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3087     {
3088       gfc_symbol *esym;
3089       esym = expr->value.function.esym;
3090
3091       if (is_illegal_recursion (esym, gfc_current_ns))
3092       {
3093         if (esym->attr.entry && esym->ns->entries)
3094           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3095                      " function '%s' is not RECURSIVE",
3096                      esym->name, &expr->where, esym->ns->entries->sym->name);
3097         else
3098           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3099                      " is not RECURSIVE", esym->name, &expr->where);
3100
3101         t = FAILURE;
3102       }
3103     }
3104
3105   /* Character lengths of use associated functions may contains references to
3106      symbols not referenced from the current program unit otherwise.  Make sure
3107      those symbols are marked as referenced.  */
3108
3109   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3110       && expr->value.function.esym->attr.use_assoc)
3111     {
3112       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3113     }
3114
3115   if (t == SUCCESS
3116         && !((expr->value.function.esym
3117                 && expr->value.function.esym->attr.elemental)
3118                         ||
3119              (expr->value.function.isym
3120                 && expr->value.function.isym->elemental)))
3121     find_noncopying_intrinsics (expr->value.function.esym,
3122                                 expr->value.function.actual);
3123
3124   /* Make sure that the expression has a typespec that works.  */
3125   if (expr->ts.type == BT_UNKNOWN)
3126     {
3127       if (expr->symtree->n.sym->result
3128             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3129             && !expr->symtree->n.sym->result->attr.proc_pointer)
3130         expr->ts = expr->symtree->n.sym->result->ts;
3131     }
3132
3133   return t;
3134 }
3135
3136
3137 /************* Subroutine resolution *************/
3138
3139 static void
3140 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3141 {
3142   if (gfc_pure (sym))
3143     return;
3144
3145   if (forall_flag)
3146     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3147                sym->name, &c->loc);
3148   else if (gfc_pure (NULL))
3149     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3150                &c->loc);
3151 }
3152
3153
3154 static match
3155 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3156 {
3157   gfc_symbol *s;
3158
3159   if (sym->attr.generic)
3160     {
3161       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3162       if (s != NULL)
3163         {
3164           c->resolved_sym = s;
3165           pure_subroutine (c, s);
3166           return MATCH_YES;
3167         }
3168
3169       /* TODO: Need to search for elemental references in generic interface.  */
3170     }
3171
3172   if (sym->attr.intrinsic)
3173     return gfc_intrinsic_sub_interface (c, 0);
3174
3175   return MATCH_NO;
3176 }
3177
3178
3179 static gfc_try
3180 resolve_generic_s (gfc_code *c)
3181 {
3182   gfc_symbol *sym;
3183   match m;
3184
3185   sym = c->symtree->n.sym;
3186
3187   for (;;)
3188     {
3189       m = resolve_generic_s0 (c, sym);
3190       if (m == MATCH_YES)
3191         return SUCCESS;
3192       else if (m == MATCH_ERROR)
3193         return FAILURE;
3194
3195 generic:
3196       if (sym->ns->parent == NULL)
3197         break;
3198       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3199
3200       if (sym == NULL)
3201         break;
3202       if (!generic_sym (sym))
3203         goto generic;
3204     }
3205
3206   /* Last ditch attempt.  See if the reference is to an intrinsic
3207      that possesses a matching interface.  14.1.2.4  */
3208   sym = c->symtree->n.sym;
3209
3210   if (!gfc_is_intrinsic (sym, 1, c->loc))
3211     {
3212       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3213                  sym->name, &c->loc);
3214       return FAILURE;
3215     }
3216
3217   m = gfc_intrinsic_sub_interface (c, 0);
3218   if (m == MATCH_YES)
3219     return SUCCESS;
3220   if (m == MATCH_NO)
3221     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3222                "intrinsic subroutine interface", sym->name, &c->loc);
3223
3224   return FAILURE;
3225 }
3226
3227
3228 /* Set the name and binding label of the subroutine symbol in the call
3229    expression represented by 'c' to include the type and kind of the
3230    second parameter.  This function is for resolving the appropriate
3231    version of c_f_pointer() and c_f_procpointer().  For example, a
3232    call to c_f_pointer() for a default integer pointer could have a
3233    name of c_f_pointer_i4.  If no second arg exists, which is an error
3234    for these two functions, it defaults to the generic symbol's name
3235    and binding label.  */
3236
3237 static void
3238 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3239                     char *name, char *binding_label)
3240 {
3241   gfc_expr *arg = NULL;
3242   char type;
3243   int kind;
3244
3245   /* The second arg of c_f_pointer and c_f_procpointer determines
3246      the type and kind for the procedure name.  */
3247   arg = c->ext.actual->next->expr;
3248
3249   if (arg != NULL)
3250     {
3251       /* Set up the name to have the given symbol's name,
3252          plus the type and kind.  */
3253       /* a derived type is marked with the type letter 'u' */
3254       if (arg->ts.type == BT_DERIVED)
3255         {
3256           type = 'd';
3257           kind = 0; /* set the kind as 0 for now */
3258         }
3259       else
3260         {
3261           type = gfc_type_letter (arg->ts.type);
3262           kind = arg->ts.kind;
3263         }
3264
3265       if (arg->ts.type == BT_CHARACTER)
3266         /* Kind info for character strings not needed.  */
3267         kind = 0;
3268
3269       sprintf (name, "%s_%c%d", sym->name, type, kind);
3270       /* Set up the binding label as the given symbol's label plus
3271          the type and kind.  */
3272       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
3273     }
3274   else
3275     {
3276       /* If the second arg is missing, set the name and label as
3277          was, cause it should at least be found, and the missing
3278          arg error will be caught by compare_parameters().  */
3279       sprintf (name, "%s", sym->name);
3280       sprintf (binding_label, "%s", sym->binding_label);
3281     }
3282    
3283   return;
3284 }
3285
3286
3287 /* Resolve a generic version of the iso_c_binding procedure given
3288    (sym) to the specific one based on the type and kind of the
3289    argument(s).  Currently, this function resolves c_f_pointer() and
3290    c_f_procpointer based on the type and kind of the second argument
3291    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3292    Upon successfully exiting, c->resolved_sym will hold the resolved
3293    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3294    otherwise.  */
3295
3296 match
3297 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3298 {
3299   gfc_symbol *new_sym;
3300   /* this is fine, since we know the names won't use the max */
3301   char name[GFC_MAX_SYMBOL_LEN + 1];
3302   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
3303   /* default to success; will override if find error */
3304   match m = MATCH_YES;
3305
3306   /* Make sure the actual arguments are in the necessary order (based on the 
3307      formal args) before resolving.  */
3308   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3309
3310   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3311       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3312     {
3313       set_name_and_label (c, sym, name, binding_label);
3314       
3315       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3316         {
3317           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3318             {
3319               /* Make sure we got a third arg if the second arg has non-zero
3320                  rank.  We must also check that the type and rank are
3321                  correct since we short-circuit this check in
3322                  gfc_procedure_use() (called above to sort actual args).  */
3323               if (c->ext.actual->next->expr->rank != 0)
3324                 {
3325                   if(c->ext.actual->next->next == NULL 
3326                      || c->ext.actual->next->next->expr == NULL)
3327                     {
3328                       m = MATCH_ERROR;
3329                       gfc_error ("Missing SHAPE parameter for call to %s "
3330                                  "at %L", sym->name, &(c->loc));
3331                     }
3332                   else if (c->ext.actual->next->next->expr->ts.type
3333                            != BT_INTEGER
3334                            || c->ext.actual->next->next->expr->rank != 1)
3335                     {
3336                       m = MATCH_ERROR;
3337                       gfc_error ("SHAPE parameter for call to %s at %L must "
3338                                  "be a rank 1 INTEGER array", sym->name,
3339                                  &(c->loc));
3340                     }
3341                 }
3342             }
3343         }
3344       
3345       if (m != MATCH_ERROR)
3346         {
3347           /* the 1 means to add the optional arg to formal list */
3348           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3349          
3350           /* for error reporting, say it's declared where the original was */
3351           new_sym->declared_at = sym->declared_at;
3352         }
3353     }
3354   else
3355     {
3356       /* no differences for c_loc or c_funloc */
3357       new_sym = sym;
3358     }
3359
3360   /* set the resolved symbol */
3361   if (m != MATCH_ERROR)
3362     c->resolved_sym = new_sym;
3363   else
3364     c->resolved_sym = sym;
3365   
3366   return m;
3367 }
3368
3369
3370 /* Resolve a subroutine call known to be specific.  */
3371
3372 static match
3373 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3374 {
3375   match m;
3376
3377   if(sym->attr.is_iso_c)
3378     {
3379       m = gfc_iso_c_sub_interface (c,sym);
3380       return m;
3381     }
3382   
3383   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3384     {
3385       if (sym->attr.dummy)
3386         {
3387           sym->attr.proc = PROC_DUMMY;
3388           goto found;
3389         }
3390
3391       sym->attr.proc = PROC_EXTERNAL;
3392       goto found;
3393     }
3394
3395   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3396     goto found;
3397
3398   if (sym->attr.intrinsic)
3399     {
3400       m = gfc_intrinsic_sub_interface (c, 1);
3401       if (m == MATCH_YES)
3402         return MATCH_YES;
3403       if (m == MATCH_NO)
3404         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3405                    "with an intrinsic", sym->name, &c->loc);
3406
3407       return MATCH_ERROR;
3408     }
3409
3410   return MATCH_NO;
3411
3412 found:
3413   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3414
3415   c->resolved_sym = sym;
3416   pure_subroutine (c, sym);
3417
3418   return MATCH_YES;
3419 }
3420
3421
3422 static gfc_try
3423 resolve_specific_s (gfc_code *c)
3424 {
3425   gfc_symbol *sym;
3426   match m;
3427
3428   sym = c->symtree->n.sym;
3429
3430   for (;;)
3431     {
3432       m = resolve_specific_s0 (c, sym);
3433       if (m == MATCH_YES)
3434         return SUCCESS;
3435       if (m == MATCH_ERROR)
3436         return FAILURE;
3437
3438       if (sym->ns->parent == NULL)
3439         break;
3440
3441       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3442
3443       if (sym == NULL)
3444         break;
3445     }
3446
3447   sym = c->symtree->n.sym;
3448   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3449              sym->name, &c->loc);
3450
3451   return FAILURE;
3452 }
3453
3454
3455 /* Resolve a subroutine call not known to be generic nor specific.  */
3456
3457 static gfc_try
3458 resolve_unknown_s (gfc_code *c)
3459 {
3460   gfc_symbol *sym;
3461
3462   sym = c->symtree->n.sym;
3463
3464   if (sym->attr.dummy)
3465     {
3466       sym->attr.proc = PROC_DUMMY;
3467       goto found;
3468     }
3469
3470   /* See if we have an intrinsic function reference.  */
3471
3472   if (gfc_is_intrinsic (sym, 1, c->loc))
3473     {
3474       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3475         return SUCCESS;
3476       return FAILURE;
3477     }
3478
3479   /* The reference is to an external name.  */
3480
3481 found:
3482   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3483
3484   c->resolved_sym = sym;
3485
3486   pure_subroutine (c, sym);
3487
3488   return SUCCESS;
3489 }
3490
3491
3492 /* Resolve a subroutine call.  Although it was tempting to use the same code
3493    for functions, subroutines and functions are stored differently and this
3494    makes things awkward.  */
3495
3496 static gfc_try
3497 resolve_call (gfc_code *c)
3498 {
3499   gfc_try t;
3500   procedure_type ptype = PROC_INTRINSIC;
3501   gfc_symbol *csym, *sym;
3502   bool no_formal_args;
3503
3504   csym = c->symtree ? c->symtree->n.sym : NULL;
3505
3506   if (csym && csym->ts.type != BT_UNKNOWN)
3507     {
3508       gfc_error ("'%s' at %L has a type, which is not consistent with "
3509                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3510       return FAILURE;
3511     }
3512
3513   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3514     {
3515       gfc_symtree *st;
3516       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3517       sym = st ? st->n.sym : NULL;
3518       if (sym && csym != sym
3519               && sym->ns == gfc_current_ns
3520               && sym->attr.flavor == FL_PROCEDURE
3521               && sym->attr.contained)
3522         {
3523           sym->refs++;
3524           if (csym->attr.generic)
3525             c->symtree->n.sym = sym;
3526           else
3527             c->symtree = st;
3528           csym = c->symtree->n.sym;
3529         }
3530     }
3531
3532   /* If this ia a deferred TBP with an abstract interface
3533      (which may of course be referenced), c->expr1 will be set.  */
3534   if (csym && csym->attr.abstract && !c->expr1)
3535     {
3536       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3537                  csym->name, &c->loc);
3538       return FAILURE;
3539     }
3540
3541   /* Subroutines without the RECURSIVE attribution are not allowed to
3542    * call themselves.  */
3543   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3544     {
3545       if (csym->attr.entry && csym->ns->entries)
3546         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3547                    " subroutine '%s' is not RECURSIVE",
3548                    csym->name, &c->loc, csym->ns->entries->sym->name);
3549       else
3550         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3551                    " is not RECURSIVE", csym->name, &c->loc);
3552
3553       t = FAILURE;
3554     }
3555
3556   /* Switch off assumed size checking and do this again for certain kinds
3557      of procedure, once the procedure itself is resolved.  */
3558   need_full_assumed_size++;
3559
3560   if (csym)
3561     ptype = csym->attr.proc;
3562
3563   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3564   if (resolve_actual_arglist (c->ext.actual, ptype,
3565                               no_formal_args) == FAILURE)
3566     return FAILURE;
3567
3568   /* Resume assumed_size checking.  */
3569   need_full_assumed_size--;
3570
3571   /* If external, check for usage.  */
3572   if (csym && is_external_proc (csym))
3573     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3574
3575   t = SUCCESS;
3576   if (c->resolved_sym == NULL)
3577     {
3578       c->resolved_isym = NULL;
3579       switch (procedure_kind (csym))
3580         {
3581         case PTYPE_GENERIC:
3582           t = resolve_generic_s (c);
3583           break;
3584
3585         case PTYPE_SPECIFIC:
3586           t = resolve_specific_s (c);
3587           break;
3588
3589         case PTYPE_UNKNOWN:
3590           t = resolve_unknown_s (c);
3591           break;
3592
3593         default:
3594           gfc_internal_error ("resolve_subroutine(): bad function type");
3595         }
3596     }
3597
3598   /* Some checks of elemental subroutine actual arguments.  */
3599   if (resolve_elemental_actual (NULL, c) == FAILURE)
3600     return FAILURE;
3601
3602   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3603     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3604   return t;
3605 }
3606
3607
3608 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3609    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3610    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3611    if their shapes do not match.  If either op1->shape or op2->shape is
3612    NULL, return SUCCESS.  */
3613
3614 static gfc_try
3615 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3616 {
3617   gfc_try t;
3618   int i;
3619
3620   t = SUCCESS;
3621
3622   if (op1->shape != NULL && op2->shape != NULL)
3623     {
3624       for (i = 0; i < op1->rank; i++)
3625         {
3626           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3627            {
3628              gfc_error ("Shapes for operands at %L and %L are not conformable",
3629                          &op1->where, &op2->where);
3630              t = FAILURE;
3631              break;
3632            }
3633         }
3634     }
3635
3636   return t;
3637 }
3638
3639
3640 /* Resolve an operator expression node.  This can involve replacing the
3641    operation with a user defined function call.  */
3642
3643 static gfc_try
3644 resolve_operator (gfc_expr *e)
3645 {
3646   gfc_expr *op1, *op2;
3647   char msg[200];
3648   bool dual_locus_error;
3649   gfc_try t;
3650
3651   /* Resolve all subnodes-- give them types.  */
3652
3653   switch (e->value.op.op)
3654     {
3655     default:
3656       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3657         return FAILURE;
3658
3659     /* Fall through...  */
3660
3661     case INTRINSIC_NOT:
3662     case INTRINSIC_UPLUS:
3663     case INTRINSIC_UMINUS:
3664     case INTRINSIC_PARENTHESES:
3665       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3666         return FAILURE;
3667       break;
3668     }
3669
3670   /* Typecheck the new node.  */
3671
3672   op1 = e->value.op.op1;
3673   op2 = e->value.op.op2;
3674   dual_locus_error = false;
3675
3676   if ((op1 && op1->expr_type == EXPR_NULL)
3677       || (op2 && op2->expr_type == EXPR_NULL))
3678     {
3679       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3680       goto bad_op;
3681     }
3682
3683   switch (e->value.op.op)
3684     {
3685     case INTRINSIC_UPLUS:
3686     case INTRINSIC_UMINUS:
3687       if (op1->ts.type == BT_INTEGER
3688           || op1->ts.type == BT_REAL
3689           || op1->ts.type == BT_COMPLEX)
3690         {
3691           e->ts = op1->ts;
3692           break;
3693         }
3694
3695       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3696                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3697       goto bad_op;
3698
3699     case INTRINSIC_PLUS:
3700     case INTRINSIC_MINUS:
3701     case INTRINSIC_TIMES:
3702     case INTRINSIC_DIVIDE:
3703     case INTRINSIC_POWER:
3704       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3705         {
3706           gfc_type_convert_binary (e, 1);
3707           break;
3708         }
3709
3710       sprintf (msg,
3711                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3712                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3713                gfc_typename (&op2->ts));
3714       goto bad_op;
3715
3716     case INTRINSIC_CONCAT:
3717       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3718           && op1->ts.kind == op2->ts.kind)
3719         {
3720           e->ts.type = BT_CHARACTER;
3721           e->ts.kind = op1->ts.kind;
3722           break;
3723         }
3724
3725       sprintf (msg,
3726                _("Operands of string concatenation operator at %%L are %s/%s"),
3727                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3728       goto bad_op;
3729
3730     case INTRINSIC_AND:
3731     case INTRINSIC_OR:
3732     case INTRINSIC_EQV:
3733     case INTRINSIC_NEQV:
3734       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3735         {
3736           e->ts.type = BT_LOGICAL;
3737           e->ts.kind = gfc_kind_max (op1, op2);
3738           if (op1->ts.kind < e->ts.kind)
3739             gfc_convert_type (op1, &e->ts, 2);
3740           else if (op2->ts.kind < e->ts.kind)
3741             gfc_convert_type (op2, &e->ts, 2);
3742           break;
3743         }
3744
3745       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3746                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3747                gfc_typename (&op2->ts));
3748
3749       goto bad_op;
3750
3751     case INTRINSIC_NOT:
3752       if (op1->ts.type == BT_LOGICAL)
3753         {
3754           e->ts.type = BT_LOGICAL;
3755           e->ts.kind = op1->ts.kind;
3756           break;
3757         }
3758
3759       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3760                gfc_typename (&op1->ts));
3761       goto bad_op;
3762
3763     case INTRINSIC_GT:
3764     case INTRINSIC_GT_OS:
3765     case INTRINSIC_GE:
3766     case INTRINSIC_GE_OS:
3767     case INTRINSIC_LT:
3768     case INTRINSIC_LT_OS:
3769     case INTRINSIC_LE:
3770     case INTRINSIC_LE_OS:
3771       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3772         {
3773           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3774           goto bad_op;
3775         }
3776
3777       /* Fall through...  */
3778
3779     case INTRINSIC_EQ:
3780     case INTRINSIC_EQ_OS:
3781     case INTRINSIC_NE:
3782     case INTRINSIC_NE_OS:
3783       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3784           && op1->ts.kind == op2->ts.kind)
3785         {
3786           e->ts.type = BT_LOGICAL;
3787           e->ts.kind = gfc_default_logical_kind;
3788           break;
3789         }
3790
3791       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3792         {
3793           gfc_type_convert_binary (e, 1);
3794
3795           e->ts.type = BT_LOGICAL;
3796           e->ts.kind = gfc_default_logical_kind;
3797           break;
3798         }
3799
3800       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3801         sprintf (msg,
3802                  _("Logicals at %%L must be compared with %s instead of %s"),
3803                  (e->value.op.op == INTRINSIC_EQ 
3804                   || e->value.op.op == INTRINSIC_EQ_OS)
3805                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3806       else
3807         sprintf (msg,
3808                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3809                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3810                  gfc_typename (&op2->ts));
3811
3812       goto bad_op;
3813
3814     case INTRINSIC_USER:
3815       if (e->value.op.uop->op == NULL)
3816         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3817       else if (op2 == NULL)
3818         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3819                  e->value.op.uop->name, gfc_typename (&op1->ts));
3820       else
3821         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3822                  e->value.op.uop->name, gfc_typename (&op1->ts),
3823                  gfc_typename (&op2->ts));
3824
3825       goto bad_op;
3826
3827     case INTRINSIC_PARENTHESES:
3828       e->ts = op1->ts;
3829       if (e->ts.type == BT_CHARACTER)
3830         e->ts.u.cl = op1->ts.u.cl;
3831       break;
3832
3833     default:
3834       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3835     }
3836
3837   /* Deal with arrayness of an operand through an operator.  */
3838
3839   t = SUCCESS;
3840
3841   switch (e->value.op.op)
3842     {
3843     case INTRINSIC_PLUS:
3844     case INTRINSIC_MINUS:
3845     case INTRINSIC_TIMES:
3846     case INTRINSIC_DIVIDE:
3847     case INTRINSIC_POWER:
3848     case INTRINSIC_CONCAT:
3849     case INTRINSIC_AND:
3850     case INTRINSIC_OR:
3851     case INTRINSIC_EQV:
3852     case INTRINSIC_NEQV:
3853     case INTRINSIC_EQ:
3854     case INTRINSIC_EQ_OS:
3855     case INTRINSIC_NE:
3856     case INTRINSIC_NE_OS:
3857     case INTRINSIC_GT:
3858     case INTRINSIC_GT_OS:
3859     case INTRINSIC_GE:
3860     case INTRINSIC_GE_OS:
3861     case INTRINSIC_LT:
3862     case INTRINSIC_LT_OS:
3863     case INTRINSIC_LE:
3864     case INTRINSIC_LE_OS:
3865
3866       if (op1->rank == 0 && op2->rank == 0)
3867         e->rank = 0;
3868
3869       if (op1->rank == 0 && op2->rank != 0)
3870         {
3871           e->rank = op2->rank;
3872
3873           if (e->shape == NULL)
3874             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3875         }
3876
3877       if (op1->rank != 0 && op2->rank == 0)
3878         {
3879           e->rank = op1->rank;
3880
3881           if (e->shape == NULL)
3882             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3883         }
3884
3885       if (op1->rank != 0 && op2->rank != 0)
3886         {
3887           if (op1->rank == op2->rank)
3888             {
3889               e->rank = op1->rank;
3890               if (e->shape == NULL)
3891                 {
3892                   t = compare_shapes (op1, op2);
3893                   if (t == FAILURE)
3894                     e->shape = NULL;
3895                   else
3896                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
3897                 }
3898             }
3899           else
3900             {
3901               /* Allow higher level expressions to work.  */
3902               e->rank = 0;
3903
3904               /* Try user-defined operators, and otherwise throw an error.  */
3905               dual_locus_error = true;
3906               sprintf (msg,
3907                        _("Inconsistent ranks for operator at %%L and %%L"));
3908               goto bad_op;
3909             }
3910         }
3911
3912       break;
3913
3914     case INTRINSIC_PARENTHESES:
3915     case INTRINSIC_NOT:
3916     case INTRINSIC_UPLUS:
3917     case INTRINSIC_UMINUS:
3918       /* Simply copy arrayness attribute */
3919       e->rank = op1->rank;
3920
3921       if (e->shape == NULL)
3922         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3923
3924       break;
3925
3926     default:
3927       break;
3928     }
3929
3930   /* Attempt to simplify the expression.  */
3931   if (t == SUCCESS)
3932     {
3933       t = gfc_simplify_expr (e, 0);
3934       /* Some calls do not succeed in simplification and return FAILURE
3935          even though there is no error; e.g. variable references to
3936          PARAMETER arrays.  */
3937       if (!gfc_is_constant_expr (e))
3938         t = SUCCESS;
3939     }
3940   return t;
3941
3942 bad_op:
3943
3944   {
3945     bool real_error;
3946     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3947       return SUCCESS;
3948
3949     if (real_error)
3950       return FAILURE;
3951   }
3952
3953   if (dual_locus_error)
3954     gfc_error (msg, &op1->where, &op2->where);
3955   else
3956     gfc_error (msg, &e->where);
3957
3958   return FAILURE;
3959 }
3960
3961
3962 /************** Array resolution subroutines **************/
3963
3964 typedef enum
3965 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3966 comparison;
3967
3968 /* Compare two integer expressions.  */
3969
3970 static comparison
3971 compare_bound (gfc_expr *a, gfc_expr *b)
3972 {
3973   int i;
3974
3975   if (a == NULL || a->expr_type != EXPR_CONSTANT
3976       || b == NULL || b->expr_type != EXPR_CONSTANT)
3977     return CMP_UNKNOWN;
3978
3979   /* If either of the types isn't INTEGER, we must have
3980      raised an error earlier.  */
3981
3982   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3983     return CMP_UNKNOWN;
3984
3985   i = mpz_cmp (a->value.integer, b->value.integer);
3986
3987   if (i < 0)
3988     return CMP_LT;
3989   if (i > 0)
3990     return CMP_GT;
3991   return CMP_EQ;
3992 }
3993
3994
3995 /* Compare an integer expression with an integer.  */
3996
3997 static comparison
3998 compare_bound_int (gfc_expr *a, int b)
3999 {
4000   int i;
4001
4002   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4003     return CMP_UNKNOWN;
4004
4005   if (a->ts.type != BT_INTEGER)
4006     gfc_internal_error ("compare_bound_int(): Bad expression");
4007
4008   i = mpz_cmp_si (a->value.integer, b);
4009
4010   if (i < 0)
4011     return CMP_LT;
4012   if (i > 0)
4013     return CMP_GT;
4014   return CMP_EQ;
4015 }
4016
4017
4018 /* Compare an integer expression with a mpz_t.  */
4019
4020 static comparison
4021 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4022 {
4023   int i;
4024
4025   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4026     return CMP_UNKNOWN;
4027
4028   if (a->ts.type != BT_INTEGER)
4029     gfc_internal_error ("compare_bound_int(): Bad expression");
4030
4031   i = mpz_cmp (a->value.integer, b);
4032
4033   if (i < 0)
4034     return CMP_LT;
4035   if (i > 0)
4036     return CMP_GT;
4037   return CMP_EQ;
4038 }
4039
4040
4041 /* Compute the last value of a sequence given by a triplet.  
4042    Return 0 if it wasn't able to compute the last value, or if the
4043    sequence if empty, and 1 otherwise.  */
4044
4045 static int
4046 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4047                                 gfc_expr *stride, mpz_t last)
4048 {
4049   mpz_t rem;
4050
4051   if (start == NULL || start->expr_type != EXPR_CONSTANT
4052       || end == NULL || end->expr_type != EXPR_CONSTANT
4053       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4054     return 0;
4055
4056   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4057       || (stride != NULL && stride->ts.type != BT_INTEGER))
4058     return 0;
4059
4060   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4061     {
4062       if (compare_bound (start, end) == CMP_GT)
4063         return 0;
4064       mpz_set (last, end->value.integer);
4065       return 1;
4066     }
4067
4068   if (compare_bound_int (stride, 0) == CMP_GT)
4069     {
4070       /* Stride is positive */
4071       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4072         return 0;
4073     }
4074   else
4075     {
4076       /* Stride is negative */
4077       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4078         return 0;
4079     }
4080
4081   mpz_init (rem);
4082   mpz_sub (rem, end->value.integer, start->value.integer);
4083   mpz_tdiv_r (rem, rem, stride->value.integer);
4084   mpz_sub (last, end->value.integer, rem);
4085   mpz_clear (rem);
4086
4087   return 1;
4088 }
4089
4090
4091 /* Compare a single dimension of an array reference to the array
4092    specification.  */
4093
4094 static gfc_try
4095 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4096 {
4097   mpz_t last_value;
4098
4099   if (ar->dimen_type[i] == DIMEN_STAR)
4100     {
4101       gcc_assert (ar->stride[i] == NULL);
4102       /* This implies [*] as [*:] and [*:3] are not possible.  */
4103       if (ar->start[i] == NULL)
4104         {
4105           gcc_assert (ar->end[i] == NULL);
4106           return SUCCESS;
4107         }
4108     }
4109
4110 /* Given start, end and stride values, calculate the minimum and
4111    maximum referenced indexes.  */
4112
4113   switch (ar->dimen_type[i])
4114     {
4115     case DIMEN_VECTOR:
4116       break;
4117
4118     case DIMEN_STAR:
4119     case DIMEN_ELEMENT:
4120       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4121         {
4122           if (i < as->rank)
4123             gfc_warning ("Array reference at %L is out of bounds "
4124                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4125                          mpz_get_si (ar->start[i]->value.integer),
4126                          mpz_get_si (as->lower[i]->value.integer), i+1);
4127           else
4128             gfc_warning ("Array reference at %L is out of bounds "
4129                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4130                          mpz_get_si (ar->start[i]->value.integer),
4131                          mpz_get_si (as->lower[i]->value.integer),
4132                          i + 1 - as->rank);
4133           return SUCCESS;
4134         }
4135       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4136         {
4137           if (i < as->rank)
4138             gfc_warning ("Array reference at %L is out of bounds "
4139                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4140                          mpz_get_si (ar->start[i]->value.integer),
4141                          mpz_get_si (as->upper[i]->value.integer), i+1);
4142           else
4143             gfc_warning ("Array reference at %L is out of bounds "
4144                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4145                          mpz_get_si (ar->start[i]->value.integer),
4146                          mpz_get_si (as->upper[i]->value.integer),
4147                          i + 1 - as->rank);
4148           return SUCCESS;
4149         }
4150
4151       break;
4152
4153     case DIMEN_RANGE:
4154       {
4155 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4156 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4157
4158         comparison comp_start_end = compare_bound (AR_START, AR_END);
4159
4160         /* Check for zero stride, which is not allowed.  */
4161         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4162           {
4163             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4164             return FAILURE;
4165           }
4166
4167         /* if start == len || (stride > 0 && start < len)
4168                            || (stride < 0 && start > len),
4169            then the array section contains at least one element.  In this
4170            case, there is an out-of-bounds access if
4171            (start < lower || start > upper).  */
4172         if (compare_bound (AR_START, AR_END) == CMP_EQ
4173             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4174                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4175             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4176                 && comp_start_end == CMP_GT))
4177           {
4178             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4179               {
4180                 gfc_warning ("Lower array reference at %L is out of bounds "
4181                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4182                        mpz_get_si (AR_START->value.integer),
4183                        mpz_get_si (as->lower[i]->value.integer), i+1);
4184                 return SUCCESS;
4185               }
4186             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4187               {
4188                 gfc_warning ("Lower array reference at %L is out of bounds "
4189                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4190                        mpz_get_si (AR_START->value.integer),
4191                        mpz_get_si (as->upper[i]->value.integer), i+1);
4192                 return SUCCESS;
4193               }
4194           }
4195
4196         /* If we can compute the highest index of the array section,
4197            then it also has to be between lower and upper.  */
4198         mpz_init (last_value);
4199         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4200                                             last_value))
4201           {
4202             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4203               {
4204                 gfc_warning ("Upper array reference at %L is out of bounds "
4205                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4206                        mpz_get_si (last_value),
4207                        mpz_get_si (as->lower[i]->value.integer), i+1);
4208                 mpz_clear (last_value);
4209                 return SUCCESS;
4210               }
4211             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4212               {
4213                 gfc_warning ("Upper array reference at %L is out of bounds "
4214                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4215                        mpz_get_si (last_value),
4216                        mpz_get_si (as->upper[i]->value.integer), i+1);
4217                 mpz_clear (last_value);
4218                 return SUCCESS;
4219               }
4220           }
4221         mpz_clear (last_value);
4222
4223 #undef AR_START
4224 #undef AR_END
4225       }
4226       break;
4227
4228     default:
4229       gfc_internal_error ("check_dimension(): Bad array reference");
4230     }
4231
4232   return SUCCESS;
4233 }
4234
4235
4236 /* Compare an array reference with an array specification.  */
4237
4238 static gfc_try
4239 compare_spec_to_ref (gfc_array_ref *ar)
4240 {
4241   gfc_array_spec *as;
4242   int i;
4243
4244   as = ar->as;
4245   i = as->rank - 1;
4246   /* TODO: Full array sections are only allowed as actual parameters.  */
4247   if (as->type == AS_ASSUMED_SIZE
4248       && (/*ar->type == AR_FULL
4249           ||*/ (ar->type == AR_SECTION
4250               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4251     {
4252       gfc_error ("Rightmost upper bound of assumed size array section "
4253                  "not specified at %L", &ar->where);
4254       return FAILURE;
4255     }
4256
4257   if (ar->type == AR_FULL)
4258     return SUCCESS;
4259
4260   if (as->rank != ar->dimen)
4261     {
4262       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4263                  &ar->where, ar->dimen, as->rank);
4264       return FAILURE;
4265     }
4266
4267   /* ar->codimen == 0 is a local array.  */
4268   if (as->corank != ar->codimen && ar->codimen != 0)
4269     {
4270       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4271                  &ar->where, ar->codimen, as->corank);
4272       return FAILURE;
4273     }
4274
4275   for (i = 0; i < as->rank; i++)
4276     if (check_dimension (i, ar, as) == FAILURE)
4277       return FAILURE;
4278
4279   /* Local access has no coarray spec.  */
4280   if (ar->codimen != 0)
4281     for (i = as->rank; i < as->rank + as->corank; i++)
4282       {
4283         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate)
4284           {
4285             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4286                        i + 1 - as->rank, &ar->where);
4287             return FAILURE;
4288           }
4289         if (check_dimension (i, ar, as) == FAILURE)
4290           return FAILURE;
4291       }
4292
4293   return SUCCESS;
4294 }
4295
4296
4297 /* Resolve one part of an array index.  */
4298
4299 static gfc_try
4300 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4301                      int force_index_integer_kind)
4302 {
4303   gfc_typespec ts;
4304
4305   if (index == NULL)
4306     return SUCCESS;
4307
4308   if (gfc_resolve_expr (index) == FAILURE)
4309     return FAILURE;
4310
4311   if (check_scalar && index->rank != 0)
4312     {
4313       gfc_error ("Array index at %L must be scalar", &index->where);
4314       return FAILURE;
4315     }
4316
4317   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4318     {
4319       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4320                  &index->where, gfc_basic_typename (index->ts.type));
4321       return FAILURE;
4322     }
4323
4324   if (index->ts.type == BT_REAL)
4325     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4326                         &index->where) == FAILURE)
4327       return FAILURE;
4328
4329   if ((index->ts.kind != gfc_index_integer_kind
4330        && force_index_integer_kind)
4331       || index->ts.type != BT_INTEGER)
4332     {
4333       gfc_clear_ts (&ts);
4334       ts.type = BT_INTEGER;
4335       ts.kind = gfc_index_integer_kind;
4336
4337       gfc_convert_type_warn (index, &ts, 2, 0);
4338     }
4339
4340   return SUCCESS;
4341 }
4342
4343 /* Resolve one part of an array index.  */
4344
4345 gfc_try
4346 gfc_resolve_index (gfc_expr *index, int check_scalar)
4347 {
4348   return gfc_resolve_index_1 (index, check_scalar, 1);
4349 }
4350
4351 /* Resolve a dim argument to an intrinsic function.  */
4352
4353 gfc_try
4354 gfc_resolve_dim_arg (gfc_expr *dim)
4355 {
4356   if (dim == NULL)
4357     return SUCCESS;
4358
4359   if (gfc_resolve_expr (dim) == FAILURE)
4360     return FAILURE;
4361
4362   if (dim->rank != 0)
4363     {
4364       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4365       return FAILURE;
4366
4367     }
4368
4369   if (dim->ts.type != BT_INTEGER)
4370     {
4371       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4372       return FAILURE;
4373     }
4374
4375   if (dim->ts.kind != gfc_index_integer_kind)
4376     {
4377       gfc_typespec ts;
4378
4379       gfc_clear_ts (&ts);
4380       ts.type = BT_INTEGER;
4381       ts.kind = gfc_index_integer_kind;
4382
4383       gfc_convert_type_warn (dim, &ts, 2, 0);
4384     }
4385
4386   return SUCCESS;
4387 }
4388
4389 /* Given an expression that contains array references, update those array
4390    references to point to the right array specifications.  While this is
4391    filled in during matching, this information is difficult to save and load
4392    in a module, so we take care of it here.
4393
4394    The idea here is that the original array reference comes from the
4395    base symbol.  We traverse the list of reference structures, setting
4396    the stored reference to references.  Component references can
4397    provide an additional array specification.  */
4398
4399 static void
4400 find_array_spec (gfc_expr *e)
4401 {
4402   gfc_array_spec *as;
4403   gfc_component *c;
4404   gfc_symbol *derived;
4405   gfc_ref *ref;
4406
4407   if (e->symtree->n.sym->ts.type == BT_CLASS)
4408     as = CLASS_DATA (e->symtree->n.sym)->as;
4409   else
4410     as = e->symtree->n.sym->as;
4411   derived = NULL;
4412
4413   for (ref = e->ref; ref; ref = ref->next)
4414     switch (ref->type)
4415       {
4416       case REF_ARRAY:
4417         if (as == NULL)
4418           gfc_internal_error ("find_array_spec(): Missing spec");
4419
4420         ref->u.ar.as = as;
4421         as = NULL;
4422         break;
4423
4424       case REF_COMPONENT:
4425         if (derived == NULL)
4426           derived = e->symtree->n.sym->ts.u.derived;
4427
4428         if (derived->attr.is_class)
4429           derived = derived->components->ts.u.derived;
4430
4431         c = derived->components;
4432
4433         for (; c; c = c->next)
4434           if (c == ref->u.c.component)
4435             {
4436               /* Track the sequence of component references.  */
4437               if (c->ts.type == BT_DERIVED)
4438                 derived = c->ts.u.derived;
4439               break;
4440             }
4441
4442         if (c == NULL)
4443           gfc_internal_error ("find_array_spec(): Component not found");
4444
4445         if (c->attr.dimension)
4446           {
4447             if (as != NULL)
4448               gfc_internal_error ("find_array_spec(): unused as(1)");
4449             as = c->as;
4450           }
4451
4452         break;
4453
4454       case REF_SUBSTRING:
4455         break;
4456       }
4457
4458   if (as != NULL)
4459     gfc_internal_error ("find_array_spec(): unused as(2)");
4460 }
4461
4462
4463 /* Resolve an array reference.  */
4464
4465 static gfc_try
4466 resolve_array_ref (gfc_array_ref *ar)
4467 {
4468   int i, check_scalar;
4469   gfc_expr *e;
4470
4471   for (i = 0; i < ar->dimen + ar->codimen; i++)
4472     {
4473       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4474
4475       /* Do not force gfc_index_integer_kind for the start.  We can
4476          do fine with any integer kind.  This avoids temporary arrays
4477          created for indexing with a vector.  */
4478       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4479         return FAILURE;
4480       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4481         return FAILURE;
4482       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4483         return FAILURE;
4484
4485       e = ar->start[i];
4486
4487       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4488         switch (e->rank)
4489           {
4490           case 0:
4491             ar->dimen_type[i] = DIMEN_ELEMENT;
4492             break;
4493
4494           case 1:
4495             ar->dimen_type[i] = DIMEN_VECTOR;
4496             if (e->expr_type == EXPR_VARIABLE
4497                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4498               ar->start[i] = gfc_get_parentheses (e);
4499             break;
4500
4501           default:
4502             gfc_error ("Array index at %L is an array of rank %d",
4503                        &ar->c_where[i], e->rank);
4504             return FAILURE;
4505           }
4506
4507       /* Fill in the upper bound, which may be lower than the
4508          specified one for something like a(2:10:5), which is
4509          identical to a(2:7:5).  Only relevant for strides not equal
4510          to one.  */
4511       if (ar->dimen_type[i] == DIMEN_RANGE
4512           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4513           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0)
4514         {
4515           mpz_t size, end;
4516
4517           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4518             {
4519               if (ar->end[i] == NULL)
4520                 {
4521                   ar->end[i] =
4522                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4523                                            &ar->where);
4524                   mpz_set (ar->end[i]->value.integer, end);
4525                 }
4526               else if (ar->end[i]->ts.type == BT_INTEGER
4527                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4528                 {
4529                   mpz_set (ar->end[i]->value.integer, end);
4530                 }
4531               else
4532                 gcc_unreachable ();
4533
4534               mpz_clear (size);
4535               mpz_clear (end);
4536             }
4537         }
4538     }
4539
4540   if (ar->type == AR_FULL && ar->as->rank == 0)
4541     ar->type = AR_ELEMENT;
4542
4543   /* If the reference type is unknown, figure out what kind it is.  */
4544
4545   if (ar->type == AR_UNKNOWN)
4546     {
4547       ar->type = AR_ELEMENT;
4548       for (i = 0; i < ar->dimen; i++)
4549         if (ar->dimen_type[i] == DIMEN_RANGE
4550             || ar->dimen_type[i] == DIMEN_VECTOR)
4551           {
4552             ar->type = AR_SECTION;
4553             break;
4554           }
4555     }
4556
4557   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4558     return FAILURE;
4559
4560   return SUCCESS;
4561 }
4562
4563
4564 static gfc_try
4565 resolve_substring (gfc_ref *ref)
4566 {
4567   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4568
4569   if (ref->u.ss.start != NULL)
4570     {
4571       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4572         return FAILURE;
4573
4574       if (ref->u.ss.start->ts.type != BT_INTEGER)
4575         {
4576           gfc_error ("Substring start index at %L must be of type INTEGER",
4577                      &ref->u.ss.start->where);
4578           return FAILURE;
4579         }
4580
4581       if (ref->u.ss.start->rank != 0)
4582         {
4583           gfc_error ("Substring start index at %L must be scalar",
4584                      &ref->u.ss.start->where);
4585           return FAILURE;
4586         }
4587
4588       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4589           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4590               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4591         {
4592           gfc_error ("Substring start index at %L is less than one",
4593                      &ref->u.ss.start->where);
4594           return FAILURE;
4595         }
4596     }
4597
4598   if (ref->u.ss.end != NULL)
4599     {
4600       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4601         return FAILURE;
4602
4603       if (ref->u.ss.end->ts.type != BT_INTEGER)
4604         {
4605           gfc_error ("Substring end index at %L must be of type INTEGER",
4606                      &ref->u.ss.end->where);
4607           return FAILURE;
4608         }
4609
4610       if (ref->u.ss.end->rank != 0)
4611         {
4612           gfc_error ("Substring end index at %L must be scalar",
4613                      &ref->u.ss.end->where);
4614           return FAILURE;
4615         }
4616
4617       if (ref->u.ss.length != NULL
4618           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4619           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4620               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4621         {
4622           gfc_error ("Substring end index at %L exceeds the string length",
4623                      &ref->u.ss.start->where);
4624           return FAILURE;
4625         }
4626
4627       if (compare_bound_mpz_t (ref->u.ss.end,
4628                                gfc_integer_kinds[k].huge) == CMP_GT
4629           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4630               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4631         {
4632           gfc_error ("Substring end index at %L is too large",
4633                      &ref->u.ss.end->where);
4634           return FAILURE;
4635         }
4636     }
4637
4638   return SUCCESS;
4639 }
4640
4641
4642 /* This function supplies missing substring charlens.  */
4643
4644 void
4645 gfc_resolve_substring_charlen (gfc_expr *e)
4646 {
4647   gfc_ref *char_ref;
4648   gfc_expr *start, *end;
4649
4650   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4651     if (char_ref->type == REF_SUBSTRING)
4652       break;
4653
4654   if (!char_ref)
4655     return;
4656
4657   gcc_assert (char_ref->next == NULL);
4658
4659   if (e->ts.u.cl)
4660     {
4661       if (e->ts.u.cl->length)
4662         gfc_free_expr (e->ts.u.cl->length);
4663       else if (e->expr_type == EXPR_VARIABLE
4664                  && e->symtree->n.sym->attr.dummy)
4665         return;
4666     }
4667
4668   e->ts.type = BT_CHARACTER;
4669   e->ts.kind = gfc_default_character_kind;
4670
4671   if (!e->ts.u.cl)
4672     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4673
4674   if (char_ref->u.ss.start)
4675     start = gfc_copy_expr (char_ref->u.ss.start);
4676   else
4677     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4678
4679   if (char_ref->u.ss.end)
4680     end = gfc_copy_expr (char_ref->u.ss.end);
4681   else if (e->expr_type == EXPR_VARIABLE)
4682     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4683   else
4684     end = NULL;
4685
4686   if (!start || !end)
4687     return;
4688
4689   /* Length = (end - start +1).  */
4690   e->ts.u.cl->length = gfc_subtract (end, start);
4691   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4692                                 gfc_get_int_expr (gfc_default_integer_kind,
4693                                                   NULL, 1));
4694
4695   e->ts.u.cl->length->ts.type = BT_INTEGER;
4696   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4697
4698   /* Make sure that the length is simplified.  */
4699   gfc_simplify_expr (e->ts.u.cl->length, 1);
4700   gfc_resolve_expr (e->ts.u.cl->length);
4701 }
4702
4703
4704 /* Resolve subtype references.  */
4705
4706 static gfc_try
4707 resolve_ref (gfc_expr *expr)
4708 {
4709   int current_part_dimension, n_components, seen_part_dimension;
4710   gfc_ref *ref;
4711
4712   for (ref = expr->ref; ref; ref = ref->next)
4713     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4714       {
4715         find_array_spec (expr);
4716         break;
4717       }
4718
4719   for (ref = expr->ref; ref; ref = ref->next)
4720     switch (ref->type)
4721       {
4722       case REF_ARRAY:
4723         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4724           return FAILURE;
4725         break;
4726
4727       case REF_COMPONENT:
4728         break;
4729
4730       case REF_SUBSTRING:
4731         resolve_substring (ref);
4732         break;
4733       }
4734
4735   /* Check constraints on part references.  */
4736
4737   current_part_dimension = 0;
4738   seen_part_dimension = 0;
4739   n_components = 0;
4740
4741   for (ref = expr->ref; ref; ref = ref->next)
4742     {
4743       switch (ref->type)
4744         {
4745         case REF_ARRAY:
4746           switch (ref->u.ar.type)
4747             {
4748             case AR_FULL:
4749               /* Coarray scalar.  */
4750               if (ref->u.ar.as->rank == 0)
4751                 {
4752                   current_part_dimension = 0;
4753                   break;
4754                 }
4755               /* Fall through.  */
4756             case AR_SECTION:
4757               current_part_dimension = 1;
4758               break;
4759
4760             case AR_ELEMENT:
4761               current_part_dimension = 0;
4762               break;
4763
4764             case AR_UNKNOWN:
4765               gfc_internal_error ("resolve_ref(): Bad array reference");
4766             }
4767
4768           break;
4769
4770         case REF_COMPONENT:
4771           if (current_part_dimension || seen_part_dimension)
4772             {
4773               /* F03:C614.  */
4774               if (ref->u.c.component->attr.pointer
4775                   || ref->u.c.component->attr.proc_pointer)
4776                 {
4777                   gfc_error ("Component to the right of a part reference "
4778                              "with nonzero rank must not have the POINTER "
4779                              "attribute at %L", &expr->where);
4780                   return FAILURE;
4781                 }
4782               else if (ref->u.c.component->attr.allocatable)
4783                 {
4784                   gfc_error ("Component to the right of a part reference "
4785                              "with nonzero rank must not have the ALLOCATABLE "
4786                              "attribute at %L", &expr->where);
4787                   return FAILURE;
4788                 }
4789             }
4790
4791           n_components++;
4792           break;
4793
4794         case REF_SUBSTRING:
4795           break;
4796         }
4797
4798       if (((ref->type == REF_COMPONENT && n_components > 1)
4799            || ref->next == NULL)
4800           && current_part_dimension
4801           && seen_part_dimension)
4802         {
4803           gfc_error ("Two or more part references with nonzero rank must "
4804                      "not be specified at %L", &expr->where);
4805           return FAILURE;
4806         }
4807
4808       if (ref->type == REF_COMPONENT)
4809         {
4810           if (current_part_dimension)
4811             seen_part_dimension = 1;
4812
4813           /* reset to make sure */
4814           current_part_dimension = 0;
4815         }
4816     }
4817
4818   return SUCCESS;
4819 }
4820
4821
4822 /* Given an expression, determine its shape.  This is easier than it sounds.
4823    Leaves the shape array NULL if it is not possible to determine the shape.  */
4824
4825 static void
4826 expression_shape (gfc_expr *e)
4827 {
4828   mpz_t array[GFC_MAX_DIMENSIONS];
4829   int i;
4830
4831   if (e->rank == 0 || e->shape != NULL)
4832     return;
4833
4834   for (i = 0; i < e->rank; i++)
4835     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4836       goto fail;
4837
4838   e->shape = gfc_get_shape (e->rank);
4839
4840   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4841
4842   return;
4843
4844 fail:
4845   for (i--; i >= 0; i--)
4846     mpz_clear (array[i]);
4847 }
4848
4849
4850 /* Given a variable expression node, compute the rank of the expression by
4851    examining the base symbol and any reference structures it may have.  */
4852
4853 static void
4854 expression_rank (gfc_expr *e)
4855 {
4856   gfc_ref *ref;
4857   int i, rank;
4858
4859   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4860      could lead to serious confusion...  */
4861   gcc_assert (e->expr_type != EXPR_COMPCALL);
4862
4863   if (e->ref == NULL)
4864     {
4865       if (e->expr_type == EXPR_ARRAY)
4866         goto done;
4867       /* Constructors can have a rank different from one via RESHAPE().  */
4868
4869       if (e->symtree == NULL)
4870         {
4871           e->rank = 0;
4872           goto done;
4873         }
4874
4875       e->rank = (e->symtree->n.sym->as == NULL)
4876                 ? 0 : e->symtree->n.sym->as->rank;
4877       goto done;
4878     }
4879
4880   rank = 0;
4881
4882   for (ref = e->ref; ref; ref = ref->next)
4883     {
4884       if (ref->type != REF_ARRAY)
4885         continue;
4886
4887       if (ref->u.ar.type == AR_FULL)
4888         {
4889           rank = ref->u.ar.as->rank;
4890           break;
4891         }
4892
4893       if (ref->u.ar.type == AR_SECTION)
4894         {
4895           /* Figure out the rank of the section.  */
4896           if (rank != 0)
4897             gfc_internal_error ("expression_rank(): Two array specs");
4898
4899           for (i = 0; i < ref->u.ar.dimen; i++)
4900             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4901                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4902               rank++;
4903
4904           break;
4905         }
4906     }
4907
4908   e->rank = rank;
4909
4910 done:
4911   expression_shape (e);
4912 }
4913
4914
4915 /* Resolve a variable expression.  */
4916
4917 static gfc_try
4918 resolve_variable (gfc_expr *e)
4919 {
4920   gfc_symbol *sym;
4921   gfc_try t;
4922
4923   t = SUCCESS;
4924
4925   if (e->symtree == NULL)
4926     return FAILURE;
4927   sym = e->symtree->n.sym;
4928
4929   /* If this is an associate-name, it may be parsed with an array reference
4930      in error even though the target is scalar.  Fail directly in this case.  */
4931   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
4932     return FAILURE;
4933
4934   /* On the other hand, the parser may not have known this is an array;
4935      in this case, we have to add a FULL reference.  */
4936   if (sym->assoc && sym->attr.dimension && !e->ref)
4937     {
4938       e->ref = gfc_get_ref ();
4939       e->ref->type = REF_ARRAY;
4940       e->ref->u.ar.type = AR_FULL;
4941       e->ref->u.ar.dimen = 0;
4942     }
4943
4944   if (e->ref && resolve_ref (e) == FAILURE)
4945     return FAILURE;
4946
4947   if (sym->attr.flavor == FL_PROCEDURE
4948       && (!sym->attr.function
4949           || (sym->attr.function && sym->result
4950               && sym->result->attr.proc_pointer
4951               && !sym->result->attr.function)))
4952     {
4953       e->ts.type = BT_PROCEDURE;
4954       goto resolve_procedure;
4955     }
4956
4957   if (sym->ts.type != BT_UNKNOWN)
4958     gfc_variable_attr (e, &e->ts);
4959   else
4960     {
4961       /* Must be a simple variable reference.  */
4962       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4963         return FAILURE;
4964       e->ts = sym->ts;
4965     }
4966
4967   if (check_assumed_size_reference (sym, e))
4968     return FAILURE;
4969
4970   /* Deal with forward references to entries during resolve_code, to
4971      satisfy, at least partially, 12.5.2.5.  */
4972   if (gfc_current_ns->entries
4973       && current_entry_id == sym->entry_id
4974       && cs_base
4975       && cs_base->current
4976       && cs_base->current->op != EXEC_ENTRY)
4977     {
4978       gfc_entry_list *entry;
4979       gfc_formal_arglist *formal;
4980       int n;
4981       bool seen;
4982
4983       /* If the symbol is a dummy...  */
4984       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4985         {
4986           entry = gfc_current_ns->entries;
4987           seen = false;
4988
4989           /* ...test if the symbol is a parameter of previous entries.  */
4990           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4991             for (formal = entry->sym->formal; formal; formal = formal->next)
4992               {
4993                 if (formal->sym && sym->name == formal->sym->name)
4994                   seen = true;
4995               }
4996
4997           /*  If it has not been seen as a dummy, this is an error.  */
4998           if (!seen)
4999             {
5000               if (specification_expr)
5001                 gfc_error ("Variable '%s', used in a specification expression"
5002                            ", is referenced at %L before the ENTRY statement "
5003                            "in which it is a parameter",
5004                            sym->name, &cs_base->current->loc);
5005               else
5006                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5007                            "statement in which it is a parameter",
5008                            sym->name, &cs_base->current->loc);
5009               t = FAILURE;
5010             }
5011         }
5012
5013       /* Now do the same check on the specification expressions.  */
5014       specification_expr = 1;
5015       if (sym->ts.type == BT_CHARACTER
5016           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5017         t = FAILURE;
5018
5019       if (sym->as)
5020         for (n = 0; n < sym->as->rank; n++)
5021           {
5022              specification_expr = 1;
5023              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5024                t = FAILURE;
5025              specification_expr = 1;
5026              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5027                t = FAILURE;
5028           }
5029       specification_expr = 0;
5030
5031       if (t == SUCCESS)
5032         /* Update the symbol's entry level.  */
5033         sym->entry_id = current_entry_id + 1;
5034     }
5035
5036   /* If a symbol has been host_associated mark it.  This is used latter,
5037      to identify if aliasing is possible via host association.  */
5038   if (sym->attr.flavor == FL_VARIABLE
5039         && gfc_current_ns->parent
5040         && (gfc_current_ns->parent == sym->ns
5041               || (gfc_current_ns->parent->parent
5042                     && gfc_current_ns->parent->parent == sym->ns)))
5043     sym->attr.host_assoc = 1;
5044
5045 resolve_procedure:
5046   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5047     t = FAILURE;
5048
5049   /* F2008, C617 and C1229.  */
5050   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5051       && gfc_is_coindexed (e))
5052     {
5053       gfc_ref *ref, *ref2 = NULL;
5054
5055       if (e->ts.type == BT_CLASS)
5056         {
5057           gfc_error ("Polymorphic subobject of coindexed object at %L",
5058                      &e->where);
5059           t = FAILURE;
5060         }
5061
5062       for (ref = e->ref; ref; ref = ref->next)
5063         {
5064           if (ref->type == REF_COMPONENT)
5065             ref2 = ref;
5066           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5067             break;
5068         }
5069
5070       for ( ; ref; ref = ref->next)
5071         if (ref->type == REF_COMPONENT)
5072           break;
5073
5074       /* Expression itself is coindexed object.  */
5075       if (ref == NULL)
5076         {
5077           gfc_component *c;
5078           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5079           for ( ; c; c = c->next)
5080             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5081               {
5082                 gfc_error ("Coindexed object with polymorphic allocatable "
5083                          "subcomponent at %L", &e->where);
5084                 t = FAILURE;
5085                 break;
5086               }
5087         }
5088     }
5089
5090   return t;
5091 }
5092
5093
5094 /* Checks to see that the correct symbol has been host associated.
5095    The only situation where this arises is that in which a twice
5096    contained function is parsed after the host association is made.
5097    Therefore, on detecting this, change the symbol in the expression
5098    and convert the array reference into an actual arglist if the old
5099    symbol is a variable.  */
5100 static bool
5101 check_host_association (gfc_expr *e)
5102 {
5103   gfc_symbol *sym, *old_sym;
5104   gfc_symtree *st;
5105   int n;
5106   gfc_ref *ref;
5107   gfc_actual_arglist *arg, *tail = NULL;
5108   bool retval = e->expr_type == EXPR_FUNCTION;
5109
5110   /*  If the expression is the result of substitution in
5111       interface.c(gfc_extend_expr) because there is no way in
5112       which the host association can be wrong.  */
5113   if (e->symtree == NULL
5114         || e->symtree->n.sym == NULL
5115         || e->user_operator)
5116     return retval;
5117
5118   old_sym = e->symtree->n.sym;
5119
5120   if (gfc_current_ns->parent
5121         && old_sym->ns != gfc_current_ns)
5122     {
5123       /* Use the 'USE' name so that renamed module symbols are
5124          correctly handled.  */
5125       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5126
5127       if (sym && old_sym != sym
5128               && sym->ts.type == old_sym->ts.type
5129               && sym->attr.flavor == FL_PROCEDURE
5130               && sym->attr.contained)
5131         {
5132           /* Clear the shape, since it might not be valid.  */
5133           if (e->shape != NULL)
5134             {
5135               for (n = 0; n < e->rank; n++)
5136                 mpz_clear (e->shape[n]);
5137
5138               gfc_free (e->shape);
5139             }
5140
5141           /* Give the expression the right symtree!  */
5142           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5143           gcc_assert (st != NULL);
5144
5145           if (old_sym->attr.flavor == FL_PROCEDURE
5146                 || e->expr_type == EXPR_FUNCTION)
5147             {
5148               /* Original was function so point to the new symbol, since
5149                  the actual argument list is already attached to the
5150                  expression. */
5151               e->value.function.esym = NULL;
5152               e->symtree = st;
5153             }
5154           else
5155             {
5156               /* Original was variable so convert array references into
5157                  an actual arglist. This does not need any checking now
5158                  since gfc_resolve_function will take care of it.  */
5159               e->value.function.actual = NULL;
5160               e->expr_type = EXPR_FUNCTION;
5161               e->symtree = st;
5162
5163               /* Ambiguity will not arise if the array reference is not
5164                  the last reference.  */
5165               for (ref = e->ref; ref; ref = ref->next)
5166                 if (ref->type == REF_ARRAY && ref->next == NULL)
5167                   break;
5168
5169               gcc_assert (ref->type == REF_ARRAY);
5170
5171               /* Grab the start expressions from the array ref and
5172                  copy them into actual arguments.  */
5173               for (n = 0; n < ref->u.ar.dimen; n++)
5174                 {
5175                   arg = gfc_get_actual_arglist ();
5176                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5177                   if (e->value.function.actual == NULL)
5178                     tail = e->value.function.actual = arg;
5179                   else
5180                     {
5181                       tail->next = arg;
5182                       tail = arg;
5183                     }
5184                 }
5185
5186               /* Dump the reference list and set the rank.  */
5187               gfc_free_ref_list (e->ref);
5188               e->ref = NULL;
5189               e->rank = sym->as ? sym->as->rank : 0;
5190             }
5191
5192           gfc_resolve_expr (e);
5193           sym->refs++;
5194         }
5195     }
5196   /* This might have changed!  */
5197   return e->expr_type == EXPR_FUNCTION;
5198 }
5199
5200
5201 static void
5202 gfc_resolve_character_operator (gfc_expr *e)
5203 {
5204   gfc_expr *op1 = e->value.op.op1;
5205   gfc_expr *op2 = e->value.op.op2;
5206   gfc_expr *e1 = NULL;
5207   gfc_expr *e2 = NULL;
5208
5209   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5210
5211   if (op1->ts.u.cl && op1->ts.u.cl->length)
5212     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5213   else if (op1->expr_type == EXPR_CONSTANT)
5214     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5215                            op1->value.character.length);
5216
5217   if (op2->ts.u.cl && op2->ts.u.cl->length)
5218     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5219   else if (op2->expr_type == EXPR_CONSTANT)
5220     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5221                            op2->value.character.length);
5222
5223   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5224
5225   if (!e1 || !e2)
5226     return;
5227
5228   e->ts.u.cl->length = gfc_add (e1, e2);
5229   e->ts.u.cl->length->ts.type = BT_INTEGER;
5230   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5231   gfc_simplify_expr (e->ts.u.cl->length, 0);
5232   gfc_resolve_expr (e->ts.u.cl->length);
5233
5234   return;
5235 }
5236
5237
5238 /*  Ensure that an character expression has a charlen and, if possible, a
5239     length expression.  */
5240
5241 static void
5242 fixup_charlen (gfc_expr *e)
5243 {
5244   /* The cases fall through so that changes in expression type and the need
5245      for multiple fixes are picked up.  In all circumstances, a charlen should
5246      be available for the middle end to hang a backend_decl on.  */
5247   switch (e->expr_type)
5248     {
5249     case EXPR_OP:
5250       gfc_resolve_character_operator (e);
5251
5252     case EXPR_ARRAY:
5253       if (e->expr_type == EXPR_ARRAY)
5254         gfc_resolve_character_array_constructor (e);
5255
5256     case EXPR_SUBSTRING:
5257       if (!e->ts.u.cl && e->ref)
5258         gfc_resolve_substring_charlen (e);
5259
5260     default:
5261       if (!e->ts.u.cl)
5262         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5263
5264       break;
5265     }
5266 }
5267
5268
5269 /* Update an actual argument to include the passed-object for type-bound
5270    procedures at the right position.  */
5271
5272 static gfc_actual_arglist*
5273 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5274                      const char *name)
5275 {
5276   gcc_assert (argpos > 0);
5277
5278   if (argpos == 1)
5279     {
5280       gfc_actual_arglist* result;
5281
5282       result = gfc_get_actual_arglist ();
5283       result->expr = po;
5284       result->next = lst;
5285       if (name)
5286         result->name = name;
5287
5288       return result;
5289     }
5290
5291   if (lst)
5292     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5293   else
5294     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5295   return lst;
5296 }
5297
5298
5299 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5300
5301 static gfc_expr*
5302 extract_compcall_passed_object (gfc_expr* e)
5303 {
5304   gfc_expr* po;
5305
5306   gcc_assert (e->expr_type == EXPR_COMPCALL);
5307
5308   if (e->value.compcall.base_object)
5309     po = gfc_copy_expr (e->value.compcall.base_object);
5310   else
5311     {
5312       po = gfc_get_expr ();
5313       po->expr_type = EXPR_VARIABLE;
5314       po->symtree = e->symtree;
5315       po->ref = gfc_copy_ref (e->ref);
5316       po->where = e->where;
5317     }
5318
5319   if (gfc_resolve_expr (po) == FAILURE)
5320     return NULL;
5321
5322   return po;
5323 }
5324
5325
5326 /* Update the arglist of an EXPR_COMPCALL expression to include the
5327    passed-object.  */
5328
5329 static gfc_try
5330 update_compcall_arglist (gfc_expr* e)
5331 {
5332   gfc_expr* po;
5333   gfc_typebound_proc* tbp;
5334
5335   tbp = e->value.compcall.tbp;
5336
5337   if (tbp->error)
5338     return FAILURE;
5339
5340   po = extract_compcall_passed_object (e);
5341   if (!po)
5342     return FAILURE;
5343
5344   if (tbp->nopass || e->value.compcall.ignore_pass)
5345     {
5346       gfc_free_expr (po);
5347       return SUCCESS;
5348     }
5349
5350   gcc_assert (tbp->pass_arg_num > 0);
5351   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5352                                                   tbp->pass_arg_num,
5353                                                   tbp->pass_arg);
5354
5355   return SUCCESS;
5356 }
5357
5358
5359 /* Extract the passed object from a PPC call (a copy of it).  */
5360
5361 static gfc_expr*
5362 extract_ppc_passed_object (gfc_expr *e)
5363 {
5364   gfc_expr *po;
5365   gfc_ref **ref;
5366
5367   po = gfc_get_expr ();
5368   po->expr_type = EXPR_VARIABLE;
5369   po->symtree = e->symtree;
5370   po->ref = gfc_copy_ref (e->ref);
5371   po->where = e->where;
5372
5373   /* Remove PPC reference.  */
5374   ref = &po->ref;
5375   while ((*ref)->next)
5376     ref = &(*ref)->next;
5377   gfc_free_ref_list (*ref);
5378   *ref = NULL;
5379
5380   if (gfc_resolve_expr (po) == FAILURE)
5381     return NULL;
5382
5383   return po;
5384 }
5385
5386
5387 /* Update the actual arglist of a procedure pointer component to include the
5388    passed-object.  */
5389
5390 static gfc_try
5391 update_ppc_arglist (gfc_expr* e)
5392 {
5393   gfc_expr* po;
5394   gfc_component *ppc;
5395   gfc_typebound_proc* tb;
5396
5397   if (!gfc_is_proc_ptr_comp (e, &ppc))
5398     return FAILURE;
5399
5400   tb = ppc->tb;
5401
5402   if (tb->error)
5403     return FAILURE;
5404   else if (tb->nopass)
5405     return SUCCESS;
5406
5407   po = extract_ppc_passed_object (e);
5408   if (!po)
5409     return FAILURE;
5410
5411   if (po->rank > 0)
5412     {
5413       gfc_error ("Passed-object at %L must be scalar", &e->where);
5414       return FAILURE;
5415     }
5416
5417   gcc_assert (tb->pass_arg_num > 0);
5418   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5419                                                   tb->pass_arg_num,
5420                                                   tb->pass_arg);
5421
5422   return SUCCESS;
5423 }
5424
5425
5426 /* Check that the object a TBP is called on is valid, i.e. it must not be
5427    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5428
5429 static gfc_try
5430 check_typebound_baseobject (gfc_expr* e)
5431 {
5432   gfc_expr* base;
5433
5434   base = extract_compcall_passed_object (e);
5435   if (!base)
5436     return FAILURE;
5437
5438   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5439
5440   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5441     {
5442       gfc_error ("Base object for type-bound procedure call at %L is of"
5443                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5444       return FAILURE;
5445     }
5446
5447   /* If the procedure called is NOPASS, the base object must be scalar.  */
5448   if (e->value.compcall.tbp->nopass && base->rank > 0)
5449     {
5450       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5451                  " be scalar", &e->where);
5452       return FAILURE;
5453     }
5454
5455   /* FIXME: Remove once PR 41177 (this problem) is fixed completely.  */
5456   if (base->rank > 0)
5457     {
5458       gfc_error ("Non-scalar base object at %L currently not implemented",
5459                  &e->where);
5460       return FAILURE;
5461     }
5462
5463   return SUCCESS;
5464 }
5465
5466
5467 /* Resolve a call to a type-bound procedure, either function or subroutine,
5468    statically from the data in an EXPR_COMPCALL expression.  The adapted
5469    arglist and the target-procedure symtree are returned.  */
5470
5471 static gfc_try
5472 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5473                           gfc_actual_arglist** actual)
5474 {
5475   gcc_assert (e->expr_type == EXPR_COMPCALL);
5476   gcc_assert (!e->value.compcall.tbp->is_generic);
5477
5478   /* Update the actual arglist for PASS.  */
5479   if (update_compcall_arglist (e) == FAILURE)
5480     return FAILURE;
5481
5482   *actual = e->value.compcall.actual;
5483   *target = e->value.compcall.tbp->u.specific;
5484
5485   gfc_free_ref_list (e->ref);
5486   e->ref = NULL;
5487   e->value.compcall.actual = NULL;
5488
5489   return SUCCESS;
5490 }
5491
5492
5493 /* Get the ultimate declared type from an expression.  In addition,
5494    return the last class/derived type reference and the copy of the
5495    reference list.  */
5496 static gfc_symbol*
5497 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5498                         gfc_expr *e)
5499 {
5500   gfc_symbol *declared;
5501   gfc_ref *ref;
5502
5503   declared = NULL;
5504   if (class_ref)
5505     *class_ref = NULL;
5506   if (new_ref)
5507     *new_ref = gfc_copy_ref (e->ref);
5508
5509   for (ref = e->ref; ref; ref = ref->next)
5510     {
5511       if (ref->type != REF_COMPONENT)
5512         continue;
5513
5514       if (ref->u.c.component->ts.type == BT_CLASS
5515             || ref->u.c.component->ts.type == BT_DERIVED)
5516         {
5517           declared = ref->u.c.component->ts.u.derived;
5518           if (class_ref)
5519             *class_ref = ref;
5520         }
5521     }
5522
5523   if (declared == NULL)
5524     declared = e->symtree->n.sym->ts.u.derived;
5525
5526   return declared;
5527 }
5528
5529
5530 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5531    which of the specific bindings (if any) matches the arglist and transform
5532    the expression into a call of that binding.  */
5533
5534 static gfc_try
5535 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5536 {
5537   gfc_typebound_proc* genproc;
5538   const char* genname;
5539   gfc_symtree *st;
5540   gfc_symbol *derived;
5541
5542   gcc_assert (e->expr_type == EXPR_COMPCALL);
5543   genname = e->value.compcall.name;
5544   genproc = e->value.compcall.tbp;
5545
5546   if (!genproc->is_generic)
5547     return SUCCESS;
5548
5549   /* Try the bindings on this type and in the inheritance hierarchy.  */
5550   for (; genproc; genproc = genproc->overridden)
5551     {
5552       gfc_tbp_generic* g;
5553
5554       gcc_assert (genproc->is_generic);
5555       for (g = genproc->u.generic; g; g = g->next)
5556         {
5557           gfc_symbol* target;
5558           gfc_actual_arglist* args;
5559           bool matches;
5560
5561           gcc_assert (g->specific);
5562
5563           if (g->specific->error)
5564             continue;
5565
5566           target = g->specific->u.specific->n.sym;
5567
5568           /* Get the right arglist by handling PASS/NOPASS.  */
5569           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5570           if (!g->specific->nopass)
5571             {
5572               gfc_expr* po;
5573               po = extract_compcall_passed_object (e);
5574               if (!po)
5575                 return FAILURE;
5576
5577               gcc_assert (g->specific->pass_arg_num > 0);
5578               gcc_assert (!g->specific->error);
5579               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5580                                           g->specific->pass_arg);
5581             }
5582           resolve_actual_arglist (args, target->attr.proc,
5583                                   is_external_proc (target) && !target->formal);
5584
5585           /* Check if this arglist matches the formal.  */
5586           matches = gfc_arglist_matches_symbol (&args, target);
5587
5588           /* Clean up and break out of the loop if we've found it.  */
5589           gfc_free_actual_arglist (args);
5590           if (matches)
5591             {
5592               e->value.compcall.tbp = g->specific;
5593               genname = g->specific_st->name;
5594               /* Pass along the name for CLASS methods, where the vtab
5595                  procedure pointer component has to be referenced.  */
5596               if (name)
5597                 *name = genname;
5598               goto success;
5599             }
5600         }
5601     }
5602
5603   /* Nothing matching found!  */
5604   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5605              " '%s' at %L", genname, &e->where);
5606   return FAILURE;
5607
5608 success:
5609   /* Make sure that we have the right specific instance for the name.  */
5610   derived = get_declared_from_expr (NULL, NULL, e);
5611
5612   st = gfc_find_typebound_proc (derived, NULL, genname, false, &e->where);
5613   if (st)
5614     e->value.compcall.tbp = st->n.tb;
5615
5616   return SUCCESS;
5617 }
5618
5619
5620 /* Resolve a call to a type-bound subroutine.  */
5621
5622 static gfc_try
5623 resolve_typebound_call (gfc_code* c, const char **name)
5624 {
5625   gfc_actual_arglist* newactual;
5626   gfc_symtree* target;
5627
5628   /* Check that's really a SUBROUTINE.  */
5629   if (!c->expr1->value.compcall.tbp->subroutine)
5630     {
5631       gfc_error ("'%s' at %L should be a SUBROUTINE",
5632                  c->expr1->value.compcall.name, &c->loc);
5633       return FAILURE;
5634     }
5635
5636   if (check_typebound_baseobject (c->expr1) == FAILURE)
5637     return FAILURE;
5638
5639   /* Pass along the name for CLASS methods, where the vtab
5640      procedure pointer component has to be referenced.  */
5641   if (name)
5642     *name = c->expr1->value.compcall.name;
5643
5644   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5645     return FAILURE;
5646
5647   /* Transform into an ordinary EXEC_CALL for now.  */
5648
5649   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5650     return FAILURE;
5651
5652   c->ext.actual = newactual;
5653   c->symtree = target;
5654   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5655
5656   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5657
5658   gfc_free_expr (c->expr1);
5659   c->expr1 = gfc_get_expr ();
5660   c->expr1->expr_type = EXPR_FUNCTION;
5661   c->expr1->symtree = target;
5662   c->expr1->where = c->loc;
5663
5664   return resolve_call (c);
5665 }
5666
5667
5668 /* Resolve a component-call expression.  */
5669 static gfc_try
5670 resolve_compcall (gfc_expr* e, const char **name)
5671 {
5672   gfc_actual_arglist* newactual;
5673   gfc_symtree* target;
5674
5675   /* Check that's really a FUNCTION.  */
5676   if (!e->value.compcall.tbp->function)
5677     {
5678       gfc_error ("'%s' at %L should be a FUNCTION",
5679                  e->value.compcall.name, &e->where);
5680       return FAILURE;
5681     }
5682
5683   /* These must not be assign-calls!  */
5684   gcc_assert (!e->value.compcall.assign);
5685
5686   if (check_typebound_baseobject (e) == FAILURE)
5687     return FAILURE;
5688
5689   /* Pass along the name for CLASS methods, where the vtab
5690      procedure pointer component has to be referenced.  */
5691   if (name)
5692     *name = e->value.compcall.name;
5693
5694   if (resolve_typebound_generic_call (e, name) == FAILURE)
5695     return FAILURE;
5696   gcc_assert (!e->value.compcall.tbp->is_generic);
5697
5698   /* Take the rank from the function's symbol.  */
5699   if (e->value.compcall.tbp->u.specific->n.sym->as)
5700     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5701
5702   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5703      arglist to the TBP's binding target.  */
5704
5705   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5706     return FAILURE;
5707
5708   e->value.function.actual = newactual;
5709   e->value.function.name = NULL;
5710   e->value.function.esym = target->n.sym;
5711   e->value.function.isym = NULL;
5712   e->symtree = target;
5713   e->ts = target->n.sym->ts;
5714   e->expr_type = EXPR_FUNCTION;
5715
5716   /* Resolution is not necessary if this is a class subroutine; this
5717      function only has to identify the specific proc. Resolution of
5718      the call will be done next in resolve_typebound_call.  */
5719   return gfc_resolve_expr (e);
5720 }
5721
5722
5723
5724 /* Resolve a typebound function, or 'method'. First separate all
5725    the non-CLASS references by calling resolve_compcall directly.  */
5726
5727 static gfc_try
5728 resolve_typebound_function (gfc_expr* e)
5729 {
5730   gfc_symbol *declared;
5731   gfc_component *c;
5732   gfc_ref *new_ref;
5733   gfc_ref *class_ref;
5734   gfc_symtree *st;
5735   const char *name;
5736   gfc_typespec ts;
5737   gfc_expr *expr;
5738
5739   st = e->symtree;
5740
5741   /* Deal with typebound operators for CLASS objects.  */
5742   expr = e->value.compcall.base_object;
5743   if (expr && expr->symtree->n.sym->ts.type == BT_CLASS
5744         && e->value.compcall.name)
5745     {
5746       /* Since the typebound operators are generic, we have to ensure
5747          that any delays in resolution are corrected and that the vtab
5748          is present.  */
5749       ts = expr->symtree->n.sym->ts;
5750       declared = ts.u.derived;
5751       c = gfc_find_component (declared, "$vptr", true, true);
5752       if (c->ts.u.derived == NULL)
5753         c->ts.u.derived = gfc_find_derived_vtab (declared);
5754
5755       if (resolve_compcall (e, &name) == FAILURE)
5756         return FAILURE;
5757
5758       /* Use the generic name if it is there.  */
5759       name = name ? name : e->value.function.esym->name;
5760       e->symtree = expr->symtree;
5761       expr->symtree->n.sym->ts.u.derived = declared;
5762       gfc_add_component_ref (e, "$vptr");
5763       gfc_add_component_ref (e, name);
5764       e->value.function.esym = NULL;
5765       return SUCCESS;
5766     }
5767
5768   if (st == NULL)
5769     return resolve_compcall (e, NULL);
5770
5771   if (resolve_ref (e) == FAILURE)
5772     return FAILURE;
5773
5774   /* Get the CLASS declared type.  */
5775   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5776
5777   /* Weed out cases of the ultimate component being a derived type.  */
5778   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5779          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5780     {
5781       gfc_free_ref_list (new_ref);
5782       return resolve_compcall (e, NULL);
5783     }
5784
5785   c = gfc_find_component (declared, "$data", true, true);
5786   declared = c->ts.u.derived;
5787
5788   /* Treat the call as if it is a typebound procedure, in order to roll
5789      out the correct name for the specific function.  */
5790   if (resolve_compcall (e, &name) == FAILURE)
5791     return FAILURE;
5792   ts = e->ts;
5793
5794   /* Then convert the expression to a procedure pointer component call.  */
5795   e->value.function.esym = NULL;
5796   e->symtree = st;
5797
5798   if (new_ref)  
5799     e->ref = new_ref;
5800
5801   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5802   gfc_add_component_ref (e, "$vptr");
5803   gfc_add_component_ref (e, name);
5804
5805   /* Recover the typespec for the expression.  This is really only
5806      necessary for generic procedures, where the additional call
5807      to gfc_add_component_ref seems to throw the collection of the
5808      correct typespec.  */
5809   e->ts = ts;
5810   return SUCCESS;
5811 }
5812
5813 /* Resolve a typebound subroutine, or 'method'. First separate all
5814    the non-CLASS references by calling resolve_typebound_call
5815    directly.  */
5816
5817 static gfc_try
5818 resolve_typebound_subroutine (gfc_code *code)
5819 {
5820   gfc_symbol *declared;
5821   gfc_component *c;
5822   gfc_ref *new_ref;
5823   gfc_ref *class_ref;
5824   gfc_symtree *st;
5825   const char *name;
5826   gfc_typespec ts;
5827   gfc_expr *expr;
5828
5829   st = code->expr1->symtree;
5830
5831   /* Deal with typebound operators for CLASS objects.  */
5832   expr = code->expr1->value.compcall.base_object;
5833   if (expr && expr->symtree->n.sym->ts.type == BT_CLASS
5834         && code->expr1->value.compcall.name)
5835     {
5836       /* Since the typebound operators are generic, we have to ensure
5837          that any delays in resolution are corrected and that the vtab
5838          is present.  */
5839       ts = expr->symtree->n.sym->ts;
5840       declared = ts.u.derived;
5841       c = gfc_find_component (declared, "$vptr", true, true);
5842       if (c->ts.u.derived == NULL)
5843         c->ts.u.derived = gfc_find_derived_vtab (declared);
5844
5845       if (resolve_typebound_call (code, &name) == FAILURE)
5846         return FAILURE;
5847
5848       /* Use the generic name if it is there.  */
5849       name = name ? name : code->expr1->value.function.esym->name;
5850       code->expr1->symtree = expr->symtree;
5851       expr->symtree->n.sym->ts.u.derived = declared;
5852       gfc_add_component_ref (code->expr1, "$vptr");
5853       gfc_add_component_ref (code->expr1, name);
5854       code->expr1->value.function.esym = NULL;
5855       return SUCCESS;
5856     }
5857
5858   if (st == NULL)
5859     return resolve_typebound_call (code, NULL);
5860
5861   if (resolve_ref (code->expr1) == FAILURE)
5862     return FAILURE;
5863
5864   /* Get the CLASS declared type.  */
5865   get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5866
5867   /* Weed out cases of the ultimate component being a derived type.  */
5868   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5869          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5870     {
5871       gfc_free_ref_list (new_ref);
5872       return resolve_typebound_call (code, NULL);
5873     }
5874
5875   if (resolve_typebound_call (code, &name) == FAILURE)
5876     return FAILURE;
5877   ts = code->expr1->ts;
5878
5879   /* Then convert the expression to a procedure pointer component call.  */
5880   code->expr1->value.function.esym = NULL;
5881   code->expr1->symtree = st;
5882
5883   if (new_ref)
5884     code->expr1->ref = new_ref;
5885
5886   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5887   gfc_add_component_ref (code->expr1, "$vptr");
5888   gfc_add_component_ref (code->expr1, name);
5889
5890   /* Recover the typespec for the expression.  This is really only
5891      necessary for generic procedures, where the additional call
5892      to gfc_add_component_ref seems to throw the collection of the
5893      correct typespec.  */
5894   code->expr1->ts = ts;
5895   return SUCCESS;
5896 }
5897
5898
5899 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5900
5901 static gfc_try
5902 resolve_ppc_call (gfc_code* c)
5903 {
5904   gfc_component *comp;
5905   bool b;
5906
5907   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5908   gcc_assert (b);
5909
5910   c->resolved_sym = c->expr1->symtree->n.sym;
5911   c->expr1->expr_type = EXPR_VARIABLE;
5912
5913   if (!comp->attr.subroutine)
5914     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5915
5916   if (resolve_ref (c->expr1) == FAILURE)
5917     return FAILURE;
5918
5919   if (update_ppc_arglist (c->expr1) == FAILURE)
5920     return FAILURE;
5921
5922   c->ext.actual = c->expr1->value.compcall.actual;
5923
5924   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5925                               comp->formal == NULL) == FAILURE)
5926     return FAILURE;
5927
5928   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5929
5930   return SUCCESS;
5931 }
5932
5933
5934 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5935
5936 static gfc_try
5937 resolve_expr_ppc (gfc_expr* e)
5938 {
5939   gfc_component *comp;
5940   bool b;
5941
5942   b = gfc_is_proc_ptr_comp (e, &comp);
5943   gcc_assert (b);
5944
5945   /* Convert to EXPR_FUNCTION.  */
5946   e->expr_type = EXPR_FUNCTION;
5947   e->value.function.isym = NULL;
5948   e->value.function.actual = e->value.compcall.actual;
5949   e->ts = comp->ts;
5950   if (comp->as != NULL)
5951     e->rank = comp->as->rank;
5952
5953   if (!comp->attr.function)
5954     gfc_add_function (&comp->attr, comp->name, &e->where);
5955
5956   if (resolve_ref (e) == FAILURE)
5957     return FAILURE;
5958
5959   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
5960                               comp->formal == NULL) == FAILURE)
5961     return FAILURE;
5962
5963   if (update_ppc_arglist (e) == FAILURE)
5964     return FAILURE;
5965
5966   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
5967
5968   return SUCCESS;
5969 }
5970
5971
5972 static bool
5973 gfc_is_expandable_expr (gfc_expr *e)
5974 {
5975   gfc_constructor *con;
5976
5977   if (e->expr_type == EXPR_ARRAY)
5978     {
5979       /* Traverse the constructor looking for variables that are flavor
5980          parameter.  Parameters must be expanded since they are fully used at
5981          compile time.  */
5982       con = gfc_constructor_first (e->value.constructor);
5983       for (; con; con = gfc_constructor_next (con))
5984         {
5985           if (con->expr->expr_type == EXPR_VARIABLE
5986               && con->expr->symtree
5987               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
5988               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
5989             return true;
5990           if (con->expr->expr_type == EXPR_ARRAY
5991               && gfc_is_expandable_expr (con->expr))
5992             return true;
5993         }
5994     }
5995
5996   return false;
5997 }
5998
5999 /* Resolve an expression.  That is, make sure that types of operands agree
6000    with their operators, intrinsic operators are converted to function calls
6001    for overloaded types and unresolved function references are resolved.  */
6002
6003 gfc_try
6004 gfc_resolve_expr (gfc_expr *e)
6005 {
6006   gfc_try t;
6007   bool inquiry_save;
6008
6009   if (e == NULL)
6010     return SUCCESS;
6011
6012   /* inquiry_argument only applies to variables.  */
6013   inquiry_save = inquiry_argument;
6014   if (e->expr_type != EXPR_VARIABLE)
6015     inquiry_argument = false;
6016
6017   switch (e->expr_type)
6018     {
6019     case EXPR_OP:
6020       t = resolve_operator (e);
6021       break;
6022
6023     case EXPR_FUNCTION:
6024     case EXPR_VARIABLE:
6025
6026       if (check_host_association (e))
6027         t = resolve_function (e);
6028       else
6029         {
6030           t = resolve_variable (e);
6031           if (t == SUCCESS)
6032             expression_rank (e);
6033         }
6034
6035       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6036           && e->ref->type != REF_SUBSTRING)
6037         gfc_resolve_substring_charlen (e);
6038
6039       break;
6040
6041     case EXPR_COMPCALL:
6042       t = resolve_typebound_function (e);
6043       break;
6044
6045     case EXPR_SUBSTRING:
6046       t = resolve_ref (e);
6047       break;
6048
6049     case EXPR_CONSTANT:
6050     case EXPR_NULL:
6051       t = SUCCESS;
6052       break;
6053
6054     case EXPR_PPC:
6055       t = resolve_expr_ppc (e);
6056       break;
6057
6058     case EXPR_ARRAY:
6059       t = FAILURE;
6060       if (resolve_ref (e) == FAILURE)
6061         break;
6062
6063       t = gfc_resolve_array_constructor (e);
6064       /* Also try to expand a constructor.  */
6065       if (t == SUCCESS)
6066         {
6067           expression_rank (e);
6068           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6069             gfc_expand_constructor (e, false);
6070         }
6071
6072       /* This provides the opportunity for the length of constructors with
6073          character valued function elements to propagate the string length
6074          to the expression.  */
6075       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6076         {
6077           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6078              here rather then add a duplicate test for it above.  */ 
6079           gfc_expand_constructor (e, false);
6080           t = gfc_resolve_character_array_constructor (e);
6081         }
6082
6083       break;
6084
6085     case EXPR_STRUCTURE:
6086       t = resolve_ref (e);
6087       if (t == FAILURE)
6088         break;
6089
6090       t = resolve_structure_cons (e, 0);
6091       if (t == FAILURE)
6092         break;
6093
6094       t = gfc_simplify_expr (e, 0);
6095       break;
6096
6097     default:
6098       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6099     }
6100
6101   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6102     fixup_charlen (e);
6103
6104   inquiry_argument = inquiry_save;
6105
6106   return t;
6107 }
6108
6109
6110 /* Resolve an expression from an iterator.  They must be scalar and have
6111    INTEGER or (optionally) REAL type.  */
6112
6113 static gfc_try
6114 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6115                            const char *name_msgid)
6116 {
6117   if (gfc_resolve_expr (expr) == FAILURE)
6118     return FAILURE;
6119
6120   if (expr->rank != 0)
6121     {
6122       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6123       return FAILURE;
6124     }
6125
6126   if (expr->ts.type != BT_INTEGER)
6127     {
6128       if (expr->ts.type == BT_REAL)
6129         {
6130           if (real_ok)
6131             return gfc_notify_std (GFC_STD_F95_DEL,
6132                                    "Deleted feature: %s at %L must be integer",
6133                                    _(name_msgid), &expr->where);
6134           else
6135             {
6136               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6137                          &expr->where);
6138               return FAILURE;
6139             }
6140         }
6141       else
6142         {
6143           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6144           return FAILURE;
6145         }
6146     }
6147   return SUCCESS;
6148 }
6149
6150
6151 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6152    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6153
6154 gfc_try
6155 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6156 {
6157   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6158       == FAILURE)
6159     return FAILURE;
6160
6161   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
6162     {
6163       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
6164                  &iter->var->where);
6165       return FAILURE;
6166     }
6167
6168   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6169                                  "Start expression in DO loop") == FAILURE)
6170     return FAILURE;
6171
6172   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6173                                  "End expression in DO loop") == FAILURE)
6174     return FAILURE;
6175
6176   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6177                                  "Step expression in DO loop") == FAILURE)
6178     return FAILURE;
6179
6180   if (iter->step->expr_type == EXPR_CONSTANT)
6181     {
6182       if ((iter->step->ts.type == BT_INTEGER
6183            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6184           || (iter->step->ts.type == BT_REAL
6185               && mpfr_sgn (iter->step->value.real) == 0))
6186         {
6187           gfc_error ("Step expression in DO loop at %L cannot be zero",
6188                      &iter->step->where);
6189           return FAILURE;
6190         }
6191     }
6192
6193   /* Convert start, end, and step to the same type as var.  */
6194   if (iter->start->ts.kind != iter->var->ts.kind
6195       || iter->start->ts.type != iter->var->ts.type)
6196     gfc_convert_type (iter->start, &iter->var->ts, 2);
6197
6198   if (iter->end->ts.kind != iter->var->ts.kind
6199       || iter->end->ts.type != iter->var->ts.type)
6200     gfc_convert_type (iter->end, &iter->var->ts, 2);
6201
6202   if (iter->step->ts.kind != iter->var->ts.kind
6203       || iter->step->ts.type != iter->var->ts.type)
6204     gfc_convert_type (iter->step, &iter->var->ts, 2);
6205
6206   if (iter->start->expr_type == EXPR_CONSTANT
6207       && iter->end->expr_type == EXPR_CONSTANT
6208       && iter->step->expr_type == EXPR_CONSTANT)
6209     {
6210       int sgn, cmp;
6211       if (iter->start->ts.type == BT_INTEGER)
6212         {
6213           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6214           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6215         }
6216       else
6217         {
6218           sgn = mpfr_sgn (iter->step->value.real);
6219           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6220         }
6221       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6222         gfc_warning ("DO loop at %L will be executed zero times",
6223                      &iter->step->where);
6224     }
6225
6226   return SUCCESS;
6227 }
6228
6229
6230 /* Traversal function for find_forall_index.  f == 2 signals that
6231    that variable itself is not to be checked - only the references.  */
6232
6233 static bool
6234 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6235 {
6236   if (expr->expr_type != EXPR_VARIABLE)
6237     return false;
6238   
6239   /* A scalar assignment  */
6240   if (!expr->ref || *f == 1)
6241     {
6242       if (expr->symtree->n.sym == sym)
6243         return true;
6244       else
6245         return false;
6246     }
6247
6248   if (*f == 2)
6249     *f = 1;
6250   return false;
6251 }
6252
6253
6254 /* Check whether the FORALL index appears in the expression or not.
6255    Returns SUCCESS if SYM is found in EXPR.  */
6256
6257 gfc_try
6258 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6259 {
6260   if (gfc_traverse_expr (expr, sym, forall_index, f))
6261     return SUCCESS;
6262   else
6263     return FAILURE;
6264 }
6265
6266
6267 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6268    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6269    INTEGERs, and if stride is a constant it must be nonzero.
6270    Furthermore "A subscript or stride in a forall-triplet-spec shall
6271    not contain a reference to any index-name in the
6272    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6273
6274 static void
6275 resolve_forall_iterators (gfc_forall_iterator *it)
6276 {
6277   gfc_forall_iterator *iter, *iter2;
6278
6279   for (iter = it; iter; iter = iter->next)
6280     {
6281       if (gfc_resolve_expr (iter->var) == SUCCESS
6282           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6283         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6284                    &iter->var->where);
6285
6286       if (gfc_resolve_expr (iter->start) == SUCCESS
6287           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6288         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6289                    &iter->start->where);
6290       if (iter->var->ts.kind != iter->start->ts.kind)
6291         gfc_convert_type (iter->start, &iter->var->ts, 2);
6292
6293       if (gfc_resolve_expr (iter->end) == SUCCESS
6294           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6295         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6296                    &iter->end->where);
6297       if (iter->var->ts.kind != iter->end->ts.kind)
6298         gfc_convert_type (iter->end, &iter->var->ts, 2);
6299
6300       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6301         {
6302           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6303             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6304                        &iter->stride->where, "INTEGER");
6305
6306           if (iter->stride->expr_type == EXPR_CONSTANT
6307               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6308             gfc_error ("FORALL stride expression at %L cannot be zero",
6309                        &iter->stride->where);
6310         }
6311       if (iter->var->ts.kind != iter->stride->ts.kind)
6312         gfc_convert_type (iter->stride, &iter->var->ts, 2);
6313     }
6314
6315   for (iter = it; iter; iter = iter->next)
6316     for (iter2 = iter; iter2; iter2 = iter2->next)
6317       {
6318         if (find_forall_index (iter2->start,
6319                                iter->var->symtree->n.sym, 0) == SUCCESS
6320             || find_forall_index (iter2->end,
6321                                   iter->var->symtree->n.sym, 0) == SUCCESS
6322             || find_forall_index (iter2->stride,
6323                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6324           gfc_error ("FORALL index '%s' may not appear in triplet "
6325                      "specification at %L", iter->var->symtree->name,
6326                      &iter2->start->where);
6327       }
6328 }
6329
6330
6331 /* Given a pointer to a symbol that is a derived type, see if it's
6332    inaccessible, i.e. if it's defined in another module and the components are
6333    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6334    inaccessible components are found, nonzero otherwise.  */
6335
6336 static int
6337 derived_inaccessible (gfc_symbol *sym)
6338 {
6339   gfc_component *c;
6340
6341   if (sym->attr.use_assoc && sym->attr.private_comp)
6342     return 1;
6343
6344   for (c = sym->components; c; c = c->next)
6345     {
6346         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6347           return 1;
6348     }
6349
6350   return 0;
6351 }
6352
6353
6354 /* Resolve the argument of a deallocate expression.  The expression must be
6355    a pointer or a full array.  */
6356
6357 static gfc_try
6358 resolve_deallocate_expr (gfc_expr *e)
6359 {
6360   symbol_attribute attr;
6361   int allocatable, pointer, check_intent_in;
6362   gfc_ref *ref;
6363   gfc_symbol *sym;
6364   gfc_component *c;
6365
6366   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6367   check_intent_in = 1;
6368
6369   if (gfc_resolve_expr (e) == FAILURE)
6370     return FAILURE;
6371
6372   if (e->expr_type != EXPR_VARIABLE)
6373     goto bad;
6374
6375   sym = e->symtree->n.sym;
6376
6377   if (sym->ts.type == BT_CLASS)
6378     {
6379       allocatable = CLASS_DATA (sym)->attr.allocatable;
6380       pointer = CLASS_DATA (sym)->attr.class_pointer;
6381     }
6382   else
6383     {
6384       allocatable = sym->attr.allocatable;
6385       pointer = sym->attr.pointer;
6386     }
6387   for (ref = e->ref; ref; ref = ref->next)
6388     {
6389       if (pointer)
6390         check_intent_in = 0;
6391
6392       switch (ref->type)
6393         {
6394         case REF_ARRAY:
6395           if (ref->u.ar.type != AR_FULL)
6396             allocatable = 0;
6397           break;
6398
6399         case REF_COMPONENT:
6400           c = ref->u.c.component;
6401           if (c->ts.type == BT_CLASS)
6402             {
6403               allocatable = CLASS_DATA (c)->attr.allocatable;
6404               pointer = CLASS_DATA (c)->attr.class_pointer;
6405             }
6406           else
6407             {
6408               allocatable = c->attr.allocatable;
6409               pointer = c->attr.pointer;
6410             }
6411           break;
6412
6413         case REF_SUBSTRING:
6414           allocatable = 0;
6415           break;
6416         }
6417     }
6418
6419   attr = gfc_expr_attr (e);
6420
6421   if (allocatable == 0 && attr.pointer == 0)
6422     {
6423     bad:
6424       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6425                  &e->where);
6426       return FAILURE;
6427     }
6428
6429   if (check_intent_in && sym->attr.intent == INTENT_IN)
6430     {
6431       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
6432                  sym->name, &e->where);
6433       return FAILURE;
6434     }
6435
6436   if (e->ts.type == BT_CLASS)
6437     {
6438       /* Only deallocate the DATA component.  */
6439       gfc_add_component_ref (e, "$data");
6440     }
6441
6442   return SUCCESS;
6443 }
6444
6445
6446 /* Returns true if the expression e contains a reference to the symbol sym.  */
6447 static bool
6448 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6449 {
6450   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6451     return true;
6452
6453   return false;
6454 }
6455
6456 bool
6457 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6458 {
6459   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6460 }
6461
6462
6463 /* Given the expression node e for an allocatable/pointer of derived type to be
6464    allocated, get the expression node to be initialized afterwards (needed for
6465    derived types with default initializers, and derived types with allocatable
6466    components that need nullification.)  */
6467
6468 gfc_expr *
6469 gfc_expr_to_initialize (gfc_expr *e)
6470 {
6471   gfc_expr *result;
6472   gfc_ref *ref;
6473   int i;
6474
6475   result = gfc_copy_expr (e);
6476
6477   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6478   for (ref = result->ref; ref; ref = ref->next)
6479     if (ref->type == REF_ARRAY && ref->next == NULL)
6480       {
6481         ref->u.ar.type = AR_FULL;
6482
6483         for (i = 0; i < ref->u.ar.dimen; i++)
6484           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6485
6486         result->rank = ref->u.ar.dimen;
6487         break;
6488       }
6489
6490   return result;
6491 }
6492
6493
6494 /* Used in resolve_allocate_expr to check that a allocation-object and
6495    a source-expr are conformable.  This does not catch all possible 
6496    cases; in particular a runtime checking is needed.  */
6497
6498 static gfc_try
6499 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6500 {
6501   gfc_ref *tail;
6502   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6503   
6504   /* First compare rank.  */
6505   if (tail && e1->rank != tail->u.ar.as->rank)
6506     {
6507       gfc_error ("Source-expr at %L must be scalar or have the "
6508                  "same rank as the allocate-object at %L",
6509                  &e1->where, &e2->where);
6510       return FAILURE;
6511     }
6512
6513   if (e1->shape)
6514     {
6515       int i;
6516       mpz_t s;
6517
6518       mpz_init (s);
6519
6520       for (i = 0; i < e1->rank; i++)
6521         {
6522           if (tail->u.ar.end[i])
6523             {
6524               mpz_set (s, tail->u.ar.end[i]->value.integer);
6525               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6526               mpz_add_ui (s, s, 1);
6527             }
6528           else
6529             {
6530               mpz_set (s, tail->u.ar.start[i]->value.integer);
6531             }
6532
6533           if (mpz_cmp (e1->shape[i], s) != 0)
6534             {
6535               gfc_error ("Source-expr at %L and allocate-object at %L must "
6536                          "have the same shape", &e1->where, &e2->where);
6537               mpz_clear (s);
6538               return FAILURE;
6539             }
6540         }
6541
6542       mpz_clear (s);
6543     }
6544
6545   return SUCCESS;
6546 }
6547
6548
6549 /* Resolve the expression in an ALLOCATE statement, doing the additional
6550    checks to see whether the expression is OK or not.  The expression must
6551    have a trailing array reference that gives the size of the array.  */
6552
6553 static gfc_try
6554 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6555 {
6556   int i, pointer, allocatable, dimension, check_intent_in, is_abstract;
6557   int codimension;
6558   symbol_attribute attr;
6559   gfc_ref *ref, *ref2;
6560   gfc_array_ref *ar;
6561   gfc_symbol *sym = NULL;
6562   gfc_alloc *a;
6563   gfc_component *c;
6564
6565   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6566   check_intent_in = 1;
6567
6568   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6569      checking of coarrays.  */
6570   for (ref = e->ref; ref; ref = ref->next)
6571     if (ref->next == NULL)
6572       break;
6573
6574   if (ref && ref->type == REF_ARRAY)
6575     ref->u.ar.in_allocate = true;
6576
6577   if (gfc_resolve_expr (e) == FAILURE)
6578     goto failure;
6579
6580   /* Make sure the expression is allocatable or a pointer.  If it is
6581      pointer, the next-to-last reference must be a pointer.  */
6582
6583   ref2 = NULL;
6584   if (e->symtree)
6585     sym = e->symtree->n.sym;
6586
6587   /* Check whether ultimate component is abstract and CLASS.  */
6588   is_abstract = 0;
6589
6590   if (e->expr_type != EXPR_VARIABLE)
6591     {
6592       allocatable = 0;
6593       attr = gfc_expr_attr (e);
6594       pointer = attr.pointer;
6595       dimension = attr.dimension;
6596       codimension = attr.codimension;
6597     }
6598   else
6599     {
6600       if (sym->ts.type == BT_CLASS)
6601         {
6602           allocatable = CLASS_DATA (sym)->attr.allocatable;
6603           pointer = CLASS_DATA (sym)->attr.class_pointer;
6604           dimension = CLASS_DATA (sym)->attr.dimension;
6605           codimension = CLASS_DATA (sym)->attr.codimension;
6606           is_abstract = CLASS_DATA (sym)->attr.abstract;
6607         }
6608       else
6609         {
6610           allocatable = sym->attr.allocatable;
6611           pointer = sym->attr.pointer;
6612           dimension = sym->attr.dimension;
6613           codimension = sym->attr.codimension;
6614         }
6615
6616       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6617         {
6618           if (pointer)
6619             check_intent_in = 0;
6620
6621           switch (ref->type)
6622             {
6623               case REF_ARRAY:
6624                 if (ref->next != NULL)
6625                   pointer = 0;
6626                 break;
6627
6628               case REF_COMPONENT:
6629                 /* F2008, C644.  */
6630                 if (gfc_is_coindexed (e))
6631                   {
6632                     gfc_error ("Coindexed allocatable object at %L",
6633                                &e->where);
6634                     goto failure;
6635                   }
6636
6637                 c = ref->u.c.component;
6638                 if (c->ts.type == BT_CLASS)
6639                   {
6640                     allocatable = CLASS_DATA (c)->attr.allocatable;
6641                     pointer = CLASS_DATA (c)->attr.class_pointer;
6642                     dimension = CLASS_DATA (c)->attr.dimension;
6643                     codimension = CLASS_DATA (c)->attr.codimension;
6644                     is_abstract = CLASS_DATA (c)->attr.abstract;
6645                   }
6646                 else
6647                   {
6648                     allocatable = c->attr.allocatable;
6649                     pointer = c->attr.pointer;
6650                     dimension = c->attr.dimension;
6651                     codimension = c->attr.codimension;
6652                     is_abstract = c->attr.abstract;
6653                   }
6654                 break;
6655
6656               case REF_SUBSTRING:
6657                 allocatable = 0;
6658                 pointer = 0;
6659                 break;
6660             }
6661         }
6662     }
6663
6664   if (allocatable == 0 && pointer == 0)
6665     {
6666       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6667                  &e->where);
6668       goto failure;
6669     }
6670
6671   /* Some checks for the SOURCE tag.  */
6672   if (code->expr3)
6673     {
6674       /* Check F03:C631.  */
6675       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6676         {
6677           gfc_error ("Type of entity at %L is type incompatible with "
6678                       "source-expr at %L", &e->where, &code->expr3->where);
6679           goto failure;
6680         }
6681
6682       /* Check F03:C632 and restriction following Note 6.18.  */
6683       if (code->expr3->rank > 0
6684           && conformable_arrays (code->expr3, e) == FAILURE)
6685         goto failure;
6686
6687       /* Check F03:C633.  */
6688       if (code->expr3->ts.kind != e->ts.kind)
6689         {
6690           gfc_error ("The allocate-object at %L and the source-expr at %L "
6691                       "shall have the same kind type parameter",
6692                       &e->where, &code->expr3->where);
6693           goto failure;
6694         }
6695     }
6696
6697   /* Check F08:C629.  */
6698   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6699       && !code->expr3)
6700     {
6701       gcc_assert (e->ts.type == BT_CLASS);
6702       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6703                  "type-spec or source-expr", sym->name, &e->where);
6704       goto failure;
6705     }
6706
6707   if (check_intent_in && sym->attr.intent == INTENT_IN)
6708     {
6709       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
6710                  sym->name, &e->where);
6711       goto failure;
6712     }
6713     
6714   if (!code->expr3 || code->expr3->mold)
6715     {
6716       /* Add default initializer for those derived types that need them.  */
6717       gfc_expr *init_e = NULL;
6718       gfc_typespec ts;
6719
6720       if (code->ext.alloc.ts.type == BT_DERIVED)
6721         ts = code->ext.alloc.ts;
6722       else if (code->expr3)
6723         ts = code->expr3->ts;
6724       else
6725         ts = e->ts;
6726
6727       if (ts.type == BT_DERIVED)
6728         init_e = gfc_default_initializer (&ts);
6729       /* FIXME: Use default init of dynamic type (cf. PR 44541).  */
6730       else if (e->ts.type == BT_CLASS)
6731         init_e = gfc_default_initializer (&ts.u.derived->components->ts);
6732
6733       if (init_e)
6734         {
6735           gfc_code *init_st = gfc_get_code ();
6736           init_st->loc = code->loc;
6737           init_st->op = EXEC_INIT_ASSIGN;
6738           init_st->expr1 = gfc_expr_to_initialize (e);
6739           init_st->expr2 = init_e;
6740           init_st->next = code->next;
6741           code->next = init_st;
6742         }
6743     }
6744
6745   if (e->ts.type == BT_CLASS)
6746     {
6747       /* Make sure the vtab symbol is present when
6748          the module variables are generated.  */
6749       gfc_typespec ts = e->ts;
6750       if (code->expr3)
6751         ts = code->expr3->ts;
6752       else if (code->ext.alloc.ts.type == BT_DERIVED)
6753         ts = code->ext.alloc.ts;
6754       gfc_find_derived_vtab (ts.u.derived);
6755     }
6756
6757   if (pointer || (dimension == 0 && codimension == 0))
6758     goto success;
6759
6760   /* Make sure the next-to-last reference node is an array specification.  */
6761
6762   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6763       || (dimension && ref2->u.ar.dimen == 0))
6764     {
6765       gfc_error ("Array specification required in ALLOCATE statement "
6766                  "at %L", &e->where);
6767       goto failure;
6768     }
6769
6770   /* Make sure that the array section reference makes sense in the
6771     context of an ALLOCATE specification.  */
6772
6773   ar = &ref2->u.ar;
6774
6775   if (codimension && ar->codimen == 0)
6776     {
6777       gfc_error ("Coarray specification required in ALLOCATE statement "
6778                  "at %L", &e->where);
6779       goto failure;
6780     }
6781
6782   for (i = 0; i < ar->dimen; i++)
6783     {
6784       if (ref2->u.ar.type == AR_ELEMENT)
6785         goto check_symbols;
6786
6787       switch (ar->dimen_type[i])
6788         {
6789         case DIMEN_ELEMENT:
6790           break;
6791
6792         case DIMEN_RANGE:
6793           if (ar->start[i] != NULL
6794               && ar->end[i] != NULL
6795               && ar->stride[i] == NULL)
6796             break;
6797
6798           /* Fall Through...  */
6799
6800         case DIMEN_UNKNOWN:
6801         case DIMEN_VECTOR:
6802         case DIMEN_STAR:
6803           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6804                      &e->where);
6805           goto failure;
6806         }
6807
6808 check_symbols:
6809       for (a = code->ext.alloc.list; a; a = a->next)
6810         {
6811           sym = a->expr->symtree->n.sym;
6812
6813           /* TODO - check derived type components.  */
6814           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6815             continue;
6816
6817           if ((ar->start[i] != NULL
6818                && gfc_find_sym_in_expr (sym, ar->start[i]))
6819               || (ar->end[i] != NULL
6820                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6821             {
6822               gfc_error ("'%s' must not appear in the array specification at "
6823                          "%L in the same ALLOCATE statement where it is "
6824                          "itself allocated", sym->name, &ar->where);
6825               goto failure;
6826             }
6827         }
6828     }
6829
6830   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6831     {
6832       if (ar->dimen_type[i] == DIMEN_ELEMENT
6833           || ar->dimen_type[i] == DIMEN_RANGE)
6834         {
6835           if (i == (ar->dimen + ar->codimen - 1))
6836             {
6837               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6838                          "statement at %L", &e->where);
6839               goto failure;
6840             }
6841           break;
6842         }
6843
6844       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6845           && ar->stride[i] == NULL)
6846         break;
6847
6848       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6849                  &e->where);
6850       goto failure;
6851     }
6852
6853   if (codimension && ar->as->rank == 0)
6854     {
6855       gfc_error ("Sorry, allocatable scalar coarrays are not yet supported "
6856                  "at %L", &e->where);
6857       goto failure;
6858     }
6859
6860 success:
6861   return SUCCESS;
6862
6863 failure:
6864   return FAILURE;
6865 }
6866
6867 static void
6868 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6869 {
6870   gfc_expr *stat, *errmsg, *pe, *qe;
6871   gfc_alloc *a, *p, *q;
6872
6873   stat = code->expr1 ? code->expr1 : NULL;
6874
6875   errmsg = code->expr2 ? code->expr2 : NULL;
6876
6877   /* Check the stat variable.  */
6878   if (stat)
6879     {
6880       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
6881         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
6882                    stat->symtree->n.sym->name, &stat->where);
6883
6884       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
6885         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
6886                    &stat->where);
6887
6888       if ((stat->ts.type != BT_INTEGER
6889            && !(stat->ref && (stat->ref->type == REF_ARRAY
6890                               || stat->ref->type == REF_COMPONENT)))
6891           || stat->rank > 0)
6892         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6893                    "variable", &stat->where);
6894
6895       for (p = code->ext.alloc.list; p; p = p->next)
6896         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6897           {
6898             gfc_ref *ref1, *ref2;
6899             bool found = true;
6900
6901             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
6902                  ref1 = ref1->next, ref2 = ref2->next)
6903               {
6904                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
6905                   continue;
6906                 if (ref1->u.c.component->name != ref2->u.c.component->name)
6907                   {
6908                     found = false;
6909                     break;
6910                   }
6911               }
6912
6913             if (found)
6914               {
6915                 gfc_error ("Stat-variable at %L shall not be %sd within "
6916                            "the same %s statement", &stat->where, fcn, fcn);
6917                 break;
6918               }
6919           }
6920     }
6921
6922   /* Check the errmsg variable.  */
6923   if (errmsg)
6924     {
6925       if (!stat)
6926         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6927                      &errmsg->where);
6928
6929       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
6930         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
6931                    errmsg->symtree->n.sym->name, &errmsg->where);
6932
6933       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
6934         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
6935                    &errmsg->where);
6936
6937       if ((errmsg->ts.type != BT_CHARACTER
6938            && !(errmsg->ref
6939                 && (errmsg->ref->type == REF_ARRAY
6940                     || errmsg->ref->type == REF_COMPONENT)))
6941           || errmsg->rank > 0 )
6942         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6943                    "variable", &errmsg->where);
6944
6945       for (p = code->ext.alloc.list; p; p = p->next)
6946         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6947           {
6948             gfc_ref *ref1, *ref2;
6949             bool found = true;
6950
6951             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
6952                  ref1 = ref1->next, ref2 = ref2->next)
6953               {
6954                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
6955                   continue;
6956                 if (ref1->u.c.component->name != ref2->u.c.component->name)
6957                   {
6958                     found = false;
6959                     break;
6960                   }
6961               }
6962
6963             if (found)
6964               {
6965                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
6966                            "the same %s statement", &errmsg->where, fcn, fcn);
6967                 break;
6968               }
6969           }
6970     }
6971
6972   /* Check that an allocate-object appears only once in the statement.  
6973      FIXME: Checking derived types is disabled.  */
6974   for (p = code->ext.alloc.list; p; p = p->next)
6975     {
6976       pe = p->expr;
6977       if ((pe->ref && pe->ref->type != REF_COMPONENT)
6978            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
6979         {
6980           for (q = p->next; q; q = q->next)
6981             {
6982               qe = q->expr;
6983               if ((qe->ref && qe->ref->type != REF_COMPONENT)
6984                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
6985                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
6986                 gfc_error ("Allocate-object at %L also appears at %L",
6987                            &pe->where, &qe->where);
6988             }
6989         }
6990     }
6991
6992   if (strcmp (fcn, "ALLOCATE") == 0)
6993     {
6994       for (a = code->ext.alloc.list; a; a = a->next)
6995         resolve_allocate_expr (a->expr, code);
6996     }
6997   else
6998     {
6999       for (a = code->ext.alloc.list; a; a = a->next)
7000         resolve_deallocate_expr (a->expr);
7001     }
7002 }
7003
7004
7005 /************ SELECT CASE resolution subroutines ************/
7006
7007 /* Callback function for our mergesort variant.  Determines interval
7008    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7009    op1 > op2.  Assumes we're not dealing with the default case.  
7010    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7011    There are nine situations to check.  */
7012
7013 static int
7014 compare_cases (const gfc_case *op1, const gfc_case *op2)
7015 {
7016   int retval;
7017
7018   if (op1->low == NULL) /* op1 = (:L)  */
7019     {
7020       /* op2 = (:N), so overlap.  */
7021       retval = 0;
7022       /* op2 = (M:) or (M:N),  L < M  */
7023       if (op2->low != NULL
7024           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7025         retval = -1;
7026     }
7027   else if (op1->high == NULL) /* op1 = (K:)  */
7028     {
7029       /* op2 = (M:), so overlap.  */
7030       retval = 0;
7031       /* op2 = (:N) or (M:N), K > N  */
7032       if (op2->high != NULL
7033           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7034         retval = 1;
7035     }
7036   else /* op1 = (K:L)  */
7037     {
7038       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7039         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7040                  ? 1 : 0;
7041       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7042         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7043                  ? -1 : 0;
7044       else                      /* op2 = (M:N)  */
7045         {
7046           retval =  0;
7047           /* L < M  */
7048           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7049             retval =  -1;
7050           /* K > N  */
7051           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7052             retval =  1;
7053         }
7054     }
7055
7056   return retval;
7057 }
7058
7059
7060 /* Merge-sort a double linked case list, detecting overlap in the
7061    process.  LIST is the head of the double linked case list before it
7062    is sorted.  Returns the head of the sorted list if we don't see any
7063    overlap, or NULL otherwise.  */
7064
7065 static gfc_case *
7066 check_case_overlap (gfc_case *list)
7067 {
7068   gfc_case *p, *q, *e, *tail;
7069   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7070
7071   /* If the passed list was empty, return immediately.  */
7072   if (!list)
7073     return NULL;
7074
7075   overlap_seen = 0;
7076   insize = 1;
7077
7078   /* Loop unconditionally.  The only exit from this loop is a return
7079      statement, when we've finished sorting the case list.  */
7080   for (;;)
7081     {
7082       p = list;
7083       list = NULL;
7084       tail = NULL;
7085
7086       /* Count the number of merges we do in this pass.  */
7087       nmerges = 0;
7088
7089       /* Loop while there exists a merge to be done.  */
7090       while (p)
7091         {
7092           int i;
7093
7094           /* Count this merge.  */
7095           nmerges++;
7096
7097           /* Cut the list in two pieces by stepping INSIZE places
7098              forward in the list, starting from P.  */
7099           psize = 0;
7100           q = p;
7101           for (i = 0; i < insize; i++)
7102             {
7103               psize++;
7104               q = q->right;
7105               if (!q)
7106                 break;
7107             }
7108           qsize = insize;
7109
7110           /* Now we have two lists.  Merge them!  */
7111           while (psize > 0 || (qsize > 0 && q != NULL))
7112             {
7113               /* See from which the next case to merge comes from.  */
7114               if (psize == 0)
7115                 {
7116                   /* P is empty so the next case must come from Q.  */
7117                   e = q;
7118                   q = q->right;
7119                   qsize--;
7120                 }
7121               else if (qsize == 0 || q == NULL)
7122                 {
7123                   /* Q is empty.  */
7124                   e = p;
7125                   p = p->right;
7126                   psize--;
7127                 }
7128               else
7129                 {
7130                   cmp = compare_cases (p, q);
7131                   if (cmp < 0)
7132                     {
7133                       /* The whole case range for P is less than the
7134                          one for Q.  */
7135                       e = p;
7136                       p = p->right;
7137                       psize--;
7138                     }
7139                   else if (cmp > 0)
7140                     {
7141                       /* The whole case range for Q is greater than
7142                          the case range for P.  */
7143                       e = q;
7144                       q = q->right;
7145                       qsize--;
7146                     }
7147                   else
7148                     {
7149                       /* The cases overlap, or they are the same
7150                          element in the list.  Either way, we must
7151                          issue an error and get the next case from P.  */
7152                       /* FIXME: Sort P and Q by line number.  */
7153                       gfc_error ("CASE label at %L overlaps with CASE "
7154                                  "label at %L", &p->where, &q->where);
7155                       overlap_seen = 1;
7156                       e = p;
7157                       p = p->right;
7158                       psize--;
7159                     }
7160                 }
7161
7162                 /* Add the next element to the merged list.  */
7163               if (tail)
7164                 tail->right = e;
7165               else
7166                 list = e;
7167               e->left = tail;
7168               tail = e;
7169             }
7170
7171           /* P has now stepped INSIZE places along, and so has Q.  So
7172              they're the same.  */
7173           p = q;
7174         }
7175       tail->right = NULL;
7176
7177       /* If we have done only one merge or none at all, we've
7178          finished sorting the cases.  */
7179       if (nmerges <= 1)
7180         {
7181           if (!overlap_seen)
7182             return list;
7183           else
7184             return NULL;
7185         }
7186
7187       /* Otherwise repeat, merging lists twice the size.  */
7188       insize *= 2;
7189     }
7190 }
7191
7192
7193 /* Check to see if an expression is suitable for use in a CASE statement.
7194    Makes sure that all case expressions are scalar constants of the same
7195    type.  Return FAILURE if anything is wrong.  */
7196
7197 static gfc_try
7198 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7199 {
7200   if (e == NULL) return SUCCESS;
7201
7202   if (e->ts.type != case_expr->ts.type)
7203     {
7204       gfc_error ("Expression in CASE statement at %L must be of type %s",
7205                  &e->where, gfc_basic_typename (case_expr->ts.type));
7206       return FAILURE;
7207     }
7208
7209   /* C805 (R808) For a given case-construct, each case-value shall be of
7210      the same type as case-expr.  For character type, length differences
7211      are allowed, but the kind type parameters shall be the same.  */
7212
7213   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7214     {
7215       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7216                  &e->where, case_expr->ts.kind);
7217       return FAILURE;
7218     }
7219
7220   /* Convert the case value kind to that of case expression kind,
7221      if needed */
7222
7223   if (e->ts.kind != case_expr->ts.kind)
7224     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7225
7226   if (e->rank != 0)
7227     {
7228       gfc_error ("Expression in CASE statement at %L must be scalar",
7229                  &e->where);
7230       return FAILURE;
7231     }
7232
7233   return SUCCESS;
7234 }
7235
7236
7237 /* Given a completely parsed select statement, we:
7238
7239      - Validate all expressions and code within the SELECT.
7240      - Make sure that the selection expression is not of the wrong type.
7241      - Make sure that no case ranges overlap.
7242      - Eliminate unreachable cases and unreachable code resulting from
7243        removing case labels.
7244
7245    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7246    they are a hassle for code generation, and to prevent that, we just
7247    cut them out here.  This is not necessary for overlapping cases
7248    because they are illegal and we never even try to generate code.
7249
7250    We have the additional caveat that a SELECT construct could have
7251    been a computed GOTO in the source code. Fortunately we can fairly
7252    easily work around that here: The case_expr for a "real" SELECT CASE
7253    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7254    we have to do is make sure that the case_expr is a scalar integer
7255    expression.  */
7256
7257 static void
7258 resolve_select (gfc_code *code)
7259 {
7260   gfc_code *body;
7261   gfc_expr *case_expr;
7262   gfc_case *cp, *default_case, *tail, *head;
7263   int seen_unreachable;
7264   int seen_logical;
7265   int ncases;
7266   bt type;
7267   gfc_try t;
7268
7269   if (code->expr1 == NULL)
7270     {
7271       /* This was actually a computed GOTO statement.  */
7272       case_expr = code->expr2;
7273       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7274         gfc_error ("Selection expression in computed GOTO statement "
7275                    "at %L must be a scalar integer expression",
7276                    &case_expr->where);
7277
7278       /* Further checking is not necessary because this SELECT was built
7279          by the compiler, so it should always be OK.  Just move the
7280          case_expr from expr2 to expr so that we can handle computed
7281          GOTOs as normal SELECTs from here on.  */
7282       code->expr1 = code->expr2;
7283       code->expr2 = NULL;
7284       return;
7285     }
7286
7287   case_expr = code->expr1;
7288
7289   type = case_expr->ts.type;
7290   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7291     {
7292       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7293                  &case_expr->where, gfc_typename (&case_expr->ts));
7294
7295       /* Punt. Going on here just produce more garbage error messages.  */
7296       return;
7297     }
7298
7299   if (case_expr->rank != 0)
7300     {
7301       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7302                  "expression", &case_expr->where);
7303
7304       /* Punt.  */
7305       return;
7306     }
7307
7308
7309   /* Raise a warning if an INTEGER case value exceeds the range of
7310      the case-expr. Later, all expressions will be promoted to the
7311      largest kind of all case-labels.  */
7312
7313   if (type == BT_INTEGER)
7314     for (body = code->block; body; body = body->block)
7315       for (cp = body->ext.case_list; cp; cp = cp->next)
7316         {
7317           if (cp->low
7318               && gfc_check_integer_range (cp->low->value.integer,
7319                                           case_expr->ts.kind) != ARITH_OK)
7320             gfc_warning ("Expression in CASE statement at %L is "
7321                          "not in the range of %s", &cp->low->where,
7322                          gfc_typename (&case_expr->ts));
7323
7324           if (cp->high
7325               && cp->low != cp->high
7326               && gfc_check_integer_range (cp->high->value.integer,
7327                                           case_expr->ts.kind) != ARITH_OK)
7328             gfc_warning ("Expression in CASE statement at %L is "
7329                          "not in the range of %s", &cp->high->where,
7330                          gfc_typename (&case_expr->ts));
7331         }
7332
7333   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7334      of the SELECT CASE expression and its CASE values.  Walk the lists
7335      of case values, and if we find a mismatch, promote case_expr to
7336      the appropriate kind.  */
7337
7338   if (type == BT_LOGICAL || type == BT_INTEGER)
7339     {
7340       for (body = code->block; body; body = body->block)
7341         {
7342           /* Walk the case label list.  */
7343           for (cp = body->ext.case_list; cp; cp = cp->next)
7344             {
7345               /* Intercept the DEFAULT case.  It does not have a kind.  */
7346               if (cp->low == NULL && cp->high == NULL)
7347                 continue;
7348
7349               /* Unreachable case ranges are discarded, so ignore.  */
7350               if (cp->low != NULL && cp->high != NULL
7351                   && cp->low != cp->high
7352                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7353                 continue;
7354
7355               if (cp->low != NULL
7356                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7357                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7358
7359               if (cp->high != NULL
7360                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7361                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7362             }
7363          }
7364     }
7365
7366   /* Assume there is no DEFAULT case.  */
7367   default_case = NULL;
7368   head = tail = NULL;
7369   ncases = 0;
7370   seen_logical = 0;
7371
7372   for (body = code->block; body; body = body->block)
7373     {
7374       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7375       t = SUCCESS;
7376       seen_unreachable = 0;
7377
7378       /* Walk the case label list, making sure that all case labels
7379          are legal.  */
7380       for (cp = body->ext.case_list; cp; cp = cp->next)
7381         {
7382           /* Count the number of cases in the whole construct.  */
7383           ncases++;
7384
7385           /* Intercept the DEFAULT case.  */
7386           if (cp->low == NULL && cp->high == NULL)
7387             {
7388               if (default_case != NULL)
7389                 {
7390                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7391                              "by a second DEFAULT CASE at %L",
7392                              &default_case->where, &cp->where);
7393                   t = FAILURE;
7394                   break;
7395                 }
7396               else
7397                 {
7398                   default_case = cp;
7399                   continue;
7400                 }
7401             }
7402
7403           /* Deal with single value cases and case ranges.  Errors are
7404              issued from the validation function.  */
7405           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7406               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7407             {
7408               t = FAILURE;
7409               break;
7410             }
7411
7412           if (type == BT_LOGICAL
7413               && ((cp->low == NULL || cp->high == NULL)
7414                   || cp->low != cp->high))
7415             {
7416               gfc_error ("Logical range in CASE statement at %L is not "
7417                          "allowed", &cp->low->where);
7418               t = FAILURE;
7419               break;
7420             }
7421
7422           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7423             {
7424               int value;
7425               value = cp->low->value.logical == 0 ? 2 : 1;
7426               if (value & seen_logical)
7427                 {
7428                   gfc_error ("Constant logical value in CASE statement "
7429                              "is repeated at %L",
7430                              &cp->low->where);
7431                   t = FAILURE;
7432                   break;
7433                 }
7434               seen_logical |= value;
7435             }
7436
7437           if (cp->low != NULL && cp->high != NULL
7438               && cp->low != cp->high
7439               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7440             {
7441               if (gfc_option.warn_surprising)
7442                 gfc_warning ("Range specification at %L can never "
7443                              "be matched", &cp->where);
7444
7445               cp->unreachable = 1;
7446               seen_unreachable = 1;
7447             }
7448           else
7449             {
7450               /* If the case range can be matched, it can also overlap with
7451                  other cases.  To make sure it does not, we put it in a
7452                  double linked list here.  We sort that with a merge sort
7453                  later on to detect any overlapping cases.  */
7454               if (!head)
7455                 {
7456                   head = tail = cp;
7457                   head->right = head->left = NULL;
7458                 }
7459               else
7460                 {
7461                   tail->right = cp;
7462                   tail->right->left = tail;
7463                   tail = tail->right;
7464                   tail->right = NULL;
7465                 }
7466             }
7467         }
7468
7469       /* It there was a failure in the previous case label, give up
7470          for this case label list.  Continue with the next block.  */
7471       if (t == FAILURE)
7472         continue;
7473
7474       /* See if any case labels that are unreachable have been seen.
7475          If so, we eliminate them.  This is a bit of a kludge because
7476          the case lists for a single case statement (label) is a
7477          single forward linked lists.  */
7478       if (seen_unreachable)
7479       {
7480         /* Advance until the first case in the list is reachable.  */
7481         while (body->ext.case_list != NULL
7482                && body->ext.case_list->unreachable)
7483           {
7484             gfc_case *n = body->ext.case_list;
7485             body->ext.case_list = body->ext.case_list->next;
7486             n->next = NULL;
7487             gfc_free_case_list (n);
7488           }
7489
7490         /* Strip all other unreachable cases.  */
7491         if (body->ext.case_list)
7492           {
7493             for (cp = body->ext.case_list; cp->next; cp = cp->next)
7494               {
7495                 if (cp->next->unreachable)
7496                   {
7497                     gfc_case *n = cp->next;
7498                     cp->next = cp->next->next;
7499                     n->next = NULL;
7500                     gfc_free_case_list (n);
7501                   }
7502               }
7503           }
7504       }
7505     }
7506
7507   /* See if there were overlapping cases.  If the check returns NULL,
7508      there was overlap.  In that case we don't do anything.  If head
7509      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7510      then used during code generation for SELECT CASE constructs with
7511      a case expression of a CHARACTER type.  */
7512   if (head)
7513     {
7514       head = check_case_overlap (head);
7515
7516       /* Prepend the default_case if it is there.  */
7517       if (head != NULL && default_case)
7518         {
7519           default_case->left = NULL;
7520           default_case->right = head;
7521           head->left = default_case;
7522         }
7523     }
7524
7525   /* Eliminate dead blocks that may be the result if we've seen
7526      unreachable case labels for a block.  */
7527   for (body = code; body && body->block; body = body->block)
7528     {
7529       if (body->block->ext.case_list == NULL)
7530         {
7531           /* Cut the unreachable block from the code chain.  */
7532           gfc_code *c = body->block;
7533           body->block = c->block;
7534
7535           /* Kill the dead block, but not the blocks below it.  */
7536           c->block = NULL;
7537           gfc_free_statements (c);
7538         }
7539     }
7540
7541   /* More than two cases is legal but insane for logical selects.
7542      Issue a warning for it.  */
7543   if (gfc_option.warn_surprising && type == BT_LOGICAL
7544       && ncases > 2)
7545     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7546                  &code->loc);
7547 }
7548
7549
7550 /* Check if a derived type is extensible.  */
7551
7552 bool
7553 gfc_type_is_extensible (gfc_symbol *sym)
7554 {
7555   return !(sym->attr.is_bind_c || sym->attr.sequence);
7556 }
7557
7558
7559 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7560    correct as well as possibly the array-spec.  */
7561
7562 static void
7563 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7564 {
7565   gfc_expr* target;
7566   bool to_var;
7567
7568   gcc_assert (sym->assoc);
7569   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7570
7571   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7572      case, return.  Resolution will be called later manually again when
7573      this is done.  */
7574   target = sym->assoc->target;
7575   if (!target)
7576     return;
7577   gcc_assert (!sym->assoc->dangling);
7578
7579   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7580     return;
7581
7582   /* For variable targets, we get some attributes from the target.  */
7583   if (target->expr_type == EXPR_VARIABLE)
7584     {
7585       gfc_symbol* tsym;
7586
7587       gcc_assert (target->symtree);
7588       tsym = target->symtree->n.sym;
7589
7590       sym->attr.asynchronous = tsym->attr.asynchronous;
7591       sym->attr.volatile_ = tsym->attr.volatile_;
7592
7593       sym->attr.target = (tsym->attr.target || tsym->attr.pointer);
7594     }
7595
7596   sym->ts = target->ts;
7597   gcc_assert (sym->ts.type != BT_UNKNOWN);
7598
7599   /* See if this is a valid association-to-variable.  */
7600   to_var = (target->expr_type == EXPR_VARIABLE
7601             && !gfc_has_vector_subscript (target));
7602   if (sym->assoc->variable && !to_var)
7603     {
7604       if (target->expr_type == EXPR_VARIABLE)
7605         gfc_error ("'%s' at %L associated to vector-indexed target can not"
7606                    " be used in a variable definition context",
7607                    sym->name, &sym->declared_at);
7608       else
7609         gfc_error ("'%s' at %L associated to expression can not"
7610                    " be used in a variable definition context",
7611                    sym->name, &sym->declared_at);
7612
7613       return;
7614     }
7615   sym->assoc->variable = to_var;
7616
7617   /* Finally resolve if this is an array or not.  */
7618   if (sym->attr.dimension && target->rank == 0)
7619     {
7620       gfc_error ("Associate-name '%s' at %L is used as array",
7621                  sym->name, &sym->declared_at);
7622       sym->attr.dimension = 0;
7623       return;
7624     }
7625   if (target->rank > 0)
7626     sym->attr.dimension = 1;
7627
7628   if (sym->attr.dimension)
7629     {
7630       sym->as = gfc_get_array_spec ();
7631       sym->as->rank = target->rank;
7632       sym->as->type = AS_DEFERRED;
7633
7634       /* Target must not be coindexed, thus the associate-variable
7635          has no corank.  */
7636       sym->as->corank = 0;
7637     }
7638 }
7639
7640
7641 /* Resolve a SELECT TYPE statement.  */
7642
7643 static void
7644 resolve_select_type (gfc_code *code)
7645 {
7646   gfc_symbol *selector_type;
7647   gfc_code *body, *new_st, *if_st, *tail;
7648   gfc_code *class_is = NULL, *default_case = NULL;
7649   gfc_case *c;
7650   gfc_symtree *st;
7651   char name[GFC_MAX_SYMBOL_LEN];
7652   gfc_namespace *ns;
7653   int error = 0;
7654
7655   ns = code->ext.block.ns;
7656   gfc_resolve (ns);
7657
7658   /* Check for F03:C813.  */
7659   if (code->expr1->ts.type != BT_CLASS
7660       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7661     {
7662       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7663                  "at %L", &code->loc);
7664       return;
7665     }
7666
7667   if (code->expr2)
7668     {
7669       if (code->expr1->symtree->n.sym->attr.untyped)
7670         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7671       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7672     }
7673   else
7674     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7675
7676   /* Loop over TYPE IS / CLASS IS cases.  */
7677   for (body = code->block; body; body = body->block)
7678     {
7679       c = body->ext.case_list;
7680
7681       /* Check F03:C815.  */
7682       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7683           && !gfc_type_is_extensible (c->ts.u.derived))
7684         {
7685           gfc_error ("Derived type '%s' at %L must be extensible",
7686                      c->ts.u.derived->name, &c->where);
7687           error++;
7688           continue;
7689         }
7690
7691       /* Check F03:C816.  */
7692       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7693           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7694         {
7695           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7696                      c->ts.u.derived->name, &c->where, selector_type->name);
7697           error++;
7698           continue;
7699         }
7700
7701       /* Intercept the DEFAULT case.  */
7702       if (c->ts.type == BT_UNKNOWN)
7703         {
7704           /* Check F03:C818.  */
7705           if (default_case)
7706             {
7707               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7708                          "by a second DEFAULT CASE at %L",
7709                          &default_case->ext.case_list->where, &c->where);
7710               error++;
7711               continue;
7712             }
7713           else
7714             default_case = body;
7715         }
7716     }
7717     
7718   if (error > 0)
7719     return;
7720
7721   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7722      target if present.  */
7723   code->op = EXEC_BLOCK;
7724   if (code->expr2)
7725     {
7726       gfc_association_list* assoc;
7727
7728       assoc = gfc_get_association_list ();
7729       assoc->st = code->expr1->symtree;
7730       assoc->target = gfc_copy_expr (code->expr2);
7731       /* assoc->variable will be set by resolve_assoc_var.  */
7732       
7733       code->ext.block.assoc = assoc;
7734       code->expr1->symtree->n.sym->assoc = assoc;
7735
7736       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7737     }
7738   else
7739     code->ext.block.assoc = NULL;
7740
7741   /* Add EXEC_SELECT to switch on type.  */
7742   new_st = gfc_get_code ();
7743   new_st->op = code->op;
7744   new_st->expr1 = code->expr1;
7745   new_st->expr2 = code->expr2;
7746   new_st->block = code->block;
7747   code->expr1 = code->expr2 =  NULL;
7748   code->block = NULL;
7749   if (!ns->code)
7750     ns->code = new_st;
7751   else
7752     ns->code->next = new_st;
7753   code = new_st;
7754   code->op = EXEC_SELECT;
7755   gfc_add_component_ref (code->expr1, "$vptr");
7756   gfc_add_component_ref (code->expr1, "$hash");
7757
7758   /* Loop over TYPE IS / CLASS IS cases.  */
7759   for (body = code->block; body; body = body->block)
7760     {
7761       c = body->ext.case_list;
7762
7763       if (c->ts.type == BT_DERIVED)
7764         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7765                                              c->ts.u.derived->hash_value);
7766
7767       else if (c->ts.type == BT_UNKNOWN)
7768         continue;
7769
7770       /* Associate temporary to selector.  This should only be done
7771          when this case is actually true, so build a new ASSOCIATE
7772          that does precisely this here (instead of using the
7773          'global' one).  */
7774
7775       if (c->ts.type == BT_CLASS)
7776         sprintf (name, "tmp$class$%s", c->ts.u.derived->name);
7777       else
7778         sprintf (name, "tmp$type$%s", c->ts.u.derived->name);
7779       st = gfc_find_symtree (ns->sym_root, name);
7780       gcc_assert (st->n.sym->assoc);
7781       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
7782       if (c->ts.type == BT_DERIVED)
7783         gfc_add_component_ref (st->n.sym->assoc->target, "$data");
7784
7785       new_st = gfc_get_code ();
7786       new_st->op = EXEC_BLOCK;
7787       new_st->ext.block.ns = gfc_build_block_ns (ns);
7788       new_st->ext.block.ns->code = body->next;
7789       body->next = new_st;
7790
7791       /* Chain in the new list only if it is marked as dangling.  Otherwise
7792          there is a CASE label overlap and this is already used.  Just ignore,
7793          the error is diagonsed elsewhere.  */
7794       if (st->n.sym->assoc->dangling)
7795         {
7796           new_st->ext.block.assoc = st->n.sym->assoc;
7797           st->n.sym->assoc->dangling = 0;
7798         }
7799
7800       resolve_assoc_var (st->n.sym, false);
7801     }
7802     
7803   /* Take out CLASS IS cases for separate treatment.  */
7804   body = code;
7805   while (body && body->block)
7806     {
7807       if (body->block->ext.case_list->ts.type == BT_CLASS)
7808         {
7809           /* Add to class_is list.  */
7810           if (class_is == NULL)
7811             { 
7812               class_is = body->block;
7813               tail = class_is;
7814             }
7815           else
7816             {
7817               for (tail = class_is; tail->block; tail = tail->block) ;
7818               tail->block = body->block;
7819               tail = tail->block;
7820             }
7821           /* Remove from EXEC_SELECT list.  */
7822           body->block = body->block->block;
7823           tail->block = NULL;
7824         }
7825       else
7826         body = body->block;
7827     }
7828
7829   if (class_is)
7830     {
7831       gfc_symbol *vtab;
7832       
7833       if (!default_case)
7834         {
7835           /* Add a default case to hold the CLASS IS cases.  */
7836           for (tail = code; tail->block; tail = tail->block) ;
7837           tail->block = gfc_get_code ();
7838           tail = tail->block;
7839           tail->op = EXEC_SELECT_TYPE;
7840           tail->ext.case_list = gfc_get_case ();
7841           tail->ext.case_list->ts.type = BT_UNKNOWN;
7842           tail->next = NULL;
7843           default_case = tail;
7844         }
7845
7846       /* More than one CLASS IS block?  */
7847       if (class_is->block)
7848         {
7849           gfc_code **c1,*c2;
7850           bool swapped;
7851           /* Sort CLASS IS blocks by extension level.  */
7852           do
7853             {
7854               swapped = false;
7855               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
7856                 {
7857                   c2 = (*c1)->block;
7858                   /* F03:C817 (check for doubles).  */
7859                   if ((*c1)->ext.case_list->ts.u.derived->hash_value
7860                       == c2->ext.case_list->ts.u.derived->hash_value)
7861                     {
7862                       gfc_error ("Double CLASS IS block in SELECT TYPE "
7863                                  "statement at %L", &c2->ext.case_list->where);
7864                       return;
7865                     }
7866                   if ((*c1)->ext.case_list->ts.u.derived->attr.extension
7867                       < c2->ext.case_list->ts.u.derived->attr.extension)
7868                     {
7869                       /* Swap.  */
7870                       (*c1)->block = c2->block;
7871                       c2->block = *c1;
7872                       *c1 = c2;
7873                       swapped = true;
7874                     }
7875                 }
7876             }
7877           while (swapped);
7878         }
7879         
7880       /* Generate IF chain.  */
7881       if_st = gfc_get_code ();
7882       if_st->op = EXEC_IF;
7883       new_st = if_st;
7884       for (body = class_is; body; body = body->block)
7885         {
7886           new_st->block = gfc_get_code ();
7887           new_st = new_st->block;
7888           new_st->op = EXEC_IF;
7889           /* Set up IF condition: Call _gfortran_is_extension_of.  */
7890           new_st->expr1 = gfc_get_expr ();
7891           new_st->expr1->expr_type = EXPR_FUNCTION;
7892           new_st->expr1->ts.type = BT_LOGICAL;
7893           new_st->expr1->ts.kind = 4;
7894           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
7895           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
7896           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
7897           /* Set up arguments.  */
7898           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
7899           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
7900           gfc_add_component_ref (new_st->expr1->value.function.actual->expr, "$vptr");
7901           vtab = gfc_find_derived_vtab (body->ext.case_list->ts.u.derived);
7902           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
7903           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
7904           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
7905           new_st->next = body->next;
7906         }
7907         if (default_case->next)
7908           {
7909             new_st->block = gfc_get_code ();
7910             new_st = new_st->block;
7911             new_st->op = EXEC_IF;
7912             new_st->next = default_case->next;
7913           }
7914           
7915         /* Replace CLASS DEFAULT code by the IF chain.  */
7916         default_case->next = if_st;
7917     }
7918
7919   resolve_select (code);
7920
7921 }
7922
7923
7924 /* Resolve a transfer statement. This is making sure that:
7925    -- a derived type being transferred has only non-pointer components
7926    -- a derived type being transferred doesn't have private components, unless 
7927       it's being transferred from the module where the type was defined
7928    -- we're not trying to transfer a whole assumed size array.  */
7929
7930 static void
7931 resolve_transfer (gfc_code *code)
7932 {
7933   gfc_typespec *ts;
7934   gfc_symbol *sym;
7935   gfc_ref *ref;
7936   gfc_expr *exp;
7937
7938   exp = code->expr1;
7939
7940   while (exp != NULL && exp->expr_type == EXPR_OP
7941          && exp->value.op.op == INTRINSIC_PARENTHESES)
7942     exp = exp->value.op.op1;
7943
7944   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
7945                       && exp->expr_type != EXPR_FUNCTION))
7946     return;
7947
7948   sym = exp->symtree->n.sym;
7949   ts = &sym->ts;
7950
7951   /* Go to actual component transferred.  */
7952   for (ref = code->expr1->ref; ref; ref = ref->next)
7953     if (ref->type == REF_COMPONENT)
7954       ts = &ref->u.c.component->ts;
7955
7956   if (ts->type == BT_DERIVED)
7957     {
7958       /* Check that transferred derived type doesn't contain POINTER
7959          components.  */
7960       if (ts->u.derived->attr.pointer_comp)
7961         {
7962           gfc_error ("Data transfer element at %L cannot have "
7963                      "POINTER components", &code->loc);
7964           return;
7965         }
7966
7967       if (ts->u.derived->attr.alloc_comp)
7968         {
7969           gfc_error ("Data transfer element at %L cannot have "
7970                      "ALLOCATABLE components", &code->loc);
7971           return;
7972         }
7973
7974       if (derived_inaccessible (ts->u.derived))
7975         {
7976           gfc_error ("Data transfer element at %L cannot have "
7977                      "PRIVATE components",&code->loc);
7978           return;
7979         }
7980     }
7981
7982   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
7983       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
7984     {
7985       gfc_error ("Data transfer element at %L cannot be a full reference to "
7986                  "an assumed-size array", &code->loc);
7987       return;
7988     }
7989 }
7990
7991
7992 /*********** Toplevel code resolution subroutines ***********/
7993
7994 /* Find the set of labels that are reachable from this block.  We also
7995    record the last statement in each block.  */
7996      
7997 static void
7998 find_reachable_labels (gfc_code *block)
7999 {
8000   gfc_code *c;
8001
8002   if (!block)
8003     return;
8004
8005   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8006
8007   /* Collect labels in this block.  We don't keep those corresponding
8008      to END {IF|SELECT}, these are checked in resolve_branch by going
8009      up through the code_stack.  */
8010   for (c = block; c; c = c->next)
8011     {
8012       if (c->here && c->op != EXEC_END_BLOCK)
8013         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8014     }
8015
8016   /* Merge with labels from parent block.  */
8017   if (cs_base->prev)
8018     {
8019       gcc_assert (cs_base->prev->reachable_labels);
8020       bitmap_ior_into (cs_base->reachable_labels,
8021                        cs_base->prev->reachable_labels);
8022     }
8023 }
8024
8025
8026 static void
8027 resolve_sync (gfc_code *code)
8028 {
8029   /* Check imageset. The * case matches expr1 == NULL.  */
8030   if (code->expr1)
8031     {
8032       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8033         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8034                    "INTEGER expression", &code->expr1->where);
8035       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8036           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8037         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8038                    &code->expr1->where);
8039       else if (code->expr1->expr_type == EXPR_ARRAY
8040                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8041         {
8042            gfc_constructor *cons;
8043            cons = gfc_constructor_first (code->expr1->value.constructor);
8044            for (; cons; cons = gfc_constructor_next (cons))
8045              if (cons->expr->expr_type == EXPR_CONSTANT
8046                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8047                gfc_error ("Imageset argument at %L must between 1 and "
8048                           "num_images()", &cons->expr->where);
8049         }
8050     }
8051
8052   /* Check STAT.  */
8053   if (code->expr2
8054       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8055           || code->expr2->expr_type != EXPR_VARIABLE))
8056     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8057                &code->expr2->where);
8058
8059   /* Check ERRMSG.  */
8060   if (code->expr3
8061       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8062           || code->expr3->expr_type != EXPR_VARIABLE))
8063     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8064                &code->expr3->where);
8065 }
8066
8067
8068 /* Given a branch to a label, see if the branch is conforming.
8069    The code node describes where the branch is located.  */
8070
8071 static void
8072 resolve_branch (gfc_st_label *label, gfc_code *code)
8073 {
8074   code_stack *stack;
8075
8076   if (label == NULL)
8077     return;
8078
8079   /* Step one: is this a valid branching target?  */
8080
8081   if (label->defined == ST_LABEL_UNKNOWN)
8082     {
8083       gfc_error ("Label %d referenced at %L is never defined", label->value,
8084                  &label->where);
8085       return;
8086     }
8087
8088   if (label->defined != ST_LABEL_TARGET)
8089     {
8090       gfc_error ("Statement at %L is not a valid branch target statement "
8091                  "for the branch statement at %L", &label->where, &code->loc);
8092       return;
8093     }
8094
8095   /* Step two: make sure this branch is not a branch to itself ;-)  */
8096
8097   if (code->here == label)
8098     {
8099       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8100       return;
8101     }
8102
8103   /* Step three:  See if the label is in the same block as the
8104      branching statement.  The hard work has been done by setting up
8105      the bitmap reachable_labels.  */
8106
8107   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8108     {
8109       /* Check now whether there is a CRITICAL construct; if so, check
8110          whether the label is still visible outside of the CRITICAL block,
8111          which is invalid.  */
8112       for (stack = cs_base; stack; stack = stack->prev)
8113         if (stack->current->op == EXEC_CRITICAL
8114             && bitmap_bit_p (stack->reachable_labels, label->value))
8115           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8116                       " at %L", &code->loc, &label->where);
8117
8118       return;
8119     }
8120
8121   /* Step four:  If we haven't found the label in the bitmap, it may
8122     still be the label of the END of the enclosing block, in which
8123     case we find it by going up the code_stack.  */
8124
8125   for (stack = cs_base; stack; stack = stack->prev)
8126     {
8127       if (stack->current->next && stack->current->next->here == label)
8128         break;
8129       if (stack->current->op == EXEC_CRITICAL)
8130         {
8131           /* Note: A label at END CRITICAL does not leave the CRITICAL
8132              construct as END CRITICAL is still part of it.  */
8133           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8134                       " at %L", &code->loc, &label->where);
8135           return;
8136         }
8137     }
8138
8139   if (stack)
8140     {
8141       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
8142       return;
8143     }
8144
8145   /* The label is not in an enclosing block, so illegal.  This was
8146      allowed in Fortran 66, so we allow it as extension.  No
8147      further checks are necessary in this case.  */
8148   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8149                   "as the GOTO statement at %L", &label->where,
8150                   &code->loc);
8151   return;
8152 }
8153
8154
8155 /* Check whether EXPR1 has the same shape as EXPR2.  */
8156
8157 static gfc_try
8158 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8159 {
8160   mpz_t shape[GFC_MAX_DIMENSIONS];
8161   mpz_t shape2[GFC_MAX_DIMENSIONS];
8162   gfc_try result = FAILURE;
8163   int i;
8164
8165   /* Compare the rank.  */
8166   if (expr1->rank != expr2->rank)
8167     return result;
8168
8169   /* Compare the size of each dimension.  */
8170   for (i=0; i<expr1->rank; i++)
8171     {
8172       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8173         goto ignore;
8174
8175       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8176         goto ignore;
8177
8178       if (mpz_cmp (shape[i], shape2[i]))
8179         goto over;
8180     }
8181
8182   /* When either of the two expression is an assumed size array, we
8183      ignore the comparison of dimension sizes.  */
8184 ignore:
8185   result = SUCCESS;
8186
8187 over:
8188   for (i--; i >= 0; i--)
8189     {
8190       mpz_clear (shape[i]);
8191       mpz_clear (shape2[i]);
8192     }
8193   return result;
8194 }
8195
8196
8197 /* Check whether a WHERE assignment target or a WHERE mask expression
8198    has the same shape as the outmost WHERE mask expression.  */
8199
8200 static void
8201 resolve_where (gfc_code *code, gfc_expr *mask)
8202 {
8203   gfc_code *cblock;
8204   gfc_code *cnext;
8205   gfc_expr *e = NULL;
8206
8207   cblock = code->block;
8208
8209   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8210      In case of nested WHERE, only the outmost one is stored.  */
8211   if (mask == NULL) /* outmost WHERE */
8212     e = cblock->expr1;
8213   else /* inner WHERE */
8214     e = mask;
8215
8216   while (cblock)
8217     {
8218       if (cblock->expr1)
8219         {
8220           /* Check if the mask-expr has a consistent shape with the
8221              outmost WHERE mask-expr.  */
8222           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8223             gfc_error ("WHERE mask at %L has inconsistent shape",
8224                        &cblock->expr1->where);
8225          }
8226
8227       /* the assignment statement of a WHERE statement, or the first
8228          statement in where-body-construct of a WHERE construct */
8229       cnext = cblock->next;
8230       while (cnext)
8231         {
8232           switch (cnext->op)
8233             {
8234             /* WHERE assignment statement */
8235             case EXEC_ASSIGN:
8236
8237               /* Check shape consistent for WHERE assignment target.  */
8238               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8239                gfc_error ("WHERE assignment target at %L has "
8240                           "inconsistent shape", &cnext->expr1->where);
8241               break;
8242
8243   
8244             case EXEC_ASSIGN_CALL:
8245               resolve_call (cnext);
8246               if (!cnext->resolved_sym->attr.elemental)
8247                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8248                           &cnext->ext.actual->expr->where);
8249               break;
8250
8251             /* WHERE or WHERE construct is part of a where-body-construct */
8252             case EXEC_WHERE:
8253               resolve_where (cnext, e);
8254               break;
8255
8256             default:
8257               gfc_error ("Unsupported statement inside WHERE at %L",
8258                          &cnext->loc);
8259             }
8260          /* the next statement within the same where-body-construct */
8261          cnext = cnext->next;
8262        }
8263     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8264     cblock = cblock->block;
8265   }
8266 }
8267
8268
8269 /* Resolve assignment in FORALL construct.
8270    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8271    FORALL index variables.  */
8272
8273 static void
8274 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8275 {
8276   int n;
8277
8278   for (n = 0; n < nvar; n++)
8279     {
8280       gfc_symbol *forall_index;
8281
8282       forall_index = var_expr[n]->symtree->n.sym;
8283
8284       /* Check whether the assignment target is one of the FORALL index
8285          variable.  */
8286       if ((code->expr1->expr_type == EXPR_VARIABLE)
8287           && (code->expr1->symtree->n.sym == forall_index))
8288         gfc_error ("Assignment to a FORALL index variable at %L",
8289                    &code->expr1->where);
8290       else
8291         {
8292           /* If one of the FORALL index variables doesn't appear in the
8293              assignment variable, then there could be a many-to-one
8294              assignment.  Emit a warning rather than an error because the
8295              mask could be resolving this problem.  */
8296           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8297             gfc_warning ("The FORALL with index '%s' is not used on the "
8298                          "left side of the assignment at %L and so might "
8299                          "cause multiple assignment to this object",
8300                          var_expr[n]->symtree->name, &code->expr1->where);
8301         }
8302     }
8303 }
8304
8305
8306 /* Resolve WHERE statement in FORALL construct.  */
8307
8308 static void
8309 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8310                                   gfc_expr **var_expr)
8311 {
8312   gfc_code *cblock;
8313   gfc_code *cnext;
8314
8315   cblock = code->block;
8316   while (cblock)
8317     {
8318       /* the assignment statement of a WHERE statement, or the first
8319          statement in where-body-construct of a WHERE construct */
8320       cnext = cblock->next;
8321       while (cnext)
8322         {
8323           switch (cnext->op)
8324             {
8325             /* WHERE assignment statement */
8326             case EXEC_ASSIGN:
8327               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8328               break;
8329   
8330             /* WHERE operator assignment statement */
8331             case EXEC_ASSIGN_CALL:
8332               resolve_call (cnext);
8333               if (!cnext->resolved_sym->attr.elemental)
8334                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8335                           &cnext->ext.actual->expr->where);
8336               break;
8337
8338             /* WHERE or WHERE construct is part of a where-body-construct */
8339             case EXEC_WHERE:
8340               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8341               break;
8342
8343             default:
8344               gfc_error ("Unsupported statement inside WHERE at %L",
8345                          &cnext->loc);
8346             }
8347           /* the next statement within the same where-body-construct */
8348           cnext = cnext->next;
8349         }
8350       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8351       cblock = cblock->block;
8352     }
8353 }
8354
8355
8356 /* Traverse the FORALL body to check whether the following errors exist:
8357    1. For assignment, check if a many-to-one assignment happens.
8358    2. For WHERE statement, check the WHERE body to see if there is any
8359       many-to-one assignment.  */
8360
8361 static void
8362 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8363 {
8364   gfc_code *c;
8365
8366   c = code->block->next;
8367   while (c)
8368     {
8369       switch (c->op)
8370         {
8371         case EXEC_ASSIGN:
8372         case EXEC_POINTER_ASSIGN:
8373           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8374           break;
8375
8376         case EXEC_ASSIGN_CALL:
8377           resolve_call (c);
8378           break;
8379
8380         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8381            there is no need to handle it here.  */
8382         case EXEC_FORALL:
8383           break;
8384         case EXEC_WHERE:
8385           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8386           break;
8387         default:
8388           break;
8389         }
8390       /* The next statement in the FORALL body.  */
8391       c = c->next;
8392     }
8393 }
8394
8395
8396 /* Counts the number of iterators needed inside a forall construct, including
8397    nested forall constructs. This is used to allocate the needed memory 
8398    in gfc_resolve_forall.  */
8399
8400 static int 
8401 gfc_count_forall_iterators (gfc_code *code)
8402 {
8403   int max_iters, sub_iters, current_iters;
8404   gfc_forall_iterator *fa;
8405
8406   gcc_assert(code->op == EXEC_FORALL);
8407   max_iters = 0;
8408   current_iters = 0;
8409
8410   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8411     current_iters ++;
8412   
8413   code = code->block->next;
8414
8415   while (code)
8416     {          
8417       if (code->op == EXEC_FORALL)
8418         {
8419           sub_iters = gfc_count_forall_iterators (code);
8420           if (sub_iters > max_iters)
8421             max_iters = sub_iters;
8422         }
8423       code = code->next;
8424     }
8425
8426   return current_iters + max_iters;
8427 }
8428
8429
8430 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8431    gfc_resolve_forall_body to resolve the FORALL body.  */
8432
8433 static void
8434 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8435 {
8436   static gfc_expr **var_expr;
8437   static int total_var = 0;
8438   static int nvar = 0;
8439   int old_nvar, tmp;
8440   gfc_forall_iterator *fa;
8441   int i;
8442
8443   old_nvar = nvar;
8444
8445   /* Start to resolve a FORALL construct   */
8446   if (forall_save == 0)
8447     {
8448       /* Count the total number of FORALL index in the nested FORALL
8449          construct in order to allocate the VAR_EXPR with proper size.  */
8450       total_var = gfc_count_forall_iterators (code);
8451
8452       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8453       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
8454     }
8455
8456   /* The information about FORALL iterator, including FORALL index start, end
8457      and stride. The FORALL index can not appear in start, end or stride.  */
8458   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8459     {
8460       /* Check if any outer FORALL index name is the same as the current
8461          one.  */
8462       for (i = 0; i < nvar; i++)
8463         {
8464           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8465             {
8466               gfc_error ("An outer FORALL construct already has an index "
8467                          "with this name %L", &fa->var->where);
8468             }
8469         }
8470
8471       /* Record the current FORALL index.  */
8472       var_expr[nvar] = gfc_copy_expr (fa->var);
8473
8474       nvar++;
8475
8476       /* No memory leak.  */
8477       gcc_assert (nvar <= total_var);
8478     }
8479
8480   /* Resolve the FORALL body.  */
8481   gfc_resolve_forall_body (code, nvar, var_expr);
8482
8483   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8484   gfc_resolve_blocks (code->block, ns);
8485
8486   tmp = nvar;
8487   nvar = old_nvar;
8488   /* Free only the VAR_EXPRs allocated in this frame.  */
8489   for (i = nvar; i < tmp; i++)
8490      gfc_free_expr (var_expr[i]);
8491
8492   if (nvar == 0)
8493     {
8494       /* We are in the outermost FORALL construct.  */
8495       gcc_assert (forall_save == 0);
8496
8497       /* VAR_EXPR is not needed any more.  */
8498       gfc_free (var_expr);
8499       total_var = 0;
8500     }
8501 }
8502
8503
8504 /* Resolve a BLOCK construct statement.  */
8505
8506 static void
8507 resolve_block_construct (gfc_code* code)
8508 {
8509   /* Resolve the BLOCK's namespace.  */
8510   gfc_resolve (code->ext.block.ns);
8511
8512   /* For an ASSOCIATE block, the associations (and their targets) are already
8513      resolved during resolve_symbol.  */
8514 }
8515
8516
8517 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8518    DO code nodes.  */
8519
8520 static void resolve_code (gfc_code *, gfc_namespace *);
8521
8522 void
8523 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8524 {
8525   gfc_try t;
8526
8527   for (; b; b = b->block)
8528     {
8529       t = gfc_resolve_expr (b->expr1);
8530       if (gfc_resolve_expr (b->expr2) == FAILURE)
8531         t = FAILURE;
8532
8533       switch (b->op)
8534         {
8535         case EXEC_IF:
8536           if (t == SUCCESS && b->expr1 != NULL
8537               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8538             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8539                        &b->expr1->where);
8540           break;
8541
8542         case EXEC_WHERE:
8543           if (t == SUCCESS
8544               && b->expr1 != NULL
8545               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8546             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8547                        &b->expr1->where);
8548           break;
8549
8550         case EXEC_GOTO:
8551           resolve_branch (b->label1, b);
8552           break;
8553
8554         case EXEC_BLOCK:
8555           resolve_block_construct (b);
8556           break;
8557
8558         case EXEC_SELECT:
8559         case EXEC_SELECT_TYPE:
8560         case EXEC_FORALL:
8561         case EXEC_DO:
8562         case EXEC_DO_WHILE:
8563         case EXEC_CRITICAL:
8564         case EXEC_READ:
8565         case EXEC_WRITE:
8566         case EXEC_IOLENGTH:
8567         case EXEC_WAIT:
8568           break;
8569
8570         case EXEC_OMP_ATOMIC:
8571         case EXEC_OMP_CRITICAL:
8572         case EXEC_OMP_DO:
8573         case EXEC_OMP_MASTER:
8574         case EXEC_OMP_ORDERED:
8575         case EXEC_OMP_PARALLEL:
8576         case EXEC_OMP_PARALLEL_DO:
8577         case EXEC_OMP_PARALLEL_SECTIONS:
8578         case EXEC_OMP_PARALLEL_WORKSHARE:
8579         case EXEC_OMP_SECTIONS:
8580         case EXEC_OMP_SINGLE:
8581         case EXEC_OMP_TASK:
8582         case EXEC_OMP_TASKWAIT:
8583         case EXEC_OMP_WORKSHARE:
8584           break;
8585
8586         default:
8587           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8588         }
8589
8590       resolve_code (b->next, ns);
8591     }
8592 }
8593
8594
8595 /* Does everything to resolve an ordinary assignment.  Returns true
8596    if this is an interface assignment.  */
8597 static bool
8598 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8599 {
8600   bool rval = false;
8601   gfc_expr *lhs;
8602   gfc_expr *rhs;
8603   int llen = 0;
8604   int rlen = 0;
8605   int n;
8606   gfc_ref *ref;
8607
8608   if (gfc_extend_assign (code, ns) == SUCCESS)
8609     {
8610       gfc_expr** rhsptr;
8611
8612       if (code->op == EXEC_ASSIGN_CALL)
8613         {
8614           lhs = code->ext.actual->expr;
8615           rhsptr = &code->ext.actual->next->expr;
8616         }
8617       else
8618         {
8619           gfc_actual_arglist* args;
8620           gfc_typebound_proc* tbp;
8621
8622           gcc_assert (code->op == EXEC_COMPCALL);
8623
8624           args = code->expr1->value.compcall.actual;
8625           lhs = args->expr;
8626           rhsptr = &args->next->expr;
8627
8628           tbp = code->expr1->value.compcall.tbp;
8629           gcc_assert (!tbp->is_generic);
8630         }
8631
8632       /* Make a temporary rhs when there is a default initializer
8633          and rhs is the same symbol as the lhs.  */
8634       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8635             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8636             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8637             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8638         *rhsptr = gfc_get_parentheses (*rhsptr);
8639
8640       return true;
8641     }
8642
8643   lhs = code->expr1;
8644   rhs = code->expr2;
8645
8646   if (rhs->is_boz
8647       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8648                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8649                          &code->loc) == FAILURE)
8650     return false;
8651
8652   /* Handle the case of a BOZ literal on the RHS.  */
8653   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8654     {
8655       int rc;
8656       if (gfc_option.warn_surprising)
8657         gfc_warning ("BOZ literal at %L is bitwise transferred "
8658                      "non-integer symbol '%s'", &code->loc,
8659                      lhs->symtree->n.sym->name);
8660
8661       if (!gfc_convert_boz (rhs, &lhs->ts))
8662         return false;
8663       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8664         {
8665           if (rc == ARITH_UNDERFLOW)
8666             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8667                        ". This check can be disabled with the option "
8668                        "-fno-range-check", &rhs->where);
8669           else if (rc == ARITH_OVERFLOW)
8670             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8671                        ". This check can be disabled with the option "
8672                        "-fno-range-check", &rhs->where);
8673           else if (rc == ARITH_NAN)
8674             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8675                        ". This check can be disabled with the option "
8676                        "-fno-range-check", &rhs->where);
8677           return false;
8678         }
8679     }
8680
8681
8682   if (lhs->ts.type == BT_CHARACTER
8683         && gfc_option.warn_character_truncation)
8684     {
8685       if (lhs->ts.u.cl != NULL
8686             && lhs->ts.u.cl->length != NULL
8687             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8688         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8689
8690       if (rhs->expr_type == EXPR_CONSTANT)
8691         rlen = rhs->value.character.length;
8692
8693       else if (rhs->ts.u.cl != NULL
8694                  && rhs->ts.u.cl->length != NULL
8695                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8696         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8697
8698       if (rlen && llen && rlen > llen)
8699         gfc_warning_now ("CHARACTER expression will be truncated "
8700                          "in assignment (%d/%d) at %L",
8701                          llen, rlen, &code->loc);
8702     }
8703
8704   /* Ensure that a vector index expression for the lvalue is evaluated
8705      to a temporary if the lvalue symbol is referenced in it.  */
8706   if (lhs->rank)
8707     {
8708       for (ref = lhs->ref; ref; ref= ref->next)
8709         if (ref->type == REF_ARRAY)
8710           {
8711             for (n = 0; n < ref->u.ar.dimen; n++)
8712               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8713                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8714                                            ref->u.ar.start[n]))
8715                 ref->u.ar.start[n]
8716                         = gfc_get_parentheses (ref->u.ar.start[n]);
8717           }
8718     }
8719
8720   if (gfc_pure (NULL))
8721     {
8722       if (gfc_impure_variable (lhs->symtree->n.sym))
8723         {
8724           gfc_error ("Cannot assign to variable '%s' in PURE "
8725                      "procedure at %L",
8726                       lhs->symtree->n.sym->name,
8727                       &lhs->where);
8728           return rval;
8729         }
8730
8731       if (lhs->ts.type == BT_DERIVED
8732             && lhs->expr_type == EXPR_VARIABLE
8733             && lhs->ts.u.derived->attr.pointer_comp
8734             && rhs->expr_type == EXPR_VARIABLE
8735             && (gfc_impure_variable (rhs->symtree->n.sym)
8736                 || gfc_is_coindexed (rhs)))
8737         {
8738           /* F2008, C1283.  */
8739           if (gfc_is_coindexed (rhs))
8740             gfc_error ("Coindexed expression at %L is assigned to "
8741                         "a derived type variable with a POINTER "
8742                         "component in a PURE procedure",
8743                         &rhs->where);
8744           else
8745             gfc_error ("The impure variable at %L is assigned to "
8746                         "a derived type variable with a POINTER "
8747                         "component in a PURE procedure (12.6)",
8748                         &rhs->where);
8749           return rval;
8750         }
8751
8752       /* Fortran 2008, C1283.  */
8753       if (gfc_is_coindexed (lhs))
8754         {
8755           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8756                      "procedure", &rhs->where);
8757           return rval;
8758         }
8759     }
8760
8761   /* F03:7.4.1.2.  */
8762   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
8763      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
8764   if (lhs->ts.type == BT_CLASS)
8765     {
8766       gfc_error ("Variable must not be polymorphic in assignment at %L",
8767                  &lhs->where);
8768       return false;
8769     }
8770
8771   /* F2008, Section 7.2.1.2.  */
8772   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
8773     {
8774       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
8775                  "component in assignment at %L", &lhs->where);
8776       return false;
8777     }
8778
8779   gfc_check_assign (lhs, rhs, 1);
8780   return false;
8781 }
8782
8783
8784 /* Given a block of code, recursively resolve everything pointed to by this
8785    code block.  */
8786
8787 static void
8788 resolve_code (gfc_code *code, gfc_namespace *ns)
8789 {
8790   int omp_workshare_save;
8791   int forall_save;
8792   code_stack frame;
8793   gfc_try t;
8794
8795   frame.prev = cs_base;
8796   frame.head = code;
8797   cs_base = &frame;
8798
8799   find_reachable_labels (code);
8800
8801   for (; code; code = code->next)
8802     {
8803       frame.current = code;
8804       forall_save = forall_flag;
8805
8806       if (code->op == EXEC_FORALL)
8807         {
8808           forall_flag = 1;
8809           gfc_resolve_forall (code, ns, forall_save);
8810           forall_flag = 2;
8811         }
8812       else if (code->block)
8813         {
8814           omp_workshare_save = -1;
8815           switch (code->op)
8816             {
8817             case EXEC_OMP_PARALLEL_WORKSHARE:
8818               omp_workshare_save = omp_workshare_flag;
8819               omp_workshare_flag = 1;
8820               gfc_resolve_omp_parallel_blocks (code, ns);
8821               break;
8822             case EXEC_OMP_PARALLEL:
8823             case EXEC_OMP_PARALLEL_DO:
8824             case EXEC_OMP_PARALLEL_SECTIONS:
8825             case EXEC_OMP_TASK:
8826               omp_workshare_save = omp_workshare_flag;
8827               omp_workshare_flag = 0;
8828               gfc_resolve_omp_parallel_blocks (code, ns);
8829               break;
8830             case EXEC_OMP_DO:
8831               gfc_resolve_omp_do_blocks (code, ns);
8832               break;
8833             case EXEC_SELECT_TYPE:
8834               gfc_current_ns = code->ext.block.ns;
8835               gfc_resolve_blocks (code->block, gfc_current_ns);
8836               gfc_current_ns = ns;
8837               break;
8838             case EXEC_OMP_WORKSHARE:
8839               omp_workshare_save = omp_workshare_flag;
8840               omp_workshare_flag = 1;
8841               /* FALLTHROUGH */
8842             default:
8843               gfc_resolve_blocks (code->block, ns);
8844               break;
8845             }
8846
8847           if (omp_workshare_save != -1)
8848             omp_workshare_flag = omp_workshare_save;
8849         }
8850
8851       t = SUCCESS;
8852       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
8853         t = gfc_resolve_expr (code->expr1);
8854       forall_flag = forall_save;
8855
8856       if (gfc_resolve_expr (code->expr2) == FAILURE)
8857         t = FAILURE;
8858
8859       if (code->op == EXEC_ALLOCATE
8860           && gfc_resolve_expr (code->expr3) == FAILURE)
8861         t = FAILURE;
8862
8863       switch (code->op)
8864         {
8865         case EXEC_NOP:
8866         case EXEC_END_BLOCK:
8867         case EXEC_CYCLE:
8868         case EXEC_PAUSE:
8869         case EXEC_STOP:
8870         case EXEC_ERROR_STOP:
8871         case EXEC_EXIT:
8872         case EXEC_CONTINUE:
8873         case EXEC_DT_END:
8874         case EXEC_ASSIGN_CALL:
8875         case EXEC_CRITICAL:
8876           break;
8877
8878         case EXEC_SYNC_ALL:
8879         case EXEC_SYNC_IMAGES:
8880         case EXEC_SYNC_MEMORY:
8881           resolve_sync (code);
8882           break;
8883
8884         case EXEC_ENTRY:
8885           /* Keep track of which entry we are up to.  */
8886           current_entry_id = code->ext.entry->id;
8887           break;
8888
8889         case EXEC_WHERE:
8890           resolve_where (code, NULL);
8891           break;
8892
8893         case EXEC_GOTO:
8894           if (code->expr1 != NULL)
8895             {
8896               if (code->expr1->ts.type != BT_INTEGER)
8897                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
8898                            "INTEGER variable", &code->expr1->where);
8899               else if (code->expr1->symtree->n.sym->attr.assign != 1)
8900                 gfc_error ("Variable '%s' has not been assigned a target "
8901                            "label at %L", code->expr1->symtree->n.sym->name,
8902                            &code->expr1->where);
8903             }
8904           else
8905             resolve_branch (code->label1, code);
8906           break;
8907
8908         case EXEC_RETURN:
8909           if (code->expr1 != NULL
8910                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
8911             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
8912                        "INTEGER return specifier", &code->expr1->where);
8913           break;
8914
8915         case EXEC_INIT_ASSIGN:
8916         case EXEC_END_PROCEDURE:
8917           break;
8918
8919         case EXEC_ASSIGN:
8920           if (t == FAILURE)
8921             break;
8922
8923           if (resolve_ordinary_assign (code, ns))
8924             {
8925               if (code->op == EXEC_COMPCALL)
8926                 goto compcall;
8927               else
8928                 goto call;
8929             }
8930           break;
8931
8932         case EXEC_LABEL_ASSIGN:
8933           if (code->label1->defined == ST_LABEL_UNKNOWN)
8934             gfc_error ("Label %d referenced at %L is never defined",
8935                        code->label1->value, &code->label1->where);
8936           if (t == SUCCESS
8937               && (code->expr1->expr_type != EXPR_VARIABLE
8938                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
8939                   || code->expr1->symtree->n.sym->ts.kind
8940                      != gfc_default_integer_kind
8941                   || code->expr1->symtree->n.sym->as != NULL))
8942             gfc_error ("ASSIGN statement at %L requires a scalar "
8943                        "default INTEGER variable", &code->expr1->where);
8944           break;
8945
8946         case EXEC_POINTER_ASSIGN:
8947           if (t == FAILURE)
8948             break;
8949
8950           gfc_check_pointer_assign (code->expr1, code->expr2);
8951           break;
8952
8953         case EXEC_ARITHMETIC_IF:
8954           if (t == SUCCESS
8955               && code->expr1->ts.type != BT_INTEGER
8956               && code->expr1->ts.type != BT_REAL)
8957             gfc_error ("Arithmetic IF statement at %L requires a numeric "
8958                        "expression", &code->expr1->where);
8959
8960           resolve_branch (code->label1, code);
8961           resolve_branch (code->label2, code);
8962           resolve_branch (code->label3, code);
8963           break;
8964
8965         case EXEC_IF:
8966           if (t == SUCCESS && code->expr1 != NULL
8967               && (code->expr1->ts.type != BT_LOGICAL
8968                   || code->expr1->rank != 0))
8969             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8970                        &code->expr1->where);
8971           break;
8972
8973         case EXEC_CALL:
8974         call:
8975           resolve_call (code);
8976           break;
8977
8978         case EXEC_COMPCALL:
8979         compcall:
8980           resolve_typebound_subroutine (code);
8981           break;
8982
8983         case EXEC_CALL_PPC:
8984           resolve_ppc_call (code);
8985           break;
8986
8987         case EXEC_SELECT:
8988           /* Select is complicated. Also, a SELECT construct could be
8989              a transformed computed GOTO.  */
8990           resolve_select (code);
8991           break;
8992
8993         case EXEC_SELECT_TYPE:
8994           resolve_select_type (code);
8995           break;
8996
8997         case EXEC_BLOCK:
8998           resolve_block_construct (code);
8999           break;
9000
9001         case EXEC_DO:
9002           if (code->ext.iterator != NULL)
9003             {
9004               gfc_iterator *iter = code->ext.iterator;
9005               if (gfc_resolve_iterator (iter, true) != FAILURE)
9006                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9007             }
9008           break;
9009
9010         case EXEC_DO_WHILE:
9011           if (code->expr1 == NULL)
9012             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9013           if (t == SUCCESS
9014               && (code->expr1->rank != 0
9015                   || code->expr1->ts.type != BT_LOGICAL))
9016             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9017                        "a scalar LOGICAL expression", &code->expr1->where);
9018           break;
9019
9020         case EXEC_ALLOCATE:
9021           if (t == SUCCESS)
9022             resolve_allocate_deallocate (code, "ALLOCATE");
9023
9024           break;
9025
9026         case EXEC_DEALLOCATE:
9027           if (t == SUCCESS)
9028             resolve_allocate_deallocate (code, "DEALLOCATE");
9029
9030           break;
9031
9032         case EXEC_OPEN:
9033           if (gfc_resolve_open (code->ext.open) == FAILURE)
9034             break;
9035
9036           resolve_branch (code->ext.open->err, code);
9037           break;
9038
9039         case EXEC_CLOSE:
9040           if (gfc_resolve_close (code->ext.close) == FAILURE)
9041             break;
9042
9043           resolve_branch (code->ext.close->err, code);
9044           break;
9045
9046         case EXEC_BACKSPACE:
9047         case EXEC_ENDFILE:
9048         case EXEC_REWIND:
9049         case EXEC_FLUSH:
9050           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9051             break;
9052
9053           resolve_branch (code->ext.filepos->err, code);
9054           break;
9055
9056         case EXEC_INQUIRE:
9057           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9058               break;
9059
9060           resolve_branch (code->ext.inquire->err, code);
9061           break;
9062
9063         case EXEC_IOLENGTH:
9064           gcc_assert (code->ext.inquire != NULL);
9065           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9066             break;
9067
9068           resolve_branch (code->ext.inquire->err, code);
9069           break;
9070
9071         case EXEC_WAIT:
9072           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9073             break;
9074
9075           resolve_branch (code->ext.wait->err, code);
9076           resolve_branch (code->ext.wait->end, code);
9077           resolve_branch (code->ext.wait->eor, code);
9078           break;
9079
9080         case EXEC_READ:
9081         case EXEC_WRITE:
9082           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9083             break;
9084
9085           resolve_branch (code->ext.dt->err, code);
9086           resolve_branch (code->ext.dt->end, code);
9087           resolve_branch (code->ext.dt->eor, code);
9088           break;
9089
9090         case EXEC_TRANSFER:
9091           resolve_transfer (code);
9092           break;
9093
9094         case EXEC_FORALL:
9095           resolve_forall_iterators (code->ext.forall_iterator);
9096
9097           if (code->expr1 != NULL && code->expr1->ts.type != BT_LOGICAL)
9098             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
9099                        "expression", &code->expr1->where);
9100           break;
9101
9102         case EXEC_OMP_ATOMIC:
9103         case EXEC_OMP_BARRIER:
9104         case EXEC_OMP_CRITICAL:
9105         case EXEC_OMP_FLUSH:
9106         case EXEC_OMP_DO:
9107         case EXEC_OMP_MASTER:
9108         case EXEC_OMP_ORDERED:
9109         case EXEC_OMP_SECTIONS:
9110         case EXEC_OMP_SINGLE:
9111         case EXEC_OMP_TASKWAIT:
9112         case EXEC_OMP_WORKSHARE:
9113           gfc_resolve_omp_directive (code, ns);
9114           break;
9115
9116         case EXEC_OMP_PARALLEL:
9117         case EXEC_OMP_PARALLEL_DO:
9118         case EXEC_OMP_PARALLEL_SECTIONS:
9119         case EXEC_OMP_PARALLEL_WORKSHARE:
9120         case EXEC_OMP_TASK:
9121           omp_workshare_save = omp_workshare_flag;
9122           omp_workshare_flag = 0;
9123           gfc_resolve_omp_directive (code, ns);
9124           omp_workshare_flag = omp_workshare_save;
9125           break;
9126
9127         default:
9128           gfc_internal_error ("resolve_code(): Bad statement code");
9129         }
9130     }
9131
9132   cs_base = frame.prev;
9133 }
9134
9135
9136 /* Resolve initial values and make sure they are compatible with
9137    the variable.  */
9138
9139 static void
9140 resolve_values (gfc_symbol *sym)
9141 {
9142   gfc_try t;
9143
9144   if (sym->value == NULL)
9145     return;
9146
9147   if (sym->value->expr_type == EXPR_STRUCTURE)
9148     t= resolve_structure_cons (sym->value, 1);
9149   else 
9150     t = gfc_resolve_expr (sym->value);
9151
9152   if (t == FAILURE)
9153     return;
9154
9155   gfc_check_assign_symbol (sym, sym->value);
9156 }
9157
9158
9159 /* Verify the binding labels for common blocks that are BIND(C).  The label
9160    for a BIND(C) common block must be identical in all scoping units in which
9161    the common block is declared.  Further, the binding label can not collide
9162    with any other global entity in the program.  */
9163
9164 static void
9165 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9166 {
9167   if (comm_block_tree->n.common->is_bind_c == 1)
9168     {
9169       gfc_gsymbol *binding_label_gsym;
9170       gfc_gsymbol *comm_name_gsym;
9171
9172       /* See if a global symbol exists by the common block's name.  It may
9173          be NULL if the common block is use-associated.  */
9174       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9175                                          comm_block_tree->n.common->name);
9176       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9177         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9178                    "with the global entity '%s' at %L",
9179                    comm_block_tree->n.common->binding_label,
9180                    comm_block_tree->n.common->name,
9181                    &(comm_block_tree->n.common->where),
9182                    comm_name_gsym->name, &(comm_name_gsym->where));
9183       else if (comm_name_gsym != NULL
9184                && strcmp (comm_name_gsym->name,
9185                           comm_block_tree->n.common->name) == 0)
9186         {
9187           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9188              as expected.  */
9189           if (comm_name_gsym->binding_label == NULL)
9190             /* No binding label for common block stored yet; save this one.  */
9191             comm_name_gsym->binding_label =
9192               comm_block_tree->n.common->binding_label;
9193           else
9194             if (strcmp (comm_name_gsym->binding_label,
9195                         comm_block_tree->n.common->binding_label) != 0)
9196               {
9197                 /* Common block names match but binding labels do not.  */
9198                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9199                            "does not match the binding label '%s' for common "
9200                            "block '%s' at %L",
9201                            comm_block_tree->n.common->binding_label,
9202                            comm_block_tree->n.common->name,
9203                            &(comm_block_tree->n.common->where),
9204                            comm_name_gsym->binding_label,
9205                            comm_name_gsym->name,
9206                            &(comm_name_gsym->where));
9207                 return;
9208               }
9209         }
9210
9211       /* There is no binding label (NAME="") so we have nothing further to
9212          check and nothing to add as a global symbol for the label.  */
9213       if (comm_block_tree->n.common->binding_label[0] == '\0' )
9214         return;
9215       
9216       binding_label_gsym =
9217         gfc_find_gsymbol (gfc_gsym_root,
9218                           comm_block_tree->n.common->binding_label);
9219       if (binding_label_gsym == NULL)
9220         {
9221           /* Need to make a global symbol for the binding label to prevent
9222              it from colliding with another.  */
9223           binding_label_gsym =
9224             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9225           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9226           binding_label_gsym->type = GSYM_COMMON;
9227         }
9228       else
9229         {
9230           /* If comm_name_gsym is NULL, the name common block is use
9231              associated and the name could be colliding.  */
9232           if (binding_label_gsym->type != GSYM_COMMON)
9233             gfc_error ("Binding label '%s' for common block '%s' at %L "
9234                        "collides with the global entity '%s' at %L",
9235                        comm_block_tree->n.common->binding_label,
9236                        comm_block_tree->n.common->name,
9237                        &(comm_block_tree->n.common->where),
9238                        binding_label_gsym->name,
9239                        &(binding_label_gsym->where));
9240           else if (comm_name_gsym != NULL
9241                    && (strcmp (binding_label_gsym->name,
9242                                comm_name_gsym->binding_label) != 0)
9243                    && (strcmp (binding_label_gsym->sym_name,
9244                                comm_name_gsym->name) != 0))
9245             gfc_error ("Binding label '%s' for common block '%s' at %L "
9246                        "collides with global entity '%s' at %L",
9247                        binding_label_gsym->name, binding_label_gsym->sym_name,
9248                        &(comm_block_tree->n.common->where),
9249                        comm_name_gsym->name, &(comm_name_gsym->where));
9250         }
9251     }
9252   
9253   return;
9254 }
9255
9256
9257 /* Verify any BIND(C) derived types in the namespace so we can report errors
9258    for them once, rather than for each variable declared of that type.  */
9259
9260 static void
9261 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9262 {
9263   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9264       && derived_sym->attr.is_bind_c == 1)
9265     verify_bind_c_derived_type (derived_sym);
9266   
9267   return;
9268 }
9269
9270
9271 /* Verify that any binding labels used in a given namespace do not collide 
9272    with the names or binding labels of any global symbols.  */
9273
9274 static void
9275 gfc_verify_binding_labels (gfc_symbol *sym)
9276 {
9277   int has_error = 0;
9278   
9279   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
9280       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
9281     {
9282       gfc_gsymbol *bind_c_sym;
9283
9284       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9285       if (bind_c_sym != NULL 
9286           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9287         {
9288           if (sym->attr.if_source == IFSRC_DECL 
9289               && (bind_c_sym->type != GSYM_SUBROUTINE 
9290                   && bind_c_sym->type != GSYM_FUNCTION) 
9291               && ((sym->attr.contained == 1 
9292                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
9293                   || (sym->attr.use_assoc == 1 
9294                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9295             {
9296               /* Make sure global procedures don't collide with anything.  */
9297               gfc_error ("Binding label '%s' at %L collides with the global "
9298                          "entity '%s' at %L", sym->binding_label,
9299                          &(sym->declared_at), bind_c_sym->name,
9300                          &(bind_c_sym->where));
9301               has_error = 1;
9302             }
9303           else if (sym->attr.contained == 0 
9304                    && (sym->attr.if_source == IFSRC_IFBODY 
9305                        && sym->attr.flavor == FL_PROCEDURE) 
9306                    && (bind_c_sym->sym_name != NULL 
9307                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9308             {
9309               /* Make sure procedures in interface bodies don't collide.  */
9310               gfc_error ("Binding label '%s' in interface body at %L collides "
9311                          "with the global entity '%s' at %L",
9312                          sym->binding_label,
9313                          &(sym->declared_at), bind_c_sym->name,
9314                          &(bind_c_sym->where));
9315               has_error = 1;
9316             }
9317           else if (sym->attr.contained == 0 
9318                    && sym->attr.if_source == IFSRC_UNKNOWN)
9319             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9320                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
9321                 || sym->attr.use_assoc == 0)
9322               {
9323                 gfc_error ("Binding label '%s' at %L collides with global "
9324                            "entity '%s' at %L", sym->binding_label,
9325                            &(sym->declared_at), bind_c_sym->name,
9326                            &(bind_c_sym->where));
9327                 has_error = 1;
9328               }
9329
9330           if (has_error != 0)
9331             /* Clear the binding label to prevent checking multiple times.  */
9332             sym->binding_label[0] = '\0';
9333         }
9334       else if (bind_c_sym == NULL)
9335         {
9336           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9337           bind_c_sym->where = sym->declared_at;
9338           bind_c_sym->sym_name = sym->name;
9339
9340           if (sym->attr.use_assoc == 1)
9341             bind_c_sym->mod_name = sym->module;
9342           else
9343             if (sym->ns->proc_name != NULL)
9344               bind_c_sym->mod_name = sym->ns->proc_name->name;
9345
9346           if (sym->attr.contained == 0)
9347             {
9348               if (sym->attr.subroutine)
9349                 bind_c_sym->type = GSYM_SUBROUTINE;
9350               else if (sym->attr.function)
9351                 bind_c_sym->type = GSYM_FUNCTION;
9352             }
9353         }
9354     }
9355   return;
9356 }
9357
9358
9359 /* Resolve an index expression.  */
9360
9361 static gfc_try
9362 resolve_index_expr (gfc_expr *e)
9363 {
9364   if (gfc_resolve_expr (e) == FAILURE)
9365     return FAILURE;
9366
9367   if (gfc_simplify_expr (e, 0) == FAILURE)
9368     return FAILURE;
9369
9370   if (gfc_specification_expr (e) == FAILURE)
9371     return FAILURE;
9372
9373   return SUCCESS;
9374 }
9375
9376 /* Resolve a charlen structure.  */
9377
9378 static gfc_try
9379 resolve_charlen (gfc_charlen *cl)
9380 {
9381   int i, k;
9382
9383   if (cl->resolved)
9384     return SUCCESS;
9385
9386   cl->resolved = 1;
9387
9388   specification_expr = 1;
9389
9390   if (resolve_index_expr (cl->length) == FAILURE)
9391     {
9392       specification_expr = 0;
9393       return FAILURE;
9394     }
9395
9396   /* "If the character length parameter value evaluates to a negative
9397      value, the length of character entities declared is zero."  */
9398   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9399     {
9400       if (gfc_option.warn_surprising)
9401         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9402                          " the length has been set to zero",
9403                          &cl->length->where, i);
9404       gfc_replace_expr (cl->length,
9405                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9406     }
9407
9408   /* Check that the character length is not too large.  */
9409   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9410   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9411       && cl->length->ts.type == BT_INTEGER
9412       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9413     {
9414       gfc_error ("String length at %L is too large", &cl->length->where);
9415       return FAILURE;
9416     }
9417
9418   return SUCCESS;
9419 }
9420
9421
9422 /* Test for non-constant shape arrays.  */
9423
9424 static bool
9425 is_non_constant_shape_array (gfc_symbol *sym)
9426 {
9427   gfc_expr *e;
9428   int i;
9429   bool not_constant;
9430
9431   not_constant = false;
9432   if (sym->as != NULL)
9433     {
9434       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9435          has not been simplified; parameter array references.  Do the
9436          simplification now.  */
9437       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9438         {
9439           e = sym->as->lower[i];
9440           if (e && (resolve_index_expr (e) == FAILURE
9441                     || !gfc_is_constant_expr (e)))
9442             not_constant = true;
9443           e = sym->as->upper[i];
9444           if (e && (resolve_index_expr (e) == FAILURE
9445                     || !gfc_is_constant_expr (e)))
9446             not_constant = true;
9447         }
9448     }
9449   return not_constant;
9450 }
9451
9452 /* Given a symbol and an initialization expression, add code to initialize
9453    the symbol to the function entry.  */
9454 static void
9455 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9456 {
9457   gfc_expr *lval;
9458   gfc_code *init_st;
9459   gfc_namespace *ns = sym->ns;
9460
9461   /* Search for the function namespace if this is a contained
9462      function without an explicit result.  */
9463   if (sym->attr.function && sym == sym->result
9464       && sym->name != sym->ns->proc_name->name)
9465     {
9466       ns = ns->contained;
9467       for (;ns; ns = ns->sibling)
9468         if (strcmp (ns->proc_name->name, sym->name) == 0)
9469           break;
9470     }
9471
9472   if (ns == NULL)
9473     {
9474       gfc_free_expr (init);
9475       return;
9476     }
9477
9478   /* Build an l-value expression for the result.  */
9479   lval = gfc_lval_expr_from_sym (sym);
9480
9481   /* Add the code at scope entry.  */
9482   init_st = gfc_get_code ();
9483   init_st->next = ns->code;
9484   ns->code = init_st;
9485
9486   /* Assign the default initializer to the l-value.  */
9487   init_st->loc = sym->declared_at;
9488   init_st->op = EXEC_INIT_ASSIGN;
9489   init_st->expr1 = lval;
9490   init_st->expr2 = init;
9491 }
9492
9493 /* Assign the default initializer to a derived type variable or result.  */
9494
9495 static void
9496 apply_default_init (gfc_symbol *sym)
9497 {
9498   gfc_expr *init = NULL;
9499
9500   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9501     return;
9502
9503   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
9504     init = gfc_default_initializer (&sym->ts);
9505
9506   if (init == NULL)
9507     return;
9508
9509   build_init_assign (sym, init);
9510 }
9511
9512 /* Build an initializer for a local integer, real, complex, logical, or
9513    character variable, based on the command line flags finit-local-zero,
9514    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9515    null if the symbol should not have a default initialization.  */
9516 static gfc_expr *
9517 build_default_init_expr (gfc_symbol *sym)
9518 {
9519   int char_len;
9520   gfc_expr *init_expr;
9521   int i;
9522
9523   /* These symbols should never have a default initialization.  */
9524   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
9525       || sym->attr.external
9526       || sym->attr.dummy
9527       || sym->attr.pointer
9528       || sym->attr.in_equivalence
9529       || sym->attr.in_common
9530       || sym->attr.data
9531       || sym->module
9532       || sym->attr.cray_pointee
9533       || sym->attr.cray_pointer)
9534     return NULL;
9535
9536   /* Now we'll try to build an initializer expression.  */
9537   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
9538                                      &sym->declared_at);
9539
9540   /* We will only initialize integers, reals, complex, logicals, and
9541      characters, and only if the corresponding command-line flags
9542      were set.  Otherwise, we free init_expr and return null.  */
9543   switch (sym->ts.type)
9544     {    
9545     case BT_INTEGER:
9546       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9547         mpz_set_si (init_expr->value.integer, 
9548                          gfc_option.flag_init_integer_value);
9549       else
9550         {
9551           gfc_free_expr (init_expr);
9552           init_expr = NULL;
9553         }
9554       break;
9555
9556     case BT_REAL:
9557       switch (gfc_option.flag_init_real)
9558         {
9559         case GFC_INIT_REAL_SNAN:
9560           init_expr->is_snan = 1;
9561           /* Fall through.  */
9562         case GFC_INIT_REAL_NAN:
9563           mpfr_set_nan (init_expr->value.real);
9564           break;
9565
9566         case GFC_INIT_REAL_INF:
9567           mpfr_set_inf (init_expr->value.real, 1);
9568           break;
9569
9570         case GFC_INIT_REAL_NEG_INF:
9571           mpfr_set_inf (init_expr->value.real, -1);
9572           break;
9573
9574         case GFC_INIT_REAL_ZERO:
9575           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9576           break;
9577
9578         default:
9579           gfc_free_expr (init_expr);
9580           init_expr = NULL;
9581           break;
9582         }
9583       break;
9584           
9585     case BT_COMPLEX:
9586       switch (gfc_option.flag_init_real)
9587         {
9588         case GFC_INIT_REAL_SNAN:
9589           init_expr->is_snan = 1;
9590           /* Fall through.  */
9591         case GFC_INIT_REAL_NAN:
9592           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9593           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9594           break;
9595
9596         case GFC_INIT_REAL_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_NEG_INF:
9602           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9603           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9604           break;
9605
9606         case GFC_INIT_REAL_ZERO:
9607           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9608           break;
9609
9610         default:
9611           gfc_free_expr (init_expr);
9612           init_expr = NULL;
9613           break;
9614         }
9615       break;
9616           
9617     case BT_LOGICAL:
9618       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9619         init_expr->value.logical = 0;
9620       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9621         init_expr->value.logical = 1;
9622       else
9623         {
9624           gfc_free_expr (init_expr);
9625           init_expr = NULL;
9626         }
9627       break;
9628           
9629     case BT_CHARACTER:
9630       /* For characters, the length must be constant in order to 
9631          create a default initializer.  */
9632       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9633           && sym->ts.u.cl->length
9634           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9635         {
9636           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9637           init_expr->value.character.length = char_len;
9638           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9639           for (i = 0; i < char_len; i++)
9640             init_expr->value.character.string[i]
9641               = (unsigned char) gfc_option.flag_init_character_value;
9642         }
9643       else
9644         {
9645           gfc_free_expr (init_expr);
9646           init_expr = NULL;
9647         }
9648       break;
9649           
9650     default:
9651      gfc_free_expr (init_expr);
9652      init_expr = NULL;
9653     }
9654   return init_expr;
9655 }
9656
9657 /* Add an initialization expression to a local variable.  */
9658 static void
9659 apply_default_init_local (gfc_symbol *sym)
9660 {
9661   gfc_expr *init = NULL;
9662
9663   /* The symbol should be a variable or a function return value.  */
9664   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9665       || (sym->attr.function && sym->result != sym))
9666     return;
9667
9668   /* Try to build the initializer expression.  If we can't initialize
9669      this symbol, then init will be NULL.  */
9670   init = build_default_init_expr (sym);
9671   if (init == NULL)
9672     return;
9673
9674   /* For saved variables, we don't want to add an initializer at 
9675      function entry, so we just add a static initializer.  */
9676   if (sym->attr.save || sym->ns->save_all 
9677       || gfc_option.flag_max_stack_var_size == 0)
9678     {
9679       /* Don't clobber an existing initializer!  */
9680       gcc_assert (sym->value == NULL);
9681       sym->value = init;
9682       return;
9683     }
9684
9685   build_init_assign (sym, init);
9686 }
9687
9688 /* Resolution of common features of flavors variable and procedure.  */
9689
9690 static gfc_try
9691 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9692 {
9693   /* Constraints on deferred shape variable.  */
9694   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9695     {
9696       if (sym->attr.allocatable)
9697         {
9698           if (sym->attr.dimension)
9699             {
9700               gfc_error ("Allocatable array '%s' at %L must have "
9701                          "a deferred shape", sym->name, &sym->declared_at);
9702               return FAILURE;
9703             }
9704           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9705                                    "may not be ALLOCATABLE", sym->name,
9706                                    &sym->declared_at) == FAILURE)
9707             return FAILURE;
9708         }
9709
9710       if (sym->attr.pointer && sym->attr.dimension)
9711         {
9712           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
9713                      sym->name, &sym->declared_at);
9714           return FAILURE;
9715         }
9716     }
9717   else
9718     {
9719       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
9720           && !sym->attr.dummy && sym->ts.type != BT_CLASS && !sym->assoc)
9721         {
9722           gfc_error ("Array '%s' at %L cannot have a deferred shape",
9723                      sym->name, &sym->declared_at);
9724           return FAILURE;
9725          }
9726     }
9727
9728   /* Constraints on polymorphic variables.  */
9729   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
9730     {
9731       /* F03:C502.  */
9732       if (sym->attr.class_ok
9733           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
9734         {
9735           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
9736                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
9737                      &sym->declared_at);
9738           return FAILURE;
9739         }
9740
9741       /* F03:C509.  */
9742       /* Assume that use associated symbols were checked in the module ns.
9743          Class-variables that are associate-names are also something special
9744          and excepted from the test.  */
9745       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
9746         {
9747           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
9748                      "or pointer", sym->name, &sym->declared_at);
9749           return FAILURE;
9750         }
9751     }
9752     
9753   return SUCCESS;
9754 }
9755
9756
9757 /* Additional checks for symbols with flavor variable and derived
9758    type.  To be called from resolve_fl_variable.  */
9759
9760 static gfc_try
9761 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
9762 {
9763   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
9764
9765   /* Check to see if a derived type is blocked from being host
9766      associated by the presence of another class I symbol in the same
9767      namespace.  14.6.1.3 of the standard and the discussion on
9768      comp.lang.fortran.  */
9769   if (sym->ns != sym->ts.u.derived->ns
9770       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
9771     {
9772       gfc_symbol *s;
9773       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
9774       if (s && s->attr.flavor != FL_DERIVED)
9775         {
9776           gfc_error ("The type '%s' cannot be host associated at %L "
9777                      "because it is blocked by an incompatible object "
9778                      "of the same name declared at %L",
9779                      sym->ts.u.derived->name, &sym->declared_at,
9780                      &s->declared_at);
9781           return FAILURE;
9782         }
9783     }
9784
9785   /* 4th constraint in section 11.3: "If an object of a type for which
9786      component-initialization is specified (R429) appears in the
9787      specification-part of a module and does not have the ALLOCATABLE
9788      or POINTER attribute, the object shall have the SAVE attribute."
9789
9790      The check for initializers is performed with
9791      gfc_has_default_initializer because gfc_default_initializer generates
9792      a hidden default for allocatable components.  */
9793   if (!(sym->value || no_init_flag) && sym->ns->proc_name
9794       && sym->ns->proc_name->attr.flavor == FL_MODULE
9795       && !sym->ns->save_all && !sym->attr.save
9796       && !sym->attr.pointer && !sym->attr.allocatable
9797       && gfc_has_default_initializer (sym->ts.u.derived)
9798       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
9799                          "module variable '%s' at %L, needed due to "
9800                          "the default initialization", sym->name,
9801                          &sym->declared_at) == FAILURE)
9802     return FAILURE;
9803
9804   /* Assign default initializer.  */
9805   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
9806       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
9807     {
9808       sym->value = gfc_default_initializer (&sym->ts);
9809     }
9810
9811   return SUCCESS;
9812 }
9813
9814
9815 /* Resolve symbols with flavor variable.  */
9816
9817 static gfc_try
9818 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
9819 {
9820   int no_init_flag, automatic_flag;
9821   gfc_expr *e;
9822   const char *auto_save_msg;
9823
9824   auto_save_msg = "Automatic object '%s' at %L cannot have the "
9825                   "SAVE attribute";
9826
9827   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9828     return FAILURE;
9829
9830   /* Set this flag to check that variables are parameters of all entries.
9831      This check is effected by the call to gfc_resolve_expr through
9832      is_non_constant_shape_array.  */
9833   specification_expr = 1;
9834
9835   if (sym->ns->proc_name
9836       && (sym->ns->proc_name->attr.flavor == FL_MODULE
9837           || sym->ns->proc_name->attr.is_main_program)
9838       && !sym->attr.use_assoc
9839       && !sym->attr.allocatable
9840       && !sym->attr.pointer
9841       && is_non_constant_shape_array (sym))
9842     {
9843       /* The shape of a main program or module array needs to be
9844          constant.  */
9845       gfc_error ("The module or main program array '%s' at %L must "
9846                  "have constant shape", sym->name, &sym->declared_at);
9847       specification_expr = 0;
9848       return FAILURE;
9849     }
9850
9851   if (sym->ts.type == BT_CHARACTER)
9852     {
9853       /* Make sure that character string variables with assumed length are
9854          dummy arguments.  */
9855       e = sym->ts.u.cl->length;
9856       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
9857         {
9858           gfc_error ("Entity with assumed character length at %L must be a "
9859                      "dummy argument or a PARAMETER", &sym->declared_at);
9860           return FAILURE;
9861         }
9862
9863       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
9864         {
9865           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9866           return FAILURE;
9867         }
9868
9869       if (!gfc_is_constant_expr (e)
9870           && !(e->expr_type == EXPR_VARIABLE
9871                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
9872           && sym->ns->proc_name
9873           && (sym->ns->proc_name->attr.flavor == FL_MODULE
9874               || sym->ns->proc_name->attr.is_main_program)
9875           && !sym->attr.use_assoc)
9876         {
9877           gfc_error ("'%s' at %L must have constant character length "
9878                      "in this context", sym->name, &sym->declared_at);
9879           return FAILURE;
9880         }
9881     }
9882
9883   if (sym->value == NULL && sym->attr.referenced)
9884     apply_default_init_local (sym); /* Try to apply a default initialization.  */
9885
9886   /* Determine if the symbol may not have an initializer.  */
9887   no_init_flag = automatic_flag = 0;
9888   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
9889       || sym->attr.intrinsic || sym->attr.result)
9890     no_init_flag = 1;
9891   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
9892            && is_non_constant_shape_array (sym))
9893     {
9894       no_init_flag = automatic_flag = 1;
9895
9896       /* Also, they must not have the SAVE attribute.
9897          SAVE_IMPLICIT is checked below.  */
9898       if (sym->attr.save == SAVE_EXPLICIT)
9899         {
9900           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9901           return FAILURE;
9902         }
9903     }
9904
9905   /* Ensure that any initializer is simplified.  */
9906   if (sym->value)
9907     gfc_simplify_expr (sym->value, 1);
9908
9909   /* Reject illegal initializers.  */
9910   if (!sym->mark && sym->value)
9911     {
9912       if (sym->attr.allocatable)
9913         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
9914                    sym->name, &sym->declared_at);
9915       else if (sym->attr.external)
9916         gfc_error ("External '%s' at %L cannot have an initializer",
9917                    sym->name, &sym->declared_at);
9918       else if (sym->attr.dummy
9919         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
9920         gfc_error ("Dummy '%s' at %L cannot have an initializer",
9921                    sym->name, &sym->declared_at);
9922       else if (sym->attr.intrinsic)
9923         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
9924                    sym->name, &sym->declared_at);
9925       else if (sym->attr.result)
9926         gfc_error ("Function result '%s' at %L cannot have an initializer",
9927                    sym->name, &sym->declared_at);
9928       else if (automatic_flag)
9929         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
9930                    sym->name, &sym->declared_at);
9931       else
9932         goto no_init_error;
9933       return FAILURE;
9934     }
9935
9936 no_init_error:
9937   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
9938     return resolve_fl_variable_derived (sym, no_init_flag);
9939
9940   return SUCCESS;
9941 }
9942
9943
9944 /* Resolve a procedure.  */
9945
9946 static gfc_try
9947 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
9948 {
9949   gfc_formal_arglist *arg;
9950
9951   if (sym->attr.function
9952       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9953     return FAILURE;
9954
9955   if (sym->ts.type == BT_CHARACTER)
9956     {
9957       gfc_charlen *cl = sym->ts.u.cl;
9958
9959       if (cl && cl->length && gfc_is_constant_expr (cl->length)
9960              && resolve_charlen (cl) == FAILURE)
9961         return FAILURE;
9962
9963       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
9964           && sym->attr.proc == PROC_ST_FUNCTION)
9965         {
9966           gfc_error ("Character-valued statement function '%s' at %L must "
9967                      "have constant length", sym->name, &sym->declared_at);
9968           return FAILURE;
9969         }
9970     }
9971
9972   /* Ensure that derived type for are not of a private type.  Internal
9973      module procedures are excluded by 2.2.3.3 - i.e., they are not
9974      externally accessible and can access all the objects accessible in
9975      the host.  */
9976   if (!(sym->ns->parent
9977         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
9978       && gfc_check_access(sym->attr.access, sym->ns->default_access))
9979     {
9980       gfc_interface *iface;
9981
9982       for (arg = sym->formal; arg; arg = arg->next)
9983         {
9984           if (arg->sym
9985               && arg->sym->ts.type == BT_DERIVED
9986               && !arg->sym->ts.u.derived->attr.use_assoc
9987               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9988                                     arg->sym->ts.u.derived->ns->default_access)
9989               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
9990                                  "PRIVATE type and cannot be a dummy argument"
9991                                  " of '%s', which is PUBLIC at %L",
9992                                  arg->sym->name, sym->name, &sym->declared_at)
9993                  == FAILURE)
9994             {
9995               /* Stop this message from recurring.  */
9996               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9997               return FAILURE;
9998             }
9999         }
10000
10001       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10002          PRIVATE to the containing module.  */
10003       for (iface = sym->generic; iface; iface = iface->next)
10004         {
10005           for (arg = iface->sym->formal; arg; arg = arg->next)
10006             {
10007               if (arg->sym
10008                   && arg->sym->ts.type == BT_DERIVED
10009                   && !arg->sym->ts.u.derived->attr.use_assoc
10010                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10011                                         arg->sym->ts.u.derived->ns->default_access)
10012                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10013                                      "'%s' in PUBLIC interface '%s' at %L "
10014                                      "takes dummy arguments of '%s' which is "
10015                                      "PRIVATE", iface->sym->name, sym->name,
10016                                      &iface->sym->declared_at,
10017                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10018                 {
10019                   /* Stop this message from recurring.  */
10020                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10021                   return FAILURE;
10022                 }
10023              }
10024         }
10025
10026       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10027          PRIVATE to the containing module.  */
10028       for (iface = sym->generic; iface; iface = iface->next)
10029         {
10030           for (arg = iface->sym->formal; arg; arg = arg->next)
10031             {
10032               if (arg->sym
10033                   && arg->sym->ts.type == BT_DERIVED
10034                   && !arg->sym->ts.u.derived->attr.use_assoc
10035                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
10036                                         arg->sym->ts.u.derived->ns->default_access)
10037                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10038                                      "'%s' in PUBLIC interface '%s' at %L "
10039                                      "takes dummy arguments of '%s' which is "
10040                                      "PRIVATE", iface->sym->name, sym->name,
10041                                      &iface->sym->declared_at,
10042                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10043                 {
10044                   /* Stop this message from recurring.  */
10045                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10046                   return FAILURE;
10047                 }
10048              }
10049         }
10050     }
10051
10052   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10053       && !sym->attr.proc_pointer)
10054     {
10055       gfc_error ("Function '%s' at %L cannot have an initializer",
10056                  sym->name, &sym->declared_at);
10057       return FAILURE;
10058     }
10059
10060   /* An external symbol may not have an initializer because it is taken to be
10061      a procedure. Exception: Procedure Pointers.  */
10062   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10063     {
10064       gfc_error ("External object '%s' at %L may not have an initializer",
10065                  sym->name, &sym->declared_at);
10066       return FAILURE;
10067     }
10068
10069   /* An elemental function is required to return a scalar 12.7.1  */
10070   if (sym->attr.elemental && sym->attr.function && sym->as)
10071     {
10072       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10073                  "result", sym->name, &sym->declared_at);
10074       /* Reset so that the error only occurs once.  */
10075       sym->attr.elemental = 0;
10076       return FAILURE;
10077     }
10078
10079   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10080      char-len-param shall not be array-valued, pointer-valued, recursive
10081      or pure.  ....snip... A character value of * may only be used in the
10082      following ways: (i) Dummy arg of procedure - dummy associates with
10083      actual length; (ii) To declare a named constant; or (iii) External
10084      function - but length must be declared in calling scoping unit.  */
10085   if (sym->attr.function
10086       && sym->ts.type == BT_CHARACTER
10087       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10088     {
10089       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10090           || (sym->attr.recursive) || (sym->attr.pure))
10091         {
10092           if (sym->as && sym->as->rank)
10093             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10094                        "array-valued", sym->name, &sym->declared_at);
10095
10096           if (sym->attr.pointer)
10097             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10098                        "pointer-valued", sym->name, &sym->declared_at);
10099
10100           if (sym->attr.pure)
10101             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10102                        "pure", sym->name, &sym->declared_at);
10103
10104           if (sym->attr.recursive)
10105             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10106                        "recursive", sym->name, &sym->declared_at);
10107
10108           return FAILURE;
10109         }
10110
10111       /* Appendix B.2 of the standard.  Contained functions give an
10112          error anyway.  Fixed-form is likely to be F77/legacy.  */
10113       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
10114         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10115                         "CHARACTER(*) function '%s' at %L",
10116                         sym->name, &sym->declared_at);
10117     }
10118
10119   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10120     {
10121       gfc_formal_arglist *curr_arg;
10122       int has_non_interop_arg = 0;
10123
10124       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10125                              sym->common_block) == FAILURE)
10126         {
10127           /* Clear these to prevent looking at them again if there was an
10128              error.  */
10129           sym->attr.is_bind_c = 0;
10130           sym->attr.is_c_interop = 0;
10131           sym->ts.is_c_interop = 0;
10132         }
10133       else
10134         {
10135           /* So far, no errors have been found.  */
10136           sym->attr.is_c_interop = 1;
10137           sym->ts.is_c_interop = 1;
10138         }
10139       
10140       curr_arg = sym->formal;
10141       while (curr_arg != NULL)
10142         {
10143           /* Skip implicitly typed dummy args here.  */
10144           if (curr_arg->sym->attr.implicit_type == 0)
10145             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
10146               /* If something is found to fail, record the fact so we
10147                  can mark the symbol for the procedure as not being
10148                  BIND(C) to try and prevent multiple errors being
10149                  reported.  */
10150               has_non_interop_arg = 1;
10151           
10152           curr_arg = curr_arg->next;
10153         }
10154
10155       /* See if any of the arguments were not interoperable and if so, clear
10156          the procedure symbol to prevent duplicate error messages.  */
10157       if (has_non_interop_arg != 0)
10158         {
10159           sym->attr.is_c_interop = 0;
10160           sym->ts.is_c_interop = 0;
10161           sym->attr.is_bind_c = 0;
10162         }
10163     }
10164   
10165   if (!sym->attr.proc_pointer)
10166     {
10167       if (sym->attr.save == SAVE_EXPLICIT)
10168         {
10169           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10170                      "in '%s' at %L", sym->name, &sym->declared_at);
10171           return FAILURE;
10172         }
10173       if (sym->attr.intent)
10174         {
10175           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10176                      "in '%s' at %L", sym->name, &sym->declared_at);
10177           return FAILURE;
10178         }
10179       if (sym->attr.subroutine && sym->attr.result)
10180         {
10181           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10182                      "in '%s' at %L", sym->name, &sym->declared_at);
10183           return FAILURE;
10184         }
10185       if (sym->attr.external && sym->attr.function
10186           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10187               || sym->attr.contained))
10188         {
10189           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10190                      "in '%s' at %L", sym->name, &sym->declared_at);
10191           return FAILURE;
10192         }
10193       if (strcmp ("ppr@", sym->name) == 0)
10194         {
10195           gfc_error ("Procedure pointer result '%s' at %L "
10196                      "is missing the pointer attribute",
10197                      sym->ns->proc_name->name, &sym->declared_at);
10198           return FAILURE;
10199         }
10200     }
10201
10202   return SUCCESS;
10203 }
10204
10205
10206 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10207    been defined and we now know their defined arguments, check that they fulfill
10208    the requirements of the standard for procedures used as finalizers.  */
10209
10210 static gfc_try
10211 gfc_resolve_finalizers (gfc_symbol* derived)
10212 {
10213   gfc_finalizer* list;
10214   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10215   gfc_try result = SUCCESS;
10216   bool seen_scalar = false;
10217
10218   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10219     return SUCCESS;
10220
10221   /* Walk over the list of finalizer-procedures, check them, and if any one
10222      does not fit in with the standard's definition, print an error and remove
10223      it from the list.  */
10224   prev_link = &derived->f2k_derived->finalizers;
10225   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10226     {
10227       gfc_symbol* arg;
10228       gfc_finalizer* i;
10229       int my_rank;
10230
10231       /* Skip this finalizer if we already resolved it.  */
10232       if (list->proc_tree)
10233         {
10234           prev_link = &(list->next);
10235           continue;
10236         }
10237
10238       /* Check this exists and is a SUBROUTINE.  */
10239       if (!list->proc_sym->attr.subroutine)
10240         {
10241           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10242                      list->proc_sym->name, &list->where);
10243           goto error;
10244         }
10245
10246       /* We should have exactly one argument.  */
10247       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10248         {
10249           gfc_error ("FINAL procedure at %L must have exactly one argument",
10250                      &list->where);
10251           goto error;
10252         }
10253       arg = list->proc_sym->formal->sym;
10254
10255       /* This argument must be of our type.  */
10256       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10257         {
10258           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10259                      &arg->declared_at, derived->name);
10260           goto error;
10261         }
10262
10263       /* It must neither be a pointer nor allocatable nor optional.  */
10264       if (arg->attr.pointer)
10265         {
10266           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10267                      &arg->declared_at);
10268           goto error;
10269         }
10270       if (arg->attr.allocatable)
10271         {
10272           gfc_error ("Argument of FINAL procedure at %L must not be"
10273                      " ALLOCATABLE", &arg->declared_at);
10274           goto error;
10275         }
10276       if (arg->attr.optional)
10277         {
10278           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10279                      &arg->declared_at);
10280           goto error;
10281         }
10282
10283       /* It must not be INTENT(OUT).  */
10284       if (arg->attr.intent == INTENT_OUT)
10285         {
10286           gfc_error ("Argument of FINAL procedure at %L must not be"
10287                      " INTENT(OUT)", &arg->declared_at);
10288           goto error;
10289         }
10290
10291       /* Warn if the procedure is non-scalar and not assumed shape.  */
10292       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10293           && arg->as->type != AS_ASSUMED_SHAPE)
10294         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10295                      " shape argument", &arg->declared_at);
10296
10297       /* Check that it does not match in kind and rank with a FINAL procedure
10298          defined earlier.  To really loop over the *earlier* declarations,
10299          we need to walk the tail of the list as new ones were pushed at the
10300          front.  */
10301       /* TODO: Handle kind parameters once they are implemented.  */
10302       my_rank = (arg->as ? arg->as->rank : 0);
10303       for (i = list->next; i; i = i->next)
10304         {
10305           /* Argument list might be empty; that is an error signalled earlier,
10306              but we nevertheless continued resolving.  */
10307           if (i->proc_sym->formal)
10308             {
10309               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10310               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10311               if (i_rank == my_rank)
10312                 {
10313                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10314                              " rank (%d) as '%s'",
10315                              list->proc_sym->name, &list->where, my_rank, 
10316                              i->proc_sym->name);
10317                   goto error;
10318                 }
10319             }
10320         }
10321
10322         /* Is this the/a scalar finalizer procedure?  */
10323         if (!arg->as || arg->as->rank == 0)
10324           seen_scalar = true;
10325
10326         /* Find the symtree for this procedure.  */
10327         gcc_assert (!list->proc_tree);
10328         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10329
10330         prev_link = &list->next;
10331         continue;
10332
10333         /* Remove wrong nodes immediately from the list so we don't risk any
10334            troubles in the future when they might fail later expectations.  */
10335 error:
10336         result = FAILURE;
10337         i = list;
10338         *prev_link = list->next;
10339         gfc_free_finalizer (i);
10340     }
10341
10342   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10343      were nodes in the list, must have been for arrays.  It is surely a good
10344      idea to have a scalar version there if there's something to finalize.  */
10345   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10346     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10347                  " defined at %L, suggest also scalar one",
10348                  derived->name, &derived->declared_at);
10349
10350   /* TODO:  Remove this error when finalization is finished.  */
10351   gfc_error ("Finalization at %L is not yet implemented",
10352              &derived->declared_at);
10353
10354   return result;
10355 }
10356
10357
10358 /* Check that it is ok for the typebound procedure proc to override the
10359    procedure old.  */
10360
10361 static gfc_try
10362 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
10363 {
10364   locus where;
10365   const gfc_symbol* proc_target;
10366   const gfc_symbol* old_target;
10367   unsigned proc_pass_arg, old_pass_arg, argpos;
10368   gfc_formal_arglist* proc_formal;
10369   gfc_formal_arglist* old_formal;
10370
10371   /* This procedure should only be called for non-GENERIC proc.  */
10372   gcc_assert (!proc->n.tb->is_generic);
10373
10374   /* If the overwritten procedure is GENERIC, this is an error.  */
10375   if (old->n.tb->is_generic)
10376     {
10377       gfc_error ("Can't overwrite GENERIC '%s' at %L",
10378                  old->name, &proc->n.tb->where);
10379       return FAILURE;
10380     }
10381
10382   where = proc->n.tb->where;
10383   proc_target = proc->n.tb->u.specific->n.sym;
10384   old_target = old->n.tb->u.specific->n.sym;
10385
10386   /* Check that overridden binding is not NON_OVERRIDABLE.  */
10387   if (old->n.tb->non_overridable)
10388     {
10389       gfc_error ("'%s' at %L overrides a procedure binding declared"
10390                  " NON_OVERRIDABLE", proc->name, &where);
10391       return FAILURE;
10392     }
10393
10394   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
10395   if (!old->n.tb->deferred && proc->n.tb->deferred)
10396     {
10397       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
10398                  " non-DEFERRED binding", proc->name, &where);
10399       return FAILURE;
10400     }
10401
10402   /* If the overridden binding is PURE, the overriding must be, too.  */
10403   if (old_target->attr.pure && !proc_target->attr.pure)
10404     {
10405       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
10406                  proc->name, &where);
10407       return FAILURE;
10408     }
10409
10410   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
10411      is not, the overriding must not be either.  */
10412   if (old_target->attr.elemental && !proc_target->attr.elemental)
10413     {
10414       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
10415                  " ELEMENTAL", proc->name, &where);
10416       return FAILURE;
10417     }
10418   if (!old_target->attr.elemental && proc_target->attr.elemental)
10419     {
10420       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
10421                  " be ELEMENTAL, either", proc->name, &where);
10422       return FAILURE;
10423     }
10424
10425   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
10426      SUBROUTINE.  */
10427   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
10428     {
10429       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
10430                  " SUBROUTINE", proc->name, &where);
10431       return FAILURE;
10432     }
10433
10434   /* If the overridden binding is a FUNCTION, the overriding must also be a
10435      FUNCTION and have the same characteristics.  */
10436   if (old_target->attr.function)
10437     {
10438       if (!proc_target->attr.function)
10439         {
10440           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
10441                      " FUNCTION", proc->name, &where);
10442           return FAILURE;
10443         }
10444
10445       /* FIXME:  Do more comprehensive checking (including, for instance, the
10446          rank and array-shape).  */
10447       gcc_assert (proc_target->result && old_target->result);
10448       if (!gfc_compare_types (&proc_target->result->ts,
10449                               &old_target->result->ts))
10450         {
10451           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
10452                      " matching result types", proc->name, &where);
10453           return FAILURE;
10454         }
10455     }
10456
10457   /* If the overridden binding is PUBLIC, the overriding one must not be
10458      PRIVATE.  */
10459   if (old->n.tb->access == ACCESS_PUBLIC
10460       && proc->n.tb->access == ACCESS_PRIVATE)
10461     {
10462       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
10463                  " PRIVATE", proc->name, &where);
10464       return FAILURE;
10465     }
10466
10467   /* Compare the formal argument lists of both procedures.  This is also abused
10468      to find the position of the passed-object dummy arguments of both
10469      bindings as at least the overridden one might not yet be resolved and we
10470      need those positions in the check below.  */
10471   proc_pass_arg = old_pass_arg = 0;
10472   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
10473     proc_pass_arg = 1;
10474   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
10475     old_pass_arg = 1;
10476   argpos = 1;
10477   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
10478        proc_formal && old_formal;
10479        proc_formal = proc_formal->next, old_formal = old_formal->next)
10480     {
10481       if (proc->n.tb->pass_arg
10482           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
10483         proc_pass_arg = argpos;
10484       if (old->n.tb->pass_arg
10485           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
10486         old_pass_arg = argpos;
10487
10488       /* Check that the names correspond.  */
10489       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
10490         {
10491           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
10492                      " to match the corresponding argument of the overridden"
10493                      " procedure", proc_formal->sym->name, proc->name, &where,
10494                      old_formal->sym->name);
10495           return FAILURE;
10496         }
10497
10498       /* Check that the types correspond if neither is the passed-object
10499          argument.  */
10500       /* FIXME:  Do more comprehensive testing here.  */
10501       if (proc_pass_arg != argpos && old_pass_arg != argpos
10502           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
10503         {
10504           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
10505                      "in respect to the overridden procedure",
10506                      proc_formal->sym->name, proc->name, &where);
10507           return FAILURE;
10508         }
10509
10510       ++argpos;
10511     }
10512   if (proc_formal || old_formal)
10513     {
10514       gfc_error ("'%s' at %L must have the same number of formal arguments as"
10515                  " the overridden procedure", proc->name, &where);
10516       return FAILURE;
10517     }
10518
10519   /* If the overridden binding is NOPASS, the overriding one must also be
10520      NOPASS.  */
10521   if (old->n.tb->nopass && !proc->n.tb->nopass)
10522     {
10523       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
10524                  " NOPASS", proc->name, &where);
10525       return FAILURE;
10526     }
10527
10528   /* If the overridden binding is PASS(x), the overriding one must also be
10529      PASS and the passed-object dummy arguments must correspond.  */
10530   if (!old->n.tb->nopass)
10531     {
10532       if (proc->n.tb->nopass)
10533         {
10534           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
10535                      " PASS", proc->name, &where);
10536           return FAILURE;
10537         }
10538
10539       if (proc_pass_arg != old_pass_arg)
10540         {
10541           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
10542                      " the same position as the passed-object dummy argument of"
10543                      " the overridden procedure", proc->name, &where);
10544           return FAILURE;
10545         }
10546     }
10547
10548   return SUCCESS;
10549 }
10550
10551
10552 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10553
10554 static gfc_try
10555 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10556                              const char* generic_name, locus where)
10557 {
10558   gfc_symbol* sym1;
10559   gfc_symbol* sym2;
10560
10561   gcc_assert (t1->specific && t2->specific);
10562   gcc_assert (!t1->specific->is_generic);
10563   gcc_assert (!t2->specific->is_generic);
10564
10565   sym1 = t1->specific->u.specific->n.sym;
10566   sym2 = t2->specific->u.specific->n.sym;
10567
10568   if (sym1 == sym2)
10569     return SUCCESS;
10570
10571   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10572   if (sym1->attr.subroutine != sym2->attr.subroutine
10573       || sym1->attr.function != sym2->attr.function)
10574     {
10575       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10576                  " GENERIC '%s' at %L",
10577                  sym1->name, sym2->name, generic_name, &where);
10578       return FAILURE;
10579     }
10580
10581   /* Compare the interfaces.  */
10582   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10583     {
10584       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10585                  sym1->name, sym2->name, generic_name, &where);
10586       return FAILURE;
10587     }
10588
10589   return SUCCESS;
10590 }
10591
10592
10593 /* Worker function for resolving a generic procedure binding; this is used to
10594    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10595
10596    The difference between those cases is finding possible inherited bindings
10597    that are overridden, as one has to look for them in tb_sym_root,
10598    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10599    the super-type and set p->overridden correctly.  */
10600
10601 static gfc_try
10602 resolve_tb_generic_targets (gfc_symbol* super_type,
10603                             gfc_typebound_proc* p, const char* name)
10604 {
10605   gfc_tbp_generic* target;
10606   gfc_symtree* first_target;
10607   gfc_symtree* inherited;
10608
10609   gcc_assert (p && p->is_generic);
10610
10611   /* Try to find the specific bindings for the symtrees in our target-list.  */
10612   gcc_assert (p->u.generic);
10613   for (target = p->u.generic; target; target = target->next)
10614     if (!target->specific)
10615       {
10616         gfc_typebound_proc* overridden_tbp;
10617         gfc_tbp_generic* g;
10618         const char* target_name;
10619
10620         target_name = target->specific_st->name;
10621
10622         /* Defined for this type directly.  */
10623         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
10624           {
10625             target->specific = target->specific_st->n.tb;
10626             goto specific_found;
10627           }
10628
10629         /* Look for an inherited specific binding.  */
10630         if (super_type)
10631           {
10632             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10633                                                  true, NULL);
10634
10635             if (inherited)
10636               {
10637                 gcc_assert (inherited->n.tb);
10638                 target->specific = inherited->n.tb;
10639                 goto specific_found;
10640               }
10641           }
10642
10643         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10644                    " at %L", target_name, name, &p->where);
10645         return FAILURE;
10646
10647         /* Once we've found the specific binding, check it is not ambiguous with
10648            other specifics already found or inherited for the same GENERIC.  */
10649 specific_found:
10650         gcc_assert (target->specific);
10651
10652         /* This must really be a specific binding!  */
10653         if (target->specific->is_generic)
10654           {
10655             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10656                        " '%s' is GENERIC, too", name, &p->where, target_name);
10657             return FAILURE;
10658           }
10659
10660         /* Check those already resolved on this type directly.  */
10661         for (g = p->u.generic; g; g = g->next)
10662           if (g != target && g->specific
10663               && check_generic_tbp_ambiguity (target, g, name, p->where)
10664                   == FAILURE)
10665             return FAILURE;
10666
10667         /* Check for ambiguity with inherited specific targets.  */
10668         for (overridden_tbp = p->overridden; overridden_tbp;
10669              overridden_tbp = overridden_tbp->overridden)
10670           if (overridden_tbp->is_generic)
10671             {
10672               for (g = overridden_tbp->u.generic; g; g = g->next)
10673                 {
10674                   gcc_assert (g->specific);
10675                   if (check_generic_tbp_ambiguity (target, g,
10676                                                    name, p->where) == FAILURE)
10677                     return FAILURE;
10678                 }
10679             }
10680       }
10681
10682   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10683   if (p->overridden && !p->overridden->is_generic)
10684     {
10685       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10686                  " the same name", name, &p->where);
10687       return FAILURE;
10688     }
10689
10690   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10691      all must have the same attributes here.  */
10692   first_target = p->u.generic->specific->u.specific;
10693   gcc_assert (first_target);
10694   p->subroutine = first_target->n.sym->attr.subroutine;
10695   p->function = first_target->n.sym->attr.function;
10696
10697   return SUCCESS;
10698 }
10699
10700
10701 /* Resolve a GENERIC procedure binding for a derived type.  */
10702
10703 static gfc_try
10704 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10705 {
10706   gfc_symbol* super_type;
10707
10708   /* Find the overridden binding if any.  */
10709   st->n.tb->overridden = NULL;
10710   super_type = gfc_get_derived_super_type (derived);
10711   if (super_type)
10712     {
10713       gfc_symtree* overridden;
10714       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10715                                             true, NULL);
10716
10717       if (overridden && overridden->n.tb)
10718         st->n.tb->overridden = overridden->n.tb;
10719     }
10720
10721   /* Resolve using worker function.  */
10722   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10723 }
10724
10725
10726 /* Retrieve the target-procedure of an operator binding and do some checks in
10727    common for intrinsic and user-defined type-bound operators.  */
10728
10729 static gfc_symbol*
10730 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10731 {
10732   gfc_symbol* target_proc;
10733
10734   gcc_assert (target->specific && !target->specific->is_generic);
10735   target_proc = target->specific->u.specific->n.sym;
10736   gcc_assert (target_proc);
10737
10738   /* All operator bindings must have a passed-object dummy argument.  */
10739   if (target->specific->nopass)
10740     {
10741       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10742       return NULL;
10743     }
10744
10745   return target_proc;
10746 }
10747
10748
10749 /* Resolve a type-bound intrinsic operator.  */
10750
10751 static gfc_try
10752 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10753                                 gfc_typebound_proc* p)
10754 {
10755   gfc_symbol* super_type;
10756   gfc_tbp_generic* target;
10757   
10758   /* If there's already an error here, do nothing (but don't fail again).  */
10759   if (p->error)
10760     return SUCCESS;
10761
10762   /* Operators should always be GENERIC bindings.  */
10763   gcc_assert (p->is_generic);
10764
10765   /* Look for an overridden binding.  */
10766   super_type = gfc_get_derived_super_type (derived);
10767   if (super_type && super_type->f2k_derived)
10768     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10769                                                      op, true, NULL);
10770   else
10771     p->overridden = NULL;
10772
10773   /* Resolve general GENERIC properties using worker function.  */
10774   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10775     goto error;
10776
10777   /* Check the targets to be procedures of correct interface.  */
10778   for (target = p->u.generic; target; target = target->next)
10779     {
10780       gfc_symbol* target_proc;
10781
10782       target_proc = get_checked_tb_operator_target (target, p->where);
10783       if (!target_proc)
10784         goto error;
10785
10786       if (!gfc_check_operator_interface (target_proc, op, p->where))
10787         goto error;
10788     }
10789
10790   return SUCCESS;
10791
10792 error:
10793   p->error = 1;
10794   return FAILURE;
10795 }
10796
10797
10798 /* Resolve a type-bound user operator (tree-walker callback).  */
10799
10800 static gfc_symbol* resolve_bindings_derived;
10801 static gfc_try resolve_bindings_result;
10802
10803 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10804
10805 static void
10806 resolve_typebound_user_op (gfc_symtree* stree)
10807 {
10808   gfc_symbol* super_type;
10809   gfc_tbp_generic* target;
10810
10811   gcc_assert (stree && stree->n.tb);
10812
10813   if (stree->n.tb->error)
10814     return;
10815
10816   /* Operators should always be GENERIC bindings.  */
10817   gcc_assert (stree->n.tb->is_generic);
10818
10819   /* Find overridden procedure, if any.  */
10820   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10821   if (super_type && super_type->f2k_derived)
10822     {
10823       gfc_symtree* overridden;
10824       overridden = gfc_find_typebound_user_op (super_type, NULL,
10825                                                stree->name, true, NULL);
10826
10827       if (overridden && overridden->n.tb)
10828         stree->n.tb->overridden = overridden->n.tb;
10829     }
10830   else
10831     stree->n.tb->overridden = NULL;
10832
10833   /* Resolve basically using worker function.  */
10834   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10835         == FAILURE)
10836     goto error;
10837
10838   /* Check the targets to be functions of correct interface.  */
10839   for (target = stree->n.tb->u.generic; target; target = target->next)
10840     {
10841       gfc_symbol* target_proc;
10842
10843       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
10844       if (!target_proc)
10845         goto error;
10846
10847       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
10848         goto error;
10849     }
10850
10851   return;
10852
10853 error:
10854   resolve_bindings_result = FAILURE;
10855   stree->n.tb->error = 1;
10856 }
10857
10858
10859 /* Resolve the type-bound procedures for a derived type.  */
10860
10861 static void
10862 resolve_typebound_procedure (gfc_symtree* stree)
10863 {
10864   gfc_symbol* proc;
10865   locus where;
10866   gfc_symbol* me_arg;
10867   gfc_symbol* super_type;
10868   gfc_component* comp;
10869
10870   gcc_assert (stree);
10871
10872   /* Undefined specific symbol from GENERIC target definition.  */
10873   if (!stree->n.tb)
10874     return;
10875
10876   if (stree->n.tb->error)
10877     return;
10878
10879   /* If this is a GENERIC binding, use that routine.  */
10880   if (stree->n.tb->is_generic)
10881     {
10882       if (resolve_typebound_generic (resolve_bindings_derived, stree)
10883             == FAILURE)
10884         goto error;
10885       return;
10886     }
10887
10888   /* Get the target-procedure to check it.  */
10889   gcc_assert (!stree->n.tb->is_generic);
10890   gcc_assert (stree->n.tb->u.specific);
10891   proc = stree->n.tb->u.specific->n.sym;
10892   where = stree->n.tb->where;
10893
10894   /* Default access should already be resolved from the parser.  */
10895   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
10896
10897   /* It should be a module procedure or an external procedure with explicit
10898      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
10899   if ((!proc->attr.subroutine && !proc->attr.function)
10900       || (proc->attr.proc != PROC_MODULE
10901           && proc->attr.if_source != IFSRC_IFBODY)
10902       || (proc->attr.abstract && !stree->n.tb->deferred))
10903     {
10904       gfc_error ("'%s' must be a module procedure or an external procedure with"
10905                  " an explicit interface at %L", proc->name, &where);
10906       goto error;
10907     }
10908   stree->n.tb->subroutine = proc->attr.subroutine;
10909   stree->n.tb->function = proc->attr.function;
10910
10911   /* Find the super-type of the current derived type.  We could do this once and
10912      store in a global if speed is needed, but as long as not I believe this is
10913      more readable and clearer.  */
10914   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10915
10916   /* If PASS, resolve and check arguments if not already resolved / loaded
10917      from a .mod file.  */
10918   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
10919     {
10920       if (stree->n.tb->pass_arg)
10921         {
10922           gfc_formal_arglist* i;
10923
10924           /* If an explicit passing argument name is given, walk the arg-list
10925              and look for it.  */
10926
10927           me_arg = NULL;
10928           stree->n.tb->pass_arg_num = 1;
10929           for (i = proc->formal; i; i = i->next)
10930             {
10931               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
10932                 {
10933                   me_arg = i->sym;
10934                   break;
10935                 }
10936               ++stree->n.tb->pass_arg_num;
10937             }
10938
10939           if (!me_arg)
10940             {
10941               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
10942                          " argument '%s'",
10943                          proc->name, stree->n.tb->pass_arg, &where,
10944                          stree->n.tb->pass_arg);
10945               goto error;
10946             }
10947         }
10948       else
10949         {
10950           /* Otherwise, take the first one; there should in fact be at least
10951              one.  */
10952           stree->n.tb->pass_arg_num = 1;
10953           if (!proc->formal)
10954             {
10955               gfc_error ("Procedure '%s' with PASS at %L must have at"
10956                          " least one argument", proc->name, &where);
10957               goto error;
10958             }
10959           me_arg = proc->formal->sym;
10960         }
10961
10962       /* Now check that the argument-type matches and the passed-object
10963          dummy argument is generally fine.  */
10964
10965       gcc_assert (me_arg);
10966
10967       if (me_arg->ts.type != BT_CLASS)
10968         {
10969           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10970                      " at %L", proc->name, &where);
10971           goto error;
10972         }
10973
10974       if (CLASS_DATA (me_arg)->ts.u.derived
10975           != resolve_bindings_derived)
10976         {
10977           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10978                      " the derived-type '%s'", me_arg->name, proc->name,
10979                      me_arg->name, &where, resolve_bindings_derived->name);
10980           goto error;
10981         }
10982   
10983       gcc_assert (me_arg->ts.type == BT_CLASS);
10984       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
10985         {
10986           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
10987                      " scalar", proc->name, &where);
10988           goto error;
10989         }
10990       if (CLASS_DATA (me_arg)->attr.allocatable)
10991         {
10992           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10993                      " be ALLOCATABLE", proc->name, &where);
10994           goto error;
10995         }
10996       if (CLASS_DATA (me_arg)->attr.class_pointer)
10997         {
10998           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10999                      " be POINTER", proc->name, &where);
11000           goto error;
11001         }
11002     }
11003
11004   /* If we are extending some type, check that we don't override a procedure
11005      flagged NON_OVERRIDABLE.  */
11006   stree->n.tb->overridden = NULL;
11007   if (super_type)
11008     {
11009       gfc_symtree* overridden;
11010       overridden = gfc_find_typebound_proc (super_type, NULL,
11011                                             stree->name, true, NULL);
11012
11013       if (overridden && overridden->n.tb)
11014         stree->n.tb->overridden = overridden->n.tb;
11015
11016       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
11017         goto error;
11018     }
11019
11020   /* See if there's a name collision with a component directly in this type.  */
11021   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11022     if (!strcmp (comp->name, stree->name))
11023       {
11024         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11025                    " '%s'",
11026                    stree->name, &where, resolve_bindings_derived->name);
11027         goto error;
11028       }
11029
11030   /* Try to find a name collision with an inherited component.  */
11031   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11032     {
11033       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11034                  " component of '%s'",
11035                  stree->name, &where, resolve_bindings_derived->name);
11036       goto error;
11037     }
11038
11039   stree->n.tb->error = 0;
11040   return;
11041
11042 error:
11043   resolve_bindings_result = FAILURE;
11044   stree->n.tb->error = 1;
11045 }
11046
11047
11048 static gfc_try
11049 resolve_typebound_procedures (gfc_symbol* derived)
11050 {
11051   int op;
11052
11053   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11054     return SUCCESS;
11055
11056   resolve_bindings_derived = derived;
11057   resolve_bindings_result = SUCCESS;
11058
11059   /* Make sure the vtab has been generated.  */
11060   gfc_find_derived_vtab (derived);
11061
11062   if (derived->f2k_derived->tb_sym_root)
11063     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11064                           &resolve_typebound_procedure);
11065
11066   if (derived->f2k_derived->tb_uop_root)
11067     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11068                           &resolve_typebound_user_op);
11069
11070   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11071     {
11072       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11073       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11074                                                p) == FAILURE)
11075         resolve_bindings_result = FAILURE;
11076     }
11077
11078   return resolve_bindings_result;
11079 }
11080
11081
11082 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11083    to give all identical derived types the same backend_decl.  */
11084 static void
11085 add_dt_to_dt_list (gfc_symbol *derived)
11086 {
11087   gfc_dt_list *dt_list;
11088
11089   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11090     if (derived == dt_list->derived)
11091       break;
11092
11093   if (dt_list == NULL)
11094     {
11095       dt_list = gfc_get_dt_list ();
11096       dt_list->next = gfc_derived_types;
11097       dt_list->derived = derived;
11098       gfc_derived_types = dt_list;
11099     }
11100 }
11101
11102
11103 /* Ensure that a derived-type is really not abstract, meaning that every
11104    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11105
11106 static gfc_try
11107 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11108 {
11109   if (!st)
11110     return SUCCESS;
11111
11112   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11113     return FAILURE;
11114   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11115     return FAILURE;
11116
11117   if (st->n.tb && st->n.tb->deferred)
11118     {
11119       gfc_symtree* overriding;
11120       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11121       if (!overriding)
11122         return FAILURE;
11123       gcc_assert (overriding->n.tb);
11124       if (overriding->n.tb->deferred)
11125         {
11126           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11127                      " '%s' is DEFERRED and not overridden",
11128                      sub->name, &sub->declared_at, st->name);
11129           return FAILURE;
11130         }
11131     }
11132
11133   return SUCCESS;
11134 }
11135
11136 static gfc_try
11137 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11138 {
11139   /* The algorithm used here is to recursively travel up the ancestry of sub
11140      and for each ancestor-type, check all bindings.  If any of them is
11141      DEFERRED, look it up starting from sub and see if the found (overriding)
11142      binding is not DEFERRED.
11143      This is not the most efficient way to do this, but it should be ok and is
11144      clearer than something sophisticated.  */
11145
11146   gcc_assert (ancestor && !sub->attr.abstract);
11147   
11148   if (!ancestor->attr.abstract)
11149     return SUCCESS;
11150
11151   /* Walk bindings of this ancestor.  */
11152   if (ancestor->f2k_derived)
11153     {
11154       gfc_try t;
11155       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11156       if (t == FAILURE)
11157         return FAILURE;
11158     }
11159
11160   /* Find next ancestor type and recurse on it.  */
11161   ancestor = gfc_get_derived_super_type (ancestor);
11162   if (ancestor)
11163     return ensure_not_abstract (sub, ancestor);
11164
11165   return SUCCESS;
11166 }
11167
11168
11169 /* Resolve the components of a derived type.  */
11170
11171 static gfc_try
11172 resolve_fl_derived (gfc_symbol *sym)
11173 {
11174   gfc_symbol* super_type;
11175   gfc_component *c;
11176
11177   super_type = gfc_get_derived_super_type (sym);
11178   
11179   if (sym->attr.is_class && sym->ts.u.derived == NULL)
11180     {
11181       /* Fix up incomplete CLASS symbols.  */
11182       gfc_component *data = gfc_find_component (sym, "$data", true, true);
11183       gfc_component *vptr = gfc_find_component (sym, "$vptr", true, true);
11184       if (vptr->ts.u.derived == NULL)
11185         {
11186           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
11187           gcc_assert (vtab);
11188           vptr->ts.u.derived = vtab->ts.u.derived;
11189         }
11190     }
11191
11192   /* F2008, C432. */
11193   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11194     {
11195       gfc_error ("As extending type '%s' at %L has a coarray component, "
11196                  "parent type '%s' shall also have one", sym->name,
11197                  &sym->declared_at, super_type->name);
11198       return FAILURE;
11199     }
11200
11201   /* Ensure the extended type gets resolved before we do.  */
11202   if (super_type && resolve_fl_derived (super_type) == FAILURE)
11203     return FAILURE;
11204
11205   /* An ABSTRACT type must be extensible.  */
11206   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11207     {
11208       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11209                  sym->name, &sym->declared_at);
11210       return FAILURE;
11211     }
11212
11213   for (c = sym->components; c != NULL; c = c->next)
11214     {
11215       /* F2008, C442.  */
11216       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
11217           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11218         {
11219           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11220                      "deferred shape", c->name, &c->loc);
11221           return FAILURE;
11222         }
11223
11224       /* F2008, C443.  */
11225       if (c->attr.codimension && c->ts.type == BT_DERIVED
11226           && c->ts.u.derived->ts.is_iso_c)
11227         {
11228           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11229                      "shall not be a coarray", c->name, &c->loc);
11230           return FAILURE;
11231         }
11232
11233       /* F2008, C444.  */
11234       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11235           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11236               || c->attr.allocatable))
11237         {
11238           gfc_error ("Component '%s' at %L with coarray component "
11239                      "shall be a nonpointer, nonallocatable scalar",
11240                      c->name, &c->loc);
11241           return FAILURE;
11242         }
11243
11244       /* F2008, C448.  */
11245       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11246         {
11247           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11248                      "is not an array pointer", c->name, &c->loc);
11249           return FAILURE;
11250         }
11251
11252       if (c->attr.proc_pointer && c->ts.interface)
11253         {
11254           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11255             gfc_error ("Interface '%s', used by procedure pointer component "
11256                        "'%s' at %L, is declared in a later PROCEDURE statement",
11257                        c->ts.interface->name, c->name, &c->loc);
11258
11259           /* Get the attributes from the interface (now resolved).  */
11260           if (c->ts.interface->attr.if_source
11261               || c->ts.interface->attr.intrinsic)
11262             {
11263               gfc_symbol *ifc = c->ts.interface;
11264
11265               if (ifc->formal && !ifc->formal_ns)
11266                 resolve_symbol (ifc);
11267
11268               if (ifc->attr.intrinsic)
11269                 resolve_intrinsic (ifc, &ifc->declared_at);
11270
11271               if (ifc->result)
11272                 {
11273                   c->ts = ifc->result->ts;
11274                   c->attr.allocatable = ifc->result->attr.allocatable;
11275                   c->attr.pointer = ifc->result->attr.pointer;
11276                   c->attr.dimension = ifc->result->attr.dimension;
11277                   c->as = gfc_copy_array_spec (ifc->result->as);
11278                 }
11279               else
11280                 {   
11281                   c->ts = ifc->ts;
11282                   c->attr.allocatable = ifc->attr.allocatable;
11283                   c->attr.pointer = ifc->attr.pointer;
11284                   c->attr.dimension = ifc->attr.dimension;
11285                   c->as = gfc_copy_array_spec (ifc->as);
11286                 }
11287               c->ts.interface = ifc;
11288               c->attr.function = ifc->attr.function;
11289               c->attr.subroutine = ifc->attr.subroutine;
11290               gfc_copy_formal_args_ppc (c, ifc);
11291
11292               c->attr.pure = ifc->attr.pure;
11293               c->attr.elemental = ifc->attr.elemental;
11294               c->attr.recursive = ifc->attr.recursive;
11295               c->attr.always_explicit = ifc->attr.always_explicit;
11296               c->attr.ext_attr |= ifc->attr.ext_attr;
11297               /* Replace symbols in array spec.  */
11298               if (c->as)
11299                 {
11300                   int i;
11301                   for (i = 0; i < c->as->rank; i++)
11302                     {
11303                       gfc_expr_replace_comp (c->as->lower[i], c);
11304                       gfc_expr_replace_comp (c->as->upper[i], c);
11305                     }
11306                 }
11307               /* Copy char length.  */
11308               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11309                 {
11310                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11311                   gfc_expr_replace_comp (cl->length, c);
11312                   if (cl->length && !cl->resolved
11313                         && gfc_resolve_expr (cl->length) == FAILURE)
11314                     return FAILURE;
11315                   c->ts.u.cl = cl;
11316                 }
11317             }
11318           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11319             {
11320               gfc_error ("Interface '%s' of procedure pointer component "
11321                          "'%s' at %L must be explicit", c->ts.interface->name,
11322                          c->name, &c->loc);
11323               return FAILURE;
11324             }
11325         }
11326       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11327         {
11328           /* Since PPCs are not implicitly typed, a PPC without an explicit
11329              interface must be a subroutine.  */
11330           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11331         }
11332
11333       /* Procedure pointer components: Check PASS arg.  */
11334       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11335           && !sym->attr.vtype)
11336         {
11337           gfc_symbol* me_arg;
11338
11339           if (c->tb->pass_arg)
11340             {
11341               gfc_formal_arglist* i;
11342
11343               /* If an explicit passing argument name is given, walk the arg-list
11344                 and look for it.  */
11345
11346               me_arg = NULL;
11347               c->tb->pass_arg_num = 1;
11348               for (i = c->formal; i; i = i->next)
11349                 {
11350                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11351                     {
11352                       me_arg = i->sym;
11353                       break;
11354                     }
11355                   c->tb->pass_arg_num++;
11356                 }
11357
11358               if (!me_arg)
11359                 {
11360                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11361                              "at %L has no argument '%s'", c->name,
11362                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11363                   c->tb->error = 1;
11364                   return FAILURE;
11365                 }
11366             }
11367           else
11368             {
11369               /* Otherwise, take the first one; there should in fact be at least
11370                 one.  */
11371               c->tb->pass_arg_num = 1;
11372               if (!c->formal)
11373                 {
11374                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11375                              "must have at least one argument",
11376                              c->name, &c->loc);
11377                   c->tb->error = 1;
11378                   return FAILURE;
11379                 }
11380               me_arg = c->formal->sym;
11381             }
11382
11383           /* Now check that the argument-type matches.  */
11384           gcc_assert (me_arg);
11385           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11386               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11387               || (me_arg->ts.type == BT_CLASS
11388                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11389             {
11390               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11391                          " the derived type '%s'", me_arg->name, c->name,
11392                          me_arg->name, &c->loc, sym->name);
11393               c->tb->error = 1;
11394               return FAILURE;
11395             }
11396
11397           /* Check for C453.  */
11398           if (me_arg->attr.dimension)
11399             {
11400               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11401                          "must be scalar", me_arg->name, c->name, me_arg->name,
11402                          &c->loc);
11403               c->tb->error = 1;
11404               return FAILURE;
11405             }
11406
11407           if (me_arg->attr.pointer)
11408             {
11409               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11410                          "may not have the POINTER attribute", me_arg->name,
11411                          c->name, me_arg->name, &c->loc);
11412               c->tb->error = 1;
11413               return FAILURE;
11414             }
11415
11416           if (me_arg->attr.allocatable)
11417             {
11418               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11419                          "may not be ALLOCATABLE", me_arg->name, c->name,
11420                          me_arg->name, &c->loc);
11421               c->tb->error = 1;
11422               return FAILURE;
11423             }
11424
11425           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11426             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11427                        " at %L", c->name, &c->loc);
11428
11429         }
11430
11431       /* Check type-spec if this is not the parent-type component.  */
11432       if ((!sym->attr.extension || c != sym->components)
11433           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11434         return FAILURE;
11435
11436       /* If this type is an extension, set the accessibility of the parent
11437          component.  */
11438       if (super_type && c == sym->components
11439           && strcmp (super_type->name, c->name) == 0)
11440         c->attr.access = super_type->attr.access;
11441       
11442       /* If this type is an extension, see if this component has the same name
11443          as an inherited type-bound procedure.  */
11444       if (super_type && !sym->attr.is_class
11445           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11446         {
11447           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11448                      " inherited type-bound procedure",
11449                      c->name, sym->name, &c->loc);
11450           return FAILURE;
11451         }
11452
11453       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
11454         {
11455          if (c->ts.u.cl->length == NULL
11456              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11457              || !gfc_is_constant_expr (c->ts.u.cl->length))
11458            {
11459              gfc_error ("Character length of component '%s' needs to "
11460                         "be a constant specification expression at %L",
11461                         c->name,
11462                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11463              return FAILURE;
11464            }
11465         }
11466
11467       if (c->ts.type == BT_DERIVED
11468           && sym->component_access != ACCESS_PRIVATE
11469           && gfc_check_access (sym->attr.access, sym->ns->default_access)
11470           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11471           && !c->ts.u.derived->attr.use_assoc
11472           && !gfc_check_access (c->ts.u.derived->attr.access,
11473                                 c->ts.u.derived->ns->default_access)
11474           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11475                              "is a PRIVATE type and cannot be a component of "
11476                              "'%s', which is PUBLIC at %L", c->name,
11477                              sym->name, &sym->declared_at) == FAILURE)
11478         return FAILURE;
11479
11480       if (sym->attr.sequence)
11481         {
11482           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11483             {
11484               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11485                          "not have the SEQUENCE attribute",
11486                          c->ts.u.derived->name, &sym->declared_at);
11487               return FAILURE;
11488             }
11489         }
11490
11491       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && c->attr.pointer
11492           && c->ts.u.derived->components == NULL
11493           && !c->ts.u.derived->attr.zero_comp)
11494         {
11495           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11496                      "that has not been declared", c->name, sym->name,
11497                      &c->loc);
11498           return FAILURE;
11499         }
11500
11501       if (c->ts.type == BT_CLASS && CLASS_DATA (c)->attr.class_pointer
11502           && CLASS_DATA (c)->ts.u.derived->components == NULL
11503           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11504         {
11505           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11506                      "that has not been declared", c->name, sym->name,
11507                      &c->loc);
11508           return FAILURE;
11509         }
11510
11511       /* C437.  */
11512       if (c->ts.type == BT_CLASS
11513           && !(CLASS_DATA (c)->attr.class_pointer
11514                || CLASS_DATA (c)->attr.allocatable))
11515         {
11516           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11517                      "or pointer", c->name, &c->loc);
11518           return FAILURE;
11519         }
11520
11521       /* Ensure that all the derived type components are put on the
11522          derived type list; even in formal namespaces, where derived type
11523          pointer components might not have been declared.  */
11524       if (c->ts.type == BT_DERIVED
11525             && c->ts.u.derived
11526             && c->ts.u.derived->components
11527             && c->attr.pointer
11528             && sym != c->ts.u.derived)
11529         add_dt_to_dt_list (c->ts.u.derived);
11530
11531       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11532                                            || c->attr.proc_pointer
11533                                            || c->attr.allocatable)) == FAILURE)
11534         return FAILURE;
11535     }
11536
11537   /* Resolve the type-bound procedures.  */
11538   if (resolve_typebound_procedures (sym) == FAILURE)
11539     return FAILURE;
11540
11541   /* Resolve the finalizer procedures.  */
11542   if (gfc_resolve_finalizers (sym) == FAILURE)
11543     return FAILURE;
11544
11545   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11546      all DEFERRED bindings are overridden.  */
11547   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11548       && !sym->attr.is_class
11549       && ensure_not_abstract (sym, super_type) == FAILURE)
11550     return FAILURE;
11551
11552   /* Add derived type to the derived type list.  */
11553   add_dt_to_dt_list (sym);
11554
11555   return SUCCESS;
11556 }
11557
11558
11559 static gfc_try
11560 resolve_fl_namelist (gfc_symbol *sym)
11561 {
11562   gfc_namelist *nl;
11563   gfc_symbol *nlsym;
11564
11565   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11566   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
11567     {
11568       for (nl = sym->namelist; nl; nl = nl->next)
11569         {
11570           if (!nl->sym->attr.use_assoc
11571               && !is_sym_host_assoc (nl->sym, sym->ns)
11572               && !gfc_check_access(nl->sym->attr.access,
11573                                 nl->sym->ns->default_access))
11574             {
11575               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11576                          "cannot be member of PUBLIC namelist '%s' at %L",
11577                          nl->sym->name, sym->name, &sym->declared_at);
11578               return FAILURE;
11579             }
11580
11581           /* Types with private components that came here by USE-association.  */
11582           if (nl->sym->ts.type == BT_DERIVED
11583               && derived_inaccessible (nl->sym->ts.u.derived))
11584             {
11585               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11586                          "components and cannot be member of namelist '%s' at %L",
11587                          nl->sym->name, sym->name, &sym->declared_at);
11588               return FAILURE;
11589             }
11590
11591           /* Types with private components that are defined in the same module.  */
11592           if (nl->sym->ts.type == BT_DERIVED
11593               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11594               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
11595                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
11596                                         nl->sym->ns->default_access))
11597             {
11598               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11599                          "cannot be a member of PUBLIC namelist '%s' at %L",
11600                          nl->sym->name, sym->name, &sym->declared_at);
11601               return FAILURE;
11602             }
11603         }
11604     }
11605
11606   for (nl = sym->namelist; nl; nl = nl->next)
11607     {
11608       /* Reject namelist arrays of assumed shape.  */
11609       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11610           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
11611                              "must not have assumed shape in namelist "
11612                              "'%s' at %L", nl->sym->name, sym->name,
11613                              &sym->declared_at) == FAILURE)
11614             return FAILURE;
11615
11616       /* Reject namelist arrays that are not constant shape.  */
11617       if (is_non_constant_shape_array (nl->sym))
11618         {
11619           gfc_error ("NAMELIST array object '%s' must have constant "
11620                      "shape in namelist '%s' at %L", nl->sym->name,
11621                      sym->name, &sym->declared_at);
11622           return FAILURE;
11623         }
11624
11625       /* Namelist objects cannot have allocatable or pointer components.  */
11626       if (nl->sym->ts.type != BT_DERIVED)
11627         continue;
11628
11629       if (nl->sym->ts.u.derived->attr.alloc_comp)
11630         {
11631           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11632                      "have ALLOCATABLE components",
11633                      nl->sym->name, sym->name, &sym->declared_at);
11634           return FAILURE;
11635         }
11636
11637       if (nl->sym->ts.u.derived->attr.pointer_comp)
11638         {
11639           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11640                      "have POINTER components", 
11641                      nl->sym->name, sym->name, &sym->declared_at);
11642           return FAILURE;
11643         }
11644     }
11645
11646
11647   /* 14.1.2 A module or internal procedure represent local entities
11648      of the same type as a namelist member and so are not allowed.  */
11649   for (nl = sym->namelist; nl; nl = nl->next)
11650     {
11651       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11652         continue;
11653
11654       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11655         if ((nl->sym == sym->ns->proc_name)
11656                ||
11657             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11658           continue;
11659
11660       nlsym = NULL;
11661       if (nl->sym && nl->sym->name)
11662         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11663       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11664         {
11665           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11666                      "attribute in '%s' at %L", nlsym->name,
11667                      &sym->declared_at);
11668           return FAILURE;
11669         }
11670     }
11671
11672   return SUCCESS;
11673 }
11674
11675
11676 static gfc_try
11677 resolve_fl_parameter (gfc_symbol *sym)
11678 {
11679   /* A parameter array's shape needs to be constant.  */
11680   if (sym->as != NULL 
11681       && (sym->as->type == AS_DEFERRED
11682           || is_non_constant_shape_array (sym)))
11683     {
11684       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11685                  "or of deferred shape", sym->name, &sym->declared_at);
11686       return FAILURE;
11687     }
11688
11689   /* Make sure a parameter that has been implicitly typed still
11690      matches the implicit type, since PARAMETER statements can precede
11691      IMPLICIT statements.  */
11692   if (sym->attr.implicit_type
11693       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11694                                                              sym->ns)))
11695     {
11696       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11697                  "later IMPLICIT type", sym->name, &sym->declared_at);
11698       return FAILURE;
11699     }
11700
11701   /* Make sure the types of derived parameters are consistent.  This
11702      type checking is deferred until resolution because the type may
11703      refer to a derived type from the host.  */
11704   if (sym->ts.type == BT_DERIVED
11705       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11706     {
11707       gfc_error ("Incompatible derived type in PARAMETER at %L",
11708                  &sym->value->where);
11709       return FAILURE;
11710     }
11711   return SUCCESS;
11712 }
11713
11714
11715 /* Do anything necessary to resolve a symbol.  Right now, we just
11716    assume that an otherwise unknown symbol is a variable.  This sort
11717    of thing commonly happens for symbols in module.  */
11718
11719 static void
11720 resolve_symbol (gfc_symbol *sym)
11721 {
11722   int check_constant, mp_flag;
11723   gfc_symtree *symtree;
11724   gfc_symtree *this_symtree;
11725   gfc_namespace *ns;
11726   gfc_component *c;
11727
11728   /* Avoid double resolution of function result symbols.  */
11729   if ((sym->result || sym->attr.result) && !sym->attr.dummy
11730       && (sym->ns != gfc_current_ns))
11731     return;
11732   
11733   if (sym->attr.flavor == FL_UNKNOWN)
11734     {
11735
11736     /* If we find that a flavorless symbol is an interface in one of the
11737        parent namespaces, find its symtree in this namespace, free the
11738        symbol and set the symtree to point to the interface symbol.  */
11739       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11740         {
11741           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11742           if (symtree && symtree->n.sym->generic)
11743             {
11744               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11745                                                sym->name);
11746               gfc_release_symbol (sym);
11747               symtree->n.sym->refs++;
11748               this_symtree->n.sym = symtree->n.sym;
11749               return;
11750             }
11751         }
11752
11753       /* Otherwise give it a flavor according to such attributes as
11754          it has.  */
11755       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11756         sym->attr.flavor = FL_VARIABLE;
11757       else
11758         {
11759           sym->attr.flavor = FL_PROCEDURE;
11760           if (sym->attr.dimension)
11761             sym->attr.function = 1;
11762         }
11763     }
11764
11765   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11766     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11767
11768   if (sym->attr.procedure && sym->ts.interface
11769       && sym->attr.if_source != IFSRC_DECL
11770       && resolve_procedure_interface (sym) == FAILURE)
11771     return;
11772
11773   if (sym->attr.is_protected && !sym->attr.proc_pointer
11774       && (sym->attr.procedure || sym->attr.external))
11775     {
11776       if (sym->attr.external)
11777         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
11778                    "at %L", &sym->declared_at);
11779       else
11780         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
11781                    "at %L", &sym->declared_at);
11782
11783       return;
11784     }
11785
11786
11787   /* F2008, C530. */
11788   if (sym->attr.contiguous
11789       && (!sym->attr.dimension || (sym->as->type != AS_ASSUMED_SHAPE
11790                                    && !sym->attr.pointer)))
11791     {
11792       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
11793                   "array pointer or an assumed-shape array", sym->name,
11794                   &sym->declared_at);
11795       return;
11796     }
11797
11798   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11799     return;
11800
11801   /* Symbols that are module procedures with results (functions) have
11802      the types and array specification copied for type checking in
11803      procedures that call them, as well as for saving to a module
11804      file.  These symbols can't stand the scrutiny that their results
11805      can.  */
11806   mp_flag = (sym->result != NULL && sym->result != sym);
11807
11808   /* Make sure that the intrinsic is consistent with its internal 
11809      representation. This needs to be done before assigning a default 
11810      type to avoid spurious warnings.  */
11811   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11812       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11813     return;
11814
11815   /* Resolve associate names.  */
11816   if (sym->assoc)
11817     resolve_assoc_var (sym, true);
11818
11819   /* Assign default type to symbols that need one and don't have one.  */
11820   if (sym->ts.type == BT_UNKNOWN)
11821     {
11822       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
11823         gfc_set_default_type (sym, 1, NULL);
11824
11825       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
11826           && !sym->attr.function && !sym->attr.subroutine
11827           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
11828         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
11829
11830       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
11831         {
11832           /* The specific case of an external procedure should emit an error
11833              in the case that there is no implicit type.  */
11834           if (!mp_flag)
11835             gfc_set_default_type (sym, sym->attr.external, NULL);
11836           else
11837             {
11838               /* Result may be in another namespace.  */
11839               resolve_symbol (sym->result);
11840
11841               if (!sym->result->attr.proc_pointer)
11842                 {
11843                   sym->ts = sym->result->ts;
11844                   sym->as = gfc_copy_array_spec (sym->result->as);
11845                   sym->attr.dimension = sym->result->attr.dimension;
11846                   sym->attr.pointer = sym->result->attr.pointer;
11847                   sym->attr.allocatable = sym->result->attr.allocatable;
11848                   sym->attr.contiguous = sym->result->attr.contiguous;
11849                 }
11850             }
11851         }
11852     }
11853
11854   /* Assumed size arrays and assumed shape arrays must be dummy
11855      arguments.  Array-spec's of implied-shape should have been resolved to
11856      AS_EXPLICIT already.  */
11857
11858   if (sym->as)
11859     {
11860       gcc_assert (sym->as->type != AS_IMPLIED_SHAPE);
11861       if (((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
11862            || sym->as->type == AS_ASSUMED_SHAPE)
11863           && sym->attr.dummy == 0)
11864         {
11865           if (sym->as->type == AS_ASSUMED_SIZE)
11866             gfc_error ("Assumed size array at %L must be a dummy argument",
11867                        &sym->declared_at);
11868           else
11869             gfc_error ("Assumed shape array at %L must be a dummy argument",
11870                        &sym->declared_at);
11871           return;
11872         }
11873     }
11874
11875   /* Make sure symbols with known intent or optional are really dummy
11876      variable.  Because of ENTRY statement, this has to be deferred
11877      until resolution time.  */
11878
11879   if (!sym->attr.dummy
11880       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
11881     {
11882       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
11883       return;
11884     }
11885
11886   if (sym->attr.value && !sym->attr.dummy)
11887     {
11888       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
11889                  "it is not a dummy argument", sym->name, &sym->declared_at);
11890       return;
11891     }
11892
11893   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
11894     {
11895       gfc_charlen *cl = sym->ts.u.cl;
11896       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
11897         {
11898           gfc_error ("Character dummy variable '%s' at %L with VALUE "
11899                      "attribute must have constant length",
11900                      sym->name, &sym->declared_at);
11901           return;
11902         }
11903
11904       if (sym->ts.is_c_interop
11905           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
11906         {
11907           gfc_error ("C interoperable character dummy variable '%s' at %L "
11908                      "with VALUE attribute must have length one",
11909                      sym->name, &sym->declared_at);
11910           return;
11911         }
11912     }
11913
11914   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
11915      do this for something that was implicitly typed because that is handled
11916      in gfc_set_default_type.  Handle dummy arguments and procedure
11917      definitions separately.  Also, anything that is use associated is not
11918      handled here but instead is handled in the module it is declared in.
11919      Finally, derived type definitions are allowed to be BIND(C) since that
11920      only implies that they're interoperable, and they are checked fully for
11921      interoperability when a variable is declared of that type.  */
11922   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
11923       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
11924       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
11925     {
11926       gfc_try t = SUCCESS;
11927       
11928       /* First, make sure the variable is declared at the
11929          module-level scope (J3/04-007, Section 15.3).  */
11930       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
11931           sym->attr.in_common == 0)
11932         {
11933           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
11934                      "is neither a COMMON block nor declared at the "
11935                      "module level scope", sym->name, &(sym->declared_at));
11936           t = FAILURE;
11937         }
11938       else if (sym->common_head != NULL)
11939         {
11940           t = verify_com_block_vars_c_interop (sym->common_head);
11941         }
11942       else
11943         {
11944           /* If type() declaration, we need to verify that the components
11945              of the given type are all C interoperable, etc.  */
11946           if (sym->ts.type == BT_DERIVED &&
11947               sym->ts.u.derived->attr.is_c_interop != 1)
11948             {
11949               /* Make sure the user marked the derived type as BIND(C).  If
11950                  not, call the verify routine.  This could print an error
11951                  for the derived type more than once if multiple variables
11952                  of that type are declared.  */
11953               if (sym->ts.u.derived->attr.is_bind_c != 1)
11954                 verify_bind_c_derived_type (sym->ts.u.derived);
11955               t = FAILURE;
11956             }
11957           
11958           /* Verify the variable itself as C interoperable if it
11959              is BIND(C).  It is not possible for this to succeed if
11960              the verify_bind_c_derived_type failed, so don't have to handle
11961              any error returned by verify_bind_c_derived_type.  */
11962           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
11963                                  sym->common_block);
11964         }
11965
11966       if (t == FAILURE)
11967         {
11968           /* clear the is_bind_c flag to prevent reporting errors more than
11969              once if something failed.  */
11970           sym->attr.is_bind_c = 0;
11971           return;
11972         }
11973     }
11974
11975   /* If a derived type symbol has reached this point, without its
11976      type being declared, we have an error.  Notice that most
11977      conditions that produce undefined derived types have already
11978      been dealt with.  However, the likes of:
11979      implicit type(t) (t) ..... call foo (t) will get us here if
11980      the type is not declared in the scope of the implicit
11981      statement. Change the type to BT_UNKNOWN, both because it is so
11982      and to prevent an ICE.  */
11983   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
11984       && !sym->ts.u.derived->attr.zero_comp)
11985     {
11986       gfc_error ("The derived type '%s' at %L is of type '%s', "
11987                  "which has not been defined", sym->name,
11988                   &sym->declared_at, sym->ts.u.derived->name);
11989       sym->ts.type = BT_UNKNOWN;
11990       return;
11991     }
11992
11993   /* Make sure that the derived type has been resolved and that the
11994      derived type is visible in the symbol's namespace, if it is a
11995      module function and is not PRIVATE.  */
11996   if (sym->ts.type == BT_DERIVED
11997         && sym->ts.u.derived->attr.use_assoc
11998         && sym->ns->proc_name
11999         && sym->ns->proc_name->attr.flavor == FL_MODULE)
12000     {
12001       gfc_symbol *ds;
12002
12003       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
12004         return;
12005
12006       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
12007       if (!ds && sym->attr.function
12008             && gfc_check_access (sym->attr.access, sym->ns->default_access))
12009         {
12010           symtree = gfc_new_symtree (&sym->ns->sym_root,
12011                                      sym->ts.u.derived->name);
12012           symtree->n.sym = sym->ts.u.derived;
12013           sym->ts.u.derived->refs++;
12014         }
12015     }
12016
12017   /* Unless the derived-type declaration is use associated, Fortran 95
12018      does not allow public entries of private derived types.
12019      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12020      161 in 95-006r3.  */
12021   if (sym->ts.type == BT_DERIVED
12022       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12023       && !sym->ts.u.derived->attr.use_assoc
12024       && gfc_check_access (sym->attr.access, sym->ns->default_access)
12025       && !gfc_check_access (sym->ts.u.derived->attr.access,
12026                             sym->ts.u.derived->ns->default_access)
12027       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12028                          "of PRIVATE derived type '%s'",
12029                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12030                          : "variable", sym->name, &sym->declared_at,
12031                          sym->ts.u.derived->name) == FAILURE)
12032     return;
12033
12034   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12035      default initialization is defined (5.1.2.4.4).  */
12036   if (sym->ts.type == BT_DERIVED
12037       && sym->attr.dummy
12038       && sym->attr.intent == INTENT_OUT
12039       && sym->as
12040       && sym->as->type == AS_ASSUMED_SIZE)
12041     {
12042       for (c = sym->ts.u.derived->components; c; c = c->next)
12043         {
12044           if (c->initializer)
12045             {
12046               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12047                          "ASSUMED SIZE and so cannot have a default initializer",
12048                          sym->name, &sym->declared_at);
12049               return;
12050             }
12051         }
12052     }
12053
12054   /* F2008, C526.  */
12055   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12056        || sym->attr.codimension)
12057       && sym->attr.result)
12058     gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12059                "a coarray component", sym->name, &sym->declared_at);
12060
12061   /* F2008, C524.  */
12062   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12063       && sym->ts.u.derived->ts.is_iso_c)
12064     gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12065                "shall not be a coarray", sym->name, &sym->declared_at);
12066
12067   /* F2008, C525.  */
12068   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
12069       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
12070           || sym->attr.allocatable))
12071     gfc_error ("Variable '%s' at %L with coarray component "
12072                "shall be a nonpointer, nonallocatable scalar",
12073                sym->name, &sym->declared_at);
12074
12075   /* F2008, C526.  The function-result case was handled above.  */
12076   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12077        || sym->attr.codimension)
12078       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
12079            || sym->ns->proc_name->attr.flavor == FL_MODULE
12080            || sym->ns->proc_name->attr.is_main_program
12081            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12082     gfc_error ("Variable '%s' at %L is a coarray or has a coarray "
12083                "component and is not ALLOCATABLE, SAVE nor a "
12084                "dummy argument", sym->name, &sym->declared_at);
12085   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
12086   else if (sym->attr.codimension && !sym->attr.allocatable
12087       && sym->as && sym->as->cotype == AS_DEFERRED)
12088     gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12089                 "deferred shape", sym->name, &sym->declared_at);
12090   else if (sym->attr.codimension && sym->attr.allocatable
12091       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
12092     gfc_error ("Allocatable coarray variable '%s' at %L must have "
12093                "deferred shape", sym->name, &sym->declared_at);
12094
12095
12096   /* F2008, C541.  */
12097   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12098        || (sym->attr.codimension && sym->attr.allocatable))
12099       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12100     gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12101                "allocatable coarray or have coarray components",
12102                sym->name, &sym->declared_at);
12103
12104   if (sym->attr.codimension && sym->attr.dummy
12105       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12106     gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12107                "procedure '%s'", sym->name, &sym->declared_at,
12108                sym->ns->proc_name->name);
12109
12110   switch (sym->attr.flavor)
12111     {
12112     case FL_VARIABLE:
12113       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12114         return;
12115       break;
12116
12117     case FL_PROCEDURE:
12118       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12119         return;
12120       break;
12121
12122     case FL_NAMELIST:
12123       if (resolve_fl_namelist (sym) == FAILURE)
12124         return;
12125       break;
12126
12127     case FL_PARAMETER:
12128       if (resolve_fl_parameter (sym) == FAILURE)
12129         return;
12130       break;
12131
12132     default:
12133       break;
12134     }
12135
12136   /* Resolve array specifier. Check as well some constraints
12137      on COMMON blocks.  */
12138
12139   check_constant = sym->attr.in_common && !sym->attr.pointer;
12140
12141   /* Set the formal_arg_flag so that check_conflict will not throw
12142      an error for host associated variables in the specification
12143      expression for an array_valued function.  */
12144   if (sym->attr.function && sym->as)
12145     formal_arg_flag = 1;
12146
12147   gfc_resolve_array_spec (sym->as, check_constant);
12148
12149   formal_arg_flag = 0;
12150
12151   /* Resolve formal namespaces.  */
12152   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12153       && !sym->attr.contained && !sym->attr.intrinsic)
12154     gfc_resolve (sym->formal_ns);
12155
12156   /* Make sure the formal namespace is present.  */
12157   if (sym->formal && !sym->formal_ns)
12158     {
12159       gfc_formal_arglist *formal = sym->formal;
12160       while (formal && !formal->sym)
12161         formal = formal->next;
12162
12163       if (formal)
12164         {
12165           sym->formal_ns = formal->sym->ns;
12166           sym->formal_ns->refs++;
12167         }
12168     }
12169
12170   /* Check threadprivate restrictions.  */
12171   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12172       && (!sym->attr.in_common
12173           && sym->module == NULL
12174           && (sym->ns->proc_name == NULL
12175               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12176     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12177
12178   /* If we have come this far we can apply default-initializers, as
12179      described in 14.7.5, to those variables that have not already
12180      been assigned one.  */
12181   if (sym->ts.type == BT_DERIVED
12182       && sym->attr.referenced
12183       && sym->ns == gfc_current_ns
12184       && !sym->value
12185       && !sym->attr.allocatable
12186       && !sym->attr.alloc_comp)
12187     {
12188       symbol_attribute *a = &sym->attr;
12189
12190       if ((!a->save && !a->dummy && !a->pointer
12191            && !a->in_common && !a->use_assoc
12192            && !(a->function && sym != sym->result))
12193           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12194         apply_default_init (sym);
12195     }
12196
12197   /* If this symbol has a type-spec, check it.  */
12198   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12199       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12200     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12201           == FAILURE)
12202       return;
12203 }
12204
12205
12206 /************* Resolve DATA statements *************/
12207
12208 static struct
12209 {
12210   gfc_data_value *vnode;
12211   mpz_t left;
12212 }
12213 values;
12214
12215
12216 /* Advance the values structure to point to the next value in the data list.  */
12217
12218 static gfc_try
12219 next_data_value (void)
12220 {
12221   while (mpz_cmp_ui (values.left, 0) == 0)
12222     {
12223
12224       if (values.vnode->next == NULL)
12225         return FAILURE;
12226
12227       values.vnode = values.vnode->next;
12228       mpz_set (values.left, values.vnode->repeat);
12229     }
12230
12231   return SUCCESS;
12232 }
12233
12234
12235 static gfc_try
12236 check_data_variable (gfc_data_variable *var, locus *where)
12237 {
12238   gfc_expr *e;
12239   mpz_t size;
12240   mpz_t offset;
12241   gfc_try t;
12242   ar_type mark = AR_UNKNOWN;
12243   int i;
12244   mpz_t section_index[GFC_MAX_DIMENSIONS];
12245   gfc_ref *ref;
12246   gfc_array_ref *ar;
12247   gfc_symbol *sym;
12248   int has_pointer;
12249
12250   if (gfc_resolve_expr (var->expr) == FAILURE)
12251     return FAILURE;
12252
12253   ar = NULL;
12254   mpz_init_set_si (offset, 0);
12255   e = var->expr;
12256
12257   if (e->expr_type != EXPR_VARIABLE)
12258     gfc_internal_error ("check_data_variable(): Bad expression");
12259
12260   sym = e->symtree->n.sym;
12261
12262   if (sym->ns->is_block_data && !sym->attr.in_common)
12263     {
12264       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12265                  sym->name, &sym->declared_at);
12266     }
12267
12268   if (e->ref == NULL && sym->as)
12269     {
12270       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12271                  " declaration", sym->name, where);
12272       return FAILURE;
12273     }
12274
12275   has_pointer = sym->attr.pointer;
12276
12277   for (ref = e->ref; ref; ref = ref->next)
12278     {
12279       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12280         has_pointer = 1;
12281
12282       if (ref->type == REF_ARRAY && ref->u.ar.codimen)
12283         {
12284           gfc_error ("DATA element '%s' at %L cannot have a coindex",
12285                      sym->name, where);
12286           return FAILURE;
12287         }
12288
12289       if (has_pointer
12290             && ref->type == REF_ARRAY
12291             && ref->u.ar.type != AR_FULL)
12292           {
12293             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12294                         "be a full array", sym->name, where);
12295             return FAILURE;
12296           }
12297     }
12298
12299   if (e->rank == 0 || has_pointer)
12300     {
12301       mpz_init_set_ui (size, 1);
12302       ref = NULL;
12303     }
12304   else
12305     {
12306       ref = e->ref;
12307
12308       /* Find the array section reference.  */
12309       for (ref = e->ref; ref; ref = ref->next)
12310         {
12311           if (ref->type != REF_ARRAY)
12312             continue;
12313           if (ref->u.ar.type == AR_ELEMENT)
12314             continue;
12315           break;
12316         }
12317       gcc_assert (ref);
12318
12319       /* Set marks according to the reference pattern.  */
12320       switch (ref->u.ar.type)
12321         {
12322         case AR_FULL:
12323           mark = AR_FULL;
12324           break;
12325
12326         case AR_SECTION:
12327           ar = &ref->u.ar;
12328           /* Get the start position of array section.  */
12329           gfc_get_section_index (ar, section_index, &offset);
12330           mark = AR_SECTION;
12331           break;
12332
12333         default:
12334           gcc_unreachable ();
12335         }
12336
12337       if (gfc_array_size (e, &size) == FAILURE)
12338         {
12339           gfc_error ("Nonconstant array section at %L in DATA statement",
12340                      &e->where);
12341           mpz_clear (offset);
12342           return FAILURE;
12343         }
12344     }
12345
12346   t = SUCCESS;
12347
12348   while (mpz_cmp_ui (size, 0) > 0)
12349     {
12350       if (next_data_value () == FAILURE)
12351         {
12352           gfc_error ("DATA statement at %L has more variables than values",
12353                      where);
12354           t = FAILURE;
12355           break;
12356         }
12357
12358       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12359       if (t == FAILURE)
12360         break;
12361
12362       /* If we have more than one element left in the repeat count,
12363          and we have more than one element left in the target variable,
12364          then create a range assignment.  */
12365       /* FIXME: Only done for full arrays for now, since array sections
12366          seem tricky.  */
12367       if (mark == AR_FULL && ref && ref->next == NULL
12368           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12369         {
12370           mpz_t range;
12371
12372           if (mpz_cmp (size, values.left) >= 0)
12373             {
12374               mpz_init_set (range, values.left);
12375               mpz_sub (size, size, values.left);
12376               mpz_set_ui (values.left, 0);
12377             }
12378           else
12379             {
12380               mpz_init_set (range, size);
12381               mpz_sub (values.left, values.left, size);
12382               mpz_set_ui (size, 0);
12383             }
12384
12385           t = gfc_assign_data_value_range (var->expr, values.vnode->expr,
12386                                            offset, range);
12387
12388           mpz_add (offset, offset, range);
12389           mpz_clear (range);
12390
12391           if (t == FAILURE)
12392             break;
12393         }
12394
12395       /* Assign initial value to symbol.  */
12396       else
12397         {
12398           mpz_sub_ui (values.left, values.left, 1);
12399           mpz_sub_ui (size, size, 1);
12400
12401           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
12402           if (t == FAILURE)
12403             break;
12404
12405           if (mark == AR_FULL)
12406             mpz_add_ui (offset, offset, 1);
12407
12408           /* Modify the array section indexes and recalculate the offset
12409              for next element.  */
12410           else if (mark == AR_SECTION)
12411             gfc_advance_section (section_index, ar, &offset);
12412         }
12413     }
12414
12415   if (mark == AR_SECTION)
12416     {
12417       for (i = 0; i < ar->dimen; i++)
12418         mpz_clear (section_index[i]);
12419     }
12420
12421   mpz_clear (size);
12422   mpz_clear (offset);
12423
12424   return t;
12425 }
12426
12427
12428 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
12429
12430 /* Iterate over a list of elements in a DATA statement.  */
12431
12432 static gfc_try
12433 traverse_data_list (gfc_data_variable *var, locus *where)
12434 {
12435   mpz_t trip;
12436   iterator_stack frame;
12437   gfc_expr *e, *start, *end, *step;
12438   gfc_try retval = SUCCESS;
12439
12440   mpz_init (frame.value);
12441   mpz_init (trip);
12442
12443   start = gfc_copy_expr (var->iter.start);
12444   end = gfc_copy_expr (var->iter.end);
12445   step = gfc_copy_expr (var->iter.step);
12446
12447   if (gfc_simplify_expr (start, 1) == FAILURE
12448       || start->expr_type != EXPR_CONSTANT)
12449     {
12450       gfc_error ("start of implied-do loop at %L could not be "
12451                  "simplified to a constant value", &start->where);
12452       retval = FAILURE;
12453       goto cleanup;
12454     }
12455   if (gfc_simplify_expr (end, 1) == FAILURE
12456       || end->expr_type != EXPR_CONSTANT)
12457     {
12458       gfc_error ("end of implied-do loop at %L could not be "
12459                  "simplified to a constant value", &start->where);
12460       retval = FAILURE;
12461       goto cleanup;
12462     }
12463   if (gfc_simplify_expr (step, 1) == FAILURE
12464       || step->expr_type != EXPR_CONSTANT)
12465     {
12466       gfc_error ("step of implied-do loop at %L could not be "
12467                  "simplified to a constant value", &start->where);
12468       retval = FAILURE;
12469       goto cleanup;
12470     }
12471
12472   mpz_set (trip, end->value.integer);
12473   mpz_sub (trip, trip, start->value.integer);
12474   mpz_add (trip, trip, step->value.integer);
12475
12476   mpz_div (trip, trip, step->value.integer);
12477
12478   mpz_set (frame.value, start->value.integer);
12479
12480   frame.prev = iter_stack;
12481   frame.variable = var->iter.var->symtree;
12482   iter_stack = &frame;
12483
12484   while (mpz_cmp_ui (trip, 0) > 0)
12485     {
12486       if (traverse_data_var (var->list, where) == FAILURE)
12487         {
12488           retval = FAILURE;
12489           goto cleanup;
12490         }
12491
12492       e = gfc_copy_expr (var->expr);
12493       if (gfc_simplify_expr (e, 1) == FAILURE)
12494         {
12495           gfc_free_expr (e);
12496           retval = FAILURE;
12497           goto cleanup;
12498         }
12499
12500       mpz_add (frame.value, frame.value, step->value.integer);
12501
12502       mpz_sub_ui (trip, trip, 1);
12503     }
12504
12505 cleanup:
12506   mpz_clear (frame.value);
12507   mpz_clear (trip);
12508
12509   gfc_free_expr (start);
12510   gfc_free_expr (end);
12511   gfc_free_expr (step);
12512
12513   iter_stack = frame.prev;
12514   return retval;
12515 }
12516
12517
12518 /* Type resolve variables in the variable list of a DATA statement.  */
12519
12520 static gfc_try
12521 traverse_data_var (gfc_data_variable *var, locus *where)
12522 {
12523   gfc_try t;
12524
12525   for (; var; var = var->next)
12526     {
12527       if (var->expr == NULL)
12528         t = traverse_data_list (var, where);
12529       else
12530         t = check_data_variable (var, where);
12531
12532       if (t == FAILURE)
12533         return FAILURE;
12534     }
12535
12536   return SUCCESS;
12537 }
12538
12539
12540 /* Resolve the expressions and iterators associated with a data statement.
12541    This is separate from the assignment checking because data lists should
12542    only be resolved once.  */
12543
12544 static gfc_try
12545 resolve_data_variables (gfc_data_variable *d)
12546 {
12547   for (; d; d = d->next)
12548     {
12549       if (d->list == NULL)
12550         {
12551           if (gfc_resolve_expr (d->expr) == FAILURE)
12552             return FAILURE;
12553         }
12554       else
12555         {
12556           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12557             return FAILURE;
12558
12559           if (resolve_data_variables (d->list) == FAILURE)
12560             return FAILURE;
12561         }
12562     }
12563
12564   return SUCCESS;
12565 }
12566
12567
12568 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12569    the value list into static variables, and then recursively traversing the
12570    variables list, expanding iterators and such.  */
12571
12572 static void
12573 resolve_data (gfc_data *d)
12574 {
12575
12576   if (resolve_data_variables (d->var) == FAILURE)
12577     return;
12578
12579   values.vnode = d->value;
12580   if (d->value == NULL)
12581     mpz_set_ui (values.left, 0);
12582   else
12583     mpz_set (values.left, d->value->repeat);
12584
12585   if (traverse_data_var (d->var, &d->where) == FAILURE)
12586     return;
12587
12588   /* At this point, we better not have any values left.  */
12589
12590   if (next_data_value () == SUCCESS)
12591     gfc_error ("DATA statement at %L has more values than variables",
12592                &d->where);
12593 }
12594
12595
12596 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12597    accessed by host or use association, is a dummy argument to a pure function,
12598    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12599    is storage associated with any such variable, shall not be used in the
12600    following contexts: (clients of this function).  */
12601
12602 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12603    procedure.  Returns zero if assignment is OK, nonzero if there is a
12604    problem.  */
12605 int
12606 gfc_impure_variable (gfc_symbol *sym)
12607 {
12608   gfc_symbol *proc;
12609   gfc_namespace *ns;
12610
12611   if (sym->attr.use_assoc || sym->attr.in_common)
12612     return 1;
12613
12614   /* Check if the symbol's ns is inside the pure procedure.  */
12615   for (ns = gfc_current_ns; ns; ns = ns->parent)
12616     {
12617       if (ns == sym->ns)
12618         break;
12619       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12620         return 1;
12621     }
12622
12623   proc = sym->ns->proc_name;
12624   if (sym->attr.dummy && gfc_pure (proc)
12625         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12626                 ||
12627              proc->attr.function))
12628     return 1;
12629
12630   /* TODO: Sort out what can be storage associated, if anything, and include
12631      it here.  In principle equivalences should be scanned but it does not
12632      seem to be possible to storage associate an impure variable this way.  */
12633   return 0;
12634 }
12635
12636
12637 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12638    current namespace is inside a pure procedure.  */
12639
12640 int
12641 gfc_pure (gfc_symbol *sym)
12642 {
12643   symbol_attribute attr;
12644   gfc_namespace *ns;
12645
12646   if (sym == NULL)
12647     {
12648       /* Check if the current namespace or one of its parents
12649         belongs to a pure procedure.  */
12650       for (ns = gfc_current_ns; ns; ns = ns->parent)
12651         {
12652           sym = ns->proc_name;
12653           if (sym == NULL)
12654             return 0;
12655           attr = sym->attr;
12656           if (attr.flavor == FL_PROCEDURE && attr.pure)
12657             return 1;
12658         }
12659       return 0;
12660     }
12661
12662   attr = sym->attr;
12663
12664   return attr.flavor == FL_PROCEDURE && attr.pure;
12665 }
12666
12667
12668 /* Test whether the current procedure is elemental or not.  */
12669
12670 int
12671 gfc_elemental (gfc_symbol *sym)
12672 {
12673   symbol_attribute attr;
12674
12675   if (sym == NULL)
12676     sym = gfc_current_ns->proc_name;
12677   if (sym == NULL)
12678     return 0;
12679   attr = sym->attr;
12680
12681   return attr.flavor == FL_PROCEDURE && attr.elemental;
12682 }
12683
12684
12685 /* Warn about unused labels.  */
12686
12687 static void
12688 warn_unused_fortran_label (gfc_st_label *label)
12689 {
12690   if (label == NULL)
12691     return;
12692
12693   warn_unused_fortran_label (label->left);
12694
12695   if (label->defined == ST_LABEL_UNKNOWN)
12696     return;
12697
12698   switch (label->referenced)
12699     {
12700     case ST_LABEL_UNKNOWN:
12701       gfc_warning ("Label %d at %L defined but not used", label->value,
12702                    &label->where);
12703       break;
12704
12705     case ST_LABEL_BAD_TARGET:
12706       gfc_warning ("Label %d at %L defined but cannot be used",
12707                    label->value, &label->where);
12708       break;
12709
12710     default:
12711       break;
12712     }
12713
12714   warn_unused_fortran_label (label->right);
12715 }
12716
12717
12718 /* Returns the sequence type of a symbol or sequence.  */
12719
12720 static seq_type
12721 sequence_type (gfc_typespec ts)
12722 {
12723   seq_type result;
12724   gfc_component *c;
12725
12726   switch (ts.type)
12727   {
12728     case BT_DERIVED:
12729
12730       if (ts.u.derived->components == NULL)
12731         return SEQ_NONDEFAULT;
12732
12733       result = sequence_type (ts.u.derived->components->ts);
12734       for (c = ts.u.derived->components->next; c; c = c->next)
12735         if (sequence_type (c->ts) != result)
12736           return SEQ_MIXED;
12737
12738       return result;
12739
12740     case BT_CHARACTER:
12741       if (ts.kind != gfc_default_character_kind)
12742           return SEQ_NONDEFAULT;
12743
12744       return SEQ_CHARACTER;
12745
12746     case BT_INTEGER:
12747       if (ts.kind != gfc_default_integer_kind)
12748           return SEQ_NONDEFAULT;
12749
12750       return SEQ_NUMERIC;
12751
12752     case BT_REAL:
12753       if (!(ts.kind == gfc_default_real_kind
12754             || ts.kind == gfc_default_double_kind))
12755           return SEQ_NONDEFAULT;
12756
12757       return SEQ_NUMERIC;
12758
12759     case BT_COMPLEX:
12760       if (ts.kind != gfc_default_complex_kind)
12761           return SEQ_NONDEFAULT;
12762
12763       return SEQ_NUMERIC;
12764
12765     case BT_LOGICAL:
12766       if (ts.kind != gfc_default_logical_kind)
12767           return SEQ_NONDEFAULT;
12768
12769       return SEQ_NUMERIC;
12770
12771     default:
12772       return SEQ_NONDEFAULT;
12773   }
12774 }
12775
12776
12777 /* Resolve derived type EQUIVALENCE object.  */
12778
12779 static gfc_try
12780 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
12781 {
12782   gfc_component *c = derived->components;
12783
12784   if (!derived)
12785     return SUCCESS;
12786
12787   /* Shall not be an object of nonsequence derived type.  */
12788   if (!derived->attr.sequence)
12789     {
12790       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
12791                  "attribute to be an EQUIVALENCE object", sym->name,
12792                  &e->where);
12793       return FAILURE;
12794     }
12795
12796   /* Shall not have allocatable components.  */
12797   if (derived->attr.alloc_comp)
12798     {
12799       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
12800                  "components to be an EQUIVALENCE object",sym->name,
12801                  &e->where);
12802       return FAILURE;
12803     }
12804
12805   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
12806     {
12807       gfc_error ("Derived type variable '%s' at %L with default "
12808                  "initialization cannot be in EQUIVALENCE with a variable "
12809                  "in COMMON", sym->name, &e->where);
12810       return FAILURE;
12811     }
12812
12813   for (; c ; c = c->next)
12814     {
12815       if (c->ts.type == BT_DERIVED
12816           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
12817         return FAILURE;
12818
12819       /* Shall not be an object of sequence derived type containing a pointer
12820          in the structure.  */
12821       if (c->attr.pointer)
12822         {
12823           gfc_error ("Derived type variable '%s' at %L with pointer "
12824                      "component(s) cannot be an EQUIVALENCE object",
12825                      sym->name, &e->where);
12826           return FAILURE;
12827         }
12828     }
12829   return SUCCESS;
12830 }
12831
12832
12833 /* Resolve equivalence object. 
12834    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
12835    an allocatable array, an object of nonsequence derived type, an object of
12836    sequence derived type containing a pointer at any level of component
12837    selection, an automatic object, a function name, an entry name, a result
12838    name, a named constant, a structure component, or a subobject of any of
12839    the preceding objects.  A substring shall not have length zero.  A
12840    derived type shall not have components with default initialization nor
12841    shall two objects of an equivalence group be initialized.
12842    Either all or none of the objects shall have an protected attribute.
12843    The simple constraints are done in symbol.c(check_conflict) and the rest
12844    are implemented here.  */
12845
12846 static void
12847 resolve_equivalence (gfc_equiv *eq)
12848 {
12849   gfc_symbol *sym;
12850   gfc_symbol *first_sym;
12851   gfc_expr *e;
12852   gfc_ref *r;
12853   locus *last_where = NULL;
12854   seq_type eq_type, last_eq_type;
12855   gfc_typespec *last_ts;
12856   int object, cnt_protected;
12857   const char *msg;
12858
12859   last_ts = &eq->expr->symtree->n.sym->ts;
12860
12861   first_sym = eq->expr->symtree->n.sym;
12862
12863   cnt_protected = 0;
12864
12865   for (object = 1; eq; eq = eq->eq, object++)
12866     {
12867       e = eq->expr;
12868
12869       e->ts = e->symtree->n.sym->ts;
12870       /* match_varspec might not know yet if it is seeing
12871          array reference or substring reference, as it doesn't
12872          know the types.  */
12873       if (e->ref && e->ref->type == REF_ARRAY)
12874         {
12875           gfc_ref *ref = e->ref;
12876           sym = e->symtree->n.sym;
12877
12878           if (sym->attr.dimension)
12879             {
12880               ref->u.ar.as = sym->as;
12881               ref = ref->next;
12882             }
12883
12884           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
12885           if (e->ts.type == BT_CHARACTER
12886               && ref
12887               && ref->type == REF_ARRAY
12888               && ref->u.ar.dimen == 1
12889               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
12890               && ref->u.ar.stride[0] == NULL)
12891             {
12892               gfc_expr *start = ref->u.ar.start[0];
12893               gfc_expr *end = ref->u.ar.end[0];
12894               void *mem = NULL;
12895
12896               /* Optimize away the (:) reference.  */
12897               if (start == NULL && end == NULL)
12898                 {
12899                   if (e->ref == ref)
12900                     e->ref = ref->next;
12901                   else
12902                     e->ref->next = ref->next;
12903                   mem = ref;
12904                 }
12905               else
12906                 {
12907                   ref->type = REF_SUBSTRING;
12908                   if (start == NULL)
12909                     start = gfc_get_int_expr (gfc_default_integer_kind,
12910                                               NULL, 1);
12911                   ref->u.ss.start = start;
12912                   if (end == NULL && e->ts.u.cl)
12913                     end = gfc_copy_expr (e->ts.u.cl->length);
12914                   ref->u.ss.end = end;
12915                   ref->u.ss.length = e->ts.u.cl;
12916                   e->ts.u.cl = NULL;
12917                 }
12918               ref = ref->next;
12919               gfc_free (mem);
12920             }
12921
12922           /* Any further ref is an error.  */
12923           if (ref)
12924             {
12925               gcc_assert (ref->type == REF_ARRAY);
12926               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
12927                          &ref->u.ar.where);
12928               continue;
12929             }
12930         }
12931
12932       if (gfc_resolve_expr (e) == FAILURE)
12933         continue;
12934
12935       sym = e->symtree->n.sym;
12936
12937       if (sym->attr.is_protected)
12938         cnt_protected++;
12939       if (cnt_protected > 0 && cnt_protected != object)
12940         {
12941               gfc_error ("Either all or none of the objects in the "
12942                          "EQUIVALENCE set at %L shall have the "
12943                          "PROTECTED attribute",
12944                          &e->where);
12945               break;
12946         }
12947
12948       /* Shall not equivalence common block variables in a PURE procedure.  */
12949       if (sym->ns->proc_name
12950           && sym->ns->proc_name->attr.pure
12951           && sym->attr.in_common)
12952         {
12953           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
12954                      "object in the pure procedure '%s'",
12955                      sym->name, &e->where, sym->ns->proc_name->name);
12956           break;
12957         }
12958
12959       /* Shall not be a named constant.  */
12960       if (e->expr_type == EXPR_CONSTANT)
12961         {
12962           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
12963                      "object", sym->name, &e->where);
12964           continue;
12965         }
12966
12967       if (e->ts.type == BT_DERIVED
12968           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
12969         continue;
12970
12971       /* Check that the types correspond correctly:
12972          Note 5.28:
12973          A numeric sequence structure may be equivalenced to another sequence
12974          structure, an object of default integer type, default real type, double
12975          precision real type, default logical type such that components of the
12976          structure ultimately only become associated to objects of the same
12977          kind. A character sequence structure may be equivalenced to an object
12978          of default character kind or another character sequence structure.
12979          Other objects may be equivalenced only to objects of the same type and
12980          kind parameters.  */
12981
12982       /* Identical types are unconditionally OK.  */
12983       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
12984         goto identical_types;
12985
12986       last_eq_type = sequence_type (*last_ts);
12987       eq_type = sequence_type (sym->ts);
12988
12989       /* Since the pair of objects is not of the same type, mixed or
12990          non-default sequences can be rejected.  */
12991
12992       msg = "Sequence %s with mixed components in EQUIVALENCE "
12993             "statement at %L with different type objects";
12994       if ((object ==2
12995            && last_eq_type == SEQ_MIXED
12996            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
12997               == FAILURE)
12998           || (eq_type == SEQ_MIXED
12999               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13000                                  &e->where) == FAILURE))
13001         continue;
13002
13003       msg = "Non-default type object or sequence %s in EQUIVALENCE "
13004             "statement at %L with objects of different type";
13005       if ((object ==2
13006            && last_eq_type == SEQ_NONDEFAULT
13007            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
13008                               last_where) == FAILURE)
13009           || (eq_type == SEQ_NONDEFAULT
13010               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13011                                  &e->where) == FAILURE))
13012         continue;
13013
13014       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13015            "EQUIVALENCE statement at %L";
13016       if (last_eq_type == SEQ_CHARACTER
13017           && eq_type != SEQ_CHARACTER
13018           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13019                              &e->where) == FAILURE)
13020                 continue;
13021
13022       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13023            "EQUIVALENCE statement at %L";
13024       if (last_eq_type == SEQ_NUMERIC
13025           && eq_type != SEQ_NUMERIC
13026           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13027                              &e->where) == FAILURE)
13028                 continue;
13029
13030   identical_types:
13031       last_ts =&sym->ts;
13032       last_where = &e->where;
13033
13034       if (!e->ref)
13035         continue;
13036
13037       /* Shall not be an automatic array.  */
13038       if (e->ref->type == REF_ARRAY
13039           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13040         {
13041           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13042                      "an EQUIVALENCE object", sym->name, &e->where);
13043           continue;
13044         }
13045
13046       r = e->ref;
13047       while (r)
13048         {
13049           /* Shall not be a structure component.  */
13050           if (r->type == REF_COMPONENT)
13051             {
13052               gfc_error ("Structure component '%s' at %L cannot be an "
13053                          "EQUIVALENCE object",
13054                          r->u.c.component->name, &e->where);
13055               break;
13056             }
13057
13058           /* A substring shall not have length zero.  */
13059           if (r->type == REF_SUBSTRING)
13060             {
13061               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13062                 {
13063                   gfc_error ("Substring at %L has length zero",
13064                              &r->u.ss.start->where);
13065                   break;
13066                 }
13067             }
13068           r = r->next;
13069         }
13070     }
13071 }
13072
13073
13074 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13075
13076 static void
13077 resolve_fntype (gfc_namespace *ns)
13078 {
13079   gfc_entry_list *el;
13080   gfc_symbol *sym;
13081
13082   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13083     return;
13084
13085   /* If there are any entries, ns->proc_name is the entry master
13086      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13087   if (ns->entries)
13088     sym = ns->entries->sym;
13089   else
13090     sym = ns->proc_name;
13091   if (sym->result == sym
13092       && sym->ts.type == BT_UNKNOWN
13093       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13094       && !sym->attr.untyped)
13095     {
13096       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13097                  sym->name, &sym->declared_at);
13098       sym->attr.untyped = 1;
13099     }
13100
13101   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13102       && !sym->attr.contained
13103       && !gfc_check_access (sym->ts.u.derived->attr.access,
13104                             sym->ts.u.derived->ns->default_access)
13105       && gfc_check_access (sym->attr.access, sym->ns->default_access))
13106     {
13107       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13108                       "%L of PRIVATE type '%s'", sym->name,
13109                       &sym->declared_at, sym->ts.u.derived->name);
13110     }
13111
13112     if (ns->entries)
13113     for (el = ns->entries->next; el; el = el->next)
13114       {
13115         if (el->sym->result == el->sym
13116             && el->sym->ts.type == BT_UNKNOWN
13117             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13118             && !el->sym->attr.untyped)
13119           {
13120             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13121                        el->sym->name, &el->sym->declared_at);
13122             el->sym->attr.untyped = 1;
13123           }
13124       }
13125 }
13126
13127
13128 /* 12.3.2.1.1 Defined operators.  */
13129
13130 static gfc_try
13131 check_uop_procedure (gfc_symbol *sym, locus where)
13132 {
13133   gfc_formal_arglist *formal;
13134
13135   if (!sym->attr.function)
13136     {
13137       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13138                  sym->name, &where);
13139       return FAILURE;
13140     }
13141
13142   if (sym->ts.type == BT_CHARACTER
13143       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13144       && !(sym->result && sym->result->ts.u.cl
13145            && sym->result->ts.u.cl->length))
13146     {
13147       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13148                  "character length", sym->name, &where);
13149       return FAILURE;
13150     }
13151
13152   formal = sym->formal;
13153   if (!formal || !formal->sym)
13154     {
13155       gfc_error ("User operator procedure '%s' at %L must have at least "
13156                  "one argument", sym->name, &where);
13157       return FAILURE;
13158     }
13159
13160   if (formal->sym->attr.intent != INTENT_IN)
13161     {
13162       gfc_error ("First argument of operator interface at %L must be "
13163                  "INTENT(IN)", &where);
13164       return FAILURE;
13165     }
13166
13167   if (formal->sym->attr.optional)
13168     {
13169       gfc_error ("First argument of operator interface at %L cannot be "
13170                  "optional", &where);
13171       return FAILURE;
13172     }
13173
13174   formal = formal->next;
13175   if (!formal || !formal->sym)
13176     return SUCCESS;
13177
13178   if (formal->sym->attr.intent != INTENT_IN)
13179     {
13180       gfc_error ("Second argument of operator interface at %L must be "
13181                  "INTENT(IN)", &where);
13182       return FAILURE;
13183     }
13184
13185   if (formal->sym->attr.optional)
13186     {
13187       gfc_error ("Second argument of operator interface at %L cannot be "
13188                  "optional", &where);
13189       return FAILURE;
13190     }
13191
13192   if (formal->next)
13193     {
13194       gfc_error ("Operator interface at %L must have, at most, two "
13195                  "arguments", &where);
13196       return FAILURE;
13197     }
13198
13199   return SUCCESS;
13200 }
13201
13202 static void
13203 gfc_resolve_uops (gfc_symtree *symtree)
13204 {
13205   gfc_interface *itr;
13206
13207   if (symtree == NULL)
13208     return;
13209
13210   gfc_resolve_uops (symtree->left);
13211   gfc_resolve_uops (symtree->right);
13212
13213   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13214     check_uop_procedure (itr->sym, itr->sym->declared_at);
13215 }
13216
13217
13218 /* Examine all of the expressions associated with a program unit,
13219    assign types to all intermediate expressions, make sure that all
13220    assignments are to compatible types and figure out which names
13221    refer to which functions or subroutines.  It doesn't check code
13222    block, which is handled by resolve_code.  */
13223
13224 static void
13225 resolve_types (gfc_namespace *ns)
13226 {
13227   gfc_namespace *n;
13228   gfc_charlen *cl;
13229   gfc_data *d;
13230   gfc_equiv *eq;
13231   gfc_namespace* old_ns = gfc_current_ns;
13232
13233   /* Check that all IMPLICIT types are ok.  */
13234   if (!ns->seen_implicit_none)
13235     {
13236       unsigned letter;
13237       for (letter = 0; letter != GFC_LETTERS; ++letter)
13238         if (ns->set_flag[letter]
13239             && resolve_typespec_used (&ns->default_type[letter],
13240                                       &ns->implicit_loc[letter],
13241                                       NULL) == FAILURE)
13242           return;
13243     }
13244
13245   gfc_current_ns = ns;
13246
13247   resolve_entries (ns);
13248
13249   resolve_common_vars (ns->blank_common.head, false);
13250   resolve_common_blocks (ns->common_root);
13251
13252   resolve_contained_functions (ns);
13253
13254   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13255
13256   for (cl = ns->cl_list; cl; cl = cl->next)
13257     resolve_charlen (cl);
13258
13259   gfc_traverse_ns (ns, resolve_symbol);
13260
13261   resolve_fntype (ns);
13262
13263   for (n = ns->contained; n; n = n->sibling)
13264     {
13265       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13266         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13267                    "also be PURE", n->proc_name->name,
13268                    &n->proc_name->declared_at);
13269
13270       resolve_types (n);
13271     }
13272
13273   forall_flag = 0;
13274   gfc_check_interfaces (ns);
13275
13276   gfc_traverse_ns (ns, resolve_values);
13277
13278   if (ns->save_all)
13279     gfc_save_all (ns);
13280
13281   iter_stack = NULL;
13282   for (d = ns->data; d; d = d->next)
13283     resolve_data (d);
13284
13285   iter_stack = NULL;
13286   gfc_traverse_ns (ns, gfc_formalize_init_value);
13287
13288   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13289
13290   if (ns->common_root != NULL)
13291     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13292
13293   for (eq = ns->equiv; eq; eq = eq->next)
13294     resolve_equivalence (eq);
13295
13296   /* Warn about unused labels.  */
13297   if (warn_unused_label)
13298     warn_unused_fortran_label (ns->st_labels);
13299
13300   gfc_resolve_uops (ns->uop_root);
13301
13302   gfc_current_ns = old_ns;
13303 }
13304
13305
13306 /* Call resolve_code recursively.  */
13307
13308 static void
13309 resolve_codes (gfc_namespace *ns)
13310 {
13311   gfc_namespace *n;
13312   bitmap_obstack old_obstack;
13313
13314   for (n = ns->contained; n; n = n->sibling)
13315     resolve_codes (n);
13316
13317   gfc_current_ns = ns;
13318
13319   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13320   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13321     cs_base = NULL;
13322
13323   /* Set to an out of range value.  */
13324   current_entry_id = -1;
13325
13326   old_obstack = labels_obstack;
13327   bitmap_obstack_initialize (&labels_obstack);
13328
13329   resolve_code (ns->code, ns);
13330
13331   bitmap_obstack_release (&labels_obstack);
13332   labels_obstack = old_obstack;
13333 }
13334
13335
13336 /* This function is called after a complete program unit has been compiled.
13337    Its purpose is to examine all of the expressions associated with a program
13338    unit, assign types to all intermediate expressions, make sure that all
13339    assignments are to compatible types and figure out which names refer to
13340    which functions or subroutines.  */
13341
13342 void
13343 gfc_resolve (gfc_namespace *ns)
13344 {
13345   gfc_namespace *old_ns;
13346   code_stack *old_cs_base;
13347
13348   if (ns->resolved)
13349     return;
13350
13351   ns->resolved = -1;
13352   old_ns = gfc_current_ns;
13353   old_cs_base = cs_base;
13354
13355   resolve_types (ns);
13356   resolve_codes (ns);
13357
13358   gfc_current_ns = old_ns;
13359   cs_base = old_cs_base;
13360   ns->resolved = 1;
13361
13362   gfc_run_passes (ns);
13363 }