OSDN Git Service

2009-04-03 Tobias Burnus <burnus@net-b.de>
[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
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
33 /* Types used in equivalence statements.  */
34
35 typedef enum seq_type
36 {
37   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
38 }
39 seq_type;
40
41 /* Stack to keep track of the nesting of blocks as we move through the
42    code.  See resolve_branch() and resolve_code().  */
43
44 typedef struct code_stack
45 {
46   struct gfc_code *head, *current;
47   struct code_stack *prev;
48
49   /* This bitmap keeps track of the targets valid for a branch from
50      inside this block except for END {IF|SELECT}s of enclosing
51      blocks.  */
52   bitmap reachable_labels;
53 }
54 code_stack;
55
56 static code_stack *cs_base = NULL;
57
58
59 /* Nonzero if we're inside a FORALL block.  */
60
61 static int forall_flag;
62
63 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
64
65 static int omp_workshare_flag;
66
67 /* Nonzero if we are processing a formal arglist. The corresponding function
68    resets the flag each time that it is read.  */
69 static int formal_arg_flag = 0;
70
71 /* True if we are resolving a specification expression.  */
72 static int specification_expr = 0;
73
74 /* The id of the last entry seen.  */
75 static int current_entry_id;
76
77 /* We use bitmaps to determine if a branch target is valid.  */
78 static bitmap_obstack labels_obstack;
79
80 int
81 gfc_is_formal_arg (void)
82 {
83   return formal_arg_flag;
84 }
85
86
87 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
88    an ABSTRACT derived-type.  If where is not NULL, an error message with that
89    locus is printed, optionally using name.  */
90
91 static gfc_try
92 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
93 {
94   if (ts->type == BT_DERIVED && ts->derived->attr.abstract)
95     {
96       if (where)
97         {
98           if (name)
99             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
100                        name, where, ts->derived->name);
101           else
102             gfc_error ("ABSTRACT type '%s' used at %L",
103                        ts->derived->name, where);
104         }
105
106       return FAILURE;
107     }
108
109   return SUCCESS;
110 }
111
112
113 /* Resolve types of formal argument lists.  These have to be done early so that
114    the formal argument lists of module procedures can be copied to the
115    containing module before the individual procedures are resolved
116    individually.  We also resolve argument lists of procedures in interface
117    blocks because they are self-contained scoping units.
118
119    Since a dummy argument cannot be a non-dummy procedure, the only
120    resort left for untyped names are the IMPLICIT types.  */
121
122 static void
123 resolve_formal_arglist (gfc_symbol *proc)
124 {
125   gfc_formal_arglist *f;
126   gfc_symbol *sym;
127   int i;
128
129   if (proc->result != NULL)
130     sym = proc->result;
131   else
132     sym = proc;
133
134   if (gfc_elemental (proc)
135       || sym->attr.pointer || sym->attr.allocatable
136       || (sym->as && sym->as->rank > 0))
137     {
138       proc->attr.always_explicit = 1;
139       sym->attr.always_explicit = 1;
140     }
141
142   formal_arg_flag = 1;
143
144   for (f = proc->formal; f; f = f->next)
145     {
146       sym = f->sym;
147
148       if (sym == NULL)
149         {
150           /* Alternate return placeholder.  */
151           if (gfc_elemental (proc))
152             gfc_error ("Alternate return specifier in elemental subroutine "
153                        "'%s' at %L is not allowed", proc->name,
154                        &proc->declared_at);
155           if (proc->attr.function)
156             gfc_error ("Alternate return specifier in function "
157                        "'%s' at %L is not allowed", proc->name,
158                        &proc->declared_at);
159           continue;
160         }
161
162       if (sym->attr.if_source != IFSRC_UNKNOWN)
163         resolve_formal_arglist (sym);
164
165       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
166         {
167           if (gfc_pure (proc) && !gfc_pure (sym))
168             {
169               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
170                          "also be PURE", sym->name, &sym->declared_at);
171               continue;
172             }
173
174           if (gfc_elemental (proc))
175             {
176               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
177                          "procedure", &sym->declared_at);
178               continue;
179             }
180
181           if (sym->attr.function
182                 && sym->ts.type == BT_UNKNOWN
183                 && sym->attr.intrinsic)
184             {
185               gfc_intrinsic_sym *isym;
186               isym = gfc_find_function (sym->name);
187               if (isym == NULL || !isym->specific)
188                 {
189                   gfc_error ("Unable to find a specific INTRINSIC procedure "
190                              "for the reference '%s' at %L", sym->name,
191                              &sym->declared_at);
192                 }
193               sym->ts = isym->ts;
194             }
195
196           continue;
197         }
198
199       if (sym->ts.type == BT_UNKNOWN)
200         {
201           if (!sym->attr.function || sym->result == sym)
202             gfc_set_default_type (sym, 1, sym->ns);
203         }
204
205       gfc_resolve_array_spec (sym->as, 0);
206
207       /* We can't tell if an array with dimension (:) is assumed or deferred
208          shape until we know if it has the pointer or allocatable attributes.
209       */
210       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
211           && !(sym->attr.pointer || sym->attr.allocatable))
212         {
213           sym->as->type = AS_ASSUMED_SHAPE;
214           for (i = 0; i < sym->as->rank; i++)
215             sym->as->lower[i] = gfc_int_expr (1);
216         }
217
218       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
219           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
220           || sym->attr.optional)
221         {
222           proc->attr.always_explicit = 1;
223           if (proc->result)
224             proc->result->attr.always_explicit = 1;
225         }
226
227       /* If the flavor is unknown at this point, it has to be a variable.
228          A procedure specification would have already set the type.  */
229
230       if (sym->attr.flavor == FL_UNKNOWN)
231         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
232
233       if (gfc_pure (proc) && !sym->attr.pointer
234           && sym->attr.flavor != FL_PROCEDURE)
235         {
236           if (proc->attr.function && sym->attr.intent != INTENT_IN)
237             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
238                        "INTENT(IN)", sym->name, proc->name,
239                        &sym->declared_at);
240
241           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
242             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
243                        "have its INTENT specified", sym->name, proc->name,
244                        &sym->declared_at);
245         }
246
247       if (gfc_elemental (proc))
248         {
249           if (sym->as != NULL)
250             {
251               gfc_error ("Argument '%s' of elemental procedure at %L must "
252                          "be scalar", sym->name, &sym->declared_at);
253               continue;
254             }
255
256           if (sym->attr.pointer)
257             {
258               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
259                          "have the POINTER attribute", sym->name,
260                          &sym->declared_at);
261               continue;
262             }
263
264           if (sym->attr.flavor == FL_PROCEDURE)
265             {
266               gfc_error ("Dummy procedure '%s' not allowed in elemental "
267                          "procedure '%s' at %L", sym->name, proc->name,
268                          &sym->declared_at);
269               continue;
270             }
271         }
272
273       /* Each dummy shall be specified to be scalar.  */
274       if (proc->attr.proc == PROC_ST_FUNCTION)
275         {
276           if (sym->as != NULL)
277             {
278               gfc_error ("Argument '%s' of statement function at %L must "
279                          "be scalar", sym->name, &sym->declared_at);
280               continue;
281             }
282
283           if (sym->ts.type == BT_CHARACTER)
284             {
285               gfc_charlen *cl = sym->ts.cl;
286               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
287                 {
288                   gfc_error ("Character-valued argument '%s' of statement "
289                              "function at %L must have constant length",
290                              sym->name, &sym->declared_at);
291                   continue;
292                 }
293             }
294         }
295     }
296   formal_arg_flag = 0;
297 }
298
299
300 /* Work function called when searching for symbols that have argument lists
301    associated with them.  */
302
303 static void
304 find_arglists (gfc_symbol *sym)
305 {
306   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
307     return;
308
309   resolve_formal_arglist (sym);
310 }
311
312
313 /* Given a namespace, resolve all formal argument lists within the namespace.
314  */
315
316 static void
317 resolve_formal_arglists (gfc_namespace *ns)
318 {
319   if (ns == NULL)
320     return;
321
322   gfc_traverse_ns (ns, find_arglists);
323 }
324
325
326 static void
327 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
328 {
329   gfc_try t;
330
331   /* If this namespace is not a function or an entry master function,
332      ignore it.  */
333   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
334       || sym->attr.entry_master)
335     return;
336
337   /* Try to find out of what the return type is.  */
338   if (sym->result->ts.type == BT_UNKNOWN)
339     {
340       t = gfc_set_default_type (sym->result, 0, ns);
341
342       if (t == FAILURE && !sym->result->attr.untyped)
343         {
344           if (sym->result == sym)
345             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
346                        sym->name, &sym->declared_at);
347           else
348             gfc_error ("Result '%s' of contained function '%s' at %L has "
349                        "no IMPLICIT type", sym->result->name, sym->name,
350                        &sym->result->declared_at);
351           sym->result->attr.untyped = 1;
352         }
353     }
354
355   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
356      type, lists the only ways a character length value of * can be used:
357      dummy arguments of procedures, named constants, and function results
358      in external functions.  Internal function results are not on that list;
359      ergo, not permitted.  */
360
361   if (sym->result->ts.type == BT_CHARACTER)
362     {
363       gfc_charlen *cl = sym->result->ts.cl;
364       if (!cl || !cl->length)
365         gfc_error ("Character-valued internal function '%s' at %L must "
366                    "not be assumed length", sym->name, &sym->declared_at);
367     }
368 }
369
370
371 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
372    introduce duplicates.  */
373
374 static void
375 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
376 {
377   gfc_formal_arglist *f, *new_arglist;
378   gfc_symbol *new_sym;
379
380   for (; new_args != NULL; new_args = new_args->next)
381     {
382       new_sym = new_args->sym;
383       /* See if this arg is already in the formal argument list.  */
384       for (f = proc->formal; f; f = f->next)
385         {
386           if (new_sym == f->sym)
387             break;
388         }
389
390       if (f)
391         continue;
392
393       /* Add a new argument.  Argument order is not important.  */
394       new_arglist = gfc_get_formal_arglist ();
395       new_arglist->sym = new_sym;
396       new_arglist->next = proc->formal;
397       proc->formal  = new_arglist;
398     }
399 }
400
401
402 /* Flag the arguments that are not present in all entries.  */
403
404 static void
405 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
406 {
407   gfc_formal_arglist *f, *head;
408   head = new_args;
409
410   for (f = proc->formal; f; f = f->next)
411     {
412       if (f->sym == NULL)
413         continue;
414
415       for (new_args = head; new_args; new_args = new_args->next)
416         {
417           if (new_args->sym == f->sym)
418             break;
419         }
420
421       if (new_args)
422         continue;
423
424       f->sym->attr.not_always_present = 1;
425     }
426 }
427
428
429 /* Resolve alternate entry points.  If a symbol has multiple entry points we
430    create a new master symbol for the main routine, and turn the existing
431    symbol into an entry point.  */
432
433 static void
434 resolve_entries (gfc_namespace *ns)
435 {
436   gfc_namespace *old_ns;
437   gfc_code *c;
438   gfc_symbol *proc;
439   gfc_entry_list *el;
440   char name[GFC_MAX_SYMBOL_LEN + 1];
441   static int master_count = 0;
442
443   if (ns->proc_name == NULL)
444     return;
445
446   /* No need to do anything if this procedure doesn't have alternate entry
447      points.  */
448   if (!ns->entries)
449     return;
450
451   /* We may already have resolved alternate entry points.  */
452   if (ns->proc_name->attr.entry_master)
453     return;
454
455   /* If this isn't a procedure something has gone horribly wrong.  */
456   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
457
458   /* Remember the current namespace.  */
459   old_ns = gfc_current_ns;
460
461   gfc_current_ns = ns;
462
463   /* Add the main entry point to the list of entry points.  */
464   el = gfc_get_entry_list ();
465   el->sym = ns->proc_name;
466   el->id = 0;
467   el->next = ns->entries;
468   ns->entries = el;
469   ns->proc_name->attr.entry = 1;
470
471   /* If it is a module function, it needs to be in the right namespace
472      so that gfc_get_fake_result_decl can gather up the results. The
473      need for this arose in get_proc_name, where these beasts were
474      left in their own namespace, to keep prior references linked to
475      the entry declaration.*/
476   if (ns->proc_name->attr.function
477       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
478     el->sym->ns = ns;
479
480   /* Do the same for entries where the master is not a module
481      procedure.  These are retained in the module namespace because
482      of the module procedure declaration.  */
483   for (el = el->next; el; el = el->next)
484     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
485           && el->sym->attr.mod_proc)
486       el->sym->ns = ns;
487   el = ns->entries;
488
489   /* Add an entry statement for it.  */
490   c = gfc_get_code ();
491   c->op = EXEC_ENTRY;
492   c->ext.entry = el;
493   c->next = ns->code;
494   ns->code = c;
495
496   /* Create a new symbol for the master function.  */
497   /* Give the internal function a unique name (within this file).
498      Also include the function name so the user has some hope of figuring
499      out what is going on.  */
500   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
501             master_count++, ns->proc_name->name);
502   gfc_get_ha_symbol (name, &proc);
503   gcc_assert (proc != NULL);
504
505   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
506   if (ns->proc_name->attr.subroutine)
507     gfc_add_subroutine (&proc->attr, proc->name, NULL);
508   else
509     {
510       gfc_symbol *sym;
511       gfc_typespec *ts, *fts;
512       gfc_array_spec *as, *fas;
513       gfc_add_function (&proc->attr, proc->name, NULL);
514       proc->result = proc;
515       fas = ns->entries->sym->as;
516       fas = fas ? fas : ns->entries->sym->result->as;
517       fts = &ns->entries->sym->result->ts;
518       if (fts->type == BT_UNKNOWN)
519         fts = gfc_get_default_type (ns->entries->sym->result, NULL);
520       for (el = ns->entries->next; el; el = el->next)
521         {
522           ts = &el->sym->result->ts;
523           as = el->sym->as;
524           as = as ? as : el->sym->result->as;
525           if (ts->type == BT_UNKNOWN)
526             ts = gfc_get_default_type (el->sym->result, NULL);
527
528           if (! gfc_compare_types (ts, fts)
529               || (el->sym->result->attr.dimension
530                   != ns->entries->sym->result->attr.dimension)
531               || (el->sym->result->attr.pointer
532                   != ns->entries->sym->result->attr.pointer))
533             break;
534           else if (as && fas && ns->entries->sym->result != el->sym->result
535                       && gfc_compare_array_spec (as, fas) == 0)
536             gfc_error ("Function %s at %L has entries with mismatched "
537                        "array specifications", ns->entries->sym->name,
538                        &ns->entries->sym->declared_at);
539           /* The characteristics need to match and thus both need to have
540              the same string length, i.e. both len=*, or both len=4.
541              Having both len=<variable> is also possible, but difficult to
542              check at compile time.  */
543           else if (ts->type == BT_CHARACTER && ts->cl && fts->cl
544                    && (((ts->cl->length && !fts->cl->length)
545                         ||(!ts->cl->length && fts->cl->length))
546                        || (ts->cl->length
547                            && ts->cl->length->expr_type
548                               != fts->cl->length->expr_type)
549                        || (ts->cl->length
550                            && ts->cl->length->expr_type == EXPR_CONSTANT
551                            && mpz_cmp (ts->cl->length->value.integer,
552                                        fts->cl->length->value.integer) != 0)))
553             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
554                             "entries returning variables of different "
555                             "string lengths", ns->entries->sym->name,
556                             &ns->entries->sym->declared_at);
557         }
558
559       if (el == NULL)
560         {
561           sym = ns->entries->sym->result;
562           /* All result types the same.  */
563           proc->ts = *fts;
564           if (sym->attr.dimension)
565             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
566           if (sym->attr.pointer)
567             gfc_add_pointer (&proc->attr, NULL);
568         }
569       else
570         {
571           /* Otherwise the result will be passed through a union by
572              reference.  */
573           proc->attr.mixed_entry_master = 1;
574           for (el = ns->entries; el; el = el->next)
575             {
576               sym = el->sym->result;
577               if (sym->attr.dimension)
578                 {
579                   if (el == ns->entries)
580                     gfc_error ("FUNCTION result %s can't be an array in "
581                                "FUNCTION %s at %L", sym->name,
582                                ns->entries->sym->name, &sym->declared_at);
583                   else
584                     gfc_error ("ENTRY result %s can't be an array in "
585                                "FUNCTION %s at %L", sym->name,
586                                ns->entries->sym->name, &sym->declared_at);
587                 }
588               else if (sym->attr.pointer)
589                 {
590                   if (el == ns->entries)
591                     gfc_error ("FUNCTION result %s can't be a POINTER in "
592                                "FUNCTION %s at %L", sym->name,
593                                ns->entries->sym->name, &sym->declared_at);
594                   else
595                     gfc_error ("ENTRY result %s can't be a POINTER in "
596                                "FUNCTION %s at %L", sym->name,
597                                ns->entries->sym->name, &sym->declared_at);
598                 }
599               else
600                 {
601                   ts = &sym->ts;
602                   if (ts->type == BT_UNKNOWN)
603                     ts = gfc_get_default_type (sym, NULL);
604                   switch (ts->type)
605                     {
606                     case BT_INTEGER:
607                       if (ts->kind == gfc_default_integer_kind)
608                         sym = NULL;
609                       break;
610                     case BT_REAL:
611                       if (ts->kind == gfc_default_real_kind
612                           || ts->kind == gfc_default_double_kind)
613                         sym = NULL;
614                       break;
615                     case BT_COMPLEX:
616                       if (ts->kind == gfc_default_complex_kind)
617                         sym = NULL;
618                       break;
619                     case BT_LOGICAL:
620                       if (ts->kind == gfc_default_logical_kind)
621                         sym = NULL;
622                       break;
623                     case BT_UNKNOWN:
624                       /* We will issue error elsewhere.  */
625                       sym = NULL;
626                       break;
627                     default:
628                       break;
629                     }
630                   if (sym)
631                     {
632                       if (el == ns->entries)
633                         gfc_error ("FUNCTION result %s can't be of type %s "
634                                    "in FUNCTION %s at %L", sym->name,
635                                    gfc_typename (ts), ns->entries->sym->name,
636                                    &sym->declared_at);
637                       else
638                         gfc_error ("ENTRY result %s can't be of type %s "
639                                    "in FUNCTION %s at %L", sym->name,
640                                    gfc_typename (ts), ns->entries->sym->name,
641                                    &sym->declared_at);
642                     }
643                 }
644             }
645         }
646     }
647   proc->attr.access = ACCESS_PRIVATE;
648   proc->attr.entry_master = 1;
649
650   /* Merge all the entry point arguments.  */
651   for (el = ns->entries; el; el = el->next)
652     merge_argument_lists (proc, el->sym->formal);
653
654   /* Check the master formal arguments for any that are not
655      present in all entry points.  */
656   for (el = ns->entries; el; el = el->next)
657     check_argument_lists (proc, el->sym->formal);
658
659   /* Use the master function for the function body.  */
660   ns->proc_name = proc;
661
662   /* Finalize the new symbols.  */
663   gfc_commit_symbols ();
664
665   /* Restore the original namespace.  */
666   gfc_current_ns = old_ns;
667 }
668
669
670 static bool
671 has_default_initializer (gfc_symbol *der)
672 {
673   gfc_component *c;
674
675   gcc_assert (der->attr.flavor == FL_DERIVED);
676   for (c = der->components; c; c = c->next)
677     if ((c->ts.type != BT_DERIVED && c->initializer)
678         || (c->ts.type == BT_DERIVED
679             && (!c->attr.pointer && has_default_initializer (c->ts.derived))))
680       break;
681
682   return c != NULL;
683 }
684
685 /* Resolve common variables.  */
686 static void
687 resolve_common_vars (gfc_symbol *sym, bool named_common)
688 {
689   gfc_symbol *csym = sym;
690
691   for (; csym; csym = csym->common_next)
692     {
693       if (csym->value || csym->attr.data)
694         {
695           if (!csym->ns->is_block_data)
696             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
697                             "but only in BLOCK DATA initialization is "
698                             "allowed", csym->name, &csym->declared_at);
699           else if (!named_common)
700             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
701                             "in a blank COMMON but initialization is only "
702                             "allowed in named common blocks", csym->name,
703                             &csym->declared_at);
704         }
705
706       if (csym->ts.type != BT_DERIVED)
707         continue;
708
709       if (!(csym->ts.derived->attr.sequence
710             || csym->ts.derived->attr.is_bind_c))
711         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
712                        "has neither the SEQUENCE nor the BIND(C) "
713                        "attribute", csym->name, &csym->declared_at);
714       if (csym->ts.derived->attr.alloc_comp)
715         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
716                        "has an ultimate component that is "
717                        "allocatable", csym->name, &csym->declared_at);
718       if (has_default_initializer (csym->ts.derived))
719         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
720                        "may not have default initializer", csym->name,
721                        &csym->declared_at);
722
723       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
724         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
725     }
726 }
727
728 /* Resolve common blocks.  */
729 static void
730 resolve_common_blocks (gfc_symtree *common_root)
731 {
732   gfc_symbol *sym;
733
734   if (common_root == NULL)
735     return;
736
737   if (common_root->left)
738     resolve_common_blocks (common_root->left);
739   if (common_root->right)
740     resolve_common_blocks (common_root->right);
741
742   resolve_common_vars (common_root->n.common->head, true);
743
744   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
745   if (sym == NULL)
746     return;
747
748   if (sym->attr.flavor == FL_PARAMETER)
749     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
750                sym->name, &common_root->n.common->where, &sym->declared_at);
751
752   if (sym->attr.intrinsic)
753     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
754                sym->name, &common_root->n.common->where);
755   else if (sym->attr.result
756            ||(sym->attr.function && gfc_current_ns->proc_name == sym))
757     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
758                     "that is also a function result", sym->name,
759                     &common_root->n.common->where);
760   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
761            && sym->attr.proc != PROC_ST_FUNCTION)
762     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
763                     "that is also a global procedure", sym->name,
764                     &common_root->n.common->where);
765 }
766
767
768 /* Resolve contained function types.  Because contained functions can call one
769    another, they have to be worked out before any of the contained procedures
770    can be resolved.
771
772    The good news is that if a function doesn't already have a type, the only
773    way it can get one is through an IMPLICIT type or a RESULT variable, because
774    by definition contained functions are contained namespace they're contained
775    in, not in a sibling or parent namespace.  */
776
777 static void
778 resolve_contained_functions (gfc_namespace *ns)
779 {
780   gfc_namespace *child;
781   gfc_entry_list *el;
782
783   resolve_formal_arglists (ns);
784
785   for (child = ns->contained; child; child = child->sibling)
786     {
787       /* Resolve alternate entry points first.  */
788       resolve_entries (child);
789
790       /* Then check function return types.  */
791       resolve_contained_fntype (child->proc_name, child);
792       for (el = child->entries; el; el = el->next)
793         resolve_contained_fntype (el->sym, child);
794     }
795 }
796
797
798 /* Resolve all of the elements of a structure constructor and make sure that
799    the types are correct.  */
800
801 static gfc_try
802 resolve_structure_cons (gfc_expr *expr)
803 {
804   gfc_constructor *cons;
805   gfc_component *comp;
806   gfc_try t;
807   symbol_attribute a;
808
809   t = SUCCESS;
810   cons = expr->value.constructor;
811   /* A constructor may have references if it is the result of substituting a
812      parameter variable.  In this case we just pull out the component we
813      want.  */
814   if (expr->ref)
815     comp = expr->ref->u.c.sym->components;
816   else
817     comp = expr->ts.derived->components;
818
819   /* See if the user is trying to invoke a structure constructor for one of
820      the iso_c_binding derived types.  */
821   if (expr->ts.derived && expr->ts.derived->ts.is_iso_c && cons
822       && cons->expr != NULL)
823     {
824       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
825                  expr->ts.derived->name, &(expr->where));
826       return FAILURE;
827     }
828
829   for (; comp; comp = comp->next, cons = cons->next)
830     {
831       int rank;
832
833       if (!cons->expr)
834         continue;
835
836       if (gfc_resolve_expr (cons->expr) == FAILURE)
837         {
838           t = FAILURE;
839           continue;
840         }
841
842       rank = comp->as ? comp->as->rank : 0;
843       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
844           && (comp->attr.allocatable || cons->expr->rank))
845         {
846           gfc_error ("The rank of the element in the derived type "
847                      "constructor at %L does not match that of the "
848                      "component (%d/%d)", &cons->expr->where,
849                      cons->expr->rank, rank);
850           t = FAILURE;
851         }
852
853       /* If we don't have the right type, try to convert it.  */
854
855       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
856         {
857           t = FAILURE;
858           if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
859             gfc_error ("The element in the derived type constructor at %L, "
860                        "for pointer component '%s', is %s but should be %s",
861                        &cons->expr->where, comp->name,
862                        gfc_basic_typename (cons->expr->ts.type),
863                        gfc_basic_typename (comp->ts.type));
864           else
865             t = gfc_convert_type (cons->expr, &comp->ts, 1);
866         }
867
868       if (cons->expr->expr_type == EXPR_NULL
869             && !(comp->attr.pointer || comp->attr.allocatable))
870         {
871           t = FAILURE;
872           gfc_error ("The NULL in the derived type constructor at %L is "
873                      "being applied to component '%s', which is neither "
874                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
875                      comp->name);
876         }
877
878       if (!comp->attr.pointer || cons->expr->expr_type == EXPR_NULL)
879         continue;
880
881       a = gfc_expr_attr (cons->expr);
882
883       if (!a.pointer && !a.target)
884         {
885           t = FAILURE;
886           gfc_error ("The element in the derived type constructor at %L, "
887                      "for pointer component '%s' should be a POINTER or "
888                      "a TARGET", &cons->expr->where, comp->name);
889         }
890     }
891
892   return t;
893 }
894
895
896 /****************** Expression name resolution ******************/
897
898 /* Returns 0 if a symbol was not declared with a type or
899    attribute declaration statement, nonzero otherwise.  */
900
901 static int
902 was_declared (gfc_symbol *sym)
903 {
904   symbol_attribute a;
905
906   a = sym->attr;
907
908   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
909     return 1;
910
911   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
912       || a.optional || a.pointer || a.save || a.target || a.volatile_
913       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN)
914     return 1;
915
916   return 0;
917 }
918
919
920 /* Determine if a symbol is generic or not.  */
921
922 static int
923 generic_sym (gfc_symbol *sym)
924 {
925   gfc_symbol *s;
926
927   if (sym->attr.generic ||
928       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
929     return 1;
930
931   if (was_declared (sym) || sym->ns->parent == NULL)
932     return 0;
933
934   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
935   
936   if (s != NULL)
937     {
938       if (s == sym)
939         return 0;
940       else
941         return generic_sym (s);
942     }
943
944   return 0;
945 }
946
947
948 /* Determine if a symbol is specific or not.  */
949
950 static int
951 specific_sym (gfc_symbol *sym)
952 {
953   gfc_symbol *s;
954
955   if (sym->attr.if_source == IFSRC_IFBODY
956       || sym->attr.proc == PROC_MODULE
957       || sym->attr.proc == PROC_INTERNAL
958       || sym->attr.proc == PROC_ST_FUNCTION
959       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
960       || sym->attr.external)
961     return 1;
962
963   if (was_declared (sym) || sym->ns->parent == NULL)
964     return 0;
965
966   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
967
968   return (s == NULL) ? 0 : specific_sym (s);
969 }
970
971
972 /* Figure out if the procedure is specific, generic or unknown.  */
973
974 typedef enum
975 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
976 proc_type;
977
978 static proc_type
979 procedure_kind (gfc_symbol *sym)
980 {
981   if (generic_sym (sym))
982     return PTYPE_GENERIC;
983
984   if (specific_sym (sym))
985     return PTYPE_SPECIFIC;
986
987   return PTYPE_UNKNOWN;
988 }
989
990 /* Check references to assumed size arrays.  The flag need_full_assumed_size
991    is nonzero when matching actual arguments.  */
992
993 static int need_full_assumed_size = 0;
994
995 static bool
996 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
997 {
998   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
999       return false;
1000
1001   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1002      What should it be?  */
1003   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1004           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1005                && (e->ref->u.ar.type == AR_FULL))
1006     {
1007       gfc_error ("The upper bound in the last dimension must "
1008                  "appear in the reference to the assumed size "
1009                  "array '%s' at %L", sym->name, &e->where);
1010       return true;
1011     }
1012   return false;
1013 }
1014
1015
1016 /* Look for bad assumed size array references in argument expressions
1017   of elemental and array valued intrinsic procedures.  Since this is
1018   called from procedure resolution functions, it only recurses at
1019   operators.  */
1020
1021 static bool
1022 resolve_assumed_size_actual (gfc_expr *e)
1023 {
1024   if (e == NULL)
1025    return false;
1026
1027   switch (e->expr_type)
1028     {
1029     case EXPR_VARIABLE:
1030       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1031         return true;
1032       break;
1033
1034     case EXPR_OP:
1035       if (resolve_assumed_size_actual (e->value.op.op1)
1036           || resolve_assumed_size_actual (e->value.op.op2))
1037         return true;
1038       break;
1039
1040     default:
1041       break;
1042     }
1043   return false;
1044 }
1045
1046
1047 /* Check a generic procedure, passed as an actual argument, to see if
1048    there is a matching specific name.  If none, it is an error, and if
1049    more than one, the reference is ambiguous.  */
1050 static int
1051 count_specific_procs (gfc_expr *e)
1052 {
1053   int n;
1054   gfc_interface *p;
1055   gfc_symbol *sym;
1056         
1057   n = 0;
1058   sym = e->symtree->n.sym;
1059
1060   for (p = sym->generic; p; p = p->next)
1061     if (strcmp (sym->name, p->sym->name) == 0)
1062       {
1063         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1064                                        sym->name);
1065         n++;
1066       }
1067
1068   if (n > 1)
1069     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1070                &e->where);
1071
1072   if (n == 0)
1073     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1074                "argument at %L", sym->name, &e->where);
1075
1076   return n;
1077 }
1078
1079
1080 /* See if a call to sym could possibly be a not allowed RECURSION because of
1081    a missing RECURIVE declaration.  This means that either sym is the current
1082    context itself, or sym is the parent of a contained procedure calling its
1083    non-RECURSIVE containing procedure.
1084    This also works if sym is an ENTRY.  */
1085
1086 static bool
1087 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1088 {
1089   gfc_symbol* proc_sym;
1090   gfc_symbol* context_proc;
1091
1092   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1093
1094   /* If we've got an ENTRY, find real procedure.  */
1095   if (sym->attr.entry && sym->ns->entries)
1096     proc_sym = sym->ns->entries->sym;
1097   else
1098     proc_sym = sym;
1099
1100   /* If sym is RECURSIVE, all is well of course.  */
1101   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1102     return false;
1103
1104   /* Find the context procdure's "real" symbol if it has entries.  */
1105   context_proc = (context->entries ? context->entries->sym
1106                                    : context->proc_name);
1107   if (!context_proc)
1108     return true;
1109
1110   /* A call from sym's body to itself is recursion, of course.  */
1111   if (context_proc == proc_sym)
1112     return true;
1113
1114   /* The same is true if context is a contained procedure and sym the
1115      containing one.  */
1116   if (context_proc->attr.contained)
1117     {
1118       gfc_symbol* parent_proc;
1119
1120       gcc_assert (context->parent);
1121       parent_proc = (context->parent->entries ? context->parent->entries->sym
1122                                               : context->parent->proc_name);
1123
1124       if (parent_proc == proc_sym)
1125         return true;
1126     }
1127
1128   return false;
1129 }
1130
1131
1132 /* Resolve a procedure expression, like passing it to a called procedure or as
1133    RHS for a procedure pointer assignment.  */
1134
1135 static gfc_try
1136 resolve_procedure_expression (gfc_expr* expr)
1137 {
1138   gfc_symbol* sym;
1139
1140   if (expr->expr_type != EXPR_VARIABLE)
1141     return SUCCESS;
1142   gcc_assert (expr->symtree);
1143
1144   sym = expr->symtree->n.sym;
1145   if (sym->attr.flavor != FL_PROCEDURE
1146       || (sym->attr.function && sym->result == sym))
1147     return SUCCESS;
1148
1149   /* A non-RECURSIVE procedure that is used as procedure expression within its
1150      own body is in danger of being called recursively.  */
1151   if (is_illegal_recursion (sym, gfc_current_ns))
1152     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1153                  " itself recursively.  Declare it RECURSIVE or use"
1154                  " -frecursive", sym->name, &expr->where);
1155   
1156   return SUCCESS;
1157 }
1158
1159
1160 /* Resolve an actual argument list.  Most of the time, this is just
1161    resolving the expressions in the list.
1162    The exception is that we sometimes have to decide whether arguments
1163    that look like procedure arguments are really simple variable
1164    references.  */
1165
1166 static gfc_try
1167 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1168                         bool no_formal_args)
1169 {
1170   gfc_symbol *sym;
1171   gfc_symtree *parent_st;
1172   gfc_expr *e;
1173   int save_need_full_assumed_size;
1174         
1175   for (; arg; arg = arg->next)
1176     {
1177       e = arg->expr;
1178       if (e == NULL)
1179         {
1180           /* Check the label is a valid branching target.  */
1181           if (arg->label)
1182             {
1183               if (arg->label->defined == ST_LABEL_UNKNOWN)
1184                 {
1185                   gfc_error ("Label %d referenced at %L is never defined",
1186                              arg->label->value, &arg->label->where);
1187                   return FAILURE;
1188                 }
1189             }
1190           continue;
1191         }
1192
1193       if (e->expr_type == EXPR_VARIABLE
1194             && e->symtree->n.sym->attr.generic
1195             && no_formal_args
1196             && count_specific_procs (e) != 1)
1197         return FAILURE;
1198
1199       if (e->ts.type != BT_PROCEDURE)
1200         {
1201           save_need_full_assumed_size = need_full_assumed_size;
1202           if (e->expr_type != EXPR_VARIABLE)
1203             need_full_assumed_size = 0;
1204           if (gfc_resolve_expr (e) != SUCCESS)
1205             return FAILURE;
1206           need_full_assumed_size = save_need_full_assumed_size;
1207           goto argument_list;
1208         }
1209
1210       /* See if the expression node should really be a variable reference.  */
1211
1212       sym = e->symtree->n.sym;
1213
1214       if (sym->attr.flavor == FL_PROCEDURE
1215           || sym->attr.intrinsic
1216           || sym->attr.external)
1217         {
1218           int actual_ok;
1219
1220           /* If a procedure is not already determined to be something else
1221              check if it is intrinsic.  */
1222           if (!sym->attr.intrinsic
1223               && !(sym->attr.external || sym->attr.use_assoc
1224                    || sym->attr.if_source == IFSRC_IFBODY)
1225               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1226             sym->attr.intrinsic = 1;
1227
1228           if (sym->attr.proc == PROC_ST_FUNCTION)
1229             {
1230               gfc_error ("Statement function '%s' at %L is not allowed as an "
1231                          "actual argument", sym->name, &e->where);
1232             }
1233
1234           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1235                                                sym->attr.subroutine);
1236           if (sym->attr.intrinsic && actual_ok == 0)
1237             {
1238               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1239                          "actual argument", sym->name, &e->where);
1240             }
1241
1242           if (sym->attr.contained && !sym->attr.use_assoc
1243               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1244             {
1245               gfc_error ("Internal procedure '%s' is not allowed as an "
1246                          "actual argument at %L", sym->name, &e->where);
1247             }
1248
1249           if (sym->attr.elemental && !sym->attr.intrinsic)
1250             {
1251               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1252                          "allowed as an actual argument at %L", sym->name,
1253                          &e->where);
1254             }
1255
1256           /* Check if a generic interface has a specific procedure
1257             with the same name before emitting an error.  */
1258           if (sym->attr.generic && count_specific_procs (e) != 1)
1259             return FAILURE;
1260           
1261           /* Just in case a specific was found for the expression.  */
1262           sym = e->symtree->n.sym;
1263
1264           /* If the symbol is the function that names the current (or
1265              parent) scope, then we really have a variable reference.  */
1266
1267           if (sym->attr.function && sym->result == sym
1268               && (sym->ns->proc_name == sym
1269                   || (sym->ns->parent != NULL
1270                       && sym->ns->parent->proc_name == sym)))
1271             goto got_variable;
1272
1273           /* If all else fails, see if we have a specific intrinsic.  */
1274           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1275             {
1276               gfc_intrinsic_sym *isym;
1277
1278               isym = gfc_find_function (sym->name);
1279               if (isym == NULL || !isym->specific)
1280                 {
1281                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1282                              "for the reference '%s' at %L", sym->name,
1283                              &e->where);
1284                   return FAILURE;
1285                 }
1286               sym->ts = isym->ts;
1287               sym->attr.intrinsic = 1;
1288               sym->attr.function = 1;
1289             }
1290
1291           if (gfc_resolve_expr (e) == FAILURE)
1292             return FAILURE;
1293           goto argument_list;
1294         }
1295
1296       /* See if the name is a module procedure in a parent unit.  */
1297
1298       if (was_declared (sym) || sym->ns->parent == NULL)
1299         goto got_variable;
1300
1301       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1302         {
1303           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1304           return FAILURE;
1305         }
1306
1307       if (parent_st == NULL)
1308         goto got_variable;
1309
1310       sym = parent_st->n.sym;
1311       e->symtree = parent_st;           /* Point to the right thing.  */
1312
1313       if (sym->attr.flavor == FL_PROCEDURE
1314           || sym->attr.intrinsic
1315           || sym->attr.external)
1316         {
1317           if (gfc_resolve_expr (e) == FAILURE)
1318             return FAILURE;
1319           goto argument_list;
1320         }
1321
1322     got_variable:
1323       e->expr_type = EXPR_VARIABLE;
1324       e->ts = sym->ts;
1325       if (sym->as != NULL)
1326         {
1327           e->rank = sym->as->rank;
1328           e->ref = gfc_get_ref ();
1329           e->ref->type = REF_ARRAY;
1330           e->ref->u.ar.type = AR_FULL;
1331           e->ref->u.ar.as = sym->as;
1332         }
1333
1334       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1335          primary.c (match_actual_arg). If above code determines that it
1336          is a  variable instead, it needs to be resolved as it was not
1337          done at the beginning of this function.  */
1338       save_need_full_assumed_size = need_full_assumed_size;
1339       if (e->expr_type != EXPR_VARIABLE)
1340         need_full_assumed_size = 0;
1341       if (gfc_resolve_expr (e) != SUCCESS)
1342         return FAILURE;
1343       need_full_assumed_size = save_need_full_assumed_size;
1344
1345     argument_list:
1346       /* Check argument list functions %VAL, %LOC and %REF.  There is
1347          nothing to do for %REF.  */
1348       if (arg->name && arg->name[0] == '%')
1349         {
1350           if (strncmp ("%VAL", arg->name, 4) == 0)
1351             {
1352               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1353                 {
1354                   gfc_error ("By-value argument at %L is not of numeric "
1355                              "type", &e->where);
1356                   return FAILURE;
1357                 }
1358
1359               if (e->rank)
1360                 {
1361                   gfc_error ("By-value argument at %L cannot be an array or "
1362                              "an array section", &e->where);
1363                 return FAILURE;
1364                 }
1365
1366               /* Intrinsics are still PROC_UNKNOWN here.  However,
1367                  since same file external procedures are not resolvable
1368                  in gfortran, it is a good deal easier to leave them to
1369                  intrinsic.c.  */
1370               if (ptype != PROC_UNKNOWN
1371                   && ptype != PROC_DUMMY
1372                   && ptype != PROC_EXTERNAL
1373                   && ptype != PROC_MODULE)
1374                 {
1375                   gfc_error ("By-value argument at %L is not allowed "
1376                              "in this context", &e->where);
1377                   return FAILURE;
1378                 }
1379             }
1380
1381           /* Statement functions have already been excluded above.  */
1382           else if (strncmp ("%LOC", arg->name, 4) == 0
1383                    && e->ts.type == BT_PROCEDURE)
1384             {
1385               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1386                 {
1387                   gfc_error ("Passing internal procedure at %L by location "
1388                              "not allowed", &e->where);
1389                   return FAILURE;
1390                 }
1391             }
1392         }
1393     }
1394
1395   return SUCCESS;
1396 }
1397
1398
1399 /* Do the checks of the actual argument list that are specific to elemental
1400    procedures.  If called with c == NULL, we have a function, otherwise if
1401    expr == NULL, we have a subroutine.  */
1402
1403 static gfc_try
1404 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1405 {
1406   gfc_actual_arglist *arg0;
1407   gfc_actual_arglist *arg;
1408   gfc_symbol *esym = NULL;
1409   gfc_intrinsic_sym *isym = NULL;
1410   gfc_expr *e = NULL;
1411   gfc_intrinsic_arg *iformal = NULL;
1412   gfc_formal_arglist *eformal = NULL;
1413   bool formal_optional = false;
1414   bool set_by_optional = false;
1415   int i;
1416   int rank = 0;
1417
1418   /* Is this an elemental procedure?  */
1419   if (expr && expr->value.function.actual != NULL)
1420     {
1421       if (expr->value.function.esym != NULL
1422           && expr->value.function.esym->attr.elemental)
1423         {
1424           arg0 = expr->value.function.actual;
1425           esym = expr->value.function.esym;
1426         }
1427       else if (expr->value.function.isym != NULL
1428                && expr->value.function.isym->elemental)
1429         {
1430           arg0 = expr->value.function.actual;
1431           isym = expr->value.function.isym;
1432         }
1433       else
1434         return SUCCESS;
1435     }
1436   else if (c && c->ext.actual != NULL)
1437     {
1438       arg0 = c->ext.actual;
1439       
1440       if (c->resolved_sym)
1441         esym = c->resolved_sym;
1442       else
1443         esym = c->symtree->n.sym;
1444       gcc_assert (esym);
1445
1446       if (!esym->attr.elemental)
1447         return SUCCESS;
1448     }
1449   else
1450     return SUCCESS;
1451
1452   /* The rank of an elemental is the rank of its array argument(s).  */
1453   for (arg = arg0; arg; arg = arg->next)
1454     {
1455       if (arg->expr != NULL && arg->expr->rank > 0)
1456         {
1457           rank = arg->expr->rank;
1458           if (arg->expr->expr_type == EXPR_VARIABLE
1459               && arg->expr->symtree->n.sym->attr.optional)
1460             set_by_optional = true;
1461
1462           /* Function specific; set the result rank and shape.  */
1463           if (expr)
1464             {
1465               expr->rank = rank;
1466               if (!expr->shape && arg->expr->shape)
1467                 {
1468                   expr->shape = gfc_get_shape (rank);
1469                   for (i = 0; i < rank; i++)
1470                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1471                 }
1472             }
1473           break;
1474         }
1475     }
1476
1477   /* If it is an array, it shall not be supplied as an actual argument
1478      to an elemental procedure unless an array of the same rank is supplied
1479      as an actual argument corresponding to a nonoptional dummy argument of
1480      that elemental procedure(12.4.1.5).  */
1481   formal_optional = false;
1482   if (isym)
1483     iformal = isym->formal;
1484   else
1485     eformal = esym->formal;
1486
1487   for (arg = arg0; arg; arg = arg->next)
1488     {
1489       if (eformal)
1490         {
1491           if (eformal->sym && eformal->sym->attr.optional)
1492             formal_optional = true;
1493           eformal = eformal->next;
1494         }
1495       else if (isym && iformal)
1496         {
1497           if (iformal->optional)
1498             formal_optional = true;
1499           iformal = iformal->next;
1500         }
1501       else if (isym)
1502         formal_optional = true;
1503
1504       if (pedantic && arg->expr != NULL
1505           && arg->expr->expr_type == EXPR_VARIABLE
1506           && arg->expr->symtree->n.sym->attr.optional
1507           && formal_optional
1508           && arg->expr->rank
1509           && (set_by_optional || arg->expr->rank != rank)
1510           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1511         {
1512           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1513                        "MISSING, it cannot be the actual argument of an "
1514                        "ELEMENTAL procedure unless there is a non-optional "
1515                        "argument with the same rank (12.4.1.5)",
1516                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1517           return FAILURE;
1518         }
1519     }
1520
1521   for (arg = arg0; arg; arg = arg->next)
1522     {
1523       if (arg->expr == NULL || arg->expr->rank == 0)
1524         continue;
1525
1526       /* Being elemental, the last upper bound of an assumed size array
1527          argument must be present.  */
1528       if (resolve_assumed_size_actual (arg->expr))
1529         return FAILURE;
1530
1531       /* Elemental procedure's array actual arguments must conform.  */
1532       if (e != NULL)
1533         {
1534           if (gfc_check_conformance ("elemental procedure", arg->expr, e)
1535               == FAILURE)
1536             return FAILURE;
1537         }
1538       else
1539         e = arg->expr;
1540     }
1541
1542   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1543      is an array, the intent inout/out variable needs to be also an array.  */
1544   if (rank > 0 && esym && expr == NULL)
1545     for (eformal = esym->formal, arg = arg0; arg && eformal;
1546          arg = arg->next, eformal = eformal->next)
1547       if ((eformal->sym->attr.intent == INTENT_OUT
1548            || eformal->sym->attr.intent == INTENT_INOUT)
1549           && arg->expr && arg->expr->rank == 0)
1550         {
1551           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1552                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1553                      "actual argument is an array", &arg->expr->where,
1554                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1555                      : "INOUT", eformal->sym->name, esym->name);
1556           return FAILURE;
1557         }
1558   return SUCCESS;
1559 }
1560
1561
1562 /* Go through each actual argument in ACTUAL and see if it can be
1563    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1564    function being called, or NULL if not known.  */
1565
1566 static void
1567 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1568 {
1569   gfc_actual_arglist *ap;
1570   gfc_expr *expr;
1571
1572   for (ap = actual; ap; ap = ap->next)
1573     if (ap->expr
1574         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1575         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1576                                          NOT_ELEMENTAL))
1577       ap->expr->inline_noncopying_intrinsic = 1;
1578 }
1579
1580
1581 /* This function does the checking of references to global procedures
1582    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1583    77 and 95 standards.  It checks for a gsymbol for the name, making
1584    one if it does not already exist.  If it already exists, then the
1585    reference being resolved must correspond to the type of gsymbol.
1586    Otherwise, the new symbol is equipped with the attributes of the
1587    reference.  The corresponding code that is called in creating
1588    global entities is parse.c.
1589
1590    In addition, for all but -std=legacy, the gsymbols are used to
1591    check the interfaces of external procedures from the same file.
1592    The namespace of the gsymbol is resolved and then, once this is
1593    done the interface is checked.  */
1594
1595 static void
1596 resolve_global_procedure (gfc_symbol *sym, locus *where,
1597                           gfc_actual_arglist **actual, int sub)
1598 {
1599   gfc_gsymbol * gsym;
1600   gfc_namespace *ns;
1601   unsigned int type;
1602
1603   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1604
1605   gsym = gfc_get_gsymbol (sym->name);
1606
1607   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1608     gfc_global_used (gsym, where);
1609
1610   if (gfc_option.flag_whole_file
1611         && gsym->type != GSYM_UNKNOWN
1612         && gsym->ns
1613         && gsym->ns->proc_name
1614         && gsym->ns->proc_name->formal)
1615     {
1616       /* Make sure that translation for the gsymbol occurs before
1617          the procedure currently being resolved.  */
1618       ns = gsym->ns->resolved ? NULL : gfc_global_ns_list;
1619       for (; ns && ns != gsym->ns; ns = ns->sibling)
1620         {
1621           if (ns->sibling == gsym->ns)
1622             {
1623               ns->sibling = gsym->ns->sibling;
1624               gsym->ns->sibling = gfc_global_ns_list;
1625               gfc_global_ns_list = gsym->ns;
1626               break;
1627             }
1628         }
1629
1630       if (!gsym->ns->resolved)
1631         gfc_resolve (gsym->ns);
1632
1633       gfc_procedure_use (gsym->ns->proc_name, actual, where);
1634     }
1635
1636   if (gsym->type == GSYM_UNKNOWN)
1637     {
1638       gsym->type = type;
1639       gsym->where = *where;
1640     }
1641
1642   gsym->used = 1;
1643 }
1644
1645
1646 /************* Function resolution *************/
1647
1648 /* Resolve a function call known to be generic.
1649    Section 14.1.2.4.1.  */
1650
1651 static match
1652 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
1653 {
1654   gfc_symbol *s;
1655
1656   if (sym->attr.generic)
1657     {
1658       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
1659       if (s != NULL)
1660         {
1661           expr->value.function.name = s->name;
1662           expr->value.function.esym = s;
1663
1664           if (s->ts.type != BT_UNKNOWN)
1665             expr->ts = s->ts;
1666           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
1667             expr->ts = s->result->ts;
1668
1669           if (s->as != NULL)
1670             expr->rank = s->as->rank;
1671           else if (s->result != NULL && s->result->as != NULL)
1672             expr->rank = s->result->as->rank;
1673
1674           gfc_set_sym_referenced (expr->value.function.esym);
1675
1676           return MATCH_YES;
1677         }
1678
1679       /* TODO: Need to search for elemental references in generic
1680          interface.  */
1681     }
1682
1683   if (sym->attr.intrinsic)
1684     return gfc_intrinsic_func_interface (expr, 0);
1685
1686   return MATCH_NO;
1687 }
1688
1689
1690 static gfc_try
1691 resolve_generic_f (gfc_expr *expr)
1692 {
1693   gfc_symbol *sym;
1694   match m;
1695
1696   sym = expr->symtree->n.sym;
1697
1698   for (;;)
1699     {
1700       m = resolve_generic_f0 (expr, sym);
1701       if (m == MATCH_YES)
1702         return SUCCESS;
1703       else if (m == MATCH_ERROR)
1704         return FAILURE;
1705
1706 generic:
1707       if (sym->ns->parent == NULL)
1708         break;
1709       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1710
1711       if (sym == NULL)
1712         break;
1713       if (!generic_sym (sym))
1714         goto generic;
1715     }
1716
1717   /* Last ditch attempt.  See if the reference is to an intrinsic
1718      that possesses a matching interface.  14.1.2.4  */
1719   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
1720     {
1721       gfc_error ("There is no specific function for the generic '%s' at %L",
1722                  expr->symtree->n.sym->name, &expr->where);
1723       return FAILURE;
1724     }
1725
1726   m = gfc_intrinsic_func_interface (expr, 0);
1727   if (m == MATCH_YES)
1728     return SUCCESS;
1729   if (m == MATCH_NO)
1730     gfc_error ("Generic function '%s' at %L is not consistent with a "
1731                "specific intrinsic interface", expr->symtree->n.sym->name,
1732                &expr->where);
1733
1734   return FAILURE;
1735 }
1736
1737
1738 /* Resolve a function call known to be specific.  */
1739
1740 static match
1741 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
1742 {
1743   match m;
1744
1745   /* See if we have an intrinsic interface.  */
1746
1747   if (sym->ts.interface != NULL && sym->ts.interface->attr.intrinsic)
1748     {
1749       gfc_intrinsic_sym *isym;
1750       isym = gfc_find_function (sym->ts.interface->name);
1751
1752       /* Existence of isym should be checked already.  */
1753       gcc_assert (isym);
1754
1755       sym->ts.type = isym->ts.type;
1756       sym->ts.kind = isym->ts.kind;
1757       sym->attr.function = 1;
1758       sym->attr.proc = PROC_EXTERNAL;
1759       goto found;
1760     }
1761
1762   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1763     {
1764       if (sym->attr.dummy)
1765         {
1766           sym->attr.proc = PROC_DUMMY;
1767           goto found;
1768         }
1769
1770       sym->attr.proc = PROC_EXTERNAL;
1771       goto found;
1772     }
1773
1774   if (sym->attr.proc == PROC_MODULE
1775       || sym->attr.proc == PROC_ST_FUNCTION
1776       || sym->attr.proc == PROC_INTERNAL)
1777     goto found;
1778
1779   if (sym->attr.intrinsic)
1780     {
1781       m = gfc_intrinsic_func_interface (expr, 1);
1782       if (m == MATCH_YES)
1783         return MATCH_YES;
1784       if (m == MATCH_NO)
1785         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
1786                    "with an intrinsic", sym->name, &expr->where);
1787
1788       return MATCH_ERROR;
1789     }
1790
1791   return MATCH_NO;
1792
1793 found:
1794   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1795
1796   expr->ts = sym->ts;
1797   expr->value.function.name = sym->name;
1798   expr->value.function.esym = sym;
1799   if (sym->as != NULL)
1800     expr->rank = sym->as->rank;
1801
1802   return MATCH_YES;
1803 }
1804
1805
1806 static gfc_try
1807 resolve_specific_f (gfc_expr *expr)
1808 {
1809   gfc_symbol *sym;
1810   match m;
1811
1812   sym = expr->symtree->n.sym;
1813
1814   for (;;)
1815     {
1816       m = resolve_specific_f0 (sym, expr);
1817       if (m == MATCH_YES)
1818         return SUCCESS;
1819       if (m == MATCH_ERROR)
1820         return FAILURE;
1821
1822       if (sym->ns->parent == NULL)
1823         break;
1824
1825       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1826
1827       if (sym == NULL)
1828         break;
1829     }
1830
1831   gfc_error ("Unable to resolve the specific function '%s' at %L",
1832              expr->symtree->n.sym->name, &expr->where);
1833
1834   return SUCCESS;
1835 }
1836
1837
1838 /* Resolve a procedure call not known to be generic nor specific.  */
1839
1840 static gfc_try
1841 resolve_unknown_f (gfc_expr *expr)
1842 {
1843   gfc_symbol *sym;
1844   gfc_typespec *ts;
1845
1846   sym = expr->symtree->n.sym;
1847
1848   if (sym->attr.dummy)
1849     {
1850       sym->attr.proc = PROC_DUMMY;
1851       expr->value.function.name = sym->name;
1852       goto set_type;
1853     }
1854
1855   /* See if we have an intrinsic function reference.  */
1856
1857   if (gfc_is_intrinsic (sym, 0, expr->where))
1858     {
1859       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
1860         return SUCCESS;
1861       return FAILURE;
1862     }
1863
1864   /* The reference is to an external name.  */
1865
1866   sym->attr.proc = PROC_EXTERNAL;
1867   expr->value.function.name = sym->name;
1868   expr->value.function.esym = expr->symtree->n.sym;
1869
1870   if (sym->as != NULL)
1871     expr->rank = sym->as->rank;
1872
1873   /* Type of the expression is either the type of the symbol or the
1874      default type of the symbol.  */
1875
1876 set_type:
1877   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1878
1879   if (sym->ts.type != BT_UNKNOWN)
1880     expr->ts = sym->ts;
1881   else
1882     {
1883       ts = gfc_get_default_type (sym, sym->ns);
1884
1885       if (ts->type == BT_UNKNOWN)
1886         {
1887           gfc_error ("Function '%s' at %L has no IMPLICIT type",
1888                      sym->name, &expr->where);
1889           return FAILURE;
1890         }
1891       else
1892         expr->ts = *ts;
1893     }
1894
1895   return SUCCESS;
1896 }
1897
1898
1899 /* Return true, if the symbol is an external procedure.  */
1900 static bool
1901 is_external_proc (gfc_symbol *sym)
1902 {
1903   if (!sym->attr.dummy && !sym->attr.contained
1904         && !(sym->attr.intrinsic
1905               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
1906         && sym->attr.proc != PROC_ST_FUNCTION
1907         && !sym->attr.use_assoc
1908         && sym->name)
1909     return true;
1910
1911   return false;
1912 }
1913
1914
1915 /* Figure out if a function reference is pure or not.  Also set the name
1916    of the function for a potential error message.  Return nonzero if the
1917    function is PURE, zero if not.  */
1918 static int
1919 pure_stmt_function (gfc_expr *, gfc_symbol *);
1920
1921 static int
1922 pure_function (gfc_expr *e, const char **name)
1923 {
1924   int pure;
1925
1926   *name = NULL;
1927
1928   if (e->symtree != NULL
1929         && e->symtree->n.sym != NULL
1930         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
1931     return pure_stmt_function (e, e->symtree->n.sym);
1932
1933   if (e->value.function.esym)
1934     {
1935       pure = gfc_pure (e->value.function.esym);
1936       *name = e->value.function.esym->name;
1937     }
1938   else if (e->value.function.isym)
1939     {
1940       pure = e->value.function.isym->pure
1941              || e->value.function.isym->elemental;
1942       *name = e->value.function.isym->name;
1943     }
1944   else
1945     {
1946       /* Implicit functions are not pure.  */
1947       pure = 0;
1948       *name = e->value.function.name;
1949     }
1950
1951   return pure;
1952 }
1953
1954
1955 static bool
1956 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
1957                  int *f ATTRIBUTE_UNUSED)
1958 {
1959   const char *name;
1960
1961   /* Don't bother recursing into other statement functions
1962      since they will be checked individually for purity.  */
1963   if (e->expr_type != EXPR_FUNCTION
1964         || !e->symtree
1965         || e->symtree->n.sym == sym
1966         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
1967     return false;
1968
1969   return pure_function (e, &name) ? false : true;
1970 }
1971
1972
1973 static int
1974 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
1975 {
1976   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
1977 }
1978
1979
1980 static gfc_try
1981 is_scalar_expr_ptr (gfc_expr *expr)
1982 {
1983   gfc_try retval = SUCCESS;
1984   gfc_ref *ref;
1985   int start;
1986   int end;
1987
1988   /* See if we have a gfc_ref, which means we have a substring, array
1989      reference, or a component.  */
1990   if (expr->ref != NULL)
1991     {
1992       ref = expr->ref;
1993       while (ref->next != NULL)
1994         ref = ref->next;
1995
1996       switch (ref->type)
1997         {
1998         case REF_SUBSTRING:
1999           if (ref->u.ss.length != NULL 
2000               && ref->u.ss.length->length != NULL
2001               && ref->u.ss.start
2002               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2003               && ref->u.ss.end
2004               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2005             {
2006               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2007               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2008               if (end - start + 1 != 1)
2009                 retval = FAILURE;
2010             }
2011           else
2012             retval = FAILURE;
2013           break;
2014         case REF_ARRAY:
2015           if (ref->u.ar.type == AR_ELEMENT)
2016             retval = SUCCESS;
2017           else if (ref->u.ar.type == AR_FULL)
2018             {
2019               /* The user can give a full array if the array is of size 1.  */
2020               if (ref->u.ar.as != NULL
2021                   && ref->u.ar.as->rank == 1
2022                   && ref->u.ar.as->type == AS_EXPLICIT
2023                   && ref->u.ar.as->lower[0] != NULL
2024                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2025                   && ref->u.ar.as->upper[0] != NULL
2026                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2027                 {
2028                   /* If we have a character string, we need to check if
2029                      its length is one.  */
2030                   if (expr->ts.type == BT_CHARACTER)
2031                     {
2032                       if (expr->ts.cl == NULL
2033                           || expr->ts.cl->length == NULL
2034                           || mpz_cmp_si (expr->ts.cl->length->value.integer, 1)
2035                           != 0)
2036                         retval = FAILURE;
2037                     }
2038                   else
2039                     {
2040                       /* We have constant lower and upper bounds.  If the
2041                          difference between is 1, it can be considered a
2042                          scalar.  */
2043                       start = (int) mpz_get_si
2044                                 (ref->u.ar.as->lower[0]->value.integer);
2045                       end = (int) mpz_get_si
2046                                 (ref->u.ar.as->upper[0]->value.integer);
2047                       if (end - start + 1 != 1)
2048                         retval = FAILURE;
2049                    }
2050                 }
2051               else
2052                 retval = FAILURE;
2053             }
2054           else
2055             retval = FAILURE;
2056           break;
2057         default:
2058           retval = SUCCESS;
2059           break;
2060         }
2061     }
2062   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2063     {
2064       /* Character string.  Make sure it's of length 1.  */
2065       if (expr->ts.cl == NULL
2066           || expr->ts.cl->length == NULL
2067           || mpz_cmp_si (expr->ts.cl->length->value.integer, 1) != 0)
2068         retval = FAILURE;
2069     }
2070   else if (expr->rank != 0)
2071     retval = FAILURE;
2072
2073   return retval;
2074 }
2075
2076
2077 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2078    and, in the case of c_associated, set the binding label based on
2079    the arguments.  */
2080
2081 static gfc_try
2082 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2083                           gfc_symbol **new_sym)
2084 {
2085   char name[GFC_MAX_SYMBOL_LEN + 1];
2086   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2087   int optional_arg = 0, is_pointer = 0;
2088   gfc_try retval = SUCCESS;
2089   gfc_symbol *args_sym;
2090   gfc_typespec *arg_ts;
2091
2092   if (args->expr->expr_type == EXPR_CONSTANT
2093       || args->expr->expr_type == EXPR_OP
2094       || args->expr->expr_type == EXPR_NULL)
2095     {
2096       gfc_error ("Argument to '%s' at %L is not a variable",
2097                  sym->name, &(args->expr->where));
2098       return FAILURE;
2099     }
2100
2101   args_sym = args->expr->symtree->n.sym;
2102
2103   /* The typespec for the actual arg should be that stored in the expr
2104      and not necessarily that of the expr symbol (args_sym), because
2105      the actual expression could be a part-ref of the expr symbol.  */
2106   arg_ts = &(args->expr->ts);
2107
2108   is_pointer = gfc_is_data_pointer (args->expr);
2109     
2110   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2111     {
2112       /* If the user gave two args then they are providing something for
2113          the optional arg (the second cptr).  Therefore, set the name and
2114          binding label to the c_associated for two cptrs.  Otherwise,
2115          set c_associated to expect one cptr.  */
2116       if (args->next)
2117         {
2118           /* two args.  */
2119           sprintf (name, "%s_2", sym->name);
2120           sprintf (binding_label, "%s_2", sym->binding_label);
2121           optional_arg = 1;
2122         }
2123       else
2124         {
2125           /* one arg.  */
2126           sprintf (name, "%s_1", sym->name);
2127           sprintf (binding_label, "%s_1", sym->binding_label);
2128           optional_arg = 0;
2129         }
2130
2131       /* Get a new symbol for the version of c_associated that
2132          will get called.  */
2133       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2134     }
2135   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2136            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2137     {
2138       sprintf (name, "%s", sym->name);
2139       sprintf (binding_label, "%s", sym->binding_label);
2140
2141       /* Error check the call.  */
2142       if (args->next != NULL)
2143         {
2144           gfc_error_now ("More actual than formal arguments in '%s' "
2145                          "call at %L", name, &(args->expr->where));
2146           retval = FAILURE;
2147         }
2148       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2149         {
2150           /* Make sure we have either the target or pointer attribute.  */
2151           if (!args_sym->attr.target && !is_pointer)
2152             {
2153               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2154                              "a TARGET or an associated pointer",
2155                              args_sym->name,
2156                              sym->name, &(args->expr->where));
2157               retval = FAILURE;
2158             }
2159
2160           /* See if we have interoperable type and type param.  */
2161           if (verify_c_interop (arg_ts) == SUCCESS
2162               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2163             {
2164               if (args_sym->attr.target == 1)
2165                 {
2166                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2167                      has the target attribute and is interoperable.  */
2168                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2169                      allocatable variable that has the TARGET attribute and
2170                      is not an array of zero size.  */
2171                   if (args_sym->attr.allocatable == 1)
2172                     {
2173                       if (args_sym->attr.dimension != 0 
2174                           && (args_sym->as && args_sym->as->rank == 0))
2175                         {
2176                           gfc_error_now ("Allocatable variable '%s' used as a "
2177                                          "parameter to '%s' at %L must not be "
2178                                          "an array of zero size",
2179                                          args_sym->name, sym->name,
2180                                          &(args->expr->where));
2181                           retval = FAILURE;
2182                         }
2183                     }
2184                   else
2185                     {
2186                       /* A non-allocatable target variable with C
2187                          interoperable type and type parameters must be
2188                          interoperable.  */
2189                       if (args_sym && args_sym->attr.dimension)
2190                         {
2191                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2192                             {
2193                               gfc_error ("Assumed-shape array '%s' at %L "
2194                                          "cannot be an argument to the "
2195                                          "procedure '%s' because "
2196                                          "it is not C interoperable",
2197                                          args_sym->name,
2198                                          &(args->expr->where), sym->name);
2199                               retval = FAILURE;
2200                             }
2201                           else if (args_sym->as->type == AS_DEFERRED)
2202                             {
2203                               gfc_error ("Deferred-shape array '%s' at %L "
2204                                          "cannot be an argument to the "
2205                                          "procedure '%s' because "
2206                                          "it is not C interoperable",
2207                                          args_sym->name,
2208                                          &(args->expr->where), sym->name);
2209                               retval = FAILURE;
2210                             }
2211                         }
2212                               
2213                       /* Make sure it's not a character string.  Arrays of
2214                          any type should be ok if the variable is of a C
2215                          interoperable type.  */
2216                       if (arg_ts->type == BT_CHARACTER)
2217                         if (arg_ts->cl != NULL
2218                             && (arg_ts->cl->length == NULL
2219                                 || arg_ts->cl->length->expr_type
2220                                    != EXPR_CONSTANT
2221                                 || mpz_cmp_si
2222                                     (arg_ts->cl->length->value.integer, 1)
2223                                    != 0)
2224                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2225                           {
2226                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2227                                            "at %L must have a length of 1",
2228                                            args_sym->name, sym->name,
2229                                            &(args->expr->where));
2230                             retval = FAILURE;
2231                           }
2232                     }
2233                 }
2234               else if (is_pointer
2235                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2236                 {
2237                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2238                      scalar pointer.  */
2239                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2240                                  "associated scalar POINTER", args_sym->name,
2241                                  sym->name, &(args->expr->where));
2242                   retval = FAILURE;
2243                 }
2244             }
2245           else
2246             {
2247               /* The parameter is not required to be C interoperable.  If it
2248                  is not C interoperable, it must be a nonpolymorphic scalar
2249                  with no length type parameters.  It still must have either
2250                  the pointer or target attribute, and it can be
2251                  allocatable (but must be allocated when c_loc is called).  */
2252               if (args->expr->rank != 0 
2253                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2254                 {
2255                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2256                                  "scalar", args_sym->name, sym->name,
2257                                  &(args->expr->where));
2258                   retval = FAILURE;
2259                 }
2260               else if (arg_ts->type == BT_CHARACTER 
2261                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2262                 {
2263                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2264                                  "%L must have a length of 1",
2265                                  args_sym->name, sym->name,
2266                                  &(args->expr->where));
2267                   retval = FAILURE;
2268                 }
2269             }
2270         }
2271       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2272         {
2273           if (args_sym->attr.flavor != FL_PROCEDURE)
2274             {
2275               /* TODO: Update this error message to allow for procedure
2276                  pointers once they are implemented.  */
2277               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2278                              "procedure",
2279                              args_sym->name, sym->name,
2280                              &(args->expr->where));
2281               retval = FAILURE;
2282             }
2283           else if (args_sym->attr.is_bind_c != 1)
2284             {
2285               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2286                              "BIND(C)",
2287                              args_sym->name, sym->name,
2288                              &(args->expr->where));
2289               retval = FAILURE;
2290             }
2291         }
2292       
2293       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2294       *new_sym = sym;
2295     }
2296   else
2297     {
2298       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2299                           "iso_c_binding function: '%s'!\n", sym->name);
2300     }
2301
2302   return retval;
2303 }
2304
2305
2306 /* Resolve a function call, which means resolving the arguments, then figuring
2307    out which entity the name refers to.  */
2308 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2309    to INTENT(OUT) or INTENT(INOUT).  */
2310
2311 static gfc_try
2312 resolve_function (gfc_expr *expr)
2313 {
2314   gfc_actual_arglist *arg;
2315   gfc_symbol *sym;
2316   const char *name;
2317   gfc_try t;
2318   int temp;
2319   procedure_type p = PROC_INTRINSIC;
2320   bool no_formal_args;
2321
2322   sym = NULL;
2323   if (expr->symtree)
2324     sym = expr->symtree->n.sym;
2325
2326   if (sym && sym->attr.intrinsic
2327       && !gfc_find_function (sym->name)
2328       && gfc_find_subroutine (sym->name)
2329       && sym->attr.function)
2330     {
2331       gfc_error ("Intrinsic subroutine '%s' used as "
2332                   "a function at %L", sym->name, &expr->where);
2333       return FAILURE;
2334     }
2335
2336   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2337     {
2338       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2339       return FAILURE;
2340     }
2341
2342   if (sym && sym->attr.abstract)
2343     {
2344       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2345                  sym->name, &expr->where);
2346       return FAILURE;
2347     }
2348
2349   /* Switch off assumed size checking and do this again for certain kinds
2350      of procedure, once the procedure itself is resolved.  */
2351   need_full_assumed_size++;
2352
2353   if (expr->symtree && expr->symtree->n.sym)
2354     p = expr->symtree->n.sym->attr.proc;
2355
2356   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2357   if (resolve_actual_arglist (expr->value.function.actual,
2358                               p, no_formal_args) == FAILURE)
2359       return FAILURE;
2360
2361   /* Need to setup the call to the correct c_associated, depending on
2362      the number of cptrs to user gives to compare.  */
2363   if (sym && sym->attr.is_iso_c == 1)
2364     {
2365       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2366           == FAILURE)
2367         return FAILURE;
2368       
2369       /* Get the symtree for the new symbol (resolved func).
2370          the old one will be freed later, when it's no longer used.  */
2371       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2372     }
2373   
2374   /* Resume assumed_size checking.  */
2375   need_full_assumed_size--;
2376
2377   /* If the procedure is external, check for usage.  */
2378   if (sym && is_external_proc (sym))
2379     resolve_global_procedure (sym, &expr->where,
2380                               &expr->value.function.actual, 0);
2381
2382   if (sym && sym->ts.type == BT_CHARACTER
2383       && sym->ts.cl
2384       && sym->ts.cl->length == NULL
2385       && !sym->attr.dummy
2386       && expr->value.function.esym == NULL
2387       && !sym->attr.contained)
2388     {
2389       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2390       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2391                  "be used at %L since it is not a dummy argument",
2392                  sym->name, &expr->where);
2393       return FAILURE;
2394     }
2395
2396   /* See if function is already resolved.  */
2397
2398   if (expr->value.function.name != NULL)
2399     {
2400       if (expr->ts.type == BT_UNKNOWN)
2401         expr->ts = sym->ts;
2402       t = SUCCESS;
2403     }
2404   else
2405     {
2406       /* Apply the rules of section 14.1.2.  */
2407
2408       switch (procedure_kind (sym))
2409         {
2410         case PTYPE_GENERIC:
2411           t = resolve_generic_f (expr);
2412           break;
2413
2414         case PTYPE_SPECIFIC:
2415           t = resolve_specific_f (expr);
2416           break;
2417
2418         case PTYPE_UNKNOWN:
2419           t = resolve_unknown_f (expr);
2420           break;
2421
2422         default:
2423           gfc_internal_error ("resolve_function(): bad function type");
2424         }
2425     }
2426
2427   /* If the expression is still a function (it might have simplified),
2428      then we check to see if we are calling an elemental function.  */
2429
2430   if (expr->expr_type != EXPR_FUNCTION)
2431     return t;
2432
2433   temp = need_full_assumed_size;
2434   need_full_assumed_size = 0;
2435
2436   if (resolve_elemental_actual (expr, NULL) == FAILURE)
2437     return FAILURE;
2438
2439   if (omp_workshare_flag
2440       && expr->value.function.esym
2441       && ! gfc_elemental (expr->value.function.esym))
2442     {
2443       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
2444                  "in WORKSHARE construct", expr->value.function.esym->name,
2445                  &expr->where);
2446       t = FAILURE;
2447     }
2448
2449 #define GENERIC_ID expr->value.function.isym->id
2450   else if (expr->value.function.actual != NULL
2451            && expr->value.function.isym != NULL
2452            && GENERIC_ID != GFC_ISYM_LBOUND
2453            && GENERIC_ID != GFC_ISYM_LEN
2454            && GENERIC_ID != GFC_ISYM_LOC
2455            && GENERIC_ID != GFC_ISYM_PRESENT)
2456     {
2457       /* Array intrinsics must also have the last upper bound of an
2458          assumed size array argument.  UBOUND and SIZE have to be
2459          excluded from the check if the second argument is anything
2460          than a constant.  */
2461
2462       for (arg = expr->value.function.actual; arg; arg = arg->next)
2463         {
2464           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
2465               && arg->next != NULL && arg->next->expr)
2466             {
2467               if (arg->next->expr->expr_type != EXPR_CONSTANT)
2468                 break;
2469
2470               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
2471                 break;
2472
2473               if ((int)mpz_get_si (arg->next->expr->value.integer)
2474                         < arg->expr->rank)
2475                 break;
2476             }
2477
2478           if (arg->expr != NULL
2479               && arg->expr->rank > 0
2480               && resolve_assumed_size_actual (arg->expr))
2481             return FAILURE;
2482         }
2483     }
2484 #undef GENERIC_ID
2485
2486   need_full_assumed_size = temp;
2487   name = NULL;
2488
2489   if (!pure_function (expr, &name) && name)
2490     {
2491       if (forall_flag)
2492         {
2493           gfc_error ("reference to non-PURE function '%s' at %L inside a "
2494                      "FORALL %s", name, &expr->where,
2495                      forall_flag == 2 ? "mask" : "block");
2496           t = FAILURE;
2497         }
2498       else if (gfc_pure (NULL))
2499         {
2500           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
2501                      "procedure within a PURE procedure", name, &expr->where);
2502           t = FAILURE;
2503         }
2504     }
2505
2506   /* Functions without the RECURSIVE attribution are not allowed to
2507    * call themselves.  */
2508   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
2509     {
2510       gfc_symbol *esym;
2511       esym = expr->value.function.esym;
2512
2513       if (is_illegal_recursion (esym, gfc_current_ns))
2514       {
2515         if (esym->attr.entry && esym->ns->entries)
2516           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
2517                      " function '%s' is not RECURSIVE",
2518                      esym->name, &expr->where, esym->ns->entries->sym->name);
2519         else
2520           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
2521                      " is not RECURSIVE", esym->name, &expr->where);
2522
2523         t = FAILURE;
2524       }
2525     }
2526
2527   /* Character lengths of use associated functions may contains references to
2528      symbols not referenced from the current program unit otherwise.  Make sure
2529      those symbols are marked as referenced.  */
2530
2531   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
2532       && expr->value.function.esym->attr.use_assoc)
2533     {
2534       gfc_expr_set_symbols_referenced (expr->ts.cl->length);
2535     }
2536
2537   if (t == SUCCESS
2538         && !((expr->value.function.esym
2539                 && expr->value.function.esym->attr.elemental)
2540                         ||
2541              (expr->value.function.isym
2542                 && expr->value.function.isym->elemental)))
2543     find_noncopying_intrinsics (expr->value.function.esym,
2544                                 expr->value.function.actual);
2545
2546   /* Make sure that the expression has a typespec that works.  */
2547   if (expr->ts.type == BT_UNKNOWN)
2548     {
2549       if (expr->symtree->n.sym->result
2550             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN)
2551         expr->ts = expr->symtree->n.sym->result->ts;
2552     }
2553
2554   return t;
2555 }
2556
2557
2558 /************* Subroutine resolution *************/
2559
2560 static void
2561 pure_subroutine (gfc_code *c, gfc_symbol *sym)
2562 {
2563   if (gfc_pure (sym))
2564     return;
2565
2566   if (forall_flag)
2567     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
2568                sym->name, &c->loc);
2569   else if (gfc_pure (NULL))
2570     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
2571                &c->loc);
2572 }
2573
2574
2575 static match
2576 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
2577 {
2578   gfc_symbol *s;
2579
2580   if (sym->attr.generic)
2581     {
2582       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
2583       if (s != NULL)
2584         {
2585           c->resolved_sym = s;
2586           pure_subroutine (c, s);
2587           return MATCH_YES;
2588         }
2589
2590       /* TODO: Need to search for elemental references in generic interface.  */
2591     }
2592
2593   if (sym->attr.intrinsic)
2594     return gfc_intrinsic_sub_interface (c, 0);
2595
2596   return MATCH_NO;
2597 }
2598
2599
2600 static gfc_try
2601 resolve_generic_s (gfc_code *c)
2602 {
2603   gfc_symbol *sym;
2604   match m;
2605
2606   sym = c->symtree->n.sym;
2607
2608   for (;;)
2609     {
2610       m = resolve_generic_s0 (c, sym);
2611       if (m == MATCH_YES)
2612         return SUCCESS;
2613       else if (m == MATCH_ERROR)
2614         return FAILURE;
2615
2616 generic:
2617       if (sym->ns->parent == NULL)
2618         break;
2619       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2620
2621       if (sym == NULL)
2622         break;
2623       if (!generic_sym (sym))
2624         goto generic;
2625     }
2626
2627   /* Last ditch attempt.  See if the reference is to an intrinsic
2628      that possesses a matching interface.  14.1.2.4  */
2629   sym = c->symtree->n.sym;
2630
2631   if (!gfc_is_intrinsic (sym, 1, c->loc))
2632     {
2633       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
2634                  sym->name, &c->loc);
2635       return FAILURE;
2636     }
2637
2638   m = gfc_intrinsic_sub_interface (c, 0);
2639   if (m == MATCH_YES)
2640     return SUCCESS;
2641   if (m == MATCH_NO)
2642     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
2643                "intrinsic subroutine interface", sym->name, &c->loc);
2644
2645   return FAILURE;
2646 }
2647
2648
2649 /* Set the name and binding label of the subroutine symbol in the call
2650    expression represented by 'c' to include the type and kind of the
2651    second parameter.  This function is for resolving the appropriate
2652    version of c_f_pointer() and c_f_procpointer().  For example, a
2653    call to c_f_pointer() for a default integer pointer could have a
2654    name of c_f_pointer_i4.  If no second arg exists, which is an error
2655    for these two functions, it defaults to the generic symbol's name
2656    and binding label.  */
2657
2658 static void
2659 set_name_and_label (gfc_code *c, gfc_symbol *sym,
2660                     char *name, char *binding_label)
2661 {
2662   gfc_expr *arg = NULL;
2663   char type;
2664   int kind;
2665
2666   /* The second arg of c_f_pointer and c_f_procpointer determines
2667      the type and kind for the procedure name.  */
2668   arg = c->ext.actual->next->expr;
2669
2670   if (arg != NULL)
2671     {
2672       /* Set up the name to have the given symbol's name,
2673          plus the type and kind.  */
2674       /* a derived type is marked with the type letter 'u' */
2675       if (arg->ts.type == BT_DERIVED)
2676         {
2677           type = 'd';
2678           kind = 0; /* set the kind as 0 for now */
2679         }
2680       else
2681         {
2682           type = gfc_type_letter (arg->ts.type);
2683           kind = arg->ts.kind;
2684         }
2685
2686       if (arg->ts.type == BT_CHARACTER)
2687         /* Kind info for character strings not needed.  */
2688         kind = 0;
2689
2690       sprintf (name, "%s_%c%d", sym->name, type, kind);
2691       /* Set up the binding label as the given symbol's label plus
2692          the type and kind.  */
2693       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
2694     }
2695   else
2696     {
2697       /* If the second arg is missing, set the name and label as
2698          was, cause it should at least be found, and the missing
2699          arg error will be caught by compare_parameters().  */
2700       sprintf (name, "%s", sym->name);
2701       sprintf (binding_label, "%s", sym->binding_label);
2702     }
2703    
2704   return;
2705 }
2706
2707
2708 /* Resolve a generic version of the iso_c_binding procedure given
2709    (sym) to the specific one based on the type and kind of the
2710    argument(s).  Currently, this function resolves c_f_pointer() and
2711    c_f_procpointer based on the type and kind of the second argument
2712    (FPTR).  Other iso_c_binding procedures aren't specially handled.
2713    Upon successfully exiting, c->resolved_sym will hold the resolved
2714    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
2715    otherwise.  */
2716
2717 match
2718 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
2719 {
2720   gfc_symbol *new_sym;
2721   /* this is fine, since we know the names won't use the max */
2722   char name[GFC_MAX_SYMBOL_LEN + 1];
2723   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2724   /* default to success; will override if find error */
2725   match m = MATCH_YES;
2726
2727   /* Make sure the actual arguments are in the necessary order (based on the 
2728      formal args) before resolving.  */
2729   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
2730
2731   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
2732       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
2733     {
2734       set_name_and_label (c, sym, name, binding_label);
2735       
2736       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
2737         {
2738           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
2739             {
2740               /* Make sure we got a third arg if the second arg has non-zero
2741                  rank.  We must also check that the type and rank are
2742                  correct since we short-circuit this check in
2743                  gfc_procedure_use() (called above to sort actual args).  */
2744               if (c->ext.actual->next->expr->rank != 0)
2745                 {
2746                   if(c->ext.actual->next->next == NULL 
2747                      || c->ext.actual->next->next->expr == NULL)
2748                     {
2749                       m = MATCH_ERROR;
2750                       gfc_error ("Missing SHAPE parameter for call to %s "
2751                                  "at %L", sym->name, &(c->loc));
2752                     }
2753                   else if (c->ext.actual->next->next->expr->ts.type
2754                            != BT_INTEGER
2755                            || c->ext.actual->next->next->expr->rank != 1)
2756                     {
2757                       m = MATCH_ERROR;
2758                       gfc_error ("SHAPE parameter for call to %s at %L must "
2759                                  "be a rank 1 INTEGER array", sym->name,
2760                                  &(c->loc));
2761                     }
2762                 }
2763             }
2764         }
2765       
2766       if (m != MATCH_ERROR)
2767         {
2768           /* the 1 means to add the optional arg to formal list */
2769           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
2770          
2771           /* for error reporting, say it's declared where the original was */
2772           new_sym->declared_at = sym->declared_at;
2773         }
2774     }
2775   else
2776     {
2777       /* no differences for c_loc or c_funloc */
2778       new_sym = sym;
2779     }
2780
2781   /* set the resolved symbol */
2782   if (m != MATCH_ERROR)
2783     c->resolved_sym = new_sym;
2784   else
2785     c->resolved_sym = sym;
2786   
2787   return m;
2788 }
2789
2790
2791 /* Resolve a subroutine call known to be specific.  */
2792
2793 static match
2794 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
2795 {
2796   match m;
2797
2798   /* See if we have an intrinsic interface.  */
2799   if (sym->ts.interface != NULL && !sym->ts.interface->attr.abstract
2800       && !sym->ts.interface->attr.subroutine
2801       && sym->ts.interface->attr.intrinsic)
2802     {
2803       gfc_intrinsic_sym *isym;
2804
2805       isym = gfc_find_function (sym->ts.interface->name);
2806
2807       /* Existence of isym should be checked already.  */
2808       gcc_assert (isym);
2809
2810       sym->ts.type = isym->ts.type;
2811       sym->ts.kind = isym->ts.kind;
2812       sym->attr.subroutine = 1;
2813       goto found;
2814     }
2815
2816   if(sym->attr.is_iso_c)
2817     {
2818       m = gfc_iso_c_sub_interface (c,sym);
2819       return m;
2820     }
2821   
2822   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2823     {
2824       if (sym->attr.dummy)
2825         {
2826           sym->attr.proc = PROC_DUMMY;
2827           goto found;
2828         }
2829
2830       sym->attr.proc = PROC_EXTERNAL;
2831       goto found;
2832     }
2833
2834   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
2835     goto found;
2836
2837   if (sym->attr.intrinsic)
2838     {
2839       m = gfc_intrinsic_sub_interface (c, 1);
2840       if (m == MATCH_YES)
2841         return MATCH_YES;
2842       if (m == MATCH_NO)
2843         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
2844                    "with an intrinsic", sym->name, &c->loc);
2845
2846       return MATCH_ERROR;
2847     }
2848
2849   return MATCH_NO;
2850
2851 found:
2852   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
2853
2854   c->resolved_sym = sym;
2855   pure_subroutine (c, sym);
2856
2857   return MATCH_YES;
2858 }
2859
2860
2861 static gfc_try
2862 resolve_specific_s (gfc_code *c)
2863 {
2864   gfc_symbol *sym;
2865   match m;
2866
2867   sym = c->symtree->n.sym;
2868
2869   for (;;)
2870     {
2871       m = resolve_specific_s0 (c, sym);
2872       if (m == MATCH_YES)
2873         return SUCCESS;
2874       if (m == MATCH_ERROR)
2875         return FAILURE;
2876
2877       if (sym->ns->parent == NULL)
2878         break;
2879
2880       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2881
2882       if (sym == NULL)
2883         break;
2884     }
2885
2886   sym = c->symtree->n.sym;
2887   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
2888              sym->name, &c->loc);
2889
2890   return FAILURE;
2891 }
2892
2893
2894 /* Resolve a subroutine call not known to be generic nor specific.  */
2895
2896 static gfc_try
2897 resolve_unknown_s (gfc_code *c)
2898 {
2899   gfc_symbol *sym;
2900
2901   sym = c->symtree->n.sym;
2902
2903   if (sym->attr.dummy)
2904     {
2905       sym->attr.proc = PROC_DUMMY;
2906       goto found;
2907     }
2908
2909   /* See if we have an intrinsic function reference.  */
2910
2911   if (gfc_is_intrinsic (sym, 1, c->loc))
2912     {
2913       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
2914         return SUCCESS;
2915       return FAILURE;
2916     }
2917
2918   /* The reference is to an external name.  */
2919
2920 found:
2921   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
2922
2923   c->resolved_sym = sym;
2924
2925   pure_subroutine (c, sym);
2926
2927   return SUCCESS;
2928 }
2929
2930
2931 /* Resolve a subroutine call.  Although it was tempting to use the same code
2932    for functions, subroutines and functions are stored differently and this
2933    makes things awkward.  */
2934
2935 static gfc_try
2936 resolve_call (gfc_code *c)
2937 {
2938   gfc_try t;
2939   procedure_type ptype = PROC_INTRINSIC;
2940   gfc_symbol *csym, *sym;
2941   bool no_formal_args;
2942
2943   csym = c->symtree ? c->symtree->n.sym : NULL;
2944
2945   if (csym && csym->ts.type != BT_UNKNOWN)
2946     {
2947       gfc_error ("'%s' at %L has a type, which is not consistent with "
2948                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
2949       return FAILURE;
2950     }
2951
2952   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
2953     {
2954       gfc_symtree *st;
2955       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
2956       sym = st ? st->n.sym : NULL;
2957       if (sym && csym != sym
2958               && sym->ns == gfc_current_ns
2959               && sym->attr.flavor == FL_PROCEDURE
2960               && sym->attr.contained)
2961         {
2962           sym->refs++;
2963           if (csym->attr.generic)
2964             c->symtree->n.sym = sym;
2965           else
2966             c->symtree = st;
2967           csym = c->symtree->n.sym;
2968         }
2969     }
2970
2971   /* Subroutines without the RECURSIVE attribution are not allowed to
2972    * call themselves.  */
2973   if (csym && is_illegal_recursion (csym, gfc_current_ns))
2974     {
2975       if (csym->attr.entry && csym->ns->entries)
2976         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
2977                    " subroutine '%s' is not RECURSIVE",
2978                    csym->name, &c->loc, csym->ns->entries->sym->name);
2979       else
2980         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
2981                    " is not RECURSIVE", csym->name, &c->loc);
2982
2983       t = FAILURE;
2984     }
2985
2986   /* Switch off assumed size checking and do this again for certain kinds
2987      of procedure, once the procedure itself is resolved.  */
2988   need_full_assumed_size++;
2989
2990   if (csym)
2991     ptype = csym->attr.proc;
2992
2993   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
2994   if (resolve_actual_arglist (c->ext.actual, ptype,
2995                               no_formal_args) == FAILURE)
2996     return FAILURE;
2997
2998   /* Resume assumed_size checking.  */
2999   need_full_assumed_size--;
3000
3001   /* If external, check for usage.  */
3002   if (csym && is_external_proc (csym))
3003     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3004
3005   t = SUCCESS;
3006   if (c->resolved_sym == NULL)
3007     {
3008       c->resolved_isym = NULL;
3009       switch (procedure_kind (csym))
3010         {
3011         case PTYPE_GENERIC:
3012           t = resolve_generic_s (c);
3013           break;
3014
3015         case PTYPE_SPECIFIC:
3016           t = resolve_specific_s (c);
3017           break;
3018
3019         case PTYPE_UNKNOWN:
3020           t = resolve_unknown_s (c);
3021           break;
3022
3023         default:
3024           gfc_internal_error ("resolve_subroutine(): bad function type");
3025         }
3026     }
3027
3028   /* Some checks of elemental subroutine actual arguments.  */
3029   if (resolve_elemental_actual (NULL, c) == FAILURE)
3030     return FAILURE;
3031
3032   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3033     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3034   return t;
3035 }
3036
3037
3038 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3039    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3040    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3041    if their shapes do not match.  If either op1->shape or op2->shape is
3042    NULL, return SUCCESS.  */
3043
3044 static gfc_try
3045 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3046 {
3047   gfc_try t;
3048   int i;
3049
3050   t = SUCCESS;
3051
3052   if (op1->shape != NULL && op2->shape != NULL)
3053     {
3054       for (i = 0; i < op1->rank; i++)
3055         {
3056           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3057            {
3058              gfc_error ("Shapes for operands at %L and %L are not conformable",
3059                          &op1->where, &op2->where);
3060              t = FAILURE;
3061              break;
3062            }
3063         }
3064     }
3065
3066   return t;
3067 }
3068
3069
3070 /* Resolve an operator expression node.  This can involve replacing the
3071    operation with a user defined function call.  */
3072
3073 static gfc_try
3074 resolve_operator (gfc_expr *e)
3075 {
3076   gfc_expr *op1, *op2;
3077   char msg[200];
3078   bool dual_locus_error;
3079   gfc_try t;
3080
3081   /* Resolve all subnodes-- give them types.  */
3082
3083   switch (e->value.op.op)
3084     {
3085     default:
3086       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3087         return FAILURE;
3088
3089     /* Fall through...  */
3090
3091     case INTRINSIC_NOT:
3092     case INTRINSIC_UPLUS:
3093     case INTRINSIC_UMINUS:
3094     case INTRINSIC_PARENTHESES:
3095       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3096         return FAILURE;
3097       break;
3098     }
3099
3100   /* Typecheck the new node.  */
3101
3102   op1 = e->value.op.op1;
3103   op2 = e->value.op.op2;
3104   dual_locus_error = false;
3105
3106   if ((op1 && op1->expr_type == EXPR_NULL)
3107       || (op2 && op2->expr_type == EXPR_NULL))
3108     {
3109       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3110       goto bad_op;
3111     }
3112
3113   switch (e->value.op.op)
3114     {
3115     case INTRINSIC_UPLUS:
3116     case INTRINSIC_UMINUS:
3117       if (op1->ts.type == BT_INTEGER
3118           || op1->ts.type == BT_REAL
3119           || op1->ts.type == BT_COMPLEX)
3120         {
3121           e->ts = op1->ts;
3122           break;
3123         }
3124
3125       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3126                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3127       goto bad_op;
3128
3129     case INTRINSIC_PLUS:
3130     case INTRINSIC_MINUS:
3131     case INTRINSIC_TIMES:
3132     case INTRINSIC_DIVIDE:
3133     case INTRINSIC_POWER:
3134       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3135         {
3136           gfc_type_convert_binary (e);
3137           break;
3138         }
3139
3140       sprintf (msg,
3141                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3142                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3143                gfc_typename (&op2->ts));
3144       goto bad_op;
3145
3146     case INTRINSIC_CONCAT:
3147       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3148           && op1->ts.kind == op2->ts.kind)
3149         {
3150           e->ts.type = BT_CHARACTER;
3151           e->ts.kind = op1->ts.kind;
3152           break;
3153         }
3154
3155       sprintf (msg,
3156                _("Operands of string concatenation operator at %%L are %s/%s"),
3157                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3158       goto bad_op;
3159
3160     case INTRINSIC_AND:
3161     case INTRINSIC_OR:
3162     case INTRINSIC_EQV:
3163     case INTRINSIC_NEQV:
3164       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3165         {
3166           e->ts.type = BT_LOGICAL;
3167           e->ts.kind = gfc_kind_max (op1, op2);
3168           if (op1->ts.kind < e->ts.kind)
3169             gfc_convert_type (op1, &e->ts, 2);
3170           else if (op2->ts.kind < e->ts.kind)
3171             gfc_convert_type (op2, &e->ts, 2);
3172           break;
3173         }
3174
3175       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3176                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3177                gfc_typename (&op2->ts));
3178
3179       goto bad_op;
3180
3181     case INTRINSIC_NOT:
3182       if (op1->ts.type == BT_LOGICAL)
3183         {
3184           e->ts.type = BT_LOGICAL;
3185           e->ts.kind = op1->ts.kind;
3186           break;
3187         }
3188
3189       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3190                gfc_typename (&op1->ts));
3191       goto bad_op;
3192
3193     case INTRINSIC_GT:
3194     case INTRINSIC_GT_OS:
3195     case INTRINSIC_GE:
3196     case INTRINSIC_GE_OS:
3197     case INTRINSIC_LT:
3198     case INTRINSIC_LT_OS:
3199     case INTRINSIC_LE:
3200     case INTRINSIC_LE_OS:
3201       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3202         {
3203           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3204           goto bad_op;
3205         }
3206
3207       /* Fall through...  */
3208
3209     case INTRINSIC_EQ:
3210     case INTRINSIC_EQ_OS:
3211     case INTRINSIC_NE:
3212     case INTRINSIC_NE_OS:
3213       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3214           && op1->ts.kind == op2->ts.kind)
3215         {
3216           e->ts.type = BT_LOGICAL;
3217           e->ts.kind = gfc_default_logical_kind;
3218           break;
3219         }
3220
3221       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3222         {
3223           gfc_type_convert_binary (e);
3224
3225           e->ts.type = BT_LOGICAL;
3226           e->ts.kind = gfc_default_logical_kind;
3227           break;
3228         }
3229
3230       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3231         sprintf (msg,
3232                  _("Logicals at %%L must be compared with %s instead of %s"),
3233                  (e->value.op.op == INTRINSIC_EQ 
3234                   || e->value.op.op == INTRINSIC_EQ_OS)
3235                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3236       else
3237         sprintf (msg,
3238                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3239                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3240                  gfc_typename (&op2->ts));
3241
3242       goto bad_op;
3243
3244     case INTRINSIC_USER:
3245       if (e->value.op.uop->op == NULL)
3246         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3247       else if (op2 == NULL)
3248         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3249                  e->value.op.uop->name, gfc_typename (&op1->ts));
3250       else
3251         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3252                  e->value.op.uop->name, gfc_typename (&op1->ts),
3253                  gfc_typename (&op2->ts));
3254
3255       goto bad_op;
3256
3257     case INTRINSIC_PARENTHESES:
3258       e->ts = op1->ts;
3259       if (e->ts.type == BT_CHARACTER)
3260         e->ts.cl = op1->ts.cl;
3261       break;
3262
3263     default:
3264       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3265     }
3266
3267   /* Deal with arrayness of an operand through an operator.  */
3268
3269   t = SUCCESS;
3270
3271   switch (e->value.op.op)
3272     {
3273     case INTRINSIC_PLUS:
3274     case INTRINSIC_MINUS:
3275     case INTRINSIC_TIMES:
3276     case INTRINSIC_DIVIDE:
3277     case INTRINSIC_POWER:
3278     case INTRINSIC_CONCAT:
3279     case INTRINSIC_AND:
3280     case INTRINSIC_OR:
3281     case INTRINSIC_EQV:
3282     case INTRINSIC_NEQV:
3283     case INTRINSIC_EQ:
3284     case INTRINSIC_EQ_OS:
3285     case INTRINSIC_NE:
3286     case INTRINSIC_NE_OS:
3287     case INTRINSIC_GT:
3288     case INTRINSIC_GT_OS:
3289     case INTRINSIC_GE:
3290     case INTRINSIC_GE_OS:
3291     case INTRINSIC_LT:
3292     case INTRINSIC_LT_OS:
3293     case INTRINSIC_LE:
3294     case INTRINSIC_LE_OS:
3295
3296       if (op1->rank == 0 && op2->rank == 0)
3297         e->rank = 0;
3298
3299       if (op1->rank == 0 && op2->rank != 0)
3300         {
3301           e->rank = op2->rank;
3302
3303           if (e->shape == NULL)
3304             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3305         }
3306
3307       if (op1->rank != 0 && op2->rank == 0)
3308         {
3309           e->rank = op1->rank;
3310
3311           if (e->shape == NULL)
3312             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3313         }
3314
3315       if (op1->rank != 0 && op2->rank != 0)
3316         {
3317           if (op1->rank == op2->rank)
3318             {
3319               e->rank = op1->rank;
3320               if (e->shape == NULL)
3321                 {
3322                   t = compare_shapes(op1, op2);
3323                   if (t == FAILURE)
3324                     e->shape = NULL;
3325                   else
3326                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
3327                 }
3328             }
3329           else
3330             {
3331               /* Allow higher level expressions to work.  */
3332               e->rank = 0;
3333
3334               /* Try user-defined operators, and otherwise throw an error.  */
3335               dual_locus_error = true;
3336               sprintf (msg,
3337                        _("Inconsistent ranks for operator at %%L and %%L"));
3338               goto bad_op;
3339             }
3340         }
3341
3342       break;
3343
3344     case INTRINSIC_PARENTHESES:
3345     case INTRINSIC_NOT:
3346     case INTRINSIC_UPLUS:
3347     case INTRINSIC_UMINUS:
3348       /* Simply copy arrayness attribute */
3349       e->rank = op1->rank;
3350
3351       if (e->shape == NULL)
3352         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3353
3354       break;
3355
3356     default:
3357       break;
3358     }
3359
3360   /* Attempt to simplify the expression.  */
3361   if (t == SUCCESS)
3362     {
3363       t = gfc_simplify_expr (e, 0);
3364       /* Some calls do not succeed in simplification and return FAILURE
3365          even though there is no error; e.g. variable references to
3366          PARAMETER arrays.  */
3367       if (!gfc_is_constant_expr (e))
3368         t = SUCCESS;
3369     }
3370   return t;
3371
3372 bad_op:
3373
3374   if (gfc_extend_expr (e) == SUCCESS)
3375     return SUCCESS;
3376
3377   if (dual_locus_error)
3378     gfc_error (msg, &op1->where, &op2->where);
3379   else
3380     gfc_error (msg, &e->where);
3381
3382   return FAILURE;
3383 }
3384
3385
3386 /************** Array resolution subroutines **************/
3387
3388 typedef enum
3389 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3390 comparison;
3391
3392 /* Compare two integer expressions.  */
3393
3394 static comparison
3395 compare_bound (gfc_expr *a, gfc_expr *b)
3396 {
3397   int i;
3398
3399   if (a == NULL || a->expr_type != EXPR_CONSTANT
3400       || b == NULL || b->expr_type != EXPR_CONSTANT)
3401     return CMP_UNKNOWN;
3402
3403   /* If either of the types isn't INTEGER, we must have
3404      raised an error earlier.  */
3405
3406   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3407     return CMP_UNKNOWN;
3408
3409   i = mpz_cmp (a->value.integer, b->value.integer);
3410
3411   if (i < 0)
3412     return CMP_LT;
3413   if (i > 0)
3414     return CMP_GT;
3415   return CMP_EQ;
3416 }
3417
3418
3419 /* Compare an integer expression with an integer.  */
3420
3421 static comparison
3422 compare_bound_int (gfc_expr *a, int b)
3423 {
3424   int i;
3425
3426   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3427     return CMP_UNKNOWN;
3428
3429   if (a->ts.type != BT_INTEGER)
3430     gfc_internal_error ("compare_bound_int(): Bad expression");
3431
3432   i = mpz_cmp_si (a->value.integer, b);
3433
3434   if (i < 0)
3435     return CMP_LT;
3436   if (i > 0)
3437     return CMP_GT;
3438   return CMP_EQ;
3439 }
3440
3441
3442 /* Compare an integer expression with a mpz_t.  */
3443
3444 static comparison
3445 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
3446 {
3447   int i;
3448
3449   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3450     return CMP_UNKNOWN;
3451
3452   if (a->ts.type != BT_INTEGER)
3453     gfc_internal_error ("compare_bound_int(): Bad expression");
3454
3455   i = mpz_cmp (a->value.integer, b);
3456
3457   if (i < 0)
3458     return CMP_LT;
3459   if (i > 0)
3460     return CMP_GT;
3461   return CMP_EQ;
3462 }
3463
3464
3465 /* Compute the last value of a sequence given by a triplet.  
3466    Return 0 if it wasn't able to compute the last value, or if the
3467    sequence if empty, and 1 otherwise.  */
3468
3469 static int
3470 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
3471                                 gfc_expr *stride, mpz_t last)
3472 {
3473   mpz_t rem;
3474
3475   if (start == NULL || start->expr_type != EXPR_CONSTANT
3476       || end == NULL || end->expr_type != EXPR_CONSTANT
3477       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
3478     return 0;
3479
3480   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
3481       || (stride != NULL && stride->ts.type != BT_INTEGER))
3482     return 0;
3483
3484   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
3485     {
3486       if (compare_bound (start, end) == CMP_GT)
3487         return 0;
3488       mpz_set (last, end->value.integer);
3489       return 1;
3490     }
3491
3492   if (compare_bound_int (stride, 0) == CMP_GT)
3493     {
3494       /* Stride is positive */
3495       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
3496         return 0;
3497     }
3498   else
3499     {
3500       /* Stride is negative */
3501       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
3502         return 0;
3503     }
3504
3505   mpz_init (rem);
3506   mpz_sub (rem, end->value.integer, start->value.integer);
3507   mpz_tdiv_r (rem, rem, stride->value.integer);
3508   mpz_sub (last, end->value.integer, rem);
3509   mpz_clear (rem);
3510
3511   return 1;
3512 }
3513
3514
3515 /* Compare a single dimension of an array reference to the array
3516    specification.  */
3517
3518 static gfc_try
3519 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
3520 {
3521   mpz_t last_value;
3522
3523 /* Given start, end and stride values, calculate the minimum and
3524    maximum referenced indexes.  */
3525
3526   switch (ar->dimen_type[i])
3527     {
3528     case DIMEN_VECTOR:
3529       break;
3530
3531     case DIMEN_ELEMENT:
3532       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
3533         {
3534           gfc_warning ("Array reference at %L is out of bounds "
3535                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3536                        mpz_get_si (ar->start[i]->value.integer),
3537                        mpz_get_si (as->lower[i]->value.integer), i+1);
3538           return SUCCESS;
3539         }
3540       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
3541         {
3542           gfc_warning ("Array reference at %L is out of bounds "
3543                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3544                        mpz_get_si (ar->start[i]->value.integer),
3545                        mpz_get_si (as->upper[i]->value.integer), i+1);
3546           return SUCCESS;
3547         }
3548
3549       break;
3550
3551     case DIMEN_RANGE:
3552       {
3553 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
3554 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
3555
3556         comparison comp_start_end = compare_bound (AR_START, AR_END);
3557
3558         /* Check for zero stride, which is not allowed.  */
3559         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
3560           {
3561             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
3562             return FAILURE;
3563           }
3564
3565         /* if start == len || (stride > 0 && start < len)
3566                            || (stride < 0 && start > len),
3567            then the array section contains at least one element.  In this
3568            case, there is an out-of-bounds access if
3569            (start < lower || start > upper).  */
3570         if (compare_bound (AR_START, AR_END) == CMP_EQ
3571             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
3572                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
3573             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
3574                 && comp_start_end == CMP_GT))
3575           {
3576             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
3577               {
3578                 gfc_warning ("Lower array reference at %L is out of bounds "
3579                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3580                        mpz_get_si (AR_START->value.integer),
3581                        mpz_get_si (as->lower[i]->value.integer), i+1);
3582                 return SUCCESS;
3583               }
3584             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
3585               {
3586                 gfc_warning ("Lower array reference at %L is out of bounds "
3587                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3588                        mpz_get_si (AR_START->value.integer),
3589                        mpz_get_si (as->upper[i]->value.integer), i+1);
3590                 return SUCCESS;
3591               }
3592           }
3593
3594         /* If we can compute the highest index of the array section,
3595            then it also has to be between lower and upper.  */
3596         mpz_init (last_value);
3597         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
3598                                             last_value))
3599           {
3600             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
3601               {
3602                 gfc_warning ("Upper array reference at %L is out of bounds "
3603                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3604                        mpz_get_si (last_value),
3605                        mpz_get_si (as->lower[i]->value.integer), i+1);
3606                 mpz_clear (last_value);
3607                 return SUCCESS;
3608               }
3609             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
3610               {
3611                 gfc_warning ("Upper array reference at %L is out of bounds "
3612                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3613                        mpz_get_si (last_value),
3614                        mpz_get_si (as->upper[i]->value.integer), i+1);
3615                 mpz_clear (last_value);
3616                 return SUCCESS;
3617               }
3618           }
3619         mpz_clear (last_value);
3620
3621 #undef AR_START
3622 #undef AR_END
3623       }
3624       break;
3625
3626     default:
3627       gfc_internal_error ("check_dimension(): Bad array reference");
3628     }
3629
3630   return SUCCESS;
3631 }
3632
3633
3634 /* Compare an array reference with an array specification.  */
3635
3636 static gfc_try
3637 compare_spec_to_ref (gfc_array_ref *ar)
3638 {
3639   gfc_array_spec *as;
3640   int i;
3641
3642   as = ar->as;
3643   i = as->rank - 1;
3644   /* TODO: Full array sections are only allowed as actual parameters.  */
3645   if (as->type == AS_ASSUMED_SIZE
3646       && (/*ar->type == AR_FULL
3647           ||*/ (ar->type == AR_SECTION
3648               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
3649     {
3650       gfc_error ("Rightmost upper bound of assumed size array section "
3651                  "not specified at %L", &ar->where);
3652       return FAILURE;
3653     }
3654
3655   if (ar->type == AR_FULL)
3656     return SUCCESS;
3657
3658   if (as->rank != ar->dimen)
3659     {
3660       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
3661                  &ar->where, ar->dimen, as->rank);
3662       return FAILURE;
3663     }
3664
3665   for (i = 0; i < as->rank; i++)
3666     if (check_dimension (i, ar, as) == FAILURE)
3667       return FAILURE;
3668
3669   return SUCCESS;
3670 }
3671
3672
3673 /* Resolve one part of an array index.  */
3674
3675 gfc_try
3676 gfc_resolve_index (gfc_expr *index, int check_scalar)
3677 {
3678   gfc_typespec ts;
3679
3680   if (index == NULL)
3681     return SUCCESS;
3682
3683   if (gfc_resolve_expr (index) == FAILURE)
3684     return FAILURE;
3685
3686   if (check_scalar && index->rank != 0)
3687     {
3688       gfc_error ("Array index at %L must be scalar", &index->where);
3689       return FAILURE;
3690     }
3691
3692   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
3693     {
3694       gfc_error ("Array index at %L must be of INTEGER type, found %s",
3695                  &index->where, gfc_basic_typename (index->ts.type));
3696       return FAILURE;
3697     }
3698
3699   if (index->ts.type == BT_REAL)
3700     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
3701                         &index->where) == FAILURE)
3702       return FAILURE;
3703
3704   if (index->ts.kind != gfc_index_integer_kind
3705       || index->ts.type != BT_INTEGER)
3706     {
3707       gfc_clear_ts (&ts);
3708       ts.type = BT_INTEGER;
3709       ts.kind = gfc_index_integer_kind;
3710
3711       gfc_convert_type_warn (index, &ts, 2, 0);
3712     }
3713
3714   return SUCCESS;
3715 }
3716
3717 /* Resolve a dim argument to an intrinsic function.  */
3718
3719 gfc_try
3720 gfc_resolve_dim_arg (gfc_expr *dim)
3721 {
3722   if (dim == NULL)
3723     return SUCCESS;
3724
3725   if (gfc_resolve_expr (dim) == FAILURE)
3726     return FAILURE;
3727
3728   if (dim->rank != 0)
3729     {
3730       gfc_error ("Argument dim at %L must be scalar", &dim->where);
3731       return FAILURE;
3732
3733     }
3734
3735   if (dim->ts.type != BT_INTEGER)
3736     {
3737       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
3738       return FAILURE;
3739     }
3740
3741   if (dim->ts.kind != gfc_index_integer_kind)
3742     {
3743       gfc_typespec ts;
3744
3745       ts.type = BT_INTEGER;
3746       ts.kind = gfc_index_integer_kind;
3747
3748       gfc_convert_type_warn (dim, &ts, 2, 0);
3749     }
3750
3751   return SUCCESS;
3752 }
3753
3754 /* Given an expression that contains array references, update those array
3755    references to point to the right array specifications.  While this is
3756    filled in during matching, this information is difficult to save and load
3757    in a module, so we take care of it here.
3758
3759    The idea here is that the original array reference comes from the
3760    base symbol.  We traverse the list of reference structures, setting
3761    the stored reference to references.  Component references can
3762    provide an additional array specification.  */
3763
3764 static void
3765 find_array_spec (gfc_expr *e)
3766 {
3767   gfc_array_spec *as;
3768   gfc_component *c;
3769   gfc_symbol *derived;
3770   gfc_ref *ref;
3771
3772   as = e->symtree->n.sym->as;
3773   derived = NULL;
3774
3775   for (ref = e->ref; ref; ref = ref->next)
3776     switch (ref->type)
3777       {
3778       case REF_ARRAY:
3779         if (as == NULL)
3780           gfc_internal_error ("find_array_spec(): Missing spec");
3781
3782         ref->u.ar.as = as;
3783         as = NULL;
3784         break;
3785
3786       case REF_COMPONENT:
3787         if (derived == NULL)
3788           derived = e->symtree->n.sym->ts.derived;
3789
3790         c = derived->components;
3791
3792         for (; c; c = c->next)
3793           if (c == ref->u.c.component)
3794             {
3795               /* Track the sequence of component references.  */
3796               if (c->ts.type == BT_DERIVED)
3797                 derived = c->ts.derived;
3798               break;
3799             }
3800
3801         if (c == NULL)
3802           gfc_internal_error ("find_array_spec(): Component not found");
3803
3804         if (c->attr.dimension)
3805           {
3806             if (as != NULL)
3807               gfc_internal_error ("find_array_spec(): unused as(1)");
3808             as = c->as;
3809           }
3810
3811         break;
3812
3813       case REF_SUBSTRING:
3814         break;
3815       }
3816
3817   if (as != NULL)
3818     gfc_internal_error ("find_array_spec(): unused as(2)");
3819 }
3820
3821
3822 /* Resolve an array reference.  */
3823
3824 static gfc_try
3825 resolve_array_ref (gfc_array_ref *ar)
3826 {
3827   int i, check_scalar;
3828   gfc_expr *e;
3829
3830   for (i = 0; i < ar->dimen; i++)
3831     {
3832       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
3833
3834       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
3835         return FAILURE;
3836       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
3837         return FAILURE;
3838       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
3839         return FAILURE;
3840
3841       e = ar->start[i];
3842
3843       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
3844         switch (e->rank)
3845           {
3846           case 0:
3847             ar->dimen_type[i] = DIMEN_ELEMENT;
3848             break;
3849
3850           case 1:
3851             ar->dimen_type[i] = DIMEN_VECTOR;
3852             if (e->expr_type == EXPR_VARIABLE
3853                 && e->symtree->n.sym->ts.type == BT_DERIVED)
3854               ar->start[i] = gfc_get_parentheses (e);
3855             break;
3856
3857           default:
3858             gfc_error ("Array index at %L is an array of rank %d",
3859                        &ar->c_where[i], e->rank);
3860             return FAILURE;
3861           }
3862     }
3863
3864   /* If the reference type is unknown, figure out what kind it is.  */
3865
3866   if (ar->type == AR_UNKNOWN)
3867     {
3868       ar->type = AR_ELEMENT;
3869       for (i = 0; i < ar->dimen; i++)
3870         if (ar->dimen_type[i] == DIMEN_RANGE
3871             || ar->dimen_type[i] == DIMEN_VECTOR)
3872           {
3873             ar->type = AR_SECTION;
3874             break;
3875           }
3876     }
3877
3878   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
3879     return FAILURE;
3880
3881   return SUCCESS;
3882 }
3883
3884
3885 static gfc_try
3886 resolve_substring (gfc_ref *ref)
3887 {
3888   if (ref->u.ss.start != NULL)
3889     {
3890       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
3891         return FAILURE;
3892
3893       if (ref->u.ss.start->ts.type != BT_INTEGER)
3894         {
3895           gfc_error ("Substring start index at %L must be of type INTEGER",
3896                      &ref->u.ss.start->where);
3897           return FAILURE;
3898         }
3899
3900       if (ref->u.ss.start->rank != 0)
3901         {
3902           gfc_error ("Substring start index at %L must be scalar",
3903                      &ref->u.ss.start->where);
3904           return FAILURE;
3905         }
3906
3907       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
3908           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
3909               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
3910         {
3911           gfc_error ("Substring start index at %L is less than one",
3912                      &ref->u.ss.start->where);
3913           return FAILURE;
3914         }
3915     }
3916
3917   if (ref->u.ss.end != NULL)
3918     {
3919       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
3920         return FAILURE;
3921
3922       if (ref->u.ss.end->ts.type != BT_INTEGER)
3923         {
3924           gfc_error ("Substring end index at %L must be of type INTEGER",
3925                      &ref->u.ss.end->where);
3926           return FAILURE;
3927         }
3928
3929       if (ref->u.ss.end->rank != 0)
3930         {
3931           gfc_error ("Substring end index at %L must be scalar",
3932                      &ref->u.ss.end->where);
3933           return FAILURE;
3934         }
3935
3936       if (ref->u.ss.length != NULL
3937           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
3938           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
3939               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
3940         {
3941           gfc_error ("Substring end index at %L exceeds the string length",
3942                      &ref->u.ss.start->where);
3943           return FAILURE;
3944         }
3945     }
3946
3947   return SUCCESS;
3948 }
3949
3950
3951 /* This function supplies missing substring charlens.  */
3952
3953 void
3954 gfc_resolve_substring_charlen (gfc_expr *e)
3955 {
3956   gfc_ref *char_ref;
3957   gfc_expr *start, *end;
3958
3959   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
3960     if (char_ref->type == REF_SUBSTRING)
3961       break;
3962
3963   if (!char_ref)
3964     return;
3965
3966   gcc_assert (char_ref->next == NULL);
3967
3968   if (e->ts.cl)
3969     {
3970       if (e->ts.cl->length)
3971         gfc_free_expr (e->ts.cl->length);
3972       else if (e->expr_type == EXPR_VARIABLE
3973                  && e->symtree->n.sym->attr.dummy)
3974         return;
3975     }
3976
3977   e->ts.type = BT_CHARACTER;
3978   e->ts.kind = gfc_default_character_kind;
3979
3980   if (!e->ts.cl)
3981     {
3982       e->ts.cl = gfc_get_charlen ();
3983       e->ts.cl->next = gfc_current_ns->cl_list;
3984       gfc_current_ns->cl_list = e->ts.cl;
3985     }
3986
3987   if (char_ref->u.ss.start)
3988     start = gfc_copy_expr (char_ref->u.ss.start);
3989   else
3990     start = gfc_int_expr (1);
3991
3992   if (char_ref->u.ss.end)
3993     end = gfc_copy_expr (char_ref->u.ss.end);
3994   else if (e->expr_type == EXPR_VARIABLE)
3995     end = gfc_copy_expr (e->symtree->n.sym->ts.cl->length);
3996   else
3997     end = NULL;
3998
3999   if (!start || !end)
4000     return;
4001
4002   /* Length = (end - start +1).  */
4003   e->ts.cl->length = gfc_subtract (end, start);
4004   e->ts.cl->length = gfc_add (e->ts.cl->length, gfc_int_expr (1));
4005
4006   e->ts.cl->length->ts.type = BT_INTEGER;
4007   e->ts.cl->length->ts.kind = gfc_charlen_int_kind;;
4008
4009   /* Make sure that the length is simplified.  */
4010   gfc_simplify_expr (e->ts.cl->length, 1);
4011   gfc_resolve_expr (e->ts.cl->length);
4012 }
4013
4014
4015 /* Resolve subtype references.  */
4016
4017 static gfc_try
4018 resolve_ref (gfc_expr *expr)
4019 {
4020   int current_part_dimension, n_components, seen_part_dimension;
4021   gfc_ref *ref;
4022
4023   for (ref = expr->ref; ref; ref = ref->next)
4024     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4025       {
4026         find_array_spec (expr);
4027         break;
4028       }
4029
4030   for (ref = expr->ref; ref; ref = ref->next)
4031     switch (ref->type)
4032       {
4033       case REF_ARRAY:
4034         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4035           return FAILURE;
4036         break;
4037
4038       case REF_COMPONENT:
4039         break;
4040
4041       case REF_SUBSTRING:
4042         resolve_substring (ref);
4043         break;
4044       }
4045
4046   /* Check constraints on part references.  */
4047
4048   current_part_dimension = 0;
4049   seen_part_dimension = 0;
4050   n_components = 0;
4051
4052   for (ref = expr->ref; ref; ref = ref->next)
4053     {
4054       switch (ref->type)
4055         {
4056         case REF_ARRAY:
4057           switch (ref->u.ar.type)
4058             {
4059             case AR_FULL:
4060             case AR_SECTION:
4061               current_part_dimension = 1;
4062               break;
4063
4064             case AR_ELEMENT:
4065               current_part_dimension = 0;
4066               break;
4067
4068             case AR_UNKNOWN:
4069               gfc_internal_error ("resolve_ref(): Bad array reference");
4070             }
4071
4072           break;
4073
4074         case REF_COMPONENT:
4075           if (current_part_dimension || seen_part_dimension)
4076             {
4077               if (ref->u.c.component->attr.pointer)
4078                 {
4079                   gfc_error ("Component to the right of a part reference "
4080                              "with nonzero rank must not have the POINTER "
4081                              "attribute at %L", &expr->where);
4082                   return FAILURE;
4083                 }
4084               else if (ref->u.c.component->attr.allocatable)
4085                 {
4086                   gfc_error ("Component to the right of a part reference "
4087                              "with nonzero rank must not have the ALLOCATABLE "
4088                              "attribute at %L", &expr->where);
4089                   return FAILURE;
4090                 }
4091             }
4092
4093           n_components++;
4094           break;
4095
4096         case REF_SUBSTRING:
4097           break;
4098         }
4099
4100       if (((ref->type == REF_COMPONENT && n_components > 1)
4101            || ref->next == NULL)
4102           && current_part_dimension
4103           && seen_part_dimension)
4104         {
4105           gfc_error ("Two or more part references with nonzero rank must "
4106                      "not be specified at %L", &expr->where);
4107           return FAILURE;
4108         }
4109
4110       if (ref->type == REF_COMPONENT)
4111         {
4112           if (current_part_dimension)
4113             seen_part_dimension = 1;
4114
4115           /* reset to make sure */
4116           current_part_dimension = 0;
4117         }
4118     }
4119
4120   return SUCCESS;
4121 }
4122
4123
4124 /* Given an expression, determine its shape.  This is easier than it sounds.
4125    Leaves the shape array NULL if it is not possible to determine the shape.  */
4126
4127 static void
4128 expression_shape (gfc_expr *e)
4129 {
4130   mpz_t array[GFC_MAX_DIMENSIONS];
4131   int i;
4132
4133   if (e->rank == 0 || e->shape != NULL)
4134     return;
4135
4136   for (i = 0; i < e->rank; i++)
4137     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4138       goto fail;
4139
4140   e->shape = gfc_get_shape (e->rank);
4141
4142   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4143
4144   return;
4145
4146 fail:
4147   for (i--; i >= 0; i--)
4148     mpz_clear (array[i]);
4149 }
4150
4151
4152 /* Given a variable expression node, compute the rank of the expression by
4153    examining the base symbol and any reference structures it may have.  */
4154
4155 static void
4156 expression_rank (gfc_expr *e)
4157 {
4158   gfc_ref *ref;
4159   int i, rank;
4160
4161   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4162      could lead to serious confusion...  */
4163   gcc_assert (e->expr_type != EXPR_COMPCALL);
4164
4165   if (e->ref == NULL)
4166     {
4167       if (e->expr_type == EXPR_ARRAY)
4168         goto done;
4169       /* Constructors can have a rank different from one via RESHAPE().  */
4170
4171       if (e->symtree == NULL)
4172         {
4173           e->rank = 0;
4174           goto done;
4175         }
4176
4177       e->rank = (e->symtree->n.sym->as == NULL)
4178                 ? 0 : e->symtree->n.sym->as->rank;
4179       goto done;
4180     }
4181
4182   rank = 0;
4183
4184   for (ref = e->ref; ref; ref = ref->next)
4185     {
4186       if (ref->type != REF_ARRAY)
4187         continue;
4188
4189       if (ref->u.ar.type == AR_FULL)
4190         {
4191           rank = ref->u.ar.as->rank;
4192           break;
4193         }
4194
4195       if (ref->u.ar.type == AR_SECTION)
4196         {
4197           /* Figure out the rank of the section.  */
4198           if (rank != 0)
4199             gfc_internal_error ("expression_rank(): Two array specs");
4200
4201           for (i = 0; i < ref->u.ar.dimen; i++)
4202             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4203                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4204               rank++;
4205
4206           break;
4207         }
4208     }
4209
4210   e->rank = rank;
4211
4212 done:
4213   expression_shape (e);
4214 }
4215
4216
4217 /* Resolve a variable expression.  */
4218
4219 static gfc_try
4220 resolve_variable (gfc_expr *e)
4221 {
4222   gfc_symbol *sym;
4223   gfc_try t;
4224
4225   t = SUCCESS;
4226
4227   if (e->symtree == NULL)
4228     return FAILURE;
4229
4230   if (e->ref && resolve_ref (e) == FAILURE)
4231     return FAILURE;
4232
4233   sym = e->symtree->n.sym;
4234   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
4235     {
4236       e->ts.type = BT_PROCEDURE;
4237       goto resolve_procedure;
4238     }
4239
4240   if (sym->ts.type != BT_UNKNOWN)
4241     gfc_variable_attr (e, &e->ts);
4242   else
4243     {
4244       /* Must be a simple variable reference.  */
4245       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4246         return FAILURE;
4247       e->ts = sym->ts;
4248     }
4249
4250   if (check_assumed_size_reference (sym, e))
4251     return FAILURE;
4252
4253   /* Deal with forward references to entries during resolve_code, to
4254      satisfy, at least partially, 12.5.2.5.  */
4255   if (gfc_current_ns->entries
4256       && current_entry_id == sym->entry_id
4257       && cs_base
4258       && cs_base->current
4259       && cs_base->current->op != EXEC_ENTRY)
4260     {
4261       gfc_entry_list *entry;
4262       gfc_formal_arglist *formal;
4263       int n;
4264       bool seen;
4265
4266       /* If the symbol is a dummy...  */
4267       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4268         {
4269           entry = gfc_current_ns->entries;
4270           seen = false;
4271
4272           /* ...test if the symbol is a parameter of previous entries.  */
4273           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4274             for (formal = entry->sym->formal; formal; formal = formal->next)
4275               {
4276                 if (formal->sym && sym->name == formal->sym->name)
4277                   seen = true;
4278               }
4279
4280           /*  If it has not been seen as a dummy, this is an error.  */
4281           if (!seen)
4282             {
4283               if (specification_expr)
4284                 gfc_error ("Variable '%s', used in a specification expression"
4285                            ", is referenced at %L before the ENTRY statement "
4286                            "in which it is a parameter",
4287                            sym->name, &cs_base->current->loc);
4288               else
4289                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
4290                            "statement in which it is a parameter",
4291                            sym->name, &cs_base->current->loc);
4292               t = FAILURE;
4293             }
4294         }
4295
4296       /* Now do the same check on the specification expressions.  */
4297       specification_expr = 1;
4298       if (sym->ts.type == BT_CHARACTER
4299           && gfc_resolve_expr (sym->ts.cl->length) == FAILURE)
4300         t = FAILURE;
4301
4302       if (sym->as)
4303         for (n = 0; n < sym->as->rank; n++)
4304           {
4305              specification_expr = 1;
4306              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
4307                t = FAILURE;
4308              specification_expr = 1;
4309              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
4310                t = FAILURE;
4311           }
4312       specification_expr = 0;
4313
4314       if (t == SUCCESS)
4315         /* Update the symbol's entry level.  */
4316         sym->entry_id = current_entry_id + 1;
4317     }
4318
4319 resolve_procedure:
4320   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
4321     t = FAILURE;
4322
4323   return t;
4324 }
4325
4326
4327 /* Checks to see that the correct symbol has been host associated.
4328    The only situation where this arises is that in which a twice
4329    contained function is parsed after the host association is made.
4330    Therefore, on detecting this, change the symbol in the expression
4331    and convert the array reference into an actual arglist if the old
4332    symbol is a variable.  */
4333 static bool
4334 check_host_association (gfc_expr *e)
4335 {
4336   gfc_symbol *sym, *old_sym;
4337   gfc_symtree *st;
4338   int n;
4339   gfc_ref *ref;
4340   gfc_actual_arglist *arg, *tail;
4341   bool retval = e->expr_type == EXPR_FUNCTION;
4342
4343   /*  If the expression is the result of substitution in
4344       interface.c(gfc_extend_expr) because there is no way in
4345       which the host association can be wrong.  */
4346   if (e->symtree == NULL
4347         || e->symtree->n.sym == NULL
4348         || e->user_operator)
4349     return retval;
4350
4351   old_sym = e->symtree->n.sym;
4352
4353   if (gfc_current_ns->parent
4354         && old_sym->ns != gfc_current_ns)
4355     {
4356       /* Use the 'USE' name so that renamed module symbols are
4357          correctly handled.  */
4358       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
4359
4360       if (sym && old_sym != sym
4361               && sym->ts.type == old_sym->ts.type
4362               && sym->attr.flavor == FL_PROCEDURE
4363               && sym->attr.contained)
4364         {
4365           /* Clear the shape, since it might not be valid.  */
4366           if (e->shape != NULL)
4367             {
4368               for (n = 0; n < e->rank; n++)
4369                 mpz_clear (e->shape[n]);
4370
4371               gfc_free (e->shape);
4372             }
4373
4374           /* Give the symbol a symtree in the right place!  */
4375           gfc_get_sym_tree (sym->name, gfc_current_ns, &st);
4376           st->n.sym = sym;
4377
4378           if (old_sym->attr.flavor == FL_PROCEDURE)
4379             {
4380               /* Original was function so point to the new symbol, since
4381                  the actual argument list is already attached to the
4382                  expression. */
4383               e->value.function.esym = NULL;
4384               e->symtree = st;
4385             }
4386           else
4387             {
4388               /* Original was variable so convert array references into
4389                  an actual arglist. This does not need any checking now
4390                  since gfc_resolve_function will take care of it.  */
4391               e->value.function.actual = NULL;
4392               e->expr_type = EXPR_FUNCTION;
4393               e->symtree = st;
4394
4395               /* Ambiguity will not arise if the array reference is not
4396                  the last reference.  */
4397               for (ref = e->ref; ref; ref = ref->next)
4398                 if (ref->type == REF_ARRAY && ref->next == NULL)
4399                   break;
4400
4401               gcc_assert (ref->type == REF_ARRAY);
4402
4403               /* Grab the start expressions from the array ref and
4404                  copy them into actual arguments.  */
4405               for (n = 0; n < ref->u.ar.dimen; n++)
4406                 {
4407                   arg = gfc_get_actual_arglist ();
4408                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
4409                   if (e->value.function.actual == NULL)
4410                     tail = e->value.function.actual = arg;
4411                   else
4412                     {
4413                       tail->next = arg;
4414                       tail = arg;
4415                     }
4416                 }
4417
4418               /* Dump the reference list and set the rank.  */
4419               gfc_free_ref_list (e->ref);
4420               e->ref = NULL;
4421               e->rank = sym->as ? sym->as->rank : 0;
4422             }
4423
4424           gfc_resolve_expr (e);
4425           sym->refs++;
4426         }
4427     }
4428   /* This might have changed!  */
4429   return e->expr_type == EXPR_FUNCTION;
4430 }
4431
4432
4433 static void
4434 gfc_resolve_character_operator (gfc_expr *e)
4435 {
4436   gfc_expr *op1 = e->value.op.op1;
4437   gfc_expr *op2 = e->value.op.op2;
4438   gfc_expr *e1 = NULL;
4439   gfc_expr *e2 = NULL;
4440
4441   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
4442
4443   if (op1->ts.cl && op1->ts.cl->length)
4444     e1 = gfc_copy_expr (op1->ts.cl->length);
4445   else if (op1->expr_type == EXPR_CONSTANT)
4446     e1 = gfc_int_expr (op1->value.character.length);
4447
4448   if (op2->ts.cl && op2->ts.cl->length)
4449     e2 = gfc_copy_expr (op2->ts.cl->length);
4450   else if (op2->expr_type == EXPR_CONSTANT)
4451     e2 = gfc_int_expr (op2->value.character.length);
4452
4453   e->ts.cl = gfc_get_charlen ();
4454   e->ts.cl->next = gfc_current_ns->cl_list;
4455   gfc_current_ns->cl_list = e->ts.cl;
4456
4457   if (!e1 || !e2)
4458     return;
4459
4460   e->ts.cl->length = gfc_add (e1, e2);
4461   e->ts.cl->length->ts.type = BT_INTEGER;
4462   e->ts.cl->length->ts.kind = gfc_charlen_int_kind;;
4463   gfc_simplify_expr (e->ts.cl->length, 0);
4464   gfc_resolve_expr (e->ts.cl->length);
4465
4466   return;
4467 }
4468
4469
4470 /*  Ensure that an character expression has a charlen and, if possible, a
4471     length expression.  */
4472
4473 static void
4474 fixup_charlen (gfc_expr *e)
4475 {
4476   /* The cases fall through so that changes in expression type and the need
4477      for multiple fixes are picked up.  In all circumstances, a charlen should
4478      be available for the middle end to hang a backend_decl on.  */
4479   switch (e->expr_type)
4480     {
4481     case EXPR_OP:
4482       gfc_resolve_character_operator (e);
4483
4484     case EXPR_ARRAY:
4485       if (e->expr_type == EXPR_ARRAY)
4486         gfc_resolve_character_array_constructor (e);
4487
4488     case EXPR_SUBSTRING:
4489       if (!e->ts.cl && e->ref)
4490         gfc_resolve_substring_charlen (e);
4491
4492     default:
4493       if (!e->ts.cl)
4494         {
4495           e->ts.cl = gfc_get_charlen ();
4496           e->ts.cl->next = gfc_current_ns->cl_list;
4497           gfc_current_ns->cl_list = e->ts.cl;
4498         }
4499
4500       break;
4501     }
4502 }
4503
4504
4505 /* Update an actual argument to include the passed-object for type-bound
4506    procedures at the right position.  */
4507
4508 static gfc_actual_arglist*
4509 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos)
4510 {
4511   gcc_assert (argpos > 0);
4512
4513   if (argpos == 1)
4514     {
4515       gfc_actual_arglist* result;
4516
4517       result = gfc_get_actual_arglist ();
4518       result->expr = po;
4519       result->next = lst;
4520
4521       return result;
4522     }
4523
4524   gcc_assert (lst);
4525   gcc_assert (argpos > 1);
4526
4527   lst->next = update_arglist_pass (lst->next, po, argpos - 1);
4528   return lst;
4529 }
4530
4531
4532 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
4533
4534 static gfc_expr*
4535 extract_compcall_passed_object (gfc_expr* e)
4536 {
4537   gfc_expr* po;
4538
4539   gcc_assert (e->expr_type == EXPR_COMPCALL);
4540
4541   po = gfc_get_expr ();
4542   po->expr_type = EXPR_VARIABLE;
4543   po->symtree = e->symtree;
4544   po->ref = gfc_copy_ref (e->ref);
4545
4546   if (gfc_resolve_expr (po) == FAILURE)
4547     return NULL;
4548
4549   return po;
4550 }
4551
4552
4553 /* Update the arglist of an EXPR_COMPCALL expression to include the
4554    passed-object.  */
4555
4556 static gfc_try
4557 update_compcall_arglist (gfc_expr* e)
4558 {
4559   gfc_expr* po;
4560   gfc_typebound_proc* tbp;
4561
4562   tbp = e->value.compcall.tbp;
4563
4564   if (tbp->error)
4565     return FAILURE;
4566
4567   po = extract_compcall_passed_object (e);
4568   if (!po)
4569     return FAILURE;
4570
4571   if (po->rank > 0)
4572     {
4573       gfc_error ("Passed-object at %L must be scalar", &e->where);
4574       return FAILURE;
4575     }
4576
4577   if (tbp->nopass)
4578     {
4579       gfc_free_expr (po);
4580       return SUCCESS;
4581     }
4582
4583   gcc_assert (tbp->pass_arg_num > 0);
4584   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
4585                                                   tbp->pass_arg_num);
4586
4587   return SUCCESS;
4588 }
4589
4590
4591 /* Check that the object a TBP is called on is valid, i.e. it must not be
4592    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
4593
4594 static gfc_try
4595 check_typebound_baseobject (gfc_expr* e)
4596 {
4597   gfc_expr* base;
4598
4599   base = extract_compcall_passed_object (e);
4600   if (!base)
4601     return FAILURE;
4602
4603   gcc_assert (base->ts.type == BT_DERIVED);
4604   if (base->ts.derived->attr.abstract)
4605     {
4606       gfc_error ("Base object for type-bound procedure call at %L is of"
4607                  " ABSTRACT type '%s'", &e->where, base->ts.derived->name);
4608       return FAILURE;
4609     }
4610
4611   return SUCCESS;
4612 }
4613
4614
4615 /* Resolve a call to a type-bound procedure, either function or subroutine,
4616    statically from the data in an EXPR_COMPCALL expression.  The adapted
4617    arglist and the target-procedure symtree are returned.  */
4618
4619 static gfc_try
4620 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
4621                           gfc_actual_arglist** actual)
4622 {
4623   gcc_assert (e->expr_type == EXPR_COMPCALL);
4624   gcc_assert (!e->value.compcall.tbp->is_generic);
4625
4626   /* Update the actual arglist for PASS.  */
4627   if (update_compcall_arglist (e) == FAILURE)
4628     return FAILURE;
4629
4630   *actual = e->value.compcall.actual;
4631   *target = e->value.compcall.tbp->u.specific;
4632
4633   gfc_free_ref_list (e->ref);
4634   e->ref = NULL;
4635   e->value.compcall.actual = NULL;
4636
4637   return SUCCESS;
4638 }
4639
4640
4641 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
4642    which of the specific bindings (if any) matches the arglist and transform
4643    the expression into a call of that binding.  */
4644
4645 static gfc_try
4646 resolve_typebound_generic_call (gfc_expr* e)
4647 {
4648   gfc_typebound_proc* genproc;
4649   const char* genname;
4650
4651   gcc_assert (e->expr_type == EXPR_COMPCALL);
4652   genname = e->value.compcall.name;
4653   genproc = e->value.compcall.tbp;
4654
4655   if (!genproc->is_generic)
4656     return SUCCESS;
4657
4658   /* Try the bindings on this type and in the inheritance hierarchy.  */
4659   for (; genproc; genproc = genproc->overridden)
4660     {
4661       gfc_tbp_generic* g;
4662
4663       gcc_assert (genproc->is_generic);
4664       for (g = genproc->u.generic; g; g = g->next)
4665         {
4666           gfc_symbol* target;
4667           gfc_actual_arglist* args;
4668           bool matches;
4669
4670           gcc_assert (g->specific);
4671
4672           if (g->specific->error)
4673             continue;
4674
4675           target = g->specific->u.specific->n.sym;
4676
4677           /* Get the right arglist by handling PASS/NOPASS.  */
4678           args = gfc_copy_actual_arglist (e->value.compcall.actual);
4679           if (!g->specific->nopass)
4680             {
4681               gfc_expr* po;
4682               po = extract_compcall_passed_object (e);
4683               if (!po)
4684                 return FAILURE;
4685
4686               gcc_assert (g->specific->pass_arg_num > 0);
4687               gcc_assert (!g->specific->error);
4688               args = update_arglist_pass (args, po, g->specific->pass_arg_num);
4689             }
4690           resolve_actual_arglist (args, target->attr.proc,
4691                                   is_external_proc (target) && !target->formal);
4692
4693           /* Check if this arglist matches the formal.  */
4694           matches = gfc_arglist_matches_symbol (&args, target);
4695
4696           /* Clean up and break out of the loop if we've found it.  */
4697           gfc_free_actual_arglist (args);
4698           if (matches)
4699             {
4700               e->value.compcall.tbp = g->specific;
4701               goto success;
4702             }
4703         }
4704     }
4705
4706   /* Nothing matching found!  */
4707   gfc_error ("Found no matching specific binding for the call to the GENERIC"
4708              " '%s' at %L", genname, &e->where);
4709   return FAILURE;
4710
4711 success:
4712   return SUCCESS;
4713 }
4714
4715
4716 /* Resolve a call to a type-bound subroutine.  */
4717
4718 static gfc_try
4719 resolve_typebound_call (gfc_code* c)
4720 {
4721   gfc_actual_arglist* newactual;
4722   gfc_symtree* target;
4723
4724   /* Check that's really a SUBROUTINE.  */
4725   if (!c->expr->value.compcall.tbp->subroutine)
4726     {
4727       gfc_error ("'%s' at %L should be a SUBROUTINE",
4728                  c->expr->value.compcall.name, &c->loc);
4729       return FAILURE;
4730     }
4731
4732   if (check_typebound_baseobject (c->expr) == FAILURE)
4733     return FAILURE;
4734
4735   if (resolve_typebound_generic_call (c->expr) == FAILURE)
4736     return FAILURE;
4737
4738   /* Transform into an ordinary EXEC_CALL for now.  */
4739
4740   if (resolve_typebound_static (c->expr, &target, &newactual) == FAILURE)
4741     return FAILURE;
4742
4743   c->ext.actual = newactual;
4744   c->symtree = target;
4745   c->op = EXEC_CALL;
4746
4747   gcc_assert (!c->expr->ref && !c->expr->value.compcall.actual);
4748   gfc_free_expr (c->expr);
4749   c->expr = NULL;
4750
4751   return resolve_call (c);
4752 }
4753
4754
4755 /* Resolve a component-call expression.  */
4756
4757 static gfc_try
4758 resolve_compcall (gfc_expr* e)
4759 {
4760   gfc_actual_arglist* newactual;
4761   gfc_symtree* target;
4762
4763   /* Check that's really a FUNCTION.  */
4764   if (!e->value.compcall.tbp->function)
4765     {
4766       gfc_error ("'%s' at %L should be a FUNCTION",
4767                  e->value.compcall.name, &e->where);
4768       return FAILURE;
4769     }
4770
4771   if (check_typebound_baseobject (e) == FAILURE)
4772     return FAILURE;
4773
4774   if (resolve_typebound_generic_call (e) == FAILURE)
4775     return FAILURE;
4776   gcc_assert (!e->value.compcall.tbp->is_generic);
4777
4778   /* Take the rank from the function's symbol.  */
4779   if (e->value.compcall.tbp->u.specific->n.sym->as)
4780     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
4781
4782   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
4783      arglist to the TBP's binding target.  */
4784
4785   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
4786     return FAILURE;
4787
4788   e->value.function.actual = newactual;
4789   e->value.function.name = e->value.compcall.name;
4790   e->value.function.isym = NULL;
4791   e->value.function.esym = NULL;
4792   e->symtree = target;
4793   e->ts = target->n.sym->ts;
4794   e->expr_type = EXPR_FUNCTION;
4795
4796   return gfc_resolve_expr (e);
4797 }
4798
4799
4800 /* Resolve an expression.  That is, make sure that types of operands agree
4801    with their operators, intrinsic operators are converted to function calls
4802    for overloaded types and unresolved function references are resolved.  */
4803
4804 gfc_try
4805 gfc_resolve_expr (gfc_expr *e)
4806 {
4807   gfc_try t;
4808
4809   if (e == NULL)
4810     return SUCCESS;
4811
4812   switch (e->expr_type)
4813     {
4814     case EXPR_OP:
4815       t = resolve_operator (e);
4816       break;
4817
4818     case EXPR_FUNCTION:
4819     case EXPR_VARIABLE:
4820
4821       if (check_host_association (e))
4822         t = resolve_function (e);
4823       else
4824         {
4825           t = resolve_variable (e);
4826           if (t == SUCCESS)
4827             expression_rank (e);
4828         }
4829
4830       if (e->ts.type == BT_CHARACTER && e->ts.cl == NULL && e->ref
4831           && e->ref->type != REF_SUBSTRING)
4832         gfc_resolve_substring_charlen (e);
4833
4834       break;
4835
4836     case EXPR_COMPCALL:
4837       t = resolve_compcall (e);
4838       break;
4839
4840     case EXPR_SUBSTRING:
4841       t = resolve_ref (e);
4842       break;
4843
4844     case EXPR_CONSTANT:
4845     case EXPR_NULL:
4846       t = SUCCESS;
4847       break;
4848
4849     case EXPR_ARRAY:
4850       t = FAILURE;
4851       if (resolve_ref (e) == FAILURE)
4852         break;
4853
4854       t = gfc_resolve_array_constructor (e);
4855       /* Also try to expand a constructor.  */
4856       if (t == SUCCESS)
4857         {
4858           expression_rank (e);
4859           gfc_expand_constructor (e);
4860         }
4861
4862       /* This provides the opportunity for the length of constructors with
4863          character valued function elements to propagate the string length
4864          to the expression.  */
4865       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
4866         t = gfc_resolve_character_array_constructor (e);
4867
4868       break;
4869
4870     case EXPR_STRUCTURE:
4871       t = resolve_ref (e);
4872       if (t == FAILURE)
4873         break;
4874
4875       t = resolve_structure_cons (e);
4876       if (t == FAILURE)
4877         break;
4878
4879       t = gfc_simplify_expr (e, 0);
4880       break;
4881
4882     default:
4883       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
4884     }
4885
4886   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.cl)
4887     fixup_charlen (e);
4888
4889   return t;
4890 }
4891
4892
4893 /* Resolve an expression from an iterator.  They must be scalar and have
4894    INTEGER or (optionally) REAL type.  */
4895
4896 static gfc_try
4897 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
4898                            const char *name_msgid)
4899 {
4900   if (gfc_resolve_expr (expr) == FAILURE)
4901     return FAILURE;
4902
4903   if (expr->rank != 0)
4904     {
4905       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
4906       return FAILURE;
4907     }
4908
4909   if (expr->ts.type != BT_INTEGER)
4910     {
4911       if (expr->ts.type == BT_REAL)
4912         {
4913           if (real_ok)
4914             return gfc_notify_std (GFC_STD_F95_DEL,
4915                                    "Deleted feature: %s at %L must be integer",
4916                                    _(name_msgid), &expr->where);
4917           else
4918             {
4919               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
4920                          &expr->where);
4921               return FAILURE;
4922             }
4923         }
4924       else
4925         {
4926           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
4927           return FAILURE;
4928         }
4929     }
4930   return SUCCESS;
4931 }
4932
4933
4934 /* Resolve the expressions in an iterator structure.  If REAL_OK is
4935    false allow only INTEGER type iterators, otherwise allow REAL types.  */
4936
4937 gfc_try
4938 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
4939 {
4940   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
4941       == FAILURE)
4942     return FAILURE;
4943
4944   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
4945     {
4946       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
4947                  &iter->var->where);
4948       return FAILURE;
4949     }
4950
4951   if (gfc_resolve_iterator_expr (iter->start, real_ok,
4952                                  "Start expression in DO loop") == FAILURE)
4953     return FAILURE;
4954
4955   if (gfc_resolve_iterator_expr (iter->end, real_ok,
4956                                  "End expression in DO loop") == FAILURE)
4957     return FAILURE;
4958
4959   if (gfc_resolve_iterator_expr (iter->step, real_ok,
4960                                  "Step expression in DO loop") == FAILURE)
4961     return FAILURE;
4962
4963   if (iter->step->expr_type == EXPR_CONSTANT)
4964     {
4965       if ((iter->step->ts.type == BT_INTEGER
4966            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
4967           || (iter->step->ts.type == BT_REAL
4968               && mpfr_sgn (iter->step->value.real) == 0))
4969         {
4970           gfc_error ("Step expression in DO loop at %L cannot be zero",
4971                      &iter->step->where);
4972           return FAILURE;
4973         }
4974     }
4975
4976   /* Convert start, end, and step to the same type as var.  */
4977   if (iter->start->ts.kind != iter->var->ts.kind
4978       || iter->start->ts.type != iter->var->ts.type)
4979     gfc_convert_type (iter->start, &iter->var->ts, 2);
4980
4981   if (iter->end->ts.kind != iter->var->ts.kind
4982       || iter->end->ts.type != iter->var->ts.type)
4983     gfc_convert_type (iter->end, &iter->var->ts, 2);
4984
4985   if (iter->step->ts.kind != iter->var->ts.kind
4986       || iter->step->ts.type != iter->var->ts.type)
4987     gfc_convert_type (iter->step, &iter->var->ts, 2);
4988
4989   if (iter->start->expr_type == EXPR_CONSTANT
4990       && iter->end->expr_type == EXPR_CONSTANT
4991       && iter->step->expr_type == EXPR_CONSTANT)
4992     {
4993       int sgn, cmp;
4994       if (iter->start->ts.type == BT_INTEGER)
4995         {
4996           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
4997           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
4998         }
4999       else
5000         {
5001           sgn = mpfr_sgn (iter->step->value.real);
5002           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
5003         }
5004       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
5005         gfc_warning ("DO loop at %L will be executed zero times",
5006                      &iter->step->where);
5007     }
5008
5009   return SUCCESS;
5010 }
5011
5012
5013 /* Traversal function for find_forall_index.  f == 2 signals that
5014    that variable itself is not to be checked - only the references.  */
5015
5016 static bool
5017 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
5018 {
5019   if (expr->expr_type != EXPR_VARIABLE)
5020     return false;
5021   
5022   /* A scalar assignment  */
5023   if (!expr->ref || *f == 1)
5024     {
5025       if (expr->symtree->n.sym == sym)
5026         return true;
5027       else
5028         return false;
5029     }
5030
5031   if (*f == 2)
5032     *f = 1;
5033   return false;
5034 }
5035
5036
5037 /* Check whether the FORALL index appears in the expression or not.
5038    Returns SUCCESS if SYM is found in EXPR.  */
5039
5040 gfc_try
5041 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
5042 {
5043   if (gfc_traverse_expr (expr, sym, forall_index, f))
5044     return SUCCESS;
5045   else
5046     return FAILURE;
5047 }
5048
5049
5050 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
5051    to be a scalar INTEGER variable.  The subscripts and stride are scalar
5052    INTEGERs, and if stride is a constant it must be nonzero.
5053    Furthermore "A subscript or stride in a forall-triplet-spec shall
5054    not contain a reference to any index-name in the
5055    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
5056
5057 static void
5058 resolve_forall_iterators (gfc_forall_iterator *it)
5059 {
5060   gfc_forall_iterator *iter, *iter2;
5061
5062   for (iter = it; iter; iter = iter->next)
5063     {
5064       if (gfc_resolve_expr (iter->var) == SUCCESS
5065           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
5066         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
5067                    &iter->var->where);
5068
5069       if (gfc_resolve_expr (iter->start) == SUCCESS
5070           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
5071         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
5072                    &iter->start->where);
5073       if (iter->var->ts.kind != iter->start->ts.kind)
5074         gfc_convert_type (iter->start, &iter->var->ts, 2);
5075
5076       if (gfc_resolve_expr (iter->end) == SUCCESS
5077           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
5078         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
5079                    &iter->end->where);
5080       if (iter->var->ts.kind != iter->end->ts.kind)
5081         gfc_convert_type (iter->end, &iter->var->ts, 2);
5082
5083       if (gfc_resolve_expr (iter->stride) == SUCCESS)
5084         {
5085           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
5086             gfc_error ("FORALL stride expression at %L must be a scalar %s",
5087                        &iter->stride->where, "INTEGER");
5088
5089           if (iter->stride->expr_type == EXPR_CONSTANT
5090               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
5091             gfc_error ("FORALL stride expression at %L cannot be zero",
5092                        &iter->stride->where);
5093         }
5094       if (iter->var->ts.kind != iter->stride->ts.kind)
5095         gfc_convert_type (iter->stride, &iter->var->ts, 2);
5096     }
5097
5098   for (iter = it; iter; iter = iter->next)
5099     for (iter2 = iter; iter2; iter2 = iter2->next)
5100       {
5101         if (find_forall_index (iter2->start,
5102                                iter->var->symtree->n.sym, 0) == SUCCESS
5103             || find_forall_index (iter2->end,
5104                                   iter->var->symtree->n.sym, 0) == SUCCESS
5105             || find_forall_index (iter2->stride,
5106                                   iter->var->symtree->n.sym, 0) == SUCCESS)
5107           gfc_error ("FORALL index '%s' may not appear in triplet "
5108                      "specification at %L", iter->var->symtree->name,
5109                      &iter2->start->where);
5110       }
5111 }
5112
5113
5114 /* Given a pointer to a symbol that is a derived type, see if it's
5115    inaccessible, i.e. if it's defined in another module and the components are
5116    PRIVATE.  The search is recursive if necessary.  Returns zero if no
5117    inaccessible components are found, nonzero otherwise.  */
5118
5119 static int
5120 derived_inaccessible (gfc_symbol *sym)
5121 {
5122   gfc_component *c;
5123
5124   if (sym->attr.use_assoc && sym->attr.private_comp)
5125     return 1;
5126
5127   for (c = sym->components; c; c = c->next)
5128     {
5129         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.derived))
5130           return 1;
5131     }
5132
5133   return 0;
5134 }
5135
5136
5137 /* Resolve the argument of a deallocate expression.  The expression must be
5138    a pointer or a full array.  */
5139
5140 static gfc_try
5141 resolve_deallocate_expr (gfc_expr *e)
5142 {
5143   symbol_attribute attr;
5144   int allocatable, pointer, check_intent_in;
5145   gfc_ref *ref;
5146
5147   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
5148   check_intent_in = 1;
5149
5150   if (gfc_resolve_expr (e) == FAILURE)
5151     return FAILURE;
5152
5153   if (e->expr_type != EXPR_VARIABLE)
5154     goto bad;
5155
5156   allocatable = e->symtree->n.sym->attr.allocatable;
5157   pointer = e->symtree->n.sym->attr.pointer;
5158   for (ref = e->ref; ref; ref = ref->next)
5159     {
5160       if (pointer)
5161         check_intent_in = 0;
5162
5163       switch (ref->type)
5164         {
5165         case REF_ARRAY:
5166           if (ref->u.ar.type != AR_FULL)
5167             allocatable = 0;
5168           break;
5169
5170         case REF_COMPONENT:
5171           allocatable = (ref->u.c.component->as != NULL
5172                          && ref->u.c.component->as->type == AS_DEFERRED);
5173           pointer = ref->u.c.component->attr.pointer;
5174           break;
5175
5176         case REF_SUBSTRING:
5177           allocatable = 0;
5178           break;
5179         }
5180     }
5181
5182   attr = gfc_expr_attr (e);
5183
5184   if (allocatable == 0 && attr.pointer == 0)
5185     {
5186     bad:
5187       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
5188                  &e->where);
5189     }
5190
5191   if (check_intent_in
5192       && e->symtree->n.sym->attr.intent == INTENT_IN)
5193     {
5194       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
5195                  e->symtree->n.sym->name, &e->where);
5196       return FAILURE;
5197     }
5198
5199   return SUCCESS;
5200 }
5201
5202
5203 /* Returns true if the expression e contains a reference to the symbol sym.  */
5204 static bool
5205 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
5206 {
5207   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
5208     return true;
5209
5210   return false;
5211 }
5212
5213 bool
5214 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
5215 {
5216   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
5217 }
5218
5219
5220 /* Given the expression node e for an allocatable/pointer of derived type to be
5221    allocated, get the expression node to be initialized afterwards (needed for
5222    derived types with default initializers, and derived types with allocatable
5223    components that need nullification.)  */
5224
5225 static gfc_expr *
5226 expr_to_initialize (gfc_expr *e)
5227 {
5228   gfc_expr *result;
5229   gfc_ref *ref;
5230   int i;
5231
5232   result = gfc_copy_expr (e);
5233
5234   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
5235   for (ref = result->ref; ref; ref = ref->next)
5236     if (ref->type == REF_ARRAY && ref->next == NULL)
5237       {
5238         ref->u.ar.type = AR_FULL;
5239
5240         for (i = 0; i < ref->u.ar.dimen; i++)
5241           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
5242
5243         result->rank = ref->u.ar.dimen;
5244         break;
5245       }
5246
5247   return result;
5248 }
5249
5250
5251 /* Resolve the expression in an ALLOCATE statement, doing the additional
5252    checks to see whether the expression is OK or not.  The expression must
5253    have a trailing array reference that gives the size of the array.  */
5254
5255 static gfc_try
5256 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
5257 {
5258   int i, pointer, allocatable, dimension, check_intent_in;
5259   symbol_attribute attr;
5260   gfc_ref *ref, *ref2;
5261   gfc_array_ref *ar;
5262   gfc_code *init_st;
5263   gfc_expr *init_e;
5264   gfc_symbol *sym;
5265   gfc_alloc *a;
5266
5267   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
5268   check_intent_in = 1;
5269
5270   if (gfc_resolve_expr (e) == FAILURE)
5271     return FAILURE;
5272
5273   /* Make sure the expression is allocatable or a pointer.  If it is
5274      pointer, the next-to-last reference must be a pointer.  */
5275
5276   ref2 = NULL;
5277
5278   if (e->expr_type != EXPR_VARIABLE)
5279     {
5280       allocatable = 0;
5281       attr = gfc_expr_attr (e);
5282       pointer = attr.pointer;
5283       dimension = attr.dimension;
5284     }
5285   else
5286     {
5287       allocatable = e->symtree->n.sym->attr.allocatable;
5288       pointer = e->symtree->n.sym->attr.pointer;
5289       dimension = e->symtree->n.sym->attr.dimension;
5290
5291       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
5292         {
5293           if (pointer)
5294             check_intent_in = 0;
5295
5296           switch (ref->type)
5297             {
5298               case REF_ARRAY:
5299                 if (ref->next != NULL)
5300                   pointer = 0;
5301                 break;
5302
5303               case REF_COMPONENT:
5304                 allocatable = (ref->u.c.component->as != NULL
5305                                && ref->u.c.component->as->type == AS_DEFERRED);
5306
5307                 pointer = ref->u.c.component->attr.pointer;
5308                 dimension = ref->u.c.component->attr.dimension;
5309                 break;
5310
5311               case REF_SUBSTRING:
5312                 allocatable = 0;
5313                 pointer = 0;
5314                 break;
5315             }
5316         }
5317     }
5318
5319   if (allocatable == 0 && pointer == 0)
5320     {
5321       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
5322                  &e->where);
5323       return FAILURE;
5324     }
5325
5326   if (check_intent_in
5327       && e->symtree->n.sym->attr.intent == INTENT_IN)
5328     {
5329       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
5330                  e->symtree->n.sym->name, &e->where);
5331       return FAILURE;
5332     }
5333
5334   /* Add default initializer for those derived types that need them.  */
5335   if (e->ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&e->ts)))
5336     {
5337       init_st = gfc_get_code ();
5338       init_st->loc = code->loc;
5339       init_st->op = EXEC_INIT_ASSIGN;
5340       init_st->expr = expr_to_initialize (e);
5341       init_st->expr2 = init_e;
5342       init_st->next = code->next;
5343       code->next = init_st;
5344     }
5345
5346   if (pointer && dimension == 0)
5347     return SUCCESS;
5348
5349   /* Make sure the next-to-last reference node is an array specification.  */
5350
5351   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL)
5352     {
5353       gfc_error ("Array specification required in ALLOCATE statement "
5354                  "at %L", &e->where);
5355       return FAILURE;
5356     }
5357
5358   /* Make sure that the array section reference makes sense in the
5359     context of an ALLOCATE specification.  */
5360
5361   ar = &ref2->u.ar;
5362
5363   for (i = 0; i < ar->dimen; i++)
5364     {
5365       if (ref2->u.ar.type == AR_ELEMENT)
5366         goto check_symbols;
5367
5368       switch (ar->dimen_type[i])
5369         {
5370         case DIMEN_ELEMENT:
5371           break;
5372
5373         case DIMEN_RANGE:
5374           if (ar->start[i] != NULL
5375               && ar->end[i] != NULL
5376               && ar->stride[i] == NULL)
5377             break;
5378
5379           /* Fall Through...  */
5380
5381         case DIMEN_UNKNOWN:
5382         case DIMEN_VECTOR:
5383           gfc_error ("Bad array specification in ALLOCATE statement at %L",
5384                      &e->where);
5385           return FAILURE;
5386         }
5387
5388 check_symbols:
5389
5390       for (a = code->ext.alloc_list; a; a = a->next)
5391         {
5392           sym = a->expr->symtree->n.sym;
5393
5394           /* TODO - check derived type components.  */
5395           if (sym->ts.type == BT_DERIVED)
5396             continue;
5397
5398           if ((ar->start[i] != NULL
5399                && gfc_find_sym_in_expr (sym, ar->start[i]))
5400               || (ar->end[i] != NULL
5401                   && gfc_find_sym_in_expr (sym, ar->end[i])))
5402             {
5403               gfc_error ("'%s' must not appear in the array specification at "
5404                          "%L in the same ALLOCATE statement where it is "
5405                          "itself allocated", sym->name, &ar->where);
5406               return FAILURE;
5407             }
5408         }
5409     }
5410
5411   return SUCCESS;
5412 }
5413
5414 static void
5415 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
5416 {
5417   gfc_expr *stat, *errmsg, *pe, *qe;
5418   gfc_alloc *a, *p, *q;
5419
5420   stat = code->expr ? code->expr : NULL;
5421
5422   errmsg = code->expr2 ? code->expr2 : NULL;
5423
5424   /* Check the stat variable.  */
5425   if (stat)
5426     {
5427       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
5428         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
5429                    stat->symtree->n.sym->name, &stat->where);
5430
5431       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
5432         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
5433                    &stat->where);
5434
5435       if (stat->ts.type != BT_INTEGER
5436           && !(stat->ref && (stat->ref->type == REF_ARRAY
5437                || stat->ref->type == REF_COMPONENT)))
5438         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
5439                    "variable", &stat->where);
5440
5441       for (p = code->ext.alloc_list; p; p = p->next)
5442         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
5443           gfc_error ("Stat-variable at %L shall not be %sd within "
5444                      "the same %s statement", &stat->where, fcn, fcn);
5445     }
5446
5447   /* Check the errmsg variable.  */
5448   if (errmsg)
5449     {
5450       if (!stat)
5451         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
5452                      &errmsg->where);
5453
5454       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
5455         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
5456                    errmsg->symtree->n.sym->name, &errmsg->where);
5457
5458       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
5459         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
5460                    &errmsg->where);
5461
5462       if (errmsg->ts.type != BT_CHARACTER
5463           && !(errmsg->ref
5464                && (errmsg->ref->type == REF_ARRAY
5465                    || errmsg->ref->type == REF_COMPONENT)))
5466         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
5467                    "variable", &errmsg->where);
5468
5469       for (p = code->ext.alloc_list; p; p = p->next)
5470         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
5471           gfc_error ("Errmsg-variable at %L shall not be %sd within "
5472                      "the same %s statement", &errmsg->where, fcn, fcn);
5473     }
5474
5475   /* Check that an allocate-object appears only once in the statement.  
5476      FIXME: Checking derived types is disabled.  */
5477   for (p = code->ext.alloc_list; p; p = p->next)
5478     {
5479       pe = p->expr;
5480       if ((pe->ref && pe->ref->type != REF_COMPONENT)
5481            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
5482         {
5483           for (q = p->next; q; q = q->next)
5484             {
5485               qe = q->expr;
5486               if ((qe->ref && qe->ref->type != REF_COMPONENT)
5487                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
5488                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
5489                 gfc_error ("Allocate-object at %L also appears at %L",
5490                            &pe->where, &qe->where);
5491             }
5492         }
5493     }
5494
5495   if (strcmp (fcn, "ALLOCATE") == 0)
5496     {
5497       for (a = code->ext.alloc_list; a; a = a->next)
5498         resolve_allocate_expr (a->expr, code);
5499     }
5500   else
5501     {
5502       for (a = code->ext.alloc_list; a; a = a->next)
5503         resolve_deallocate_expr (a->expr);
5504     }
5505 }
5506
5507
5508 /************ SELECT CASE resolution subroutines ************/
5509
5510 /* Callback function for our mergesort variant.  Determines interval
5511    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
5512    op1 > op2.  Assumes we're not dealing with the default case.  
5513    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
5514    There are nine situations to check.  */
5515
5516 static int
5517 compare_cases (const gfc_case *op1, const gfc_case *op2)
5518 {
5519   int retval;
5520
5521   if (op1->low == NULL) /* op1 = (:L)  */
5522     {
5523       /* op2 = (:N), so overlap.  */
5524       retval = 0;
5525       /* op2 = (M:) or (M:N),  L < M  */
5526       if (op2->low != NULL
5527           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
5528         retval = -1;
5529     }
5530   else if (op1->high == NULL) /* op1 = (K:)  */
5531     {
5532       /* op2 = (M:), so overlap.  */
5533       retval = 0;
5534       /* op2 = (:N) or (M:N), K > N  */
5535       if (op2->high != NULL
5536           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
5537         retval = 1;
5538     }
5539   else /* op1 = (K:L)  */
5540     {
5541       if (op2->low == NULL)       /* op2 = (:N), K > N  */
5542         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
5543                  ? 1 : 0;
5544       else if (op2->high == NULL) /* op2 = (M:), L < M  */
5545         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
5546                  ? -1 : 0;
5547       else                      /* op2 = (M:N)  */
5548         {
5549           retval =  0;
5550           /* L < M  */
5551           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
5552             retval =  -1;
5553           /* K > N  */
5554           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
5555             retval =  1;
5556         }
5557     }
5558
5559   return retval;
5560 }
5561
5562
5563 /* Merge-sort a double linked case list, detecting overlap in the
5564    process.  LIST is the head of the double linked case list before it
5565    is sorted.  Returns the head of the sorted list if we don't see any
5566    overlap, or NULL otherwise.  */
5567
5568 static gfc_case *
5569 check_case_overlap (gfc_case *list)
5570 {
5571   gfc_case *p, *q, *e, *tail;
5572   int insize, nmerges, psize, qsize, cmp, overlap_seen;
5573
5574   /* If the passed list was empty, return immediately.  */
5575   if (!list)
5576     return NULL;
5577
5578   overlap_seen = 0;
5579   insize = 1;
5580
5581   /* Loop unconditionally.  The only exit from this loop is a return
5582      statement, when we've finished sorting the case list.  */
5583   for (;;)
5584     {
5585       p = list;
5586       list = NULL;
5587       tail = NULL;
5588
5589       /* Count the number of merges we do in this pass.  */
5590       nmerges = 0;
5591
5592       /* Loop while there exists a merge to be done.  */
5593       while (p)
5594         {
5595           int i;
5596
5597           /* Count this merge.  */
5598           nmerges++;
5599
5600           /* Cut the list in two pieces by stepping INSIZE places
5601              forward in the list, starting from P.  */
5602           psize = 0;
5603           q = p;
5604           for (i = 0; i < insize; i++)
5605             {
5606               psize++;
5607               q = q->right;
5608               if (!q)
5609                 break;
5610             }
5611           qsize = insize;
5612
5613           /* Now we have two lists.  Merge them!  */
5614           while (psize > 0 || (qsize > 0 && q != NULL))
5615             {
5616               /* See from which the next case to merge comes from.  */
5617               if (psize == 0)
5618                 {
5619                   /* P is empty so the next case must come from Q.  */
5620                   e = q;
5621                   q = q->right;
5622                   qsize--;
5623                 }
5624               else if (qsize == 0 || q == NULL)
5625                 {
5626                   /* Q is empty.  */
5627                   e = p;
5628                   p = p->right;
5629                   psize--;
5630                 }
5631               else
5632                 {
5633                   cmp = compare_cases (p, q);
5634                   if (cmp < 0)
5635                     {
5636                       /* The whole case range for P is less than the
5637                          one for Q.  */
5638                       e = p;
5639                       p = p->right;
5640                       psize--;
5641                     }
5642                   else if (cmp > 0)
5643                     {
5644                       /* The whole case range for Q is greater than
5645                          the case range for P.  */
5646                       e = q;
5647                       q = q->right;
5648                       qsize--;
5649                     }
5650                   else
5651                     {
5652                       /* The cases overlap, or they are the same
5653                          element in the list.  Either way, we must
5654                          issue an error and get the next case from P.  */
5655                       /* FIXME: Sort P and Q by line number.  */
5656                       gfc_error ("CASE label at %L overlaps with CASE "
5657                                  "label at %L", &p->where, &q->where);
5658                       overlap_seen = 1;
5659                       e = p;
5660                       p = p->right;
5661                       psize--;
5662                     }
5663                 }
5664
5665                 /* Add the next element to the merged list.  */
5666               if (tail)
5667                 tail->right = e;
5668               else
5669                 list = e;
5670               e->left = tail;
5671               tail = e;
5672             }
5673
5674           /* P has now stepped INSIZE places along, and so has Q.  So
5675              they're the same.  */
5676           p = q;
5677         }
5678       tail->right = NULL;
5679
5680       /* If we have done only one merge or none at all, we've
5681          finished sorting the cases.  */
5682       if (nmerges <= 1)
5683         {
5684           if (!overlap_seen)
5685             return list;
5686           else
5687             return NULL;
5688         }
5689
5690       /* Otherwise repeat, merging lists twice the size.  */
5691       insize *= 2;
5692     }
5693 }
5694
5695
5696 /* Check to see if an expression is suitable for use in a CASE statement.
5697    Makes sure that all case expressions are scalar constants of the same
5698    type.  Return FAILURE if anything is wrong.  */
5699
5700 static gfc_try
5701 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
5702 {
5703   if (e == NULL) return SUCCESS;
5704
5705   if (e->ts.type != case_expr->ts.type)
5706     {
5707       gfc_error ("Expression in CASE statement at %L must be of type %s",
5708                  &e->where, gfc_basic_typename (case_expr->ts.type));
5709       return FAILURE;
5710     }
5711
5712   /* C805 (R808) For a given case-construct, each case-value shall be of
5713      the same type as case-expr.  For character type, length differences
5714      are allowed, but the kind type parameters shall be the same.  */
5715
5716   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
5717     {
5718       gfc_error ("Expression in CASE statement at %L must be of kind %d",
5719                  &e->where, case_expr->ts.kind);
5720       return FAILURE;
5721     }
5722
5723   /* Convert the case value kind to that of case expression kind, if needed.
5724      FIXME:  Should a warning be issued?  */
5725   if (e->ts.kind != case_expr->ts.kind)
5726     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
5727
5728   if (e->rank != 0)
5729     {
5730       gfc_error ("Expression in CASE statement at %L must be scalar",
5731                  &e->where);
5732       return FAILURE;
5733     }
5734
5735   return SUCCESS;
5736 }
5737
5738
5739 /* Given a completely parsed select statement, we:
5740
5741      - Validate all expressions and code within the SELECT.
5742      - Make sure that the selection expression is not of the wrong type.
5743      - Make sure that no case ranges overlap.
5744      - Eliminate unreachable cases and unreachable code resulting from
5745        removing case labels.
5746
5747    The standard does allow unreachable cases, e.g. CASE (5:3).  But
5748    they are a hassle for code generation, and to prevent that, we just
5749    cut them out here.  This is not necessary for overlapping cases
5750    because they are illegal and we never even try to generate code.
5751
5752    We have the additional caveat that a SELECT construct could have
5753    been a computed GOTO in the source code. Fortunately we can fairly
5754    easily work around that here: The case_expr for a "real" SELECT CASE
5755    is in code->expr1, but for a computed GOTO it is in code->expr2. All
5756    we have to do is make sure that the case_expr is a scalar integer
5757    expression.  */
5758
5759 static void
5760 resolve_select (gfc_code *code)
5761 {
5762   gfc_code *body;
5763   gfc_expr *case_expr;
5764   gfc_case *cp, *default_case, *tail, *head;
5765   int seen_unreachable;
5766   int seen_logical;
5767   int ncases;
5768   bt type;
5769   gfc_try t;
5770
5771   if (code->expr == NULL)
5772     {
5773       /* This was actually a computed GOTO statement.  */
5774       case_expr = code->expr2;
5775       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
5776         gfc_error ("Selection expression in computed GOTO statement "
5777                    "at %L must be a scalar integer expression",
5778                    &case_expr->where);
5779
5780       /* Further checking is not necessary because this SELECT was built
5781          by the compiler, so it should always be OK.  Just move the
5782          case_expr from expr2 to expr so that we can handle computed
5783          GOTOs as normal SELECTs from here on.  */
5784       code->expr = code->expr2;
5785       code->expr2 = NULL;
5786       return;
5787     }
5788
5789   case_expr = code->expr;
5790
5791   type = case_expr->ts.type;
5792   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
5793     {
5794       gfc_error ("Argument of SELECT statement at %L cannot be %s",
5795                  &case_expr->where, gfc_typename (&case_expr->ts));
5796
5797       /* Punt. Going on here just produce more garbage error messages.  */
5798       return;
5799     }
5800
5801   if (case_expr->rank != 0)
5802     {
5803       gfc_error ("Argument of SELECT statement at %L must be a scalar "
5804                  "expression", &case_expr->where);
5805
5806       /* Punt.  */
5807       return;
5808     }
5809
5810   /* PR 19168 has a long discussion concerning a mismatch of the kinds
5811      of the SELECT CASE expression and its CASE values.  Walk the lists
5812      of case values, and if we find a mismatch, promote case_expr to
5813      the appropriate kind.  */
5814
5815   if (type == BT_LOGICAL || type == BT_INTEGER)
5816     {
5817       for (body = code->block; body; body = body->block)
5818         {
5819           /* Walk the case label list.  */
5820           for (cp = body->ext.case_list; cp; cp = cp->next)
5821             {
5822               /* Intercept the DEFAULT case.  It does not have a kind.  */
5823               if (cp->low == NULL && cp->high == NULL)
5824                 continue;
5825
5826               /* Unreachable case ranges are discarded, so ignore.  */
5827               if (cp->low != NULL && cp->high != NULL
5828                   && cp->low != cp->high
5829                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
5830                 continue;
5831
5832               /* FIXME: Should a warning be issued?  */
5833               if (cp->low != NULL
5834                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
5835                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
5836
5837               if (cp->high != NULL
5838                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
5839                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
5840             }
5841          }
5842     }
5843
5844   /* Assume there is no DEFAULT case.  */
5845   default_case = NULL;
5846   head = tail = NULL;
5847   ncases = 0;
5848   seen_logical = 0;
5849
5850   for (body = code->block; body; body = body->block)
5851     {
5852       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
5853       t = SUCCESS;
5854       seen_unreachable = 0;
5855
5856       /* Walk the case label list, making sure that all case labels
5857          are legal.  */
5858       for (cp = body->ext.case_list; cp; cp = cp->next)
5859         {
5860           /* Count the number of cases in the whole construct.  */
5861           ncases++;
5862
5863           /* Intercept the DEFAULT case.  */
5864           if (cp->low == NULL && cp->high == NULL)
5865             {
5866               if (default_case != NULL)
5867                 {
5868                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
5869                              "by a second DEFAULT CASE at %L",
5870                              &default_case->where, &cp->where);
5871                   t = FAILURE;
5872                   break;
5873                 }
5874               else
5875                 {
5876                   default_case = cp;
5877                   continue;
5878                 }
5879             }
5880
5881           /* Deal with single value cases and case ranges.  Errors are
5882              issued from the validation function.  */
5883           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
5884              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
5885             {
5886               t = FAILURE;
5887               break;
5888             }
5889
5890           if (type == BT_LOGICAL
5891               && ((cp->low == NULL || cp->high == NULL)
5892                   || cp->low != cp->high))
5893             {
5894               gfc_error ("Logical range in CASE statement at %L is not "
5895                          "allowed", &cp->low->where);
5896               t = FAILURE;
5897               break;
5898             }
5899
5900           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
5901             {
5902               int value;
5903               value = cp->low->value.logical == 0 ? 2 : 1;
5904               if (value & seen_logical)
5905                 {
5906                   gfc_error ("constant logical value in CASE statement "
5907                              "is repeated at %L",
5908                              &cp->low->where);
5909                   t = FAILURE;
5910                   break;
5911                 }
5912               seen_logical |= value;
5913             }
5914
5915           if (cp->low != NULL && cp->high != NULL
5916               && cp->low != cp->high
5917               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
5918             {
5919               if (gfc_option.warn_surprising)
5920                 gfc_warning ("Range specification at %L can never "
5921                              "be matched", &cp->where);
5922
5923               cp->unreachable = 1;
5924               seen_unreachable = 1;
5925             }
5926           else
5927             {
5928               /* If the case range can be matched, it can also overlap with
5929                  other cases.  To make sure it does not, we put it in a
5930                  double linked list here.  We sort that with a merge sort
5931                  later on to detect any overlapping cases.  */
5932               if (!head)
5933                 {
5934                   head = tail = cp;
5935                   head->right = head->left = NULL;
5936                 }
5937               else
5938                 {
5939                   tail->right = cp;
5940                   tail->right->left = tail;
5941                   tail = tail->right;
5942                   tail->right = NULL;
5943                 }
5944             }
5945         }
5946
5947       /* It there was a failure in the previous case label, give up
5948          for this case label list.  Continue with the next block.  */
5949       if (t == FAILURE)
5950         continue;
5951
5952       /* See if any case labels that are unreachable have been seen.
5953          If so, we eliminate them.  This is a bit of a kludge because
5954          the case lists for a single case statement (label) is a
5955          single forward linked lists.  */
5956       if (seen_unreachable)
5957       {
5958         /* Advance until the first case in the list is reachable.  */
5959         while (body->ext.case_list != NULL
5960                && body->ext.case_list->unreachable)
5961           {
5962             gfc_case *n = body->ext.case_list;
5963             body->ext.case_list = body->ext.case_list->next;
5964             n->next = NULL;
5965             gfc_free_case_list (n);
5966           }
5967
5968         /* Strip all other unreachable cases.  */
5969         if (body->ext.case_list)
5970           {
5971             for (cp = body->ext.case_list; cp->next; cp = cp->next)
5972               {
5973                 if (cp->next->unreachable)
5974                   {
5975                     gfc_case *n = cp->next;
5976                     cp->next = cp->next->next;
5977                     n->next = NULL;
5978                     gfc_free_case_list (n);
5979                   }
5980               }
5981           }
5982       }
5983     }
5984
5985   /* See if there were overlapping cases.  If the check returns NULL,
5986      there was overlap.  In that case we don't do anything.  If head
5987      is non-NULL, we prepend the DEFAULT case.  The sorted list can
5988      then used during code generation for SELECT CASE constructs with
5989      a case expression of a CHARACTER type.  */
5990   if (head)
5991     {
5992       head = check_case_overlap (head);
5993
5994       /* Prepend the default_case if it is there.  */
5995       if (head != NULL && default_case)
5996         {
5997           default_case->left = NULL;
5998           default_case->right = head;
5999           head->left = default_case;
6000         }
6001     }
6002
6003   /* Eliminate dead blocks that may be the result if we've seen
6004      unreachable case labels for a block.  */
6005   for (body = code; body && body->block; body = body->block)
6006     {
6007       if (body->block->ext.case_list == NULL)
6008         {
6009           /* Cut the unreachable block from the code chain.  */
6010           gfc_code *c = body->block;
6011           body->block = c->block;
6012
6013           /* Kill the dead block, but not the blocks below it.  */
6014           c->block = NULL;
6015           gfc_free_statements (c);
6016         }
6017     }
6018
6019   /* More than two cases is legal but insane for logical selects.
6020      Issue a warning for it.  */
6021   if (gfc_option.warn_surprising && type == BT_LOGICAL
6022       && ncases > 2)
6023     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
6024                  &code->loc);
6025 }
6026
6027
6028 /* Resolve a transfer statement. This is making sure that:
6029    -- a derived type being transferred has only non-pointer components
6030    -- a derived type being transferred doesn't have private components, unless 
6031       it's being transferred from the module where the type was defined
6032    -- we're not trying to transfer a whole assumed size array.  */
6033
6034 static void
6035 resolve_transfer (gfc_code *code)
6036 {
6037   gfc_typespec *ts;
6038   gfc_symbol *sym;
6039   gfc_ref *ref;
6040   gfc_expr *exp;
6041
6042   exp = code->expr;
6043
6044   if (exp->expr_type != EXPR_VARIABLE && exp->expr_type != EXPR_FUNCTION)
6045     return;
6046
6047   sym = exp->symtree->n.sym;
6048   ts = &sym->ts;
6049
6050   /* Go to actual component transferred.  */
6051   for (ref = code->expr->ref; ref; ref = ref->next)
6052     if (ref->type == REF_COMPONENT)
6053       ts = &ref->u.c.component->ts;
6054
6055   if (ts->type == BT_DERIVED)
6056     {
6057       /* Check that transferred derived type doesn't contain POINTER
6058          components.  */
6059       if (ts->derived->attr.pointer_comp)
6060         {
6061           gfc_error ("Data transfer element at %L cannot have "
6062                      "POINTER components", &code->loc);
6063           return;
6064         }
6065
6066       if (ts->derived->attr.alloc_comp)
6067         {
6068           gfc_error ("Data transfer element at %L cannot have "
6069                      "ALLOCATABLE components", &code->loc);
6070           return;
6071         }
6072
6073       if (derived_inaccessible (ts->derived))
6074         {
6075           gfc_error ("Data transfer element at %L cannot have "
6076                      "PRIVATE components",&code->loc);
6077           return;
6078         }
6079     }
6080
6081   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
6082       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
6083     {
6084       gfc_error ("Data transfer element at %L cannot be a full reference to "
6085                  "an assumed-size array", &code->loc);
6086       return;
6087     }
6088 }
6089
6090
6091 /*********** Toplevel code resolution subroutines ***********/
6092
6093 /* Find the set of labels that are reachable from this block.  We also
6094    record the last statement in each block.  */
6095      
6096 static void
6097 find_reachable_labels (gfc_code *block)
6098 {
6099   gfc_code *c;
6100
6101   if (!block)
6102     return;
6103
6104   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
6105
6106   /* Collect labels in this block.  We don't keep those corresponding
6107      to END {IF|SELECT}, these are checked in resolve_branch by going
6108      up through the code_stack.  */
6109   for (c = block; c; c = c->next)
6110     {
6111       if (c->here && c->op != EXEC_END_BLOCK)
6112         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
6113     }
6114
6115   /* Merge with labels from parent block.  */
6116   if (cs_base->prev)
6117     {
6118       gcc_assert (cs_base->prev->reachable_labels);
6119       bitmap_ior_into (cs_base->reachable_labels,
6120                        cs_base->prev->reachable_labels);
6121     }
6122 }
6123
6124 /* Given a branch to a label, see if the branch is conforming.
6125    The code node describes where the branch is located.  */
6126
6127 static void
6128 resolve_branch (gfc_st_label *label, gfc_code *code)
6129 {
6130   code_stack *stack;
6131
6132   if (label == NULL)
6133     return;
6134
6135   /* Step one: is this a valid branching target?  */
6136
6137   if (label->defined == ST_LABEL_UNKNOWN)
6138     {
6139       gfc_error ("Label %d referenced at %L is never defined", label->value,
6140                  &label->where);
6141       return;
6142     }
6143
6144   if (label->defined != ST_LABEL_TARGET)
6145     {
6146       gfc_error ("Statement at %L is not a valid branch target statement "
6147                  "for the branch statement at %L", &label->where, &code->loc);
6148       return;
6149     }
6150
6151   /* Step two: make sure this branch is not a branch to itself ;-)  */
6152
6153   if (code->here == label)
6154     {
6155       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
6156       return;
6157     }
6158
6159   /* Step three:  See if the label is in the same block as the
6160      branching statement.  The hard work has been done by setting up
6161      the bitmap reachable_labels.  */
6162
6163   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
6164     return;
6165
6166   /* Step four:  If we haven't found the label in the bitmap, it may
6167     still be the label of the END of the enclosing block, in which
6168     case we find it by going up the code_stack.  */
6169
6170   for (stack = cs_base; stack; stack = stack->prev)
6171     if (stack->current->next && stack->current->next->here == label)
6172       break;
6173
6174   if (stack)
6175     {
6176       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
6177       return;
6178     }
6179
6180   /* The label is not in an enclosing block, so illegal.  This was
6181      allowed in Fortran 66, so we allow it as extension.  No
6182      further checks are necessary in this case.  */
6183   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
6184                   "as the GOTO statement at %L", &label->where,
6185                   &code->loc);
6186   return;
6187 }
6188
6189
6190 /* Check whether EXPR1 has the same shape as EXPR2.  */
6191
6192 static gfc_try
6193 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
6194 {
6195   mpz_t shape[GFC_MAX_DIMENSIONS];
6196   mpz_t shape2[GFC_MAX_DIMENSIONS];
6197   gfc_try result = FAILURE;
6198   int i;
6199
6200   /* Compare the rank.  */
6201   if (expr1->rank != expr2->rank)
6202     return result;
6203
6204   /* Compare the size of each dimension.  */
6205   for (i=0; i<expr1->rank; i++)
6206     {
6207       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
6208         goto ignore;
6209
6210       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
6211         goto ignore;
6212
6213       if (mpz_cmp (shape[i], shape2[i]))
6214         goto over;
6215     }
6216
6217   /* When either of the two expression is an assumed size array, we
6218      ignore the comparison of dimension sizes.  */
6219 ignore:
6220   result = SUCCESS;
6221
6222 over:
6223   for (i--; i >= 0; i--)
6224     {
6225       mpz_clear (shape[i]);
6226       mpz_clear (shape2[i]);
6227     }
6228   return result;
6229 }
6230
6231
6232 /* Check whether a WHERE assignment target or a WHERE mask expression
6233    has the same shape as the outmost WHERE mask expression.  */
6234
6235 static void
6236 resolve_where (gfc_code *code, gfc_expr *mask)
6237 {
6238   gfc_code *cblock;
6239   gfc_code *cnext;
6240   gfc_expr *e = NULL;
6241
6242   cblock = code->block;
6243
6244   /* Store the first WHERE mask-expr of the WHERE statement or construct.
6245      In case of nested WHERE, only the outmost one is stored.  */
6246   if (mask == NULL) /* outmost WHERE */
6247     e = cblock->expr;
6248   else /* inner WHERE */
6249     e = mask;
6250
6251   while (cblock)
6252     {
6253       if (cblock->expr)
6254         {
6255           /* Check if the mask-expr has a consistent shape with the
6256              outmost WHERE mask-expr.  */
6257           if (resolve_where_shape (cblock->expr, e) == FAILURE)
6258             gfc_error ("WHERE mask at %L has inconsistent shape",
6259                        &cblock->expr->where);
6260          }
6261
6262       /* the assignment statement of a WHERE statement, or the first
6263          statement in where-body-construct of a WHERE construct */
6264       cnext = cblock->next;
6265       while (cnext)
6266         {
6267           switch (cnext->op)
6268             {
6269             /* WHERE assignment statement */
6270             case EXEC_ASSIGN:
6271
6272               /* Check shape consistent for WHERE assignment target.  */
6273               if (e && resolve_where_shape (cnext->expr, e) == FAILURE)
6274                gfc_error ("WHERE assignment target at %L has "
6275                           "inconsistent shape", &cnext->expr->where);
6276               break;
6277
6278   
6279             case EXEC_ASSIGN_CALL:
6280               resolve_call (cnext);
6281               if (!cnext->resolved_sym->attr.elemental)
6282                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
6283                           &cnext->ext.actual->expr->where);
6284               break;
6285
6286             /* WHERE or WHERE construct is part of a where-body-construct */
6287             case EXEC_WHERE:
6288               resolve_where (cnext, e);
6289               break;
6290
6291             default:
6292               gfc_error ("Unsupported statement inside WHERE at %L",
6293                          &cnext->loc);
6294             }
6295          /* the next statement within the same where-body-construct */
6296          cnext = cnext->next;
6297        }
6298     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
6299     cblock = cblock->block;
6300   }
6301 }
6302
6303
6304 /* Resolve assignment in FORALL construct.
6305    NVAR is the number of FORALL index variables, and VAR_EXPR records the
6306    FORALL index variables.  */
6307
6308 static void
6309 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
6310 {
6311   int n;
6312
6313   for (n = 0; n < nvar; n++)
6314     {
6315       gfc_symbol *forall_index;
6316
6317       forall_index = var_expr[n]->symtree->n.sym;
6318
6319       /* Check whether the assignment target is one of the FORALL index
6320          variable.  */
6321       if ((code->expr->expr_type == EXPR_VARIABLE)
6322           && (code->expr->symtree->n.sym == forall_index))
6323         gfc_error ("Assignment to a FORALL index variable at %L",
6324                    &code->expr->where);
6325       else
6326         {
6327           /* If one of the FORALL index variables doesn't appear in the
6328              assignment variable, then there could be a many-to-one
6329              assignment.  Emit a warning rather than an error because the
6330              mask could be resolving this problem.  */
6331           if (find_forall_index (code->expr, forall_index, 0) == FAILURE)
6332             gfc_warning ("The FORALL with index '%s' is not used on the "
6333                          "left side of the assignment at %L and so might "
6334                          "cause multiple assignment to this object",
6335                          var_expr[n]->symtree->name, &code->expr->where);
6336         }
6337     }
6338 }
6339
6340
6341 /* Resolve WHERE statement in FORALL construct.  */
6342
6343 static void
6344 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
6345                                   gfc_expr **var_expr)
6346 {
6347   gfc_code *cblock;
6348   gfc_code *cnext;
6349
6350   cblock = code->block;
6351   while (cblock)
6352     {
6353       /* the assignment statement of a WHERE statement, or the first
6354          statement in where-body-construct of a WHERE construct */
6355       cnext = cblock->next;
6356       while (cnext)
6357         {
6358           switch (cnext->op)
6359             {
6360             /* WHERE assignment statement */
6361             case EXEC_ASSIGN:
6362               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
6363               break;
6364   
6365             /* WHERE operator assignment statement */
6366             case EXEC_ASSIGN_CALL:
6367               resolve_call (cnext);
6368               if (!cnext->resolved_sym->attr.elemental)
6369                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
6370                           &cnext->ext.actual->expr->where);
6371               break;
6372
6373             /* WHERE or WHERE construct is part of a where-body-construct */
6374             case EXEC_WHERE:
6375               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
6376               break;
6377
6378             default:
6379               gfc_error ("Unsupported statement inside WHERE at %L",
6380                          &cnext->loc);
6381             }
6382           /* the next statement within the same where-body-construct */
6383           cnext = cnext->next;
6384         }
6385       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
6386       cblock = cblock->block;
6387     }
6388 }
6389
6390
6391 /* Traverse the FORALL body to check whether the following errors exist:
6392    1. For assignment, check if a many-to-one assignment happens.
6393    2. For WHERE statement, check the WHERE body to see if there is any
6394       many-to-one assignment.  */
6395
6396 static void
6397 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
6398 {
6399   gfc_code *c;
6400
6401   c = code->block->next;
6402   while (c)
6403     {
6404       switch (c->op)
6405         {
6406         case EXEC_ASSIGN:
6407         case EXEC_POINTER_ASSIGN:
6408           gfc_resolve_assign_in_forall (c, nvar, var_expr);
6409           break;
6410
6411         case EXEC_ASSIGN_CALL:
6412           resolve_call (c);
6413           break;
6414
6415         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
6416            there is no need to handle it here.  */
6417         case EXEC_FORALL:
6418           break;
6419         case EXEC_WHERE:
6420           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
6421           break;
6422         default:
6423           break;
6424         }
6425       /* The next statement in the FORALL body.  */
6426       c = c->next;
6427     }
6428 }
6429
6430
6431 /* Counts the number of iterators needed inside a forall construct, including
6432    nested forall constructs. This is used to allocate the needed memory 
6433    in gfc_resolve_forall.  */
6434
6435 static int 
6436 gfc_count_forall_iterators (gfc_code *code)
6437 {
6438   int max_iters, sub_iters, current_iters;
6439   gfc_forall_iterator *fa;
6440
6441   gcc_assert(code->op == EXEC_FORALL);
6442   max_iters = 0;
6443   current_iters = 0;
6444
6445   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
6446     current_iters ++;
6447   
6448   code = code->block->next;
6449
6450   while (code)
6451     {          
6452       if (code->op == EXEC_FORALL)
6453         {
6454           sub_iters = gfc_count_forall_iterators (code);
6455           if (sub_iters > max_iters)
6456             max_iters = sub_iters;
6457         }
6458       code = code->next;
6459     }
6460
6461   return current_iters + max_iters;
6462 }
6463
6464
6465 /* Given a FORALL construct, first resolve the FORALL iterator, then call
6466    gfc_resolve_forall_body to resolve the FORALL body.  */
6467
6468 static void
6469 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
6470 {
6471   static gfc_expr **var_expr;
6472   static int total_var = 0;
6473   static int nvar = 0;
6474   int old_nvar, tmp;
6475   gfc_forall_iterator *fa;
6476   int i;
6477
6478   old_nvar = nvar;
6479
6480   /* Start to resolve a FORALL construct   */
6481   if (forall_save == 0)
6482     {
6483       /* Count the total number of FORALL index in the nested FORALL
6484          construct in order to allocate the VAR_EXPR with proper size.  */
6485       total_var = gfc_count_forall_iterators (code);
6486
6487       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
6488       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
6489     }
6490
6491   /* The information about FORALL iterator, including FORALL index start, end
6492      and stride. The FORALL index can not appear in start, end or stride.  */
6493   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
6494     {
6495       /* Check if any outer FORALL index name is the same as the current
6496          one.  */
6497       for (i = 0; i < nvar; i++)
6498         {
6499           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
6500             {
6501               gfc_error ("An outer FORALL construct already has an index "
6502                          "with this name %L", &fa->var->where);
6503             }
6504         }
6505
6506       /* Record the current FORALL index.  */
6507       var_expr[nvar] = gfc_copy_expr (fa->var);
6508
6509       nvar++;
6510
6511       /* No memory leak.  */
6512       gcc_assert (nvar <= total_var);
6513     }
6514
6515   /* Resolve the FORALL body.  */
6516   gfc_resolve_forall_body (code, nvar, var_expr);
6517
6518   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
6519   gfc_resolve_blocks (code->block, ns);
6520
6521   tmp = nvar;
6522   nvar = old_nvar;
6523   /* Free only the VAR_EXPRs allocated in this frame.  */
6524   for (i = nvar; i < tmp; i++)
6525      gfc_free_expr (var_expr[i]);
6526
6527   if (nvar == 0)
6528     {
6529       /* We are in the outermost FORALL construct.  */
6530       gcc_assert (forall_save == 0);
6531
6532       /* VAR_EXPR is not needed any more.  */
6533       gfc_free (var_expr);
6534       total_var = 0;
6535     }
6536 }
6537
6538
6539 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL ,GOTO and
6540    DO code nodes.  */
6541
6542 static void resolve_code (gfc_code *, gfc_namespace *);
6543
6544 void
6545 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
6546 {
6547   gfc_try t;
6548
6549   for (; b; b = b->block)
6550     {
6551       t = gfc_resolve_expr (b->expr);
6552       if (gfc_resolve_expr (b->expr2) == FAILURE)
6553         t = FAILURE;
6554
6555       switch (b->op)
6556         {
6557         case EXEC_IF:
6558           if (t == SUCCESS && b->expr != NULL
6559               && (b->expr->ts.type != BT_LOGICAL || b->expr->rank != 0))
6560             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
6561                        &b->expr->where);
6562           break;
6563
6564         case EXEC_WHERE:
6565           if (t == SUCCESS
6566               && b->expr != NULL
6567               && (b->expr->ts.type != BT_LOGICAL || b->expr->rank == 0))
6568             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
6569                        &b->expr->where);
6570           break;
6571
6572         case EXEC_GOTO:
6573           resolve_branch (b->label, b);
6574           break;
6575
6576         case EXEC_SELECT:
6577         case EXEC_FORALL:
6578         case EXEC_DO:
6579         case EXEC_DO_WHILE:
6580         case EXEC_READ:
6581         case EXEC_WRITE:
6582         case EXEC_IOLENGTH:
6583         case EXEC_WAIT:
6584           break;
6585
6586         case EXEC_OMP_ATOMIC:
6587         case EXEC_OMP_CRITICAL:
6588         case EXEC_OMP_DO:
6589         case EXEC_OMP_MASTER:
6590         case EXEC_OMP_ORDERED:
6591         case EXEC_OMP_PARALLEL:
6592         case EXEC_OMP_PARALLEL_DO:
6593         case EXEC_OMP_PARALLEL_SECTIONS:
6594         case EXEC_OMP_PARALLEL_WORKSHARE:
6595         case EXEC_OMP_SECTIONS:
6596         case EXEC_OMP_SINGLE:
6597         case EXEC_OMP_TASK:
6598         case EXEC_OMP_TASKWAIT:
6599         case EXEC_OMP_WORKSHARE:
6600           break;
6601
6602         default:
6603           gfc_internal_error ("resolve_block(): Bad block type");
6604         }
6605
6606       resolve_code (b->next, ns);
6607     }
6608 }
6609
6610
6611 /* Does everything to resolve an ordinary assignment.  Returns true
6612    if this is an interface assignment.  */
6613 static bool
6614 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
6615 {
6616   bool rval = false;
6617   gfc_expr *lhs;
6618   gfc_expr *rhs;
6619   int llen = 0;
6620   int rlen = 0;
6621   int n;
6622   gfc_ref *ref;
6623
6624   if (gfc_extend_assign (code, ns) == SUCCESS)
6625     {
6626       lhs = code->ext.actual->expr;
6627       rhs = code->ext.actual->next->expr;
6628       if (gfc_pure (NULL) && !gfc_pure (code->symtree->n.sym))
6629         {
6630           gfc_error ("Subroutine '%s' called instead of assignment at "
6631                      "%L must be PURE", code->symtree->n.sym->name,
6632                      &code->loc);
6633           return rval;
6634         }
6635
6636       /* Make a temporary rhs when there is a default initializer
6637          and rhs is the same symbol as the lhs.  */
6638       if (rhs->expr_type == EXPR_VARIABLE
6639             && rhs->symtree->n.sym->ts.type == BT_DERIVED
6640             && has_default_initializer (rhs->symtree->n.sym->ts.derived)
6641             && (lhs->symtree->n.sym == rhs->symtree->n.sym))
6642         code->ext.actual->next->expr = gfc_get_parentheses (rhs);
6643
6644       return true;
6645     }
6646
6647   lhs = code->expr;
6648   rhs = code->expr2;
6649
6650   if (rhs->is_boz
6651       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
6652                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
6653                          &code->loc) == FAILURE)
6654     return false;
6655
6656   /* Handle the case of a BOZ literal on the RHS.  */
6657   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
6658     {
6659       int rc;
6660       if (gfc_option.warn_surprising)
6661         gfc_warning ("BOZ literal at %L is bitwise transferred "
6662                      "non-integer symbol '%s'", &code->loc,
6663                      lhs->symtree->n.sym->name);
6664
6665       if (!gfc_convert_boz (rhs, &lhs->ts))
6666         return false;
6667       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
6668         {
6669           if (rc == ARITH_UNDERFLOW)
6670             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
6671                        ". This check can be disabled with the option "
6672                        "-fno-range-check", &rhs->where);
6673           else if (rc == ARITH_OVERFLOW)
6674             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
6675                        ". This check can be disabled with the option "
6676                        "-fno-range-check", &rhs->where);
6677           else if (rc == ARITH_NAN)
6678             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
6679                        ". This check can be disabled with the option "
6680                        "-fno-range-check", &rhs->where);
6681           return false;
6682         }
6683     }
6684
6685
6686   if (lhs->ts.type == BT_CHARACTER
6687         && gfc_option.warn_character_truncation)
6688     {
6689       if (lhs->ts.cl != NULL
6690             && lhs->ts.cl->length != NULL
6691             && lhs->ts.cl->length->expr_type == EXPR_CONSTANT)
6692         llen = mpz_get_si (lhs->ts.cl->length->value.integer);
6693
6694       if (rhs->expr_type == EXPR_CONSTANT)
6695         rlen = rhs->value.character.length;
6696
6697       else if (rhs->ts.cl != NULL
6698                  && rhs->ts.cl->length != NULL
6699                  && rhs->ts.cl->length->expr_type == EXPR_CONSTANT)
6700         rlen = mpz_get_si (rhs->ts.cl->length->value.integer);
6701
6702       if (rlen && llen && rlen > llen)
6703         gfc_warning_now ("CHARACTER expression will be truncated "
6704                          "in assignment (%d/%d) at %L",
6705                          llen, rlen, &code->loc);
6706     }
6707
6708   /* Ensure that a vector index expression for the lvalue is evaluated
6709      to a temporary if the lvalue symbol is referenced in it.  */
6710   if (lhs->rank)
6711     {
6712       for (ref = lhs->ref; ref; ref= ref->next)
6713         if (ref->type == REF_ARRAY)
6714           {
6715             for (n = 0; n < ref->u.ar.dimen; n++)
6716               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
6717                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
6718                                            ref->u.ar.start[n]))
6719                 ref->u.ar.start[n]
6720                         = gfc_get_parentheses (ref->u.ar.start[n]);
6721           }
6722     }
6723
6724   if (gfc_pure (NULL))
6725     {
6726       if (gfc_impure_variable (lhs->symtree->n.sym))
6727         {
6728           gfc_error ("Cannot assign to variable '%s' in PURE "
6729                      "procedure at %L",
6730                       lhs->symtree->n.sym->name,
6731                       &lhs->where);
6732           return rval;
6733         }
6734
6735       if (lhs->ts.type == BT_DERIVED
6736             && lhs->expr_type == EXPR_VARIABLE
6737             && lhs->ts.derived->attr.pointer_comp
6738             && gfc_impure_variable (rhs->symtree->n.sym))
6739         {
6740           gfc_error ("The impure variable at %L is assigned to "
6741                      "a derived type variable with a POINTER "
6742                      "component in a PURE procedure (12.6)",
6743                      &rhs->where);
6744           return rval;
6745         }
6746     }
6747
6748   gfc_check_assign (lhs, rhs, 1);
6749   return false;
6750 }
6751
6752 /* Given a block of code, recursively resolve everything pointed to by this
6753    code block.  */
6754
6755 static void
6756 resolve_code (gfc_code *code, gfc_namespace *ns)
6757 {
6758   int omp_workshare_save;
6759   int forall_save;
6760   code_stack frame;
6761   gfc_try t;
6762
6763   frame.prev = cs_base;
6764   frame.head = code;
6765   cs_base = &frame;
6766
6767   find_reachable_labels (code);
6768
6769   for (; code; code = code->next)
6770     {
6771       frame.current = code;
6772       forall_save = forall_flag;
6773
6774       if (code->op == EXEC_FORALL)
6775         {
6776           forall_flag = 1;
6777           gfc_resolve_forall (code, ns, forall_save);
6778           forall_flag = 2;
6779         }
6780       else if (code->block)
6781         {
6782           omp_workshare_save = -1;
6783           switch (code->op)
6784             {
6785             case EXEC_OMP_PARALLEL_WORKSHARE:
6786               omp_workshare_save = omp_workshare_flag;
6787               omp_workshare_flag = 1;
6788               gfc_resolve_omp_parallel_blocks (code, ns);
6789               break;
6790             case EXEC_OMP_PARALLEL:
6791             case EXEC_OMP_PARALLEL_DO:
6792             case EXEC_OMP_PARALLEL_SECTIONS:
6793             case EXEC_OMP_TASK:
6794               omp_workshare_save = omp_workshare_flag;
6795               omp_workshare_flag = 0;
6796               gfc_resolve_omp_parallel_blocks (code, ns);
6797               break;
6798             case EXEC_OMP_DO:
6799               gfc_resolve_omp_do_blocks (code, ns);
6800               break;
6801             case EXEC_OMP_WORKSHARE:
6802               omp_workshare_save = omp_workshare_flag;
6803               omp_workshare_flag = 1;
6804               /* FALLTHROUGH */
6805             default:
6806               gfc_resolve_blocks (code->block, ns);
6807               break;
6808             }
6809
6810           if (omp_workshare_save != -1)
6811             omp_workshare_flag = omp_workshare_save;
6812         }
6813
6814       t = SUCCESS;
6815       if (code->op != EXEC_COMPCALL)
6816         t = gfc_resolve_expr (code->expr);
6817       forall_flag = forall_save;
6818
6819       if (gfc_resolve_expr (code->expr2) == FAILURE)
6820         t = FAILURE;
6821
6822       switch (code->op)
6823         {
6824         case EXEC_NOP:
6825         case EXEC_END_BLOCK:
6826         case EXEC_CYCLE:
6827         case EXEC_PAUSE:
6828         case EXEC_STOP:
6829         case EXEC_EXIT:
6830         case EXEC_CONTINUE:
6831         case EXEC_DT_END:
6832           break;
6833
6834         case EXEC_ENTRY:
6835           /* Keep track of which entry we are up to.  */
6836           current_entry_id = code->ext.entry->id;
6837           break;
6838
6839         case EXEC_WHERE:
6840           resolve_where (code, NULL);
6841           break;
6842
6843         case EXEC_GOTO:
6844           if (code->expr != NULL)
6845             {
6846               if (code->expr->ts.type != BT_INTEGER)
6847                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
6848                            "INTEGER variable", &code->expr->where);
6849               else if (code->expr->symtree->n.sym->attr.assign != 1)
6850                 gfc_error ("Variable '%s' has not been assigned a target "
6851                            "label at %L", code->expr->symtree->n.sym->name,
6852                            &code->expr->where);
6853             }
6854           else
6855             resolve_branch (code->label, code);
6856           break;
6857
6858         case EXEC_RETURN:
6859           if (code->expr != NULL
6860                 && (code->expr->ts.type != BT_INTEGER || code->expr->rank))
6861             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
6862                        "INTEGER return specifier", &code->expr->where);
6863           break;
6864
6865         case EXEC_INIT_ASSIGN:
6866           break;
6867
6868         case EXEC_ASSIGN:
6869           if (t == FAILURE)
6870             break;
6871
6872           if (resolve_ordinary_assign (code, ns))
6873             goto call;
6874
6875           break;
6876
6877         case EXEC_LABEL_ASSIGN:
6878           if (code->label->defined == ST_LABEL_UNKNOWN)
6879             gfc_error ("Label %d referenced at %L is never defined",
6880                        code->label->value, &code->label->where);
6881           if (t == SUCCESS
6882               && (code->expr->expr_type != EXPR_VARIABLE
6883                   || code->expr->symtree->n.sym->ts.type != BT_INTEGER
6884                   || code->expr->symtree->n.sym->ts.kind
6885                      != gfc_default_integer_kind
6886                   || code->expr->symtree->n.sym->as != NULL))
6887             gfc_error ("ASSIGN statement at %L requires a scalar "
6888                        "default INTEGER variable", &code->expr->where);
6889           break;
6890
6891         case EXEC_POINTER_ASSIGN:
6892           if (t == FAILURE)
6893             break;
6894
6895           gfc_check_pointer_assign (code->expr, code->expr2);
6896           break;
6897
6898         case EXEC_ARITHMETIC_IF:
6899           if (t == SUCCESS
6900               && code->expr->ts.type != BT_INTEGER
6901               && code->expr->ts.type != BT_REAL)
6902             gfc_error ("Arithmetic IF statement at %L requires a numeric "
6903                        "expression", &code->expr->where);
6904
6905           resolve_branch (code->label, code);
6906           resolve_branch (code->label2, code);
6907           resolve_branch (code->label3, code);
6908           break;
6909
6910         case EXEC_IF:
6911           if (t == SUCCESS && code->expr != NULL
6912               && (code->expr->ts.type != BT_LOGICAL
6913                   || code->expr->rank != 0))
6914             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
6915                        &code->expr->where);
6916           break;
6917
6918         case EXEC_CALL:
6919         call:
6920           resolve_call (code);
6921           break;
6922
6923         case EXEC_COMPCALL:
6924           resolve_typebound_call (code);
6925           break;
6926
6927         case EXEC_SELECT:
6928           /* Select is complicated. Also, a SELECT construct could be
6929              a transformed computed GOTO.  */
6930           resolve_select (code);
6931           break;
6932
6933         case EXEC_DO:
6934           if (code->ext.iterator != NULL)
6935             {
6936               gfc_iterator *iter = code->ext.iterator;
6937               if (gfc_resolve_iterator (iter, true) != FAILURE)
6938                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
6939             }
6940           break;
6941
6942         case EXEC_DO_WHILE:
6943           if (code->expr == NULL)
6944             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
6945           if (t == SUCCESS
6946               && (code->expr->rank != 0
6947                   || code->expr->ts.type != BT_LOGICAL))
6948             gfc_error ("Exit condition of DO WHILE loop at %L must be "
6949                        "a scalar LOGICAL expression", &code->expr->where);
6950           break;
6951
6952         case EXEC_ALLOCATE:
6953           if (t == SUCCESS)
6954             resolve_allocate_deallocate (code, "ALLOCATE");
6955
6956           break;
6957
6958         case EXEC_DEALLOCATE:
6959           if (t == SUCCESS)
6960             resolve_allocate_deallocate (code, "DEALLOCATE");
6961
6962           break;
6963
6964         case EXEC_OPEN:
6965           if (gfc_resolve_open (code->ext.open) == FAILURE)
6966             break;
6967
6968           resolve_branch (code->ext.open->err, code);
6969           break;
6970
6971         case EXEC_CLOSE:
6972           if (gfc_resolve_close (code->ext.close) == FAILURE)
6973             break;
6974
6975           resolve_branch (code->ext.close->err, code);
6976           break;
6977
6978         case EXEC_BACKSPACE:
6979         case EXEC_ENDFILE:
6980         case EXEC_REWIND:
6981         case EXEC_FLUSH:
6982           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
6983             break;
6984
6985           resolve_branch (code->ext.filepos->err, code);
6986           break;
6987
6988         case EXEC_INQUIRE:
6989           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
6990               break;
6991
6992           resolve_branch (code->ext.inquire->err, code);
6993           break;
6994
6995         case EXEC_IOLENGTH:
6996           gcc_assert (code->ext.inquire != NULL);
6997           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
6998             break;
6999
7000           resolve_branch (code->ext.inquire->err, code);
7001           break;
7002
7003         case EXEC_WAIT:
7004           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
7005             break;
7006
7007           resolve_branch (code->ext.wait->err, code);
7008           resolve_branch (code->ext.wait->end, code);
7009           resolve_branch (code->ext.wait->eor, code);
7010           break;
7011
7012         case EXEC_READ:
7013         case EXEC_WRITE:
7014           if (gfc_resolve_dt (code->ext.dt) == FAILURE)
7015             break;
7016
7017           resolve_branch (code->ext.dt->err, code);
7018           resolve_branch (code->ext.dt->end, code);
7019           resolve_branch (code->ext.dt->eor, code);
7020           break;
7021
7022         case EXEC_TRANSFER:
7023           resolve_transfer (code);
7024           break;
7025
7026         case EXEC_FORALL:
7027           resolve_forall_iterators (code->ext.forall_iterator);
7028
7029           if (code->expr != NULL && code->expr->ts.type != BT_LOGICAL)
7030             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
7031                        "expression", &code->expr->where);
7032           break;
7033
7034         case EXEC_OMP_ATOMIC:
7035         case EXEC_OMP_BARRIER:
7036         case EXEC_OMP_CRITICAL:
7037         case EXEC_OMP_FLUSH:
7038         case EXEC_OMP_DO:
7039         case EXEC_OMP_MASTER:
7040         case EXEC_OMP_ORDERED:
7041         case EXEC_OMP_SECTIONS:
7042         case EXEC_OMP_SINGLE:
7043         case EXEC_OMP_TASKWAIT:
7044         case EXEC_OMP_WORKSHARE:
7045           gfc_resolve_omp_directive (code, ns);
7046           break;
7047
7048         case EXEC_OMP_PARALLEL:
7049         case EXEC_OMP_PARALLEL_DO:
7050         case EXEC_OMP_PARALLEL_SECTIONS:
7051         case EXEC_OMP_PARALLEL_WORKSHARE:
7052         case EXEC_OMP_TASK:
7053           omp_workshare_save = omp_workshare_flag;
7054           omp_workshare_flag = 0;
7055           gfc_resolve_omp_directive (code, ns);
7056           omp_workshare_flag = omp_workshare_save;
7057           break;
7058
7059         default:
7060           gfc_internal_error ("resolve_code(): Bad statement code");
7061         }
7062     }
7063
7064   cs_base = frame.prev;
7065 }
7066
7067
7068 /* Resolve initial values and make sure they are compatible with
7069    the variable.  */
7070
7071 static void
7072 resolve_values (gfc_symbol *sym)
7073 {
7074   if (sym->value == NULL)
7075     return;
7076
7077   if (gfc_resolve_expr (sym->value) == FAILURE)
7078     return;
7079
7080   gfc_check_assign_symbol (sym, sym->value);
7081 }
7082
7083
7084 /* Verify the binding labels for common blocks that are BIND(C).  The label
7085    for a BIND(C) common block must be identical in all scoping units in which
7086    the common block is declared.  Further, the binding label can not collide
7087    with any other global entity in the program.  */
7088
7089 static void
7090 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
7091 {
7092   if (comm_block_tree->n.common->is_bind_c == 1)
7093     {
7094       gfc_gsymbol *binding_label_gsym;
7095       gfc_gsymbol *comm_name_gsym;
7096
7097       /* See if a global symbol exists by the common block's name.  It may
7098          be NULL if the common block is use-associated.  */
7099       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
7100                                          comm_block_tree->n.common->name);
7101       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
7102         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
7103                    "with the global entity '%s' at %L",
7104                    comm_block_tree->n.common->binding_label,
7105                    comm_block_tree->n.common->name,
7106                    &(comm_block_tree->n.common->where),
7107                    comm_name_gsym->name, &(comm_name_gsym->where));
7108       else if (comm_name_gsym != NULL
7109                && strcmp (comm_name_gsym->name,
7110                           comm_block_tree->n.common->name) == 0)
7111         {
7112           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
7113              as expected.  */
7114           if (comm_name_gsym->binding_label == NULL)
7115             /* No binding label for common block stored yet; save this one.  */
7116             comm_name_gsym->binding_label =
7117               comm_block_tree->n.common->binding_label;
7118           else
7119             if (strcmp (comm_name_gsym->binding_label,
7120                         comm_block_tree->n.common->binding_label) != 0)
7121               {
7122                 /* Common block names match but binding labels do not.  */
7123                 gfc_error ("Binding label '%s' for common block '%s' at %L "
7124                            "does not match the binding label '%s' for common "
7125                            "block '%s' at %L",
7126                            comm_block_tree->n.common->binding_label,
7127                            comm_block_tree->n.common->name,
7128                            &(comm_block_tree->n.common->where),
7129                            comm_name_gsym->binding_label,
7130                            comm_name_gsym->name,
7131                            &(comm_name_gsym->where));
7132                 return;
7133               }
7134         }
7135
7136       /* There is no binding label (NAME="") so we have nothing further to
7137          check and nothing to add as a global symbol for the label.  */
7138       if (comm_block_tree->n.common->binding_label[0] == '\0' )
7139         return;
7140       
7141       binding_label_gsym =
7142         gfc_find_gsymbol (gfc_gsym_root,
7143                           comm_block_tree->n.common->binding_label);
7144       if (binding_label_gsym == NULL)
7145         {
7146           /* Need to make a global symbol for the binding label to prevent
7147              it from colliding with another.  */
7148           binding_label_gsym =
7149             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
7150           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
7151           binding_label_gsym->type = GSYM_COMMON;
7152         }
7153       else
7154         {
7155           /* If comm_name_gsym is NULL, the name common block is use
7156              associated and the name could be colliding.  */
7157           if (binding_label_gsym->type != GSYM_COMMON)
7158             gfc_error ("Binding label '%s' for common block '%s' at %L "
7159                        "collides with the global entity '%s' at %L",
7160                        comm_block_tree->n.common->binding_label,
7161                        comm_block_tree->n.common->name,
7162                        &(comm_block_tree->n.common->where),
7163                        binding_label_gsym->name,
7164                        &(binding_label_gsym->where));
7165           else if (comm_name_gsym != NULL
7166                    && (strcmp (binding_label_gsym->name,
7167                                comm_name_gsym->binding_label) != 0)
7168                    && (strcmp (binding_label_gsym->sym_name,
7169                                comm_name_gsym->name) != 0))
7170             gfc_error ("Binding label '%s' for common block '%s' at %L "
7171                        "collides with global entity '%s' at %L",
7172                        binding_label_gsym->name, binding_label_gsym->sym_name,
7173                        &(comm_block_tree->n.common->where),
7174                        comm_name_gsym->name, &(comm_name_gsym->where));
7175         }
7176     }
7177   
7178   return;
7179 }
7180
7181
7182 /* Verify any BIND(C) derived types in the namespace so we can report errors
7183    for them once, rather than for each variable declared of that type.  */
7184
7185 static void
7186 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
7187 {
7188   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
7189       && derived_sym->attr.is_bind_c == 1)
7190     verify_bind_c_derived_type (derived_sym);
7191   
7192   return;
7193 }
7194
7195
7196 /* Verify that any binding labels used in a given namespace do not collide 
7197    with the names or binding labels of any global symbols.  */
7198
7199 static void
7200 gfc_verify_binding_labels (gfc_symbol *sym)
7201 {
7202   int has_error = 0;
7203   
7204   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
7205       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
7206     {
7207       gfc_gsymbol *bind_c_sym;
7208
7209       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
7210       if (bind_c_sym != NULL 
7211           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
7212         {
7213           if (sym->attr.if_source == IFSRC_DECL 
7214               && (bind_c_sym->type != GSYM_SUBROUTINE 
7215                   && bind_c_sym->type != GSYM_FUNCTION) 
7216               && ((sym->attr.contained == 1 
7217                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
7218                   || (sym->attr.use_assoc == 1 
7219                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
7220             {
7221               /* Make sure global procedures don't collide with anything.  */
7222               gfc_error ("Binding label '%s' at %L collides with the global "
7223                          "entity '%s' at %L", sym->binding_label,
7224                          &(sym->declared_at), bind_c_sym->name,
7225                          &(bind_c_sym->where));
7226               has_error = 1;
7227             }
7228           else if (sym->attr.contained == 0 
7229                    && (sym->attr.if_source == IFSRC_IFBODY 
7230                        && sym->attr.flavor == FL_PROCEDURE) 
7231                    && (bind_c_sym->sym_name != NULL 
7232                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
7233             {
7234               /* Make sure procedures in interface bodies don't collide.  */
7235               gfc_error ("Binding label '%s' in interface body at %L collides "
7236                          "with the global entity '%s' at %L",
7237                          sym->binding_label,
7238                          &(sym->declared_at), bind_c_sym->name,
7239                          &(bind_c_sym->where));
7240               has_error = 1;
7241             }
7242           else if (sym->attr.contained == 0 
7243                    && sym->attr.if_source == IFSRC_UNKNOWN)
7244             if ((sym->attr.use_assoc && bind_c_sym->mod_name
7245                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
7246                 || sym->attr.use_assoc == 0)
7247               {
7248                 gfc_error ("Binding label '%s' at %L collides with global "
7249                            "entity '%s' at %L", sym->binding_label,
7250                            &(sym->declared_at), bind_c_sym->name,
7251                            &(bind_c_sym->where));
7252                 has_error = 1;
7253               }
7254
7255           if (has_error != 0)
7256             /* Clear the binding label to prevent checking multiple times.  */
7257             sym->binding_label[0] = '\0';
7258         }
7259       else if (bind_c_sym == NULL)
7260         {
7261           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
7262           bind_c_sym->where = sym->declared_at;
7263           bind_c_sym->sym_name = sym->name;
7264
7265           if (sym->attr.use_assoc == 1)
7266             bind_c_sym->mod_name = sym->module;
7267           else
7268             if (sym->ns->proc_name != NULL)
7269               bind_c_sym->mod_name = sym->ns->proc_name->name;
7270
7271           if (sym->attr.contained == 0)
7272             {
7273               if (sym->attr.subroutine)
7274                 bind_c_sym->type = GSYM_SUBROUTINE;
7275               else if (sym->attr.function)
7276                 bind_c_sym->type = GSYM_FUNCTION;
7277             }
7278         }
7279     }
7280   return;
7281 }
7282
7283
7284 /* Resolve an index expression.  */
7285
7286 static gfc_try
7287 resolve_index_expr (gfc_expr *e)
7288 {
7289   if (gfc_resolve_expr (e) == FAILURE)
7290     return FAILURE;
7291
7292   if (gfc_simplify_expr (e, 0) == FAILURE)
7293     return FAILURE;
7294
7295   if (gfc_specification_expr (e) == FAILURE)
7296     return FAILURE;
7297
7298   return SUCCESS;
7299 }
7300
7301 /* Resolve a charlen structure.  */
7302
7303 static gfc_try
7304 resolve_charlen (gfc_charlen *cl)
7305 {
7306   int i;
7307
7308   if (cl->resolved)
7309     return SUCCESS;
7310
7311   cl->resolved = 1;
7312
7313   specification_expr = 1;
7314
7315   if (resolve_index_expr (cl->length) == FAILURE)
7316     {
7317       specification_expr = 0;
7318       return FAILURE;
7319     }
7320
7321   /* "If the character length parameter value evaluates to a negative
7322      value, the length of character entities declared is zero."  */
7323   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
7324     {
7325       gfc_warning_now ("CHARACTER variable has zero length at %L",
7326                        &cl->length->where);
7327       gfc_replace_expr (cl->length, gfc_int_expr (0));
7328     }
7329
7330   return SUCCESS;
7331 }
7332
7333
7334 /* Test for non-constant shape arrays.  */
7335
7336 static bool
7337 is_non_constant_shape_array (gfc_symbol *sym)
7338 {
7339   gfc_expr *e;
7340   int i;
7341   bool not_constant;
7342
7343   not_constant = false;
7344   if (sym->as != NULL)
7345     {
7346       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
7347          has not been simplified; parameter array references.  Do the
7348          simplification now.  */
7349       for (i = 0; i < sym->as->rank; i++)
7350         {
7351           e = sym->as->lower[i];
7352           if (e && (resolve_index_expr (e) == FAILURE
7353                     || !gfc_is_constant_expr (e)))
7354             not_constant = true;
7355
7356           e = sym->as->upper[i];
7357           if (e && (resolve_index_expr (e) == FAILURE
7358                     || !gfc_is_constant_expr (e)))
7359             not_constant = true;
7360         }
7361     }
7362   return not_constant;
7363 }
7364
7365 /* Given a symbol and an initialization expression, add code to initialize
7366    the symbol to the function entry.  */
7367 static void
7368 build_init_assign (gfc_symbol *sym, gfc_expr *init)
7369 {
7370   gfc_expr *lval;
7371   gfc_code *init_st;
7372   gfc_namespace *ns = sym->ns;
7373
7374   /* Search for the function namespace if this is a contained
7375      function without an explicit result.  */
7376   if (sym->attr.function && sym == sym->result
7377       && sym->name != sym->ns->proc_name->name)
7378     {
7379       ns = ns->contained;
7380       for (;ns; ns = ns->sibling)
7381         if (strcmp (ns->proc_name->name, sym->name) == 0)
7382           break;
7383     }
7384
7385   if (ns == NULL)
7386     {
7387       gfc_free_expr (init);
7388       return;
7389     }
7390
7391   /* Build an l-value expression for the result.  */
7392   lval = gfc_lval_expr_from_sym (sym);
7393
7394   /* Add the code at scope entry.  */
7395   init_st = gfc_get_code ();
7396   init_st->next = ns->code;
7397   ns->code = init_st;
7398
7399   /* Assign the default initializer to the l-value.  */
7400   init_st->loc = sym->declared_at;
7401   init_st->op = EXEC_INIT_ASSIGN;
7402   init_st->expr = lval;
7403   init_st->expr2 = init;
7404 }
7405
7406 /* Assign the default initializer to a derived type variable or result.  */
7407
7408 static void
7409 apply_default_init (gfc_symbol *sym)
7410 {
7411   gfc_expr *init = NULL;
7412
7413   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
7414     return;
7415
7416   if (sym->ts.type == BT_DERIVED && sym->ts.derived)
7417     init = gfc_default_initializer (&sym->ts);
7418
7419   if (init == NULL)
7420     return;
7421
7422   build_init_assign (sym, init);
7423 }
7424
7425 /* Build an initializer for a local integer, real, complex, logical, or
7426    character variable, based on the command line flags finit-local-zero,
7427    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
7428    null if the symbol should not have a default initialization.  */
7429 static gfc_expr *
7430 build_default_init_expr (gfc_symbol *sym)
7431 {
7432   int char_len;
7433   gfc_expr *init_expr;
7434   int i;
7435
7436   /* These symbols should never have a default initialization.  */
7437   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
7438       || sym->attr.external
7439       || sym->attr.dummy
7440       || sym->attr.pointer
7441       || sym->attr.in_equivalence
7442       || sym->attr.in_common
7443       || sym->attr.data
7444       || sym->module
7445       || sym->attr.cray_pointee
7446       || sym->attr.cray_pointer)
7447     return NULL;
7448
7449   /* Now we'll try to build an initializer expression.  */
7450   init_expr = gfc_get_expr ();
7451   init_expr->expr_type = EXPR_CONSTANT;
7452   init_expr->ts.type = sym->ts.type;
7453   init_expr->ts.kind = sym->ts.kind;
7454   init_expr->where = sym->declared_at;
7455   
7456   /* We will only initialize integers, reals, complex, logicals, and
7457      characters, and only if the corresponding command-line flags
7458      were set.  Otherwise, we free init_expr and return null.  */
7459   switch (sym->ts.type)
7460     {    
7461     case BT_INTEGER:
7462       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
7463         mpz_init_set_si (init_expr->value.integer, 
7464                          gfc_option.flag_init_integer_value);
7465       else
7466         {
7467           gfc_free_expr (init_expr);
7468           init_expr = NULL;
7469         }
7470       break;
7471
7472     case BT_REAL:
7473       mpfr_init (init_expr->value.real);
7474       switch (gfc_option.flag_init_real)
7475         {
7476         case GFC_INIT_REAL_SNAN:
7477           init_expr->is_snan = 1;
7478           /* Fall through.  */
7479         case GFC_INIT_REAL_NAN:
7480           mpfr_set_nan (init_expr->value.real);
7481           break;
7482
7483         case GFC_INIT_REAL_INF:
7484           mpfr_set_inf (init_expr->value.real, 1);
7485           break;
7486
7487         case GFC_INIT_REAL_NEG_INF:
7488           mpfr_set_inf (init_expr->value.real, -1);
7489           break;
7490
7491         case GFC_INIT_REAL_ZERO:
7492           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
7493           break;
7494
7495         default:
7496           gfc_free_expr (init_expr);
7497           init_expr = NULL;
7498           break;
7499         }
7500       break;
7501           
7502     case BT_COMPLEX:
7503       mpfr_init (init_expr->value.complex.r);
7504       mpfr_init (init_expr->value.complex.i);
7505       switch (gfc_option.flag_init_real)
7506         {
7507         case GFC_INIT_REAL_SNAN:
7508           init_expr->is_snan = 1;
7509           /* Fall through.  */
7510         case GFC_INIT_REAL_NAN:
7511           mpfr_set_nan (init_expr->value.complex.r);
7512           mpfr_set_nan (init_expr->value.complex.i);
7513           break;
7514
7515         case GFC_INIT_REAL_INF:
7516           mpfr_set_inf (init_expr->value.complex.r, 1);
7517           mpfr_set_inf (init_expr->value.complex.i, 1);
7518           break;
7519
7520         case GFC_INIT_REAL_NEG_INF:
7521           mpfr_set_inf (init_expr->value.complex.r, -1);
7522           mpfr_set_inf (init_expr->value.complex.i, -1);
7523           break;
7524
7525         case GFC_INIT_REAL_ZERO:
7526           mpfr_set_ui (init_expr->value.complex.r, 0.0, GFC_RND_MODE);
7527           mpfr_set_ui (init_expr->value.complex.i, 0.0, GFC_RND_MODE);
7528           break;
7529
7530         default:
7531           gfc_free_expr (init_expr);
7532           init_expr = NULL;
7533           break;
7534         }
7535       break;
7536           
7537     case BT_LOGICAL:
7538       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
7539         init_expr->value.logical = 0;
7540       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
7541         init_expr->value.logical = 1;
7542       else
7543         {
7544           gfc_free_expr (init_expr);
7545           init_expr = NULL;
7546         }
7547       break;
7548           
7549     case BT_CHARACTER:
7550       /* For characters, the length must be constant in order to 
7551          create a default initializer.  */
7552       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
7553           && sym->ts.cl->length
7554           && sym->ts.cl->length->expr_type == EXPR_CONSTANT)
7555         {
7556           char_len = mpz_get_si (sym->ts.cl->length->value.integer);
7557           init_expr->value.character.length = char_len;
7558           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
7559           for (i = 0; i < char_len; i++)
7560             init_expr->value.character.string[i]
7561               = (unsigned char) gfc_option.flag_init_character_value;
7562         }
7563       else
7564         {
7565           gfc_free_expr (init_expr);
7566           init_expr = NULL;
7567         }
7568       break;
7569           
7570     default:
7571      gfc_free_expr (init_expr);
7572      init_expr = NULL;
7573     }
7574   return init_expr;
7575 }
7576
7577 /* Add an initialization expression to a local variable.  */
7578 static void
7579 apply_default_init_local (gfc_symbol *sym)
7580 {
7581   gfc_expr *init = NULL;
7582
7583   /* The symbol should be a variable or a function return value.  */
7584   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
7585       || (sym->attr.function && sym->result != sym))
7586     return;
7587
7588   /* Try to build the initializer expression.  If we can't initialize
7589      this symbol, then init will be NULL.  */
7590   init = build_default_init_expr (sym);
7591   if (init == NULL)
7592     return;
7593
7594   /* For saved variables, we don't want to add an initializer at 
7595      function entry, so we just add a static initializer.  */
7596   if (sym->attr.save || sym->ns->save_all)
7597     {
7598       /* Don't clobber an existing initializer!  */
7599       gcc_assert (sym->value == NULL);
7600       sym->value = init;
7601       return;
7602     }
7603
7604   build_init_assign (sym, init);
7605 }
7606
7607 /* Resolution of common features of flavors variable and procedure.  */
7608
7609 static gfc_try
7610 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
7611 {
7612   /* Constraints on deferred shape variable.  */
7613   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
7614     {
7615       if (sym->attr.allocatable)
7616         {
7617           if (sym->attr.dimension)
7618             gfc_error ("Allocatable array '%s' at %L must have "
7619                        "a deferred shape", sym->name, &sym->declared_at);
7620           else
7621             gfc_error ("Scalar object '%s' at %L may not be ALLOCATABLE",
7622                        sym->name, &sym->declared_at);
7623             return FAILURE;
7624         }
7625
7626       if (sym->attr.pointer && sym->attr.dimension)
7627         {
7628           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
7629                      sym->name, &sym->declared_at);
7630           return FAILURE;
7631         }
7632
7633     }
7634   else
7635     {
7636       if (!mp_flag && !sym->attr.allocatable
7637           && !sym->attr.pointer && !sym->attr.dummy)
7638         {
7639           gfc_error ("Array '%s' at %L cannot have a deferred shape",
7640                      sym->name, &sym->declared_at);
7641           return FAILURE;
7642          }
7643     }
7644   return SUCCESS;
7645 }
7646
7647
7648 /* Additional checks for symbols with flavor variable and derived
7649    type.  To be called from resolve_fl_variable.  */
7650
7651 static gfc_try
7652 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
7653 {
7654   gcc_assert (sym->ts.type == BT_DERIVED);
7655
7656   /* Check to see if a derived type is blocked from being host
7657      associated by the presence of another class I symbol in the same
7658      namespace.  14.6.1.3 of the standard and the discussion on
7659      comp.lang.fortran.  */
7660   if (sym->ns != sym->ts.derived->ns
7661       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
7662     {
7663       gfc_symbol *s;
7664       gfc_find_symbol (sym->ts.derived->name, sym->ns, 0, &s);
7665       if (s && s->attr.flavor != FL_DERIVED)
7666         {
7667           gfc_error ("The type '%s' cannot be host associated at %L "
7668                      "because it is blocked by an incompatible object "
7669                      "of the same name declared at %L",
7670                      sym->ts.derived->name, &sym->declared_at,
7671                      &s->declared_at);
7672           return FAILURE;
7673         }
7674     }
7675
7676   /* 4th constraint in section 11.3: "If an object of a type for which
7677      component-initialization is specified (R429) appears in the
7678      specification-part of a module and does not have the ALLOCATABLE
7679      or POINTER attribute, the object shall have the SAVE attribute."
7680
7681      The check for initializers is performed with
7682      has_default_initializer because gfc_default_initializer generates
7683      a hidden default for allocatable components.  */
7684   if (!(sym->value || no_init_flag) && sym->ns->proc_name
7685       && sym->ns->proc_name->attr.flavor == FL_MODULE
7686       && !sym->ns->save_all && !sym->attr.save
7687       && !sym->attr.pointer && !sym->attr.allocatable
7688       && has_default_initializer (sym->ts.derived))
7689     {
7690       gfc_error("Object '%s' at %L must have the SAVE attribute for "
7691                 "default initialization of a component",
7692                 sym->name, &sym->declared_at);
7693       return FAILURE;
7694     }
7695
7696   /* Assign default initializer.  */
7697   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
7698       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
7699     {
7700       sym->value = gfc_default_initializer (&sym->ts);
7701     }
7702
7703   return SUCCESS;
7704 }
7705
7706
7707 /* Resolve symbols with flavor variable.  */
7708
7709 static gfc_try
7710 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
7711 {
7712   int no_init_flag, automatic_flag;
7713   gfc_expr *e;
7714   const char *auto_save_msg;
7715
7716   auto_save_msg = "Automatic object '%s' at %L cannot have the "
7717                   "SAVE attribute";
7718
7719   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
7720     return FAILURE;
7721
7722   /* Set this flag to check that variables are parameters of all entries.
7723      This check is effected by the call to gfc_resolve_expr through
7724      is_non_constant_shape_array.  */
7725   specification_expr = 1;
7726
7727   if (sym->ns->proc_name
7728       && (sym->ns->proc_name->attr.flavor == FL_MODULE
7729           || sym->ns->proc_name->attr.is_main_program)
7730       && !sym->attr.use_assoc
7731       && !sym->attr.allocatable
7732       && !sym->attr.pointer
7733       && is_non_constant_shape_array (sym))
7734     {
7735       /* The shape of a main program or module array needs to be
7736          constant.  */
7737       gfc_error ("The module or main program array '%s' at %L must "
7738                  "have constant shape", sym->name, &sym->declared_at);
7739       specification_expr = 0;
7740       return FAILURE;
7741     }
7742
7743   if (sym->ts.type == BT_CHARACTER)
7744     {
7745       /* Make sure that character string variables with assumed length are
7746          dummy arguments.  */
7747       e = sym->ts.cl->length;
7748       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
7749         {
7750           gfc_error ("Entity with assumed character length at %L must be a "
7751                      "dummy argument or a PARAMETER", &sym->declared_at);
7752           return FAILURE;
7753         }
7754
7755       if (e && sym->attr.save && !gfc_is_constant_expr (e))
7756         {
7757           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
7758           return FAILURE;
7759         }
7760
7761       if (!gfc_is_constant_expr (e)
7762           && !(e->expr_type == EXPR_VARIABLE
7763                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
7764           && sym->ns->proc_name
7765           && (sym->ns->proc_name->attr.flavor == FL_MODULE
7766               || sym->ns->proc_name->attr.is_main_program)
7767           && !sym->attr.use_assoc)
7768         {
7769           gfc_error ("'%s' at %L must have constant character length "
7770                      "in this context", sym->name, &sym->declared_at);
7771           return FAILURE;
7772         }
7773     }
7774
7775   if (sym->value == NULL && sym->attr.referenced)
7776     apply_default_init_local (sym); /* Try to apply a default initialization.  */
7777
7778   /* Determine if the symbol may not have an initializer.  */
7779   no_init_flag = automatic_flag = 0;
7780   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
7781       || sym->attr.intrinsic || sym->attr.result)
7782     no_init_flag = 1;
7783   else if (sym->attr.dimension && !sym->attr.pointer
7784            && is_non_constant_shape_array (sym))
7785     {
7786       no_init_flag = automatic_flag = 1;
7787
7788       /* Also, they must not have the SAVE attribute.
7789          SAVE_IMPLICIT is checked below.  */
7790       if (sym->attr.save == SAVE_EXPLICIT)
7791         {
7792           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
7793           return FAILURE;
7794         }
7795     }
7796
7797   /* Ensure that any initializer is simplified.  */
7798   if (sym->value)
7799     gfc_simplify_expr (sym->value, 1);
7800
7801   /* Reject illegal initializers.  */
7802   if (!sym->mark && sym->value)
7803     {
7804       if (sym->attr.allocatable)
7805         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
7806                    sym->name, &sym->declared_at);
7807       else if (sym->attr.external)
7808         gfc_error ("External '%s' at %L cannot have an initializer",
7809                    sym->name, &sym->declared_at);
7810       else if (sym->attr.dummy
7811         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
7812         gfc_error ("Dummy '%s' at %L cannot have an initializer",
7813                    sym->name, &sym->declared_at);
7814       else if (sym->attr.intrinsic)
7815         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
7816                    sym->name, &sym->declared_at);
7817       else if (sym->attr.result)
7818         gfc_error ("Function result '%s' at %L cannot have an initializer",
7819                    sym->name, &sym->declared_at);
7820       else if (automatic_flag)
7821         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
7822                    sym->name, &sym->declared_at);
7823       else
7824         goto no_init_error;
7825       return FAILURE;
7826     }
7827
7828 no_init_error:
7829   if (sym->ts.type == BT_DERIVED)
7830     return resolve_fl_variable_derived (sym, no_init_flag);
7831
7832   return SUCCESS;
7833 }
7834
7835
7836 /* Resolve a procedure.  */
7837
7838 static gfc_try
7839 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
7840 {
7841   gfc_formal_arglist *arg;
7842
7843   if (sym->attr.ambiguous_interfaces && !sym->attr.referenced)
7844     gfc_warning ("Although not referenced, '%s' at %L has ambiguous "
7845                  "interfaces", sym->name, &sym->declared_at);
7846
7847   if (sym->attr.function
7848       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
7849     return FAILURE;
7850
7851   if (sym->ts.type == BT_CHARACTER)
7852     {
7853       gfc_charlen *cl = sym->ts.cl;
7854
7855       if (cl && cl->length && gfc_is_constant_expr (cl->length)
7856              && resolve_charlen (cl) == FAILURE)
7857         return FAILURE;
7858
7859       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
7860         {
7861           if (sym->attr.proc == PROC_ST_FUNCTION)
7862             {
7863               gfc_error ("Character-valued statement function '%s' at %L must "
7864                          "have constant length", sym->name, &sym->declared_at);
7865               return FAILURE;
7866             }
7867
7868           if (sym->attr.external && sym->formal == NULL
7869               && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
7870             {
7871               gfc_error ("Automatic character length function '%s' at %L must "
7872                          "have an explicit interface", sym->name,
7873                          &sym->declared_at);
7874               return FAILURE;
7875             }
7876         }
7877     }
7878
7879   /* Ensure that derived type for are not of a private type.  Internal
7880      module procedures are excluded by 2.2.3.3 - i.e., they are not
7881      externally accessible and can access all the objects accessible in
7882      the host.  */
7883   if (!(sym->ns->parent
7884         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
7885       && gfc_check_access(sym->attr.access, sym->ns->default_access))
7886     {
7887       gfc_interface *iface;
7888
7889       for (arg = sym->formal; arg; arg = arg->next)
7890         {
7891           if (arg->sym
7892               && arg->sym->ts.type == BT_DERIVED
7893               && !arg->sym->ts.derived->attr.use_assoc
7894               && !gfc_check_access (arg->sym->ts.derived->attr.access,
7895                                     arg->sym->ts.derived->ns->default_access)
7896               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
7897                                  "PRIVATE type and cannot be a dummy argument"
7898                                  " of '%s', which is PUBLIC at %L",
7899                                  arg->sym->name, sym->name, &sym->declared_at)
7900                  == FAILURE)
7901             {
7902               /* Stop this message from recurring.  */
7903               arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
7904               return FAILURE;
7905             }
7906         }
7907
7908       /* PUBLIC interfaces may expose PRIVATE procedures that take types
7909          PRIVATE to the containing module.  */
7910       for (iface = sym->generic; iface; iface = iface->next)
7911         {
7912           for (arg = iface->sym->formal; arg; arg = arg->next)
7913             {
7914               if (arg->sym
7915                   && arg->sym->ts.type == BT_DERIVED
7916                   && !arg->sym->ts.derived->attr.use_assoc
7917                   && !gfc_check_access (arg->sym->ts.derived->attr.access,
7918                                         arg->sym->ts.derived->ns->default_access)
7919                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
7920                                      "'%s' in PUBLIC interface '%s' at %L "
7921                                      "takes dummy arguments of '%s' which is "
7922                                      "PRIVATE", iface->sym->name, sym->name,
7923                                      &iface->sym->declared_at,
7924                                      gfc_typename (&arg->sym->ts)) == FAILURE)
7925                 {
7926                   /* Stop this message from recurring.  */
7927                   arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
7928                   return FAILURE;
7929                 }
7930              }
7931         }
7932
7933       /* PUBLIC interfaces may expose PRIVATE procedures that take types
7934          PRIVATE to the containing module.  */
7935       for (iface = sym->generic; iface; iface = iface->next)
7936         {
7937           for (arg = iface->sym->formal; arg; arg = arg->next)
7938             {
7939               if (arg->sym
7940                   && arg->sym->ts.type == BT_DERIVED
7941                   && !arg->sym->ts.derived->attr.use_assoc
7942                   && !gfc_check_access (arg->sym->ts.derived->attr.access,
7943                                         arg->sym->ts.derived->ns->default_access)
7944                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
7945                                      "'%s' in PUBLIC interface '%s' at %L "
7946                                      "takes dummy arguments of '%s' which is "
7947                                      "PRIVATE", iface->sym->name, sym->name,
7948                                      &iface->sym->declared_at,
7949                                      gfc_typename (&arg->sym->ts)) == FAILURE)
7950                 {
7951                   /* Stop this message from recurring.  */
7952                   arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
7953                   return FAILURE;
7954                 }
7955              }
7956         }
7957     }
7958
7959   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
7960       && !sym->attr.proc_pointer)
7961     {
7962       gfc_error ("Function '%s' at %L cannot have an initializer",
7963                  sym->name, &sym->declared_at);
7964       return FAILURE;
7965     }
7966
7967   /* An external symbol may not have an initializer because it is taken to be
7968      a procedure. Exception: Procedure Pointers.  */
7969   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
7970     {
7971       gfc_error ("External object '%s' at %L may not have an initializer",
7972                  sym->name, &sym->declared_at);
7973       return FAILURE;
7974     }
7975
7976   /* An elemental function is required to return a scalar 12.7.1  */
7977   if (sym->attr.elemental && sym->attr.function && sym->as)
7978     {
7979       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
7980                  "result", sym->name, &sym->declared_at);
7981       /* Reset so that the error only occurs once.  */
7982       sym->attr.elemental = 0;
7983       return FAILURE;
7984     }
7985
7986   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
7987      char-len-param shall not be array-valued, pointer-valued, recursive
7988      or pure.  ....snip... A character value of * may only be used in the
7989      following ways: (i) Dummy arg of procedure - dummy associates with
7990      actual length; (ii) To declare a named constant; or (iii) External
7991      function - but length must be declared in calling scoping unit.  */
7992   if (sym->attr.function
7993       && sym->ts.type == BT_CHARACTER
7994       && sym->ts.cl && sym->ts.cl->length == NULL)
7995     {
7996       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
7997           || (sym->attr.recursive) || (sym->attr.pure))
7998         {
7999           if (sym->as && sym->as->rank)
8000             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
8001                        "array-valued", sym->name, &sym->declared_at);
8002
8003           if (sym->attr.pointer)
8004             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
8005                        "pointer-valued", sym->name, &sym->declared_at);
8006
8007           if (sym->attr.pure)
8008             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
8009                        "pure", sym->name, &sym->declared_at);
8010
8011           if (sym->attr.recursive)
8012             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
8013                        "recursive", sym->name, &sym->declared_at);
8014
8015           return FAILURE;
8016         }
8017
8018       /* Appendix B.2 of the standard.  Contained functions give an
8019          error anyway.  Fixed-form is likely to be F77/legacy.  */
8020       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
8021         gfc_notify_std (GFC_STD_F95_OBS, "CHARACTER(*) function "
8022                         "'%s' at %L is obsolescent in fortran 95",
8023                         sym->name, &sym->declared_at);
8024     }
8025
8026   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
8027     {
8028       gfc_formal_arglist *curr_arg;
8029       int has_non_interop_arg = 0;
8030
8031       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
8032                              sym->common_block) == FAILURE)
8033         {
8034           /* Clear these to prevent looking at them again if there was an
8035              error.  */
8036           sym->attr.is_bind_c = 0;
8037           sym->attr.is_c_interop = 0;
8038           sym->ts.is_c_interop = 0;
8039         }
8040       else
8041         {
8042           /* So far, no errors have been found.  */
8043           sym->attr.is_c_interop = 1;
8044           sym->ts.is_c_interop = 1;
8045         }
8046       
8047       curr_arg = sym->formal;
8048       while (curr_arg != NULL)
8049         {
8050           /* Skip implicitly typed dummy args here.  */
8051           if (curr_arg->sym->attr.implicit_type == 0)
8052             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
8053               /* If something is found to fail, record the fact so we
8054                  can mark the symbol for the procedure as not being
8055                  BIND(C) to try and prevent multiple errors being
8056                  reported.  */
8057               has_non_interop_arg = 1;
8058           
8059           curr_arg = curr_arg->next;
8060         }
8061
8062       /* See if any of the arguments were not interoperable and if so, clear
8063          the procedure symbol to prevent duplicate error messages.  */
8064       if (has_non_interop_arg != 0)
8065         {
8066           sym->attr.is_c_interop = 0;
8067           sym->ts.is_c_interop = 0;
8068           sym->attr.is_bind_c = 0;
8069         }
8070     }
8071   
8072   if (sym->attr.save == SAVE_EXPLICIT && !sym->attr.proc_pointer)
8073     {
8074       gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
8075                  "in '%s' at %L", sym->name, &sym->declared_at);
8076       return FAILURE;
8077     }
8078
8079   if (sym->attr.intent && !sym->attr.proc_pointer)
8080     {
8081       gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
8082                  "in '%s' at %L", sym->name, &sym->declared_at);
8083       return FAILURE;
8084     }
8085
8086   return SUCCESS;
8087 }
8088
8089
8090 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
8091    been defined and we now know their defined arguments, check that they fulfill
8092    the requirements of the standard for procedures used as finalizers.  */
8093
8094 static gfc_try
8095 gfc_resolve_finalizers (gfc_symbol* derived)
8096 {
8097   gfc_finalizer* list;
8098   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
8099   gfc_try result = SUCCESS;
8100   bool seen_scalar = false;
8101
8102   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
8103     return SUCCESS;
8104
8105   /* Walk over the list of finalizer-procedures, check them, and if any one
8106      does not fit in with the standard's definition, print an error and remove
8107      it from the list.  */
8108   prev_link = &derived->f2k_derived->finalizers;
8109   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
8110     {
8111       gfc_symbol* arg;
8112       gfc_finalizer* i;
8113       int my_rank;
8114
8115       /* Skip this finalizer if we already resolved it.  */
8116       if (list->proc_tree)
8117         {
8118           prev_link = &(list->next);
8119           continue;
8120         }
8121
8122       /* Check this exists and is a SUBROUTINE.  */
8123       if (!list->proc_sym->attr.subroutine)
8124         {
8125           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
8126                      list->proc_sym->name, &list->where);
8127           goto error;
8128         }
8129
8130       /* We should have exactly one argument.  */
8131       if (!list->proc_sym->formal || list->proc_sym->formal->next)
8132         {
8133           gfc_error ("FINAL procedure at %L must have exactly one argument",
8134                      &list->where);
8135           goto error;
8136         }
8137       arg = list->proc_sym->formal->sym;
8138
8139       /* This argument must be of our type.  */
8140       if (arg->ts.type != BT_DERIVED || arg->ts.derived != derived)
8141         {
8142           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
8143                      &arg->declared_at, derived->name);
8144           goto error;
8145         }
8146
8147       /* It must neither be a pointer nor allocatable nor optional.  */
8148       if (arg->attr.pointer)
8149         {
8150           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
8151                      &arg->declared_at);
8152           goto error;
8153         }
8154       if (arg->attr.allocatable)
8155         {
8156           gfc_error ("Argument of FINAL procedure at %L must not be"
8157                      " ALLOCATABLE", &arg->declared_at);
8158           goto error;
8159         }
8160       if (arg->attr.optional)
8161         {
8162           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
8163                      &arg->declared_at);
8164           goto error;
8165         }
8166
8167       /* It must not be INTENT(OUT).  */
8168       if (arg->attr.intent == INTENT_OUT)
8169         {
8170           gfc_error ("Argument of FINAL procedure at %L must not be"
8171                      " INTENT(OUT)", &arg->declared_at);
8172           goto error;
8173         }
8174
8175       /* Warn if the procedure is non-scalar and not assumed shape.  */
8176       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
8177           && arg->as->type != AS_ASSUMED_SHAPE)
8178         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
8179                      " shape argument", &arg->declared_at);
8180
8181       /* Check that it does not match in kind and rank with a FINAL procedure
8182          defined earlier.  To really loop over the *earlier* declarations,
8183          we need to walk the tail of the list as new ones were pushed at the
8184          front.  */
8185       /* TODO: Handle kind parameters once they are implemented.  */
8186       my_rank = (arg->as ? arg->as->rank : 0);
8187       for (i = list->next; i; i = i->next)
8188         {
8189           /* Argument list might be empty; that is an error signalled earlier,
8190              but we nevertheless continued resolving.  */
8191           if (i->proc_sym->formal)
8192             {
8193               gfc_symbol* i_arg = i->proc_sym->formal->sym;
8194               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
8195               if (i_rank == my_rank)
8196                 {
8197                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
8198                              " rank (%d) as '%s'",
8199                              list->proc_sym->name, &list->where, my_rank, 
8200                              i->proc_sym->name);
8201                   goto error;
8202                 }
8203             }
8204         }
8205
8206         /* Is this the/a scalar finalizer procedure?  */
8207         if (!arg->as || arg->as->rank == 0)
8208           seen_scalar = true;
8209
8210         /* Find the symtree for this procedure.  */
8211         gcc_assert (!list->proc_tree);
8212         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
8213
8214         prev_link = &list->next;
8215         continue;
8216
8217         /* Remove wrong nodes immediately from the list so we don't risk any
8218            troubles in the future when they might fail later expectations.  */
8219 error:
8220         result = FAILURE;
8221         i = list;
8222         *prev_link = list->next;
8223         gfc_free_finalizer (i);
8224     }
8225
8226   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
8227      were nodes in the list, must have been for arrays.  It is surely a good
8228      idea to have a scalar version there if there's something to finalize.  */
8229   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
8230     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
8231                  " defined at %L, suggest also scalar one",
8232                  derived->name, &derived->declared_at);
8233
8234   /* TODO:  Remove this error when finalization is finished.  */
8235   gfc_error ("Finalization at %L is not yet implemented",
8236              &derived->declared_at);
8237
8238   return result;
8239 }
8240
8241
8242 /* Check that it is ok for the typebound procedure proc to override the
8243    procedure old.  */
8244
8245 static gfc_try
8246 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
8247 {
8248   locus where;
8249   const gfc_symbol* proc_target;
8250   const gfc_symbol* old_target;
8251   unsigned proc_pass_arg, old_pass_arg, argpos;
8252   gfc_formal_arglist* proc_formal;
8253   gfc_formal_arglist* old_formal;
8254
8255   /* This procedure should only be called for non-GENERIC proc.  */
8256   gcc_assert (!proc->typebound->is_generic);
8257
8258   /* If the overwritten procedure is GENERIC, this is an error.  */
8259   if (old->typebound->is_generic)
8260     {
8261       gfc_error ("Can't overwrite GENERIC '%s' at %L",
8262                  old->name, &proc->typebound->where);
8263       return FAILURE;
8264     }
8265
8266   where = proc->typebound->where;
8267   proc_target = proc->typebound->u.specific->n.sym;
8268   old_target = old->typebound->u.specific->n.sym;
8269
8270   /* Check that overridden binding is not NON_OVERRIDABLE.  */
8271   if (old->typebound->non_overridable)
8272     {
8273       gfc_error ("'%s' at %L overrides a procedure binding declared"
8274                  " NON_OVERRIDABLE", proc->name, &where);
8275       return FAILURE;
8276     }
8277
8278   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
8279   if (!old->typebound->deferred && proc->typebound->deferred)
8280     {
8281       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
8282                  " non-DEFERRED binding", proc->name, &where);
8283       return FAILURE;
8284     }
8285
8286   /* If the overridden binding is PURE, the overriding must be, too.  */
8287   if (old_target->attr.pure && !proc_target->attr.pure)
8288     {
8289       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
8290                  proc->name, &where);
8291       return FAILURE;
8292     }
8293
8294   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
8295      is not, the overriding must not be either.  */
8296   if (old_target->attr.elemental && !proc_target->attr.elemental)
8297     {
8298       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
8299                  " ELEMENTAL", proc->name, &where);
8300       return FAILURE;
8301     }
8302   if (!old_target->attr.elemental && proc_target->attr.elemental)
8303     {
8304       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
8305                  " be ELEMENTAL, either", proc->name, &where);
8306       return FAILURE;
8307     }
8308
8309   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
8310      SUBROUTINE.  */
8311   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
8312     {
8313       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
8314                  " SUBROUTINE", proc->name, &where);
8315       return FAILURE;
8316     }
8317
8318   /* If the overridden binding is a FUNCTION, the overriding must also be a
8319      FUNCTION and have the same characteristics.  */
8320   if (old_target->attr.function)
8321     {
8322       if (!proc_target->attr.function)
8323         {
8324           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
8325                      " FUNCTION", proc->name, &where);
8326           return FAILURE;
8327         }
8328
8329       /* FIXME:  Do more comprehensive checking (including, for instance, the
8330          rank and array-shape).  */
8331       gcc_assert (proc_target->result && old_target->result);
8332       if (!gfc_compare_types (&proc_target->result->ts,
8333                               &old_target->result->ts))
8334         {
8335           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
8336                      " matching result types", proc->name, &where);
8337           return FAILURE;
8338         }
8339     }
8340
8341   /* If the overridden binding is PUBLIC, the overriding one must not be
8342      PRIVATE.  */
8343   if (old->typebound->access == ACCESS_PUBLIC
8344       && proc->typebound->access == ACCESS_PRIVATE)
8345     {
8346       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
8347                  " PRIVATE", proc->name, &where);
8348       return FAILURE;
8349     }
8350
8351   /* Compare the formal argument lists of both procedures.  This is also abused
8352      to find the position of the passed-object dummy arguments of both
8353      bindings as at least the overridden one might not yet be resolved and we
8354      need those positions in the check below.  */
8355   proc_pass_arg = old_pass_arg = 0;
8356   if (!proc->typebound->nopass && !proc->typebound->pass_arg)
8357     proc_pass_arg = 1;
8358   if (!old->typebound->nopass && !old->typebound->pass_arg)
8359     old_pass_arg = 1;
8360   argpos = 1;
8361   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
8362        proc_formal && old_formal;
8363        proc_formal = proc_formal->next, old_formal = old_formal->next)
8364     {
8365       if (proc->typebound->pass_arg
8366           && !strcmp (proc->typebound->pass_arg, proc_formal->sym->name))
8367         proc_pass_arg = argpos;
8368       if (old->typebound->pass_arg
8369           && !strcmp (old->typebound->pass_arg, old_formal->sym->name))
8370         old_pass_arg = argpos;
8371
8372       /* Check that the names correspond.  */
8373       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
8374         {
8375           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
8376                      " to match the corresponding argument of the overridden"
8377                      " procedure", proc_formal->sym->name, proc->name, &where,
8378                      old_formal->sym->name);
8379           return FAILURE;
8380         }
8381
8382       /* Check that the types correspond if neither is the passed-object
8383          argument.  */
8384       /* FIXME:  Do more comprehensive testing here.  */
8385       if (proc_pass_arg != argpos && old_pass_arg != argpos
8386           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
8387         {
8388           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L in"
8389                      " in respect to the overridden procedure",
8390                      proc_formal->sym->name, proc->name, &where);
8391           return FAILURE;
8392         }
8393
8394       ++argpos;
8395     }
8396   if (proc_formal || old_formal)
8397     {
8398       gfc_error ("'%s' at %L must have the same number of formal arguments as"
8399                  " the overridden procedure", proc->name, &where);
8400       return FAILURE;
8401     }
8402
8403   /* If the overridden binding is NOPASS, the overriding one must also be
8404      NOPASS.  */
8405   if (old->typebound->nopass && !proc->typebound->nopass)
8406     {
8407       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
8408                  " NOPASS", proc->name, &where);
8409       return FAILURE;
8410     }
8411
8412   /* If the overridden binding is PASS(x), the overriding one must also be
8413      PASS and the passed-object dummy arguments must correspond.  */
8414   if (!old->typebound->nopass)
8415     {
8416       if (proc->typebound->nopass)
8417         {
8418           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
8419                      " PASS", proc->name, &where);
8420           return FAILURE;
8421         }
8422
8423       if (proc_pass_arg != old_pass_arg)
8424         {
8425           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
8426                      " the same position as the passed-object dummy argument of"
8427                      " the overridden procedure", proc->name, &where);
8428           return FAILURE;
8429         }
8430     }
8431
8432   return SUCCESS;
8433 }
8434
8435
8436 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
8437
8438 static gfc_try
8439 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
8440                              const char* generic_name, locus where)
8441 {
8442   gfc_symbol* sym1;
8443   gfc_symbol* sym2;
8444
8445   gcc_assert (t1->specific && t2->specific);
8446   gcc_assert (!t1->specific->is_generic);
8447   gcc_assert (!t2->specific->is_generic);
8448
8449   sym1 = t1->specific->u.specific->n.sym;
8450   sym2 = t2->specific->u.specific->n.sym;
8451
8452   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
8453   if (sym1->attr.subroutine != sym2->attr.subroutine
8454       || sym1->attr.function != sym2->attr.function)
8455     {
8456       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
8457                  " GENERIC '%s' at %L",
8458                  sym1->name, sym2->name, generic_name, &where);
8459       return FAILURE;
8460     }
8461
8462   /* Compare the interfaces.  */
8463   if (gfc_compare_interfaces (sym1, sym2, 1))
8464     {
8465       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
8466                  sym1->name, sym2->name, generic_name, &where);
8467       return FAILURE;
8468     }
8469
8470   return SUCCESS;
8471 }
8472
8473
8474 /* Resolve a GENERIC procedure binding for a derived type.  */
8475
8476 static gfc_try
8477 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
8478 {
8479   gfc_tbp_generic* target;
8480   gfc_symtree* first_target;
8481   gfc_symbol* super_type;
8482   gfc_symtree* inherited;
8483   locus where;
8484
8485   gcc_assert (st->typebound);
8486   gcc_assert (st->typebound->is_generic);
8487
8488   where = st->typebound->where;
8489   super_type = gfc_get_derived_super_type (derived);
8490
8491   /* Find the overridden binding if any.  */
8492   st->typebound->overridden = NULL;
8493   if (super_type)
8494     {
8495       gfc_symtree* overridden;
8496       overridden = gfc_find_typebound_proc (super_type, NULL, st->name, true);
8497
8498       if (overridden && overridden->typebound)
8499         st->typebound->overridden = overridden->typebound;
8500     }
8501
8502   /* Try to find the specific bindings for the symtrees in our target-list.  */
8503   gcc_assert (st->typebound->u.generic);
8504   for (target = st->typebound->u.generic; target; target = target->next)
8505     if (!target->specific)
8506       {
8507         gfc_typebound_proc* overridden_tbp;
8508         gfc_tbp_generic* g;
8509         const char* target_name;
8510
8511         target_name = target->specific_st->name;
8512
8513         /* Defined for this type directly.  */
8514         if (target->specific_st->typebound)
8515           {
8516             target->specific = target->specific_st->typebound;
8517             goto specific_found;
8518           }
8519
8520         /* Look for an inherited specific binding.  */
8521         if (super_type)
8522           {
8523             inherited = gfc_find_typebound_proc (super_type, NULL,
8524                                                  target_name, true);
8525
8526             if (inherited)
8527               {
8528                 gcc_assert (inherited->typebound);
8529                 target->specific = inherited->typebound;
8530                 goto specific_found;
8531               }
8532           }
8533
8534         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
8535                    " at %L", target_name, st->name, &where);
8536         return FAILURE;
8537
8538         /* Once we've found the specific binding, check it is not ambiguous with
8539            other specifics already found or inherited for the same GENERIC.  */
8540 specific_found:
8541         gcc_assert (target->specific);
8542
8543         /* This must really be a specific binding!  */
8544         if (target->specific->is_generic)
8545           {
8546             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
8547                        " '%s' is GENERIC, too", st->name, &where, target_name);
8548             return FAILURE;
8549           }
8550
8551         /* Check those already resolved on this type directly.  */
8552         for (g = st->typebound->u.generic; g; g = g->next)
8553           if (g != target && g->specific
8554               && check_generic_tbp_ambiguity (target, g, st->name, where)
8555                   == FAILURE)
8556             return FAILURE;
8557
8558         /* Check for ambiguity with inherited specific targets.  */
8559         for (overridden_tbp = st->typebound->overridden; overridden_tbp;
8560              overridden_tbp = overridden_tbp->overridden)
8561           if (overridden_tbp->is_generic)
8562             {
8563               for (g = overridden_tbp->u.generic; g; g = g->next)
8564                 {
8565                   gcc_assert (g->specific);
8566                   if (check_generic_tbp_ambiguity (target, g,
8567                                                    st->name, where) == FAILURE)
8568                     return FAILURE;
8569                 }
8570             }
8571       }
8572
8573   /* If we attempt to "overwrite" a specific binding, this is an error.  */
8574   if (st->typebound->overridden && !st->typebound->overridden->is_generic)
8575     {
8576       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
8577                  " the same name", st->name, &where);
8578       return FAILURE;
8579     }
8580
8581   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
8582      all must have the same attributes here.  */
8583   first_target = st->typebound->u.generic->specific->u.specific;
8584   st->typebound->subroutine = first_target->n.sym->attr.subroutine;
8585   st->typebound->function = first_target->n.sym->attr.function;
8586
8587   return SUCCESS;
8588 }
8589
8590
8591 /* Resolve the type-bound procedures for a derived type.  */
8592
8593 static gfc_symbol* resolve_bindings_derived;
8594 static gfc_try resolve_bindings_result;
8595
8596 static void
8597 resolve_typebound_procedure (gfc_symtree* stree)
8598 {
8599   gfc_symbol* proc;
8600   locus where;
8601   gfc_symbol* me_arg;
8602   gfc_symbol* super_type;
8603   gfc_component* comp;
8604
8605   /* If this is no type-bound procedure, just return.  */
8606   if (!stree->typebound)
8607     return;
8608
8609   /* If this is a GENERIC binding, use that routine.  */
8610   if (stree->typebound->is_generic)
8611     {
8612       if (resolve_typebound_generic (resolve_bindings_derived, stree)
8613             == FAILURE)
8614         goto error;
8615       return;
8616     }
8617
8618   /* Get the target-procedure to check it.  */
8619   gcc_assert (!stree->typebound->is_generic);
8620   gcc_assert (stree->typebound->u.specific);
8621   proc = stree->typebound->u.specific->n.sym;
8622   where = stree->typebound->where;
8623
8624   /* Default access should already be resolved from the parser.  */
8625   gcc_assert (stree->typebound->access != ACCESS_UNKNOWN);
8626
8627   /* It should be a module procedure or an external procedure with explicit
8628      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
8629   if ((!proc->attr.subroutine && !proc->attr.function)
8630       || (proc->attr.proc != PROC_MODULE
8631           && proc->attr.if_source != IFSRC_IFBODY)
8632       || (proc->attr.abstract && !stree->typebound->deferred))
8633     {
8634       gfc_error ("'%s' must be a module procedure or an external procedure with"
8635                  " an explicit interface at %L", proc->name, &where);
8636       goto error;
8637     }
8638   stree->typebound->subroutine = proc->attr.subroutine;
8639   stree->typebound->function = proc->attr.function;
8640
8641   /* Find the super-type of the current derived type.  We could do this once and
8642      store in a global if speed is needed, but as long as not I believe this is
8643      more readable and clearer.  */
8644   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
8645
8646   /* If PASS, resolve and check arguments if not already resolved / loaded
8647      from a .mod file.  */
8648   if (!stree->typebound->nopass && stree->typebound->pass_arg_num == 0)
8649     {
8650       if (stree->typebound->pass_arg)
8651         {
8652           gfc_formal_arglist* i;
8653
8654           /* If an explicit passing argument name is given, walk the arg-list
8655              and look for it.  */
8656
8657           me_arg = NULL;
8658           stree->typebound->pass_arg_num = 1;
8659           for (i = proc->formal; i; i = i->next)
8660             {
8661               if (!strcmp (i->sym->name, stree->typebound->pass_arg))
8662                 {
8663                   me_arg = i->sym;
8664                   break;
8665                 }
8666               ++stree->typebound->pass_arg_num;
8667             }
8668
8669           if (!me_arg)
8670             {
8671               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
8672                          " argument '%s'",
8673                          proc->name, stree->typebound->pass_arg, &where,
8674                          stree->typebound->pass_arg);
8675               goto error;
8676             }
8677         }
8678       else
8679         {
8680           /* Otherwise, take the first one; there should in fact be at least
8681              one.  */
8682           stree->typebound->pass_arg_num = 1;
8683           if (!proc->formal)
8684             {
8685               gfc_error ("Procedure '%s' with PASS at %L must have at"
8686                          " least one argument", proc->name, &where);
8687               goto error;
8688             }
8689           me_arg = proc->formal->sym;
8690         }
8691
8692       /* Now check that the argument-type matches.  */
8693       gcc_assert (me_arg);
8694       if (me_arg->ts.type != BT_DERIVED
8695           || me_arg->ts.derived != resolve_bindings_derived)
8696         {
8697           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
8698                      " the derived-type '%s'", me_arg->name, proc->name,
8699                      me_arg->name, &where, resolve_bindings_derived->name);
8700           goto error;
8701         }
8702
8703       gfc_warning ("Polymorphic entities are not yet implemented,"
8704                    " non-polymorphic passed-object dummy argument of '%s'"
8705                    " at %L accepted", proc->name, &where);
8706     }
8707
8708   /* If we are extending some type, check that we don't override a procedure
8709      flagged NON_OVERRIDABLE.  */
8710   stree->typebound->overridden = NULL;
8711   if (super_type)
8712     {
8713       gfc_symtree* overridden;
8714       overridden = gfc_find_typebound_proc (super_type, NULL,
8715                                             stree->name, true);
8716
8717       if (overridden && overridden->typebound)
8718         stree->typebound->overridden = overridden->typebound;
8719
8720       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
8721         goto error;
8722     }
8723
8724   /* See if there's a name collision with a component directly in this type.  */
8725   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
8726     if (!strcmp (comp->name, stree->name))
8727       {
8728         gfc_error ("Procedure '%s' at %L has the same name as a component of"
8729                    " '%s'",
8730                    stree->name, &where, resolve_bindings_derived->name);
8731         goto error;
8732       }
8733
8734   /* Try to find a name collision with an inherited component.  */
8735   if (super_type && gfc_find_component (super_type, stree->name, true, true))
8736     {
8737       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
8738                  " component of '%s'",
8739                  stree->name, &where, resolve_bindings_derived->name);
8740       goto error;
8741     }
8742
8743   stree->typebound->error = 0;
8744   return;
8745
8746 error:
8747   resolve_bindings_result = FAILURE;
8748   stree->typebound->error = 1;
8749 }
8750
8751 static gfc_try
8752 resolve_typebound_procedures (gfc_symbol* derived)
8753 {
8754   if (!derived->f2k_derived || !derived->f2k_derived->sym_root)
8755     return SUCCESS;
8756
8757   resolve_bindings_derived = derived;
8758   resolve_bindings_result = SUCCESS;
8759   gfc_traverse_symtree (derived->f2k_derived->sym_root,
8760                         &resolve_typebound_procedure);
8761
8762   return resolve_bindings_result;
8763 }
8764
8765
8766 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
8767    to give all identical derived types the same backend_decl.  */
8768 static void
8769 add_dt_to_dt_list (gfc_symbol *derived)
8770 {
8771   gfc_dt_list *dt_list;
8772
8773   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
8774     if (derived == dt_list->derived)
8775       break;
8776
8777   if (dt_list == NULL)
8778     {
8779       dt_list = gfc_get_dt_list ();
8780       dt_list->next = gfc_derived_types;
8781       dt_list->derived = derived;
8782       gfc_derived_types = dt_list;
8783     }
8784 }
8785
8786
8787 /* Ensure that a derived-type is really not abstract, meaning that every
8788    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
8789
8790 static gfc_try
8791 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
8792 {
8793   if (!st)
8794     return SUCCESS;
8795
8796   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
8797     return FAILURE;
8798   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
8799     return FAILURE;
8800
8801   if (st->typebound && st->typebound->deferred)
8802     {
8803       gfc_symtree* overriding;
8804       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true);
8805       gcc_assert (overriding && overriding->typebound);
8806       if (overriding->typebound->deferred)
8807         {
8808           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
8809                      " '%s' is DEFERRED and not overridden",
8810                      sub->name, &sub->declared_at, st->name);
8811           return FAILURE;
8812         }
8813     }
8814
8815   return SUCCESS;
8816 }
8817
8818 static gfc_try
8819 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
8820 {
8821   /* The algorithm used here is to recursively travel up the ancestry of sub
8822      and for each ancestor-type, check all bindings.  If any of them is
8823      DEFERRED, look it up starting from sub and see if the found (overriding)
8824      binding is not DEFERRED.
8825      This is not the most efficient way to do this, but it should be ok and is
8826      clearer than something sophisticated.  */
8827
8828   gcc_assert (ancestor && ancestor->attr.abstract && !sub->attr.abstract);
8829
8830   /* Walk bindings of this ancestor.  */
8831   if (ancestor->f2k_derived)
8832     {
8833       gfc_try t;
8834       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->sym_root);
8835       if (t == FAILURE)
8836         return FAILURE;
8837     }
8838
8839   /* Find next ancestor type and recurse on it.  */
8840   ancestor = gfc_get_derived_super_type (ancestor);
8841   if (ancestor)
8842     return ensure_not_abstract (sub, ancestor);
8843
8844   return SUCCESS;
8845 }
8846
8847
8848 /* Resolve the components of a derived type.  */
8849
8850 static gfc_try
8851 resolve_fl_derived (gfc_symbol *sym)
8852 {
8853   gfc_symbol* super_type;
8854   gfc_component *c;
8855   int i;
8856
8857   super_type = gfc_get_derived_super_type (sym);
8858
8859   /* Ensure the extended type gets resolved before we do.  */
8860   if (super_type && resolve_fl_derived (super_type) == FAILURE)
8861     return FAILURE;
8862
8863   /* An ABSTRACT type must be extensible.  */
8864   if (sym->attr.abstract && (sym->attr.is_bind_c || sym->attr.sequence))
8865     {
8866       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
8867                  sym->name, &sym->declared_at);
8868       return FAILURE;
8869     }
8870
8871   for (c = sym->components; c != NULL; c = c->next)
8872     {
8873       /* Check type-spec if this is not the parent-type component.  */
8874       if ((!sym->attr.extension || c != sym->components)
8875           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
8876         return FAILURE;
8877
8878       /* If this type is an extension, see if this component has the same name
8879          as an inherited type-bound procedure.  */
8880       if (super_type
8881           && gfc_find_typebound_proc (super_type, NULL, c->name, true))
8882         {
8883           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
8884                      " inherited type-bound procedure",
8885                      c->name, sym->name, &c->loc);
8886           return FAILURE;
8887         }
8888
8889       if (c->ts.type == BT_CHARACTER)
8890         {
8891          if (c->ts.cl->length == NULL
8892              || (resolve_charlen (c->ts.cl) == FAILURE)
8893              || !gfc_is_constant_expr (c->ts.cl->length))
8894            {
8895              gfc_error ("Character length of component '%s' needs to "
8896                         "be a constant specification expression at %L",
8897                         c->name,
8898                         c->ts.cl->length ? &c->ts.cl->length->where : &c->loc);
8899              return FAILURE;
8900            }
8901         }
8902
8903       if (c->ts.type == BT_DERIVED
8904           && sym->component_access != ACCESS_PRIVATE
8905           && gfc_check_access (sym->attr.access, sym->ns->default_access)
8906           && !c->ts.derived->attr.use_assoc
8907           && !gfc_check_access (c->ts.derived->attr.access,
8908                                 c->ts.derived->ns->default_access))
8909         {
8910           gfc_error ("The component '%s' is a PRIVATE type and cannot be "
8911                      "a component of '%s', which is PUBLIC at %L",
8912                      c->name, sym->name, &sym->declared_at);
8913           return FAILURE;
8914         }
8915
8916       if (sym->attr.sequence)
8917         {
8918           if (c->ts.type == BT_DERIVED && c->ts.derived->attr.sequence == 0)
8919             {
8920               gfc_error ("Component %s of SEQUENCE type declared at %L does "
8921                          "not have the SEQUENCE attribute",
8922                          c->ts.derived->name, &sym->declared_at);
8923               return FAILURE;
8924             }
8925         }
8926
8927       if (c->ts.type == BT_DERIVED && c->attr.pointer
8928           && c->ts.derived->components == NULL
8929           && !c->ts.derived->attr.zero_comp)
8930         {
8931           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
8932                      "that has not been declared", c->name, sym->name,
8933                      &c->loc);
8934           return FAILURE;
8935         }
8936
8937       /* Ensure that all the derived type components are put on the
8938          derived type list; even in formal namespaces, where derived type
8939          pointer components might not have been declared.  */
8940       if (c->ts.type == BT_DERIVED
8941             && c->ts.derived
8942             && c->ts.derived->components
8943             && c->attr.pointer
8944             && sym != c->ts.derived)
8945         add_dt_to_dt_list (c->ts.derived);
8946
8947       if (c->attr.pointer || c->attr.allocatable ||  c->as == NULL)
8948         continue;
8949
8950       for (i = 0; i < c->as->rank; i++)
8951         {
8952           if (c->as->lower[i] == NULL
8953               || (resolve_index_expr (c->as->lower[i]) == FAILURE)
8954               || !gfc_is_constant_expr (c->as->lower[i])
8955               || c->as->upper[i] == NULL
8956               || (resolve_index_expr (c->as->upper[i]) == FAILURE)
8957               || !gfc_is_constant_expr (c->as->upper[i]))
8958             {
8959               gfc_error ("Component '%s' of '%s' at %L must have "
8960                          "constant array bounds",
8961                          c->name, sym->name, &c->loc);
8962               return FAILURE;
8963             }
8964         }
8965     }
8966
8967   /* Resolve the type-bound procedures.  */
8968   if (resolve_typebound_procedures (sym) == FAILURE)
8969     return FAILURE;
8970
8971   /* Resolve the finalizer procedures.  */
8972   if (gfc_resolve_finalizers (sym) == FAILURE)
8973     return FAILURE;
8974
8975   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
8976      all DEFERRED bindings are overridden.  */
8977   if (super_type && super_type->attr.abstract && !sym->attr.abstract
8978       && ensure_not_abstract (sym, super_type) == FAILURE)
8979     return FAILURE;
8980
8981   /* Add derived type to the derived type list.  */
8982   add_dt_to_dt_list (sym);
8983
8984   return SUCCESS;
8985 }
8986
8987
8988 static gfc_try
8989 resolve_fl_namelist (gfc_symbol *sym)
8990 {
8991   gfc_namelist *nl;
8992   gfc_symbol *nlsym;
8993
8994   /* Reject PRIVATE objects in a PUBLIC namelist.  */
8995   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
8996     {
8997       for (nl = sym->namelist; nl; nl = nl->next)
8998         {
8999           if (!nl->sym->attr.use_assoc
9000               && !(sym->ns->parent == nl->sym->ns)
9001               && !(sym->ns->parent
9002                    && sym->ns->parent->parent == nl->sym->ns)
9003               && !gfc_check_access(nl->sym->attr.access,
9004                                 nl->sym->ns->default_access))
9005             {
9006               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
9007                          "cannot be member of PUBLIC namelist '%s' at %L",
9008                          nl->sym->name, sym->name, &sym->declared_at);
9009               return FAILURE;
9010             }
9011
9012           /* Types with private components that came here by USE-association.  */
9013           if (nl->sym->ts.type == BT_DERIVED
9014               && derived_inaccessible (nl->sym->ts.derived))
9015             {
9016               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
9017                          "components and cannot be member of namelist '%s' at %L",
9018                          nl->sym->name, sym->name, &sym->declared_at);
9019               return FAILURE;
9020             }
9021
9022           /* Types with private components that are defined in the same module.  */
9023           if (nl->sym->ts.type == BT_DERIVED
9024               && !(sym->ns->parent == nl->sym->ts.derived->ns)
9025               && !gfc_check_access (nl->sym->ts.derived->attr.private_comp
9026                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
9027                                         nl->sym->ns->default_access))
9028             {
9029               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
9030                          "cannot be a member of PUBLIC namelist '%s' at %L",
9031                          nl->sym->name, sym->name, &sym->declared_at);
9032               return FAILURE;
9033             }
9034         }
9035     }
9036
9037   for (nl = sym->namelist; nl; nl = nl->next)
9038     {
9039       /* Reject namelist arrays of assumed shape.  */
9040       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
9041           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
9042                              "must not have assumed shape in namelist "
9043                              "'%s' at %L", nl->sym->name, sym->name,
9044                              &sym->declared_at) == FAILURE)
9045             return FAILURE;
9046
9047       /* Reject namelist arrays that are not constant shape.  */
9048       if (is_non_constant_shape_array (nl->sym))
9049         {
9050           gfc_error ("NAMELIST array object '%s' must have constant "
9051                      "shape in namelist '%s' at %L", nl->sym->name,
9052                      sym->name, &sym->declared_at);
9053           return FAILURE;
9054         }
9055
9056       /* Namelist objects cannot have allocatable or pointer components.  */
9057       if (nl->sym->ts.type != BT_DERIVED)
9058         continue;
9059
9060       if (nl->sym->ts.derived->attr.alloc_comp)
9061         {
9062           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
9063                      "have ALLOCATABLE components",
9064                      nl->sym->name, sym->name, &sym->declared_at);
9065           return FAILURE;
9066         }
9067
9068       if (nl->sym->ts.derived->attr.pointer_comp)
9069         {
9070           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
9071                      "have POINTER components", 
9072                      nl->sym->name, sym->name, &sym->declared_at);
9073           return FAILURE;
9074         }
9075     }
9076
9077
9078   /* 14.1.2 A module or internal procedure represent local entities
9079      of the same type as a namelist member and so are not allowed.  */
9080   for (nl = sym->namelist; nl; nl = nl->next)
9081     {
9082       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
9083         continue;
9084
9085       if (nl->sym->attr.function && nl->sym == nl->sym->result)
9086         if ((nl->sym == sym->ns->proc_name)
9087                ||
9088             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
9089           continue;
9090
9091       nlsym = NULL;
9092       if (nl->sym && nl->sym->name)
9093         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
9094       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
9095         {
9096           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
9097                      "attribute in '%s' at %L", nlsym->name,
9098                      &sym->declared_at);
9099           return FAILURE;
9100         }
9101     }
9102
9103   return SUCCESS;
9104 }
9105
9106
9107 static gfc_try
9108 resolve_fl_parameter (gfc_symbol *sym)
9109 {
9110   /* A parameter array's shape needs to be constant.  */
9111   if (sym->as != NULL 
9112       && (sym->as->type == AS_DEFERRED
9113           || is_non_constant_shape_array (sym)))
9114     {
9115       gfc_error ("Parameter array '%s' at %L cannot be automatic "
9116                  "or of deferred shape", sym->name, &sym->declared_at);
9117       return FAILURE;
9118     }
9119
9120   /* Make sure a parameter that has been implicitly typed still
9121      matches the implicit type, since PARAMETER statements can precede
9122      IMPLICIT statements.  */
9123   if (sym->attr.implicit_type
9124       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym, sym->ns)))
9125     {
9126       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
9127                  "later IMPLICIT type", sym->name, &sym->declared_at);
9128       return FAILURE;
9129     }
9130
9131   /* Make sure the types of derived parameters are consistent.  This
9132      type checking is deferred until resolution because the type may
9133      refer to a derived type from the host.  */
9134   if (sym->ts.type == BT_DERIVED
9135       && !gfc_compare_types (&sym->ts, &sym->value->ts))
9136     {
9137       gfc_error ("Incompatible derived type in PARAMETER at %L",
9138                  &sym->value->where);
9139       return FAILURE;
9140     }
9141   return SUCCESS;
9142 }
9143
9144
9145 /* Do anything necessary to resolve a symbol.  Right now, we just
9146    assume that an otherwise unknown symbol is a variable.  This sort
9147    of thing commonly happens for symbols in module.  */
9148
9149 static void
9150 resolve_symbol (gfc_symbol *sym)
9151 {
9152   int check_constant, mp_flag;
9153   gfc_symtree *symtree;
9154   gfc_symtree *this_symtree;
9155   gfc_namespace *ns;
9156   gfc_component *c;
9157
9158   if (sym->attr.flavor == FL_UNKNOWN)
9159     {
9160
9161     /* If we find that a flavorless symbol is an interface in one of the
9162        parent namespaces, find its symtree in this namespace, free the
9163        symbol and set the symtree to point to the interface symbol.  */
9164       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
9165         {
9166           symtree = gfc_find_symtree (ns->sym_root, sym->name);
9167           if (symtree && symtree->n.sym->generic)
9168             {
9169               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
9170                                                sym->name);
9171               sym->refs--;
9172               if (!sym->refs)
9173                 gfc_free_symbol (sym);
9174               symtree->n.sym->refs++;
9175               this_symtree->n.sym = symtree->n.sym;
9176               return;
9177             }
9178         }
9179
9180       /* Otherwise give it a flavor according to such attributes as
9181          it has.  */
9182       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
9183         sym->attr.flavor = FL_VARIABLE;
9184       else
9185         {
9186           sym->attr.flavor = FL_PROCEDURE;
9187           if (sym->attr.dimension)
9188             sym->attr.function = 1;
9189         }
9190     }
9191
9192   if (sym->attr.procedure && sym->ts.interface
9193       && sym->attr.if_source != IFSRC_DECL)
9194     {
9195       if (sym->ts.interface->attr.procedure)
9196         gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
9197                    "in a later PROCEDURE statement", sym->ts.interface->name,
9198                    sym->name,&sym->declared_at);
9199
9200       /* Get the attributes from the interface (now resolved).  */
9201       if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
9202         {
9203           gfc_symbol *ifc = sym->ts.interface;
9204           sym->ts = ifc->ts;
9205           sym->ts.interface = ifc;
9206           sym->attr.function = ifc->attr.function;
9207           sym->attr.subroutine = ifc->attr.subroutine;
9208           sym->attr.allocatable = ifc->attr.allocatable;
9209           sym->attr.pointer = ifc->attr.pointer;
9210           sym->attr.pure = ifc->attr.pure;
9211           sym->attr.elemental = ifc->attr.elemental;
9212           sym->attr.dimension = ifc->attr.dimension;
9213           sym->attr.recursive = ifc->attr.recursive;
9214           sym->attr.always_explicit = ifc->attr.always_explicit;
9215           copy_formal_args (sym, ifc);
9216           /* Copy array spec.  */
9217           sym->as = gfc_copy_array_spec (ifc->as);
9218           if (sym->as)
9219             {
9220               int i;
9221               for (i = 0; i < sym->as->rank; i++)
9222                 {
9223                   gfc_expr_replace_symbols (sym->as->lower[i], sym);
9224                   gfc_expr_replace_symbols (sym->as->upper[i], sym);
9225                 }
9226             }
9227           /* Copy char length.  */
9228           if (ifc->ts.cl)
9229             {
9230               sym->ts.cl = gfc_get_charlen();
9231               sym->ts.cl->resolved = ifc->ts.cl->resolved;
9232               sym->ts.cl->length = gfc_copy_expr (ifc->ts.cl->length);
9233               gfc_expr_replace_symbols (sym->ts.cl->length, sym);
9234               /* Add charlen to namespace.  */
9235               if (sym->formal_ns)
9236                 {
9237                   sym->ts.cl->next = sym->formal_ns->cl_list;
9238                   sym->formal_ns->cl_list = sym->ts.cl;
9239                 }
9240             }
9241         }
9242       else if (sym->ts.interface->name[0] != '\0')
9243         {
9244           gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
9245                     sym->ts.interface->name, sym->name, &sym->declared_at);
9246           return;
9247         }
9248     }
9249
9250   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
9251     return;
9252
9253   /* Symbols that are module procedures with results (functions) have
9254      the types and array specification copied for type checking in
9255      procedures that call them, as well as for saving to a module
9256      file.  These symbols can't stand the scrutiny that their results
9257      can.  */
9258   mp_flag = (sym->result != NULL && sym->result != sym);
9259
9260
9261   /* Make sure that the intrinsic is consistent with its internal 
9262      representation. This needs to be done before assigning a default 
9263      type to avoid spurious warnings.  */
9264   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic)
9265     {
9266       gfc_intrinsic_sym* isym;
9267       const char* symstd;
9268
9269       /* We already know this one is an intrinsic, so we don't call
9270          gfc_is_intrinsic for full checking but rather use gfc_find_function and
9271          gfc_find_subroutine directly to check whether it is a function or
9272          subroutine.  */
9273
9274       if ((isym = gfc_find_function (sym->name)))
9275         {
9276           if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising)
9277             gfc_warning ("Type specified for intrinsic function '%s' at %L is"
9278                          " ignored", sym->name, &sym->declared_at);
9279         }
9280       else if ((isym = gfc_find_subroutine (sym->name)))
9281         {
9282           if (sym->ts.type != BT_UNKNOWN)
9283             {
9284               gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
9285                          " specifier", sym->name, &sym->declared_at);
9286               return;
9287             }
9288         }
9289       else
9290         {
9291           gfc_error ("'%s' declared INTRINSIC at %L does not exist",
9292                      sym->name, &sym->declared_at);
9293           return;
9294         }
9295
9296       /* Check it is actually available in the standard settings.  */
9297       if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
9298             == FAILURE)
9299         {
9300           gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
9301                      " available in the current standard settings but %s.  Use"
9302                      " an appropriate -std=* option or enable -fall-intrinsics"
9303                      " in order to use it.",
9304                      sym->name, &sym->declared_at, symstd);
9305           return;
9306         }
9307      }
9308
9309   /* Assign default type to symbols that need one and don't have one.  */
9310   if (sym->ts.type == BT_UNKNOWN)
9311     {
9312       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
9313         gfc_set_default_type (sym, 1, NULL);
9314
9315       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
9316         {
9317           /* The specific case of an external procedure should emit an error
9318              in the case that there is no implicit type.  */
9319           if (!mp_flag)
9320             gfc_set_default_type (sym, sym->attr.external, NULL);
9321           else
9322             {
9323               /* Result may be in another namespace.  */
9324               resolve_symbol (sym->result);
9325
9326               sym->ts = sym->result->ts;
9327               sym->as = gfc_copy_array_spec (sym->result->as);
9328               sym->attr.dimension = sym->result->attr.dimension;
9329               sym->attr.pointer = sym->result->attr.pointer;
9330               sym->attr.allocatable = sym->result->attr.allocatable;
9331             }
9332         }
9333     }
9334
9335   /* Assumed size arrays and assumed shape arrays must be dummy
9336      arguments.  */
9337
9338   if (sym->as != NULL
9339       && (sym->as->type == AS_ASSUMED_SIZE
9340           || sym->as->type == AS_ASSUMED_SHAPE)
9341       && sym->attr.dummy == 0)
9342     {
9343       if (sym->as->type == AS_ASSUMED_SIZE)
9344         gfc_error ("Assumed size array at %L must be a dummy argument",
9345                    &sym->declared_at);
9346       else
9347         gfc_error ("Assumed shape array at %L must be a dummy argument",
9348                    &sym->declared_at);
9349       return;
9350     }
9351
9352   /* Make sure symbols with known intent or optional are really dummy
9353      variable.  Because of ENTRY statement, this has to be deferred
9354      until resolution time.  */
9355
9356   if (!sym->attr.dummy
9357       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
9358     {
9359       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
9360       return;
9361     }
9362
9363   if (sym->attr.value && !sym->attr.dummy)
9364     {
9365       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
9366                  "it is not a dummy argument", sym->name, &sym->declared_at);
9367       return;
9368     }
9369
9370   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
9371     {
9372       gfc_charlen *cl = sym->ts.cl;
9373       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
9374         {
9375           gfc_error ("Character dummy variable '%s' at %L with VALUE "
9376                      "attribute must have constant length",
9377                      sym->name, &sym->declared_at);
9378           return;
9379         }
9380
9381       if (sym->ts.is_c_interop
9382           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
9383         {
9384           gfc_error ("C interoperable character dummy variable '%s' at %L "
9385                      "with VALUE attribute must have length one",
9386                      sym->name, &sym->declared_at);
9387           return;
9388         }
9389     }
9390
9391   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
9392      do this for something that was implicitly typed because that is handled
9393      in gfc_set_default_type.  Handle dummy arguments and procedure
9394      definitions separately.  Also, anything that is use associated is not
9395      handled here but instead is handled in the module it is declared in.
9396      Finally, derived type definitions are allowed to be BIND(C) since that
9397      only implies that they're interoperable, and they are checked fully for
9398      interoperability when a variable is declared of that type.  */
9399   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
9400       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
9401       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
9402     {
9403       gfc_try t = SUCCESS;
9404       
9405       /* First, make sure the variable is declared at the
9406          module-level scope (J3/04-007, Section 15.3).  */
9407       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
9408           sym->attr.in_common == 0)
9409         {
9410           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
9411                      "is neither a COMMON block nor declared at the "
9412                      "module level scope", sym->name, &(sym->declared_at));
9413           t = FAILURE;
9414         }
9415       else if (sym->common_head != NULL)
9416         {
9417           t = verify_com_block_vars_c_interop (sym->common_head);
9418         }
9419       else
9420         {
9421           /* If type() declaration, we need to verify that the components
9422              of the given type are all C interoperable, etc.  */
9423           if (sym->ts.type == BT_DERIVED &&
9424               sym->ts.derived->attr.is_c_interop != 1)
9425             {
9426               /* Make sure the user marked the derived type as BIND(C).  If
9427                  not, call the verify routine.  This could print an error
9428                  for the derived type more than once if multiple variables
9429                  of that type are declared.  */
9430               if (sym->ts.derived->attr.is_bind_c != 1)
9431                 verify_bind_c_derived_type (sym->ts.derived);
9432               t = FAILURE;
9433             }
9434           
9435           /* Verify the variable itself as C interoperable if it
9436              is BIND(C).  It is not possible for this to succeed if
9437              the verify_bind_c_derived_type failed, so don't have to handle
9438              any error returned by verify_bind_c_derived_type.  */
9439           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
9440                                  sym->common_block);
9441         }
9442
9443       if (t == FAILURE)
9444         {
9445           /* clear the is_bind_c flag to prevent reporting errors more than
9446              once if something failed.  */
9447           sym->attr.is_bind_c = 0;
9448           return;
9449         }
9450     }
9451
9452   /* If a derived type symbol has reached this point, without its
9453      type being declared, we have an error.  Notice that most
9454      conditions that produce undefined derived types have already
9455      been dealt with.  However, the likes of:
9456      implicit type(t) (t) ..... call foo (t) will get us here if
9457      the type is not declared in the scope of the implicit
9458      statement. Change the type to BT_UNKNOWN, both because it is so
9459      and to prevent an ICE.  */
9460   if (sym->ts.type == BT_DERIVED && sym->ts.derived->components == NULL
9461       && !sym->ts.derived->attr.zero_comp)
9462     {
9463       gfc_error ("The derived type '%s' at %L is of type '%s', "
9464                  "which has not been defined", sym->name,
9465                   &sym->declared_at, sym->ts.derived->name);
9466       sym->ts.type = BT_UNKNOWN;
9467       return;
9468     }
9469
9470   /* Make sure that the derived type has been resolved and that the
9471      derived type is visible in the symbol's namespace, if it is a
9472      module function and is not PRIVATE.  */
9473   if (sym->ts.type == BT_DERIVED
9474         && sym->ts.derived->attr.use_assoc
9475         && sym->ns->proc_name
9476         && sym->ns->proc_name->attr.flavor == FL_MODULE)
9477     {
9478       gfc_symbol *ds;
9479
9480       if (resolve_fl_derived (sym->ts.derived) == FAILURE)
9481         return;
9482
9483       gfc_find_symbol (sym->ts.derived->name, sym->ns, 1, &ds);
9484       if (!ds && sym->attr.function
9485             && gfc_check_access (sym->attr.access, sym->ns->default_access))
9486         {
9487           symtree = gfc_new_symtree (&sym->ns->sym_root,
9488                                      sym->ts.derived->name);
9489           symtree->n.sym = sym->ts.derived;
9490           sym->ts.derived->refs++;
9491         }
9492     }
9493
9494   /* Unless the derived-type declaration is use associated, Fortran 95
9495      does not allow public entries of private derived types.
9496      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
9497      161 in 95-006r3.  */
9498   if (sym->ts.type == BT_DERIVED
9499       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
9500       && !sym->ts.derived->attr.use_assoc
9501       && gfc_check_access (sym->attr.access, sym->ns->default_access)
9502       && !gfc_check_access (sym->ts.derived->attr.access,
9503                             sym->ts.derived->ns->default_access)
9504       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
9505                          "of PRIVATE derived type '%s'",
9506                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
9507                          : "variable", sym->name, &sym->declared_at,
9508                          sym->ts.derived->name) == FAILURE)
9509     return;
9510
9511   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
9512      default initialization is defined (5.1.2.4.4).  */
9513   if (sym->ts.type == BT_DERIVED
9514       && sym->attr.dummy
9515       && sym->attr.intent == INTENT_OUT
9516       && sym->as
9517       && sym->as->type == AS_ASSUMED_SIZE)
9518     {
9519       for (c = sym->ts.derived->components; c; c = c->next)
9520         {
9521           if (c->initializer)
9522             {
9523               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
9524                          "ASSUMED SIZE and so cannot have a default initializer",
9525                          sym->name, &sym->declared_at);
9526               return;
9527             }
9528         }
9529     }
9530
9531   switch (sym->attr.flavor)
9532     {
9533     case FL_VARIABLE:
9534       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
9535         return;
9536       break;
9537
9538     case FL_PROCEDURE:
9539       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
9540         return;
9541       break;
9542
9543     case FL_NAMELIST:
9544       if (resolve_fl_namelist (sym) == FAILURE)
9545         return;
9546       break;
9547
9548     case FL_PARAMETER:
9549       if (resolve_fl_parameter (sym) == FAILURE)
9550         return;
9551       break;
9552
9553     default:
9554       break;
9555     }
9556
9557   /* Resolve array specifier. Check as well some constraints
9558      on COMMON blocks.  */
9559
9560   check_constant = sym->attr.in_common && !sym->attr.pointer;
9561
9562   /* Set the formal_arg_flag so that check_conflict will not throw
9563      an error for host associated variables in the specification
9564      expression for an array_valued function.  */
9565   if (sym->attr.function && sym->as)
9566     formal_arg_flag = 1;
9567
9568   gfc_resolve_array_spec (sym->as, check_constant);
9569
9570   formal_arg_flag = 0;
9571
9572   /* Resolve formal namespaces.  */
9573   if (sym->formal_ns && sym->formal_ns != gfc_current_ns)
9574     gfc_resolve (sym->formal_ns);
9575
9576   /* Check threadprivate restrictions.  */
9577   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
9578       && (!sym->attr.in_common
9579           && sym->module == NULL
9580           && (sym->ns->proc_name == NULL
9581               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
9582     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
9583
9584   /* If we have come this far we can apply default-initializers, as
9585      described in 14.7.5, to those variables that have not already
9586      been assigned one.  */
9587   if (sym->ts.type == BT_DERIVED
9588       && sym->attr.referenced
9589       && sym->ns == gfc_current_ns
9590       && !sym->value
9591       && !sym->attr.allocatable
9592       && !sym->attr.alloc_comp)
9593     {
9594       symbol_attribute *a = &sym->attr;
9595
9596       if ((!a->save && !a->dummy && !a->pointer
9597            && !a->in_common && !a->use_assoc
9598            && !(a->function && sym != sym->result))
9599           || (a->dummy && a->intent == INTENT_OUT))
9600         apply_default_init (sym);
9601     }
9602
9603   /* If this symbol has a type-spec, check it.  */
9604   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
9605       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
9606     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
9607           == FAILURE)
9608       return;
9609 }
9610
9611
9612 /************* Resolve DATA statements *************/
9613
9614 static struct
9615 {
9616   gfc_data_value *vnode;
9617   mpz_t left;
9618 }
9619 values;
9620
9621
9622 /* Advance the values structure to point to the next value in the data list.  */
9623
9624 static gfc_try
9625 next_data_value (void)
9626 {
9627
9628   while (mpz_cmp_ui (values.left, 0) == 0)
9629     {
9630       if (values.vnode->next == NULL)
9631         return FAILURE;
9632
9633       values.vnode = values.vnode->next;
9634       mpz_set (values.left, values.vnode->repeat);
9635     }
9636
9637   return SUCCESS;
9638 }
9639
9640
9641 static gfc_try
9642 check_data_variable (gfc_data_variable *var, locus *where)
9643 {
9644   gfc_expr *e;
9645   mpz_t size;
9646   mpz_t offset;
9647   gfc_try t;
9648   ar_type mark = AR_UNKNOWN;
9649   int i;
9650   mpz_t section_index[GFC_MAX_DIMENSIONS];
9651   gfc_ref *ref;
9652   gfc_array_ref *ar;
9653   gfc_symbol *sym;
9654   int has_pointer;
9655
9656   if (gfc_resolve_expr (var->expr) == FAILURE)
9657     return FAILURE;
9658
9659   ar = NULL;
9660   mpz_init_set_si (offset, 0);
9661   e = var->expr;
9662
9663   if (e->expr_type != EXPR_VARIABLE)
9664     gfc_internal_error ("check_data_variable(): Bad expression");
9665
9666   sym = e->symtree->n.sym;
9667
9668   if (sym->ns->is_block_data && !sym->attr.in_common)
9669     {
9670       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
9671                  sym->name, &sym->declared_at);
9672     }
9673
9674   if (e->ref == NULL && sym->as)
9675     {
9676       gfc_error ("DATA array '%s' at %L must be specified in a previous"
9677                  " declaration", sym->name, where);
9678       return FAILURE;
9679     }
9680
9681   has_pointer = sym->attr.pointer;
9682
9683   for (ref = e->ref; ref; ref = ref->next)
9684     {
9685       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
9686         has_pointer = 1;
9687
9688       if (has_pointer
9689             && ref->type == REF_ARRAY
9690             && ref->u.ar.type != AR_FULL)
9691           {
9692             gfc_error ("DATA element '%s' at %L is a pointer and so must "
9693                         "be a full array", sym->name, where);
9694             return FAILURE;
9695           }
9696     }
9697
9698   if (e->rank == 0 || has_pointer)
9699     {
9700       mpz_init_set_ui (size, 1);
9701       ref = NULL;
9702     }
9703   else
9704     {
9705       ref = e->ref;
9706
9707       /* Find the array section reference.  */
9708       for (ref = e->ref; ref; ref = ref->next)
9709         {
9710           if (ref->type != REF_ARRAY)
9711             continue;
9712           if (ref->u.ar.type == AR_ELEMENT)
9713             continue;
9714           break;
9715         }
9716       gcc_assert (ref);
9717
9718       /* Set marks according to the reference pattern.  */
9719       switch (ref->u.ar.type)
9720         {
9721         case AR_FULL:
9722           mark = AR_FULL;
9723           break;
9724
9725         case AR_SECTION:
9726           ar = &ref->u.ar;
9727           /* Get the start position of array section.  */
9728           gfc_get_section_index (ar, section_index, &offset);
9729           mark = AR_SECTION;
9730           break;
9731
9732         default:
9733           gcc_unreachable ();
9734         }
9735
9736       if (gfc_array_size (e, &size) == FAILURE)
9737         {
9738           gfc_error ("Nonconstant array section at %L in DATA statement",
9739                      &e->where);
9740           mpz_clear (offset);
9741           return FAILURE;
9742         }
9743     }
9744
9745   t = SUCCESS;
9746
9747   while (mpz_cmp_ui (size, 0) > 0)
9748     {
9749       if (next_data_value () == FAILURE)
9750         {
9751           gfc_error ("DATA statement at %L has more variables than values",
9752                      where);
9753           t = FAILURE;
9754           break;
9755         }
9756
9757       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
9758       if (t == FAILURE)
9759         break;
9760
9761       /* If we have more than one element left in the repeat count,
9762          and we have more than one element left in the target variable,
9763          then create a range assignment.  */
9764       /* FIXME: Only done for full arrays for now, since array sections
9765          seem tricky.  */
9766       if (mark == AR_FULL && ref && ref->next == NULL
9767           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
9768         {
9769           mpz_t range;
9770
9771           if (mpz_cmp (size, values.left) >= 0)
9772             {
9773               mpz_init_set (range, values.left);
9774               mpz_sub (size, size, values.left);
9775               mpz_set_ui (values.left, 0);
9776             }
9777           else
9778             {
9779               mpz_init_set (range, size);
9780               mpz_sub (values.left, values.left, size);
9781               mpz_set_ui (size, 0);
9782             }
9783
9784           gfc_assign_data_value_range (var->expr, values.vnode->expr,
9785                                        offset, range);
9786
9787           mpz_add (offset, offset, range);
9788           mpz_clear (range);
9789         }
9790
9791       /* Assign initial value to symbol.  */
9792       else
9793         {
9794           mpz_sub_ui (values.left, values.left, 1);
9795           mpz_sub_ui (size, size, 1);
9796
9797           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
9798           if (t == FAILURE)
9799             break;
9800
9801           if (mark == AR_FULL)
9802             mpz_add_ui (offset, offset, 1);
9803
9804           /* Modify the array section indexes and recalculate the offset
9805              for next element.  */
9806           else if (mark == AR_SECTION)
9807             gfc_advance_section (section_index, ar, &offset);
9808         }
9809     }
9810
9811   if (mark == AR_SECTION)
9812     {
9813       for (i = 0; i < ar->dimen; i++)
9814         mpz_clear (section_index[i]);
9815     }
9816
9817   mpz_clear (size);
9818   mpz_clear (offset);
9819
9820   return t;
9821 }
9822
9823
9824 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
9825
9826 /* Iterate over a list of elements in a DATA statement.  */
9827
9828 static gfc_try
9829 traverse_data_list (gfc_data_variable *var, locus *where)
9830 {
9831   mpz_t trip;
9832   iterator_stack frame;
9833   gfc_expr *e, *start, *end, *step;
9834   gfc_try retval = SUCCESS;
9835
9836   mpz_init (frame.value);
9837
9838   start = gfc_copy_expr (var->iter.start);
9839   end = gfc_copy_expr (var->iter.end);
9840   step = gfc_copy_expr (var->iter.step);
9841
9842   if (gfc_simplify_expr (start, 1) == FAILURE
9843       || start->expr_type != EXPR_CONSTANT)
9844     {
9845       gfc_error ("iterator start at %L does not simplify", &start->where);
9846       retval = FAILURE;
9847       goto cleanup;
9848     }
9849   if (gfc_simplify_expr (end, 1) == FAILURE
9850       || end->expr_type != EXPR_CONSTANT)
9851     {
9852       gfc_error ("iterator end at %L does not simplify", &end->where);
9853       retval = FAILURE;
9854       goto cleanup;
9855     }
9856   if (gfc_simplify_expr (step, 1) == FAILURE
9857       || step->expr_type != EXPR_CONSTANT)
9858     {
9859       gfc_error ("iterator step at %L does not simplify", &step->where);
9860       retval = FAILURE;
9861       goto cleanup;
9862     }
9863
9864   mpz_init_set (trip, end->value.integer);
9865   mpz_sub (trip, trip, start->value.integer);
9866   mpz_add (trip, trip, step->value.integer);
9867
9868   mpz_div (trip, trip, step->value.integer);
9869
9870   mpz_set (frame.value, start->value.integer);
9871
9872   frame.prev = iter_stack;
9873   frame.variable = var->iter.var->symtree;
9874   iter_stack = &frame;
9875
9876   while (mpz_cmp_ui (trip, 0) > 0)
9877     {
9878       if (traverse_data_var (var->list, where) == FAILURE)
9879         {
9880           mpz_clear (trip);
9881           retval = FAILURE;
9882           goto cleanup;
9883         }
9884
9885       e = gfc_copy_expr (var->expr);
9886       if (gfc_simplify_expr (e, 1) == FAILURE)
9887         {
9888           gfc_free_expr (e);
9889           mpz_clear (trip);
9890           retval = FAILURE;
9891           goto cleanup;
9892         }
9893
9894       mpz_add (frame.value, frame.value, step->value.integer);
9895
9896       mpz_sub_ui (trip, trip, 1);
9897     }
9898
9899   mpz_clear (trip);
9900 cleanup:
9901   mpz_clear (frame.value);
9902
9903   gfc_free_expr (start);
9904   gfc_free_expr (end);
9905   gfc_free_expr (step);
9906
9907   iter_stack = frame.prev;
9908   return retval;
9909 }
9910
9911
9912 /* Type resolve variables in the variable list of a DATA statement.  */
9913
9914 static gfc_try
9915 traverse_data_var (gfc_data_variable *var, locus *where)
9916 {
9917   gfc_try t;
9918
9919   for (; var; var = var->next)
9920     {
9921       if (var->expr == NULL)
9922         t = traverse_data_list (var, where);
9923       else
9924         t = check_data_variable (var, where);
9925
9926       if (t == FAILURE)
9927         return FAILURE;
9928     }
9929
9930   return SUCCESS;
9931 }
9932
9933
9934 /* Resolve the expressions and iterators associated with a data statement.
9935    This is separate from the assignment checking because data lists should
9936    only be resolved once.  */
9937
9938 static gfc_try
9939 resolve_data_variables (gfc_data_variable *d)
9940 {
9941   for (; d; d = d->next)
9942     {
9943       if (d->list == NULL)
9944         {
9945           if (gfc_resolve_expr (d->expr) == FAILURE)
9946             return FAILURE;
9947         }
9948       else
9949         {
9950           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
9951             return FAILURE;
9952
9953           if (resolve_data_variables (d->list) == FAILURE)
9954             return FAILURE;
9955         }
9956     }
9957
9958   return SUCCESS;
9959 }
9960
9961
9962 /* Resolve a single DATA statement.  We implement this by storing a pointer to
9963    the value list into static variables, and then recursively traversing the
9964    variables list, expanding iterators and such.  */
9965
9966 static void
9967 resolve_data (gfc_data *d)
9968 {
9969
9970   if (resolve_data_variables (d->var) == FAILURE)
9971     return;
9972
9973   values.vnode = d->value;
9974   if (d->value == NULL)
9975     mpz_set_ui (values.left, 0);
9976   else
9977     mpz_set (values.left, d->value->repeat);
9978
9979   if (traverse_data_var (d->var, &d->where) == FAILURE)
9980     return;
9981
9982   /* At this point, we better not have any values left.  */
9983
9984   if (next_data_value () == SUCCESS)
9985     gfc_error ("DATA statement at %L has more values than variables",
9986                &d->where);
9987 }
9988
9989
9990 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
9991    accessed by host or use association, is a dummy argument to a pure function,
9992    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
9993    is storage associated with any such variable, shall not be used in the
9994    following contexts: (clients of this function).  */
9995
9996 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
9997    procedure.  Returns zero if assignment is OK, nonzero if there is a
9998    problem.  */
9999 int
10000 gfc_impure_variable (gfc_symbol *sym)
10001 {
10002   gfc_symbol *proc;
10003
10004   if (sym->attr.use_assoc || sym->attr.in_common)
10005     return 1;
10006
10007   if (sym->ns != gfc_current_ns)
10008     return !sym->attr.function;
10009
10010   proc = sym->ns->proc_name;
10011   if (sym->attr.dummy && gfc_pure (proc)
10012         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
10013                 ||
10014              proc->attr.function))
10015     return 1;
10016
10017   /* TODO: Sort out what can be storage associated, if anything, and include
10018      it here.  In principle equivalences should be scanned but it does not
10019      seem to be possible to storage associate an impure variable this way.  */
10020   return 0;
10021 }
10022
10023
10024 /* Test whether a symbol is pure or not.  For a NULL pointer, checks the
10025    symbol of the current procedure.  */
10026
10027 int
10028 gfc_pure (gfc_symbol *sym)
10029 {
10030   symbol_attribute attr;
10031
10032   if (sym == NULL)
10033     sym = gfc_current_ns->proc_name;
10034   if (sym == NULL)
10035     return 0;
10036
10037   attr = sym->attr;
10038
10039   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
10040 }
10041
10042
10043 /* Test whether the current procedure is elemental or not.  */
10044
10045 int
10046 gfc_elemental (gfc_symbol *sym)
10047 {
10048   symbol_attribute attr;
10049
10050   if (sym == NULL)
10051     sym = gfc_current_ns->proc_name;
10052   if (sym == NULL)
10053     return 0;
10054   attr = sym->attr;
10055
10056   return attr.flavor == FL_PROCEDURE && attr.elemental;
10057 }
10058
10059
10060 /* Warn about unused labels.  */
10061
10062 static void
10063 warn_unused_fortran_label (gfc_st_label *label)
10064 {
10065   if (label == NULL)
10066     return;
10067
10068   warn_unused_fortran_label (label->left);
10069
10070   if (label->defined == ST_LABEL_UNKNOWN)
10071     return;
10072
10073   switch (label->referenced)
10074     {
10075     case ST_LABEL_UNKNOWN:
10076       gfc_warning ("Label %d at %L defined but not used", label->value,
10077                    &label->where);
10078       break;
10079
10080     case ST_LABEL_BAD_TARGET:
10081       gfc_warning ("Label %d at %L defined but cannot be used",
10082                    label->value, &label->where);
10083       break;
10084
10085     default:
10086       break;
10087     }
10088
10089   warn_unused_fortran_label (label->right);
10090 }
10091
10092
10093 /* Returns the sequence type of a symbol or sequence.  */
10094
10095 static seq_type
10096 sequence_type (gfc_typespec ts)
10097 {
10098   seq_type result;
10099   gfc_component *c;
10100
10101   switch (ts.type)
10102   {
10103     case BT_DERIVED:
10104
10105       if (ts.derived->components == NULL)
10106         return SEQ_NONDEFAULT;
10107
10108       result = sequence_type (ts.derived->components->ts);
10109       for (c = ts.derived->components->next; c; c = c->next)
10110         if (sequence_type (c->ts) != result)
10111           return SEQ_MIXED;
10112
10113       return result;
10114
10115     case BT_CHARACTER:
10116       if (ts.kind != gfc_default_character_kind)
10117           return SEQ_NONDEFAULT;
10118
10119       return SEQ_CHARACTER;
10120
10121     case BT_INTEGER:
10122       if (ts.kind != gfc_default_integer_kind)
10123           return SEQ_NONDEFAULT;
10124
10125       return SEQ_NUMERIC;
10126
10127     case BT_REAL:
10128       if (!(ts.kind == gfc_default_real_kind
10129             || ts.kind == gfc_default_double_kind))
10130           return SEQ_NONDEFAULT;
10131
10132       return SEQ_NUMERIC;
10133
10134     case BT_COMPLEX:
10135       if (ts.kind != gfc_default_complex_kind)
10136           return SEQ_NONDEFAULT;
10137
10138       return SEQ_NUMERIC;
10139
10140     case BT_LOGICAL:
10141       if (ts.kind != gfc_default_logical_kind)
10142           return SEQ_NONDEFAULT;
10143
10144       return SEQ_NUMERIC;
10145
10146     default:
10147       return SEQ_NONDEFAULT;
10148   }
10149 }
10150
10151
10152 /* Resolve derived type EQUIVALENCE object.  */
10153
10154 static gfc_try
10155 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
10156 {
10157   gfc_symbol *d;
10158   gfc_component *c = derived->components;
10159
10160   if (!derived)
10161     return SUCCESS;
10162
10163   /* Shall not be an object of nonsequence derived type.  */
10164   if (!derived->attr.sequence)
10165     {
10166       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
10167                  "attribute to be an EQUIVALENCE object", sym->name,
10168                  &e->where);
10169       return FAILURE;
10170     }
10171
10172   /* Shall not have allocatable components.  */
10173   if (derived->attr.alloc_comp)
10174     {
10175       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
10176                  "components to be an EQUIVALENCE object",sym->name,
10177                  &e->where);
10178       return FAILURE;
10179     }
10180
10181   if (sym->attr.in_common && has_default_initializer (sym->ts.derived))
10182     {
10183       gfc_error ("Derived type variable '%s' at %L with default "
10184                  "initialization cannot be in EQUIVALENCE with a variable "
10185                  "in COMMON", sym->name, &e->where);
10186       return FAILURE;
10187     }
10188
10189   for (; c ; c = c->next)
10190     {
10191       d = c->ts.derived;
10192       if (d
10193           && (resolve_equivalence_derived (c->ts.derived, sym, e) == FAILURE))
10194         return FAILURE;
10195
10196       /* Shall not be an object of sequence derived type containing a pointer
10197          in the structure.  */
10198       if (c->attr.pointer)
10199         {
10200           gfc_error ("Derived type variable '%s' at %L with pointer "
10201                      "component(s) cannot be an EQUIVALENCE object",
10202                      sym->name, &e->where);
10203           return FAILURE;
10204         }
10205     }
10206   return SUCCESS;
10207 }
10208
10209
10210 /* Resolve equivalence object. 
10211    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
10212    an allocatable array, an object of nonsequence derived type, an object of
10213    sequence derived type containing a pointer at any level of component
10214    selection, an automatic object, a function name, an entry name, a result
10215    name, a named constant, a structure component, or a subobject of any of
10216    the preceding objects.  A substring shall not have length zero.  A
10217    derived type shall not have components with default initialization nor
10218    shall two objects of an equivalence group be initialized.
10219    Either all or none of the objects shall have an protected attribute.
10220    The simple constraints are done in symbol.c(check_conflict) and the rest
10221    are implemented here.  */
10222
10223 static void
10224 resolve_equivalence (gfc_equiv *eq)
10225 {
10226   gfc_symbol *sym;
10227   gfc_symbol *derived;
10228   gfc_symbol *first_sym;
10229   gfc_expr *e;
10230   gfc_ref *r;
10231   locus *last_where = NULL;
10232   seq_type eq_type, last_eq_type;
10233   gfc_typespec *last_ts;
10234   int object, cnt_protected;
10235   const char *value_name;
10236   const char *msg;
10237
10238   value_name = NULL;
10239   last_ts = &eq->expr->symtree->n.sym->ts;
10240
10241   first_sym = eq->expr->symtree->n.sym;
10242
10243   cnt_protected = 0;
10244
10245   for (object = 1; eq; eq = eq->eq, object++)
10246     {
10247       e = eq->expr;
10248
10249       e->ts = e->symtree->n.sym->ts;
10250       /* match_varspec might not know yet if it is seeing
10251          array reference or substring reference, as it doesn't
10252          know the types.  */
10253       if (e->ref && e->ref->type == REF_ARRAY)
10254         {
10255           gfc_ref *ref = e->ref;
10256           sym = e->symtree->n.sym;
10257
10258           if (sym->attr.dimension)
10259             {
10260               ref->u.ar.as = sym->as;
10261               ref = ref->next;
10262             }
10263
10264           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
10265           if (e->ts.type == BT_CHARACTER
10266               && ref
10267               && ref->type == REF_ARRAY
10268               && ref->u.ar.dimen == 1
10269               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
10270               && ref->u.ar.stride[0] == NULL)
10271             {
10272               gfc_expr *start = ref->u.ar.start[0];
10273               gfc_expr *end = ref->u.ar.end[0];
10274               void *mem = NULL;
10275
10276               /* Optimize away the (:) reference.  */
10277               if (start == NULL && end == NULL)
10278                 {
10279                   if (e->ref == ref)
10280                     e->ref = ref->next;
10281                   else
10282                     e->ref->next = ref->next;
10283                   mem = ref;
10284                 }
10285               else
10286                 {
10287                   ref->type = REF_SUBSTRING;
10288                   if (start == NULL)
10289                     start = gfc_int_expr (1);
10290                   ref->u.ss.start = start;
10291                   if (end == NULL && e->ts.cl)
10292                     end = gfc_copy_expr (e->ts.cl->length);
10293                   ref->u.ss.end = end;
10294                   ref->u.ss.length = e->ts.cl;
10295                   e->ts.cl = NULL;
10296                 }
10297               ref = ref->next;
10298               gfc_free (mem);
10299             }
10300
10301           /* Any further ref is an error.  */
10302           if (ref)
10303             {
10304               gcc_assert (ref->type == REF_ARRAY);
10305               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
10306                          &ref->u.ar.where);
10307               continue;
10308             }
10309         }
10310
10311       if (gfc_resolve_expr (e) == FAILURE)
10312         continue;
10313
10314       sym = e->symtree->n.sym;
10315
10316       if (sym->attr.is_protected)
10317         cnt_protected++;
10318       if (cnt_protected > 0 && cnt_protected != object)
10319         {
10320               gfc_error ("Either all or none of the objects in the "
10321                          "EQUIVALENCE set at %L shall have the "
10322                          "PROTECTED attribute",
10323                          &e->where);
10324               break;
10325         }
10326
10327       /* Shall not equivalence common block variables in a PURE procedure.  */
10328       if (sym->ns->proc_name
10329           && sym->ns->proc_name->attr.pure
10330           && sym->attr.in_common)
10331         {
10332           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
10333                      "object in the pure procedure '%s'",
10334                      sym->name, &e->where, sym->ns->proc_name->name);
10335           break;
10336         }
10337
10338       /* Shall not be a named constant.  */
10339       if (e->expr_type == EXPR_CONSTANT)
10340         {
10341           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
10342                      "object", sym->name, &e->where);
10343           continue;
10344         }
10345
10346       derived = e->ts.derived;
10347       if (derived && resolve_equivalence_derived (derived, sym, e) == FAILURE)
10348         continue;
10349
10350       /* Check that the types correspond correctly:
10351          Note 5.28:
10352          A numeric sequence structure may be equivalenced to another sequence
10353          structure, an object of default integer type, default real type, double
10354          precision real type, default logical type such that components of the
10355          structure ultimately only become associated to objects of the same
10356          kind. A character sequence structure may be equivalenced to an object
10357          of default character kind or another character sequence structure.
10358          Other objects may be equivalenced only to objects of the same type and
10359          kind parameters.  */
10360
10361       /* Identical types are unconditionally OK.  */
10362       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
10363         goto identical_types;
10364
10365       last_eq_type = sequence_type (*last_ts);
10366       eq_type = sequence_type (sym->ts);
10367
10368       /* Since the pair of objects is not of the same type, mixed or
10369          non-default sequences can be rejected.  */
10370
10371       msg = "Sequence %s with mixed components in EQUIVALENCE "
10372             "statement at %L with different type objects";
10373       if ((object ==2
10374            && last_eq_type == SEQ_MIXED
10375            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
10376               == FAILURE)
10377           || (eq_type == SEQ_MIXED
10378               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
10379                                  &e->where) == FAILURE))
10380         continue;
10381
10382       msg = "Non-default type object or sequence %s in EQUIVALENCE "
10383             "statement at %L with objects of different type";
10384       if ((object ==2
10385            && last_eq_type == SEQ_NONDEFAULT
10386            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
10387                               last_where) == FAILURE)
10388           || (eq_type == SEQ_NONDEFAULT
10389               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
10390                                  &e->where) == FAILURE))
10391         continue;
10392
10393       msg ="Non-CHARACTER object '%s' in default CHARACTER "
10394            "EQUIVALENCE statement at %L";
10395       if (last_eq_type == SEQ_CHARACTER
10396           && eq_type != SEQ_CHARACTER
10397           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
10398                              &e->where) == FAILURE)
10399                 continue;
10400
10401       msg ="Non-NUMERIC object '%s' in default NUMERIC "
10402            "EQUIVALENCE statement at %L";
10403       if (last_eq_type == SEQ_NUMERIC
10404           && eq_type != SEQ_NUMERIC
10405           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
10406                              &e->where) == FAILURE)
10407                 continue;
10408
10409   identical_types:
10410       last_ts =&sym->ts;
10411       last_where = &e->where;
10412
10413       if (!e->ref)
10414         continue;
10415
10416       /* Shall not be an automatic array.  */
10417       if (e->ref->type == REF_ARRAY
10418           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
10419         {
10420           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
10421                      "an EQUIVALENCE object", sym->name, &e->where);
10422           continue;
10423         }
10424
10425       r = e->ref;
10426       while (r)
10427         {
10428           /* Shall not be a structure component.  */
10429           if (r->type == REF_COMPONENT)
10430             {
10431               gfc_error ("Structure component '%s' at %L cannot be an "
10432                          "EQUIVALENCE object",
10433                          r->u.c.component->name, &e->where);
10434               break;
10435             }
10436
10437           /* A substring shall not have length zero.  */
10438           if (r->type == REF_SUBSTRING)
10439             {
10440               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
10441                 {
10442                   gfc_error ("Substring at %L has length zero",
10443                              &r->u.ss.start->where);
10444                   break;
10445                 }
10446             }
10447           r = r->next;
10448         }
10449     }
10450 }
10451
10452
10453 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
10454
10455 static void
10456 resolve_fntype (gfc_namespace *ns)
10457 {
10458   gfc_entry_list *el;
10459   gfc_symbol *sym;
10460
10461   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
10462     return;
10463
10464   /* If there are any entries, ns->proc_name is the entry master
10465      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
10466   if (ns->entries)
10467     sym = ns->entries->sym;
10468   else
10469     sym = ns->proc_name;
10470   if (sym->result == sym
10471       && sym->ts.type == BT_UNKNOWN
10472       && gfc_set_default_type (sym, 0, NULL) == FAILURE
10473       && !sym->attr.untyped)
10474     {
10475       gfc_error ("Function '%s' at %L has no IMPLICIT type",
10476                  sym->name, &sym->declared_at);
10477       sym->attr.untyped = 1;
10478     }
10479
10480   if (sym->ts.type == BT_DERIVED && !sym->ts.derived->attr.use_assoc
10481       && !sym->attr.contained
10482       && !gfc_check_access (sym->ts.derived->attr.access,
10483                             sym->ts.derived->ns->default_access)
10484       && gfc_check_access (sym->attr.access, sym->ns->default_access))
10485     {
10486       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
10487                       "%L of PRIVATE type '%s'", sym->name,
10488                       &sym->declared_at, sym->ts.derived->name);
10489     }
10490
10491     if (ns->entries)
10492     for (el = ns->entries->next; el; el = el->next)
10493       {
10494         if (el->sym->result == el->sym
10495             && el->sym->ts.type == BT_UNKNOWN
10496             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
10497             && !el->sym->attr.untyped)
10498           {
10499             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
10500                        el->sym->name, &el->sym->declared_at);
10501             el->sym->attr.untyped = 1;
10502           }
10503       }
10504 }
10505
10506 /* 12.3.2.1.1 Defined operators.  */
10507
10508 static void
10509 gfc_resolve_uops (gfc_symtree *symtree)
10510 {
10511   gfc_interface *itr;
10512   gfc_symbol *sym;
10513   gfc_formal_arglist *formal;
10514
10515   if (symtree == NULL)
10516     return;
10517
10518   gfc_resolve_uops (symtree->left);
10519   gfc_resolve_uops (symtree->right);
10520
10521   for (itr = symtree->n.uop->op; itr; itr = itr->next)
10522     {
10523       sym = itr->sym;
10524       if (!sym->attr.function)
10525         gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
10526                    sym->name, &sym->declared_at);
10527
10528       if (sym->ts.type == BT_CHARACTER
10529           && !(sym->ts.cl && sym->ts.cl->length)
10530           && !(sym->result && sym->result->ts.cl
10531                && sym->result->ts.cl->length))
10532         gfc_error ("User operator procedure '%s' at %L cannot be assumed "
10533                    "character length", sym->name, &sym->declared_at);
10534
10535       formal = sym->formal;
10536       if (!formal || !formal->sym)
10537         {
10538           gfc_error ("User operator procedure '%s' at %L must have at least "
10539                      "one argument", sym->name, &sym->declared_at);
10540           continue;
10541         }
10542
10543       if (formal->sym->attr.intent != INTENT_IN)
10544         gfc_error ("First argument of operator interface at %L must be "
10545                    "INTENT(IN)", &sym->declared_at);
10546
10547       if (formal->sym->attr.optional)
10548         gfc_error ("First argument of operator interface at %L cannot be "
10549                    "optional", &sym->declared_at);
10550
10551       formal = formal->next;
10552       if (!formal || !formal->sym)
10553         continue;
10554
10555       if (formal->sym->attr.intent != INTENT_IN)
10556         gfc_error ("Second argument of operator interface at %L must be "
10557                    "INTENT(IN)", &sym->declared_at);
10558
10559       if (formal->sym->attr.optional)
10560         gfc_error ("Second argument of operator interface at %L cannot be "
10561                    "optional", &sym->declared_at);
10562
10563       if (formal->next)
10564         gfc_error ("Operator interface at %L must have, at most, two "
10565                    "arguments", &sym->declared_at);
10566     }
10567 }
10568
10569
10570 /* Examine all of the expressions associated with a program unit,
10571    assign types to all intermediate expressions, make sure that all
10572    assignments are to compatible types and figure out which names
10573    refer to which functions or subroutines.  It doesn't check code
10574    block, which is handled by resolve_code.  */
10575
10576 static void
10577 resolve_types (gfc_namespace *ns)
10578 {
10579   gfc_namespace *n;
10580   gfc_charlen *cl;
10581   gfc_data *d;
10582   gfc_equiv *eq;
10583   gfc_namespace* old_ns = gfc_current_ns;
10584
10585   /* Check that all IMPLICIT types are ok.  */
10586   if (!ns->seen_implicit_none)
10587     {
10588       unsigned letter;
10589       for (letter = 0; letter != GFC_LETTERS; ++letter)
10590         if (ns->set_flag[letter]
10591             && resolve_typespec_used (&ns->default_type[letter],
10592                                       &ns->implicit_loc[letter],
10593                                       NULL) == FAILURE)
10594           return;
10595     }
10596
10597   gfc_current_ns = ns;
10598
10599   resolve_entries (ns);
10600
10601   resolve_common_vars (ns->blank_common.head, false);
10602   resolve_common_blocks (ns->common_root);
10603
10604   resolve_contained_functions (ns);
10605
10606   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
10607
10608   for (cl = ns->cl_list; cl; cl = cl->next)
10609     resolve_charlen (cl);
10610
10611   gfc_traverse_ns (ns, resolve_symbol);
10612
10613   resolve_fntype (ns);
10614
10615   for (n = ns->contained; n; n = n->sibling)
10616     {
10617       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
10618         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
10619                    "also be PURE", n->proc_name->name,
10620                    &n->proc_name->declared_at);
10621
10622       resolve_types (n);
10623     }
10624
10625   forall_flag = 0;
10626   gfc_check_interfaces (ns);
10627
10628   gfc_traverse_ns (ns, resolve_values);
10629
10630   if (ns->save_all)
10631     gfc_save_all (ns);
10632
10633   iter_stack = NULL;
10634   for (d = ns->data; d; d = d->next)
10635     resolve_data (d);
10636
10637   iter_stack = NULL;
10638   gfc_traverse_ns (ns, gfc_formalize_init_value);
10639
10640   gfc_traverse_ns (ns, gfc_verify_binding_labels);
10641
10642   if (ns->common_root != NULL)
10643     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
10644
10645   for (eq = ns->equiv; eq; eq = eq->next)
10646     resolve_equivalence (eq);
10647
10648   /* Warn about unused labels.  */
10649   if (warn_unused_label)
10650     warn_unused_fortran_label (ns->st_labels);
10651
10652   gfc_resolve_uops (ns->uop_root);
10653
10654   gfc_current_ns = old_ns;
10655 }
10656
10657
10658 /* Call resolve_code recursively.  */
10659
10660 static void
10661 resolve_codes (gfc_namespace *ns)
10662 {
10663   gfc_namespace *n;
10664   bitmap_obstack old_obstack;
10665
10666   for (n = ns->contained; n; n = n->sibling)
10667     resolve_codes (n);
10668
10669   gfc_current_ns = ns;
10670   cs_base = NULL;
10671   /* Set to an out of range value.  */
10672   current_entry_id = -1;
10673
10674   old_obstack = labels_obstack;
10675   bitmap_obstack_initialize (&labels_obstack);
10676
10677   resolve_code (ns->code, ns);
10678
10679   bitmap_obstack_release (&labels_obstack);
10680   labels_obstack = old_obstack;
10681 }
10682
10683
10684 /* This function is called after a complete program unit has been compiled.
10685    Its purpose is to examine all of the expressions associated with a program
10686    unit, assign types to all intermediate expressions, make sure that all
10687    assignments are to compatible types and figure out which names refer to
10688    which functions or subroutines.  */
10689
10690 void
10691 gfc_resolve (gfc_namespace *ns)
10692 {
10693   gfc_namespace *old_ns;
10694
10695   if (ns->resolved)
10696     return;
10697
10698   old_ns = gfc_current_ns;
10699
10700   resolve_types (ns);
10701   resolve_codes (ns);
10702
10703   gfc_current_ns = old_ns;
10704   ns->resolved = 1;
10705 }