OSDN Git Service

2006-12-13 Jakub Jelinek <jakub@redhat.com>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various stuctures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, 
3    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 2, 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 COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor,Boston, MA
21 02110-1301, USA.  */
22
23
24 #include "config.h"
25 #include "system.h"
26 #include "flags.h"
27 #include "gfortran.h"
28 #include "arith.h"  /* For gfc_compare_expr().  */
29 #include "dependency.h"
30
31 /* Types used in equivalence statements.  */
32
33 typedef enum seq_type
34 {
35   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
36 }
37 seq_type;
38
39 /* Stack to push the current if we descend into a block during
40    resolution.  See resolve_branch() and resolve_code().  */
41
42 typedef struct code_stack
43 {
44   struct gfc_code *head, *current;
45   struct code_stack *prev;
46 }
47 code_stack;
48
49 static code_stack *cs_base = NULL;
50
51
52 /* Nonzero if we're inside a FORALL block.  */
53
54 static int forall_flag;
55
56 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
57
58 static int omp_workshare_flag;
59
60 /* Nonzero if we are processing a formal arglist. The corresponding function
61    resets the flag each time that it is read.  */
62 static int formal_arg_flag = 0;
63
64 /* True if we are resolving a specification expression.  */
65 static int specification_expr = 0;
66
67 /* The id of the last entry seen.  */
68 static int current_entry_id;
69
70 int
71 gfc_is_formal_arg (void)
72 {
73   return formal_arg_flag;
74 }
75
76 /* Resolve types of formal argument lists.  These have to be done early so that
77    the formal argument lists of module procedures can be copied to the
78    containing module before the individual procedures are resolved
79    individually.  We also resolve argument lists of procedures in interface
80    blocks because they are self-contained scoping units.
81
82    Since a dummy argument cannot be a non-dummy procedure, the only
83    resort left for untyped names are the IMPLICIT types.  */
84
85 static void
86 resolve_formal_arglist (gfc_symbol * proc)
87 {
88   gfc_formal_arglist *f;
89   gfc_symbol *sym;
90   int i;
91
92   if (proc->result != NULL)
93     sym = proc->result;
94   else
95     sym = proc;
96
97   if (gfc_elemental (proc)
98       || sym->attr.pointer || sym->attr.allocatable
99       || (sym->as && sym->as->rank > 0))
100     proc->attr.always_explicit = 1;
101
102   formal_arg_flag = 1;
103
104   for (f = proc->formal; f; f = f->next)
105     {
106       sym = f->sym;
107
108       if (sym == NULL)
109         {
110           /* Alternate return placeholder.  */
111           if (gfc_elemental (proc))
112             gfc_error ("Alternate return specifier in elemental subroutine "
113                        "'%s' at %L is not allowed", proc->name,
114                        &proc->declared_at);
115           if (proc->attr.function)
116             gfc_error ("Alternate return specifier in function "
117                        "'%s' at %L is not allowed", proc->name,
118                        &proc->declared_at);
119           continue;
120         }
121
122       if (sym->attr.if_source != IFSRC_UNKNOWN)
123         resolve_formal_arglist (sym);
124
125       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
126         {
127           if (gfc_pure (proc) && !gfc_pure (sym))
128             {
129               gfc_error
130                 ("Dummy procedure '%s' of PURE procedure at %L must also "
131                  "be PURE", sym->name, &sym->declared_at);
132               continue;
133             }
134
135           if (gfc_elemental (proc))
136             {
137               gfc_error
138                 ("Dummy procedure at %L not allowed in ELEMENTAL procedure",
139                  &sym->declared_at);
140               continue;
141             }
142
143           continue;
144         }
145
146       if (sym->ts.type == BT_UNKNOWN)
147         {
148           if (!sym->attr.function || sym->result == sym)
149             gfc_set_default_type (sym, 1, sym->ns);
150         }
151
152       gfc_resolve_array_spec (sym->as, 0);
153
154       /* We can't tell if an array with dimension (:) is assumed or deferred
155          shape until we know if it has the pointer or allocatable attributes.
156       */
157       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
158           && !(sym->attr.pointer || sym->attr.allocatable))
159         {
160           sym->as->type = AS_ASSUMED_SHAPE;
161           for (i = 0; i < sym->as->rank; i++)
162             sym->as->lower[i] = gfc_int_expr (1);
163         }
164
165       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
166           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
167           || sym->attr.optional)
168         proc->attr.always_explicit = 1;
169
170       /* If the flavor is unknown at this point, it has to be a variable.
171          A procedure specification would have already set the type.  */
172
173       if (sym->attr.flavor == FL_UNKNOWN)
174         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
175
176       if (gfc_pure (proc))
177         {
178           if (proc->attr.function && !sym->attr.pointer
179               && sym->attr.flavor != FL_PROCEDURE
180               && sym->attr.intent != INTENT_IN)
181
182             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
183                        "INTENT(IN)", sym->name, proc->name,
184                        &sym->declared_at);
185
186           if (proc->attr.subroutine && !sym->attr.pointer
187               && sym->attr.intent == INTENT_UNKNOWN)
188
189             gfc_error
190               ("Argument '%s' of pure subroutine '%s' at %L must have "
191                "its INTENT specified", sym->name, proc->name,
192                &sym->declared_at);
193         }
194
195
196       if (gfc_elemental (proc))
197         {
198           if (sym->as != NULL)
199             {
200               gfc_error
201                 ("Argument '%s' of elemental procedure at %L must be scalar",
202                  sym->name, &sym->declared_at);
203               continue;
204             }
205
206           if (sym->attr.pointer)
207             {
208               gfc_error
209                 ("Argument '%s' of elemental procedure at %L cannot have "
210                  "the POINTER attribute", sym->name, &sym->declared_at);
211               continue;
212             }
213         }
214
215       /* Each dummy shall be specified to be scalar.  */
216       if (proc->attr.proc == PROC_ST_FUNCTION)
217         {
218           if (sym->as != NULL)
219             {
220               gfc_error
221                 ("Argument '%s' of statement function at %L must be scalar",
222                  sym->name, &sym->declared_at);
223               continue;
224             }
225
226           if (sym->ts.type == BT_CHARACTER)
227             {
228               gfc_charlen *cl = sym->ts.cl;
229               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
230                 {
231                   gfc_error
232                     ("Character-valued argument '%s' of statement function at "
233                      "%L must have constant length",
234                      sym->name, &sym->declared_at);
235                   continue;
236                 }
237             }
238         }
239     }
240   formal_arg_flag = 0;
241 }
242
243
244 /* Work function called when searching for symbols that have argument lists
245    associated with them.  */
246
247 static void
248 find_arglists (gfc_symbol * sym)
249 {
250
251   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
252     return;
253
254   resolve_formal_arglist (sym);
255 }
256
257
258 /* Given a namespace, resolve all formal argument lists within the namespace.
259  */
260
261 static void
262 resolve_formal_arglists (gfc_namespace * ns)
263 {
264
265   if (ns == NULL)
266     return;
267
268   gfc_traverse_ns (ns, find_arglists);
269 }
270
271
272 static void
273 resolve_contained_fntype (gfc_symbol * sym, gfc_namespace * ns)
274 {
275   try t;
276
277   /* If this namespace is not a function, ignore it.  */
278   if (! sym
279       || !(sym->attr.function
280            || sym->attr.flavor == FL_VARIABLE))
281     return;
282
283   /* Try to find out of what the return type is.  */
284   if (sym->result != NULL)
285     sym = sym->result;
286
287   if (sym->ts.type == BT_UNKNOWN)
288     {
289       t = gfc_set_default_type (sym, 0, ns);
290
291       if (t == FAILURE && !sym->attr.untyped)
292         {
293           gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
294                      sym->name, &sym->declared_at); /* FIXME */
295           sym->attr.untyped = 1;
296         }
297     }
298
299   /*Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character type,
300     lists the only ways a character length value of * can be used: dummy arguments
301     of procedures, named constants, and function results in external functions.
302     Internal function results are not on that list; ergo, not permitted.  */
303
304   if (sym->ts.type == BT_CHARACTER)
305     {
306       gfc_charlen *cl = sym->ts.cl;
307       if (!cl || !cl->length)
308         gfc_error ("Character-valued internal function '%s' at %L must "
309                    "not be assumed length", sym->name, &sym->declared_at);
310     }
311 }
312
313
314 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
315    introduce duplicates.  */
316
317 static void
318 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
319 {
320   gfc_formal_arglist *f, *new_arglist;
321   gfc_symbol *new_sym;
322
323   for (; new_args != NULL; new_args = new_args->next)
324     {
325       new_sym = new_args->sym;
326       /* See if this arg is already in the formal argument list.  */
327       for (f = proc->formal; f; f = f->next)
328         {
329           if (new_sym == f->sym)
330             break;
331         }
332
333       if (f)
334         continue;
335
336       /* Add a new argument.  Argument order is not important.  */
337       new_arglist = gfc_get_formal_arglist ();
338       new_arglist->sym = new_sym;
339       new_arglist->next = proc->formal;
340       proc->formal  = new_arglist;
341     }
342 }
343
344
345 /* Resolve alternate entry points.  If a symbol has multiple entry points we
346    create a new master symbol for the main routine, and turn the existing
347    symbol into an entry point.  */
348
349 static void
350 resolve_entries (gfc_namespace * ns)
351 {
352   gfc_namespace *old_ns;
353   gfc_code *c;
354   gfc_symbol *proc;
355   gfc_entry_list *el;
356   char name[GFC_MAX_SYMBOL_LEN + 1];
357   static int master_count = 0;
358
359   if (ns->proc_name == NULL)
360     return;
361
362   /* No need to do anything if this procedure doesn't have alternate entry
363      points.  */
364   if (!ns->entries)
365     return;
366
367   /* We may already have resolved alternate entry points.  */
368   if (ns->proc_name->attr.entry_master)
369     return;
370
371   /* If this isn't a procedure something has gone horribly wrong.  */
372   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
373
374   /* Remember the current namespace.  */
375   old_ns = gfc_current_ns;
376
377   gfc_current_ns = ns;
378
379   /* Add the main entry point to the list of entry points.  */
380   el = gfc_get_entry_list ();
381   el->sym = ns->proc_name;
382   el->id = 0;
383   el->next = ns->entries;
384   ns->entries = el;
385   ns->proc_name->attr.entry = 1;
386
387   /* If it is a module function, it needs to be in the right namespace
388      so that gfc_get_fake_result_decl can gather up the results. The
389      need for this arose in get_proc_name, where these beasts were
390      left in their own namespace, to keep prior references linked to
391      the entry declaration.*/
392   if (ns->proc_name->attr.function
393         && ns->parent
394         && ns->parent->proc_name->attr.flavor == FL_MODULE)
395     el->sym->ns = ns;
396
397   /* Add an entry statement for it.  */
398   c = gfc_get_code ();
399   c->op = EXEC_ENTRY;
400   c->ext.entry = el;
401   c->next = ns->code;
402   ns->code = c;
403
404   /* Create a new symbol for the master function.  */
405   /* Give the internal function a unique name (within this file).
406      Also include the function name so the user has some hope of figuring
407      out what is going on.  */
408   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
409             master_count++, ns->proc_name->name);
410   gfc_get_ha_symbol (name, &proc);
411   gcc_assert (proc != NULL);
412
413   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
414   if (ns->proc_name->attr.subroutine)
415     gfc_add_subroutine (&proc->attr, proc->name, NULL);
416   else
417     {
418       gfc_symbol *sym;
419       gfc_typespec *ts, *fts;
420       gfc_array_spec *as, *fas;
421       gfc_add_function (&proc->attr, proc->name, NULL);
422       proc->result = proc;
423       fas = ns->entries->sym->as;
424       fas = fas ? fas : ns->entries->sym->result->as;
425       fts = &ns->entries->sym->result->ts;
426       if (fts->type == BT_UNKNOWN)
427         fts = gfc_get_default_type (ns->entries->sym->result, NULL);
428       for (el = ns->entries->next; el; el = el->next)
429         {
430           ts = &el->sym->result->ts;
431           as = el->sym->as;
432           as = as ? as : el->sym->result->as;
433           if (ts->type == BT_UNKNOWN)
434             ts = gfc_get_default_type (el->sym->result, NULL);
435
436           if (! gfc_compare_types (ts, fts)
437               || (el->sym->result->attr.dimension
438                   != ns->entries->sym->result->attr.dimension)
439               || (el->sym->result->attr.pointer
440                   != ns->entries->sym->result->attr.pointer))
441             break;
442
443           else if (as && fas && gfc_compare_array_spec (as, fas) == 0)
444             gfc_error ("Procedure %s at %L has entries with mismatched "
445                        "array specifications", ns->entries->sym->name,
446                        &ns->entries->sym->declared_at);
447         }
448
449       if (el == NULL)
450         {
451           sym = ns->entries->sym->result;
452           /* All result types the same.  */
453           proc->ts = *fts;
454           if (sym->attr.dimension)
455             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
456           if (sym->attr.pointer)
457             gfc_add_pointer (&proc->attr, NULL);
458         }
459       else
460         {
461           /* Otherwise the result will be passed through a union by
462              reference.  */
463           proc->attr.mixed_entry_master = 1;
464           for (el = ns->entries; el; el = el->next)
465             {
466               sym = el->sym->result;
467               if (sym->attr.dimension)
468               {
469                 if (el == ns->entries)
470                   gfc_error
471                   ("FUNCTION result %s can't be an array in FUNCTION %s at %L",
472                    sym->name, ns->entries->sym->name, &sym->declared_at);
473                 else
474                   gfc_error
475                     ("ENTRY result %s can't be an array in FUNCTION %s at %L",
476                      sym->name, ns->entries->sym->name, &sym->declared_at);
477               }
478               else if (sym->attr.pointer)
479               {
480                 if (el == ns->entries)
481                   gfc_error
482                   ("FUNCTION result %s can't be a POINTER in FUNCTION %s at %L",
483                    sym->name, ns->entries->sym->name, &sym->declared_at);
484                 else
485                   gfc_error
486                     ("ENTRY result %s can't be a POINTER in FUNCTION %s at %L",
487                      sym->name, ns->entries->sym->name, &sym->declared_at);
488               }
489               else
490                 {
491                   ts = &sym->ts;
492                   if (ts->type == BT_UNKNOWN)
493                     ts = gfc_get_default_type (sym, NULL);
494                   switch (ts->type)
495                     {
496                     case BT_INTEGER:
497                       if (ts->kind == gfc_default_integer_kind)
498                         sym = NULL;
499                       break;
500                     case BT_REAL:
501                       if (ts->kind == gfc_default_real_kind
502                           || ts->kind == gfc_default_double_kind)
503                         sym = NULL;
504                       break;
505                     case BT_COMPLEX:
506                       if (ts->kind == gfc_default_complex_kind)
507                         sym = NULL;
508                       break;
509                     case BT_LOGICAL:
510                       if (ts->kind == gfc_default_logical_kind)
511                         sym = NULL;
512                       break;
513                     case BT_UNKNOWN:
514                       /* We will issue error elsewhere.  */
515                       sym = NULL;
516                       break;
517                     default:
518                       break;
519                     }
520                   if (sym)
521                   {
522                     if (el == ns->entries)
523                       gfc_error
524                         ("FUNCTION result %s can't be of type %s in FUNCTION %s at %L",
525                          sym->name, gfc_typename (ts), ns->entries->sym->name,
526                          &sym->declared_at);
527                     else
528                       gfc_error
529                         ("ENTRY result %s can't be of type %s in FUNCTION %s at %L",
530                          sym->name, gfc_typename (ts), ns->entries->sym->name,
531                          &sym->declared_at);
532                   }
533                 }
534             }
535         }
536     }
537   proc->attr.access = ACCESS_PRIVATE;
538   proc->attr.entry_master = 1;
539
540   /* Merge all the entry point arguments.  */
541   for (el = ns->entries; el; el = el->next)
542     merge_argument_lists (proc, el->sym->formal);
543
544   /* Use the master function for the function body.  */
545   ns->proc_name = proc;
546
547   /* Finalize the new symbols.  */
548   gfc_commit_symbols ();
549
550   /* Restore the original namespace.  */
551   gfc_current_ns = old_ns;
552 }
553
554
555 /* Resolve contained function types.  Because contained functions can call one
556    another, they have to be worked out before any of the contained procedures
557    can be resolved.
558
559    The good news is that if a function doesn't already have a type, the only
560    way it can get one is through an IMPLICIT type or a RESULT variable, because
561    by definition contained functions are contained namespace they're contained
562    in, not in a sibling or parent namespace.  */
563
564 static void
565 resolve_contained_functions (gfc_namespace * ns)
566 {
567   gfc_namespace *child;
568   gfc_entry_list *el;
569
570   resolve_formal_arglists (ns);
571
572   for (child = ns->contained; child; child = child->sibling)
573     {
574       /* Resolve alternate entry points first.  */
575       resolve_entries (child);
576
577       /* Then check function return types.  */
578       resolve_contained_fntype (child->proc_name, child);
579       for (el = child->entries; el; el = el->next)
580         resolve_contained_fntype (el->sym, child);
581     }
582 }
583
584
585 /* Resolve all of the elements of a structure constructor and make sure that
586    the types are correct.  */
587
588 static try
589 resolve_structure_cons (gfc_expr * expr)
590 {
591   gfc_constructor *cons;
592   gfc_component *comp;
593   try t;
594   symbol_attribute a;
595
596   t = SUCCESS;
597   cons = expr->value.constructor;
598   /* A constructor may have references if it is the result of substituting a
599      parameter variable.  In this case we just pull out the component we
600      want.  */
601   if (expr->ref)
602     comp = expr->ref->u.c.sym->components;
603   else
604     comp = expr->ts.derived->components;
605
606   for (; comp; comp = comp->next, cons = cons->next)
607     {
608       if (! cons->expr)
609         continue;
610
611       if (gfc_resolve_expr (cons->expr) == FAILURE)
612         {
613           t = FAILURE;
614           continue;
615         }
616
617       if (cons->expr->expr_type != EXPR_NULL
618             && comp->as && comp->as->rank != cons->expr->rank
619             && (comp->allocatable || cons->expr->rank))
620         {
621           gfc_error ("The rank of the element in the derived type "
622                      "constructor at %L does not match that of the "
623                      "component (%d/%d)", &cons->expr->where,
624                      cons->expr->rank, comp->as ? comp->as->rank : 0);
625           t = FAILURE;
626         }
627
628       /* If we don't have the right type, try to convert it.  */
629
630       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
631         {
632           t = FAILURE;
633           if (comp->pointer && cons->expr->ts.type != BT_UNKNOWN)
634             gfc_error ("The element in the derived type constructor at %L, "
635                        "for pointer component '%s', is %s but should be %s",
636                        &cons->expr->where, comp->name,
637                        gfc_basic_typename (cons->expr->ts.type),
638                        gfc_basic_typename (comp->ts.type));
639           else
640             t = gfc_convert_type (cons->expr, &comp->ts, 1);
641         }
642
643       if (!comp->pointer || cons->expr->expr_type == EXPR_NULL)
644         continue;
645
646       a = gfc_expr_attr (cons->expr);
647
648       if (!a.pointer && !a.target)
649         {
650           t = FAILURE;
651           gfc_error ("The element in the derived type constructor at %L, "
652                      "for pointer component '%s' should be a POINTER or "
653                      "a TARGET", &cons->expr->where, comp->name);
654         }
655     }
656
657   return t;
658 }
659
660
661
662 /****************** Expression name resolution ******************/
663
664 /* Returns 0 if a symbol was not declared with a type or
665    attribute declaration statement, nonzero otherwise.  */
666
667 static int
668 was_declared (gfc_symbol * sym)
669 {
670   symbol_attribute a;
671
672   a = sym->attr;
673
674   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
675     return 1;
676
677   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
678       || a.optional || a.pointer || a.save || a.target || a.volatile_ || a.value
679       || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN)
680     return 1;
681
682   return 0;
683 }
684
685
686 /* Determine if a symbol is generic or not.  */
687
688 static int
689 generic_sym (gfc_symbol * sym)
690 {
691   gfc_symbol *s;
692
693   if (sym->attr.generic ||
694       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
695     return 1;
696
697   if (was_declared (sym) || sym->ns->parent == NULL)
698     return 0;
699
700   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
701
702   return (s == NULL) ? 0 : generic_sym (s);
703 }
704
705
706 /* Determine if a symbol is specific or not.  */
707
708 static int
709 specific_sym (gfc_symbol * sym)
710 {
711   gfc_symbol *s;
712
713   if (sym->attr.if_source == IFSRC_IFBODY
714       || sym->attr.proc == PROC_MODULE
715       || sym->attr.proc == PROC_INTERNAL
716       || sym->attr.proc == PROC_ST_FUNCTION
717       || (sym->attr.intrinsic &&
718           gfc_specific_intrinsic (sym->name))
719       || sym->attr.external)
720     return 1;
721
722   if (was_declared (sym) || sym->ns->parent == NULL)
723     return 0;
724
725   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
726
727   return (s == NULL) ? 0 : specific_sym (s);
728 }
729
730
731 /* Figure out if the procedure is specific, generic or unknown.  */
732
733 typedef enum
734 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
735 proc_type;
736
737 static proc_type
738 procedure_kind (gfc_symbol * sym)
739 {
740
741   if (generic_sym (sym))
742     return PTYPE_GENERIC;
743
744   if (specific_sym (sym))
745     return PTYPE_SPECIFIC;
746
747   return PTYPE_UNKNOWN;
748 }
749
750 /* Check references to assumed size arrays.  The flag need_full_assumed_size
751    is nonzero when matching actual arguments.  */
752
753 static int need_full_assumed_size = 0;
754
755 static bool
756 check_assumed_size_reference (gfc_symbol * sym, gfc_expr * e)
757 {
758   gfc_ref * ref;
759   int dim;
760   int last = 1;
761
762   if (need_full_assumed_size
763         || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
764       return false;
765
766   for (ref = e->ref; ref; ref = ref->next)
767     if (ref->type == REF_ARRAY)
768       for (dim = 0; dim < ref->u.ar.as->rank; dim++)
769         last = (ref->u.ar.end[dim] == NULL) && (ref->u.ar.type == DIMEN_ELEMENT);
770
771   if (last)
772     {
773       gfc_error ("The upper bound in the last dimension must "
774                  "appear in the reference to the assumed size "
775                  "array '%s' at %L", sym->name, &e->where);
776       return true;
777     }
778   return false;
779 }
780
781
782 /* Look for bad assumed size array references in argument expressions
783   of elemental and array valued intrinsic procedures.  Since this is
784   called from procedure resolution functions, it only recurses at
785   operators.  */
786
787 static bool
788 resolve_assumed_size_actual (gfc_expr *e)
789 {
790   if (e == NULL)
791    return false;
792
793   switch (e->expr_type)
794     {
795     case EXPR_VARIABLE:
796       if (e->symtree
797             && check_assumed_size_reference (e->symtree->n.sym, e))
798         return true;
799       break;
800
801     case EXPR_OP:
802       if (resolve_assumed_size_actual (e->value.op.op1)
803             || resolve_assumed_size_actual (e->value.op.op2))
804         return true;
805       break;
806
807     default:
808       break;
809     }
810   return false;
811 }
812
813
814 /* Resolve an actual argument list.  Most of the time, this is just
815    resolving the expressions in the list.
816    The exception is that we sometimes have to decide whether arguments
817    that look like procedure arguments are really simple variable
818    references.  */
819
820 static try
821 resolve_actual_arglist (gfc_actual_arglist * arg)
822 {
823   gfc_symbol *sym;
824   gfc_symtree *parent_st;
825   gfc_expr *e;
826
827   for (; arg; arg = arg->next)
828     {
829
830       e = arg->expr;
831       if (e == NULL)
832         {
833           /* Check the label is a valid branching target.  */
834           if (arg->label)
835             {
836               if (arg->label->defined == ST_LABEL_UNKNOWN)
837                 {
838                   gfc_error ("Label %d referenced at %L is never defined",
839                              arg->label->value, &arg->label->where);
840                   return FAILURE;
841                 }
842             }
843           continue;
844         }
845
846       if (e->ts.type != BT_PROCEDURE)
847         {
848           if (gfc_resolve_expr (e) != SUCCESS)
849             return FAILURE;
850           continue;
851         }
852
853       /* See if the expression node should really be a variable
854          reference.  */
855
856       sym = e->symtree->n.sym;
857
858       if (sym->attr.flavor == FL_PROCEDURE
859           || sym->attr.intrinsic
860           || sym->attr.external)
861         {
862           int actual_ok;
863
864           /* If a procedure is not already determined to be something else
865              check if it is intrinsic.  */
866           if (!sym->attr.intrinsic
867                 && !(sym->attr.external || sym->attr.use_assoc
868                        || sym->attr.if_source == IFSRC_IFBODY)
869                 && gfc_intrinsic_name (sym->name, sym->attr.subroutine))
870             sym->attr.intrinsic = 1;
871
872           if (sym->attr.proc == PROC_ST_FUNCTION)
873             {
874               gfc_error ("Statement function '%s' at %L is not allowed as an "
875                          "actual argument", sym->name, &e->where);
876             }
877
878           actual_ok = gfc_intrinsic_actual_ok (sym->name, sym->attr.subroutine);
879           if (sym->attr.intrinsic && actual_ok == 0)
880             {
881               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
882                          "actual argument", sym->name, &e->where);
883             }
884
885           if (sym->attr.contained && !sym->attr.use_assoc
886               && sym->ns->proc_name->attr.flavor != FL_MODULE)
887             {
888               gfc_error ("Internal procedure '%s' is not allowed as an "
889                          "actual argument at %L", sym->name, &e->where);
890             }
891
892           if (sym->attr.elemental && !sym->attr.intrinsic)
893             {
894               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
895                          "allowed as an actual argument at %L", sym->name,
896                          &e->where);
897             }
898
899           if (sym->attr.generic)
900             {
901               gfc_error ("GENERIC non-INTRINSIC procedure '%s' is not "
902                          "allowed as an actual argument at %L", sym->name,
903                          &e->where);
904             }
905
906           /* If the symbol is the function that names the current (or
907              parent) scope, then we really have a variable reference.  */
908
909           if (sym->attr.function && sym->result == sym
910               && (sym->ns->proc_name == sym
911                   || (sym->ns->parent != NULL
912                       && sym->ns->parent->proc_name == sym)))
913             goto got_variable;
914
915           continue;
916         }
917
918       /* See if the name is a module procedure in a parent unit.  */
919
920       if (was_declared (sym) || sym->ns->parent == NULL)
921         goto got_variable;
922
923       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
924         {
925           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
926           return FAILURE;
927         }
928
929       if (parent_st == NULL)
930         goto got_variable;
931
932       sym = parent_st->n.sym;
933       e->symtree = parent_st;           /* Point to the right thing.  */
934
935       if (sym->attr.flavor == FL_PROCEDURE
936           || sym->attr.intrinsic
937           || sym->attr.external)
938         {
939           continue;
940         }
941
942     got_variable:
943       e->expr_type = EXPR_VARIABLE;
944       e->ts = sym->ts;
945       if (sym->as != NULL)
946         {
947           e->rank = sym->as->rank;
948           e->ref = gfc_get_ref ();
949           e->ref->type = REF_ARRAY;
950           e->ref->u.ar.type = AR_FULL;
951           e->ref->u.ar.as = sym->as;
952         }
953     }
954
955   return SUCCESS;
956 }
957
958
959 /* Do the checks of the actual argument list that are specific to elemental
960    procedures.  If called with c == NULL, we have a function, otherwise if
961    expr == NULL, we have a subroutine.  */
962 static try
963 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
964 {
965   gfc_actual_arglist *arg0;
966   gfc_actual_arglist *arg;
967   gfc_symbol *esym = NULL;
968   gfc_intrinsic_sym *isym = NULL;
969   gfc_expr *e = NULL;
970   gfc_intrinsic_arg *iformal = NULL;
971   gfc_formal_arglist *eformal = NULL;
972   bool formal_optional = false;
973   bool set_by_optional = false;
974   int i;
975   int rank = 0;
976
977   /* Is this an elemental procedure?  */
978   if (expr && expr->value.function.actual != NULL)
979     {
980       if (expr->value.function.esym != NULL
981             && expr->value.function.esym->attr.elemental)
982         {
983           arg0 = expr->value.function.actual;
984           esym = expr->value.function.esym;
985         }
986       else if (expr->value.function.isym != NULL
987                  && expr->value.function.isym->elemental)
988         {
989           arg0 = expr->value.function.actual;
990           isym = expr->value.function.isym;
991         }
992       else
993         return SUCCESS;
994     }
995   else if (c && c->ext.actual != NULL
996              && c->symtree->n.sym->attr.elemental)
997     {
998       arg0 = c->ext.actual;
999       esym = c->symtree->n.sym;
1000     }
1001   else
1002     return SUCCESS;
1003
1004   /* The rank of an elemental is the rank of its array argument(s).  */
1005   for (arg = arg0; arg; arg = arg->next)
1006     {
1007       if (arg->expr != NULL && arg->expr->rank > 0)
1008         {
1009           rank = arg->expr->rank;
1010           if (arg->expr->expr_type == EXPR_VARIABLE
1011                 && arg->expr->symtree->n.sym->attr.optional)
1012             set_by_optional = true;
1013
1014           /* Function specific; set the result rank and shape.  */
1015           if (expr)
1016             {
1017               expr->rank = rank;
1018               if (!expr->shape && arg->expr->shape)
1019                 {
1020                   expr->shape = gfc_get_shape (rank);
1021                   for (i = 0; i < rank; i++)
1022                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1023                 }
1024             }
1025           break;
1026         }
1027     }
1028
1029   /* If it is an array, it shall not be supplied as an actual argument
1030      to an elemental procedure unless an array of the same rank is supplied
1031      as an actual argument corresponding to a nonoptional dummy argument of
1032      that elemental procedure(12.4.1.5).  */
1033   formal_optional = false;
1034   if (isym)
1035     iformal = isym->formal;
1036   else
1037     eformal = esym->formal;
1038
1039   for (arg = arg0; arg; arg = arg->next)
1040     {
1041       if (eformal)
1042         {
1043           if (eformal->sym && eformal->sym->attr.optional)
1044             formal_optional = true;
1045           eformal = eformal->next;
1046         }
1047       else if (isym && iformal)
1048         {
1049           if (iformal->optional)
1050             formal_optional = true;
1051           iformal = iformal->next;
1052         }
1053       else if (isym)
1054         formal_optional = true;
1055
1056       if (pedantic && arg->expr != NULL
1057             && arg->expr->expr_type == EXPR_VARIABLE
1058             && arg->expr->symtree->n.sym->attr.optional
1059             && formal_optional
1060             && arg->expr->rank
1061             && (set_by_optional || arg->expr->rank != rank)
1062             && !(isym && isym->generic_id == GFC_ISYM_CONVERSION))
1063         {
1064           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1065                        "MISSING, it cannot be the actual argument of an "
1066                        "ELEMENTAL procedure unless there is a non-optional"
1067                        "argument with the same rank (12.4.1.5)",
1068                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1069           return FAILURE;
1070         }
1071     }
1072
1073   for (arg = arg0; arg; arg = arg->next)
1074     {
1075       if (arg->expr == NULL || arg->expr->rank == 0)
1076         continue;
1077
1078       /* Being elemental, the last upper bound of an assumed size array
1079          argument must be present.  */
1080       if (resolve_assumed_size_actual (arg->expr))
1081         return FAILURE;
1082
1083       if (expr)
1084         continue;
1085
1086       /* Elemental subroutine array actual arguments must conform.  */
1087       if (e != NULL)
1088         {
1089           if (gfc_check_conformance ("elemental subroutine", arg->expr, e)
1090                 == FAILURE)
1091             return FAILURE;
1092         }
1093       else
1094         e = arg->expr;
1095     }
1096
1097   return SUCCESS;
1098 }
1099
1100
1101 /* Go through each actual argument in ACTUAL and see if it can be
1102    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1103    function being called, or NULL if not known.  */
1104
1105 static void
1106 find_noncopying_intrinsics (gfc_symbol * fnsym, gfc_actual_arglist * actual)
1107 {
1108   gfc_actual_arglist *ap;
1109   gfc_expr *expr;
1110
1111   for (ap = actual; ap; ap = ap->next)
1112     if (ap->expr
1113         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1114         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual))
1115       ap->expr->inline_noncopying_intrinsic = 1;
1116 }
1117
1118 /* This function does the checking of references to global procedures
1119    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1120    77 and 95 standards.  It checks for a gsymbol for the name, making
1121    one if it does not already exist.  If it already exists, then the
1122    reference being resolved must correspond to the type of gsymbol.
1123    Otherwise, the new symbol is equipped with the attributes of the
1124    reference.  The corresponding code that is called in creating
1125    global entities is parse.c.  */
1126
1127 static void
1128 resolve_global_procedure (gfc_symbol *sym, locus *where, int sub)
1129 {
1130   gfc_gsymbol * gsym;
1131   unsigned int type;
1132
1133   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1134
1135   gsym = gfc_get_gsymbol (sym->name);
1136
1137   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1138     global_used (gsym, where);
1139
1140   if (gsym->type == GSYM_UNKNOWN)
1141     {
1142       gsym->type = type;
1143       gsym->where = *where;
1144     }
1145
1146   gsym->used = 1;
1147 }
1148
1149 /************* Function resolution *************/
1150
1151 /* Resolve a function call known to be generic.
1152    Section 14.1.2.4.1.  */
1153
1154 static match
1155 resolve_generic_f0 (gfc_expr * expr, gfc_symbol * sym)
1156 {
1157   gfc_symbol *s;
1158
1159   if (sym->attr.generic)
1160     {
1161       s =
1162         gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
1163       if (s != NULL)
1164         {
1165           expr->value.function.name = s->name;
1166           expr->value.function.esym = s;
1167
1168           if (s->ts.type != BT_UNKNOWN)
1169             expr->ts = s->ts;
1170           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
1171             expr->ts = s->result->ts;
1172
1173           if (s->as != NULL)
1174             expr->rank = s->as->rank;
1175           else if (s->result != NULL && s->result->as != NULL)
1176             expr->rank = s->result->as->rank;
1177
1178           return MATCH_YES;
1179         }
1180
1181       /* TODO: Need to search for elemental references in generic interface */
1182     }
1183
1184   if (sym->attr.intrinsic)
1185     return gfc_intrinsic_func_interface (expr, 0);
1186
1187   return MATCH_NO;
1188 }
1189
1190
1191 static try
1192 resolve_generic_f (gfc_expr * expr)
1193 {
1194   gfc_symbol *sym;
1195   match m;
1196
1197   sym = expr->symtree->n.sym;
1198
1199   for (;;)
1200     {
1201       m = resolve_generic_f0 (expr, sym);
1202       if (m == MATCH_YES)
1203         return SUCCESS;
1204       else if (m == MATCH_ERROR)
1205         return FAILURE;
1206
1207 generic:
1208       if (sym->ns->parent == NULL)
1209         break;
1210       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1211
1212       if (sym == NULL)
1213         break;
1214       if (!generic_sym (sym))
1215         goto generic;
1216     }
1217
1218   /* Last ditch attempt.  */
1219
1220   if (!gfc_generic_intrinsic (expr->symtree->n.sym->name))
1221     {
1222       gfc_error ("There is no specific function for the generic '%s' at %L",
1223                  expr->symtree->n.sym->name, &expr->where);
1224       return FAILURE;
1225     }
1226
1227   m = gfc_intrinsic_func_interface (expr, 0);
1228   if (m == MATCH_YES)
1229     return SUCCESS;
1230   if (m == MATCH_NO)
1231     gfc_error
1232       ("Generic function '%s' at %L is not consistent with a specific "
1233        "intrinsic interface", expr->symtree->n.sym->name, &expr->where);
1234
1235   return FAILURE;
1236 }
1237
1238
1239 /* Resolve a function call known to be specific.  */
1240
1241 static match
1242 resolve_specific_f0 (gfc_symbol * sym, gfc_expr * expr)
1243 {
1244   match m;
1245
1246   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1247     {
1248       if (sym->attr.dummy)
1249         {
1250           sym->attr.proc = PROC_DUMMY;
1251           goto found;
1252         }
1253
1254       sym->attr.proc = PROC_EXTERNAL;
1255       goto found;
1256     }
1257
1258   if (sym->attr.proc == PROC_MODULE
1259       || sym->attr.proc == PROC_ST_FUNCTION
1260       || sym->attr.proc == PROC_INTERNAL)
1261     goto found;
1262
1263   if (sym->attr.intrinsic)
1264     {
1265       m = gfc_intrinsic_func_interface (expr, 1);
1266       if (m == MATCH_YES)
1267         return MATCH_YES;
1268       if (m == MATCH_NO)
1269         gfc_error
1270           ("Function '%s' at %L is INTRINSIC but is not compatible with "
1271            "an intrinsic", sym->name, &expr->where);
1272
1273       return MATCH_ERROR;
1274     }
1275
1276   return MATCH_NO;
1277
1278 found:
1279   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1280
1281   expr->ts = sym->ts;
1282   expr->value.function.name = sym->name;
1283   expr->value.function.esym = sym;
1284   if (sym->as != NULL)
1285     expr->rank = sym->as->rank;
1286
1287   return MATCH_YES;
1288 }
1289
1290
1291 static try
1292 resolve_specific_f (gfc_expr * expr)
1293 {
1294   gfc_symbol *sym;
1295   match m;
1296
1297   sym = expr->symtree->n.sym;
1298
1299   for (;;)
1300     {
1301       m = resolve_specific_f0 (sym, expr);
1302       if (m == MATCH_YES)
1303         return SUCCESS;
1304       if (m == MATCH_ERROR)
1305         return FAILURE;
1306
1307       if (sym->ns->parent == NULL)
1308         break;
1309
1310       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1311
1312       if (sym == NULL)
1313         break;
1314     }
1315
1316   gfc_error ("Unable to resolve the specific function '%s' at %L",
1317              expr->symtree->n.sym->name, &expr->where);
1318
1319   return SUCCESS;
1320 }
1321
1322
1323 /* Resolve a procedure call not known to be generic nor specific.  */
1324
1325 static try
1326 resolve_unknown_f (gfc_expr * expr)
1327 {
1328   gfc_symbol *sym;
1329   gfc_typespec *ts;
1330
1331   sym = expr->symtree->n.sym;
1332
1333   if (sym->attr.dummy)
1334     {
1335       sym->attr.proc = PROC_DUMMY;
1336       expr->value.function.name = sym->name;
1337       goto set_type;
1338     }
1339
1340   /* See if we have an intrinsic function reference.  */
1341
1342   if (gfc_intrinsic_name (sym->name, 0))
1343     {
1344       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
1345         return SUCCESS;
1346       return FAILURE;
1347     }
1348
1349   /* The reference is to an external name.  */
1350
1351   sym->attr.proc = PROC_EXTERNAL;
1352   expr->value.function.name = sym->name;
1353   expr->value.function.esym = expr->symtree->n.sym;
1354
1355   if (sym->as != NULL)
1356     expr->rank = sym->as->rank;
1357
1358   /* Type of the expression is either the type of the symbol or the
1359      default type of the symbol.  */
1360
1361 set_type:
1362   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
1363
1364   if (sym->ts.type != BT_UNKNOWN)
1365     expr->ts = sym->ts;
1366   else
1367     {
1368       ts = gfc_get_default_type (sym, sym->ns);
1369
1370       if (ts->type == BT_UNKNOWN)
1371         {
1372           gfc_error ("Function '%s' at %L has no IMPLICIT type",
1373                      sym->name, &expr->where);
1374           return FAILURE;
1375         }
1376       else
1377         expr->ts = *ts;
1378     }
1379
1380   return SUCCESS;
1381 }
1382
1383
1384 /* Figure out if a function reference is pure or not.  Also set the name
1385    of the function for a potential error message.  Return nonzero if the
1386    function is PURE, zero if not.  */
1387
1388 static int
1389 pure_function (gfc_expr * e, const char **name)
1390 {
1391   int pure;
1392
1393   if (e->value.function.esym)
1394     {
1395       pure = gfc_pure (e->value.function.esym);
1396       *name = e->value.function.esym->name;
1397     }
1398   else if (e->value.function.isym)
1399     {
1400       pure = e->value.function.isym->pure
1401         || e->value.function.isym->elemental;
1402       *name = e->value.function.isym->name;
1403     }
1404   else
1405     {
1406       /* Implicit functions are not pure.  */
1407       pure = 0;
1408       *name = e->value.function.name;
1409     }
1410
1411   return pure;
1412 }
1413
1414
1415 /* Resolve a function call, which means resolving the arguments, then figuring
1416    out which entity the name refers to.  */
1417 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
1418    to INTENT(OUT) or INTENT(INOUT).  */
1419
1420 static try
1421 resolve_function (gfc_expr * expr)
1422 {
1423   gfc_actual_arglist *arg;
1424   gfc_symbol * sym;
1425   const char *name;
1426   try t;
1427   int temp;
1428
1429   sym = NULL;
1430   if (expr->symtree)
1431     sym = expr->symtree->n.sym;
1432
1433   /* If the procedure is not internal, a statement function or a module
1434      procedure,it must be external and should be checked for usage.  */
1435   if (sym && !sym->attr.dummy && !sym->attr.contained
1436         && sym->attr.proc != PROC_ST_FUNCTION
1437         && !sym->attr.use_assoc)
1438     resolve_global_procedure (sym, &expr->where, 0);
1439
1440   /* Switch off assumed size checking and do this again for certain kinds
1441      of procedure, once the procedure itself is resolved.  */
1442   need_full_assumed_size++;
1443
1444   if (resolve_actual_arglist (expr->value.function.actual) == FAILURE)
1445     return FAILURE;
1446
1447   /* Resume assumed_size checking. */
1448   need_full_assumed_size--;
1449
1450   if (sym && sym->ts.type == BT_CHARACTER
1451         && sym->ts.cl
1452         && sym->ts.cl->length == NULL
1453         && !sym->attr.dummy
1454         && expr->value.function.esym == NULL
1455         && !sym->attr.contained)
1456     {
1457       /* Internal procedures are taken care of in resolve_contained_fntype.  */
1458       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
1459                  "be used at %L since it is not a dummy argument",
1460                  sym->name, &expr->where);
1461       return FAILURE;
1462     }
1463
1464 /* See if function is already resolved.  */
1465
1466   if (expr->value.function.name != NULL)
1467     {
1468       if (expr->ts.type == BT_UNKNOWN)
1469         expr->ts = sym->ts;
1470       t = SUCCESS;
1471     }
1472   else
1473     {
1474       /* Apply the rules of section 14.1.2.  */
1475
1476       switch (procedure_kind (sym))
1477         {
1478         case PTYPE_GENERIC:
1479           t = resolve_generic_f (expr);
1480           break;
1481
1482         case PTYPE_SPECIFIC:
1483           t = resolve_specific_f (expr);
1484           break;
1485
1486         case PTYPE_UNKNOWN:
1487           t = resolve_unknown_f (expr);
1488           break;
1489
1490         default:
1491           gfc_internal_error ("resolve_function(): bad function type");
1492         }
1493     }
1494
1495   /* If the expression is still a function (it might have simplified),
1496      then we check to see if we are calling an elemental function.  */
1497
1498   if (expr->expr_type != EXPR_FUNCTION)
1499     return t;
1500
1501   temp = need_full_assumed_size;
1502   need_full_assumed_size = 0;
1503
1504   if (resolve_elemental_actual (expr, NULL) == FAILURE)
1505     return FAILURE;
1506
1507   if (omp_workshare_flag
1508       && expr->value.function.esym
1509       && ! gfc_elemental (expr->value.function.esym))
1510     {
1511       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed"
1512                  " in WORKSHARE construct", expr->value.function.esym->name,
1513                  &expr->where);
1514       t = FAILURE;
1515     }
1516
1517 #define GENERIC_ID expr->value.function.isym->generic_id
1518   else if (expr->value.function.actual != NULL
1519              && expr->value.function.isym != NULL
1520              && GENERIC_ID != GFC_ISYM_LBOUND
1521              && GENERIC_ID != GFC_ISYM_LEN
1522              && GENERIC_ID != GFC_ISYM_LOC
1523              && GENERIC_ID != GFC_ISYM_PRESENT)
1524     {
1525       /* Array intrinsics must also have the last upper bound of an
1526          assumed size array argument.  UBOUND and SIZE have to be
1527          excluded from the check if the second argument is anything
1528          than a constant.  */
1529       int inquiry;
1530       inquiry = GENERIC_ID == GFC_ISYM_UBOUND
1531                   || GENERIC_ID == GFC_ISYM_SIZE;
1532
1533       for (arg = expr->value.function.actual; arg; arg = arg->next)
1534         {
1535           if (inquiry && arg->next != NULL && arg->next->expr
1536                 && arg->next->expr->expr_type != EXPR_CONSTANT)
1537             break;
1538
1539           if (arg->expr != NULL
1540                 && arg->expr->rank > 0
1541                 && resolve_assumed_size_actual (arg->expr))
1542             return FAILURE;
1543         }
1544     }
1545 #undef GENERIC_ID
1546
1547   need_full_assumed_size = temp;
1548
1549   if (!pure_function (expr, &name) && name)
1550     {
1551       if (forall_flag)
1552         {
1553           gfc_error
1554             ("reference to non-PURE function '%s' at %L inside a "
1555              "FORALL %s", name, &expr->where, forall_flag == 2 ?
1556              "mask" : "block");
1557           t = FAILURE;
1558         }
1559       else if (gfc_pure (NULL))
1560         {
1561           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
1562                      "procedure within a PURE procedure", name, &expr->where);
1563           t = FAILURE;
1564         }
1565     }
1566
1567   /* Functions without the RECURSIVE attribution are not allowed to
1568    * call themselves.  */
1569   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
1570     {
1571       gfc_symbol *esym, *proc;
1572       esym = expr->value.function.esym;
1573       proc = gfc_current_ns->proc_name;
1574       if (esym == proc)
1575       {
1576         gfc_error ("Function '%s' at %L cannot call itself, as it is not "
1577                    "RECURSIVE", name, &expr->where);
1578         t = FAILURE;
1579       }
1580
1581       if (esym->attr.entry && esym->ns->entries && proc->ns->entries
1582           && esym->ns->entries->sym == proc->ns->entries->sym)
1583       {
1584         gfc_error ("Call to ENTRY '%s' at %L is recursive, but function "
1585                    "'%s' is not declared as RECURSIVE",
1586                    esym->name, &expr->where, esym->ns->entries->sym->name);
1587         t = FAILURE;
1588       }
1589     }
1590
1591   /* Character lengths of use associated functions may contains references to
1592      symbols not referenced from the current program unit otherwise.  Make sure
1593      those symbols are marked as referenced.  */
1594
1595   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
1596       && expr->value.function.esym->attr.use_assoc)
1597     {
1598       gfc_expr_set_symbols_referenced (expr->ts.cl->length);
1599     }
1600
1601   if (t == SUCCESS)
1602     find_noncopying_intrinsics (expr->value.function.esym,
1603                                 expr->value.function.actual);
1604   return t;
1605 }
1606
1607
1608 /************* Subroutine resolution *************/
1609
1610 static void
1611 pure_subroutine (gfc_code * c, gfc_symbol * sym)
1612 {
1613
1614   if (gfc_pure (sym))
1615     return;
1616
1617   if (forall_flag)
1618     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
1619                sym->name, &c->loc);
1620   else if (gfc_pure (NULL))
1621     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
1622                &c->loc);
1623 }
1624
1625
1626 static match
1627 resolve_generic_s0 (gfc_code * c, gfc_symbol * sym)
1628 {
1629   gfc_symbol *s;
1630
1631   if (sym->attr.generic)
1632     {
1633       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
1634       if (s != NULL)
1635         {
1636           c->resolved_sym = s;
1637           pure_subroutine (c, s);
1638           return MATCH_YES;
1639         }
1640
1641       /* TODO: Need to search for elemental references in generic interface.  */
1642     }
1643
1644   if (sym->attr.intrinsic)
1645     return gfc_intrinsic_sub_interface (c, 0);
1646
1647   return MATCH_NO;
1648 }
1649
1650
1651 static try
1652 resolve_generic_s (gfc_code * c)
1653 {
1654   gfc_symbol *sym;
1655   match m;
1656
1657   sym = c->symtree->n.sym;
1658
1659   for (;;)
1660     {
1661       m = resolve_generic_s0 (c, sym);
1662       if (m == MATCH_YES)
1663         return SUCCESS;
1664       else if (m == MATCH_ERROR)
1665         return FAILURE;
1666
1667 generic:
1668       if (sym->ns->parent == NULL)
1669         break;
1670       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1671
1672       if (sym == NULL)
1673         break;
1674       if (!generic_sym (sym))
1675         goto generic;
1676     }
1677
1678   /* Last ditch attempt.  */
1679   sym = c->symtree->n.sym;
1680   if (!gfc_generic_intrinsic (sym->name))
1681     {
1682       gfc_error
1683         ("There is no specific subroutine for the generic '%s' at %L",
1684          sym->name, &c->loc);
1685       return FAILURE;
1686     }
1687
1688   m = gfc_intrinsic_sub_interface (c, 0);
1689   if (m == MATCH_YES)
1690     return SUCCESS;
1691   if (m == MATCH_NO)
1692     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
1693                "intrinsic subroutine interface", sym->name, &c->loc);
1694
1695   return FAILURE;
1696 }
1697
1698
1699 /* Resolve a subroutine call known to be specific.  */
1700
1701 static match
1702 resolve_specific_s0 (gfc_code * c, gfc_symbol * sym)
1703 {
1704   match m;
1705
1706   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
1707     {
1708       if (sym->attr.dummy)
1709         {
1710           sym->attr.proc = PROC_DUMMY;
1711           goto found;
1712         }
1713
1714       sym->attr.proc = PROC_EXTERNAL;
1715       goto found;
1716     }
1717
1718   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
1719     goto found;
1720
1721   if (sym->attr.intrinsic)
1722     {
1723       m = gfc_intrinsic_sub_interface (c, 1);
1724       if (m == MATCH_YES)
1725         return MATCH_YES;
1726       if (m == MATCH_NO)
1727         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
1728                    "with an intrinsic", sym->name, &c->loc);
1729
1730       return MATCH_ERROR;
1731     }
1732
1733   return MATCH_NO;
1734
1735 found:
1736   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1737
1738   c->resolved_sym = sym;
1739   pure_subroutine (c, sym);
1740
1741   return MATCH_YES;
1742 }
1743
1744
1745 static try
1746 resolve_specific_s (gfc_code * c)
1747 {
1748   gfc_symbol *sym;
1749   match m;
1750
1751   sym = c->symtree->n.sym;
1752
1753   for (;;)
1754     {
1755       m = resolve_specific_s0 (c, sym);
1756       if (m == MATCH_YES)
1757         return SUCCESS;
1758       if (m == MATCH_ERROR)
1759         return FAILURE;
1760
1761       if (sym->ns->parent == NULL)
1762         break;
1763
1764       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1765
1766       if (sym == NULL)
1767         break;
1768     }
1769
1770   sym = c->symtree->n.sym;
1771   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
1772              sym->name, &c->loc);
1773
1774   return FAILURE;
1775 }
1776
1777
1778 /* Resolve a subroutine call not known to be generic nor specific.  */
1779
1780 static try
1781 resolve_unknown_s (gfc_code * c)
1782 {
1783   gfc_symbol *sym;
1784
1785   sym = c->symtree->n.sym;
1786
1787   if (sym->attr.dummy)
1788     {
1789       sym->attr.proc = PROC_DUMMY;
1790       goto found;
1791     }
1792
1793   /* See if we have an intrinsic function reference.  */
1794
1795   if (gfc_intrinsic_name (sym->name, 1))
1796     {
1797       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
1798         return SUCCESS;
1799       return FAILURE;
1800     }
1801
1802   /* The reference is to an external name.  */
1803
1804 found:
1805   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
1806
1807   c->resolved_sym = sym;
1808
1809   pure_subroutine (c, sym);
1810
1811   return SUCCESS;
1812 }
1813
1814
1815 /* Resolve a subroutine call.  Although it was tempting to use the same code
1816    for functions, subroutines and functions are stored differently and this
1817    makes things awkward.  */
1818
1819 static try
1820 resolve_call (gfc_code * c)
1821 {
1822   try t;
1823
1824   if (c->symtree && c->symtree->n.sym
1825         && c->symtree->n.sym->ts.type != BT_UNKNOWN)
1826     {
1827       gfc_error ("'%s' at %L has a type, which is not consistent with "
1828                  "the CALL at %L", c->symtree->n.sym->name,
1829                  &c->symtree->n.sym->declared_at, &c->loc);
1830       return FAILURE;
1831     }
1832
1833   /* If the procedure is not internal or module, it must be external and
1834      should be checked for usage.  */
1835   if (c->symtree && c->symtree->n.sym
1836         && !c->symtree->n.sym->attr.dummy
1837         && !c->symtree->n.sym->attr.contained
1838         && !c->symtree->n.sym->attr.use_assoc)
1839     resolve_global_procedure (c->symtree->n.sym, &c->loc, 1);
1840
1841   /* Subroutines without the RECURSIVE attribution are not allowed to
1842    * call themselves.  */
1843   if (c->symtree && c->symtree->n.sym && !c->symtree->n.sym->attr.recursive)
1844     {
1845       gfc_symbol *csym, *proc;
1846       csym = c->symtree->n.sym;
1847       proc = gfc_current_ns->proc_name;
1848       if (csym == proc)
1849       {
1850         gfc_error ("SUBROUTINE '%s' at %L cannot call itself, as it is not "
1851                    "RECURSIVE", csym->name, &c->loc);
1852         t = FAILURE;
1853       }
1854
1855       if (csym->attr.entry && csym->ns->entries && proc->ns->entries
1856           && csym->ns->entries->sym == proc->ns->entries->sym)
1857       {
1858         gfc_error ("Call to ENTRY '%s' at %L is recursive, but subroutine "
1859                    "'%s' is not declared as RECURSIVE",
1860                    csym->name, &c->loc, csym->ns->entries->sym->name);
1861         t = FAILURE;
1862       }
1863     }
1864
1865   /* Switch off assumed size checking and do this again for certain kinds
1866      of procedure, once the procedure itself is resolved.  */
1867   need_full_assumed_size++;
1868
1869   if (resolve_actual_arglist (c->ext.actual) == FAILURE)
1870     return FAILURE;
1871
1872   /* Resume assumed_size checking. */
1873   need_full_assumed_size--;
1874
1875
1876   t = SUCCESS;
1877   if (c->resolved_sym == NULL)
1878     switch (procedure_kind (c->symtree->n.sym))
1879       {
1880       case PTYPE_GENERIC:
1881         t = resolve_generic_s (c);
1882         break;
1883
1884       case PTYPE_SPECIFIC:
1885         t = resolve_specific_s (c);
1886         break;
1887
1888       case PTYPE_UNKNOWN:
1889         t = resolve_unknown_s (c);
1890         break;
1891
1892       default:
1893         gfc_internal_error ("resolve_subroutine(): bad function type");
1894       }
1895
1896   /* Some checks of elemental subroutine actual arguments.  */
1897   if (resolve_elemental_actual (NULL, c) == FAILURE)
1898     return FAILURE;
1899
1900   if (t == SUCCESS)
1901     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
1902   return t;
1903 }
1904
1905 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
1906    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
1907    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
1908    if their shapes do not match.  If either op1->shape or op2->shape is
1909    NULL, return SUCCESS.  */
1910
1911 static try
1912 compare_shapes (gfc_expr * op1, gfc_expr * op2)
1913 {
1914   try t;
1915   int i;
1916
1917   t = SUCCESS;
1918
1919   if (op1->shape != NULL && op2->shape != NULL)
1920     {
1921       for (i = 0; i < op1->rank; i++)
1922         {
1923           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
1924            {
1925              gfc_error ("Shapes for operands at %L and %L are not conformable",
1926                          &op1->where, &op2->where);
1927              t = FAILURE;
1928              break;
1929            }
1930         }
1931     }
1932
1933   return t;
1934 }
1935
1936 /* Resolve an operator expression node.  This can involve replacing the
1937    operation with a user defined function call.  */
1938
1939 static try
1940 resolve_operator (gfc_expr * e)
1941 {
1942   gfc_expr *op1, *op2;
1943   char msg[200];
1944   try t;
1945
1946   /* Resolve all subnodes-- give them types.  */
1947
1948   switch (e->value.op.operator)
1949     {
1950     default:
1951       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
1952         return FAILURE;
1953
1954     /* Fall through...  */
1955
1956     case INTRINSIC_NOT:
1957     case INTRINSIC_UPLUS:
1958     case INTRINSIC_UMINUS:
1959     case INTRINSIC_PARENTHESES:
1960       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
1961         return FAILURE;
1962       break;
1963     }
1964
1965   /* Typecheck the new node.  */
1966
1967   op1 = e->value.op.op1;
1968   op2 = e->value.op.op2;
1969
1970   switch (e->value.op.operator)
1971     {
1972     case INTRINSIC_UPLUS:
1973     case INTRINSIC_UMINUS:
1974       if (op1->ts.type == BT_INTEGER
1975           || op1->ts.type == BT_REAL
1976           || op1->ts.type == BT_COMPLEX)
1977         {
1978           e->ts = op1->ts;
1979           break;
1980         }
1981
1982       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
1983                gfc_op2string (e->value.op.operator), gfc_typename (&e->ts));
1984       goto bad_op;
1985
1986     case INTRINSIC_PLUS:
1987     case INTRINSIC_MINUS:
1988     case INTRINSIC_TIMES:
1989     case INTRINSIC_DIVIDE:
1990     case INTRINSIC_POWER:
1991       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
1992         {
1993           gfc_type_convert_binary (e);
1994           break;
1995         }
1996
1997       sprintf (msg,
1998                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
1999                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
2000                gfc_typename (&op2->ts));
2001       goto bad_op;
2002
2003     case INTRINSIC_CONCAT:
2004       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
2005         {
2006           e->ts.type = BT_CHARACTER;
2007           e->ts.kind = op1->ts.kind;
2008           break;
2009         }
2010
2011       sprintf (msg,
2012                _("Operands of string concatenation operator at %%L are %s/%s"),
2013                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
2014       goto bad_op;
2015
2016     case INTRINSIC_AND:
2017     case INTRINSIC_OR:
2018     case INTRINSIC_EQV:
2019     case INTRINSIC_NEQV:
2020       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
2021         {
2022           e->ts.type = BT_LOGICAL;
2023           e->ts.kind = gfc_kind_max (op1, op2);
2024           if (op1->ts.kind < e->ts.kind)
2025             gfc_convert_type (op1, &e->ts, 2);
2026           else if (op2->ts.kind < e->ts.kind)
2027             gfc_convert_type (op2, &e->ts, 2);
2028           break;
2029         }
2030
2031       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
2032                gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
2033                gfc_typename (&op2->ts));
2034
2035       goto bad_op;
2036
2037     case INTRINSIC_NOT:
2038       if (op1->ts.type == BT_LOGICAL)
2039         {
2040           e->ts.type = BT_LOGICAL;
2041           e->ts.kind = op1->ts.kind;
2042           break;
2043         }
2044
2045       sprintf (msg, _("Operand of .NOT. operator at %%L is %s"),
2046                gfc_typename (&op1->ts));
2047       goto bad_op;
2048
2049     case INTRINSIC_GT:
2050     case INTRINSIC_GE:
2051     case INTRINSIC_LT:
2052     case INTRINSIC_LE:
2053       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
2054         {
2055           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
2056           goto bad_op;
2057         }
2058
2059       /* Fall through...  */
2060
2061     case INTRINSIC_EQ:
2062     case INTRINSIC_NE:
2063       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER)
2064         {
2065           e->ts.type = BT_LOGICAL;
2066           e->ts.kind = gfc_default_logical_kind;
2067           break;
2068         }
2069
2070       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
2071         {
2072           gfc_type_convert_binary (e);
2073
2074           e->ts.type = BT_LOGICAL;
2075           e->ts.kind = gfc_default_logical_kind;
2076           break;
2077         }
2078
2079       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
2080         sprintf (msg,
2081                  _("Logicals at %%L must be compared with %s instead of %s"),
2082                  e->value.op.operator == INTRINSIC_EQ ? ".EQV." : ".NEQV.",
2083                  gfc_op2string (e->value.op.operator));
2084       else
2085         sprintf (msg,
2086                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
2087                  gfc_op2string (e->value.op.operator), gfc_typename (&op1->ts),
2088                  gfc_typename (&op2->ts));
2089
2090       goto bad_op;
2091
2092     case INTRINSIC_USER:
2093       if (op2 == NULL)
2094         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
2095                  e->value.op.uop->name, gfc_typename (&op1->ts));
2096       else
2097         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
2098                  e->value.op.uop->name, gfc_typename (&op1->ts),
2099                  gfc_typename (&op2->ts));
2100
2101       goto bad_op;
2102
2103     case INTRINSIC_PARENTHESES:
2104       break;
2105
2106     default:
2107       gfc_internal_error ("resolve_operator(): Bad intrinsic");
2108     }
2109
2110   /* Deal with arrayness of an operand through an operator.  */
2111
2112   t = SUCCESS;
2113
2114   switch (e->value.op.operator)
2115     {
2116     case INTRINSIC_PLUS:
2117     case INTRINSIC_MINUS:
2118     case INTRINSIC_TIMES:
2119     case INTRINSIC_DIVIDE:
2120     case INTRINSIC_POWER:
2121     case INTRINSIC_CONCAT:
2122     case INTRINSIC_AND:
2123     case INTRINSIC_OR:
2124     case INTRINSIC_EQV:
2125     case INTRINSIC_NEQV:
2126     case INTRINSIC_EQ:
2127     case INTRINSIC_NE:
2128     case INTRINSIC_GT:
2129     case INTRINSIC_GE:
2130     case INTRINSIC_LT:
2131     case INTRINSIC_LE:
2132
2133       if (op1->rank == 0 && op2->rank == 0)
2134         e->rank = 0;
2135
2136       if (op1->rank == 0 && op2->rank != 0)
2137         {
2138           e->rank = op2->rank;
2139
2140           if (e->shape == NULL)
2141             e->shape = gfc_copy_shape (op2->shape, op2->rank);
2142         }
2143
2144       if (op1->rank != 0 && op2->rank == 0)
2145         {
2146           e->rank = op1->rank;
2147
2148           if (e->shape == NULL)
2149             e->shape = gfc_copy_shape (op1->shape, op1->rank);
2150         }
2151
2152       if (op1->rank != 0 && op2->rank != 0)
2153         {
2154           if (op1->rank == op2->rank)
2155             {
2156               e->rank = op1->rank;
2157               if (e->shape == NULL)
2158                 {
2159                   t = compare_shapes(op1, op2);
2160                   if (t == FAILURE)
2161                     e->shape = NULL;
2162                   else
2163                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
2164                 }
2165             }
2166           else
2167             {
2168               gfc_error ("Inconsistent ranks for operator at %L and %L",
2169                          &op1->where, &op2->where);
2170               t = FAILURE;
2171
2172               /* Allow higher level expressions to work.  */
2173               e->rank = 0;
2174             }
2175         }
2176
2177       break;
2178
2179     case INTRINSIC_NOT:
2180     case INTRINSIC_UPLUS:
2181     case INTRINSIC_UMINUS:
2182     case INTRINSIC_PARENTHESES:
2183       e->rank = op1->rank;
2184
2185       if (e->shape == NULL)
2186         e->shape = gfc_copy_shape (op1->shape, op1->rank);
2187
2188       /* Simply copy arrayness attribute */
2189       break;
2190
2191     default:
2192       break;
2193     }
2194
2195   /* Attempt to simplify the expression.  */
2196   if (t == SUCCESS)
2197     {
2198       t = gfc_simplify_expr (e, 0);
2199       /* Some calls do not succeed in simplification and return FAILURE
2200          even though there is no error; eg. variable references to
2201          PARAMETER arrays.  */
2202       if (!gfc_is_constant_expr (e))
2203         t = SUCCESS;
2204     }
2205   return t;
2206
2207 bad_op:
2208
2209   if (gfc_extend_expr (e) == SUCCESS)
2210     return SUCCESS;
2211
2212   gfc_error (msg, &e->where);
2213
2214   return FAILURE;
2215 }
2216
2217
2218 /************** Array resolution subroutines **************/
2219
2220
2221 typedef enum
2222 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
2223 comparison;
2224
2225 /* Compare two integer expressions.  */
2226
2227 static comparison
2228 compare_bound (gfc_expr * a, gfc_expr * b)
2229 {
2230   int i;
2231
2232   if (a == NULL || a->expr_type != EXPR_CONSTANT
2233       || b == NULL || b->expr_type != EXPR_CONSTANT)
2234     return CMP_UNKNOWN;
2235
2236   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
2237     gfc_internal_error ("compare_bound(): Bad expression");
2238
2239   i = mpz_cmp (a->value.integer, b->value.integer);
2240
2241   if (i < 0)
2242     return CMP_LT;
2243   if (i > 0)
2244     return CMP_GT;
2245   return CMP_EQ;
2246 }
2247
2248
2249 /* Compare an integer expression with an integer.  */
2250
2251 static comparison
2252 compare_bound_int (gfc_expr * a, int b)
2253 {
2254   int i;
2255
2256   if (a == NULL || a->expr_type != EXPR_CONSTANT)
2257     return CMP_UNKNOWN;
2258
2259   if (a->ts.type != BT_INTEGER)
2260     gfc_internal_error ("compare_bound_int(): Bad expression");
2261
2262   i = mpz_cmp_si (a->value.integer, b);
2263
2264   if (i < 0)
2265     return CMP_LT;
2266   if (i > 0)
2267     return CMP_GT;
2268   return CMP_EQ;
2269 }
2270
2271
2272 /* Compare an integer expression with a mpz_t.  */
2273
2274 static comparison
2275 compare_bound_mpz_t (gfc_expr * a, mpz_t b)
2276 {
2277   int i;
2278
2279   if (a == NULL || a->expr_type != EXPR_CONSTANT)
2280     return CMP_UNKNOWN;
2281
2282   if (a->ts.type != BT_INTEGER)
2283     gfc_internal_error ("compare_bound_int(): Bad expression");
2284
2285   i = mpz_cmp (a->value.integer, b);
2286
2287   if (i < 0)
2288     return CMP_LT;
2289   if (i > 0)
2290     return CMP_GT;
2291   return CMP_EQ;
2292 }
2293
2294
2295 /* Compute the last value of a sequence given by a triplet.  
2296    Return 0 if it wasn't able to compute the last value, or if the
2297    sequence if empty, and 1 otherwise.  */
2298
2299 static int
2300 compute_last_value_for_triplet (gfc_expr * start, gfc_expr * end,
2301                                 gfc_expr * stride, mpz_t last)
2302 {
2303   mpz_t rem;
2304
2305   if (start == NULL || start->expr_type != EXPR_CONSTANT
2306       || end == NULL || end->expr_type != EXPR_CONSTANT
2307       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
2308     return 0;
2309
2310   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
2311       || (stride != NULL && stride->ts.type != BT_INTEGER))
2312     return 0;
2313
2314   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
2315     {
2316       if (compare_bound (start, end) == CMP_GT)
2317         return 0;
2318       mpz_set (last, end->value.integer);
2319       return 1;
2320     }
2321
2322   if (compare_bound_int (stride, 0) == CMP_GT)
2323     {
2324       /* Stride is positive */
2325       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
2326         return 0;
2327     }
2328   else
2329     {
2330       /* Stride is negative */
2331       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
2332         return 0;
2333     }
2334
2335   mpz_init (rem);
2336   mpz_sub (rem, end->value.integer, start->value.integer);
2337   mpz_tdiv_r (rem, rem, stride->value.integer);
2338   mpz_sub (last, end->value.integer, rem);
2339   mpz_clear (rem);
2340
2341   return 1;
2342 }
2343
2344
2345 /* Compare a single dimension of an array reference to the array
2346    specification.  */
2347
2348 static try
2349 check_dimension (int i, gfc_array_ref * ar, gfc_array_spec * as)
2350 {
2351   mpz_t last_value;
2352
2353 /* Given start, end and stride values, calculate the minimum and
2354    maximum referenced indexes.  */
2355
2356   switch (ar->type)
2357     {
2358     case AR_FULL:
2359       break;
2360
2361     case AR_ELEMENT:
2362       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
2363         goto bound;
2364       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
2365         goto bound;
2366
2367       break;
2368
2369     case AR_SECTION:
2370       if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
2371         {
2372           gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
2373           return FAILURE;
2374         }
2375
2376 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
2377 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
2378
2379       if (compare_bound (AR_START, AR_END) == CMP_EQ
2380           && (compare_bound (AR_START, as->lower[i]) == CMP_LT
2381               || compare_bound (AR_START, as->upper[i]) == CMP_GT))
2382         goto bound;
2383
2384       if (((compare_bound_int (ar->stride[i], 0) == CMP_GT
2385             || ar->stride[i] == NULL)
2386            && compare_bound (AR_START, AR_END) != CMP_GT)
2387           || (compare_bound_int (ar->stride[i], 0) == CMP_LT
2388               && compare_bound (AR_START, AR_END) != CMP_LT))
2389         {
2390           if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
2391             goto bound;
2392           if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
2393             goto bound;
2394         }
2395
2396       mpz_init (last_value);
2397       if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
2398                                           last_value))
2399         {
2400           if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT
2401               || compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
2402             {
2403               mpz_clear (last_value);
2404               goto bound;
2405             }
2406         }
2407       mpz_clear (last_value);
2408
2409 #undef AR_START
2410 #undef AR_END
2411
2412       break;
2413
2414     default:
2415       gfc_internal_error ("check_dimension(): Bad array reference");
2416     }
2417
2418   return SUCCESS;
2419
2420 bound:
2421   gfc_warning ("Array reference at %L is out of bounds", &ar->c_where[i]);
2422   return SUCCESS;
2423 }
2424
2425
2426 /* Compare an array reference with an array specification.  */
2427
2428 static try
2429 compare_spec_to_ref (gfc_array_ref * ar)
2430 {
2431   gfc_array_spec *as;
2432   int i;
2433
2434   as = ar->as;
2435   i = as->rank - 1;
2436   /* TODO: Full array sections are only allowed as actual parameters.  */
2437   if (as->type == AS_ASSUMED_SIZE
2438       && (/*ar->type == AR_FULL
2439           ||*/ (ar->type == AR_SECTION
2440               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
2441     {
2442       gfc_error ("Rightmost upper bound of assumed size array section"
2443                  " not specified at %L", &ar->where);
2444       return FAILURE;
2445     }
2446
2447   if (ar->type == AR_FULL)
2448     return SUCCESS;
2449
2450   if (as->rank != ar->dimen)
2451     {
2452       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
2453                  &ar->where, ar->dimen, as->rank);
2454       return FAILURE;
2455     }
2456
2457   for (i = 0; i < as->rank; i++)
2458     if (check_dimension (i, ar, as) == FAILURE)
2459       return FAILURE;
2460
2461   return SUCCESS;
2462 }
2463
2464
2465 /* Resolve one part of an array index.  */
2466
2467 try
2468 gfc_resolve_index (gfc_expr * index, int check_scalar)
2469 {
2470   gfc_typespec ts;
2471
2472   if (index == NULL)
2473     return SUCCESS;
2474
2475   if (gfc_resolve_expr (index) == FAILURE)
2476     return FAILURE;
2477
2478   if (check_scalar && index->rank != 0)
2479     {
2480       gfc_error ("Array index at %L must be scalar", &index->where);
2481       return FAILURE;
2482     }
2483
2484   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
2485     {
2486       gfc_error ("Array index at %L must be of INTEGER type",
2487                  &index->where);
2488       return FAILURE;
2489     }
2490
2491   if (index->ts.type == BT_REAL)
2492     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
2493                         &index->where) == FAILURE)
2494       return FAILURE;
2495
2496   if (index->ts.kind != gfc_index_integer_kind
2497       || index->ts.type != BT_INTEGER)
2498     {
2499       gfc_clear_ts (&ts);
2500       ts.type = BT_INTEGER;
2501       ts.kind = gfc_index_integer_kind;
2502
2503       gfc_convert_type_warn (index, &ts, 2, 0);
2504     }
2505
2506   return SUCCESS;
2507 }
2508
2509 /* Resolve a dim argument to an intrinsic function.  */
2510
2511 try
2512 gfc_resolve_dim_arg (gfc_expr *dim)
2513 {
2514   if (dim == NULL)
2515     return SUCCESS;
2516
2517   if (gfc_resolve_expr (dim) == FAILURE)
2518     return FAILURE;
2519
2520   if (dim->rank != 0)
2521     {
2522       gfc_error ("Argument dim at %L must be scalar", &dim->where);
2523       return FAILURE;
2524
2525     }
2526   if (dim->ts.type != BT_INTEGER)
2527     {
2528       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
2529       return FAILURE;
2530     }
2531   if (dim->ts.kind != gfc_index_integer_kind)
2532     {
2533       gfc_typespec ts;
2534
2535       ts.type = BT_INTEGER;
2536       ts.kind = gfc_index_integer_kind;
2537
2538       gfc_convert_type_warn (dim, &ts, 2, 0);
2539     }
2540
2541   return SUCCESS;
2542 }
2543
2544 /* Given an expression that contains array references, update those array
2545    references to point to the right array specifications.  While this is
2546    filled in during matching, this information is difficult to save and load
2547    in a module, so we take care of it here.
2548
2549    The idea here is that the original array reference comes from the
2550    base symbol.  We traverse the list of reference structures, setting
2551    the stored reference to references.  Component references can
2552    provide an additional array specification.  */
2553
2554 static void
2555 find_array_spec (gfc_expr * e)
2556 {
2557   gfc_array_spec *as;
2558   gfc_component *c;
2559   gfc_symbol *derived;
2560   gfc_ref *ref;
2561
2562   as = e->symtree->n.sym->as;
2563   derived = NULL;
2564
2565   for (ref = e->ref; ref; ref = ref->next)
2566     switch (ref->type)
2567       {
2568       case REF_ARRAY:
2569         if (as == NULL)
2570           gfc_internal_error ("find_array_spec(): Missing spec");
2571
2572         ref->u.ar.as = as;
2573         as = NULL;
2574         break;
2575
2576       case REF_COMPONENT:
2577         if (derived == NULL)
2578           derived = e->symtree->n.sym->ts.derived;
2579
2580         c = derived->components;
2581
2582         for (; c; c = c->next)
2583           if (c == ref->u.c.component)
2584             {
2585               /* Track the sequence of component references.  */
2586               if (c->ts.type == BT_DERIVED)
2587                 derived = c->ts.derived;
2588               break;
2589             }
2590
2591         if (c == NULL)
2592           gfc_internal_error ("find_array_spec(): Component not found");
2593
2594         if (c->dimension)
2595           {
2596             if (as != NULL)
2597               gfc_internal_error ("find_array_spec(): unused as(1)");
2598             as = c->as;
2599           }
2600
2601         break;
2602
2603       case REF_SUBSTRING:
2604         break;
2605       }
2606
2607   if (as != NULL)
2608     gfc_internal_error ("find_array_spec(): unused as(2)");
2609 }
2610
2611
2612 /* Resolve an array reference.  */
2613
2614 static try
2615 resolve_array_ref (gfc_array_ref * ar)
2616 {
2617   int i, check_scalar;
2618   gfc_expr *e;
2619
2620   for (i = 0; i < ar->dimen; i++)
2621     {
2622       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
2623
2624       if (gfc_resolve_index (ar->start[i], check_scalar) == FAILURE)
2625         return FAILURE;
2626       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
2627         return FAILURE;
2628       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
2629         return FAILURE;
2630
2631       e = ar->start[i];
2632
2633       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
2634         switch (e->rank)
2635           {
2636           case 0:
2637             ar->dimen_type[i] = DIMEN_ELEMENT;
2638             break;
2639
2640           case 1:
2641             ar->dimen_type[i] = DIMEN_VECTOR;
2642             if (e->expr_type == EXPR_VARIABLE
2643                    && e->symtree->n.sym->ts.type == BT_DERIVED)
2644               ar->start[i] = gfc_get_parentheses (e);
2645             break;
2646
2647           default:
2648             gfc_error ("Array index at %L is an array of rank %d",
2649                        &ar->c_where[i], e->rank);
2650             return FAILURE;
2651           }
2652     }
2653
2654   /* If the reference type is unknown, figure out what kind it is.  */
2655
2656   if (ar->type == AR_UNKNOWN)
2657     {
2658       ar->type = AR_ELEMENT;
2659       for (i = 0; i < ar->dimen; i++)
2660         if (ar->dimen_type[i] == DIMEN_RANGE
2661             || ar->dimen_type[i] == DIMEN_VECTOR)
2662           {
2663             ar->type = AR_SECTION;
2664             break;
2665           }
2666     }
2667
2668   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
2669     return FAILURE;
2670
2671   return SUCCESS;
2672 }
2673
2674
2675 static try
2676 resolve_substring (gfc_ref * ref)
2677 {
2678
2679   if (ref->u.ss.start != NULL)
2680     {
2681       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
2682         return FAILURE;
2683
2684       if (ref->u.ss.start->ts.type != BT_INTEGER)
2685         {
2686           gfc_error ("Substring start index at %L must be of type INTEGER",
2687                      &ref->u.ss.start->where);
2688           return FAILURE;
2689         }
2690
2691       if (ref->u.ss.start->rank != 0)
2692         {
2693           gfc_error ("Substring start index at %L must be scalar",
2694                      &ref->u.ss.start->where);
2695           return FAILURE;
2696         }
2697
2698       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
2699           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
2700               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
2701         {
2702           gfc_error ("Substring start index at %L is less than one",
2703                      &ref->u.ss.start->where);
2704           return FAILURE;
2705         }
2706     }
2707
2708   if (ref->u.ss.end != NULL)
2709     {
2710       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
2711         return FAILURE;
2712
2713       if (ref->u.ss.end->ts.type != BT_INTEGER)
2714         {
2715           gfc_error ("Substring end index at %L must be of type INTEGER",
2716                      &ref->u.ss.end->where);
2717           return FAILURE;
2718         }
2719
2720       if (ref->u.ss.end->rank != 0)
2721         {
2722           gfc_error ("Substring end index at %L must be scalar",
2723                      &ref->u.ss.end->where);
2724           return FAILURE;
2725         }
2726
2727       if (ref->u.ss.length != NULL
2728           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
2729           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
2730               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
2731         {
2732           gfc_error ("Substring end index at %L exceeds the string length",
2733                      &ref->u.ss.start->where);
2734           return FAILURE;
2735         }
2736     }
2737
2738   return SUCCESS;
2739 }
2740
2741
2742 /* Resolve subtype references.  */
2743
2744 static try
2745 resolve_ref (gfc_expr * expr)
2746 {
2747   int current_part_dimension, n_components, seen_part_dimension;
2748   gfc_ref *ref;
2749
2750   for (ref = expr->ref; ref; ref = ref->next)
2751     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
2752       {
2753         find_array_spec (expr);
2754         break;
2755       }
2756
2757   for (ref = expr->ref; ref; ref = ref->next)
2758     switch (ref->type)
2759       {
2760       case REF_ARRAY:
2761         if (resolve_array_ref (&ref->u.ar) == FAILURE)
2762           return FAILURE;
2763         break;
2764
2765       case REF_COMPONENT:
2766         break;
2767
2768       case REF_SUBSTRING:
2769         resolve_substring (ref);
2770         break;
2771       }
2772
2773   /* Check constraints on part references.  */
2774
2775   current_part_dimension = 0;
2776   seen_part_dimension = 0;
2777   n_components = 0;
2778
2779   for (ref = expr->ref; ref; ref = ref->next)
2780     {
2781       switch (ref->type)
2782         {
2783         case REF_ARRAY:
2784           switch (ref->u.ar.type)
2785             {
2786             case AR_FULL:
2787             case AR_SECTION:
2788               current_part_dimension = 1;
2789               break;
2790
2791             case AR_ELEMENT:
2792               current_part_dimension = 0;
2793               break;
2794
2795             case AR_UNKNOWN:
2796               gfc_internal_error ("resolve_ref(): Bad array reference");
2797             }
2798
2799           break;
2800
2801         case REF_COMPONENT:
2802           if (current_part_dimension || seen_part_dimension)
2803             {
2804               if (ref->u.c.component->pointer)
2805                 {
2806                   gfc_error
2807                     ("Component to the right of a part reference with nonzero "
2808                      "rank must not have the POINTER attribute at %L",
2809                      &expr->where);
2810                   return FAILURE;
2811                 }
2812               else if (ref->u.c.component->allocatable)
2813                 {
2814                   gfc_error
2815                     ("Component to the right of a part reference with nonzero "
2816                      "rank must not have the ALLOCATABLE attribute at %L",
2817                      &expr->where);
2818                   return FAILURE;
2819                 }
2820             }
2821
2822           n_components++;
2823           break;
2824
2825         case REF_SUBSTRING:
2826           break;
2827         }
2828
2829       if (((ref->type == REF_COMPONENT && n_components > 1)
2830            || ref->next == NULL)
2831           && current_part_dimension
2832           && seen_part_dimension)
2833         {
2834
2835           gfc_error ("Two or more part references with nonzero rank must "
2836                      "not be specified at %L", &expr->where);
2837           return FAILURE;
2838         }
2839
2840       if (ref->type == REF_COMPONENT)
2841         {
2842           if (current_part_dimension)
2843             seen_part_dimension = 1;
2844
2845           /* reset to make sure */
2846           current_part_dimension = 0;
2847         }
2848     }
2849
2850   return SUCCESS;
2851 }
2852
2853
2854 /* Given an expression, determine its shape.  This is easier than it sounds.
2855    Leaves the shape array NULL if it is not possible to determine the shape.  */
2856
2857 static void
2858 expression_shape (gfc_expr * e)
2859 {
2860   mpz_t array[GFC_MAX_DIMENSIONS];
2861   int i;
2862
2863   if (e->rank == 0 || e->shape != NULL)
2864     return;
2865
2866   for (i = 0; i < e->rank; i++)
2867     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
2868       goto fail;
2869
2870   e->shape = gfc_get_shape (e->rank);
2871
2872   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
2873
2874   return;
2875
2876 fail:
2877   for (i--; i >= 0; i--)
2878     mpz_clear (array[i]);
2879 }
2880
2881
2882 /* Given a variable expression node, compute the rank of the expression by
2883    examining the base symbol and any reference structures it may have.  */
2884
2885 static void
2886 expression_rank (gfc_expr * e)
2887 {
2888   gfc_ref *ref;
2889   int i, rank;
2890
2891   if (e->ref == NULL)
2892     {
2893       if (e->expr_type == EXPR_ARRAY)
2894         goto done;
2895       /* Constructors can have a rank different from one via RESHAPE().  */
2896
2897       if (e->symtree == NULL)
2898         {
2899           e->rank = 0;
2900           goto done;
2901         }
2902
2903       e->rank = (e->symtree->n.sym->as == NULL)
2904                   ? 0 : e->symtree->n.sym->as->rank;
2905       goto done;
2906     }
2907
2908   rank = 0;
2909
2910   for (ref = e->ref; ref; ref = ref->next)
2911     {
2912       if (ref->type != REF_ARRAY)
2913         continue;
2914
2915       if (ref->u.ar.type == AR_FULL)
2916         {
2917           rank = ref->u.ar.as->rank;
2918           break;
2919         }
2920
2921       if (ref->u.ar.type == AR_SECTION)
2922         {
2923           /* Figure out the rank of the section.  */
2924           if (rank != 0)
2925             gfc_internal_error ("expression_rank(): Two array specs");
2926
2927           for (i = 0; i < ref->u.ar.dimen; i++)
2928             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
2929                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
2930               rank++;
2931
2932           break;
2933         }
2934     }
2935
2936   e->rank = rank;
2937
2938 done:
2939   expression_shape (e);
2940 }
2941
2942
2943 /* Resolve a variable expression.  */
2944
2945 static try
2946 resolve_variable (gfc_expr * e)
2947 {
2948   gfc_symbol *sym;
2949   try t;
2950
2951   t = SUCCESS;
2952
2953   if (e->symtree == NULL)
2954     return FAILURE;
2955
2956   if (e->ref && resolve_ref (e) == FAILURE)
2957     return FAILURE;
2958
2959   sym = e->symtree->n.sym;
2960   if (sym->attr.flavor == FL_PROCEDURE && !sym->attr.function)
2961     {
2962       e->ts.type = BT_PROCEDURE;
2963       return SUCCESS;
2964     }
2965
2966   if (sym->ts.type != BT_UNKNOWN)
2967     gfc_variable_attr (e, &e->ts);
2968   else
2969     {
2970       /* Must be a simple variable reference.  */
2971       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
2972         return FAILURE;
2973       e->ts = sym->ts;
2974     }
2975
2976   if (check_assumed_size_reference (sym, e))
2977     return FAILURE;
2978
2979   /* Deal with forward references to entries during resolve_code, to
2980      satisfy, at least partially, 12.5.2.5.  */
2981   if (gfc_current_ns->entries
2982         && current_entry_id == sym->entry_id
2983         && cs_base
2984         && cs_base->current
2985         && cs_base->current->op != EXEC_ENTRY)
2986     {
2987       gfc_entry_list *entry;
2988       gfc_formal_arglist *formal;
2989       int n;
2990       bool seen;
2991
2992       /* If the symbol is a dummy...  */
2993       if (sym->attr.dummy)
2994         {
2995           entry = gfc_current_ns->entries;
2996           seen = false;
2997
2998           /* ...test if the symbol is a parameter of previous entries.  */
2999           for (; entry && entry->id <= current_entry_id; entry = entry->next)
3000             for (formal = entry->sym->formal; formal; formal = formal->next)
3001               {
3002                 if (formal->sym && sym->name == formal->sym->name)
3003                   seen = true;
3004               }
3005
3006           /*  If it has not been seen as a dummy, this is an error.  */
3007           if (!seen)
3008             {
3009               if (specification_expr)
3010                 gfc_error ("Variable '%s',used in a specification expression, "
3011                            "is referenced at %L before the ENTRY statement "
3012                            "in which it is a parameter",
3013                            sym->name, &cs_base->current->loc);
3014               else
3015                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
3016                            "statement in which it is a parameter",
3017                            sym->name, &cs_base->current->loc);
3018               t = FAILURE;
3019             }
3020         }
3021
3022       /* Now do the same check on the specification expressions.  */
3023       specification_expr = 1;
3024       if (sym->ts.type == BT_CHARACTER
3025             && gfc_resolve_expr (sym->ts.cl->length) == FAILURE)
3026         t = FAILURE;
3027
3028       if (sym->as)
3029         for (n = 0; n < sym->as->rank; n++)
3030           {
3031              specification_expr = 1;
3032              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
3033                t = FAILURE;
3034              specification_expr = 1;
3035              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
3036                t = FAILURE;
3037           }
3038       specification_expr = 0;
3039
3040       if (t == SUCCESS)
3041         /* Update the symbol's entry level.  */
3042         sym->entry_id = current_entry_id + 1;
3043     }
3044
3045   return t;
3046 }
3047
3048
3049 /* Resolve an expression.  That is, make sure that types of operands agree
3050    with their operators, intrinsic operators are converted to function calls
3051    for overloaded types and unresolved function references are resolved.  */
3052
3053 try
3054 gfc_resolve_expr (gfc_expr * e)
3055 {
3056   try t;
3057
3058   if (e == NULL)
3059     return SUCCESS;
3060
3061   switch (e->expr_type)
3062     {
3063     case EXPR_OP:
3064       t = resolve_operator (e);
3065       break;
3066
3067     case EXPR_FUNCTION:
3068       t = resolve_function (e);
3069       break;
3070
3071     case EXPR_VARIABLE:
3072       t = resolve_variable (e);
3073       if (t == SUCCESS)
3074         expression_rank (e);
3075       break;
3076
3077     case EXPR_SUBSTRING:
3078       t = resolve_ref (e);
3079       break;
3080
3081     case EXPR_CONSTANT:
3082     case EXPR_NULL:
3083       t = SUCCESS;
3084       break;
3085
3086     case EXPR_ARRAY:
3087       t = FAILURE;
3088       if (resolve_ref (e) == FAILURE)
3089         break;
3090
3091       t = gfc_resolve_array_constructor (e);
3092       /* Also try to expand a constructor.  */
3093       if (t == SUCCESS)
3094         {
3095           expression_rank (e);
3096           gfc_expand_constructor (e);
3097         }
3098
3099       /* This provides the opportunity for the length of constructors with character
3100         valued function elements to propogate the string length to the expression.  */
3101       if (e->ts.type == BT_CHARACTER)
3102         gfc_resolve_character_array_constructor (e);
3103
3104       break;
3105
3106     case EXPR_STRUCTURE:
3107       t = resolve_ref (e);
3108       if (t == FAILURE)
3109         break;
3110
3111       t = resolve_structure_cons (e);
3112       if (t == FAILURE)
3113         break;
3114
3115       t = gfc_simplify_expr (e, 0);
3116       break;
3117
3118     default:
3119       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
3120     }
3121
3122   return t;
3123 }
3124
3125
3126 /* Resolve an expression from an iterator.  They must be scalar and have
3127    INTEGER or (optionally) REAL type.  */
3128
3129 static try
3130 gfc_resolve_iterator_expr (gfc_expr * expr, bool real_ok,
3131                            const char * name_msgid)
3132 {
3133   if (gfc_resolve_expr (expr) == FAILURE)
3134     return FAILURE;
3135
3136   if (expr->rank != 0)
3137     {
3138       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
3139       return FAILURE;
3140     }
3141
3142   if (!(expr->ts.type == BT_INTEGER
3143         || (expr->ts.type == BT_REAL && real_ok)))
3144     {
3145       if (real_ok)
3146         gfc_error ("%s at %L must be INTEGER or REAL", _(name_msgid),
3147                    &expr->where);
3148       else
3149         gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
3150       return FAILURE;
3151     }
3152   return SUCCESS;
3153 }
3154
3155
3156 /* Resolve the expressions in an iterator structure.  If REAL_OK is
3157    false allow only INTEGER type iterators, otherwise allow REAL types.  */
3158
3159 try
3160 gfc_resolve_iterator (gfc_iterator * iter, bool real_ok)
3161 {
3162
3163   if (iter->var->ts.type == BT_REAL)
3164     gfc_notify_std (GFC_STD_F95_DEL,
3165                     "Obsolete: REAL DO loop iterator at %L",
3166                     &iter->var->where);
3167
3168   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
3169       == FAILURE)
3170     return FAILURE;
3171
3172   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
3173     {
3174       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
3175                  &iter->var->where);
3176       return FAILURE;
3177     }
3178
3179   if (gfc_resolve_iterator_expr (iter->start, real_ok,
3180                                  "Start expression in DO loop") == FAILURE)
3181     return FAILURE;
3182
3183   if (gfc_resolve_iterator_expr (iter->end, real_ok,
3184                                  "End expression in DO loop") == FAILURE)
3185     return FAILURE;
3186
3187   if (gfc_resolve_iterator_expr (iter->step, real_ok,
3188                                  "Step expression in DO loop") == FAILURE)
3189     return FAILURE;
3190
3191   if (iter->step->expr_type == EXPR_CONSTANT)
3192     {
3193       if ((iter->step->ts.type == BT_INTEGER
3194            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
3195           || (iter->step->ts.type == BT_REAL
3196               && mpfr_sgn (iter->step->value.real) == 0))
3197         {
3198           gfc_error ("Step expression in DO loop at %L cannot be zero",
3199                      &iter->step->where);
3200           return FAILURE;
3201         }
3202     }
3203
3204   /* Convert start, end, and step to the same type as var.  */
3205   if (iter->start->ts.kind != iter->var->ts.kind
3206       || iter->start->ts.type != iter->var->ts.type)
3207     gfc_convert_type (iter->start, &iter->var->ts, 2);
3208
3209   if (iter->end->ts.kind != iter->var->ts.kind
3210       || iter->end->ts.type != iter->var->ts.type)
3211     gfc_convert_type (iter->end, &iter->var->ts, 2);
3212
3213   if (iter->step->ts.kind != iter->var->ts.kind
3214       || iter->step->ts.type != iter->var->ts.type)
3215     gfc_convert_type (iter->step, &iter->var->ts, 2);
3216
3217   return SUCCESS;
3218 }
3219
3220
3221 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
3222    to be a scalar INTEGER variable.  The subscripts and stride are scalar
3223    INTEGERs, and if stride is a constant it must be nonzero.  */
3224
3225 static void
3226 resolve_forall_iterators (gfc_forall_iterator * iter)
3227 {
3228
3229   while (iter)
3230     {
3231       if (gfc_resolve_expr (iter->var) == SUCCESS
3232           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
3233         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
3234                    &iter->var->where);
3235
3236       if (gfc_resolve_expr (iter->start) == SUCCESS
3237           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
3238         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
3239                    &iter->start->where);
3240       if (iter->var->ts.kind != iter->start->ts.kind)
3241         gfc_convert_type (iter->start, &iter->var->ts, 2);
3242
3243       if (gfc_resolve_expr (iter->end) == SUCCESS
3244           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
3245         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
3246                    &iter->end->where);
3247       if (iter->var->ts.kind != iter->end->ts.kind)
3248         gfc_convert_type (iter->end, &iter->var->ts, 2);
3249
3250       if (gfc_resolve_expr (iter->stride) == SUCCESS)
3251         {
3252           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
3253             gfc_error ("FORALL stride expression at %L must be a scalar %s",
3254                         &iter->stride->where, "INTEGER");
3255
3256           if (iter->stride->expr_type == EXPR_CONSTANT
3257               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
3258             gfc_error ("FORALL stride expression at %L cannot be zero",
3259                        &iter->stride->where);
3260         }
3261       if (iter->var->ts.kind != iter->stride->ts.kind)
3262         gfc_convert_type (iter->stride, &iter->var->ts, 2);
3263
3264       iter = iter->next;
3265     }
3266 }
3267
3268
3269 /* Given a pointer to a symbol that is a derived type, see if any components
3270    have the POINTER attribute.  The search is recursive if necessary.
3271    Returns zero if no pointer components are found, nonzero otherwise.  */
3272
3273 static int
3274 derived_pointer (gfc_symbol * sym)
3275 {
3276   gfc_component *c;
3277
3278   for (c = sym->components; c; c = c->next)
3279     {
3280       if (c->pointer)
3281         return 1;
3282
3283       if (c->ts.type == BT_DERIVED && derived_pointer (c->ts.derived))
3284         return 1;
3285     }
3286
3287   return 0;
3288 }
3289
3290
3291 /* Given a pointer to a symbol that is a derived type, see if it's
3292    inaccessible, i.e. if it's defined in another module and the components are
3293    PRIVATE.  The search is recursive if necessary.  Returns zero if no
3294    inaccessible components are found, nonzero otherwise.  */
3295
3296 static int
3297 derived_inaccessible (gfc_symbol *sym)
3298 {
3299   gfc_component *c;
3300
3301   if (sym->attr.use_assoc && sym->component_access == ACCESS_PRIVATE)
3302     return 1;
3303
3304   for (c = sym->components; c; c = c->next)
3305     {
3306         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.derived))
3307           return 1;
3308     }
3309
3310   return 0;
3311 }
3312
3313
3314 /* Resolve the argument of a deallocate expression.  The expression must be
3315    a pointer or a full array.  */
3316
3317 static try
3318 resolve_deallocate_expr (gfc_expr * e)
3319 {
3320   symbol_attribute attr;
3321   int allocatable;
3322   gfc_ref *ref;
3323
3324   if (gfc_resolve_expr (e) == FAILURE)
3325     return FAILURE;
3326
3327   attr = gfc_expr_attr (e);
3328   if (attr.pointer)
3329     return SUCCESS;
3330
3331   if (e->expr_type != EXPR_VARIABLE)
3332     goto bad;
3333
3334   allocatable = e->symtree->n.sym->attr.allocatable;
3335   for (ref = e->ref; ref; ref = ref->next)
3336     switch (ref->type)
3337       {
3338       case REF_ARRAY:
3339         if (ref->u.ar.type != AR_FULL)
3340           allocatable = 0;
3341         break;
3342
3343       case REF_COMPONENT:
3344         allocatable = (ref->u.c.component->as != NULL
3345                        && ref->u.c.component->as->type == AS_DEFERRED);
3346         break;
3347
3348       case REF_SUBSTRING:
3349         allocatable = 0;
3350         break;
3351       }
3352
3353   if (allocatable == 0)
3354     {
3355     bad:
3356       gfc_error ("Expression in DEALLOCATE statement at %L must be "
3357                  "ALLOCATABLE or a POINTER", &e->where);
3358     }
3359
3360   if (e->symtree->n.sym->attr.intent == INTENT_IN)
3361     {
3362       gfc_error ("Can't deallocate INTENT(IN) variable '%s' at %L",
3363                  e->symtree->n.sym->name, &e->where);
3364       return FAILURE;
3365     }
3366
3367   return SUCCESS;
3368 }
3369
3370 /* Returns true if the expression e contains a reference the symbol sym.  */
3371 static bool
3372 find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
3373 {
3374   gfc_actual_arglist *arg;
3375   gfc_ref *ref;
3376   int i;
3377   bool rv = false;
3378
3379   if (e == NULL)
3380     return rv;
3381
3382   switch (e->expr_type)
3383     {
3384     case EXPR_FUNCTION:
3385       for (arg = e->value.function.actual; arg; arg = arg->next)
3386         rv = rv || find_sym_in_expr (sym, arg->expr);
3387       break;
3388
3389     /* If the variable is not the same as the dependent, 'sym', and
3390        it is not marked as being declared and it is in the same
3391        namespace as 'sym', add it to the local declarations.  */
3392     case EXPR_VARIABLE:
3393       if (sym == e->symtree->n.sym)
3394         return true;
3395       break;
3396
3397     case EXPR_OP:
3398       rv = rv || find_sym_in_expr (sym, e->value.op.op1);
3399       rv = rv || find_sym_in_expr (sym, e->value.op.op2);
3400       break;
3401
3402     default:
3403       break;
3404     }
3405
3406   if (e->ref)
3407     {
3408       for (ref = e->ref; ref; ref = ref->next)
3409         {
3410           switch (ref->type)
3411             {
3412             case REF_ARRAY:
3413               for (i = 0; i < ref->u.ar.dimen; i++)
3414                 {
3415                   rv = rv || find_sym_in_expr (sym, ref->u.ar.start[i]);
3416                   rv = rv || find_sym_in_expr (sym, ref->u.ar.end[i]);
3417                   rv = rv || find_sym_in_expr (sym, ref->u.ar.stride[i]);
3418                 }
3419               break;
3420
3421             case REF_SUBSTRING:
3422               rv = rv || find_sym_in_expr (sym, ref->u.ss.start);
3423               rv = rv || find_sym_in_expr (sym, ref->u.ss.end);
3424               break;
3425
3426             case REF_COMPONENT:
3427               if (ref->u.c.component->ts.type == BT_CHARACTER
3428                     && ref->u.c.component->ts.cl->length->expr_type
3429                                                 != EXPR_CONSTANT)
3430                 rv = rv || find_sym_in_expr (sym, ref->u.c.component->ts.cl->length);
3431
3432               if (ref->u.c.component->as)
3433                 for (i = 0; i < ref->u.c.component->as->rank; i++)
3434                   {
3435                     rv = rv || find_sym_in_expr (sym, ref->u.c.component->as->lower[i]);
3436                     rv = rv || find_sym_in_expr (sym, ref->u.c.component->as->upper[i]);
3437                   }
3438               break;
3439             }
3440         }
3441     }
3442   return rv;
3443 }
3444
3445
3446 /* Given the expression node e for an allocatable/pointer of derived type to be
3447    allocated, get the expression node to be initialized afterwards (needed for
3448    derived types with default initializers, and derived types with allocatable
3449    components that need nullification.)  */
3450
3451 static gfc_expr *
3452 expr_to_initialize (gfc_expr * e)
3453 {
3454   gfc_expr *result;
3455   gfc_ref *ref;
3456   int i;
3457
3458   result = gfc_copy_expr (e);
3459
3460   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
3461   for (ref = result->ref; ref; ref = ref->next)
3462     if (ref->type == REF_ARRAY && ref->next == NULL)
3463       {
3464         ref->u.ar.type = AR_FULL;
3465
3466         for (i = 0; i < ref->u.ar.dimen; i++)
3467           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
3468
3469         result->rank = ref->u.ar.dimen;
3470         break;
3471       }
3472
3473   return result;
3474 }
3475
3476
3477 /* Resolve the expression in an ALLOCATE statement, doing the additional
3478    checks to see whether the expression is OK or not.  The expression must
3479    have a trailing array reference that gives the size of the array.  */
3480
3481 static try
3482 resolve_allocate_expr (gfc_expr * e, gfc_code * code)
3483 {
3484   int i, pointer, allocatable, dimension;
3485   symbol_attribute attr;
3486   gfc_ref *ref, *ref2;
3487   gfc_array_ref *ar;
3488   gfc_code *init_st;
3489   gfc_expr *init_e;
3490   gfc_symbol *sym;
3491   gfc_alloc *a;
3492
3493   if (gfc_resolve_expr (e) == FAILURE)
3494     return FAILURE;
3495
3496   if (code->expr && code->expr->expr_type == EXPR_VARIABLE)
3497     sym = code->expr->symtree->n.sym;
3498   else
3499     sym = NULL;
3500
3501   /* Make sure the expression is allocatable or a pointer.  If it is
3502      pointer, the next-to-last reference must be a pointer.  */
3503
3504   ref2 = NULL;
3505
3506   if (e->expr_type != EXPR_VARIABLE)
3507     {
3508       allocatable = 0;
3509
3510       attr = gfc_expr_attr (e);
3511       pointer = attr.pointer;
3512       dimension = attr.dimension;
3513
3514     }
3515   else
3516     {
3517       allocatable = e->symtree->n.sym->attr.allocatable;
3518       pointer = e->symtree->n.sym->attr.pointer;
3519       dimension = e->symtree->n.sym->attr.dimension;
3520
3521       if (sym == e->symtree->n.sym && sym->ts.type != BT_DERIVED)
3522         {
3523           gfc_error ("The STAT variable '%s' in an ALLOCATE statement must "
3524                      "not be allocated in the same statement at %L",
3525                       sym->name, &e->where);
3526           return FAILURE;
3527         }
3528
3529       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
3530         switch (ref->type)
3531           {
3532           case REF_ARRAY:
3533             if (ref->next != NULL)
3534               pointer = 0;
3535             break;
3536
3537           case REF_COMPONENT:
3538             allocatable = (ref->u.c.component->as != NULL
3539                            && ref->u.c.component->as->type == AS_DEFERRED);
3540
3541             pointer = ref->u.c.component->pointer;
3542             dimension = ref->u.c.component->dimension;
3543             break;
3544
3545           case REF_SUBSTRING:
3546             allocatable = 0;
3547             pointer = 0;
3548             break;
3549           }
3550     }
3551
3552   if (allocatable == 0 && pointer == 0)
3553     {
3554       gfc_error ("Expression in ALLOCATE statement at %L must be "
3555                  "ALLOCATABLE or a POINTER", &e->where);
3556       return FAILURE;
3557     }
3558
3559   if (e->symtree->n.sym->attr.intent == INTENT_IN)
3560     {
3561       gfc_error ("Can't allocate INTENT(IN) variable '%s' at %L",
3562                  e->symtree->n.sym->name, &e->where);
3563       return FAILURE;
3564     }
3565
3566   /* Add default initializer for those derived types that need them.  */
3567   if (e->ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&e->ts)))
3568     {
3569         init_st = gfc_get_code ();
3570         init_st->loc = code->loc;
3571         init_st->op = EXEC_INIT_ASSIGN;
3572         init_st->expr = expr_to_initialize (e);
3573         init_st->expr2 = init_e;
3574         init_st->next = code->next;
3575         code->next = init_st;
3576     }
3577
3578   if (pointer && dimension == 0)
3579     return SUCCESS;
3580
3581   /* Make sure the next-to-last reference node is an array specification.  */
3582
3583   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL)
3584     {
3585       gfc_error ("Array specification required in ALLOCATE statement "
3586                  "at %L", &e->where);
3587       return FAILURE;
3588     }
3589
3590   /* Make sure that the array section reference makes sense in the
3591     context of an ALLOCATE specification.  */
3592
3593   ar = &ref2->u.ar;
3594
3595   for (i = 0; i < ar->dimen; i++)
3596     {
3597       if (ref2->u.ar.type == AR_ELEMENT)
3598         goto check_symbols;
3599
3600       switch (ar->dimen_type[i])
3601         {
3602         case DIMEN_ELEMENT:
3603           break;
3604
3605         case DIMEN_RANGE:
3606           if (ar->start[i] != NULL
3607               && ar->end[i] != NULL
3608               && ar->stride[i] == NULL)
3609             break;
3610
3611           /* Fall Through...  */
3612
3613         case DIMEN_UNKNOWN:
3614         case DIMEN_VECTOR:
3615           gfc_error ("Bad array specification in ALLOCATE statement at %L",
3616                      &e->where);
3617           return FAILURE;
3618         }
3619
3620 check_symbols:
3621
3622       for (a = code->ext.alloc_list; a; a = a->next)
3623         {
3624           sym = a->expr->symtree->n.sym;
3625
3626           /* TODO - check derived type components.  */
3627           if (sym->ts.type == BT_DERIVED)
3628             continue;
3629
3630           if ((ar->start[i] != NULL && find_sym_in_expr (sym, ar->start[i]))
3631                  || (ar->end[i] != NULL && find_sym_in_expr (sym, ar->end[i])))
3632             {
3633               gfc_error ("'%s' must not appear an the array specification at "
3634                          "%L in the same ALLOCATE statement where it is "
3635                          "itself allocated", sym->name, &ar->where);
3636               return FAILURE;
3637             }
3638         }
3639     }
3640
3641   return SUCCESS;
3642 }
3643
3644
3645 /************ SELECT CASE resolution subroutines ************/
3646
3647 /* Callback function for our mergesort variant.  Determines interval
3648    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
3649    op1 > op2.  Assumes we're not dealing with the default case.  
3650    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
3651    There are nine situations to check.  */
3652
3653 static int
3654 compare_cases (const gfc_case * op1, const gfc_case * op2)
3655 {
3656   int retval;
3657
3658   if (op1->low == NULL) /* op1 = (:L)  */
3659     {
3660       /* op2 = (:N), so overlap.  */
3661       retval = 0;
3662       /* op2 = (M:) or (M:N),  L < M  */
3663       if (op2->low != NULL
3664           && gfc_compare_expr (op1->high, op2->low) < 0)
3665         retval = -1;
3666     }
3667   else if (op1->high == NULL) /* op1 = (K:)  */
3668     {
3669       /* op2 = (M:), so overlap.  */
3670       retval = 0;
3671       /* op2 = (:N) or (M:N), K > N  */
3672       if (op2->high != NULL
3673           && gfc_compare_expr (op1->low, op2->high) > 0)
3674         retval = 1;
3675     }
3676   else /* op1 = (K:L)  */
3677     {
3678       if (op2->low == NULL)       /* op2 = (:N), K > N  */
3679         retval = (gfc_compare_expr (op1->low, op2->high) > 0) ? 1 : 0;
3680       else if (op2->high == NULL) /* op2 = (M:), L < M  */
3681         retval = (gfc_compare_expr (op1->high, op2->low) < 0) ? -1 : 0;
3682       else                        /* op2 = (M:N)  */
3683         {
3684           retval =  0;
3685           /* L < M  */
3686           if (gfc_compare_expr (op1->high, op2->low) < 0)
3687             retval =  -1;
3688           /* K > N  */
3689           else if (gfc_compare_expr (op1->low, op2->high) > 0)
3690             retval =  1;
3691         }
3692     }
3693
3694   return retval;
3695 }
3696
3697
3698 /* Merge-sort a double linked case list, detecting overlap in the
3699    process.  LIST is the head of the double linked case list before it
3700    is sorted.  Returns the head of the sorted list if we don't see any
3701    overlap, or NULL otherwise.  */
3702
3703 static gfc_case *
3704 check_case_overlap (gfc_case * list)
3705 {
3706   gfc_case *p, *q, *e, *tail;
3707   int insize, nmerges, psize, qsize, cmp, overlap_seen;
3708
3709   /* If the passed list was empty, return immediately.  */
3710   if (!list)
3711     return NULL;
3712
3713   overlap_seen = 0;
3714   insize = 1;
3715
3716   /* Loop unconditionally.  The only exit from this loop is a return
3717      statement, when we've finished sorting the case list.  */
3718   for (;;)
3719     {
3720       p = list;
3721       list = NULL;
3722       tail = NULL;
3723
3724       /* Count the number of merges we do in this pass.  */
3725       nmerges = 0;
3726
3727       /* Loop while there exists a merge to be done.  */
3728       while (p)
3729         {
3730           int i;
3731
3732           /* Count this merge.  */
3733           nmerges++;
3734
3735           /* Cut the list in two pieces by stepping INSIZE places
3736              forward in the list, starting from P.  */
3737           psize = 0;
3738           q = p;
3739           for (i = 0; i < insize; i++)
3740             {
3741               psize++;
3742               q = q->right;
3743               if (!q)
3744                 break;
3745             }
3746           qsize = insize;
3747
3748           /* Now we have two lists.  Merge them!  */
3749           while (psize > 0 || (qsize > 0 && q != NULL))
3750             {
3751
3752               /* See from which the next case to merge comes from.  */
3753               if (psize == 0)
3754                 {
3755                   /* P is empty so the next case must come from Q.  */
3756                   e = q;
3757                   q = q->right;
3758                   qsize--;
3759                 }
3760               else if (qsize == 0 || q == NULL)
3761                 {
3762                   /* Q is empty.  */
3763                   e = p;
3764                   p = p->right;
3765                   psize--;
3766                 }
3767               else
3768                 {
3769                   cmp = compare_cases (p, q);
3770                   if (cmp < 0)
3771                     {
3772                       /* The whole case range for P is less than the
3773                          one for Q.  */
3774                       e = p;
3775                       p = p->right;
3776                       psize--;
3777                     }
3778                   else if (cmp > 0)
3779                     {
3780                       /* The whole case range for Q is greater than
3781                          the case range for P.  */
3782                       e = q;
3783                       q = q->right;
3784                       qsize--;
3785                     }
3786                   else
3787                     {
3788                       /* The cases overlap, or they are the same
3789                          element in the list.  Either way, we must
3790                          issue an error and get the next case from P.  */
3791                       /* FIXME: Sort P and Q by line number.  */
3792                       gfc_error ("CASE label at %L overlaps with CASE "
3793                                  "label at %L", &p->where, &q->where);
3794                       overlap_seen = 1;
3795                       e = p;
3796                       p = p->right;
3797                       psize--;
3798                     }
3799                 }
3800
3801                 /* Add the next element to the merged list.  */
3802               if (tail)
3803                 tail->right = e;
3804               else
3805                 list = e;
3806               e->left = tail;
3807               tail = e;
3808             }
3809
3810           /* P has now stepped INSIZE places along, and so has Q.  So
3811              they're the same.  */
3812           p = q;
3813         }
3814       tail->right = NULL;
3815
3816       /* If we have done only one merge or none at all, we've
3817          finished sorting the cases.  */
3818       if (nmerges <= 1)
3819         {
3820           if (!overlap_seen)
3821             return list;
3822           else
3823             return NULL;
3824         }
3825
3826       /* Otherwise repeat, merging lists twice the size.  */
3827       insize *= 2;
3828     }
3829 }
3830
3831
3832 /* Check to see if an expression is suitable for use in a CASE statement.
3833    Makes sure that all case expressions are scalar constants of the same
3834    type.  Return FAILURE if anything is wrong.  */
3835
3836 static try
3837 validate_case_label_expr (gfc_expr * e, gfc_expr * case_expr)
3838 {
3839   if (e == NULL) return SUCCESS;
3840
3841   if (e->ts.type != case_expr->ts.type)
3842     {
3843       gfc_error ("Expression in CASE statement at %L must be of type %s",
3844                  &e->where, gfc_basic_typename (case_expr->ts.type));
3845       return FAILURE;
3846     }
3847
3848   /* C805 (R808) For a given case-construct, each case-value shall be of
3849      the same type as case-expr.  For character type, length differences
3850      are allowed, but the kind type parameters shall be the same.  */
3851
3852   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
3853     {
3854       gfc_error("Expression in CASE statement at %L must be kind %d",
3855                 &e->where, case_expr->ts.kind);
3856       return FAILURE;
3857     }
3858
3859   /* Convert the case value kind to that of case expression kind, if needed.
3860      FIXME:  Should a warning be issued?  */
3861   if (e->ts.kind != case_expr->ts.kind)
3862     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
3863
3864   if (e->rank != 0)
3865     {
3866       gfc_error ("Expression in CASE statement at %L must be scalar",
3867                  &e->where);
3868       return FAILURE;
3869     }
3870
3871   return SUCCESS;
3872 }
3873
3874
3875 /* Given a completely parsed select statement, we:
3876
3877      - Validate all expressions and code within the SELECT.
3878      - Make sure that the selection expression is not of the wrong type.
3879      - Make sure that no case ranges overlap.
3880      - Eliminate unreachable cases and unreachable code resulting from
3881        removing case labels.
3882
3883    The standard does allow unreachable cases, e.g. CASE (5:3).  But
3884    they are a hassle for code generation, and to prevent that, we just
3885    cut them out here.  This is not necessary for overlapping cases
3886    because they are illegal and we never even try to generate code.
3887
3888    We have the additional caveat that a SELECT construct could have
3889    been a computed GOTO in the source code. Fortunately we can fairly
3890    easily work around that here: The case_expr for a "real" SELECT CASE
3891    is in code->expr1, but for a computed GOTO it is in code->expr2. All
3892    we have to do is make sure that the case_expr is a scalar integer
3893    expression.  */
3894
3895 static void
3896 resolve_select (gfc_code * code)
3897 {
3898   gfc_code *body;
3899   gfc_expr *case_expr;
3900   gfc_case *cp, *default_case, *tail, *head;
3901   int seen_unreachable;
3902   int seen_logical;
3903   int ncases;
3904   bt type;
3905   try t;
3906
3907   if (code->expr == NULL)
3908     {
3909       /* This was actually a computed GOTO statement.  */
3910       case_expr = code->expr2;
3911       if (case_expr->ts.type != BT_INTEGER
3912           || case_expr->rank != 0)
3913         gfc_error ("Selection expression in computed GOTO statement "
3914                    "at %L must be a scalar integer expression",
3915                    &case_expr->where);
3916
3917       /* Further checking is not necessary because this SELECT was built
3918          by the compiler, so it should always be OK.  Just move the
3919          case_expr from expr2 to expr so that we can handle computed
3920          GOTOs as normal SELECTs from here on.  */
3921       code->expr = code->expr2;
3922       code->expr2 = NULL;
3923       return;
3924     }
3925
3926   case_expr = code->expr;
3927
3928   type = case_expr->ts.type;
3929   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
3930     {
3931       gfc_error ("Argument of SELECT statement at %L cannot be %s",
3932                  &case_expr->where, gfc_typename (&case_expr->ts));
3933
3934       /* Punt. Going on here just produce more garbage error messages.  */
3935       return;
3936     }
3937
3938   if (case_expr->rank != 0)
3939     {
3940       gfc_error ("Argument of SELECT statement at %L must be a scalar "
3941                  "expression", &case_expr->where);
3942
3943       /* Punt.  */
3944       return;
3945     }
3946
3947   /* PR 19168 has a long discussion concerning a mismatch of the kinds
3948      of the SELECT CASE expression and its CASE values.  Walk the lists
3949      of case values, and if we find a mismatch, promote case_expr to
3950      the appropriate kind.  */
3951
3952   if (type == BT_LOGICAL || type == BT_INTEGER)
3953     {
3954       for (body = code->block; body; body = body->block)
3955         {
3956           /* Walk the case label list.  */
3957           for (cp = body->ext.case_list; cp; cp = cp->next)
3958             {
3959               /* Intercept the DEFAULT case.  It does not have a kind.  */
3960               if (cp->low == NULL && cp->high == NULL)
3961                 continue;
3962
3963               /* Unreachable case ranges are discarded, so ignore.  */
3964               if (cp->low != NULL && cp->high != NULL
3965                   && cp->low != cp->high
3966                   && gfc_compare_expr (cp->low, cp->high) > 0)
3967                 continue;
3968
3969               /* FIXME: Should a warning be issued?  */
3970               if (cp->low != NULL
3971                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
3972                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
3973
3974               if (cp->high != NULL
3975                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
3976                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
3977             }
3978          }
3979     }
3980
3981   /* Assume there is no DEFAULT case.  */
3982   default_case = NULL;
3983   head = tail = NULL;
3984   ncases = 0;
3985   seen_logical = 0;
3986
3987   for (body = code->block; body; body = body->block)
3988     {
3989       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
3990       t = SUCCESS;
3991       seen_unreachable = 0;
3992
3993       /* Walk the case label list, making sure that all case labels
3994          are legal.  */
3995       for (cp = body->ext.case_list; cp; cp = cp->next)
3996         {
3997           /* Count the number of cases in the whole construct.  */
3998           ncases++;
3999
4000           /* Intercept the DEFAULT case.  */
4001           if (cp->low == NULL && cp->high == NULL)
4002             {
4003               if (default_case != NULL)
4004                 {
4005                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
4006                              "by a second DEFAULT CASE at %L",
4007                              &default_case->where, &cp->where);
4008                   t = FAILURE;
4009                   break;
4010                 }
4011               else
4012                 {
4013                   default_case = cp;
4014                   continue;
4015                 }
4016             }
4017
4018           /* Deal with single value cases and case ranges.  Errors are
4019              issued from the validation function.  */
4020           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
4021              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
4022             {
4023               t = FAILURE;
4024               break;
4025             }
4026
4027           if (type == BT_LOGICAL
4028               && ((cp->low == NULL || cp->high == NULL)
4029                   || cp->low != cp->high))
4030             {
4031               gfc_error
4032                 ("Logical range in CASE statement at %L is not allowed",
4033                  &cp->low->where);
4034               t = FAILURE;
4035               break;
4036             }
4037
4038           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
4039             {
4040               int value;
4041               value = cp->low->value.logical == 0 ? 2 : 1;
4042               if (value & seen_logical)
4043                 {
4044                   gfc_error ("constant logical value in CASE statement "
4045                              "is repeated at %L",
4046                              &cp->low->where);
4047                   t = FAILURE;
4048                   break;
4049                 }
4050               seen_logical |= value;
4051             }
4052
4053           if (cp->low != NULL && cp->high != NULL
4054               && cp->low != cp->high
4055               && gfc_compare_expr (cp->low, cp->high) > 0)
4056             {
4057               if (gfc_option.warn_surprising)
4058                 gfc_warning ("Range specification at %L can never "
4059                              "be matched", &cp->where);
4060
4061               cp->unreachable = 1;
4062               seen_unreachable = 1;
4063             }
4064           else
4065             {
4066               /* If the case range can be matched, it can also overlap with
4067                  other cases.  To make sure it does not, we put it in a
4068                  double linked list here.  We sort that with a merge sort
4069                  later on to detect any overlapping cases.  */
4070               if (!head)
4071                 {
4072                   head = tail = cp;
4073                   head->right = head->left = NULL;
4074                 }
4075               else
4076                 {
4077                   tail->right = cp;
4078                   tail->right->left = tail;
4079                   tail = tail->right;
4080                   tail->right = NULL;
4081                 }
4082             }
4083         }
4084
4085       /* It there was a failure in the previous case label, give up
4086          for this case label list.  Continue with the next block.  */
4087       if (t == FAILURE)
4088         continue;
4089
4090       /* See if any case labels that are unreachable have been seen.
4091          If so, we eliminate them.  This is a bit of a kludge because
4092          the case lists for a single case statement (label) is a
4093          single forward linked lists.  */
4094       if (seen_unreachable)
4095       {
4096         /* Advance until the first case in the list is reachable.  */
4097         while (body->ext.case_list != NULL
4098                && body->ext.case_list->unreachable)
4099           {
4100             gfc_case *n = body->ext.case_list;
4101             body->ext.case_list = body->ext.case_list->next;
4102             n->next = NULL;
4103             gfc_free_case_list (n);
4104           }
4105
4106         /* Strip all other unreachable cases.  */
4107         if (body->ext.case_list)
4108           {
4109             for (cp = body->ext.case_list; cp->next; cp = cp->next)
4110               {
4111                 if (cp->next->unreachable)
4112                   {
4113                     gfc_case *n = cp->next;
4114                     cp->next = cp->next->next;
4115                     n->next = NULL;
4116                     gfc_free_case_list (n);
4117                   }
4118               }
4119           }
4120       }
4121     }
4122
4123   /* See if there were overlapping cases.  If the check returns NULL,
4124      there was overlap.  In that case we don't do anything.  If head
4125      is non-NULL, we prepend the DEFAULT case.  The sorted list can
4126      then used during code generation for SELECT CASE constructs with
4127      a case expression of a CHARACTER type.  */
4128   if (head)
4129     {
4130       head = check_case_overlap (head);
4131
4132       /* Prepend the default_case if it is there.  */
4133       if (head != NULL && default_case)
4134         {
4135           default_case->left = NULL;
4136           default_case->right = head;
4137           head->left = default_case;
4138         }
4139     }
4140
4141   /* Eliminate dead blocks that may be the result if we've seen
4142      unreachable case labels for a block.  */
4143   for (body = code; body && body->block; body = body->block)
4144     {
4145       if (body->block->ext.case_list == NULL)
4146         {
4147           /* Cut the unreachable block from the code chain.  */
4148           gfc_code *c = body->block;
4149           body->block = c->block;
4150
4151           /* Kill the dead block, but not the blocks below it.  */
4152           c->block = NULL;
4153           gfc_free_statements (c);
4154         }
4155     }
4156
4157   /* More than two cases is legal but insane for logical selects.
4158      Issue a warning for it.  */
4159   if (gfc_option.warn_surprising && type == BT_LOGICAL
4160       && ncases > 2)
4161     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
4162                  &code->loc);
4163 }
4164
4165
4166 /* Resolve a transfer statement. This is making sure that:
4167    -- a derived type being transferred has only non-pointer components
4168    -- a derived type being transferred doesn't have private components, unless 
4169       it's being transferred from the module where the type was defined
4170    -- we're not trying to transfer a whole assumed size array.  */
4171
4172 static void
4173 resolve_transfer (gfc_code * code)
4174 {
4175   gfc_typespec *ts;
4176   gfc_symbol *sym;
4177   gfc_ref *ref;
4178   gfc_expr *exp;
4179
4180   exp = code->expr;
4181
4182   if (exp->expr_type != EXPR_VARIABLE
4183         && exp->expr_type != EXPR_FUNCTION)
4184     return;
4185
4186   sym = exp->symtree->n.sym;
4187   ts = &sym->ts;
4188
4189   /* Go to actual component transferred.  */
4190   for (ref = code->expr->ref; ref; ref = ref->next)
4191     if (ref->type == REF_COMPONENT)
4192       ts = &ref->u.c.component->ts;
4193
4194   if (ts->type == BT_DERIVED)
4195     {
4196       /* Check that transferred derived type doesn't contain POINTER
4197          components.  */
4198       if (derived_pointer (ts->derived))
4199         {
4200           gfc_error ("Data transfer element at %L cannot have "
4201                      "POINTER components", &code->loc);
4202           return;
4203         }
4204
4205       if (ts->derived->attr.alloc_comp)
4206         {
4207           gfc_error ("Data transfer element at %L cannot have "
4208                      "ALLOCATABLE components", &code->loc);
4209           return;
4210         }
4211
4212       if (derived_inaccessible (ts->derived))
4213         {
4214           gfc_error ("Data transfer element at %L cannot have "
4215                      "PRIVATE components",&code->loc);
4216           return;
4217         }
4218     }
4219
4220   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
4221       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
4222     {
4223       gfc_error ("Data transfer element at %L cannot be a full reference to "
4224                  "an assumed-size array", &code->loc);
4225       return;
4226     }
4227 }
4228
4229
4230 /*********** Toplevel code resolution subroutines ***********/
4231
4232 /* Given a branch to a label and a namespace, if the branch is conforming.
4233    The code node described where the branch is located.  */
4234
4235 static void
4236 resolve_branch (gfc_st_label * label, gfc_code * code)
4237 {
4238   gfc_code *block, *found;
4239   code_stack *stack;
4240   gfc_st_label *lp;
4241
4242   if (label == NULL)
4243     return;
4244   lp = label;
4245
4246   /* Step one: is this a valid branching target?  */
4247
4248   if (lp->defined == ST_LABEL_UNKNOWN)
4249     {
4250       gfc_error ("Label %d referenced at %L is never defined", lp->value,
4251                  &lp->where);
4252       return;
4253     }
4254
4255   if (lp->defined != ST_LABEL_TARGET)
4256     {
4257       gfc_error ("Statement at %L is not a valid branch target statement "
4258                  "for the branch statement at %L", &lp->where, &code->loc);
4259       return;
4260     }
4261
4262   /* Step two: make sure this branch is not a branch to itself ;-)  */
4263
4264   if (code->here == label)
4265     {
4266       gfc_warning ("Branch at %L causes an infinite loop", &code->loc);
4267       return;
4268     }
4269
4270   /* Step three: Try to find the label in the parse tree. To do this,
4271      we traverse the tree block-by-block: first the block that
4272      contains this GOTO, then the block that it is nested in, etc.  We
4273      can ignore other blocks because branching into another block is
4274      not allowed.  */
4275
4276   found = NULL;
4277
4278   for (stack = cs_base; stack; stack = stack->prev)
4279     {
4280       for (block = stack->head; block; block = block->next)
4281         {
4282           if (block->here == label)
4283             {
4284               found = block;
4285               break;
4286             }
4287         }
4288
4289       if (found)
4290         break;
4291     }
4292
4293   if (found == NULL)
4294     {
4295       /* The label is not in an enclosing block, so illegal.  This was
4296          allowed in Fortran 66, so we allow it as extension.  We also 
4297          forego further checks if we run into this.  */
4298       gfc_notify_std (GFC_STD_LEGACY,
4299                       "Label at %L is not in the same block as the "
4300                       "GOTO statement at %L", &lp->where, &code->loc);
4301       return;
4302     }
4303
4304   /* Step four: Make sure that the branching target is legal if
4305      the statement is an END {SELECT,DO,IF}.  */
4306
4307   if (found->op == EXEC_NOP)
4308     {
4309       for (stack = cs_base; stack; stack = stack->prev)
4310         if (stack->current->next == found)
4311           break;
4312
4313       if (stack == NULL)
4314         gfc_notify_std (GFC_STD_F95_DEL,
4315                         "Obsolete: GOTO at %L jumps to END of construct at %L",
4316                         &code->loc, &found->loc);
4317     }
4318 }
4319
4320
4321 /* Check whether EXPR1 has the same shape as EXPR2.  */
4322
4323 static try
4324 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
4325 {
4326   mpz_t shape[GFC_MAX_DIMENSIONS];
4327   mpz_t shape2[GFC_MAX_DIMENSIONS];
4328   try result = FAILURE;
4329   int i;
4330
4331   /* Compare the rank.  */
4332   if (expr1->rank != expr2->rank)
4333     return result;
4334
4335   /* Compare the size of each dimension.  */
4336   for (i=0; i<expr1->rank; i++)
4337     {
4338       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
4339         goto ignore;
4340
4341       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
4342         goto ignore;
4343
4344       if (mpz_cmp (shape[i], shape2[i]))
4345         goto over;
4346     }
4347
4348   /* When either of the two expression is an assumed size array, we
4349      ignore the comparison of dimension sizes.  */
4350 ignore:
4351   result = SUCCESS;
4352
4353 over:
4354   for (i--; i>=0; i--)
4355     {
4356       mpz_clear (shape[i]);
4357       mpz_clear (shape2[i]);
4358     }
4359   return result;
4360 }
4361
4362
4363 /* Check whether a WHERE assignment target or a WHERE mask expression
4364    has the same shape as the outmost WHERE mask expression.  */
4365
4366 static void
4367 resolve_where (gfc_code *code, gfc_expr *mask)
4368 {
4369   gfc_code *cblock;
4370   gfc_code *cnext;
4371   gfc_expr *e = NULL;
4372
4373   cblock = code->block;
4374
4375   /* Store the first WHERE mask-expr of the WHERE statement or construct.
4376      In case of nested WHERE, only the outmost one is stored.  */
4377   if (mask == NULL) /* outmost WHERE */
4378     e = cblock->expr;
4379   else /* inner WHERE */
4380     e = mask;
4381
4382   while (cblock)
4383     {
4384       if (cblock->expr)
4385         {
4386           /* Check if the mask-expr has a consistent shape with the
4387              outmost WHERE mask-expr.  */
4388           if (resolve_where_shape (cblock->expr, e) == FAILURE)
4389             gfc_error ("WHERE mask at %L has inconsistent shape",
4390                        &cblock->expr->where);
4391          }
4392
4393       /* the assignment statement of a WHERE statement, or the first
4394          statement in where-body-construct of a WHERE construct */
4395       cnext = cblock->next;
4396       while (cnext)
4397         {
4398           switch (cnext->op)
4399             {
4400             /* WHERE assignment statement */
4401             case EXEC_ASSIGN:
4402
4403               /* Check shape consistent for WHERE assignment target.  */
4404               if (e && resolve_where_shape (cnext->expr, e) == FAILURE)
4405                gfc_error ("WHERE assignment target at %L has "
4406                           "inconsistent shape", &cnext->expr->where);
4407               break;
4408
4409             /* WHERE or WHERE construct is part of a where-body-construct */
4410             case EXEC_WHERE:
4411               resolve_where (cnext, e);
4412               break;
4413
4414             default:
4415               gfc_error ("Unsupported statement inside WHERE at %L",
4416                          &cnext->loc);
4417             }
4418          /* the next statement within the same where-body-construct */
4419          cnext = cnext->next;
4420        }
4421     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
4422     cblock = cblock->block;
4423   }
4424 }
4425
4426
4427 /* Check whether the FORALL index appears in the expression or not.  */
4428
4429 static try
4430 gfc_find_forall_index (gfc_expr *expr, gfc_symbol *symbol)
4431 {
4432   gfc_array_ref ar;
4433   gfc_ref *tmp;
4434   gfc_actual_arglist *args;
4435   int i;
4436
4437   switch (expr->expr_type)
4438     {
4439     case EXPR_VARIABLE:
4440       gcc_assert (expr->symtree->n.sym);
4441
4442       /* A scalar assignment  */
4443       if (!expr->ref)
4444         {
4445           if (expr->symtree->n.sym == symbol)
4446             return SUCCESS;
4447           else
4448             return FAILURE;
4449         }
4450
4451       /* the expr is array ref, substring or struct component.  */
4452       tmp = expr->ref;
4453       while (tmp != NULL)
4454         {
4455           switch (tmp->type)
4456             {
4457             case  REF_ARRAY:
4458               /* Check if the symbol appears in the array subscript.  */
4459               ar = tmp->u.ar;
4460               for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
4461                 {
4462                   if (ar.start[i])
4463                     if (gfc_find_forall_index (ar.start[i], symbol) == SUCCESS)
4464                       return SUCCESS;
4465
4466                   if (ar.end[i])
4467                     if (gfc_find_forall_index (ar.end[i], symbol) == SUCCESS)
4468                       return SUCCESS;
4469
4470                   if (ar.stride[i])
4471                     if (gfc_find_forall_index (ar.stride[i], symbol) == SUCCESS)
4472                       return SUCCESS;
4473                 }  /* end for  */
4474               break;
4475
4476             case REF_SUBSTRING:
4477               if (expr->symtree->n.sym == symbol)
4478                 return SUCCESS;
4479               tmp = expr->ref;
4480               /* Check if the symbol appears in the substring section.  */
4481               if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
4482                 return SUCCESS;
4483               if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
4484                 return SUCCESS;
4485               break;
4486
4487             case REF_COMPONENT:
4488               break;
4489
4490             default:
4491               gfc_error("expression reference type error at %L", &expr->where);
4492             }
4493           tmp = tmp->next;
4494         }
4495       break;
4496
4497     /* If the expression is a function call, then check if the symbol
4498        appears in the actual arglist of the function.  */
4499     case EXPR_FUNCTION:
4500       for (args = expr->value.function.actual; args; args = args->next)
4501         {
4502           if (gfc_find_forall_index(args->expr,symbol) == SUCCESS)
4503             return SUCCESS;
4504         }
4505       break;
4506
4507     /* It seems not to happen.  */
4508     case EXPR_SUBSTRING:
4509       if (expr->ref)
4510         {
4511           tmp = expr->ref;
4512           gcc_assert (expr->ref->type == REF_SUBSTRING);
4513           if (gfc_find_forall_index (tmp->u.ss.start, symbol) == SUCCESS)
4514             return SUCCESS;
4515           if (gfc_find_forall_index (tmp->u.ss.end, symbol) == SUCCESS)
4516             return SUCCESS;
4517         }
4518       break;
4519
4520     /* It seems not to happen.  */
4521     case EXPR_STRUCTURE:
4522     case EXPR_ARRAY:
4523       gfc_error ("Unsupported statement while finding forall index in "
4524                  "expression");
4525       break;
4526
4527     case EXPR_OP:
4528       /* Find the FORALL index in the first operand.  */
4529       if (expr->value.op.op1)
4530         {
4531           if (gfc_find_forall_index (expr->value.op.op1, symbol) == SUCCESS)
4532             return SUCCESS;
4533         }
4534
4535       /* Find the FORALL index in the second operand.  */
4536       if (expr->value.op.op2)
4537         {
4538           if (gfc_find_forall_index (expr->value.op.op2, symbol) == SUCCESS)
4539             return SUCCESS;
4540         }
4541       break;
4542
4543     default:
4544       break;
4545     }
4546
4547   return FAILURE;
4548 }
4549
4550
4551 /* Resolve assignment in FORALL construct.
4552    NVAR is the number of FORALL index variables, and VAR_EXPR records the
4553    FORALL index variables.  */
4554
4555 static void
4556 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
4557 {
4558   int n;
4559
4560   for (n = 0; n < nvar; n++)
4561     {
4562       gfc_symbol *forall_index;
4563
4564       forall_index = var_expr[n]->symtree->n.sym;
4565
4566       /* Check whether the assignment target is one of the FORALL index
4567          variable.  */
4568       if ((code->expr->expr_type == EXPR_VARIABLE)
4569           && (code->expr->symtree->n.sym == forall_index))
4570         gfc_error ("Assignment to a FORALL index variable at %L",
4571                    &code->expr->where);
4572       else
4573         {
4574           /* If one of the FORALL index variables doesn't appear in the
4575              assignment target, then there will be a many-to-one
4576              assignment.  */
4577           if (gfc_find_forall_index (code->expr, forall_index) == FAILURE)
4578             gfc_error ("The FORALL with index '%s' cause more than one "
4579                        "assignment to this object at %L",
4580                        var_expr[n]->symtree->name, &code->expr->where);
4581         }
4582     }
4583 }
4584
4585
4586 /* Resolve WHERE statement in FORALL construct.  */
4587
4588 static void
4589 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr){
4590   gfc_code *cblock;
4591   gfc_code *cnext;
4592
4593   cblock = code->block;
4594   while (cblock)
4595     {
4596       /* the assignment statement of a WHERE statement, or the first
4597          statement in where-body-construct of a WHERE construct */
4598       cnext = cblock->next;
4599       while (cnext)
4600         {
4601           switch (cnext->op)
4602             {
4603             /* WHERE assignment statement */
4604             case EXEC_ASSIGN:
4605               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
4606               break;
4607
4608             /* WHERE or WHERE construct is part of a where-body-construct */
4609             case EXEC_WHERE:
4610               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
4611               break;
4612
4613             default:
4614               gfc_error ("Unsupported statement inside WHERE at %L",
4615                          &cnext->loc);
4616             }
4617           /* the next statement within the same where-body-construct */
4618           cnext = cnext->next;
4619         }
4620       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
4621       cblock = cblock->block;
4622     }
4623 }
4624
4625
4626 /* Traverse the FORALL body to check whether the following errors exist:
4627    1. For assignment, check if a many-to-one assignment happens.
4628    2. For WHERE statement, check the WHERE body to see if there is any
4629       many-to-one assignment.  */
4630
4631 static void
4632 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
4633 {
4634   gfc_code *c;
4635
4636   c = code->block->next;
4637   while (c)
4638     {
4639       switch (c->op)
4640         {
4641         case EXEC_ASSIGN:
4642         case EXEC_POINTER_ASSIGN:
4643           gfc_resolve_assign_in_forall (c, nvar, var_expr);
4644           break;
4645
4646         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
4647            there is no need to handle it here.  */
4648         case EXEC_FORALL:
4649           break;
4650         case EXEC_WHERE:
4651           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
4652           break;
4653         default:
4654           break;
4655         }
4656       /* The next statement in the FORALL body.  */
4657       c = c->next;
4658     }
4659 }
4660
4661
4662 /* Given a FORALL construct, first resolve the FORALL iterator, then call
4663    gfc_resolve_forall_body to resolve the FORALL body.  */
4664
4665 static void
4666 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
4667 {
4668   static gfc_expr **var_expr;
4669   static int total_var = 0;
4670   static int nvar = 0;
4671   gfc_forall_iterator *fa;
4672   gfc_symbol *forall_index;
4673   gfc_code *next;
4674   int i;
4675
4676   /* Start to resolve a FORALL construct   */
4677   if (forall_save == 0)
4678     {
4679       /* Count the total number of FORALL index in the nested FORALL
4680          construct in order to allocate the VAR_EXPR with proper size.  */
4681       next = code;
4682       while ((next != NULL) && (next->op == EXEC_FORALL))
4683         {
4684           for (fa = next->ext.forall_iterator; fa; fa = fa->next)
4685             total_var ++;
4686           next = next->block->next;
4687         }
4688
4689       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
4690       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
4691     }
4692
4693   /* The information about FORALL iterator, including FORALL index start, end
4694      and stride. The FORALL index can not appear in start, end or stride.  */
4695   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
4696     {
4697       /* Check if any outer FORALL index name is the same as the current
4698          one.  */
4699       for (i = 0; i < nvar; i++)
4700         {
4701           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
4702             {
4703               gfc_error ("An outer FORALL construct already has an index "
4704                          "with this name %L", &fa->var->where);
4705             }
4706         }
4707
4708       /* Record the current FORALL index.  */
4709       var_expr[nvar] = gfc_copy_expr (fa->var);
4710
4711       forall_index = fa->var->symtree->n.sym;
4712
4713       /* Check if the FORALL index appears in start, end or stride.  */
4714       if (gfc_find_forall_index (fa->start, forall_index) == SUCCESS)
4715         gfc_error ("A FORALL index must not appear in a limit or stride "
4716                    "expression in the same FORALL at %L", &fa->start->where);
4717       if (gfc_find_forall_index (fa->end, forall_index) == SUCCESS)
4718         gfc_error ("A FORALL index must not appear in a limit or stride "
4719                    "expression in the same FORALL at %L", &fa->end->where);
4720       if (gfc_find_forall_index (fa->stride, forall_index) == SUCCESS)
4721         gfc_error ("A FORALL index must not appear in a limit or stride "
4722                    "expression in the same FORALL at %L", &fa->stride->where);
4723       nvar++;
4724     }
4725
4726   /* Resolve the FORALL body.  */
4727   gfc_resolve_forall_body (code, nvar, var_expr);
4728
4729   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
4730   gfc_resolve_blocks (code->block, ns);
4731
4732   /* Free VAR_EXPR after the whole FORALL construct resolved.  */
4733   for (i = 0; i < total_var; i++)
4734     gfc_free_expr (var_expr[i]);
4735
4736   /* Reset the counters.  */
4737   total_var = 0;
4738   nvar = 0;
4739 }
4740
4741
4742 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL ,GOTO and
4743    DO code nodes.  */
4744
4745 static void resolve_code (gfc_code *, gfc_namespace *);
4746
4747 void
4748 gfc_resolve_blocks (gfc_code * b, gfc_namespace * ns)
4749 {
4750   try t;
4751
4752   for (; b; b = b->block)
4753     {
4754       t = gfc_resolve_expr (b->expr);
4755       if (gfc_resolve_expr (b->expr2) == FAILURE)
4756         t = FAILURE;
4757
4758       switch (b->op)
4759         {
4760         case EXEC_IF:
4761           if (t == SUCCESS && b->expr != NULL
4762               && (b->expr->ts.type != BT_LOGICAL || b->expr->rank != 0))
4763             gfc_error
4764               ("IF clause at %L requires a scalar LOGICAL expression",
4765                &b->expr->where);
4766           break;
4767
4768         case EXEC_WHERE:
4769           if (t == SUCCESS
4770               && b->expr != NULL
4771               && (b->expr->ts.type != BT_LOGICAL
4772                   || b->expr->rank == 0))
4773             gfc_error
4774               ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
4775                &b->expr->where);
4776           break;
4777
4778         case EXEC_GOTO:
4779           resolve_branch (b->label, b);
4780           break;
4781
4782         case EXEC_SELECT:
4783         case EXEC_FORALL:
4784         case EXEC_DO:
4785         case EXEC_DO_WHILE:
4786         case EXEC_READ:
4787         case EXEC_WRITE:
4788         case EXEC_IOLENGTH:
4789           break;
4790
4791         case EXEC_OMP_ATOMIC:
4792         case EXEC_OMP_CRITICAL:
4793         case EXEC_OMP_DO:
4794         case EXEC_OMP_MASTER:
4795         case EXEC_OMP_ORDERED:
4796         case EXEC_OMP_PARALLEL:
4797         case EXEC_OMP_PARALLEL_DO:
4798         case EXEC_OMP_PARALLEL_SECTIONS:
4799         case EXEC_OMP_PARALLEL_WORKSHARE:
4800         case EXEC_OMP_SECTIONS:
4801         case EXEC_OMP_SINGLE:
4802         case EXEC_OMP_WORKSHARE:
4803           break;
4804
4805         default:
4806           gfc_internal_error ("resolve_block(): Bad block type");
4807         }
4808
4809       resolve_code (b->next, ns);
4810     }
4811 }
4812
4813
4814 /* Given a block of code, recursively resolve everything pointed to by this
4815    code block.  */
4816
4817 static void
4818 resolve_code (gfc_code * code, gfc_namespace * ns)
4819 {
4820   int omp_workshare_save;
4821   int forall_save;
4822   code_stack frame;
4823   gfc_alloc *a;
4824   try t;
4825
4826   frame.prev = cs_base;
4827   frame.head = code;
4828   cs_base = &frame;
4829
4830   for (; code; code = code->next)
4831     {
4832       frame.current = code;
4833       forall_save = forall_flag;
4834
4835       if (code->op == EXEC_FORALL)
4836         {
4837           forall_flag = 1;
4838           gfc_resolve_forall (code, ns, forall_save);
4839           forall_flag = 2;
4840         }
4841       else if (code->block)
4842         {
4843           omp_workshare_save = -1;
4844           switch (code->op)
4845             {
4846             case EXEC_OMP_PARALLEL_WORKSHARE:
4847               omp_workshare_save = omp_workshare_flag;
4848               omp_workshare_flag = 1;
4849               gfc_resolve_omp_parallel_blocks (code, ns);
4850               break;
4851             case EXEC_OMP_PARALLEL:
4852             case EXEC_OMP_PARALLEL_DO:
4853             case EXEC_OMP_PARALLEL_SECTIONS:
4854               omp_workshare_save = omp_workshare_flag;
4855               omp_workshare_flag = 0;
4856               gfc_resolve_omp_parallel_blocks (code, ns);
4857               break;
4858             case EXEC_OMP_DO:
4859               gfc_resolve_omp_do_blocks (code, ns);
4860               break;
4861             case EXEC_OMP_WORKSHARE:
4862               omp_workshare_save = omp_workshare_flag;
4863               omp_workshare_flag = 1;
4864               /* FALLTHROUGH */
4865             default:
4866               gfc_resolve_blocks (code->block, ns);
4867               break;
4868             }
4869
4870           if (omp_workshare_save != -1)
4871             omp_workshare_flag = omp_workshare_save;
4872         }
4873
4874       t = gfc_resolve_expr (code->expr);
4875       forall_flag = forall_save;
4876
4877       if (gfc_resolve_expr (code->expr2) == FAILURE)
4878         t = FAILURE;
4879
4880       switch (code->op)
4881         {
4882         case EXEC_NOP:
4883         case EXEC_CYCLE:
4884         case EXEC_PAUSE:
4885         case EXEC_STOP:
4886         case EXEC_EXIT:
4887         case EXEC_CONTINUE:
4888         case EXEC_DT_END:
4889           break;
4890
4891         case EXEC_ENTRY:
4892           /* Keep track of which entry we are up to.  */
4893           current_entry_id = code->ext.entry->id;
4894           break;
4895
4896         case EXEC_WHERE:
4897           resolve_where (code, NULL);
4898           break;
4899
4900         case EXEC_GOTO:
4901           if (code->expr != NULL)
4902             {
4903               if (code->expr->ts.type != BT_INTEGER)
4904                 gfc_error ("ASSIGNED GOTO statement at %L requires an INTEGER "
4905                        "variable", &code->expr->where);
4906               else if (code->expr->symtree->n.sym->attr.assign != 1)
4907                 gfc_error ("Variable '%s' has not been assigned a target label "
4908                         "at %L", code->expr->symtree->n.sym->name,
4909                         &code->expr->where);
4910             }
4911           else
4912             resolve_branch (code->label, code);
4913           break;
4914
4915         case EXEC_RETURN:
4916           if (code->expr != NULL
4917                 && (code->expr->ts.type != BT_INTEGER || code->expr->rank))
4918             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
4919                        "INTEGER return specifier", &code->expr->where);
4920           break;
4921
4922         case EXEC_INIT_ASSIGN:
4923           break;
4924
4925         case EXEC_ASSIGN:
4926           if (t == FAILURE)
4927             break;
4928
4929           if (gfc_extend_assign (code, ns) == SUCCESS)
4930             {
4931               if (gfc_pure (NULL) && !gfc_pure (code->symtree->n.sym))
4932                 {
4933                   gfc_error ("Subroutine '%s' called instead of assignment at "
4934                              "%L must be PURE", code->symtree->n.sym->name,
4935                              &code->loc);
4936                   break;
4937                 }
4938               goto call;
4939             }
4940
4941           if (gfc_pure (NULL))
4942             {
4943               if (gfc_impure_variable (code->expr->symtree->n.sym))
4944                 {
4945                   gfc_error
4946                     ("Cannot assign to variable '%s' in PURE procedure at %L",
4947                      code->expr->symtree->n.sym->name, &code->expr->where);
4948                   break;
4949                 }
4950
4951               if (code->expr2->ts.type == BT_DERIVED
4952                   && derived_pointer (code->expr2->ts.derived))
4953                 {
4954                   gfc_error
4955                     ("Right side of assignment at %L is a derived type "
4956                      "containing a POINTER in a PURE procedure",
4957                      &code->expr2->where);
4958                   break;
4959                 }
4960             }
4961
4962           gfc_check_assign (code->expr, code->expr2, 1);
4963           break;
4964
4965         case EXEC_LABEL_ASSIGN:
4966           if (code->label->defined == ST_LABEL_UNKNOWN)
4967             gfc_error ("Label %d referenced at %L is never defined",
4968                        code->label->value, &code->label->where);
4969           if (t == SUCCESS
4970               && (code->expr->expr_type != EXPR_VARIABLE
4971                   || code->expr->symtree->n.sym->ts.type != BT_INTEGER
4972                   || code->expr->symtree->n.sym->ts.kind
4973                         != gfc_default_integer_kind
4974                   || code->expr->symtree->n.sym->as != NULL))
4975             gfc_error ("ASSIGN statement at %L requires a scalar "
4976                        "default INTEGER variable", &code->expr->where);
4977           break;
4978
4979         case EXEC_POINTER_ASSIGN:
4980           if (t == FAILURE)
4981             break;
4982
4983           gfc_check_pointer_assign (code->expr, code->expr2);
4984           break;
4985
4986         case EXEC_ARITHMETIC_IF:
4987           if (t == SUCCESS
4988               && code->expr->ts.type != BT_INTEGER
4989               && code->expr->ts.type != BT_REAL)
4990             gfc_error ("Arithmetic IF statement at %L requires a numeric "
4991                        "expression", &code->expr->where);
4992
4993           resolve_branch (code->label, code);
4994           resolve_branch (code->label2, code);
4995           resolve_branch (code->label3, code);
4996           break;
4997
4998         case EXEC_IF:
4999           if (t == SUCCESS && code->expr != NULL
5000               && (code->expr->ts.type != BT_LOGICAL
5001                   || code->expr->rank != 0))
5002             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
5003                        &code->expr->where);
5004           break;
5005
5006         case EXEC_CALL:
5007         call:
5008           resolve_call (code);
5009           break;
5010
5011         case EXEC_SELECT:
5012           /* Select is complicated. Also, a SELECT construct could be
5013              a transformed computed GOTO.  */
5014           resolve_select (code);
5015           break;
5016
5017         case EXEC_DO:
5018           if (code->ext.iterator != NULL)
5019             {
5020               gfc_iterator *iter = code->ext.iterator;
5021               if (gfc_resolve_iterator (iter, true) != FAILURE)
5022                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
5023             }
5024           break;
5025
5026         case EXEC_DO_WHILE:
5027           if (code->expr == NULL)
5028             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
5029           if (t == SUCCESS
5030               && (code->expr->rank != 0
5031                   || code->expr->ts.type != BT_LOGICAL))
5032             gfc_error ("Exit condition of DO WHILE loop at %L must be "
5033                        "a scalar LOGICAL expression", &code->expr->where);
5034           break;
5035
5036         case EXEC_ALLOCATE:
5037           if (t == SUCCESS && code->expr != NULL
5038               && code->expr->ts.type != BT_INTEGER)
5039             gfc_error ("STAT tag in ALLOCATE statement at %L must be "
5040                        "of type INTEGER", &code->expr->where);
5041
5042           for (a = code->ext.alloc_list; a; a = a->next)
5043             resolve_allocate_expr (a->expr, code);
5044
5045           break;
5046
5047         case EXEC_DEALLOCATE:
5048           if (t == SUCCESS && code->expr != NULL
5049               && code->expr->ts.type != BT_INTEGER)
5050             gfc_error
5051               ("STAT tag in DEALLOCATE statement at %L must be of type "
5052                "INTEGER", &code->expr->where);
5053
5054           for (a = code->ext.alloc_list; a; a = a->next)
5055             resolve_deallocate_expr (a->expr);
5056
5057           break;
5058
5059         case EXEC_OPEN:
5060           if (gfc_resolve_open (code->ext.open) == FAILURE)
5061             break;
5062
5063           resolve_branch (code->ext.open->err, code);
5064           break;
5065
5066         case EXEC_CLOSE:
5067           if (gfc_resolve_close (code->ext.close) == FAILURE)
5068             break;
5069
5070           resolve_branch (code->ext.close->err, code);
5071           break;
5072
5073         case EXEC_BACKSPACE:
5074         case EXEC_ENDFILE:
5075         case EXEC_REWIND:
5076         case EXEC_FLUSH:
5077           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
5078             break;
5079
5080           resolve_branch (code->ext.filepos->err, code);
5081           break;
5082
5083         case EXEC_INQUIRE:
5084           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
5085               break;
5086
5087           resolve_branch (code->ext.inquire->err, code);
5088           break;
5089
5090         case EXEC_IOLENGTH:
5091           gcc_assert (code->ext.inquire != NULL);
5092           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
5093             break;
5094
5095           resolve_branch (code->ext.inquire->err, code);
5096           break;
5097
5098         case EXEC_READ:
5099         case EXEC_WRITE:
5100           if (gfc_resolve_dt (code->ext.dt) == FAILURE)
5101             break;
5102
5103           resolve_branch (code->ext.dt->err, code);
5104           resolve_branch (code->ext.dt->end, code);
5105           resolve_branch (code->ext.dt->eor, code);
5106           break;
5107
5108         case EXEC_TRANSFER:
5109           resolve_transfer (code);
5110           break;
5111
5112         case EXEC_FORALL:
5113           resolve_forall_iterators (code->ext.forall_iterator);
5114
5115           if (code->expr != NULL && code->expr->ts.type != BT_LOGICAL)
5116             gfc_error
5117               ("FORALL mask clause at %L requires a LOGICAL expression",
5118                &code->expr->where);
5119           break;
5120
5121         case EXEC_OMP_ATOMIC:
5122         case EXEC_OMP_BARRIER:
5123         case EXEC_OMP_CRITICAL:
5124         case EXEC_OMP_FLUSH:
5125         case EXEC_OMP_DO:
5126         case EXEC_OMP_MASTER:
5127         case EXEC_OMP_ORDERED:
5128         case EXEC_OMP_SECTIONS:
5129         case EXEC_OMP_SINGLE:
5130         case EXEC_OMP_WORKSHARE:
5131           gfc_resolve_omp_directive (code, ns);
5132           break;
5133
5134         case EXEC_OMP_PARALLEL:
5135         case EXEC_OMP_PARALLEL_DO:
5136         case EXEC_OMP_PARALLEL_SECTIONS:
5137         case EXEC_OMP_PARALLEL_WORKSHARE:
5138           omp_workshare_save = omp_workshare_flag;
5139           omp_workshare_flag = 0;
5140           gfc_resolve_omp_directive (code, ns);
5141           omp_workshare_flag = omp_workshare_save;
5142           break;
5143
5144         default:
5145           gfc_internal_error ("resolve_code(): Bad statement code");
5146         }
5147     }
5148
5149   cs_base = frame.prev;
5150 }
5151
5152
5153 /* Resolve initial values and make sure they are compatible with
5154    the variable.  */
5155
5156 static void
5157 resolve_values (gfc_symbol * sym)
5158 {
5159
5160   if (sym->value == NULL)
5161     return;
5162
5163   if (gfc_resolve_expr (sym->value) == FAILURE)
5164     return;
5165
5166   gfc_check_assign_symbol (sym, sym->value);
5167 }
5168
5169
5170 /* Resolve an index expression.  */
5171
5172 static try
5173 resolve_index_expr (gfc_expr * e)
5174 {
5175   if (gfc_resolve_expr (e) == FAILURE)
5176     return FAILURE;
5177
5178   if (gfc_simplify_expr (e, 0) == FAILURE)
5179     return FAILURE;
5180
5181   if (gfc_specification_expr (e) == FAILURE)
5182     return FAILURE;
5183
5184   return SUCCESS;
5185 }
5186
5187 /* Resolve a charlen structure.  */
5188
5189 static try
5190 resolve_charlen (gfc_charlen *cl)
5191 {
5192   if (cl->resolved)
5193     return SUCCESS;
5194
5195   cl->resolved = 1;
5196
5197   specification_expr = 1;
5198
5199   if (resolve_index_expr (cl->length) == FAILURE)
5200     {
5201       specification_expr = 0;
5202       return FAILURE;
5203     }
5204
5205   return SUCCESS;
5206 }
5207
5208
5209 /* Test for non-constant shape arrays. */
5210
5211 static bool
5212 is_non_constant_shape_array (gfc_symbol *sym)
5213 {
5214   gfc_expr *e;
5215   int i;
5216   bool not_constant;
5217
5218   not_constant = false;
5219   if (sym->as != NULL)
5220     {
5221       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
5222          has not been simplified; parameter array references.  Do the
5223          simplification now.  */
5224       for (i = 0; i < sym->as->rank; i++)
5225         {
5226           e = sym->as->lower[i];
5227           if (e && (resolve_index_expr (e) == FAILURE
5228                 || !gfc_is_constant_expr (e)))
5229             not_constant = true;
5230
5231           e = sym->as->upper[i];
5232           if (e && (resolve_index_expr (e) == FAILURE
5233                 || !gfc_is_constant_expr (e)))
5234             not_constant = true;
5235         }
5236     }
5237   return not_constant;
5238 }
5239
5240
5241 /* Assign the default initializer to a derived type variable or result.  */
5242
5243 static void
5244 apply_default_init (gfc_symbol *sym)
5245 {
5246   gfc_expr *lval;
5247   gfc_expr *init = NULL;
5248   gfc_code *init_st;
5249   gfc_namespace *ns = sym->ns;
5250
5251   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
5252     return;
5253
5254   if (sym->ts.type == BT_DERIVED && sym->ts.derived)
5255     init = gfc_default_initializer (&sym->ts);
5256
5257   if (init == NULL)
5258     return;
5259
5260   /* Search for the function namespace if this is a contained
5261      function without an explicit result.  */
5262   if (sym->attr.function && sym == sym->result
5263         && sym->name != sym->ns->proc_name->name)
5264     {
5265       ns = ns->contained;
5266       for (;ns; ns = ns->sibling)
5267         if (strcmp (ns->proc_name->name, sym->name) == 0)
5268           break;
5269     }
5270
5271   if (ns == NULL)
5272     {
5273       gfc_free_expr (init);
5274       return;
5275     }
5276
5277   /* Build an l-value expression for the result.  */
5278   lval = gfc_get_expr ();
5279   lval->expr_type = EXPR_VARIABLE;
5280   lval->where = sym->declared_at;
5281   lval->ts = sym->ts;
5282   lval->symtree = gfc_find_symtree (sym->ns->sym_root, sym->name);
5283
5284   /* It will always be a full array.  */
5285   lval->rank = sym->as ? sym->as->rank : 0;
5286   if (lval->rank)
5287     {
5288       lval->ref = gfc_get_ref ();
5289       lval->ref->type = REF_ARRAY;
5290       lval->ref->u.ar.type = AR_FULL;
5291       lval->ref->u.ar.dimen = lval->rank;
5292       lval->ref->u.ar.where = sym->declared_at;
5293       lval->ref->u.ar.as = sym->as;
5294     }
5295
5296   /* Add the code at scope entry.  */
5297   init_st = gfc_get_code ();
5298   init_st->next = ns->code;
5299   ns->code = init_st;
5300
5301   /* Assign the default initializer to the l-value.  */
5302   init_st->loc = sym->declared_at;
5303   init_st->op = EXEC_INIT_ASSIGN;
5304   init_st->expr = lval;
5305   init_st->expr2 = init;
5306 }
5307
5308
5309 /* Resolution of common features of flavors variable and procedure. */
5310
5311 static try
5312 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
5313 {
5314   /* Constraints on deferred shape variable.  */
5315   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
5316     {
5317       if (sym->attr.allocatable)
5318         {
5319           if (sym->attr.dimension)
5320             gfc_error ("Allocatable array '%s' at %L must have "
5321                        "a deferred shape", sym->name, &sym->declared_at);
5322           else
5323             gfc_error ("Scalar object '%s' at %L may not be ALLOCATABLE",
5324                        sym->name, &sym->declared_at);
5325             return FAILURE;
5326         }
5327
5328       if (sym->attr.pointer && sym->attr.dimension)
5329         {
5330           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
5331                      sym->name, &sym->declared_at);
5332           return FAILURE;
5333         }
5334
5335     }
5336   else
5337     {
5338       if (!mp_flag && !sym->attr.allocatable
5339              && !sym->attr.pointer && !sym->attr.dummy)
5340         {
5341           gfc_error ("Array '%s' at %L cannot have a deferred shape",
5342                      sym->name, &sym->declared_at);
5343           return FAILURE;
5344          }
5345     }
5346   return SUCCESS;
5347 }
5348
5349 /* Resolve symbols with flavor variable.  */
5350
5351 static try
5352 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
5353 {
5354   int flag;
5355   int i;
5356   gfc_expr *e;
5357   gfc_expr *constructor_expr;
5358   const char * auto_save_msg;
5359
5360   auto_save_msg = "automatic object '%s' at %L cannot have the "
5361                   "SAVE attribute";
5362
5363   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
5364     return FAILURE;
5365
5366   /* Set this flag to check that variables are parameters of all entries.
5367      This check is effected by the call to gfc_resolve_expr through
5368      is_non_constant_shape_array.  */
5369   specification_expr = 1;
5370
5371   if (!sym->attr.use_assoc
5372         && !sym->attr.allocatable
5373         && !sym->attr.pointer
5374         && is_non_constant_shape_array (sym))
5375     {
5376         /* The shape of a main program or module array needs to be constant.  */
5377         if (sym->ns->proc_name
5378               && (sym->ns->proc_name->attr.flavor == FL_MODULE
5379                     || sym->ns->proc_name->attr.is_main_program))
5380           {
5381             gfc_error ("The module or main program array '%s' at %L must "
5382                        "have constant shape", sym->name, &sym->declared_at);
5383             specification_expr = 0;
5384             return FAILURE;
5385           }
5386     }
5387
5388   if (sym->ts.type == BT_CHARACTER)
5389     {
5390       /* Make sure that character string variables with assumed length are
5391          dummy arguments.  */
5392       e = sym->ts.cl->length;
5393       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
5394         {
5395           gfc_error ("Entity with assumed character length at %L must be a "
5396                      "dummy argument or a PARAMETER", &sym->declared_at);
5397           return FAILURE;
5398         }
5399
5400       if (e && sym->attr.save && !gfc_is_constant_expr (e))
5401         {
5402           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
5403           return FAILURE;
5404         }
5405
5406       if (!gfc_is_constant_expr (e)
5407             && !(e->expr_type == EXPR_VARIABLE
5408             && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
5409             && sym->ns->proc_name
5410             && (sym->ns->proc_name->attr.flavor == FL_MODULE
5411                   || sym->ns->proc_name->attr.is_main_program)
5412             && !sym->attr.use_assoc)
5413         {
5414           gfc_error ("'%s' at %L must have constant character length "
5415                      "in this context", sym->name, &sym->declared_at);
5416           return FAILURE;
5417         }
5418     }
5419
5420   /* Can the symbol have an initializer?  */
5421   flag = 0;
5422   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
5423         || sym->attr.intrinsic || sym->attr.result)
5424     flag = 1;
5425   else if (sym->attr.dimension && !sym->attr.pointer)
5426     {
5427       /* Don't allow initialization of automatic arrays.  */
5428       for (i = 0; i < sym->as->rank; i++)
5429         {
5430           if (sym->as->lower[i] == NULL
5431                 || sym->as->lower[i]->expr_type != EXPR_CONSTANT
5432                 || sym->as->upper[i] == NULL
5433                 || sym->as->upper[i]->expr_type != EXPR_CONSTANT)
5434             {
5435               flag = 1;
5436               break;
5437             }
5438         }
5439
5440       /* Also, they must not have the SAVE attribute.  */
5441       if (flag && sym->attr.save)
5442         {
5443           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
5444           return FAILURE;
5445         }
5446   }
5447
5448   /* Reject illegal initializers.  */
5449   if (sym->value && flag)
5450     {
5451       if (sym->attr.allocatable)
5452         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
5453                    sym->name, &sym->declared_at);
5454       else if (sym->attr.external)
5455         gfc_error ("External '%s' at %L cannot have an initializer",
5456                    sym->name, &sym->declared_at);
5457       else if (sym->attr.dummy)
5458         gfc_error ("Dummy '%s' at %L cannot have an initializer",
5459                    sym->name, &sym->declared_at);
5460       else if (sym->attr.intrinsic)
5461         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
5462                    sym->name, &sym->declared_at);
5463       else if (sym->attr.result)
5464         gfc_error ("Function result '%s' at %L cannot have an initializer",
5465                    sym->name, &sym->declared_at);
5466       else
5467         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
5468                    sym->name, &sym->declared_at);
5469       return FAILURE;
5470     }
5471
5472   /* Check to see if a derived type is blocked from being host associated
5473      by the presence of another class I symbol in the same namespace.
5474      14.6.1.3 of the standard and the discussion on comp.lang.fortran.  */
5475   if (sym->ts.type == BT_DERIVED && sym->ns != sym->ts.derived->ns)
5476     {
5477       gfc_symbol *s;
5478       gfc_find_symbol (sym->ts.derived->name, sym->ns, 0, &s);
5479       if (s && (s->attr.flavor != FL_DERIVED
5480                   || !gfc_compare_derived_types (s, sym->ts.derived)))
5481         {
5482           gfc_error ("The type %s cannot be host associated at %L because "
5483                      "it is blocked by an incompatible object of the same "
5484                      "name at %L", sym->ts.derived->name, &sym->declared_at,
5485                      &s->declared_at);
5486           return FAILURE;
5487         }
5488     }
5489
5490   /* 4th constraint in section 11.3:  "If an object of a type for which
5491      component-initialization is specified (R429) appears in the
5492      specification-part of a module and does not have the ALLOCATABLE
5493      or POINTER attribute, the object shall have the SAVE attribute."  */
5494
5495   constructor_expr = NULL;
5496   if (sym->ts.type == BT_DERIVED && !(sym->value || flag))
5497         constructor_expr = gfc_default_initializer (&sym->ts);
5498
5499   if (sym->ns->proc_name
5500         && sym->ns->proc_name->attr.flavor == FL_MODULE
5501         && constructor_expr
5502         && !sym->ns->save_all && !sym->attr.save
5503         && !sym->attr.pointer && !sym->attr.allocatable)
5504     {
5505       gfc_error("Object '%s' at %L must have the SAVE attribute %s",
5506                 sym->name, &sym->declared_at,
5507                 "for default initialization of a component");
5508       return FAILURE;
5509     }
5510
5511   /* Assign default initializer.  */
5512   if (sym->ts.type == BT_DERIVED
5513         && !sym->value
5514         && !sym->attr.pointer
5515         && !sym->attr.allocatable
5516         && (!flag || sym->attr.intent == INTENT_OUT))
5517     sym->value = gfc_default_initializer (&sym->ts);
5518
5519   return SUCCESS;
5520 }
5521
5522
5523 /* Resolve a procedure.  */
5524
5525 static try
5526 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
5527 {
5528   gfc_formal_arglist *arg;
5529   gfc_symtree *st;
5530
5531   if (sym->attr.ambiguous_interfaces && !sym->attr.referenced)
5532     gfc_warning ("Although not referenced, '%s' at %L has ambiguous "
5533                  "interfaces", sym->name, &sym->declared_at);
5534
5535   if (sym->attr.function
5536         && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
5537     return FAILURE;
5538
5539   st = gfc_find_symtree (gfc_current_ns->sym_root, sym->name);
5540   if (st && st->ambiguous
5541          && sym->attr.referenced
5542          && !sym->attr.generic)
5543     {
5544       gfc_error ("Procedure %s at %L is ambiguous",
5545                  sym->name, &sym->declared_at);
5546       return FAILURE;
5547     }
5548
5549   if (sym->ts.type == BT_CHARACTER)
5550     {
5551       gfc_charlen *cl = sym->ts.cl;
5552       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
5553         {
5554           if (sym->attr.proc == PROC_ST_FUNCTION)
5555             {
5556               gfc_error ("Character-valued statement function '%s' at %L must "
5557                          "have constant length", sym->name, &sym->declared_at);
5558               return FAILURE;
5559             }
5560
5561           if (sym->attr.external && sym->formal == NULL
5562                 && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
5563             {
5564               gfc_error ("Automatic character length function '%s' at %L must "
5565                          "have an explicit interface", sym->name, &sym->declared_at);
5566               return FAILURE;
5567             }
5568         }
5569     }
5570
5571   /* Ensure that derived type for are not of a private type.  Internal
5572      module procedures are excluded by 2.2.3.3 - ie. they are not
5573      externally accessible and can access all the objects accessible in
5574      the host. */
5575   if (!(sym->ns->parent
5576             && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
5577         && gfc_check_access(sym->attr.access, sym->ns->default_access))
5578     {
5579       for (arg = sym->formal; arg; arg = arg->next)
5580         {
5581           if (arg->sym
5582                 && arg->sym->ts.type == BT_DERIVED
5583                 && !arg->sym->ts.derived->attr.use_assoc
5584                 && !gfc_check_access(arg->sym->ts.derived->attr.access,
5585                         arg->sym->ts.derived->ns->default_access))
5586             {
5587               gfc_error_now ("'%s' is of a PRIVATE type and cannot be "
5588                              "a dummy argument of '%s', which is "
5589                              "PUBLIC at %L", arg->sym->name, sym->name,
5590                              &sym->declared_at);
5591               /* Stop this message from recurring.  */
5592               arg->sym->ts.derived->attr.access = ACCESS_PUBLIC;
5593               return FAILURE;
5594             }
5595         }
5596     }
5597
5598   /* An external symbol may not have an initializer because it is taken to be
5599      a procedure.  */
5600   if (sym->attr.external && sym->value)
5601     {
5602       gfc_error ("External object '%s' at %L may not have an initializer",
5603                  sym->name, &sym->declared_at);
5604       return FAILURE;
5605     }
5606
5607   /* An elemental function is required to return a scalar 12.7.1  */
5608   if (sym->attr.elemental && sym->attr.function && sym->as)
5609     {
5610       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
5611                  "result", sym->name, &sym->declared_at);
5612       /* Reset so that the error only occurs once.  */
5613       sym->attr.elemental = 0;
5614       return FAILURE;
5615     }
5616
5617   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
5618      char-len-param shall not be array-valued, pointer-valued, recursive
5619      or pure.  ....snip... A character value of * may only be used in the
5620      following ways: (i) Dummy arg of procedure - dummy associates with
5621      actual length; (ii) To declare a named constant; or (iii) External
5622      function - but length must be declared in calling scoping unit.  */
5623   if (sym->attr.function
5624         && sym->ts.type == BT_CHARACTER
5625         && sym->ts.cl && sym->ts.cl->length == NULL)
5626     {
5627       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
5628              || (sym->attr.recursive) || (sym->attr.pure))
5629         {
5630           if (sym->as && sym->as->rank)
5631             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
5632                        "array-valued", sym->name, &sym->declared_at);
5633
5634           if (sym->attr.pointer)
5635             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
5636                        "pointer-valued", sym->name, &sym->declared_at);
5637
5638           if (sym->attr.pure)
5639             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
5640                        "pure", sym->name, &sym->declared_at);
5641
5642           if (sym->attr.recursive)
5643             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
5644                        "recursive", sym->name, &sym->declared_at);
5645
5646           return FAILURE;
5647         }
5648
5649       /* Appendix B.2 of the standard.  Contained functions give an
5650          error anyway.  Fixed-form is likely to be F77/legacy.  */
5651       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
5652         gfc_notify_std (GFC_STD_F95_OBS, "CHARACTER(*) function "
5653                         "'%s' at %L is obsolescent in fortran 95",
5654                         sym->name, &sym->declared_at);
5655     }
5656   return SUCCESS;
5657 }
5658
5659
5660 /* Resolve the components of a derived type.  */
5661
5662 static try
5663 resolve_fl_derived (gfc_symbol *sym)
5664 {
5665   gfc_component *c;
5666   gfc_dt_list * dt_list;
5667   int i;
5668
5669   for (c = sym->components; c != NULL; c = c->next)
5670     {
5671       if (c->ts.type == BT_CHARACTER)
5672         {
5673          if (c->ts.cl->length == NULL
5674              || (resolve_charlen (c->ts.cl) == FAILURE)
5675              || !gfc_is_constant_expr (c->ts.cl->length))
5676            {
5677              gfc_error ("Character length of component '%s' needs to "
5678                         "be a constant specification expression at %L",
5679                         c->name,
5680                         c->ts.cl->length ? &c->ts.cl->length->where : &c->loc);
5681              return FAILURE;
5682            }
5683         }
5684
5685       if (c->ts.type == BT_DERIVED
5686             && sym->component_access != ACCESS_PRIVATE
5687             && gfc_check_access(sym->attr.access, sym->ns->default_access)
5688             && !c->ts.derived->attr.use_assoc
5689             && !gfc_check_access(c->ts.derived->attr.access,
5690                                  c->ts.derived->ns->default_access))
5691         {
5692           gfc_error ("The component '%s' is a PRIVATE type and cannot be "
5693                      "a component of '%s', which is PUBLIC at %L",
5694                       c->name, sym->name, &sym->declared_at);
5695           return FAILURE;
5696         }
5697
5698       if (sym->attr.sequence)
5699         {
5700           if (c->ts.type == BT_DERIVED && c->ts.derived->attr.sequence == 0)
5701             {
5702               gfc_error ("Component %s of SEQUENCE type declared at %L does "
5703                          "not have the SEQUENCE attribute",
5704                          c->ts.derived->name, &sym->declared_at);
5705               return FAILURE;
5706             }
5707         }
5708
5709       if (c->ts.type == BT_DERIVED && c->pointer
5710             && c->ts.derived->components == NULL)
5711         {
5712           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
5713                      "that has not been declared", c->name, sym->name,
5714                      &c->loc);
5715           return FAILURE;
5716         }
5717
5718       if (c->pointer || c->allocatable ||  c->as == NULL)
5719         continue;
5720
5721       for (i = 0; i < c->as->rank; i++)
5722         {
5723           if (c->as->lower[i] == NULL
5724                 || !gfc_is_constant_expr (c->as->lower[i])
5725                 || (resolve_index_expr (c->as->lower[i]) == FAILURE)
5726                 || c->as->upper[i] == NULL
5727                 || (resolve_index_expr (c->as->upper[i]) == FAILURE)
5728                 || !gfc_is_constant_expr (c->as->upper[i]))
5729             {
5730               gfc_error ("Component '%s' of '%s' at %L must have "
5731                          "constant array bounds",
5732                          c->name, sym->name, &c->loc);
5733               return FAILURE;
5734             }
5735         }
5736     }
5737
5738   /* Add derived type to the derived type list.  */
5739   for (dt_list = sym->ns->derived_types; dt_list; dt_list = dt_list->next)
5740     if (sym == dt_list->derived)
5741       break;
5742
5743   if (dt_list == NULL)
5744     {
5745       dt_list = gfc_get_dt_list ();
5746       dt_list->next = sym->ns->derived_types;
5747       dt_list->derived = sym;
5748       sym->ns->derived_types = dt_list;
5749     }
5750
5751   return SUCCESS;
5752 }
5753
5754
5755 static try
5756 resolve_fl_namelist (gfc_symbol *sym)
5757 {
5758   gfc_namelist *nl;
5759   gfc_symbol *nlsym;
5760
5761   /* Reject PRIVATE objects in a PUBLIC namelist.  */
5762   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
5763     {
5764       for (nl = sym->namelist; nl; nl = nl->next)
5765         {
5766           if (!nl->sym->attr.use_assoc
5767                 && !(sym->ns->parent == nl->sym->ns)
5768                        && !gfc_check_access(nl->sym->attr.access,
5769                                             nl->sym->ns->default_access))
5770             {
5771               gfc_error ("PRIVATE symbol '%s' cannot be member of "
5772                          "PUBLIC namelist at %L", nl->sym->name,
5773                          &sym->declared_at);
5774               return FAILURE;
5775             }
5776         }
5777     }
5778
5779   /* Reject namelist arrays that are not constant shape.  */
5780   for (nl = sym->namelist; nl; nl = nl->next)
5781     {
5782       if (is_non_constant_shape_array (nl->sym))
5783         {
5784           gfc_error ("The array '%s' must have constant shape to be "
5785                      "a NAMELIST object at %L", nl->sym->name,
5786                      &sym->declared_at);
5787           return FAILURE;
5788         }
5789     }
5790
5791   /* Namelist objects cannot have allocatable components.  */
5792   for (nl = sym->namelist; nl; nl = nl->next)
5793     {
5794       if (nl->sym->ts.type == BT_DERIVED
5795             && nl->sym->ts.derived->attr.alloc_comp)
5796         {
5797           gfc_error ("NAMELIST object '%s' at %L cannot have ALLOCATABLE "
5798                      "components", nl->sym->name, &sym->declared_at);
5799           return FAILURE;
5800         }
5801     }
5802
5803   /* 14.1.2 A module or internal procedure represent local entities
5804      of the same type as a namelist member and so are not allowed.
5805      Note that this is sometimes caught by check_conflict so the
5806      same message has been used.  */
5807   for (nl = sym->namelist; nl; nl = nl->next)
5808     {
5809       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
5810         continue;
5811       nlsym = NULL;
5812       if (sym->ns->parent && nl->sym && nl->sym->name)
5813         gfc_find_symbol (nl->sym->name, sym->ns->parent, 0, &nlsym);
5814       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
5815         {
5816           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
5817                      "attribute in '%s' at %L", nlsym->name,
5818                      &sym->declared_at);
5819           return FAILURE;
5820         }
5821     }
5822
5823   return SUCCESS;
5824 }
5825
5826
5827 static try
5828 resolve_fl_parameter (gfc_symbol *sym)
5829 {
5830   /* A parameter array's shape needs to be constant.  */
5831   if (sym->as != NULL && !gfc_is_compile_time_shape (sym->as))
5832     {
5833       gfc_error ("Parameter array '%s' at %L cannot be automatic "
5834                  "or assumed shape", sym->name, &sym->declared_at);
5835       return FAILURE;
5836     }
5837
5838   /* Make sure a parameter that has been implicitly typed still
5839      matches the implicit type, since PARAMETER statements can precede
5840      IMPLICIT statements.  */
5841   if (sym->attr.implicit_type
5842         && !gfc_compare_types (&sym->ts,
5843                                gfc_get_default_type (sym, sym->ns)))
5844     {
5845       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
5846                  "later IMPLICIT type", sym->name, &sym->declared_at);
5847       return FAILURE;
5848     }
5849
5850   /* Make sure the types of derived parameters are consistent.  This
5851      type checking is deferred until resolution because the type may
5852      refer to a derived type from the host.  */
5853   if (sym->ts.type == BT_DERIVED
5854         && !gfc_compare_types (&sym->ts, &sym->value->ts))
5855     {
5856       gfc_error ("Incompatible derived type in PARAMETER at %L",
5857                  &sym->value->where);
5858       return FAILURE;
5859     }
5860   return SUCCESS;
5861 }
5862
5863
5864 /* Do anything necessary to resolve a symbol.  Right now, we just
5865    assume that an otherwise unknown symbol is a variable.  This sort
5866    of thing commonly happens for symbols in module.  */
5867
5868 static void
5869 resolve_symbol (gfc_symbol * sym)
5870 {
5871   /* Zero if we are checking a formal namespace.  */
5872   static int formal_ns_flag = 1;
5873   int formal_ns_save, check_constant, mp_flag;
5874   gfc_symtree *symtree;
5875   gfc_symtree *this_symtree;
5876   gfc_namespace *ns;
5877   gfc_component *c;
5878
5879   if (sym->attr.flavor == FL_UNKNOWN)
5880     {
5881
5882     /* If we find that a flavorless symbol is an interface in one of the
5883        parent namespaces, find its symtree in this namespace, free the
5884        symbol and set the symtree to point to the interface symbol.  */
5885       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
5886         {
5887           symtree = gfc_find_symtree (ns->sym_root, sym->name);
5888           if (symtree && symtree->n.sym->generic)
5889             {
5890               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
5891                                                sym->name);
5892               sym->refs--;
5893               if (!sym->refs)
5894                 gfc_free_symbol (sym);
5895               symtree->n.sym->refs++;
5896               this_symtree->n.sym = symtree->n.sym;
5897               return;
5898             }
5899         }
5900
5901       /* Otherwise give it a flavor according to such attributes as
5902          it has.  */
5903       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
5904         sym->attr.flavor = FL_VARIABLE;
5905       else
5906         {
5907           sym->attr.flavor = FL_PROCEDURE;
5908           if (sym->attr.dimension)
5909             sym->attr.function = 1;
5910         }
5911     }
5912
5913   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
5914     return;
5915
5916   /* Symbols that are module procedures with results (functions) have
5917      the types and array specification copied for type checking in
5918      procedures that call them, as well as for saving to a module
5919      file.  These symbols can't stand the scrutiny that their results
5920      can.  */
5921   mp_flag = (sym->result != NULL && sym->result != sym);
5922
5923   /* Assign default type to symbols that need one and don't have one.  */
5924   if (sym->ts.type == BT_UNKNOWN)
5925     {
5926       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
5927         gfc_set_default_type (sym, 1, NULL);
5928
5929       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
5930         {
5931           /* The specific case of an external procedure should emit an error
5932              in the case that there is no implicit type.  */
5933           if (!mp_flag)
5934             gfc_set_default_type (sym, sym->attr.external, NULL);
5935           else
5936             {
5937               /* Result may be in another namespace.  */
5938               resolve_symbol (sym->result);
5939
5940               sym->ts = sym->result->ts;
5941               sym->as = gfc_copy_array_spec (sym->result->as);
5942               sym->attr.dimension = sym->result->attr.dimension;
5943               sym->attr.pointer = sym->result->attr.pointer;
5944               sym->attr.allocatable = sym->result->attr.allocatable;
5945             }
5946         }
5947     }
5948
5949   /* Assumed size arrays and assumed shape arrays must be dummy
5950      arguments.  */
5951
5952   if (sym->as != NULL
5953       && (sym->as->type == AS_ASSUMED_SIZE
5954           || sym->as->type == AS_ASSUMED_SHAPE)
5955       && sym->attr.dummy == 0)
5956     {
5957       if (sym->as->type == AS_ASSUMED_SIZE)
5958         gfc_error ("Assumed size array at %L must be a dummy argument",
5959                    &sym->declared_at);
5960       else
5961         gfc_error ("Assumed shape array at %L must be a dummy argument",
5962                    &sym->declared_at);
5963       return;
5964     }
5965
5966   /* Make sure symbols with known intent or optional are really dummy
5967      variable.  Because of ENTRY statement, this has to be deferred
5968      until resolution time.  */
5969
5970   if (!sym->attr.dummy
5971       && (sym->attr.optional
5972           || sym->attr.intent != INTENT_UNKNOWN))
5973     {
5974       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
5975       return;
5976     }
5977
5978   if (sym->attr.value && !sym->attr.dummy)
5979     {
5980       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
5981                  "it is not a dummy", sym->name, &sym->declared_at);
5982       return;
5983     }
5984
5985
5986   /* If a derived type symbol has reached this point, without its
5987      type being declared, we have an error.  Notice that most
5988      conditions that produce undefined derived types have already
5989      been dealt with.  However, the likes of:
5990      implicit type(t) (t) ..... call foo (t) will get us here if
5991      the type is not declared in the scope of the implicit
5992      statement. Change the type to BT_UNKNOWN, both because it is so
5993      and to prevent an ICE.  */
5994   if (sym->ts.type == BT_DERIVED
5995         && sym->ts.derived->components == NULL)
5996     {
5997       gfc_error ("The derived type '%s' at %L is of type '%s', "
5998                  "which has not been defined", sym->name,
5999                   &sym->declared_at, sym->ts.derived->name);
6000       sym->ts.type = BT_UNKNOWN;
6001       return;
6002     }
6003
6004   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
6005      default initialization is defined (5.1.2.4.4).  */
6006   if (sym->ts.type == BT_DERIVED
6007         && sym->attr.dummy
6008         && sym->attr.intent == INTENT_OUT
6009         && sym->as
6010         && sym->as->type == AS_ASSUMED_SIZE)
6011     {
6012       for (c = sym->ts.derived->components; c; c = c->next)
6013         {
6014           if (c->initializer)
6015             {
6016               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
6017                          "ASSUMED SIZE and so cannot have a default initializer",
6018                          sym->name, &sym->declared_at);
6019               return;
6020             }
6021         }
6022     }
6023
6024   switch (sym->attr.flavor)
6025     {
6026     case FL_VARIABLE:
6027       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
6028         return;
6029       break;
6030
6031     case FL_PROCEDURE:
6032       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
6033         return;
6034       break;
6035
6036     case FL_NAMELIST:
6037       if (resolve_fl_namelist (sym) == FAILURE)
6038         return;
6039       break;
6040
6041     case FL_PARAMETER:
6042       if (resolve_fl_parameter (sym) == FAILURE)
6043         return;
6044       break;
6045
6046     default:
6047       break;
6048     }
6049
6050   /* Make sure that intrinsic exist */
6051   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
6052       && ! gfc_intrinsic_name(sym->name, 0)
6053       && ! gfc_intrinsic_name(sym->name, 1))
6054     gfc_error("Intrinsic at %L does not exist", &sym->declared_at);
6055
6056   /* Resolve array specifier. Check as well some constraints
6057      on COMMON blocks.  */
6058
6059   check_constant = sym->attr.in_common && !sym->attr.pointer;
6060
6061   /* Set the formal_arg_flag so that check_conflict will not throw
6062      an error for host associated variables in the specification
6063      expression for an array_valued function.  */
6064   if (sym->attr.function && sym->as)
6065     formal_arg_flag = 1;
6066
6067   gfc_resolve_array_spec (sym->as, check_constant);
6068
6069   formal_arg_flag = 0;
6070
6071   /* Resolve formal namespaces.  */
6072
6073   if (formal_ns_flag && sym != NULL && sym->formal_ns != NULL)
6074     {
6075       formal_ns_save = formal_ns_flag;
6076       formal_ns_flag = 0;
6077       gfc_resolve (sym->formal_ns);
6078       formal_ns_flag = formal_ns_save;
6079     }
6080
6081   /* Check threadprivate restrictions.  */
6082   if (sym->attr.threadprivate && !sym->attr.save
6083       && (!sym->attr.in_common
6084           && sym->module == NULL
6085           && (sym->ns->proc_name == NULL
6086               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
6087     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
6088
6089   /* If we have come this far we can apply default-initializers, as
6090      described in 14.7.5, to those variables that have not already
6091      been assigned one.  */
6092   if (sym->ts.type == BT_DERIVED
6093         && sym->attr.referenced
6094         && sym->ns == gfc_current_ns
6095         && !sym->value
6096         && !sym->attr.allocatable
6097         && !sym->attr.alloc_comp)
6098     {
6099       symbol_attribute *a = &sym->attr;
6100
6101       if ((!a->save && !a->dummy && !a->pointer
6102                 && !a->in_common && !a->use_assoc
6103                 && !(a->function && sym != sym->result))
6104              ||
6105           (a->dummy && a->intent == INTENT_OUT))
6106         apply_default_init (sym);
6107     }
6108 }
6109
6110
6111
6112 /************* Resolve DATA statements *************/
6113
6114 static struct
6115 {
6116   gfc_data_value *vnode;
6117   unsigned int left;
6118 }
6119 values;
6120
6121
6122 /* Advance the values structure to point to the next value in the data list.  */
6123
6124 static try
6125 next_data_value (void)
6126 {
6127   while (values.left == 0)
6128     {
6129       if (values.vnode->next == NULL)
6130         return FAILURE;
6131
6132       values.vnode = values.vnode->next;
6133       values.left = values.vnode->repeat;
6134     }
6135
6136   return SUCCESS;
6137 }
6138
6139
6140 static try
6141 check_data_variable (gfc_data_variable * var, locus * where)
6142 {
6143   gfc_expr *e;
6144   mpz_t size;
6145   mpz_t offset;
6146   try t;
6147   ar_type mark = AR_UNKNOWN;
6148   int i;
6149   mpz_t section_index[GFC_MAX_DIMENSIONS];
6150   gfc_ref *ref;
6151   gfc_array_ref *ar;
6152
6153   if (gfc_resolve_expr (var->expr) == FAILURE)
6154     return FAILURE;
6155
6156   ar = NULL;
6157   mpz_init_set_si (offset, 0);
6158   e = var->expr;
6159
6160   if (e->expr_type != EXPR_VARIABLE)
6161     gfc_internal_error ("check_data_variable(): Bad expression");
6162
6163   if (e->symtree->n.sym->ns->is_block_data
6164         && !e->symtree->n.sym->attr.in_common)
6165     {
6166       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
6167                  e->symtree->n.sym->name, &e->symtree->n.sym->declared_at);
6168     }
6169
6170   if (e->rank == 0)
6171     {
6172       mpz_init_set_ui (size, 1);
6173       ref = NULL;
6174     }
6175   else
6176     {
6177       ref = e->ref;
6178
6179       /* Find the array section reference.  */
6180       for (ref = e->ref; ref; ref = ref->next)
6181         {
6182           if (ref->type != REF_ARRAY)
6183             continue;
6184           if (ref->u.ar.type == AR_ELEMENT)
6185             continue;
6186           break;
6187         }
6188       gcc_assert (ref);
6189
6190       /* Set marks according to the reference pattern.  */
6191       switch (ref->u.ar.type)
6192         {
6193         case AR_FULL:
6194           mark = AR_FULL;
6195           break;
6196
6197         case AR_SECTION:
6198           ar = &ref->u.ar;
6199           /* Get the start position of array section.  */
6200           gfc_get_section_index (ar, section_index, &offset);
6201           mark = AR_SECTION;
6202           break;
6203
6204         default:
6205           gcc_unreachable ();
6206         }
6207
6208       if (gfc_array_size (e, &size) == FAILURE)
6209         {
6210           gfc_error ("Nonconstant array section at %L in DATA statement",
6211                      &e->where);
6212           mpz_clear (offset);
6213           return FAILURE;
6214         }
6215     }
6216
6217   t = SUCCESS;
6218
6219   while (mpz_cmp_ui (size, 0) > 0)
6220     {
6221       if (next_data_value () == FAILURE)
6222         {
6223           gfc_error ("DATA statement at %L has more variables than values",
6224                      where);
6225           t = FAILURE;
6226           break;
6227         }
6228
6229       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
6230       if (t == FAILURE)
6231         break;
6232
6233       /* If we have more than one element left in the repeat count,
6234          and we have more than one element left in the target variable,
6235          then create a range assignment.  */
6236       /* ??? Only done for full arrays for now, since array sections
6237          seem tricky.  */
6238       if (mark == AR_FULL && ref && ref->next == NULL
6239           && values.left > 1 && mpz_cmp_ui (size, 1) > 0)
6240         {
6241           mpz_t range;
6242
6243           if (mpz_cmp_ui (size, values.left) >= 0)
6244             {
6245               mpz_init_set_ui (range, values.left);
6246               mpz_sub_ui (size, size, values.left);
6247               values.left = 0;
6248             }
6249           else
6250             {
6251               mpz_init_set (range, size);
6252               values.left -= mpz_get_ui (size);
6253               mpz_set_ui (size, 0);
6254             }
6255
6256           gfc_assign_data_value_range (var->expr, values.vnode->expr,
6257                                        offset, range);
6258
6259           mpz_add (offset, offset, range);
6260           mpz_clear (range);
6261         }
6262
6263       /* Assign initial value to symbol.  */
6264       else
6265         {
6266           values.left -= 1;
6267           mpz_sub_ui (size, size, 1);
6268
6269           gfc_assign_data_value (var->expr, values.vnode->expr, offset);
6270
6271           if (mark == AR_FULL)
6272             mpz_add_ui (offset, offset, 1);
6273
6274           /* Modify the array section indexes and recalculate the offset
6275              for next element.  */
6276           else if (mark == AR_SECTION)
6277             gfc_advance_section (section_index, ar, &offset);
6278         }
6279     }
6280
6281   if (mark == AR_SECTION)
6282     {
6283       for (i = 0; i < ar->dimen; i++)
6284         mpz_clear (section_index[i]);
6285     }
6286
6287   mpz_clear (size);
6288   mpz_clear (offset);
6289
6290   return t;
6291 }
6292
6293
6294 static try traverse_data_var (gfc_data_variable *, locus *);
6295
6296 /* Iterate over a list of elements in a DATA statement.  */
6297
6298 static try
6299 traverse_data_list (gfc_data_variable * var, locus * where)
6300 {
6301   mpz_t trip;
6302   iterator_stack frame;
6303   gfc_expr *e;
6304
6305   mpz_init (frame.value);
6306
6307   mpz_init_set (trip, var->iter.end->value.integer);
6308   mpz_sub (trip, trip, var->iter.start->value.integer);
6309   mpz_add (trip, trip, var->iter.step->value.integer);
6310
6311   mpz_div (trip, trip, var->iter.step->value.integer);
6312
6313   mpz_set (frame.value, var->iter.start->value.integer);
6314
6315   frame.prev = iter_stack;
6316   frame.variable = var->iter.var->symtree;
6317   iter_stack = &frame;
6318
6319   while (mpz_cmp_ui (trip, 0) > 0)
6320     {
6321       if (traverse_data_var (var->list, where) == FAILURE)
6322         {
6323           mpz_clear (trip);
6324           return FAILURE;
6325         }
6326
6327       e = gfc_copy_expr (var->expr);
6328       if (gfc_simplify_expr (e, 1) == FAILURE)
6329         {
6330           gfc_free_expr (e);
6331           return FAILURE;
6332         }
6333
6334       mpz_add (frame.value, frame.value, var->iter.step->value.integer);
6335
6336       mpz_sub_ui (trip, trip, 1);
6337     }
6338
6339   mpz_clear (trip);
6340   mpz_clear (frame.value);
6341
6342   iter_stack = frame.prev;
6343   return SUCCESS;
6344 }
6345
6346
6347 /* Type resolve variables in the variable list of a DATA statement.  */
6348
6349 static try
6350 traverse_data_var (gfc_data_variable * var, locus * where)
6351 {
6352   try t;
6353
6354   for (; var; var = var->next)
6355     {
6356       if (var->expr == NULL)
6357         t = traverse_data_list (var, where);
6358       else
6359         t = check_data_variable (var, where);
6360
6361       if (t == FAILURE)
6362         return FAILURE;
6363     }
6364
6365   return SUCCESS;
6366 }
6367
6368
6369 /* Resolve the expressions and iterators associated with a data statement.
6370    This is separate from the assignment checking because data lists should
6371    only be resolved once.  */
6372
6373 static try
6374 resolve_data_variables (gfc_data_variable * d)
6375 {
6376   for (; d; d = d->next)
6377     {
6378       if (d->list == NULL)
6379         {
6380           if (gfc_resolve_expr (d->expr) == FAILURE)
6381             return FAILURE;
6382         }
6383       else
6384         {
6385           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
6386             return FAILURE;
6387
6388           if (d->iter.start->expr_type != EXPR_CONSTANT
6389               || d->iter.end->expr_type != EXPR_CONSTANT
6390               || d->iter.step->expr_type != EXPR_CONSTANT)
6391             gfc_internal_error ("resolve_data_variables(): Bad iterator");
6392
6393           if (resolve_data_variables (d->list) == FAILURE)
6394             return FAILURE;
6395         }
6396     }
6397
6398   return SUCCESS;
6399 }
6400
6401
6402 /* Resolve a single DATA statement.  We implement this by storing a pointer to
6403    the value list into static variables, and then recursively traversing the
6404    variables list, expanding iterators and such.  */
6405
6406 static void
6407 resolve_data (gfc_data * d)
6408 {
6409   if (resolve_data_variables (d->var) == FAILURE)
6410     return;
6411
6412   values.vnode = d->value;
6413   values.left = (d->value == NULL) ? 0 : d->value->repeat;
6414
6415   if (traverse_data_var (d->var, &d->where) == FAILURE)
6416     return;
6417
6418   /* At this point, we better not have any values left.  */
6419
6420   if (next_data_value () == SUCCESS)
6421     gfc_error ("DATA statement at %L has more values than variables",
6422                &d->where);
6423 }
6424
6425
6426 /* Determines if a variable is not 'pure', ie not assignable within a pure
6427    procedure.  Returns zero if assignment is OK, nonzero if there is a problem.
6428  */
6429
6430 int
6431 gfc_impure_variable (gfc_symbol * sym)
6432 {
6433   if (sym->attr.use_assoc || sym->attr.in_common)
6434     return 1;
6435
6436   if (sym->ns != gfc_current_ns)
6437     return !sym->attr.function;
6438
6439   /* TODO: Check storage association through EQUIVALENCE statements */
6440
6441   return 0;
6442 }
6443
6444
6445 /* Test whether a symbol is pure or not.  For a NULL pointer, checks the
6446    symbol of the current procedure.  */
6447
6448 int
6449 gfc_pure (gfc_symbol * sym)
6450 {
6451   symbol_attribute attr;
6452
6453   if (sym == NULL)
6454     sym = gfc_current_ns->proc_name;
6455   if (sym == NULL)
6456     return 0;
6457
6458   attr = sym->attr;
6459
6460   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
6461 }
6462
6463
6464 /* Test whether the current procedure is elemental or not.  */
6465
6466 int
6467 gfc_elemental (gfc_symbol * sym)
6468 {
6469   symbol_attribute attr;
6470
6471   if (sym == NULL)
6472     sym = gfc_current_ns->proc_name;
6473   if (sym == NULL)
6474     return 0;
6475   attr = sym->attr;
6476
6477   return attr.flavor == FL_PROCEDURE && attr.elemental;
6478 }
6479
6480
6481 /* Warn about unused labels.  */
6482
6483 static void
6484 warn_unused_fortran_label (gfc_st_label * label)
6485 {
6486   if (label == NULL)
6487     return;
6488
6489   warn_unused_fortran_label (label->left);
6490
6491   if (label->defined == ST_LABEL_UNKNOWN)
6492     return;
6493
6494   switch (label->referenced)
6495     {
6496     case ST_LABEL_UNKNOWN:
6497       gfc_warning ("Label %d at %L defined but not used", label->value,
6498                    &label->where);
6499       break;
6500
6501     case ST_LABEL_BAD_TARGET:
6502       gfc_warning ("Label %d at %L defined but cannot be used",
6503                    label->value, &label->where);
6504       break;
6505
6506     default:
6507       break;
6508     }
6509
6510   warn_unused_fortran_label (label->right);
6511 }
6512
6513
6514 /* Returns the sequence type of a symbol or sequence.  */
6515
6516 static seq_type
6517 sequence_type (gfc_typespec ts)
6518 {
6519   seq_type result;
6520   gfc_component *c;
6521
6522   switch (ts.type)
6523   {
6524     case BT_DERIVED:
6525
6526       if (ts.derived->components == NULL)
6527         return SEQ_NONDEFAULT;
6528
6529       result = sequence_type (ts.derived->components->ts);
6530       for (c = ts.derived->components->next; c; c = c->next)
6531         if (sequence_type (c->ts) != result)
6532           return SEQ_MIXED;
6533
6534       return result;
6535
6536     case BT_CHARACTER:
6537       if (ts.kind != gfc_default_character_kind)
6538           return SEQ_NONDEFAULT;
6539
6540       return SEQ_CHARACTER;
6541
6542     case BT_INTEGER:
6543       if (ts.kind != gfc_default_integer_kind)
6544           return SEQ_NONDEFAULT;
6545
6546       return SEQ_NUMERIC;
6547
6548     case BT_REAL:
6549       if (!(ts.kind == gfc_default_real_kind
6550              || ts.kind == gfc_default_double_kind))
6551           return SEQ_NONDEFAULT;
6552
6553       return SEQ_NUMERIC;
6554
6555     case BT_COMPLEX:
6556       if (ts.kind != gfc_default_complex_kind)
6557           return SEQ_NONDEFAULT;
6558
6559       return SEQ_NUMERIC;
6560
6561     case BT_LOGICAL:
6562       if (ts.kind != gfc_default_logical_kind)
6563           return SEQ_NONDEFAULT;
6564
6565       return SEQ_NUMERIC;
6566
6567     default:
6568       return SEQ_NONDEFAULT;
6569   }
6570 }
6571
6572
6573 /* Resolve derived type EQUIVALENCE object.  */
6574
6575 static try
6576 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
6577 {
6578   gfc_symbol *d;
6579   gfc_component *c = derived->components;
6580
6581   if (!derived)
6582     return SUCCESS;
6583
6584   /* Shall not be an object of nonsequence derived type.  */
6585   if (!derived->attr.sequence)
6586     {
6587       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
6588                  "attribute to be an EQUIVALENCE object", sym->name, &e->where);
6589       return FAILURE;
6590     }
6591
6592   /* Shall not have allocatable components. */
6593   if (derived->attr.alloc_comp)
6594     {
6595       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
6596                  "components to be an EQUIVALENCE object",sym->name, &e->where);
6597       return FAILURE;
6598     }
6599
6600   for (; c ; c = c->next)
6601     {
6602       d = c->ts.derived;
6603       if (d && (resolve_equivalence_derived (c->ts.derived, sym, e) == FAILURE))
6604         return FAILURE;
6605
6606       /* Shall not be an object of sequence derived type containing a pointer
6607          in the structure.  */
6608       if (c->pointer)
6609         {
6610           gfc_error ("Derived type variable '%s' at %L with pointer component(s) "
6611                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
6612           return FAILURE;
6613         }
6614
6615       if (c->initializer)
6616         {
6617           gfc_error ("Derived type variable '%s' at %L with default initializer "
6618                      "cannot be an EQUIVALENCE object", sym->name, &e->where);
6619           return FAILURE;
6620         }
6621     }
6622   return SUCCESS;
6623 }
6624
6625
6626 /* Resolve equivalence object. 
6627    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
6628    an allocatable array, an object of nonsequence derived type, an object of
6629    sequence derived type containing a pointer at any level of component
6630    selection, an automatic object, a function name, an entry name, a result
6631    name, a named constant, a structure component, or a subobject of any of
6632    the preceding objects.  A substring shall not have length zero.  A
6633    derived type shall not have components with default initialization nor
6634    shall two objects of an equivalence group be initialized.
6635    Either all or none of the objects shall have an protected attribute.
6636    The simple constraints are done in symbol.c(check_conflict) and the rest
6637    are implemented here.  */
6638
6639 static void
6640 resolve_equivalence (gfc_equiv *eq)
6641 {
6642   gfc_symbol *sym;
6643   gfc_symbol *derived;
6644   gfc_symbol *first_sym;
6645   gfc_expr *e;
6646   gfc_ref *r;
6647   locus *last_where = NULL;
6648   seq_type eq_type, last_eq_type;
6649   gfc_typespec *last_ts;
6650   int object, cnt_protected;
6651   const char *value_name;
6652   const char *msg;
6653
6654   value_name = NULL;
6655   last_ts = &eq->expr->symtree->n.sym->ts;
6656
6657   first_sym = eq->expr->symtree->n.sym;
6658
6659   cnt_protected = 0;
6660
6661   for (object = 1; eq; eq = eq->eq, object++)
6662     {
6663       e = eq->expr;
6664
6665       e->ts = e->symtree->n.sym->ts;
6666       /* match_varspec might not know yet if it is seeing
6667          array reference or substring reference, as it doesn't
6668          know the types.  */
6669       if (e->ref && e->ref->type == REF_ARRAY)
6670         {
6671           gfc_ref *ref = e->ref;
6672           sym = e->symtree->n.sym;
6673
6674           if (sym->attr.dimension)
6675             {
6676               ref->u.ar.as = sym->as;
6677               ref = ref->next;
6678             }
6679
6680           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
6681           if (e->ts.type == BT_CHARACTER
6682               && ref
6683               && ref->type == REF_ARRAY
6684               && ref->u.ar.dimen == 1
6685               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
6686               && ref->u.ar.stride[0] == NULL)
6687             {
6688               gfc_expr *start = ref->u.ar.start[0];
6689               gfc_expr *end = ref->u.ar.end[0];
6690               void *mem = NULL;
6691
6692               /* Optimize away the (:) reference.  */
6693               if (start == NULL && end == NULL)
6694                 {
6695                   if (e->ref == ref)
6696                     e->ref = ref->next;
6697                   else
6698                     e->ref->next = ref->next;
6699                   mem = ref;
6700                 }
6701               else
6702                 {
6703                   ref->type = REF_SUBSTRING;
6704                   if (start == NULL)
6705                     start = gfc_int_expr (1);
6706                   ref->u.ss.start = start;
6707                   if (end == NULL && e->ts.cl)
6708                     end = gfc_copy_expr (e->ts.cl->length);
6709                   ref->u.ss.end = end;
6710                   ref->u.ss.length = e->ts.cl;
6711                   e->ts.cl = NULL;
6712                 }
6713               ref = ref->next;
6714               gfc_free (mem);
6715             }
6716
6717           /* Any further ref is an error.  */
6718           if (ref)
6719             {
6720               gcc_assert (ref->type == REF_ARRAY);
6721               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
6722                          &ref->u.ar.where);
6723               continue;
6724             }
6725         }
6726
6727       if (gfc_resolve_expr (e) == FAILURE)
6728         continue;
6729
6730       sym = e->symtree->n.sym;
6731
6732       if (sym->attr.protected)
6733         cnt_protected++;
6734       if (cnt_protected > 0 && cnt_protected != object)
6735         {
6736               gfc_error ("Either all or none of the objects in the "
6737                          "EQUIVALENCE set at %L shall have the "
6738                          "PROTECTED attribute",
6739                          &e->where);
6740               break;
6741         }
6742
6743       /* An equivalence statement cannot have more than one initialized
6744          object.  */
6745       if (sym->value)
6746         {
6747           if (value_name != NULL)
6748             {
6749               gfc_error ("Initialized objects '%s' and '%s' cannot both "
6750                          "be in the EQUIVALENCE statement at %L",
6751                          value_name, sym->name, &e->where);
6752               continue;
6753             }
6754           else
6755             value_name = sym->name;
6756         }
6757
6758       /* Shall not equivalence common block variables in a PURE procedure.  */
6759       if (sym->ns->proc_name
6760             && sym->ns->proc_name->attr.pure
6761             && sym->attr.in_common)
6762         {
6763           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
6764                      "object in the pure procedure '%s'",
6765                      sym->name, &e->where, sym->ns->proc_name->name);
6766           break;
6767         }
6768
6769       /* Shall not be a named constant.  */
6770       if (e->expr_type == EXPR_CONSTANT)
6771         {
6772           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
6773                      "object", sym->name, &e->where);
6774           continue;
6775         }
6776
6777       derived = e->ts.derived;
6778       if (derived && resolve_equivalence_derived (derived, sym, e) == FAILURE)
6779         continue;
6780
6781       /* Check that the types correspond correctly:
6782          Note 5.28:
6783          A numeric sequence structure may be equivalenced to another sequence
6784          structure, an object of default integer type, default real type, double
6785          precision real type, default logical type such that components of the
6786          structure ultimately only become associated to objects of the same
6787          kind. A character sequence structure may be equivalenced to an object
6788          of default character kind or another character sequence structure.
6789          Other objects may be equivalenced only to objects of the same type and
6790          kind parameters.  */
6791
6792       /* Identical types are unconditionally OK.  */
6793       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
6794         goto identical_types;
6795
6796       last_eq_type = sequence_type (*last_ts);
6797       eq_type = sequence_type (sym->ts);
6798
6799       /* Since the pair of objects is not of the same type, mixed or
6800          non-default sequences can be rejected.  */
6801
6802       msg = "Sequence %s with mixed components in EQUIVALENCE "
6803             "statement at %L with different type objects";
6804       if ((object ==2
6805                && last_eq_type == SEQ_MIXED
6806                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
6807                                   last_where) == FAILURE)
6808            ||  (eq_type == SEQ_MIXED
6809                && gfc_notify_std (GFC_STD_GNU, msg,sym->name,
6810                                   &e->where) == FAILURE))
6811         continue;
6812
6813       msg = "Non-default type object or sequence %s in EQUIVALENCE "
6814             "statement at %L with objects of different type";
6815       if ((object ==2
6816                && last_eq_type == SEQ_NONDEFAULT
6817                && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
6818                                   last_where) == FAILURE)
6819            ||  (eq_type == SEQ_NONDEFAULT
6820                && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
6821                                   &e->where) == FAILURE))
6822         continue;
6823
6824       msg ="Non-CHARACTER object '%s' in default CHARACTER "
6825            "EQUIVALENCE statement at %L";
6826       if (last_eq_type == SEQ_CHARACTER
6827             && eq_type != SEQ_CHARACTER
6828             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
6829                                   &e->where) == FAILURE)
6830                 continue;
6831
6832       msg ="Non-NUMERIC object '%s' in default NUMERIC "
6833            "EQUIVALENCE statement at %L";
6834       if (last_eq_type == SEQ_NUMERIC
6835             && eq_type != SEQ_NUMERIC
6836             && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
6837                                   &e->where) == FAILURE)
6838                 continue;
6839
6840   identical_types:
6841       last_ts =&sym->ts;
6842       last_where = &e->where;
6843
6844       if (!e->ref)
6845         continue;
6846
6847       /* Shall not be an automatic array.  */
6848       if (e->ref->type == REF_ARRAY
6849           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
6850         {
6851           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
6852                      "an EQUIVALENCE object", sym->name, &e->where);
6853           continue;
6854         }
6855
6856       r = e->ref;
6857       while (r)
6858         {
6859           /* Shall not be a structure component.  */
6860           if (r->type == REF_COMPONENT)
6861             {
6862               gfc_error ("Structure component '%s' at %L cannot be an "
6863                          "EQUIVALENCE object",
6864                          r->u.c.component->name, &e->where);
6865               break;
6866             }
6867
6868           /* A substring shall not have length zero.  */
6869           if (r->type == REF_SUBSTRING)
6870             {
6871               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
6872                 {
6873                   gfc_error ("Substring at %L has length zero",
6874                              &r->u.ss.start->where);
6875                   break;
6876                 }
6877             }
6878           r = r->next;
6879         }
6880     }
6881 }
6882
6883
6884 /* Resolve function and ENTRY types, issue diagnostics if needed. */
6885
6886 static void
6887 resolve_fntype (gfc_namespace * ns)
6888 {
6889   gfc_entry_list *el;
6890   gfc_symbol *sym;
6891
6892   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
6893     return;
6894
6895   /* If there are any entries, ns->proc_name is the entry master
6896      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
6897   if (ns->entries)
6898     sym = ns->entries->sym;
6899   else
6900     sym = ns->proc_name;
6901   if (sym->result == sym
6902       && sym->ts.type == BT_UNKNOWN
6903       && gfc_set_default_type (sym, 0, NULL) == FAILURE
6904       && !sym->attr.untyped)
6905     {
6906       gfc_error ("Function '%s' at %L has no IMPLICIT type",
6907                  sym->name, &sym->declared_at);
6908       sym->attr.untyped = 1;
6909     }
6910
6911   if (sym->ts.type == BT_DERIVED && !sym->ts.derived->attr.use_assoc
6912       && !gfc_check_access (sym->ts.derived->attr.access,
6913                             sym->ts.derived->ns->default_access)
6914       && gfc_check_access (sym->attr.access, sym->ns->default_access))
6915     {
6916       gfc_error ("PUBLIC function '%s' at %L cannot be of PRIVATE type '%s'",
6917                  sym->name, &sym->declared_at, sym->ts.derived->name);
6918     }
6919
6920   /* Make sure that the type of a module derived type function is in the
6921      module namespace, by copying it from the namespace's derived type
6922      list, if necessary.  */
6923   if (sym->ts.type == BT_DERIVED
6924         && sym->ns->proc_name->attr.flavor == FL_MODULE
6925         && sym->ts.derived->ns
6926         && sym->ns != sym->ts.derived->ns)
6927     {
6928       gfc_dt_list *dt = sym->ns->derived_types;
6929
6930       for (; dt; dt = dt->next)
6931         if (gfc_compare_derived_types (sym->ts.derived, dt->derived))
6932           sym->ts.derived = dt->derived;
6933     }
6934
6935   if (ns->entries)
6936     for (el = ns->entries->next; el; el = el->next)
6937       {
6938         if (el->sym->result == el->sym
6939             && el->sym->ts.type == BT_UNKNOWN
6940             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
6941             && !el->sym->attr.untyped)
6942           {
6943             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
6944                        el->sym->name, &el->sym->declared_at);
6945             el->sym->attr.untyped = 1;
6946           }
6947       }
6948 }
6949
6950 /* 12.3.2.1.1 Defined operators.  */
6951
6952 static void
6953 gfc_resolve_uops(gfc_symtree *symtree)
6954 {
6955   gfc_interface *itr;
6956   gfc_symbol *sym;
6957   gfc_formal_arglist *formal;
6958
6959   if (symtree == NULL)
6960     return;
6961
6962   gfc_resolve_uops (symtree->left);
6963   gfc_resolve_uops (symtree->right);
6964
6965   for (itr = symtree->n.uop->operator; itr; itr = itr->next)
6966     {
6967       sym = itr->sym;
6968       if (!sym->attr.function)
6969         gfc_error("User operator procedure '%s' at %L must be a FUNCTION",
6970                   sym->name, &sym->declared_at);
6971
6972       if (sym->ts.type == BT_CHARACTER
6973             && !(sym->ts.cl && sym->ts.cl->length)
6974             && !(sym->result && sym->result->ts.cl && sym->result->ts.cl->length))
6975         gfc_error("User operator procedure '%s' at %L cannot be assumed character "
6976                   "length", sym->name, &sym->declared_at);
6977
6978       formal = sym->formal;
6979       if (!formal || !formal->sym)
6980         {
6981           gfc_error("User operator procedure '%s' at %L must have at least "
6982                     "one argument", sym->name, &sym->declared_at);
6983           continue;
6984         }
6985
6986       if (formal->sym->attr.intent != INTENT_IN)
6987         gfc_error ("First argument of operator interface at %L must be "
6988                    "INTENT(IN)", &sym->declared_at);
6989
6990       if (formal->sym->attr.optional)
6991         gfc_error ("First argument of operator interface at %L cannot be "
6992                    "optional", &sym->declared_at);
6993
6994       formal = formal->next;
6995       if (!formal || !formal->sym)
6996         continue;
6997
6998       if (formal->sym->attr.intent != INTENT_IN)
6999         gfc_error ("Second argument of operator interface at %L must be "
7000                    "INTENT(IN)", &sym->declared_at);
7001
7002       if (formal->sym->attr.optional)
7003         gfc_error ("Second argument of operator interface at %L cannot be "
7004                    "optional", &sym->declared_at);
7005
7006       if (formal->next)
7007         gfc_error ("Operator interface at %L must have, at most, two "
7008                    "arguments", &sym->declared_at);
7009     }
7010 }
7011
7012
7013 /* Examine all of the expressions associated with a program unit,
7014    assign types to all intermediate expressions, make sure that all
7015    assignments are to compatible types and figure out which names
7016    refer to which functions or subroutines.  It doesn't check code
7017    block, which is handled by resolve_code.  */
7018
7019 static void
7020 resolve_types (gfc_namespace * ns)
7021 {
7022   gfc_namespace *n;
7023   gfc_charlen *cl;
7024   gfc_data *d;
7025   gfc_equiv *eq;
7026
7027   gfc_current_ns = ns;
7028
7029   resolve_entries (ns);
7030
7031   resolve_contained_functions (ns);
7032
7033   gfc_traverse_ns (ns, resolve_symbol);
7034
7035   resolve_fntype (ns);
7036
7037   for (n = ns->contained; n; n = n->sibling)
7038     {
7039       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
7040         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
7041                    "also be PURE", n->proc_name->name,
7042                    &n->proc_name->declared_at);
7043
7044       resolve_types (n);
7045     }
7046
7047   forall_flag = 0;
7048   gfc_check_interfaces (ns);
7049
7050   for (cl = ns->cl_list; cl; cl = cl->next)
7051     resolve_charlen (cl);
7052
7053   gfc_traverse_ns (ns, resolve_values);
7054
7055   if (ns->save_all)
7056     gfc_save_all (ns);
7057
7058   iter_stack = NULL;
7059   for (d = ns->data; d; d = d->next)
7060     resolve_data (d);
7061
7062   iter_stack = NULL;
7063   gfc_traverse_ns (ns, gfc_formalize_init_value);
7064
7065   for (eq = ns->equiv; eq; eq = eq->next)
7066     resolve_equivalence (eq);
7067
7068   /* Warn about unused labels.  */
7069   if (warn_unused_label)
7070     warn_unused_fortran_label (ns->st_labels);
7071
7072   gfc_resolve_uops (ns->uop_root);
7073 }
7074
7075
7076 /* Call resolve_code recursively.  */
7077
7078 static void
7079 resolve_codes (gfc_namespace * ns)
7080 {
7081   gfc_namespace *n;
7082
7083   for (n = ns->contained; n; n = n->sibling)
7084     resolve_codes (n);
7085
7086   gfc_current_ns = ns;
7087   cs_base = NULL;
7088   /* Set to an out of range value.  */
7089   current_entry_id = -1;
7090   resolve_code (ns->code, ns);
7091 }
7092
7093
7094 /* This function is called after a complete program unit has been compiled.
7095    Its purpose is to examine all of the expressions associated with a program
7096    unit, assign types to all intermediate expressions, make sure that all
7097    assignments are to compatible types and figure out which names refer to
7098    which functions or subroutines.  */
7099
7100 void
7101 gfc_resolve (gfc_namespace * ns)
7102 {
7103   gfc_namespace *old_ns;
7104
7105   old_ns = gfc_current_ns;
7106
7107   resolve_types (ns);
7108   resolve_codes (ns);
7109
7110   gfc_current_ns = old_ns;
7111 }