OSDN Git Service

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