OSDN Git Service

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