OSDN Git Service

5afb08d516f6e9de233c9580a5dfed2277667b3f
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Andy Vaught
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "flags.h"
25 #include "gfortran.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "arith.h"  /* For gfc_compare_expr().  */
29 #include "dependency.h"
30 #include "data.h"
31 #include "target-memory.h" /* for gfc_simplify_transfer */
32 #include "constructor.h"
33
34 /* Types used in equivalence statements.  */
35
36 typedef enum seq_type
37 {
38   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
39 }
40 seq_type;
41
42 /* Stack to keep track of the nesting of blocks as we move through the
43    code.  See resolve_branch() and resolve_code().  */
44
45 typedef struct code_stack
46 {
47   struct gfc_code *head, *current;
48   struct code_stack *prev;
49
50   /* This bitmap keeps track of the targets valid for a branch from
51      inside this block except for END {IF|SELECT}s of enclosing
52      blocks.  */
53   bitmap reachable_labels;
54 }
55 code_stack;
56
57 static code_stack *cs_base = NULL;
58
59
60 /* Nonzero if we're inside a FORALL block.  */
61
62 static int forall_flag;
63
64 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
65
66 static int omp_workshare_flag;
67
68 /* Nonzero if we are processing a formal arglist. The corresponding function
69    resets the flag each time that it is read.  */
70 static int formal_arg_flag = 0;
71
72 /* True if we are resolving a specification expression.  */
73 static int specification_expr = 0;
74
75 /* The id of the last entry seen.  */
76 static int current_entry_id;
77
78 /* We use bitmaps to determine if a branch target is valid.  */
79 static bitmap_obstack labels_obstack;
80
81 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
82 static bool inquiry_argument = false;
83
84 int
85 gfc_is_formal_arg (void)
86 {
87   return formal_arg_flag;
88 }
89
90 /* Is the symbol host associated?  */
91 static bool
92 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
93 {
94   for (ns = ns->parent; ns; ns = ns->parent)
95     {      
96       if (sym->ns == ns)
97         return true;
98     }
99
100   return false;
101 }
102
103 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
104    an ABSTRACT derived-type.  If where is not NULL, an error message with that
105    locus is printed, optionally using name.  */
106
107 static gfc_try
108 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
109 {
110   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
111     {
112       if (where)
113         {
114           if (name)
115             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
116                        name, where, ts->u.derived->name);
117           else
118             gfc_error ("ABSTRACT type '%s' used at %L",
119                        ts->u.derived->name, where);
120         }
121
122       return FAILURE;
123     }
124
125   return SUCCESS;
126 }
127
128
129 /* Resolve types of formal argument lists.  These have to be done early so that
130    the formal argument lists of module procedures can be copied to the
131    containing module before the individual procedures are resolved
132    individually.  We also resolve argument lists of procedures in interface
133    blocks because they are self-contained scoping units.
134
135    Since a dummy argument cannot be a non-dummy procedure, the only
136    resort left for untyped names are the IMPLICIT types.  */
137
138 static void
139 resolve_formal_arglist (gfc_symbol *proc)
140 {
141   gfc_formal_arglist *f;
142   gfc_symbol *sym;
143   int i;
144
145   if (proc->result != NULL)
146     sym = proc->result;
147   else
148     sym = proc;
149
150   if (gfc_elemental (proc)
151       || sym->attr.pointer || sym->attr.allocatable
152       || (sym->as && sym->as->rank > 0))
153     {
154       proc->attr.always_explicit = 1;
155       sym->attr.always_explicit = 1;
156     }
157
158   formal_arg_flag = 1;
159
160   for (f = proc->formal; f; f = f->next)
161     {
162       sym = f->sym;
163
164       if (sym == NULL)
165         {
166           /* Alternate return placeholder.  */
167           if (gfc_elemental (proc))
168             gfc_error ("Alternate return specifier in elemental subroutine "
169                        "'%s' at %L is not allowed", proc->name,
170                        &proc->declared_at);
171           if (proc->attr.function)
172             gfc_error ("Alternate return specifier in function "
173                        "'%s' at %L is not allowed", proc->name,
174                        &proc->declared_at);
175           continue;
176         }
177
178       if (sym->attr.if_source != IFSRC_UNKNOWN)
179         resolve_formal_arglist (sym);
180
181       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
182         {
183           if (gfc_pure (proc) && !gfc_pure (sym))
184             {
185               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
186                          "also be PURE", sym->name, &sym->declared_at);
187               continue;
188             }
189
190           if (gfc_elemental (proc))
191             {
192               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
193                          "procedure", &sym->declared_at);
194               continue;
195             }
196
197           if (sym->attr.function
198                 && sym->ts.type == BT_UNKNOWN
199                 && sym->attr.intrinsic)
200             {
201               gfc_intrinsic_sym *isym;
202               isym = gfc_find_function (sym->name);
203               if (isym == NULL || !isym->specific)
204                 {
205                   gfc_error ("Unable to find a specific INTRINSIC procedure "
206                              "for the reference '%s' at %L", sym->name,
207                              &sym->declared_at);
208                 }
209               sym->ts = isym->ts;
210             }
211
212           continue;
213         }
214
215       if (sym->ts.type == BT_UNKNOWN)
216         {
217           if (!sym->attr.function || sym->result == sym)
218             gfc_set_default_type (sym, 1, sym->ns);
219         }
220
221       gfc_resolve_array_spec (sym->as, 0);
222
223       /* We can't tell if an array with dimension (:) is assumed or deferred
224          shape until we know if it has the pointer or allocatable attributes.
225       */
226       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
227           && !(sym->attr.pointer || sym->attr.allocatable))
228         {
229           sym->as->type = AS_ASSUMED_SHAPE;
230           for (i = 0; i < sym->as->rank; i++)
231             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
232                                                   NULL, 1);
233         }
234
235       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
236           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
237           || sym->attr.optional)
238         {
239           proc->attr.always_explicit = 1;
240           if (proc->result)
241             proc->result->attr.always_explicit = 1;
242         }
243
244       /* If the flavor is unknown at this point, it has to be a variable.
245          A procedure specification would have already set the type.  */
246
247       if (sym->attr.flavor == FL_UNKNOWN)
248         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
249
250       if (gfc_pure (proc) && !sym->attr.pointer
251           && sym->attr.flavor != FL_PROCEDURE)
252         {
253           if (proc->attr.function && sym->attr.intent != INTENT_IN)
254             gfc_error ("Argument '%s' of pure function '%s' at %L must be "
255                        "INTENT(IN)", sym->name, proc->name,
256                        &sym->declared_at);
257
258           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
259             gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
260                        "have its INTENT specified", sym->name, proc->name,
261                        &sym->declared_at);
262         }
263
264       if (gfc_elemental (proc))
265         {
266           /* F2008, C1289.  */
267           if (sym->attr.codimension)
268             {
269               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
270                          "procedure", sym->name, &sym->declared_at);
271               continue;
272             }
273
274           if (sym->as != NULL)
275             {
276               gfc_error ("Argument '%s' of elemental procedure at %L must "
277                          "be scalar", sym->name, &sym->declared_at);
278               continue;
279             }
280
281           if (sym->attr.pointer)
282             {
283               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
284                          "have the POINTER attribute", sym->name,
285                          &sym->declared_at);
286               continue;
287             }
288
289           if (sym->attr.flavor == FL_PROCEDURE)
290             {
291               gfc_error ("Dummy procedure '%s' not allowed in elemental "
292                          "procedure '%s' at %L", sym->name, proc->name,
293                          &sym->declared_at);
294               continue;
295             }
296         }
297
298       /* Each dummy shall be specified to be scalar.  */
299       if (proc->attr.proc == PROC_ST_FUNCTION)
300         {
301           if (sym->as != NULL)
302             {
303               gfc_error ("Argument '%s' of statement function at %L must "
304                          "be scalar", sym->name, &sym->declared_at);
305               continue;
306             }
307
308           if (sym->ts.type == BT_CHARACTER)
309             {
310               gfc_charlen *cl = sym->ts.u.cl;
311               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
312                 {
313                   gfc_error ("Character-valued argument '%s' of statement "
314                              "function at %L must have constant length",
315                              sym->name, &sym->declared_at);
316                   continue;
317                 }
318             }
319         }
320     }
321   formal_arg_flag = 0;
322 }
323
324
325 /* Work function called when searching for symbols that have argument lists
326    associated with them.  */
327
328 static void
329 find_arglists (gfc_symbol *sym)
330 {
331   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
332     return;
333
334   resolve_formal_arglist (sym);
335 }
336
337
338 /* Given a namespace, resolve all formal argument lists within the namespace.
339  */
340
341 static void
342 resolve_formal_arglists (gfc_namespace *ns)
343 {
344   if (ns == NULL)
345     return;
346
347   gfc_traverse_ns (ns, find_arglists);
348 }
349
350
351 static void
352 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
353 {
354   gfc_try t;
355
356   /* If this namespace is not a function or an entry master function,
357      ignore it.  */
358   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
359       || sym->attr.entry_master)
360     return;
361
362   /* Try to find out of what the return type is.  */
363   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
364     {
365       t = gfc_set_default_type (sym->result, 0, ns);
366
367       if (t == FAILURE && !sym->result->attr.untyped)
368         {
369           if (sym->result == sym)
370             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
371                        sym->name, &sym->declared_at);
372           else if (!sym->result->attr.proc_pointer)
373             gfc_error ("Result '%s' of contained function '%s' at %L has "
374                        "no IMPLICIT type", sym->result->name, sym->name,
375                        &sym->result->declared_at);
376           sym->result->attr.untyped = 1;
377         }
378     }
379
380   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
381      type, lists the only ways a character length value of * can be used:
382      dummy arguments of procedures, named constants, and function results
383      in external functions.  Internal function results and results of module
384      procedures are not on this list, ergo, not permitted.  */
385
386   if (sym->result->ts.type == BT_CHARACTER)
387     {
388       gfc_charlen *cl = sym->result->ts.u.cl;
389       if (!cl || !cl->length)
390         {
391           /* See if this is a module-procedure and adapt error message
392              accordingly.  */
393           bool module_proc;
394           gcc_assert (ns->parent && ns->parent->proc_name);
395           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
396
397           gfc_error ("Character-valued %s '%s' at %L must not be"
398                      " assumed length",
399                      module_proc ? _("module procedure")
400                                  : _("internal function"),
401                      sym->name, &sym->declared_at);
402         }
403     }
404 }
405
406
407 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
408    introduce duplicates.  */
409
410 static void
411 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
412 {
413   gfc_formal_arglist *f, *new_arglist;
414   gfc_symbol *new_sym;
415
416   for (; new_args != NULL; new_args = new_args->next)
417     {
418       new_sym = new_args->sym;
419       /* See if this arg is already in the formal argument list.  */
420       for (f = proc->formal; f; f = f->next)
421         {
422           if (new_sym == f->sym)
423             break;
424         }
425
426       if (f)
427         continue;
428
429       /* Add a new argument.  Argument order is not important.  */
430       new_arglist = gfc_get_formal_arglist ();
431       new_arglist->sym = new_sym;
432       new_arglist->next = proc->formal;
433       proc->formal  = new_arglist;
434     }
435 }
436
437
438 /* Flag the arguments that are not present in all entries.  */
439
440 static void
441 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
442 {
443   gfc_formal_arglist *f, *head;
444   head = new_args;
445
446   for (f = proc->formal; f; f = f->next)
447     {
448       if (f->sym == NULL)
449         continue;
450
451       for (new_args = head; new_args; new_args = new_args->next)
452         {
453           if (new_args->sym == f->sym)
454             break;
455         }
456
457       if (new_args)
458         continue;
459
460       f->sym->attr.not_always_present = 1;
461     }
462 }
463
464
465 /* Resolve alternate entry points.  If a symbol has multiple entry points we
466    create a new master symbol for the main routine, and turn the existing
467    symbol into an entry point.  */
468
469 static void
470 resolve_entries (gfc_namespace *ns)
471 {
472   gfc_namespace *old_ns;
473   gfc_code *c;
474   gfc_symbol *proc;
475   gfc_entry_list *el;
476   char name[GFC_MAX_SYMBOL_LEN + 1];
477   static int master_count = 0;
478
479   if (ns->proc_name == NULL)
480     return;
481
482   /* No need to do anything if this procedure doesn't have alternate entry
483      points.  */
484   if (!ns->entries)
485     return;
486
487   /* We may already have resolved alternate entry points.  */
488   if (ns->proc_name->attr.entry_master)
489     return;
490
491   /* If this isn't a procedure something has gone horribly wrong.  */
492   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
493
494   /* Remember the current namespace.  */
495   old_ns = gfc_current_ns;
496
497   gfc_current_ns = ns;
498
499   /* Add the main entry point to the list of entry points.  */
500   el = gfc_get_entry_list ();
501   el->sym = ns->proc_name;
502   el->id = 0;
503   el->next = ns->entries;
504   ns->entries = el;
505   ns->proc_name->attr.entry = 1;
506
507   /* If it is a module function, it needs to be in the right namespace
508      so that gfc_get_fake_result_decl can gather up the results. The
509      need for this arose in get_proc_name, where these beasts were
510      left in their own namespace, to keep prior references linked to
511      the entry declaration.*/
512   if (ns->proc_name->attr.function
513       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
514     el->sym->ns = ns;
515
516   /* Do the same for entries where the master is not a module
517      procedure.  These are retained in the module namespace because
518      of the module procedure declaration.  */
519   for (el = el->next; el; el = el->next)
520     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
521           && el->sym->attr.mod_proc)
522       el->sym->ns = ns;
523   el = ns->entries;
524
525   /* Add an entry statement for it.  */
526   c = gfc_get_code ();
527   c->op = EXEC_ENTRY;
528   c->ext.entry = el;
529   c->next = ns->code;
530   ns->code = c;
531
532   /* Create a new symbol for the master function.  */
533   /* Give the internal function a unique name (within this file).
534      Also include the function name so the user has some hope of figuring
535      out what is going on.  */
536   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
537             master_count++, ns->proc_name->name);
538   gfc_get_ha_symbol (name, &proc);
539   gcc_assert (proc != NULL);
540
541   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
542   if (ns->proc_name->attr.subroutine)
543     gfc_add_subroutine (&proc->attr, proc->name, NULL);
544   else
545     {
546       gfc_symbol *sym;
547       gfc_typespec *ts, *fts;
548       gfc_array_spec *as, *fas;
549       gfc_add_function (&proc->attr, proc->name, NULL);
550       proc->result = proc;
551       fas = ns->entries->sym->as;
552       fas = fas ? fas : ns->entries->sym->result->as;
553       fts = &ns->entries->sym->result->ts;
554       if (fts->type == BT_UNKNOWN)
555         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
556       for (el = ns->entries->next; el; el = el->next)
557         {
558           ts = &el->sym->result->ts;
559           as = el->sym->as;
560           as = as ? as : el->sym->result->as;
561           if (ts->type == BT_UNKNOWN)
562             ts = gfc_get_default_type (el->sym->result->name, NULL);
563
564           if (! gfc_compare_types (ts, fts)
565               || (el->sym->result->attr.dimension
566                   != ns->entries->sym->result->attr.dimension)
567               || (el->sym->result->attr.pointer
568                   != ns->entries->sym->result->attr.pointer))
569             break;
570           else if (as && fas && ns->entries->sym->result != el->sym->result
571                       && gfc_compare_array_spec (as, fas) == 0)
572             gfc_error ("Function %s at %L has entries with mismatched "
573                        "array specifications", ns->entries->sym->name,
574                        &ns->entries->sym->declared_at);
575           /* The characteristics need to match and thus both need to have
576              the same string length, i.e. both len=*, or both len=4.
577              Having both len=<variable> is also possible, but difficult to
578              check at compile time.  */
579           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
580                    && (((ts->u.cl->length && !fts->u.cl->length)
581                         ||(!ts->u.cl->length && fts->u.cl->length))
582                        || (ts->u.cl->length
583                            && ts->u.cl->length->expr_type
584                               != fts->u.cl->length->expr_type)
585                        || (ts->u.cl->length
586                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
587                            && mpz_cmp (ts->u.cl->length->value.integer,
588                                        fts->u.cl->length->value.integer) != 0)))
589             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
590                             "entries returning variables of different "
591                             "string lengths", ns->entries->sym->name,
592                             &ns->entries->sym->declared_at);
593         }
594
595       if (el == NULL)
596         {
597           sym = ns->entries->sym->result;
598           /* All result types the same.  */
599           proc->ts = *fts;
600           if (sym->attr.dimension)
601             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
602           if (sym->attr.pointer)
603             gfc_add_pointer (&proc->attr, NULL);
604         }
605       else
606         {
607           /* Otherwise the result will be passed through a union by
608              reference.  */
609           proc->attr.mixed_entry_master = 1;
610           for (el = ns->entries; el; el = el->next)
611             {
612               sym = el->sym->result;
613               if (sym->attr.dimension)
614                 {
615                   if (el == ns->entries)
616                     gfc_error ("FUNCTION result %s can't be an array in "
617                                "FUNCTION %s at %L", sym->name,
618                                ns->entries->sym->name, &sym->declared_at);
619                   else
620                     gfc_error ("ENTRY result %s can't be an array in "
621                                "FUNCTION %s at %L", sym->name,
622                                ns->entries->sym->name, &sym->declared_at);
623                 }
624               else if (sym->attr.pointer)
625                 {
626                   if (el == ns->entries)
627                     gfc_error ("FUNCTION result %s can't be a POINTER in "
628                                "FUNCTION %s at %L", sym->name,
629                                ns->entries->sym->name, &sym->declared_at);
630                   else
631                     gfc_error ("ENTRY result %s can't be a POINTER in "
632                                "FUNCTION %s at %L", sym->name,
633                                ns->entries->sym->name, &sym->declared_at);
634                 }
635               else
636                 {
637                   ts = &sym->ts;
638                   if (ts->type == BT_UNKNOWN)
639                     ts = gfc_get_default_type (sym->name, NULL);
640                   switch (ts->type)
641                     {
642                     case BT_INTEGER:
643                       if (ts->kind == gfc_default_integer_kind)
644                         sym = NULL;
645                       break;
646                     case BT_REAL:
647                       if (ts->kind == gfc_default_real_kind
648                           || ts->kind == gfc_default_double_kind)
649                         sym = NULL;
650                       break;
651                     case BT_COMPLEX:
652                       if (ts->kind == gfc_default_complex_kind)
653                         sym = NULL;
654                       break;
655                     case BT_LOGICAL:
656                       if (ts->kind == gfc_default_logical_kind)
657                         sym = NULL;
658                       break;
659                     case BT_UNKNOWN:
660                       /* We will issue error elsewhere.  */
661                       sym = NULL;
662                       break;
663                     default:
664                       break;
665                     }
666                   if (sym)
667                     {
668                       if (el == ns->entries)
669                         gfc_error ("FUNCTION result %s can't be of type %s "
670                                    "in FUNCTION %s at %L", sym->name,
671                                    gfc_typename (ts), ns->entries->sym->name,
672                                    &sym->declared_at);
673                       else
674                         gfc_error ("ENTRY result %s can't be of type %s "
675                                    "in FUNCTION %s at %L", sym->name,
676                                    gfc_typename (ts), ns->entries->sym->name,
677                                    &sym->declared_at);
678                     }
679                 }
680             }
681         }
682     }
683   proc->attr.access = ACCESS_PRIVATE;
684   proc->attr.entry_master = 1;
685
686   /* Merge all the entry point arguments.  */
687   for (el = ns->entries; el; el = el->next)
688     merge_argument_lists (proc, el->sym->formal);
689
690   /* Check the master formal arguments for any that are not
691      present in all entry points.  */
692   for (el = ns->entries; el; el = el->next)
693     check_argument_lists (proc, el->sym->formal);
694
695   /* Use the master function for the function body.  */
696   ns->proc_name = proc;
697
698   /* Finalize the new symbols.  */
699   gfc_commit_symbols ();
700
701   /* Restore the original namespace.  */
702   gfc_current_ns = old_ns;
703 }
704
705
706 static bool
707 has_default_initializer (gfc_symbol *der)
708 {
709   gfc_component *c;
710
711   gcc_assert (der->attr.flavor == FL_DERIVED);
712   for (c = der->components; c; c = c->next)
713     if ((c->ts.type != BT_DERIVED && c->initializer)
714         || (c->ts.type == BT_DERIVED
715             && (!c->attr.pointer && has_default_initializer (c->ts.u.derived))))
716       break;
717
718   return c != NULL;
719 }
720
721 /* Resolve common variables.  */
722 static void
723 resolve_common_vars (gfc_symbol *sym, bool named_common)
724 {
725   gfc_symbol *csym = sym;
726
727   for (; csym; csym = csym->common_next)
728     {
729       if (csym->value || csym->attr.data)
730         {
731           if (!csym->ns->is_block_data)
732             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
733                             "but only in BLOCK DATA initialization is "
734                             "allowed", csym->name, &csym->declared_at);
735           else if (!named_common)
736             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
737                             "in a blank COMMON but initialization is only "
738                             "allowed in named common blocks", csym->name,
739                             &csym->declared_at);
740         }
741
742       if (csym->ts.type != BT_DERIVED)
743         continue;
744
745       if (!(csym->ts.u.derived->attr.sequence
746             || csym->ts.u.derived->attr.is_bind_c))
747         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
748                        "has neither the SEQUENCE nor the BIND(C) "
749                        "attribute", csym->name, &csym->declared_at);
750       if (csym->ts.u.derived->attr.alloc_comp)
751         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
752                        "has an ultimate component that is "
753                        "allocatable", csym->name, &csym->declared_at);
754       if (has_default_initializer (csym->ts.u.derived))
755         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
756                        "may not have default initializer", csym->name,
757                        &csym->declared_at);
758
759       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
760         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
761     }
762 }
763
764 /* Resolve common blocks.  */
765 static void
766 resolve_common_blocks (gfc_symtree *common_root)
767 {
768   gfc_symbol *sym;
769
770   if (common_root == NULL)
771     return;
772
773   if (common_root->left)
774     resolve_common_blocks (common_root->left);
775   if (common_root->right)
776     resolve_common_blocks (common_root->right);
777
778   resolve_common_vars (common_root->n.common->head, true);
779
780   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
781   if (sym == NULL)
782     return;
783
784   if (sym->attr.flavor == FL_PARAMETER)
785     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
786                sym->name, &common_root->n.common->where, &sym->declared_at);
787
788   if (sym->attr.intrinsic)
789     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
790                sym->name, &common_root->n.common->where);
791   else if (sym->attr.result
792            || gfc_is_function_return_value (sym, gfc_current_ns))
793     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
794                     "that is also a function result", sym->name,
795                     &common_root->n.common->where);
796   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
797            && sym->attr.proc != PROC_ST_FUNCTION)
798     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
799                     "that is also a global procedure", sym->name,
800                     &common_root->n.common->where);
801 }
802
803
804 /* Resolve contained function types.  Because contained functions can call one
805    another, they have to be worked out before any of the contained procedures
806    can be resolved.
807
808    The good news is that if a function doesn't already have a type, the only
809    way it can get one is through an IMPLICIT type or a RESULT variable, because
810    by definition contained functions are contained namespace they're contained
811    in, not in a sibling or parent namespace.  */
812
813 static void
814 resolve_contained_functions (gfc_namespace *ns)
815 {
816   gfc_namespace *child;
817   gfc_entry_list *el;
818
819   resolve_formal_arglists (ns);
820
821   for (child = ns->contained; child; child = child->sibling)
822     {
823       /* Resolve alternate entry points first.  */
824       resolve_entries (child);
825
826       /* Then check function return types.  */
827       resolve_contained_fntype (child->proc_name, child);
828       for (el = child->entries; el; el = el->next)
829         resolve_contained_fntype (el->sym, child);
830     }
831 }
832
833
834 /* Resolve all of the elements of a structure constructor and make sure that
835    the types are correct.  */
836
837 static gfc_try
838 resolve_structure_cons (gfc_expr *expr)
839 {
840   gfc_constructor *cons;
841   gfc_component *comp;
842   gfc_try t;
843   symbol_attribute a;
844
845   t = SUCCESS;
846   cons = gfc_constructor_first (expr->value.constructor);
847   /* A constructor may have references if it is the result of substituting a
848      parameter variable.  In this case we just pull out the component we
849      want.  */
850   if (expr->ref)
851     comp = expr->ref->u.c.sym->components;
852   else
853     comp = expr->ts.u.derived->components;
854
855   /* See if the user is trying to invoke a structure constructor for one of
856      the iso_c_binding derived types.  */
857   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
858       && expr->ts.u.derived->ts.is_iso_c && cons
859       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
860     {
861       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
862                  expr->ts.u.derived->name, &(expr->where));
863       return FAILURE;
864     }
865
866   /* Return if structure constructor is c_null_(fun)prt.  */
867   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
868       && expr->ts.u.derived->ts.is_iso_c && cons
869       && cons->expr && cons->expr->expr_type == EXPR_NULL)
870     return SUCCESS;
871
872   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
873     {
874       int rank;
875
876       if (!cons->expr)
877         continue;
878
879       if (gfc_resolve_expr (cons->expr) == FAILURE)
880         {
881           t = FAILURE;
882           continue;
883         }
884
885       rank = comp->as ? comp->as->rank : 0;
886       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
887           && (comp->attr.allocatable || cons->expr->rank))
888         {
889           gfc_error ("The rank of the element in the derived type "
890                      "constructor at %L does not match that of the "
891                      "component (%d/%d)", &cons->expr->where,
892                      cons->expr->rank, rank);
893           t = FAILURE;
894         }
895
896       /* If we don't have the right type, try to convert it.  */
897
898       if (!gfc_compare_types (&cons->expr->ts, &comp->ts))
899         {
900           t = FAILURE;
901           if (strcmp (comp->name, "$extends") == 0)
902             {
903               /* Can afford to be brutal with the $extends initializer.
904                  The derived type can get lost because it is PRIVATE
905                  but it is not usage constrained by the standard.  */
906               cons->expr->ts = comp->ts;
907               t = SUCCESS;
908             }
909           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
910             gfc_error ("The element in the derived type constructor at %L, "
911                        "for pointer component '%s', is %s but should be %s",
912                        &cons->expr->where, comp->name,
913                        gfc_basic_typename (cons->expr->ts.type),
914                        gfc_basic_typename (comp->ts.type));
915           else
916             t = gfc_convert_type (cons->expr, &comp->ts, 1);
917         }
918
919       if (cons->expr->expr_type == EXPR_NULL
920           && !(comp->attr.pointer || comp->attr.allocatable
921                || comp->attr.proc_pointer
922                || (comp->ts.type == BT_CLASS
923                    && (comp->ts.u.derived->components->attr.pointer
924                        || comp->ts.u.derived->components->attr.allocatable))))
925         {
926           t = FAILURE;
927           gfc_error ("The NULL in the derived type constructor at %L is "
928                      "being applied to component '%s', which is neither "
929                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
930                      comp->name);
931         }
932
933       if (!comp->attr.pointer || cons->expr->expr_type == EXPR_NULL)
934         continue;
935
936       a = gfc_expr_attr (cons->expr);
937
938       if (!a.pointer && !a.target)
939         {
940           t = FAILURE;
941           gfc_error ("The element in the derived type constructor at %L, "
942                      "for pointer component '%s' should be a POINTER or "
943                      "a TARGET", &cons->expr->where, comp->name);
944         }
945
946       /* F2003, C1272 (3).  */
947       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
948           && (gfc_impure_variable (cons->expr->symtree->n.sym)
949               || gfc_is_coindexed (cons->expr)))
950         {
951           t = FAILURE;
952           gfc_error ("Invalid expression in the derived type constructor for "
953                      "pointer component '%s' at %L in PURE procedure",
954                      comp->name, &cons->expr->where);
955         }
956     }
957
958   return t;
959 }
960
961
962 /****************** Expression name resolution ******************/
963
964 /* Returns 0 if a symbol was not declared with a type or
965    attribute declaration statement, nonzero otherwise.  */
966
967 static int
968 was_declared (gfc_symbol *sym)
969 {
970   symbol_attribute a;
971
972   a = sym->attr;
973
974   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
975     return 1;
976
977   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
978       || a.optional || a.pointer || a.save || a.target || a.volatile_
979       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
980       || a.asynchronous || a.codimension)
981     return 1;
982
983   return 0;
984 }
985
986
987 /* Determine if a symbol is generic or not.  */
988
989 static int
990 generic_sym (gfc_symbol *sym)
991 {
992   gfc_symbol *s;
993
994   if (sym->attr.generic ||
995       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
996     return 1;
997
998   if (was_declared (sym) || sym->ns->parent == NULL)
999     return 0;
1000
1001   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1002   
1003   if (s != NULL)
1004     {
1005       if (s == sym)
1006         return 0;
1007       else
1008         return generic_sym (s);
1009     }
1010
1011   return 0;
1012 }
1013
1014
1015 /* Determine if a symbol is specific or not.  */
1016
1017 static int
1018 specific_sym (gfc_symbol *sym)
1019 {
1020   gfc_symbol *s;
1021
1022   if (sym->attr.if_source == IFSRC_IFBODY
1023       || sym->attr.proc == PROC_MODULE
1024       || sym->attr.proc == PROC_INTERNAL
1025       || sym->attr.proc == PROC_ST_FUNCTION
1026       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1027       || sym->attr.external)
1028     return 1;
1029
1030   if (was_declared (sym) || sym->ns->parent == NULL)
1031     return 0;
1032
1033   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1034
1035   return (s == NULL) ? 0 : specific_sym (s);
1036 }
1037
1038
1039 /* Figure out if the procedure is specific, generic or unknown.  */
1040
1041 typedef enum
1042 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1043 proc_type;
1044
1045 static proc_type
1046 procedure_kind (gfc_symbol *sym)
1047 {
1048   if (generic_sym (sym))
1049     return PTYPE_GENERIC;
1050
1051   if (specific_sym (sym))
1052     return PTYPE_SPECIFIC;
1053
1054   return PTYPE_UNKNOWN;
1055 }
1056
1057 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1058    is nonzero when matching actual arguments.  */
1059
1060 static int need_full_assumed_size = 0;
1061
1062 static bool
1063 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1064 {
1065   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1066       return false;
1067
1068   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1069      What should it be?  */
1070   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1071           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1072                && (e->ref->u.ar.type == AR_FULL))
1073     {
1074       gfc_error ("The upper bound in the last dimension must "
1075                  "appear in the reference to the assumed size "
1076                  "array '%s' at %L", sym->name, &e->where);
1077       return true;
1078     }
1079   return false;
1080 }
1081
1082
1083 /* Look for bad assumed size array references in argument expressions
1084   of elemental and array valued intrinsic procedures.  Since this is
1085   called from procedure resolution functions, it only recurses at
1086   operators.  */
1087
1088 static bool
1089 resolve_assumed_size_actual (gfc_expr *e)
1090 {
1091   if (e == NULL)
1092    return false;
1093
1094   switch (e->expr_type)
1095     {
1096     case EXPR_VARIABLE:
1097       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1098         return true;
1099       break;
1100
1101     case EXPR_OP:
1102       if (resolve_assumed_size_actual (e->value.op.op1)
1103           || resolve_assumed_size_actual (e->value.op.op2))
1104         return true;
1105       break;
1106
1107     default:
1108       break;
1109     }
1110   return false;
1111 }
1112
1113
1114 /* Check a generic procedure, passed as an actual argument, to see if
1115    there is a matching specific name.  If none, it is an error, and if
1116    more than one, the reference is ambiguous.  */
1117 static int
1118 count_specific_procs (gfc_expr *e)
1119 {
1120   int n;
1121   gfc_interface *p;
1122   gfc_symbol *sym;
1123         
1124   n = 0;
1125   sym = e->symtree->n.sym;
1126
1127   for (p = sym->generic; p; p = p->next)
1128     if (strcmp (sym->name, p->sym->name) == 0)
1129       {
1130         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1131                                        sym->name);
1132         n++;
1133       }
1134
1135   if (n > 1)
1136     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1137                &e->where);
1138
1139   if (n == 0)
1140     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1141                "argument at %L", sym->name, &e->where);
1142
1143   return n;
1144 }
1145
1146
1147 /* See if a call to sym could possibly be a not allowed RECURSION because of
1148    a missing RECURIVE declaration.  This means that either sym is the current
1149    context itself, or sym is the parent of a contained procedure calling its
1150    non-RECURSIVE containing procedure.
1151    This also works if sym is an ENTRY.  */
1152
1153 static bool
1154 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1155 {
1156   gfc_symbol* proc_sym;
1157   gfc_symbol* context_proc;
1158   gfc_namespace* real_context;
1159
1160   if (sym->attr.flavor == FL_PROGRAM)
1161     return false;
1162
1163   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1164
1165   /* If we've got an ENTRY, find real procedure.  */
1166   if (sym->attr.entry && sym->ns->entries)
1167     proc_sym = sym->ns->entries->sym;
1168   else
1169     proc_sym = sym;
1170
1171   /* If sym is RECURSIVE, all is well of course.  */
1172   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1173     return false;
1174
1175   /* Find the context procedure's "real" symbol if it has entries.
1176      We look for a procedure symbol, so recurse on the parents if we don't
1177      find one (like in case of a BLOCK construct).  */
1178   for (real_context = context; ; real_context = real_context->parent)
1179     {
1180       /* We should find something, eventually!  */
1181       gcc_assert (real_context);
1182
1183       context_proc = (real_context->entries ? real_context->entries->sym
1184                                             : real_context->proc_name);
1185
1186       /* In some special cases, there may not be a proc_name, like for this
1187          invalid code:
1188          real(bad_kind()) function foo () ...
1189          when checking the call to bad_kind ().
1190          In these cases, we simply return here and assume that the
1191          call is ok.  */
1192       if (!context_proc)
1193         return false;
1194
1195       if (context_proc->attr.flavor != FL_LABEL)
1196         break;
1197     }
1198
1199   /* A call from sym's body to itself is recursion, of course.  */
1200   if (context_proc == proc_sym)
1201     return true;
1202
1203   /* The same is true if context is a contained procedure and sym the
1204      containing one.  */
1205   if (context_proc->attr.contained)
1206     {
1207       gfc_symbol* parent_proc;
1208
1209       gcc_assert (context->parent);
1210       parent_proc = (context->parent->entries ? context->parent->entries->sym
1211                                               : context->parent->proc_name);
1212
1213       if (parent_proc == proc_sym)
1214         return true;
1215     }
1216
1217   return false;
1218 }
1219
1220
1221 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1222    its typespec and formal argument list.  */
1223
1224 static gfc_try
1225 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1226 {
1227   gfc_intrinsic_sym* isym;
1228   const char* symstd;
1229
1230   if (sym->formal)
1231     return SUCCESS;
1232
1233   /* We already know this one is an intrinsic, so we don't call
1234      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1235      gfc_find_subroutine directly to check whether it is a function or
1236      subroutine.  */
1237
1238   if ((isym = gfc_find_function (sym->name)))
1239     {
1240       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1241           && !sym->attr.implicit_type)
1242         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1243                       " ignored", sym->name, &sym->declared_at);
1244
1245       if (!sym->attr.function &&
1246           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1247         return FAILURE;
1248
1249       sym->ts = isym->ts;
1250     }
1251   else if ((isym = gfc_find_subroutine (sym->name)))
1252     {
1253       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1254         {
1255           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1256                       " specifier", sym->name, &sym->declared_at);
1257           return FAILURE;
1258         }
1259
1260       if (!sym->attr.subroutine &&
1261           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1262         return FAILURE;
1263     }
1264   else
1265     {
1266       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1267                  &sym->declared_at);
1268       return FAILURE;
1269     }
1270
1271   gfc_copy_formal_args_intr (sym, isym);
1272
1273   /* Check it is actually available in the standard settings.  */
1274   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1275       == FAILURE)
1276     {
1277       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1278                  " available in the current standard settings but %s.  Use"
1279                  " an appropriate -std=* option or enable -fall-intrinsics"
1280                  " in order to use it.",
1281                  sym->name, &sym->declared_at, symstd);
1282       return FAILURE;
1283     }
1284
1285   return SUCCESS;
1286 }
1287
1288
1289 /* Resolve a procedure expression, like passing it to a called procedure or as
1290    RHS for a procedure pointer assignment.  */
1291
1292 static gfc_try
1293 resolve_procedure_expression (gfc_expr* expr)
1294 {
1295   gfc_symbol* sym;
1296
1297   if (expr->expr_type != EXPR_VARIABLE)
1298     return SUCCESS;
1299   gcc_assert (expr->symtree);
1300
1301   sym = expr->symtree->n.sym;
1302
1303   if (sym->attr.intrinsic)
1304     resolve_intrinsic (sym, &expr->where);
1305
1306   if (sym->attr.flavor != FL_PROCEDURE
1307       || (sym->attr.function && sym->result == sym))
1308     return SUCCESS;
1309
1310   /* A non-RECURSIVE procedure that is used as procedure expression within its
1311      own body is in danger of being called recursively.  */
1312   if (is_illegal_recursion (sym, gfc_current_ns))
1313     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1314                  " itself recursively.  Declare it RECURSIVE or use"
1315                  " -frecursive", sym->name, &expr->where);
1316   
1317   return SUCCESS;
1318 }
1319
1320
1321 /* Resolve an actual argument list.  Most of the time, this is just
1322    resolving the expressions in the list.
1323    The exception is that we sometimes have to decide whether arguments
1324    that look like procedure arguments are really simple variable
1325    references.  */
1326
1327 static gfc_try
1328 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1329                         bool no_formal_args)
1330 {
1331   gfc_symbol *sym;
1332   gfc_symtree *parent_st;
1333   gfc_expr *e;
1334   int save_need_full_assumed_size;
1335   gfc_component *comp;
1336
1337   for (; arg; arg = arg->next)
1338     {
1339       e = arg->expr;
1340       if (e == NULL)
1341         {
1342           /* Check the label is a valid branching target.  */
1343           if (arg->label)
1344             {
1345               if (arg->label->defined == ST_LABEL_UNKNOWN)
1346                 {
1347                   gfc_error ("Label %d referenced at %L is never defined",
1348                              arg->label->value, &arg->label->where);
1349                   return FAILURE;
1350                 }
1351             }
1352           continue;
1353         }
1354
1355       if (gfc_is_proc_ptr_comp (e, &comp))
1356         {
1357           e->ts = comp->ts;
1358           if (e->expr_type == EXPR_PPC)
1359             {
1360               if (comp->as != NULL)
1361                 e->rank = comp->as->rank;
1362               e->expr_type = EXPR_FUNCTION;
1363             }
1364           if (gfc_resolve_expr (e) == FAILURE)                          
1365             return FAILURE; 
1366           goto argument_list;
1367         }
1368
1369       if (e->expr_type == EXPR_VARIABLE
1370             && e->symtree->n.sym->attr.generic
1371             && no_formal_args
1372             && count_specific_procs (e) != 1)
1373         return FAILURE;
1374
1375       if (e->ts.type != BT_PROCEDURE)
1376         {
1377           save_need_full_assumed_size = need_full_assumed_size;
1378           if (e->expr_type != EXPR_VARIABLE)
1379             need_full_assumed_size = 0;
1380           if (gfc_resolve_expr (e) != SUCCESS)
1381             return FAILURE;
1382           need_full_assumed_size = save_need_full_assumed_size;
1383           goto argument_list;
1384         }
1385
1386       /* See if the expression node should really be a variable reference.  */
1387
1388       sym = e->symtree->n.sym;
1389
1390       if (sym->attr.flavor == FL_PROCEDURE
1391           || sym->attr.intrinsic
1392           || sym->attr.external)
1393         {
1394           int actual_ok;
1395
1396           /* If a procedure is not already determined to be something else
1397              check if it is intrinsic.  */
1398           if (!sym->attr.intrinsic
1399               && !(sym->attr.external || sym->attr.use_assoc
1400                    || sym->attr.if_source == IFSRC_IFBODY)
1401               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1402             sym->attr.intrinsic = 1;
1403
1404           if (sym->attr.proc == PROC_ST_FUNCTION)
1405             {
1406               gfc_error ("Statement function '%s' at %L is not allowed as an "
1407                          "actual argument", sym->name, &e->where);
1408             }
1409
1410           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1411                                                sym->attr.subroutine);
1412           if (sym->attr.intrinsic && actual_ok == 0)
1413             {
1414               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1415                          "actual argument", sym->name, &e->where);
1416             }
1417
1418           if (sym->attr.contained && !sym->attr.use_assoc
1419               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1420             {
1421               gfc_error ("Internal procedure '%s' is not allowed as an "
1422                          "actual argument at %L", sym->name, &e->where);
1423             }
1424
1425           if (sym->attr.elemental && !sym->attr.intrinsic)
1426             {
1427               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1428                          "allowed as an actual argument at %L", sym->name,
1429                          &e->where);
1430             }
1431
1432           /* Check if a generic interface has a specific procedure
1433             with the same name before emitting an error.  */
1434           if (sym->attr.generic && count_specific_procs (e) != 1)
1435             return FAILURE;
1436           
1437           /* Just in case a specific was found for the expression.  */
1438           sym = e->symtree->n.sym;
1439
1440           /* If the symbol is the function that names the current (or
1441              parent) scope, then we really have a variable reference.  */
1442
1443           if (gfc_is_function_return_value (sym, sym->ns))
1444             goto got_variable;
1445
1446           /* If all else fails, see if we have a specific intrinsic.  */
1447           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1448             {
1449               gfc_intrinsic_sym *isym;
1450
1451               isym = gfc_find_function (sym->name);
1452               if (isym == NULL || !isym->specific)
1453                 {
1454                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1455                              "for the reference '%s' at %L", sym->name,
1456                              &e->where);
1457                   return FAILURE;
1458                 }
1459               sym->ts = isym->ts;
1460               sym->attr.intrinsic = 1;
1461               sym->attr.function = 1;
1462             }
1463
1464           if (gfc_resolve_expr (e) == FAILURE)
1465             return FAILURE;
1466           goto argument_list;
1467         }
1468
1469       /* See if the name is a module procedure in a parent unit.  */
1470
1471       if (was_declared (sym) || sym->ns->parent == NULL)
1472         goto got_variable;
1473
1474       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1475         {
1476           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1477           return FAILURE;
1478         }
1479
1480       if (parent_st == NULL)
1481         goto got_variable;
1482
1483       sym = parent_st->n.sym;
1484       e->symtree = parent_st;           /* Point to the right thing.  */
1485
1486       if (sym->attr.flavor == FL_PROCEDURE
1487           || sym->attr.intrinsic
1488           || sym->attr.external)
1489         {
1490           if (gfc_resolve_expr (e) == FAILURE)
1491             return FAILURE;
1492           goto argument_list;
1493         }
1494
1495     got_variable:
1496       e->expr_type = EXPR_VARIABLE;
1497       e->ts = sym->ts;
1498       if (sym->as != NULL)
1499         {
1500           e->rank = sym->as->rank;
1501           e->ref = gfc_get_ref ();
1502           e->ref->type = REF_ARRAY;
1503           e->ref->u.ar.type = AR_FULL;
1504           e->ref->u.ar.as = sym->as;
1505         }
1506
1507       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1508          primary.c (match_actual_arg). If above code determines that it
1509          is a  variable instead, it needs to be resolved as it was not
1510          done at the beginning of this function.  */
1511       save_need_full_assumed_size = need_full_assumed_size;
1512       if (e->expr_type != EXPR_VARIABLE)
1513         need_full_assumed_size = 0;
1514       if (gfc_resolve_expr (e) != SUCCESS)
1515         return FAILURE;
1516       need_full_assumed_size = save_need_full_assumed_size;
1517
1518     argument_list:
1519       /* Check argument list functions %VAL, %LOC and %REF.  There is
1520          nothing to do for %REF.  */
1521       if (arg->name && arg->name[0] == '%')
1522         {
1523           if (strncmp ("%VAL", arg->name, 4) == 0)
1524             {
1525               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1526                 {
1527                   gfc_error ("By-value argument at %L is not of numeric "
1528                              "type", &e->where);
1529                   return FAILURE;
1530                 }
1531
1532               if (e->rank)
1533                 {
1534                   gfc_error ("By-value argument at %L cannot be an array or "
1535                              "an array section", &e->where);
1536                 return FAILURE;
1537                 }
1538
1539               /* Intrinsics are still PROC_UNKNOWN here.  However,
1540                  since same file external procedures are not resolvable
1541                  in gfortran, it is a good deal easier to leave them to
1542                  intrinsic.c.  */
1543               if (ptype != PROC_UNKNOWN
1544                   && ptype != PROC_DUMMY
1545                   && ptype != PROC_EXTERNAL
1546                   && ptype != PROC_MODULE)
1547                 {
1548                   gfc_error ("By-value argument at %L is not allowed "
1549                              "in this context", &e->where);
1550                   return FAILURE;
1551                 }
1552             }
1553
1554           /* Statement functions have already been excluded above.  */
1555           else if (strncmp ("%LOC", arg->name, 4) == 0
1556                    && e->ts.type == BT_PROCEDURE)
1557             {
1558               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1559                 {
1560                   gfc_error ("Passing internal procedure at %L by location "
1561                              "not allowed", &e->where);
1562                   return FAILURE;
1563                 }
1564             }
1565         }
1566
1567       /* Fortran 2008, C1237.  */
1568       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1569           && gfc_has_ultimate_pointer (e))
1570         {
1571           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1572                      "component", &e->where);
1573           return FAILURE;
1574         }
1575     }
1576
1577   return SUCCESS;
1578 }
1579
1580
1581 /* Do the checks of the actual argument list that are specific to elemental
1582    procedures.  If called with c == NULL, we have a function, otherwise if
1583    expr == NULL, we have a subroutine.  */
1584
1585 static gfc_try
1586 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1587 {
1588   gfc_actual_arglist *arg0;
1589   gfc_actual_arglist *arg;
1590   gfc_symbol *esym = NULL;
1591   gfc_intrinsic_sym *isym = NULL;
1592   gfc_expr *e = NULL;
1593   gfc_intrinsic_arg *iformal = NULL;
1594   gfc_formal_arglist *eformal = NULL;
1595   bool formal_optional = false;
1596   bool set_by_optional = false;
1597   int i;
1598   int rank = 0;
1599
1600   /* Is this an elemental procedure?  */
1601   if (expr && expr->value.function.actual != NULL)
1602     {
1603       if (expr->value.function.esym != NULL
1604           && expr->value.function.esym->attr.elemental)
1605         {
1606           arg0 = expr->value.function.actual;
1607           esym = expr->value.function.esym;
1608         }
1609       else if (expr->value.function.isym != NULL
1610                && expr->value.function.isym->elemental)
1611         {
1612           arg0 = expr->value.function.actual;
1613           isym = expr->value.function.isym;
1614         }
1615       else
1616         return SUCCESS;
1617     }
1618   else if (c && c->ext.actual != NULL)
1619     {
1620       arg0 = c->ext.actual;
1621       
1622       if (c->resolved_sym)
1623         esym = c->resolved_sym;
1624       else
1625         esym = c->symtree->n.sym;
1626       gcc_assert (esym);
1627
1628       if (!esym->attr.elemental)
1629         return SUCCESS;
1630     }
1631   else
1632     return SUCCESS;
1633
1634   /* The rank of an elemental is the rank of its array argument(s).  */
1635   for (arg = arg0; arg; arg = arg->next)
1636     {
1637       if (arg->expr != NULL && arg->expr->rank > 0)
1638         {
1639           rank = arg->expr->rank;
1640           if (arg->expr->expr_type == EXPR_VARIABLE
1641               && arg->expr->symtree->n.sym->attr.optional)
1642             set_by_optional = true;
1643
1644           /* Function specific; set the result rank and shape.  */
1645           if (expr)
1646             {
1647               expr->rank = rank;
1648               if (!expr->shape && arg->expr->shape)
1649                 {
1650                   expr->shape = gfc_get_shape (rank);
1651                   for (i = 0; i < rank; i++)
1652                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1653                 }
1654             }
1655           break;
1656         }
1657     }
1658
1659   /* If it is an array, it shall not be supplied as an actual argument
1660      to an elemental procedure unless an array of the same rank is supplied
1661      as an actual argument corresponding to a nonoptional dummy argument of
1662      that elemental procedure(12.4.1.5).  */
1663   formal_optional = false;
1664   if (isym)
1665     iformal = isym->formal;
1666   else
1667     eformal = esym->formal;
1668
1669   for (arg = arg0; arg; arg = arg->next)
1670     {
1671       if (eformal)
1672         {
1673           if (eformal->sym && eformal->sym->attr.optional)
1674             formal_optional = true;
1675           eformal = eformal->next;
1676         }
1677       else if (isym && iformal)
1678         {
1679           if (iformal->optional)
1680             formal_optional = true;
1681           iformal = iformal->next;
1682         }
1683       else if (isym)
1684         formal_optional = true;
1685
1686       if (pedantic && arg->expr != NULL
1687           && arg->expr->expr_type == EXPR_VARIABLE
1688           && arg->expr->symtree->n.sym->attr.optional
1689           && formal_optional
1690           && arg->expr->rank
1691           && (set_by_optional || arg->expr->rank != rank)
1692           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1693         {
1694           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1695                        "MISSING, it cannot be the actual argument of an "
1696                        "ELEMENTAL procedure unless there is a non-optional "
1697                        "argument with the same rank (12.4.1.5)",
1698                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1699           return FAILURE;
1700         }
1701     }
1702
1703   for (arg = arg0; arg; arg = arg->next)
1704     {
1705       if (arg->expr == NULL || arg->expr->rank == 0)
1706         continue;
1707
1708       /* Being elemental, the last upper bound of an assumed size array
1709          argument must be present.  */
1710       if (resolve_assumed_size_actual (arg->expr))
1711         return FAILURE;
1712
1713       /* Elemental procedure's array actual arguments must conform.  */
1714       if (e != NULL)
1715         {
1716           if (gfc_check_conformance (arg->expr, e,
1717                                      "elemental procedure") == FAILURE)
1718             return FAILURE;
1719         }
1720       else
1721         e = arg->expr;
1722     }
1723
1724   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1725      is an array, the intent inout/out variable needs to be also an array.  */
1726   if (rank > 0 && esym && expr == NULL)
1727     for (eformal = esym->formal, arg = arg0; arg && eformal;
1728          arg = arg->next, eformal = eformal->next)
1729       if ((eformal->sym->attr.intent == INTENT_OUT
1730            || eformal->sym->attr.intent == INTENT_INOUT)
1731           && arg->expr && arg->expr->rank == 0)
1732         {
1733           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1734                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1735                      "actual argument is an array", &arg->expr->where,
1736                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1737                      : "INOUT", eformal->sym->name, esym->name);
1738           return FAILURE;
1739         }
1740   return SUCCESS;
1741 }
1742
1743
1744 /* Go through each actual argument in ACTUAL and see if it can be
1745    implemented as an inlined, non-copying intrinsic.  FNSYM is the
1746    function being called, or NULL if not known.  */
1747
1748 static void
1749 find_noncopying_intrinsics (gfc_symbol *fnsym, gfc_actual_arglist *actual)
1750 {
1751   gfc_actual_arglist *ap;
1752   gfc_expr *expr;
1753
1754   for (ap = actual; ap; ap = ap->next)
1755     if (ap->expr
1756         && (expr = gfc_get_noncopying_intrinsic_argument (ap->expr))
1757         && !gfc_check_fncall_dependency (expr, INTENT_IN, fnsym, actual,
1758                                          NOT_ELEMENTAL))
1759       ap->expr->inline_noncopying_intrinsic = 1;
1760 }
1761
1762
1763 /* This function does the checking of references to global procedures
1764    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1765    77 and 95 standards.  It checks for a gsymbol for the name, making
1766    one if it does not already exist.  If it already exists, then the
1767    reference being resolved must correspond to the type of gsymbol.
1768    Otherwise, the new symbol is equipped with the attributes of the
1769    reference.  The corresponding code that is called in creating
1770    global entities is parse.c.
1771
1772    In addition, for all but -std=legacy, the gsymbols are used to
1773    check the interfaces of external procedures from the same file.
1774    The namespace of the gsymbol is resolved and then, once this is
1775    done the interface is checked.  */
1776
1777
1778 static bool
1779 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1780 {
1781   if (!gsym_ns->proc_name->attr.recursive)
1782     return true;
1783
1784   if (sym->ns == gsym_ns)
1785     return false;
1786
1787   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1788     return false;
1789
1790   return true;
1791 }
1792
1793 static bool
1794 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1795 {
1796   if (gsym_ns->entries)
1797     {
1798       gfc_entry_list *entry = gsym_ns->entries;
1799
1800       for (; entry; entry = entry->next)
1801         {
1802           if (strcmp (sym->name, entry->sym->name) == 0)
1803             {
1804               if (strcmp (gsym_ns->proc_name->name,
1805                           sym->ns->proc_name->name) == 0)
1806                 return false;
1807
1808               if (sym->ns->parent
1809                   && strcmp (gsym_ns->proc_name->name,
1810                              sym->ns->parent->proc_name->name) == 0)
1811                 return false;
1812             }
1813         }
1814     }
1815   return true;
1816 }
1817
1818 static void
1819 resolve_global_procedure (gfc_symbol *sym, locus *where,
1820                           gfc_actual_arglist **actual, int sub)
1821 {
1822   gfc_gsymbol * gsym;
1823   gfc_namespace *ns;
1824   enum gfc_symbol_type type;
1825
1826   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
1827
1828   gsym = gfc_get_gsymbol (sym->name);
1829
1830   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
1831     gfc_global_used (gsym, where);
1832
1833   if (gfc_option.flag_whole_file
1834         && sym->attr.if_source == IFSRC_UNKNOWN
1835         && gsym->type != GSYM_UNKNOWN
1836         && gsym->ns
1837         && gsym->ns->resolved != -1
1838         && gsym->ns->proc_name
1839         && not_in_recursive (sym, gsym->ns)
1840         && not_entry_self_reference (sym, gsym->ns))
1841     {
1842       /* Make sure that translation for the gsymbol occurs before
1843          the procedure currently being resolved.  */
1844       ns = gsym->ns->resolved ? NULL : gfc_global_ns_list;
1845       for (; ns && ns != gsym->ns; ns = ns->sibling)
1846         {
1847           if (ns->sibling == gsym->ns)
1848             {
1849               ns->sibling = gsym->ns->sibling;
1850               gsym->ns->sibling = gfc_global_ns_list;
1851               gfc_global_ns_list = gsym->ns;
1852               break;
1853             }
1854         }
1855
1856       if (!gsym->ns->resolved)
1857         {
1858           gfc_dt_list *old_dt_list;
1859
1860           /* Stash away derived types so that the backend_decls do not
1861              get mixed up.  */
1862           old_dt_list = gfc_derived_types;
1863           gfc_derived_types = NULL;
1864
1865           gfc_resolve (gsym->ns);
1866
1867           /* Store the new derived types with the global namespace.  */
1868           if (gfc_derived_types)
1869             gsym->ns->derived_types = gfc_derived_types;
1870
1871           /* Restore the derived types of this namespace.  */
1872           gfc_derived_types = old_dt_list;
1873         }
1874
1875       if (gsym->ns->proc_name->attr.function
1876             && gsym->ns->proc_name->as
1877             && gsym->ns->proc_name->as->rank
1878             && (!sym->as || sym->as->rank != gsym->ns->proc_name->as->rank))
1879         gfc_error ("The reference to function '%s' at %L either needs an "
1880                    "explicit INTERFACE or the rank is incorrect", sym->name,
1881                    where);
1882      
1883       /* Non-assumed length character functions.  */
1884       if (sym->attr.function && sym->ts.type == BT_CHARACTER
1885           && gsym->ns->proc_name->ts.u.cl->length != NULL)
1886         {
1887           gfc_charlen *cl = sym->ts.u.cl;
1888
1889           if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
1890               && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
1891             {
1892               gfc_error ("Nonconstant character-length function '%s' at %L "
1893                          "must have an explicit interface", sym->name,
1894                          &sym->declared_at);
1895             }
1896         }
1897
1898       if (gfc_option.flag_whole_file == 1
1899             || ((gfc_option.warn_std & GFC_STD_LEGACY)
1900                   &&
1901                !(gfc_option.warn_std & GFC_STD_GNU)))
1902         gfc_errors_to_warnings (1);
1903
1904       gfc_procedure_use (gsym->ns->proc_name, actual, where);
1905
1906       gfc_errors_to_warnings (0);
1907     }
1908
1909   if (gsym->type == GSYM_UNKNOWN)
1910     {
1911       gsym->type = type;
1912       gsym->where = *where;
1913     }
1914
1915   gsym->used = 1;
1916 }
1917
1918
1919 /************* Function resolution *************/
1920
1921 /* Resolve a function call known to be generic.
1922    Section 14.1.2.4.1.  */
1923
1924 static match
1925 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
1926 {
1927   gfc_symbol *s;
1928
1929   if (sym->attr.generic)
1930     {
1931       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
1932       if (s != NULL)
1933         {
1934           expr->value.function.name = s->name;
1935           expr->value.function.esym = s;
1936
1937           if (s->ts.type != BT_UNKNOWN)
1938             expr->ts = s->ts;
1939           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
1940             expr->ts = s->result->ts;
1941
1942           if (s->as != NULL)
1943             expr->rank = s->as->rank;
1944           else if (s->result != NULL && s->result->as != NULL)
1945             expr->rank = s->result->as->rank;
1946
1947           gfc_set_sym_referenced (expr->value.function.esym);
1948
1949           return MATCH_YES;
1950         }
1951
1952       /* TODO: Need to search for elemental references in generic
1953          interface.  */
1954     }
1955
1956   if (sym->attr.intrinsic)
1957     return gfc_intrinsic_func_interface (expr, 0);
1958
1959   return MATCH_NO;
1960 }
1961
1962
1963 static gfc_try
1964 resolve_generic_f (gfc_expr *expr)
1965 {
1966   gfc_symbol *sym;
1967   match m;
1968
1969   sym = expr->symtree->n.sym;
1970
1971   for (;;)
1972     {
1973       m = resolve_generic_f0 (expr, sym);
1974       if (m == MATCH_YES)
1975         return SUCCESS;
1976       else if (m == MATCH_ERROR)
1977         return FAILURE;
1978
1979 generic:
1980       if (sym->ns->parent == NULL)
1981         break;
1982       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
1983
1984       if (sym == NULL)
1985         break;
1986       if (!generic_sym (sym))
1987         goto generic;
1988     }
1989
1990   /* Last ditch attempt.  See if the reference is to an intrinsic
1991      that possesses a matching interface.  14.1.2.4  */
1992   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
1993     {
1994       gfc_error ("There is no specific function for the generic '%s' at %L",
1995                  expr->symtree->n.sym->name, &expr->where);
1996       return FAILURE;
1997     }
1998
1999   m = gfc_intrinsic_func_interface (expr, 0);
2000   if (m == MATCH_YES)
2001     return SUCCESS;
2002   if (m == MATCH_NO)
2003     gfc_error ("Generic function '%s' at %L is not consistent with a "
2004                "specific intrinsic interface", expr->symtree->n.sym->name,
2005                &expr->where);
2006
2007   return FAILURE;
2008 }
2009
2010
2011 /* Resolve a function call known to be specific.  */
2012
2013 static match
2014 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2015 {
2016   match m;
2017
2018   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2019     {
2020       if (sym->attr.dummy)
2021         {
2022           sym->attr.proc = PROC_DUMMY;
2023           goto found;
2024         }
2025
2026       sym->attr.proc = PROC_EXTERNAL;
2027       goto found;
2028     }
2029
2030   if (sym->attr.proc == PROC_MODULE
2031       || sym->attr.proc == PROC_ST_FUNCTION
2032       || sym->attr.proc == PROC_INTERNAL)
2033     goto found;
2034
2035   if (sym->attr.intrinsic)
2036     {
2037       m = gfc_intrinsic_func_interface (expr, 1);
2038       if (m == MATCH_YES)
2039         return MATCH_YES;
2040       if (m == MATCH_NO)
2041         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2042                    "with an intrinsic", sym->name, &expr->where);
2043
2044       return MATCH_ERROR;
2045     }
2046
2047   return MATCH_NO;
2048
2049 found:
2050   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2051
2052   if (sym->result)
2053     expr->ts = sym->result->ts;
2054   else
2055     expr->ts = sym->ts;
2056   expr->value.function.name = sym->name;
2057   expr->value.function.esym = sym;
2058   if (sym->as != NULL)
2059     expr->rank = sym->as->rank;
2060
2061   return MATCH_YES;
2062 }
2063
2064
2065 static gfc_try
2066 resolve_specific_f (gfc_expr *expr)
2067 {
2068   gfc_symbol *sym;
2069   match m;
2070
2071   sym = expr->symtree->n.sym;
2072
2073   for (;;)
2074     {
2075       m = resolve_specific_f0 (sym, expr);
2076       if (m == MATCH_YES)
2077         return SUCCESS;
2078       if (m == MATCH_ERROR)
2079         return FAILURE;
2080
2081       if (sym->ns->parent == NULL)
2082         break;
2083
2084       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2085
2086       if (sym == NULL)
2087         break;
2088     }
2089
2090   gfc_error ("Unable to resolve the specific function '%s' at %L",
2091              expr->symtree->n.sym->name, &expr->where);
2092
2093   return SUCCESS;
2094 }
2095
2096
2097 /* Resolve a procedure call not known to be generic nor specific.  */
2098
2099 static gfc_try
2100 resolve_unknown_f (gfc_expr *expr)
2101 {
2102   gfc_symbol *sym;
2103   gfc_typespec *ts;
2104
2105   sym = expr->symtree->n.sym;
2106
2107   if (sym->attr.dummy)
2108     {
2109       sym->attr.proc = PROC_DUMMY;
2110       expr->value.function.name = sym->name;
2111       goto set_type;
2112     }
2113
2114   /* See if we have an intrinsic function reference.  */
2115
2116   if (gfc_is_intrinsic (sym, 0, expr->where))
2117     {
2118       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2119         return SUCCESS;
2120       return FAILURE;
2121     }
2122
2123   /* The reference is to an external name.  */
2124
2125   sym->attr.proc = PROC_EXTERNAL;
2126   expr->value.function.name = sym->name;
2127   expr->value.function.esym = expr->symtree->n.sym;
2128
2129   if (sym->as != NULL)
2130     expr->rank = sym->as->rank;
2131
2132   /* Type of the expression is either the type of the symbol or the
2133      default type of the symbol.  */
2134
2135 set_type:
2136   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2137
2138   if (sym->ts.type != BT_UNKNOWN)
2139     expr->ts = sym->ts;
2140   else
2141     {
2142       ts = gfc_get_default_type (sym->name, sym->ns);
2143
2144       if (ts->type == BT_UNKNOWN)
2145         {
2146           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2147                      sym->name, &expr->where);
2148           return FAILURE;
2149         }
2150       else
2151         expr->ts = *ts;
2152     }
2153
2154   return SUCCESS;
2155 }
2156
2157
2158 /* Return true, if the symbol is an external procedure.  */
2159 static bool
2160 is_external_proc (gfc_symbol *sym)
2161 {
2162   if (!sym->attr.dummy && !sym->attr.contained
2163         && !(sym->attr.intrinsic
2164               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2165         && sym->attr.proc != PROC_ST_FUNCTION
2166         && !sym->attr.use_assoc
2167         && sym->name)
2168     return true;
2169
2170   return false;
2171 }
2172
2173
2174 /* Figure out if a function reference is pure or not.  Also set the name
2175    of the function for a potential error message.  Return nonzero if the
2176    function is PURE, zero if not.  */
2177 static int
2178 pure_stmt_function (gfc_expr *, gfc_symbol *);
2179
2180 static int
2181 pure_function (gfc_expr *e, const char **name)
2182 {
2183   int pure;
2184
2185   *name = NULL;
2186
2187   if (e->symtree != NULL
2188         && e->symtree->n.sym != NULL
2189         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2190     return pure_stmt_function (e, e->symtree->n.sym);
2191
2192   if (e->value.function.esym)
2193     {
2194       pure = gfc_pure (e->value.function.esym);
2195       *name = e->value.function.esym->name;
2196     }
2197   else if (e->value.function.isym)
2198     {
2199       pure = e->value.function.isym->pure
2200              || e->value.function.isym->elemental;
2201       *name = e->value.function.isym->name;
2202     }
2203   else
2204     {
2205       /* Implicit functions are not pure.  */
2206       pure = 0;
2207       *name = e->value.function.name;
2208     }
2209
2210   return pure;
2211 }
2212
2213
2214 static bool
2215 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2216                  int *f ATTRIBUTE_UNUSED)
2217 {
2218   const char *name;
2219
2220   /* Don't bother recursing into other statement functions
2221      since they will be checked individually for purity.  */
2222   if (e->expr_type != EXPR_FUNCTION
2223         || !e->symtree
2224         || e->symtree->n.sym == sym
2225         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2226     return false;
2227
2228   return pure_function (e, &name) ? false : true;
2229 }
2230
2231
2232 static int
2233 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2234 {
2235   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2236 }
2237
2238
2239 static gfc_try
2240 is_scalar_expr_ptr (gfc_expr *expr)
2241 {
2242   gfc_try retval = SUCCESS;
2243   gfc_ref *ref;
2244   int start;
2245   int end;
2246
2247   /* See if we have a gfc_ref, which means we have a substring, array
2248      reference, or a component.  */
2249   if (expr->ref != NULL)
2250     {
2251       ref = expr->ref;
2252       while (ref->next != NULL)
2253         ref = ref->next;
2254
2255       switch (ref->type)
2256         {
2257         case REF_SUBSTRING:
2258           if (ref->u.ss.length != NULL 
2259               && ref->u.ss.length->length != NULL
2260               && ref->u.ss.start
2261               && ref->u.ss.start->expr_type == EXPR_CONSTANT 
2262               && ref->u.ss.end
2263               && ref->u.ss.end->expr_type == EXPR_CONSTANT)
2264             {
2265               start = (int) mpz_get_si (ref->u.ss.start->value.integer);
2266               end = (int) mpz_get_si (ref->u.ss.end->value.integer);
2267               if (end - start + 1 != 1)
2268                 retval = FAILURE;
2269             }
2270           else
2271             retval = FAILURE;
2272           break;
2273         case REF_ARRAY:
2274           if (ref->u.ar.type == AR_ELEMENT)
2275             retval = SUCCESS;
2276           else if (ref->u.ar.type == AR_FULL)
2277             {
2278               /* The user can give a full array if the array is of size 1.  */
2279               if (ref->u.ar.as != NULL
2280                   && ref->u.ar.as->rank == 1
2281                   && ref->u.ar.as->type == AS_EXPLICIT
2282                   && ref->u.ar.as->lower[0] != NULL
2283                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2284                   && ref->u.ar.as->upper[0] != NULL
2285                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2286                 {
2287                   /* If we have a character string, we need to check if
2288                      its length is one.  */
2289                   if (expr->ts.type == BT_CHARACTER)
2290                     {
2291                       if (expr->ts.u.cl == NULL
2292                           || expr->ts.u.cl->length == NULL
2293                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2294                           != 0)
2295                         retval = FAILURE;
2296                     }
2297                   else
2298                     {
2299                       /* We have constant lower and upper bounds.  If the
2300                          difference between is 1, it can be considered a
2301                          scalar.  */
2302                       start = (int) mpz_get_si
2303                                 (ref->u.ar.as->lower[0]->value.integer);
2304                       end = (int) mpz_get_si
2305                                 (ref->u.ar.as->upper[0]->value.integer);
2306                       if (end - start + 1 != 1)
2307                         retval = FAILURE;
2308                    }
2309                 }
2310               else
2311                 retval = FAILURE;
2312             }
2313           else
2314             retval = FAILURE;
2315           break;
2316         default:
2317           retval = SUCCESS;
2318           break;
2319         }
2320     }
2321   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2322     {
2323       /* Character string.  Make sure it's of length 1.  */
2324       if (expr->ts.u.cl == NULL
2325           || expr->ts.u.cl->length == NULL
2326           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2327         retval = FAILURE;
2328     }
2329   else if (expr->rank != 0)
2330     retval = FAILURE;
2331
2332   return retval;
2333 }
2334
2335
2336 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2337    and, in the case of c_associated, set the binding label based on
2338    the arguments.  */
2339
2340 static gfc_try
2341 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2342                           gfc_symbol **new_sym)
2343 {
2344   char name[GFC_MAX_SYMBOL_LEN + 1];
2345   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2346   int optional_arg = 0, is_pointer = 0;
2347   gfc_try retval = SUCCESS;
2348   gfc_symbol *args_sym;
2349   gfc_typespec *arg_ts;
2350
2351   if (args->expr->expr_type == EXPR_CONSTANT
2352       || args->expr->expr_type == EXPR_OP
2353       || args->expr->expr_type == EXPR_NULL)
2354     {
2355       gfc_error ("Argument to '%s' at %L is not a variable",
2356                  sym->name, &(args->expr->where));
2357       return FAILURE;
2358     }
2359
2360   args_sym = args->expr->symtree->n.sym;
2361
2362   /* The typespec for the actual arg should be that stored in the expr
2363      and not necessarily that of the expr symbol (args_sym), because
2364      the actual expression could be a part-ref of the expr symbol.  */
2365   arg_ts = &(args->expr->ts);
2366
2367   is_pointer = gfc_is_data_pointer (args->expr);
2368     
2369   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2370     {
2371       /* If the user gave two args then they are providing something for
2372          the optional arg (the second cptr).  Therefore, set the name and
2373          binding label to the c_associated for two cptrs.  Otherwise,
2374          set c_associated to expect one cptr.  */
2375       if (args->next)
2376         {
2377           /* two args.  */
2378           sprintf (name, "%s_2", sym->name);
2379           sprintf (binding_label, "%s_2", sym->binding_label);
2380           optional_arg = 1;
2381         }
2382       else
2383         {
2384           /* one arg.  */
2385           sprintf (name, "%s_1", sym->name);
2386           sprintf (binding_label, "%s_1", sym->binding_label);
2387           optional_arg = 0;
2388         }
2389
2390       /* Get a new symbol for the version of c_associated that
2391          will get called.  */
2392       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2393     }
2394   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2395            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2396     {
2397       sprintf (name, "%s", sym->name);
2398       sprintf (binding_label, "%s", sym->binding_label);
2399
2400       /* Error check the call.  */
2401       if (args->next != NULL)
2402         {
2403           gfc_error_now ("More actual than formal arguments in '%s' "
2404                          "call at %L", name, &(args->expr->where));
2405           retval = FAILURE;
2406         }
2407       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2408         {
2409           /* Make sure we have either the target or pointer attribute.  */
2410           if (!args_sym->attr.target && !is_pointer)
2411             {
2412               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2413                              "a TARGET or an associated pointer",
2414                              args_sym->name,
2415                              sym->name, &(args->expr->where));
2416               retval = FAILURE;
2417             }
2418
2419           /* See if we have interoperable type and type param.  */
2420           if (verify_c_interop (arg_ts) == SUCCESS
2421               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2422             {
2423               if (args_sym->attr.target == 1)
2424                 {
2425                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2426                      has the target attribute and is interoperable.  */
2427                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2428                      allocatable variable that has the TARGET attribute and
2429                      is not an array of zero size.  */
2430                   if (args_sym->attr.allocatable == 1)
2431                     {
2432                       if (args_sym->attr.dimension != 0 
2433                           && (args_sym->as && args_sym->as->rank == 0))
2434                         {
2435                           gfc_error_now ("Allocatable variable '%s' used as a "
2436                                          "parameter to '%s' at %L must not be "
2437                                          "an array of zero size",
2438                                          args_sym->name, sym->name,
2439                                          &(args->expr->where));
2440                           retval = FAILURE;
2441                         }
2442                     }
2443                   else
2444                     {
2445                       /* A non-allocatable target variable with C
2446                          interoperable type and type parameters must be
2447                          interoperable.  */
2448                       if (args_sym && args_sym->attr.dimension)
2449                         {
2450                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2451                             {
2452                               gfc_error ("Assumed-shape array '%s' at %L "
2453                                          "cannot be an argument to the "
2454                                          "procedure '%s' because "
2455                                          "it is not C interoperable",
2456                                          args_sym->name,
2457                                          &(args->expr->where), sym->name);
2458                               retval = FAILURE;
2459                             }
2460                           else if (args_sym->as->type == AS_DEFERRED)
2461                             {
2462                               gfc_error ("Deferred-shape array '%s' at %L "
2463                                          "cannot be an argument to the "
2464                                          "procedure '%s' because "
2465                                          "it is not C interoperable",
2466                                          args_sym->name,
2467                                          &(args->expr->where), sym->name);
2468                               retval = FAILURE;
2469                             }
2470                         }
2471                               
2472                       /* Make sure it's not a character string.  Arrays of
2473                          any type should be ok if the variable is of a C
2474                          interoperable type.  */
2475                       if (arg_ts->type == BT_CHARACTER)
2476                         if (arg_ts->u.cl != NULL
2477                             && (arg_ts->u.cl->length == NULL
2478                                 || arg_ts->u.cl->length->expr_type
2479                                    != EXPR_CONSTANT
2480                                 || mpz_cmp_si
2481                                     (arg_ts->u.cl->length->value.integer, 1)
2482                                    != 0)
2483                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2484                           {
2485                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2486                                            "at %L must have a length of 1",
2487                                            args_sym->name, sym->name,
2488                                            &(args->expr->where));
2489                             retval = FAILURE;
2490                           }
2491                     }
2492                 }
2493               else if (is_pointer
2494                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2495                 {
2496                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2497                      scalar pointer.  */
2498                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2499                                  "associated scalar POINTER", args_sym->name,
2500                                  sym->name, &(args->expr->where));
2501                   retval = FAILURE;
2502                 }
2503             }
2504           else
2505             {
2506               /* The parameter is not required to be C interoperable.  If it
2507                  is not C interoperable, it must be a nonpolymorphic scalar
2508                  with no length type parameters.  It still must have either
2509                  the pointer or target attribute, and it can be
2510                  allocatable (but must be allocated when c_loc is called).  */
2511               if (args->expr->rank != 0 
2512                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2513                 {
2514                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2515                                  "scalar", args_sym->name, sym->name,
2516                                  &(args->expr->where));
2517                   retval = FAILURE;
2518                 }
2519               else if (arg_ts->type == BT_CHARACTER 
2520                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2521                 {
2522                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2523                                  "%L must have a length of 1",
2524                                  args_sym->name, sym->name,
2525                                  &(args->expr->where));
2526                   retval = FAILURE;
2527                 }
2528             }
2529         }
2530       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2531         {
2532           if (args_sym->attr.flavor != FL_PROCEDURE)
2533             {
2534               /* TODO: Update this error message to allow for procedure
2535                  pointers once they are implemented.  */
2536               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2537                              "procedure",
2538                              args_sym->name, sym->name,
2539                              &(args->expr->where));
2540               retval = FAILURE;
2541             }
2542           else if (args_sym->attr.is_bind_c != 1)
2543             {
2544               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2545                              "BIND(C)",
2546                              args_sym->name, sym->name,
2547                              &(args->expr->where));
2548               retval = FAILURE;
2549             }
2550         }
2551       
2552       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2553       *new_sym = sym;
2554     }
2555   else
2556     {
2557       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2558                           "iso_c_binding function: '%s'!\n", sym->name);
2559     }
2560
2561   return retval;
2562 }
2563
2564
2565 /* Resolve a function call, which means resolving the arguments, then figuring
2566    out which entity the name refers to.  */
2567 /* TODO: Check procedure arguments so that an INTENT(IN) isn't passed
2568    to INTENT(OUT) or INTENT(INOUT).  */
2569
2570 static gfc_try
2571 resolve_function (gfc_expr *expr)
2572 {
2573   gfc_actual_arglist *arg;
2574   gfc_symbol *sym;
2575   const char *name;
2576   gfc_try t;
2577   int temp;
2578   procedure_type p = PROC_INTRINSIC;
2579   bool no_formal_args;
2580
2581   sym = NULL;
2582   if (expr->symtree)
2583     sym = expr->symtree->n.sym;
2584
2585   /* If this is a procedure pointer component, it has already been resolved.  */
2586   if (gfc_is_proc_ptr_comp (expr, NULL))
2587     return SUCCESS;
2588   
2589   if (sym && sym->attr.intrinsic
2590       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2591     return FAILURE;
2592
2593   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2594     {
2595       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2596       return FAILURE;
2597     }
2598
2599   /* If this ia a deferred TBP with an abstract interface (which may
2600      of course be referenced), expr->value.function.esym will be set.  */
2601   if (sym && sym->attr.abstract && !expr->value.function.esym)
2602     {
2603       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2604                  sym->name, &expr->where);
2605       return FAILURE;
2606     }
2607
2608   /* Switch off assumed size checking and do this again for certain kinds
2609      of procedure, once the procedure itself is resolved.  */
2610   need_full_assumed_size++;
2611
2612   if (expr->symtree && expr->symtree->n.sym)
2613     p = expr->symtree->n.sym->attr.proc;
2614
2615   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2616     inquiry_argument = true;
2617   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2618
2619   if (resolve_actual_arglist (expr->value.function.actual,
2620                               p, no_formal_args) == FAILURE)
2621     {
2622       inquiry_argument = false;
2623       return FAILURE;
2624     }
2625
2626   inquiry_argument = false;
2627  
2628   /* Need to setup the call to the correct c_associated, depending on
2629      the number of cptrs to user gives to compare.  */
2630   if (sym && sym->attr.is_iso_c == 1)
2631     {
2632       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
2633           == FAILURE)
2634         return FAILURE;
2635       
2636       /* Get the symtree for the new symbol (resolved func).
2637          the old one will be freed later, when it's no longer used.  */
2638       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
2639     }
2640   
2641   /* Resume assumed_size checking.  */
2642   need_full_assumed_size--;
2643
2644   /* If the procedure is external, check for usage.  */
2645   if (sym && is_external_proc (sym))
2646     resolve_global_procedure (sym, &expr->where,
2647                               &expr->value.function.actual, 0);
2648
2649   if (sym && sym->ts.type == BT_CHARACTER
2650       && sym->ts.u.cl
2651       && sym->ts.u.cl->length == NULL
2652       && !sym->attr.dummy
2653       && expr->value.function.esym == NULL
2654       && !sym->attr.contained)
2655     {
2656       /* Internal procedures are taken care of in resolve_contained_fntype.  */
2657       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
2658                  "be used at %L since it is not a dummy argument",
2659                  sym->name, &expr->where);
2660       return FAILURE;
2661     }
2662
2663   /* See if function is already resolved.  */
2664
2665   if (expr->value.function.name != NULL)
2666     {
2667       if (expr->ts.type == BT_UNKNOWN)
2668         expr->ts = sym->ts;
2669       t = SUCCESS;
2670     }
2671   else
2672     {
2673       /* Apply the rules of section 14.1.2.  */
2674
2675       switch (procedure_kind (sym))
2676         {
2677         case PTYPE_GENERIC:
2678           t = resolve_generic_f (expr);
2679           break;
2680
2681         case PTYPE_SPECIFIC:
2682           t = resolve_specific_f (expr);
2683           break;
2684
2685         case PTYPE_UNKNOWN:
2686           t = resolve_unknown_f (expr);
2687           break;
2688
2689         default:
2690           gfc_internal_error ("resolve_function(): bad function type");
2691         }
2692     }
2693
2694   /* If the expression is still a function (it might have simplified),
2695      then we check to see if we are calling an elemental function.  */
2696
2697   if (expr->expr_type != EXPR_FUNCTION)
2698     return t;
2699
2700   temp = need_full_assumed_size;
2701   need_full_assumed_size = 0;
2702
2703   if (resolve_elemental_actual (expr, NULL) == FAILURE)
2704     return FAILURE;
2705
2706   if (omp_workshare_flag
2707       && expr->value.function.esym
2708       && ! gfc_elemental (expr->value.function.esym))
2709     {
2710       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
2711                  "in WORKSHARE construct", expr->value.function.esym->name,
2712                  &expr->where);
2713       t = FAILURE;
2714     }
2715
2716 #define GENERIC_ID expr->value.function.isym->id
2717   else if (expr->value.function.actual != NULL
2718            && expr->value.function.isym != NULL
2719            && GENERIC_ID != GFC_ISYM_LBOUND
2720            && GENERIC_ID != GFC_ISYM_LEN
2721            && GENERIC_ID != GFC_ISYM_LOC
2722            && GENERIC_ID != GFC_ISYM_PRESENT)
2723     {
2724       /* Array intrinsics must also have the last upper bound of an
2725          assumed size array argument.  UBOUND and SIZE have to be
2726          excluded from the check if the second argument is anything
2727          than a constant.  */
2728
2729       for (arg = expr->value.function.actual; arg; arg = arg->next)
2730         {
2731           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
2732               && arg->next != NULL && arg->next->expr)
2733             {
2734               if (arg->next->expr->expr_type != EXPR_CONSTANT)
2735                 break;
2736
2737               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
2738                 break;
2739
2740               if ((int)mpz_get_si (arg->next->expr->value.integer)
2741                         < arg->expr->rank)
2742                 break;
2743             }
2744
2745           if (arg->expr != NULL
2746               && arg->expr->rank > 0
2747               && resolve_assumed_size_actual (arg->expr))
2748             return FAILURE;
2749         }
2750     }
2751 #undef GENERIC_ID
2752
2753   need_full_assumed_size = temp;
2754   name = NULL;
2755
2756   if (!pure_function (expr, &name) && name)
2757     {
2758       if (forall_flag)
2759         {
2760           gfc_error ("reference to non-PURE function '%s' at %L inside a "
2761                      "FORALL %s", name, &expr->where,
2762                      forall_flag == 2 ? "mask" : "block");
2763           t = FAILURE;
2764         }
2765       else if (gfc_pure (NULL))
2766         {
2767           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
2768                      "procedure within a PURE procedure", name, &expr->where);
2769           t = FAILURE;
2770         }
2771     }
2772
2773   /* Functions without the RECURSIVE attribution are not allowed to
2774    * call themselves.  */
2775   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
2776     {
2777       gfc_symbol *esym;
2778       esym = expr->value.function.esym;
2779
2780       if (is_illegal_recursion (esym, gfc_current_ns))
2781       {
2782         if (esym->attr.entry && esym->ns->entries)
2783           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
2784                      " function '%s' is not RECURSIVE",
2785                      esym->name, &expr->where, esym->ns->entries->sym->name);
2786         else
2787           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
2788                      " is not RECURSIVE", esym->name, &expr->where);
2789
2790         t = FAILURE;
2791       }
2792     }
2793
2794   /* Character lengths of use associated functions may contains references to
2795      symbols not referenced from the current program unit otherwise.  Make sure
2796      those symbols are marked as referenced.  */
2797
2798   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
2799       && expr->value.function.esym->attr.use_assoc)
2800     {
2801       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
2802     }
2803
2804   if (t == SUCCESS
2805         && !((expr->value.function.esym
2806                 && expr->value.function.esym->attr.elemental)
2807                         ||
2808              (expr->value.function.isym
2809                 && expr->value.function.isym->elemental)))
2810     find_noncopying_intrinsics (expr->value.function.esym,
2811                                 expr->value.function.actual);
2812
2813   /* Make sure that the expression has a typespec that works.  */
2814   if (expr->ts.type == BT_UNKNOWN)
2815     {
2816       if (expr->symtree->n.sym->result
2817             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
2818             && !expr->symtree->n.sym->result->attr.proc_pointer)
2819         expr->ts = expr->symtree->n.sym->result->ts;
2820     }
2821
2822   return t;
2823 }
2824
2825
2826 /************* Subroutine resolution *************/
2827
2828 static void
2829 pure_subroutine (gfc_code *c, gfc_symbol *sym)
2830 {
2831   if (gfc_pure (sym))
2832     return;
2833
2834   if (forall_flag)
2835     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
2836                sym->name, &c->loc);
2837   else if (gfc_pure (NULL))
2838     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
2839                &c->loc);
2840 }
2841
2842
2843 static match
2844 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
2845 {
2846   gfc_symbol *s;
2847
2848   if (sym->attr.generic)
2849     {
2850       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
2851       if (s != NULL)
2852         {
2853           c->resolved_sym = s;
2854           pure_subroutine (c, s);
2855           return MATCH_YES;
2856         }
2857
2858       /* TODO: Need to search for elemental references in generic interface.  */
2859     }
2860
2861   if (sym->attr.intrinsic)
2862     return gfc_intrinsic_sub_interface (c, 0);
2863
2864   return MATCH_NO;
2865 }
2866
2867
2868 static gfc_try
2869 resolve_generic_s (gfc_code *c)
2870 {
2871   gfc_symbol *sym;
2872   match m;
2873
2874   sym = c->symtree->n.sym;
2875
2876   for (;;)
2877     {
2878       m = resolve_generic_s0 (c, sym);
2879       if (m == MATCH_YES)
2880         return SUCCESS;
2881       else if (m == MATCH_ERROR)
2882         return FAILURE;
2883
2884 generic:
2885       if (sym->ns->parent == NULL)
2886         break;
2887       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2888
2889       if (sym == NULL)
2890         break;
2891       if (!generic_sym (sym))
2892         goto generic;
2893     }
2894
2895   /* Last ditch attempt.  See if the reference is to an intrinsic
2896      that possesses a matching interface.  14.1.2.4  */
2897   sym = c->symtree->n.sym;
2898
2899   if (!gfc_is_intrinsic (sym, 1, c->loc))
2900     {
2901       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
2902                  sym->name, &c->loc);
2903       return FAILURE;
2904     }
2905
2906   m = gfc_intrinsic_sub_interface (c, 0);
2907   if (m == MATCH_YES)
2908     return SUCCESS;
2909   if (m == MATCH_NO)
2910     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
2911                "intrinsic subroutine interface", sym->name, &c->loc);
2912
2913   return FAILURE;
2914 }
2915
2916
2917 /* Set the name and binding label of the subroutine symbol in the call
2918    expression represented by 'c' to include the type and kind of the
2919    second parameter.  This function is for resolving the appropriate
2920    version of c_f_pointer() and c_f_procpointer().  For example, a
2921    call to c_f_pointer() for a default integer pointer could have a
2922    name of c_f_pointer_i4.  If no second arg exists, which is an error
2923    for these two functions, it defaults to the generic symbol's name
2924    and binding label.  */
2925
2926 static void
2927 set_name_and_label (gfc_code *c, gfc_symbol *sym,
2928                     char *name, char *binding_label)
2929 {
2930   gfc_expr *arg = NULL;
2931   char type;
2932   int kind;
2933
2934   /* The second arg of c_f_pointer and c_f_procpointer determines
2935      the type and kind for the procedure name.  */
2936   arg = c->ext.actual->next->expr;
2937
2938   if (arg != NULL)
2939     {
2940       /* Set up the name to have the given symbol's name,
2941          plus the type and kind.  */
2942       /* a derived type is marked with the type letter 'u' */
2943       if (arg->ts.type == BT_DERIVED)
2944         {
2945           type = 'd';
2946           kind = 0; /* set the kind as 0 for now */
2947         }
2948       else
2949         {
2950           type = gfc_type_letter (arg->ts.type);
2951           kind = arg->ts.kind;
2952         }
2953
2954       if (arg->ts.type == BT_CHARACTER)
2955         /* Kind info for character strings not needed.  */
2956         kind = 0;
2957
2958       sprintf (name, "%s_%c%d", sym->name, type, kind);
2959       /* Set up the binding label as the given symbol's label plus
2960          the type and kind.  */
2961       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
2962     }
2963   else
2964     {
2965       /* If the second arg is missing, set the name and label as
2966          was, cause it should at least be found, and the missing
2967          arg error will be caught by compare_parameters().  */
2968       sprintf (name, "%s", sym->name);
2969       sprintf (binding_label, "%s", sym->binding_label);
2970     }
2971    
2972   return;
2973 }
2974
2975
2976 /* Resolve a generic version of the iso_c_binding procedure given
2977    (sym) to the specific one based on the type and kind of the
2978    argument(s).  Currently, this function resolves c_f_pointer() and
2979    c_f_procpointer based on the type and kind of the second argument
2980    (FPTR).  Other iso_c_binding procedures aren't specially handled.
2981    Upon successfully exiting, c->resolved_sym will hold the resolved
2982    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
2983    otherwise.  */
2984
2985 match
2986 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
2987 {
2988   gfc_symbol *new_sym;
2989   /* this is fine, since we know the names won't use the max */
2990   char name[GFC_MAX_SYMBOL_LEN + 1];
2991   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2992   /* default to success; will override if find error */
2993   match m = MATCH_YES;
2994
2995   /* Make sure the actual arguments are in the necessary order (based on the 
2996      formal args) before resolving.  */
2997   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
2998
2999   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3000       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3001     {
3002       set_name_and_label (c, sym, name, binding_label);
3003       
3004       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3005         {
3006           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3007             {
3008               /* Make sure we got a third arg if the second arg has non-zero
3009                  rank.  We must also check that the type and rank are
3010                  correct since we short-circuit this check in
3011                  gfc_procedure_use() (called above to sort actual args).  */
3012               if (c->ext.actual->next->expr->rank != 0)
3013                 {
3014                   if(c->ext.actual->next->next == NULL 
3015                      || c->ext.actual->next->next->expr == NULL)
3016                     {
3017                       m = MATCH_ERROR;
3018                       gfc_error ("Missing SHAPE parameter for call to %s "
3019                                  "at %L", sym->name, &(c->loc));
3020                     }
3021                   else if (c->ext.actual->next->next->expr->ts.type
3022                            != BT_INTEGER
3023                            || c->ext.actual->next->next->expr->rank != 1)
3024                     {
3025                       m = MATCH_ERROR;
3026                       gfc_error ("SHAPE parameter for call to %s at %L must "
3027                                  "be a rank 1 INTEGER array", sym->name,
3028                                  &(c->loc));
3029                     }
3030                 }
3031             }
3032         }
3033       
3034       if (m != MATCH_ERROR)
3035         {
3036           /* the 1 means to add the optional arg to formal list */
3037           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3038          
3039           /* for error reporting, say it's declared where the original was */
3040           new_sym->declared_at = sym->declared_at;
3041         }
3042     }
3043   else
3044     {
3045       /* no differences for c_loc or c_funloc */
3046       new_sym = sym;
3047     }
3048
3049   /* set the resolved symbol */
3050   if (m != MATCH_ERROR)
3051     c->resolved_sym = new_sym;
3052   else
3053     c->resolved_sym = sym;
3054   
3055   return m;
3056 }
3057
3058
3059 /* Resolve a subroutine call known to be specific.  */
3060
3061 static match
3062 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3063 {
3064   match m;
3065
3066   if(sym->attr.is_iso_c)
3067     {
3068       m = gfc_iso_c_sub_interface (c,sym);
3069       return m;
3070     }
3071   
3072   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3073     {
3074       if (sym->attr.dummy)
3075         {
3076           sym->attr.proc = PROC_DUMMY;
3077           goto found;
3078         }
3079
3080       sym->attr.proc = PROC_EXTERNAL;
3081       goto found;
3082     }
3083
3084   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3085     goto found;
3086
3087   if (sym->attr.intrinsic)
3088     {
3089       m = gfc_intrinsic_sub_interface (c, 1);
3090       if (m == MATCH_YES)
3091         return MATCH_YES;
3092       if (m == MATCH_NO)
3093         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3094                    "with an intrinsic", sym->name, &c->loc);
3095
3096       return MATCH_ERROR;
3097     }
3098
3099   return MATCH_NO;
3100
3101 found:
3102   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3103
3104   c->resolved_sym = sym;
3105   pure_subroutine (c, sym);
3106
3107   return MATCH_YES;
3108 }
3109
3110
3111 static gfc_try
3112 resolve_specific_s (gfc_code *c)
3113 {
3114   gfc_symbol *sym;
3115   match m;
3116
3117   sym = c->symtree->n.sym;
3118
3119   for (;;)
3120     {
3121       m = resolve_specific_s0 (c, sym);
3122       if (m == MATCH_YES)
3123         return SUCCESS;
3124       if (m == MATCH_ERROR)
3125         return FAILURE;
3126
3127       if (sym->ns->parent == NULL)
3128         break;
3129
3130       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3131
3132       if (sym == NULL)
3133         break;
3134     }
3135
3136   sym = c->symtree->n.sym;
3137   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3138              sym->name, &c->loc);
3139
3140   return FAILURE;
3141 }
3142
3143
3144 /* Resolve a subroutine call not known to be generic nor specific.  */
3145
3146 static gfc_try
3147 resolve_unknown_s (gfc_code *c)
3148 {
3149   gfc_symbol *sym;
3150
3151   sym = c->symtree->n.sym;
3152
3153   if (sym->attr.dummy)
3154     {
3155       sym->attr.proc = PROC_DUMMY;
3156       goto found;
3157     }
3158
3159   /* See if we have an intrinsic function reference.  */
3160
3161   if (gfc_is_intrinsic (sym, 1, c->loc))
3162     {
3163       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3164         return SUCCESS;
3165       return FAILURE;
3166     }
3167
3168   /* The reference is to an external name.  */
3169
3170 found:
3171   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3172
3173   c->resolved_sym = sym;
3174
3175   pure_subroutine (c, sym);
3176
3177   return SUCCESS;
3178 }
3179
3180
3181 /* Resolve a subroutine call.  Although it was tempting to use the same code
3182    for functions, subroutines and functions are stored differently and this
3183    makes things awkward.  */
3184
3185 static gfc_try
3186 resolve_call (gfc_code *c)
3187 {
3188   gfc_try t;
3189   procedure_type ptype = PROC_INTRINSIC;
3190   gfc_symbol *csym, *sym;
3191   bool no_formal_args;
3192
3193   csym = c->symtree ? c->symtree->n.sym : NULL;
3194
3195   if (csym && csym->ts.type != BT_UNKNOWN)
3196     {
3197       gfc_error ("'%s' at %L has a type, which is not consistent with "
3198                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3199       return FAILURE;
3200     }
3201
3202   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3203     {
3204       gfc_symtree *st;
3205       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3206       sym = st ? st->n.sym : NULL;
3207       if (sym && csym != sym
3208               && sym->ns == gfc_current_ns
3209               && sym->attr.flavor == FL_PROCEDURE
3210               && sym->attr.contained)
3211         {
3212           sym->refs++;
3213           if (csym->attr.generic)
3214             c->symtree->n.sym = sym;
3215           else
3216             c->symtree = st;
3217           csym = c->symtree->n.sym;
3218         }
3219     }
3220
3221   /* If this ia a deferred TBP with an abstract interface
3222      (which may of course be referenced), c->expr1 will be set.  */
3223   if (csym && csym->attr.abstract && !c->expr1)
3224     {
3225       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3226                  csym->name, &c->loc);
3227       return FAILURE;
3228     }
3229
3230   /* Subroutines without the RECURSIVE attribution are not allowed to
3231    * call themselves.  */
3232   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3233     {
3234       if (csym->attr.entry && csym->ns->entries)
3235         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3236                    " subroutine '%s' is not RECURSIVE",
3237                    csym->name, &c->loc, csym->ns->entries->sym->name);
3238       else
3239         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3240                    " is not RECURSIVE", csym->name, &c->loc);
3241
3242       t = FAILURE;
3243     }
3244
3245   /* Switch off assumed size checking and do this again for certain kinds
3246      of procedure, once the procedure itself is resolved.  */
3247   need_full_assumed_size++;
3248
3249   if (csym)
3250     ptype = csym->attr.proc;
3251
3252   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3253   if (resolve_actual_arglist (c->ext.actual, ptype,
3254                               no_formal_args) == FAILURE)
3255     return FAILURE;
3256
3257   /* Resume assumed_size checking.  */
3258   need_full_assumed_size--;
3259
3260   /* If external, check for usage.  */
3261   if (csym && is_external_proc (csym))
3262     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3263
3264   t = SUCCESS;
3265   if (c->resolved_sym == NULL)
3266     {
3267       c->resolved_isym = NULL;
3268       switch (procedure_kind (csym))
3269         {
3270         case PTYPE_GENERIC:
3271           t = resolve_generic_s (c);
3272           break;
3273
3274         case PTYPE_SPECIFIC:
3275           t = resolve_specific_s (c);
3276           break;
3277
3278         case PTYPE_UNKNOWN:
3279           t = resolve_unknown_s (c);
3280           break;
3281
3282         default:
3283           gfc_internal_error ("resolve_subroutine(): bad function type");
3284         }
3285     }
3286
3287   /* Some checks of elemental subroutine actual arguments.  */
3288   if (resolve_elemental_actual (NULL, c) == FAILURE)
3289     return FAILURE;
3290
3291   if (t == SUCCESS && !(c->resolved_sym && c->resolved_sym->attr.elemental))
3292     find_noncopying_intrinsics (c->resolved_sym, c->ext.actual);
3293   return t;
3294 }
3295
3296
3297 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3298    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3299    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3300    if their shapes do not match.  If either op1->shape or op2->shape is
3301    NULL, return SUCCESS.  */
3302
3303 static gfc_try
3304 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3305 {
3306   gfc_try t;
3307   int i;
3308
3309   t = SUCCESS;
3310
3311   if (op1->shape != NULL && op2->shape != NULL)
3312     {
3313       for (i = 0; i < op1->rank; i++)
3314         {
3315           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3316            {
3317              gfc_error ("Shapes for operands at %L and %L are not conformable",
3318                          &op1->where, &op2->where);
3319              t = FAILURE;
3320              break;
3321            }
3322         }
3323     }
3324
3325   return t;
3326 }
3327
3328
3329 /* Resolve an operator expression node.  This can involve replacing the
3330    operation with a user defined function call.  */
3331
3332 static gfc_try
3333 resolve_operator (gfc_expr *e)
3334 {
3335   gfc_expr *op1, *op2;
3336   char msg[200];
3337   bool dual_locus_error;
3338   gfc_try t;
3339
3340   /* Resolve all subnodes-- give them types.  */
3341
3342   switch (e->value.op.op)
3343     {
3344     default:
3345       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3346         return FAILURE;
3347
3348     /* Fall through...  */
3349
3350     case INTRINSIC_NOT:
3351     case INTRINSIC_UPLUS:
3352     case INTRINSIC_UMINUS:
3353     case INTRINSIC_PARENTHESES:
3354       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3355         return FAILURE;
3356       break;
3357     }
3358
3359   /* Typecheck the new node.  */
3360
3361   op1 = e->value.op.op1;
3362   op2 = e->value.op.op2;
3363   dual_locus_error = false;
3364
3365   if ((op1 && op1->expr_type == EXPR_NULL)
3366       || (op2 && op2->expr_type == EXPR_NULL))
3367     {
3368       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3369       goto bad_op;
3370     }
3371
3372   switch (e->value.op.op)
3373     {
3374     case INTRINSIC_UPLUS:
3375     case INTRINSIC_UMINUS:
3376       if (op1->ts.type == BT_INTEGER
3377           || op1->ts.type == BT_REAL
3378           || op1->ts.type == BT_COMPLEX)
3379         {
3380           e->ts = op1->ts;
3381           break;
3382         }
3383
3384       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3385                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3386       goto bad_op;
3387
3388     case INTRINSIC_PLUS:
3389     case INTRINSIC_MINUS:
3390     case INTRINSIC_TIMES:
3391     case INTRINSIC_DIVIDE:
3392     case INTRINSIC_POWER:
3393       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3394         {
3395           gfc_type_convert_binary (e, 1);
3396           break;
3397         }
3398
3399       sprintf (msg,
3400                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3401                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3402                gfc_typename (&op2->ts));
3403       goto bad_op;
3404
3405     case INTRINSIC_CONCAT:
3406       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3407           && op1->ts.kind == op2->ts.kind)
3408         {
3409           e->ts.type = BT_CHARACTER;
3410           e->ts.kind = op1->ts.kind;
3411           break;
3412         }
3413
3414       sprintf (msg,
3415                _("Operands of string concatenation operator at %%L are %s/%s"),
3416                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3417       goto bad_op;
3418
3419     case INTRINSIC_AND:
3420     case INTRINSIC_OR:
3421     case INTRINSIC_EQV:
3422     case INTRINSIC_NEQV:
3423       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3424         {
3425           e->ts.type = BT_LOGICAL;
3426           e->ts.kind = gfc_kind_max (op1, op2);
3427           if (op1->ts.kind < e->ts.kind)
3428             gfc_convert_type (op1, &e->ts, 2);
3429           else if (op2->ts.kind < e->ts.kind)
3430             gfc_convert_type (op2, &e->ts, 2);
3431           break;
3432         }
3433
3434       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3435                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3436                gfc_typename (&op2->ts));
3437
3438       goto bad_op;
3439
3440     case INTRINSIC_NOT:
3441       if (op1->ts.type == BT_LOGICAL)
3442         {
3443           e->ts.type = BT_LOGICAL;
3444           e->ts.kind = op1->ts.kind;
3445           break;
3446         }
3447
3448       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3449                gfc_typename (&op1->ts));
3450       goto bad_op;
3451
3452     case INTRINSIC_GT:
3453     case INTRINSIC_GT_OS:
3454     case INTRINSIC_GE:
3455     case INTRINSIC_GE_OS:
3456     case INTRINSIC_LT:
3457     case INTRINSIC_LT_OS:
3458     case INTRINSIC_LE:
3459     case INTRINSIC_LE_OS:
3460       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3461         {
3462           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3463           goto bad_op;
3464         }
3465
3466       /* Fall through...  */
3467
3468     case INTRINSIC_EQ:
3469     case INTRINSIC_EQ_OS:
3470     case INTRINSIC_NE:
3471     case INTRINSIC_NE_OS:
3472       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3473           && op1->ts.kind == op2->ts.kind)
3474         {
3475           e->ts.type = BT_LOGICAL;
3476           e->ts.kind = gfc_default_logical_kind;
3477           break;
3478         }
3479
3480       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3481         {
3482           gfc_type_convert_binary (e, 1);
3483
3484           e->ts.type = BT_LOGICAL;
3485           e->ts.kind = gfc_default_logical_kind;
3486           break;
3487         }
3488
3489       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3490         sprintf (msg,
3491                  _("Logicals at %%L must be compared with %s instead of %s"),
3492                  (e->value.op.op == INTRINSIC_EQ 
3493                   || e->value.op.op == INTRINSIC_EQ_OS)
3494                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3495       else
3496         sprintf (msg,
3497                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3498                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3499                  gfc_typename (&op2->ts));
3500
3501       goto bad_op;
3502
3503     case INTRINSIC_USER:
3504       if (e->value.op.uop->op == NULL)
3505         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3506       else if (op2 == NULL)
3507         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3508                  e->value.op.uop->name, gfc_typename (&op1->ts));
3509       else
3510         sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3511                  e->value.op.uop->name, gfc_typename (&op1->ts),
3512                  gfc_typename (&op2->ts));
3513
3514       goto bad_op;
3515
3516     case INTRINSIC_PARENTHESES:
3517       e->ts = op1->ts;
3518       if (e->ts.type == BT_CHARACTER)
3519         e->ts.u.cl = op1->ts.u.cl;
3520       break;
3521
3522     default:
3523       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3524     }
3525
3526   /* Deal with arrayness of an operand through an operator.  */
3527
3528   t = SUCCESS;
3529
3530   switch (e->value.op.op)
3531     {
3532     case INTRINSIC_PLUS:
3533     case INTRINSIC_MINUS:
3534     case INTRINSIC_TIMES:
3535     case INTRINSIC_DIVIDE:
3536     case INTRINSIC_POWER:
3537     case INTRINSIC_CONCAT:
3538     case INTRINSIC_AND:
3539     case INTRINSIC_OR:
3540     case INTRINSIC_EQV:
3541     case INTRINSIC_NEQV:
3542     case INTRINSIC_EQ:
3543     case INTRINSIC_EQ_OS:
3544     case INTRINSIC_NE:
3545     case INTRINSIC_NE_OS:
3546     case INTRINSIC_GT:
3547     case INTRINSIC_GT_OS:
3548     case INTRINSIC_GE:
3549     case INTRINSIC_GE_OS:
3550     case INTRINSIC_LT:
3551     case INTRINSIC_LT_OS:
3552     case INTRINSIC_LE:
3553     case INTRINSIC_LE_OS:
3554
3555       if (op1->rank == 0 && op2->rank == 0)
3556         e->rank = 0;
3557
3558       if (op1->rank == 0 && op2->rank != 0)
3559         {
3560           e->rank = op2->rank;
3561
3562           if (e->shape == NULL)
3563             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3564         }
3565
3566       if (op1->rank != 0 && op2->rank == 0)
3567         {
3568           e->rank = op1->rank;
3569
3570           if (e->shape == NULL)
3571             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3572         }
3573
3574       if (op1->rank != 0 && op2->rank != 0)
3575         {
3576           if (op1->rank == op2->rank)
3577             {
3578               e->rank = op1->rank;
3579               if (e->shape == NULL)
3580                 {
3581                   t = compare_shapes(op1, op2);
3582                   if (t == FAILURE)
3583                     e->shape = NULL;
3584                   else
3585                 e->shape = gfc_copy_shape (op1->shape, op1->rank);
3586                 }
3587             }
3588           else
3589             {
3590               /* Allow higher level expressions to work.  */
3591               e->rank = 0;
3592
3593               /* Try user-defined operators, and otherwise throw an error.  */
3594               dual_locus_error = true;
3595               sprintf (msg,
3596                        _("Inconsistent ranks for operator at %%L and %%L"));
3597               goto bad_op;
3598             }
3599         }
3600
3601       break;
3602
3603     case INTRINSIC_PARENTHESES:
3604     case INTRINSIC_NOT:
3605     case INTRINSIC_UPLUS:
3606     case INTRINSIC_UMINUS:
3607       /* Simply copy arrayness attribute */
3608       e->rank = op1->rank;
3609
3610       if (e->shape == NULL)
3611         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3612
3613       break;
3614
3615     default:
3616       break;
3617     }
3618
3619   /* Attempt to simplify the expression.  */
3620   if (t == SUCCESS)
3621     {
3622       t = gfc_simplify_expr (e, 0);
3623       /* Some calls do not succeed in simplification and return FAILURE
3624          even though there is no error; e.g. variable references to
3625          PARAMETER arrays.  */
3626       if (!gfc_is_constant_expr (e))
3627         t = SUCCESS;
3628     }
3629   return t;
3630
3631 bad_op:
3632
3633   {
3634     bool real_error;
3635     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3636       return SUCCESS;
3637
3638     if (real_error)
3639       return FAILURE;
3640   }
3641
3642   if (dual_locus_error)
3643     gfc_error (msg, &op1->where, &op2->where);
3644   else
3645     gfc_error (msg, &e->where);
3646
3647   return FAILURE;
3648 }
3649
3650
3651 /************** Array resolution subroutines **************/
3652
3653 typedef enum
3654 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
3655 comparison;
3656
3657 /* Compare two integer expressions.  */
3658
3659 static comparison
3660 compare_bound (gfc_expr *a, gfc_expr *b)
3661 {
3662   int i;
3663
3664   if (a == NULL || a->expr_type != EXPR_CONSTANT
3665       || b == NULL || b->expr_type != EXPR_CONSTANT)
3666     return CMP_UNKNOWN;
3667
3668   /* If either of the types isn't INTEGER, we must have
3669      raised an error earlier.  */
3670
3671   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
3672     return CMP_UNKNOWN;
3673
3674   i = mpz_cmp (a->value.integer, b->value.integer);
3675
3676   if (i < 0)
3677     return CMP_LT;
3678   if (i > 0)
3679     return CMP_GT;
3680   return CMP_EQ;
3681 }
3682
3683
3684 /* Compare an integer expression with an integer.  */
3685
3686 static comparison
3687 compare_bound_int (gfc_expr *a, int b)
3688 {
3689   int i;
3690
3691   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3692     return CMP_UNKNOWN;
3693
3694   if (a->ts.type != BT_INTEGER)
3695     gfc_internal_error ("compare_bound_int(): Bad expression");
3696
3697   i = mpz_cmp_si (a->value.integer, b);
3698
3699   if (i < 0)
3700     return CMP_LT;
3701   if (i > 0)
3702     return CMP_GT;
3703   return CMP_EQ;
3704 }
3705
3706
3707 /* Compare an integer expression with a mpz_t.  */
3708
3709 static comparison
3710 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
3711 {
3712   int i;
3713
3714   if (a == NULL || a->expr_type != EXPR_CONSTANT)
3715     return CMP_UNKNOWN;
3716
3717   if (a->ts.type != BT_INTEGER)
3718     gfc_internal_error ("compare_bound_int(): Bad expression");
3719
3720   i = mpz_cmp (a->value.integer, b);
3721
3722   if (i < 0)
3723     return CMP_LT;
3724   if (i > 0)
3725     return CMP_GT;
3726   return CMP_EQ;
3727 }
3728
3729
3730 /* Compute the last value of a sequence given by a triplet.  
3731    Return 0 if it wasn't able to compute the last value, or if the
3732    sequence if empty, and 1 otherwise.  */
3733
3734 static int
3735 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
3736                                 gfc_expr *stride, mpz_t last)
3737 {
3738   mpz_t rem;
3739
3740   if (start == NULL || start->expr_type != EXPR_CONSTANT
3741       || end == NULL || end->expr_type != EXPR_CONSTANT
3742       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
3743     return 0;
3744
3745   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
3746       || (stride != NULL && stride->ts.type != BT_INTEGER))
3747     return 0;
3748
3749   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
3750     {
3751       if (compare_bound (start, end) == CMP_GT)
3752         return 0;
3753       mpz_set (last, end->value.integer);
3754       return 1;
3755     }
3756
3757   if (compare_bound_int (stride, 0) == CMP_GT)
3758     {
3759       /* Stride is positive */
3760       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
3761         return 0;
3762     }
3763   else
3764     {
3765       /* Stride is negative */
3766       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
3767         return 0;
3768     }
3769
3770   mpz_init (rem);
3771   mpz_sub (rem, end->value.integer, start->value.integer);
3772   mpz_tdiv_r (rem, rem, stride->value.integer);
3773   mpz_sub (last, end->value.integer, rem);
3774   mpz_clear (rem);
3775
3776   return 1;
3777 }
3778
3779
3780 /* Compare a single dimension of an array reference to the array
3781    specification.  */
3782
3783 static gfc_try
3784 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
3785 {
3786   mpz_t last_value;
3787
3788   if (ar->dimen_type[i] == DIMEN_STAR)
3789     {
3790       gcc_assert (ar->stride[i] == NULL);
3791       /* This implies [*] as [*:] and [*:3] are not possible.  */
3792       if (ar->start[i] == NULL)
3793         {
3794           gcc_assert (ar->end[i] == NULL);
3795           return SUCCESS;
3796         }
3797     }
3798
3799 /* Given start, end and stride values, calculate the minimum and
3800    maximum referenced indexes.  */
3801
3802   switch (ar->dimen_type[i])
3803     {
3804     case DIMEN_VECTOR:
3805       break;
3806
3807     case DIMEN_STAR:
3808     case DIMEN_ELEMENT:
3809       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
3810         {
3811           if (i < as->rank)
3812             gfc_warning ("Array reference at %L is out of bounds "
3813                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
3814                          mpz_get_si (ar->start[i]->value.integer),
3815                          mpz_get_si (as->lower[i]->value.integer), i+1);
3816           else
3817             gfc_warning ("Array reference at %L is out of bounds "
3818                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
3819                          mpz_get_si (ar->start[i]->value.integer),
3820                          mpz_get_si (as->lower[i]->value.integer),
3821                          i + 1 - as->rank);
3822           return SUCCESS;
3823         }
3824       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
3825         {
3826           if (i < as->rank)
3827             gfc_warning ("Array reference at %L is out of bounds "
3828                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
3829                          mpz_get_si (ar->start[i]->value.integer),
3830                          mpz_get_si (as->upper[i]->value.integer), i+1);
3831           else
3832             gfc_warning ("Array reference at %L is out of bounds "
3833                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
3834                          mpz_get_si (ar->start[i]->value.integer),
3835                          mpz_get_si (as->upper[i]->value.integer),
3836                          i + 1 - as->rank);
3837           return SUCCESS;
3838         }
3839
3840       break;
3841
3842     case DIMEN_RANGE:
3843       {
3844 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
3845 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
3846
3847         comparison comp_start_end = compare_bound (AR_START, AR_END);
3848
3849         /* Check for zero stride, which is not allowed.  */
3850         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
3851           {
3852             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
3853             return FAILURE;
3854           }
3855
3856         /* if start == len || (stride > 0 && start < len)
3857                            || (stride < 0 && start > len),
3858            then the array section contains at least one element.  In this
3859            case, there is an out-of-bounds access if
3860            (start < lower || start > upper).  */
3861         if (compare_bound (AR_START, AR_END) == CMP_EQ
3862             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
3863                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
3864             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
3865                 && comp_start_end == CMP_GT))
3866           {
3867             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
3868               {
3869                 gfc_warning ("Lower array reference at %L is out of bounds "
3870                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3871                        mpz_get_si (AR_START->value.integer),
3872                        mpz_get_si (as->lower[i]->value.integer), i+1);
3873                 return SUCCESS;
3874               }
3875             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
3876               {
3877                 gfc_warning ("Lower array reference at %L is out of bounds "
3878                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3879                        mpz_get_si (AR_START->value.integer),
3880                        mpz_get_si (as->upper[i]->value.integer), i+1);
3881                 return SUCCESS;
3882               }
3883           }
3884
3885         /* If we can compute the highest index of the array section,
3886            then it also has to be between lower and upper.  */
3887         mpz_init (last_value);
3888         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
3889                                             last_value))
3890           {
3891             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
3892               {
3893                 gfc_warning ("Upper array reference at %L is out of bounds "
3894                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
3895                        mpz_get_si (last_value),
3896                        mpz_get_si (as->lower[i]->value.integer), i+1);
3897                 mpz_clear (last_value);
3898                 return SUCCESS;
3899               }
3900             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
3901               {
3902                 gfc_warning ("Upper array reference at %L is out of bounds "
3903                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
3904                        mpz_get_si (last_value),
3905                        mpz_get_si (as->upper[i]->value.integer), i+1);
3906                 mpz_clear (last_value);
3907                 return SUCCESS;
3908               }
3909           }
3910         mpz_clear (last_value);
3911
3912 #undef AR_START
3913 #undef AR_END
3914       }
3915       break;
3916
3917     default:
3918       gfc_internal_error ("check_dimension(): Bad array reference");
3919     }
3920
3921   return SUCCESS;
3922 }
3923
3924
3925 /* Compare an array reference with an array specification.  */
3926
3927 static gfc_try
3928 compare_spec_to_ref (gfc_array_ref *ar)
3929 {
3930   gfc_array_spec *as;
3931   int i;
3932
3933   as = ar->as;
3934   i = as->rank - 1;
3935   /* TODO: Full array sections are only allowed as actual parameters.  */
3936   if (as->type == AS_ASSUMED_SIZE
3937       && (/*ar->type == AR_FULL
3938           ||*/ (ar->type == AR_SECTION
3939               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
3940     {
3941       gfc_error ("Rightmost upper bound of assumed size array section "
3942                  "not specified at %L", &ar->where);
3943       return FAILURE;
3944     }
3945
3946   if (ar->type == AR_FULL)
3947     return SUCCESS;
3948
3949   if (as->rank != ar->dimen)
3950     {
3951       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
3952                  &ar->where, ar->dimen, as->rank);
3953       return FAILURE;
3954     }
3955
3956   /* ar->codimen == 0 is a local array.  */
3957   if (as->corank != ar->codimen && ar->codimen != 0)
3958     {
3959       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
3960                  &ar->where, ar->codimen, as->corank);
3961       return FAILURE;
3962     }
3963
3964   for (i = 0; i < as->rank; i++)
3965     if (check_dimension (i, ar, as) == FAILURE)
3966       return FAILURE;
3967
3968   /* Local access has no coarray spec.  */
3969   if (ar->codimen != 0)
3970     for (i = as->rank; i < as->rank + as->corank; i++)
3971       {
3972         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate)
3973           {
3974             gfc_error ("Coindex of codimension %d must be a scalar at %L",
3975                        i + 1 - as->rank, &ar->where);
3976             return FAILURE;
3977           }
3978         if (check_dimension (i, ar, as) == FAILURE)
3979           return FAILURE;
3980       }
3981
3982   return SUCCESS;
3983 }
3984
3985
3986 /* Resolve one part of an array index.  */
3987
3988 static gfc_try
3989 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
3990                      int force_index_integer_kind)
3991 {
3992   gfc_typespec ts;
3993
3994   if (index == NULL)
3995     return SUCCESS;
3996
3997   if (gfc_resolve_expr (index) == FAILURE)
3998     return FAILURE;
3999
4000   if (check_scalar && index->rank != 0)
4001     {
4002       gfc_error ("Array index at %L must be scalar", &index->where);
4003       return FAILURE;
4004     }
4005
4006   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4007     {
4008       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4009                  &index->where, gfc_basic_typename (index->ts.type));
4010       return FAILURE;
4011     }
4012
4013   if (index->ts.type == BT_REAL)
4014     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4015                         &index->where) == FAILURE)
4016       return FAILURE;
4017
4018   if ((index->ts.kind != gfc_index_integer_kind
4019        && force_index_integer_kind)
4020       || index->ts.type != BT_INTEGER)
4021     {
4022       gfc_clear_ts (&ts);
4023       ts.type = BT_INTEGER;
4024       ts.kind = gfc_index_integer_kind;
4025
4026       gfc_convert_type_warn (index, &ts, 2, 0);
4027     }
4028
4029   return SUCCESS;
4030 }
4031
4032 /* Resolve one part of an array index.  */
4033
4034 gfc_try
4035 gfc_resolve_index (gfc_expr *index, int check_scalar)
4036 {
4037   return gfc_resolve_index_1 (index, check_scalar, 1);
4038 }
4039
4040 /* Resolve a dim argument to an intrinsic function.  */
4041
4042 gfc_try
4043 gfc_resolve_dim_arg (gfc_expr *dim)
4044 {
4045   if (dim == NULL)
4046     return SUCCESS;
4047
4048   if (gfc_resolve_expr (dim) == FAILURE)
4049     return FAILURE;
4050
4051   if (dim->rank != 0)
4052     {
4053       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4054       return FAILURE;
4055
4056     }
4057
4058   if (dim->ts.type != BT_INTEGER)
4059     {
4060       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4061       return FAILURE;
4062     }
4063
4064   if (dim->ts.kind != gfc_index_integer_kind)
4065     {
4066       gfc_typespec ts;
4067
4068       gfc_clear_ts (&ts);
4069       ts.type = BT_INTEGER;
4070       ts.kind = gfc_index_integer_kind;
4071
4072       gfc_convert_type_warn (dim, &ts, 2, 0);
4073     }
4074
4075   return SUCCESS;
4076 }
4077
4078 /* Given an expression that contains array references, update those array
4079    references to point to the right array specifications.  While this is
4080    filled in during matching, this information is difficult to save and load
4081    in a module, so we take care of it here.
4082
4083    The idea here is that the original array reference comes from the
4084    base symbol.  We traverse the list of reference structures, setting
4085    the stored reference to references.  Component references can
4086    provide an additional array specification.  */
4087
4088 static void
4089 find_array_spec (gfc_expr *e)
4090 {
4091   gfc_array_spec *as;
4092   gfc_component *c;
4093   gfc_symbol *derived;
4094   gfc_ref *ref;
4095
4096   if (e->symtree->n.sym->ts.type == BT_CLASS)
4097     as = e->symtree->n.sym->ts.u.derived->components->as;
4098   else
4099     as = e->symtree->n.sym->as;
4100   derived = NULL;
4101
4102   for (ref = e->ref; ref; ref = ref->next)
4103     switch (ref->type)
4104       {
4105       case REF_ARRAY:
4106         if (as == NULL)
4107           gfc_internal_error ("find_array_spec(): Missing spec");
4108
4109         ref->u.ar.as = as;
4110         as = NULL;
4111         break;
4112
4113       case REF_COMPONENT:
4114         if (derived == NULL)
4115           derived = e->symtree->n.sym->ts.u.derived;
4116
4117         if (derived->attr.is_class)
4118           derived = derived->components->ts.u.derived;
4119
4120         c = derived->components;
4121
4122         for (; c; c = c->next)
4123           if (c == ref->u.c.component)
4124             {
4125               /* Track the sequence of component references.  */
4126               if (c->ts.type == BT_DERIVED)
4127                 derived = c->ts.u.derived;
4128               break;
4129             }
4130
4131         if (c == NULL)
4132           gfc_internal_error ("find_array_spec(): Component not found");
4133
4134         if (c->attr.dimension)
4135           {
4136             if (as != NULL)
4137               gfc_internal_error ("find_array_spec(): unused as(1)");
4138             as = c->as;
4139           }
4140
4141         break;
4142
4143       case REF_SUBSTRING:
4144         break;
4145       }
4146
4147   if (as != NULL)
4148     gfc_internal_error ("find_array_spec(): unused as(2)");
4149 }
4150
4151
4152 /* Resolve an array reference.  */
4153
4154 static gfc_try
4155 resolve_array_ref (gfc_array_ref *ar)
4156 {
4157   int i, check_scalar;
4158   gfc_expr *e;
4159
4160   for (i = 0; i < ar->dimen + ar->codimen; i++)
4161     {
4162       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4163
4164       /* Do not force gfc_index_integer_kind for the start.  We can
4165          do fine with any integer kind.  This avoids temporary arrays
4166          created for indexing with a vector.  */
4167       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4168         return FAILURE;
4169       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4170         return FAILURE;
4171       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4172         return FAILURE;
4173
4174       e = ar->start[i];
4175
4176       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4177         switch (e->rank)
4178           {
4179           case 0:
4180             ar->dimen_type[i] = DIMEN_ELEMENT;
4181             break;
4182
4183           case 1:
4184             ar->dimen_type[i] = DIMEN_VECTOR;
4185             if (e->expr_type == EXPR_VARIABLE
4186                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4187               ar->start[i] = gfc_get_parentheses (e);
4188             break;
4189
4190           default:
4191             gfc_error ("Array index at %L is an array of rank %d",
4192                        &ar->c_where[i], e->rank);
4193             return FAILURE;
4194           }
4195     }
4196
4197   if (ar->type == AR_FULL && ar->as->rank == 0)
4198     ar->type = AR_ELEMENT;
4199
4200   /* If the reference type is unknown, figure out what kind it is.  */
4201
4202   if (ar->type == AR_UNKNOWN)
4203     {
4204       ar->type = AR_ELEMENT;
4205       for (i = 0; i < ar->dimen; i++)
4206         if (ar->dimen_type[i] == DIMEN_RANGE
4207             || ar->dimen_type[i] == DIMEN_VECTOR)
4208           {
4209             ar->type = AR_SECTION;
4210             break;
4211           }
4212     }
4213
4214   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4215     return FAILURE;
4216
4217   return SUCCESS;
4218 }
4219
4220
4221 static gfc_try
4222 resolve_substring (gfc_ref *ref)
4223 {
4224   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4225
4226   if (ref->u.ss.start != NULL)
4227     {
4228       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4229         return FAILURE;
4230
4231       if (ref->u.ss.start->ts.type != BT_INTEGER)
4232         {
4233           gfc_error ("Substring start index at %L must be of type INTEGER",
4234                      &ref->u.ss.start->where);
4235           return FAILURE;
4236         }
4237
4238       if (ref->u.ss.start->rank != 0)
4239         {
4240           gfc_error ("Substring start index at %L must be scalar",
4241                      &ref->u.ss.start->where);
4242           return FAILURE;
4243         }
4244
4245       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4246           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4247               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4248         {
4249           gfc_error ("Substring start index at %L is less than one",
4250                      &ref->u.ss.start->where);
4251           return FAILURE;
4252         }
4253     }
4254
4255   if (ref->u.ss.end != NULL)
4256     {
4257       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4258         return FAILURE;
4259
4260       if (ref->u.ss.end->ts.type != BT_INTEGER)
4261         {
4262           gfc_error ("Substring end index at %L must be of type INTEGER",
4263                      &ref->u.ss.end->where);
4264           return FAILURE;
4265         }
4266
4267       if (ref->u.ss.end->rank != 0)
4268         {
4269           gfc_error ("Substring end index at %L must be scalar",
4270                      &ref->u.ss.end->where);
4271           return FAILURE;
4272         }
4273
4274       if (ref->u.ss.length != NULL
4275           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4276           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4277               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4278         {
4279           gfc_error ("Substring end index at %L exceeds the string length",
4280                      &ref->u.ss.start->where);
4281           return FAILURE;
4282         }
4283
4284       if (compare_bound_mpz_t (ref->u.ss.end,
4285                                gfc_integer_kinds[k].huge) == CMP_GT
4286           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4287               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4288         {
4289           gfc_error ("Substring end index at %L is too large",
4290                      &ref->u.ss.end->where);
4291           return FAILURE;
4292         }
4293     }
4294
4295   return SUCCESS;
4296 }
4297
4298
4299 /* This function supplies missing substring charlens.  */
4300
4301 void
4302 gfc_resolve_substring_charlen (gfc_expr *e)
4303 {
4304   gfc_ref *char_ref;
4305   gfc_expr *start, *end;
4306
4307   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4308     if (char_ref->type == REF_SUBSTRING)
4309       break;
4310
4311   if (!char_ref)
4312     return;
4313
4314   gcc_assert (char_ref->next == NULL);
4315
4316   if (e->ts.u.cl)
4317     {
4318       if (e->ts.u.cl->length)
4319         gfc_free_expr (e->ts.u.cl->length);
4320       else if (e->expr_type == EXPR_VARIABLE
4321                  && e->symtree->n.sym->attr.dummy)
4322         return;
4323     }
4324
4325   e->ts.type = BT_CHARACTER;
4326   e->ts.kind = gfc_default_character_kind;
4327
4328   if (!e->ts.u.cl)
4329     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4330
4331   if (char_ref->u.ss.start)
4332     start = gfc_copy_expr (char_ref->u.ss.start);
4333   else
4334     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4335
4336   if (char_ref->u.ss.end)
4337     end = gfc_copy_expr (char_ref->u.ss.end);
4338   else if (e->expr_type == EXPR_VARIABLE)
4339     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4340   else
4341     end = NULL;
4342
4343   if (!start || !end)
4344     return;
4345
4346   /* Length = (end - start +1).  */
4347   e->ts.u.cl->length = gfc_subtract (end, start);
4348   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4349                                 gfc_get_int_expr (gfc_default_integer_kind,
4350                                                   NULL, 1));
4351
4352   e->ts.u.cl->length->ts.type = BT_INTEGER;
4353   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4354
4355   /* Make sure that the length is simplified.  */
4356   gfc_simplify_expr (e->ts.u.cl->length, 1);
4357   gfc_resolve_expr (e->ts.u.cl->length);
4358 }
4359
4360
4361 /* Resolve subtype references.  */
4362
4363 static gfc_try
4364 resolve_ref (gfc_expr *expr)
4365 {
4366   int current_part_dimension, n_components, seen_part_dimension;
4367   gfc_ref *ref;
4368
4369   for (ref = expr->ref; ref; ref = ref->next)
4370     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4371       {
4372         find_array_spec (expr);
4373         break;
4374       }
4375
4376   for (ref = expr->ref; ref; ref = ref->next)
4377     switch (ref->type)
4378       {
4379       case REF_ARRAY:
4380         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4381           return FAILURE;
4382         break;
4383
4384       case REF_COMPONENT:
4385         break;
4386
4387       case REF_SUBSTRING:
4388         resolve_substring (ref);
4389         break;
4390       }
4391
4392   /* Check constraints on part references.  */
4393
4394   current_part_dimension = 0;
4395   seen_part_dimension = 0;
4396   n_components = 0;
4397
4398   for (ref = expr->ref; ref; ref = ref->next)
4399     {
4400       switch (ref->type)
4401         {
4402         case REF_ARRAY:
4403           switch (ref->u.ar.type)
4404             {
4405             case AR_FULL:
4406               /* Coarray scalar.  */
4407               if (ref->u.ar.as->rank == 0)
4408                 {
4409                   current_part_dimension = 0;
4410                   break;
4411                 }
4412               /* Fall through.  */
4413             case AR_SECTION:
4414               current_part_dimension = 1;
4415               break;
4416
4417             case AR_ELEMENT:
4418               current_part_dimension = 0;
4419               break;
4420
4421             case AR_UNKNOWN:
4422               gfc_internal_error ("resolve_ref(): Bad array reference");
4423             }
4424
4425           break;
4426
4427         case REF_COMPONENT:
4428           if (current_part_dimension || seen_part_dimension)
4429             {
4430               /* F03:C614.  */
4431               if (ref->u.c.component->attr.pointer
4432                   || ref->u.c.component->attr.proc_pointer)
4433                 {
4434                   gfc_error ("Component to the right of a part reference "
4435                              "with nonzero rank must not have the POINTER "
4436                              "attribute at %L", &expr->where);
4437                   return FAILURE;
4438                 }
4439               else if (ref->u.c.component->attr.allocatable)
4440                 {
4441                   gfc_error ("Component to the right of a part reference "
4442                              "with nonzero rank must not have the ALLOCATABLE "
4443                              "attribute at %L", &expr->where);
4444                   return FAILURE;
4445                 }
4446             }
4447
4448           n_components++;
4449           break;
4450
4451         case REF_SUBSTRING:
4452           break;
4453         }
4454
4455       if (((ref->type == REF_COMPONENT && n_components > 1)
4456            || ref->next == NULL)
4457           && current_part_dimension
4458           && seen_part_dimension)
4459         {
4460           gfc_error ("Two or more part references with nonzero rank must "
4461                      "not be specified at %L", &expr->where);
4462           return FAILURE;
4463         }
4464
4465       if (ref->type == REF_COMPONENT)
4466         {
4467           if (current_part_dimension)
4468             seen_part_dimension = 1;
4469
4470           /* reset to make sure */
4471           current_part_dimension = 0;
4472         }
4473     }
4474
4475   return SUCCESS;
4476 }
4477
4478
4479 /* Given an expression, determine its shape.  This is easier than it sounds.
4480    Leaves the shape array NULL if it is not possible to determine the shape.  */
4481
4482 static void
4483 expression_shape (gfc_expr *e)
4484 {
4485   mpz_t array[GFC_MAX_DIMENSIONS];
4486   int i;
4487
4488   if (e->rank == 0 || e->shape != NULL)
4489     return;
4490
4491   for (i = 0; i < e->rank; i++)
4492     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4493       goto fail;
4494
4495   e->shape = gfc_get_shape (e->rank);
4496
4497   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4498
4499   return;
4500
4501 fail:
4502   for (i--; i >= 0; i--)
4503     mpz_clear (array[i]);
4504 }
4505
4506
4507 /* Given a variable expression node, compute the rank of the expression by
4508    examining the base symbol and any reference structures it may have.  */
4509
4510 static void
4511 expression_rank (gfc_expr *e)
4512 {
4513   gfc_ref *ref;
4514   int i, rank;
4515
4516   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4517      could lead to serious confusion...  */
4518   gcc_assert (e->expr_type != EXPR_COMPCALL);
4519
4520   if (e->ref == NULL)
4521     {
4522       if (e->expr_type == EXPR_ARRAY)
4523         goto done;
4524       /* Constructors can have a rank different from one via RESHAPE().  */
4525
4526       if (e->symtree == NULL)
4527         {
4528           e->rank = 0;
4529           goto done;
4530         }
4531
4532       e->rank = (e->symtree->n.sym->as == NULL)
4533                 ? 0 : e->symtree->n.sym->as->rank;
4534       goto done;
4535     }
4536
4537   rank = 0;
4538
4539   for (ref = e->ref; ref; ref = ref->next)
4540     {
4541       if (ref->type != REF_ARRAY)
4542         continue;
4543
4544       if (ref->u.ar.type == AR_FULL)
4545         {
4546           rank = ref->u.ar.as->rank;
4547           break;
4548         }
4549
4550       if (ref->u.ar.type == AR_SECTION)
4551         {
4552           /* Figure out the rank of the section.  */
4553           if (rank != 0)
4554             gfc_internal_error ("expression_rank(): Two array specs");
4555
4556           for (i = 0; i < ref->u.ar.dimen; i++)
4557             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4558                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4559               rank++;
4560
4561           break;
4562         }
4563     }
4564
4565   e->rank = rank;
4566
4567 done:
4568   expression_shape (e);
4569 }
4570
4571
4572 /* Resolve a variable expression.  */
4573
4574 static gfc_try
4575 resolve_variable (gfc_expr *e)
4576 {
4577   gfc_symbol *sym;
4578   gfc_try t;
4579
4580   t = SUCCESS;
4581
4582   if (e->symtree == NULL)
4583     return FAILURE;
4584
4585   if (e->ref && resolve_ref (e) == FAILURE)
4586     return FAILURE;
4587
4588   sym = e->symtree->n.sym;
4589   if (sym->attr.flavor == FL_PROCEDURE
4590       && (!sym->attr.function
4591           || (sym->attr.function && sym->result
4592               && sym->result->attr.proc_pointer
4593               && !sym->result->attr.function)))
4594     {
4595       e->ts.type = BT_PROCEDURE;
4596       goto resolve_procedure;
4597     }
4598
4599   if (sym->ts.type != BT_UNKNOWN)
4600     gfc_variable_attr (e, &e->ts);
4601   else
4602     {
4603       /* Must be a simple variable reference.  */
4604       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
4605         return FAILURE;
4606       e->ts = sym->ts;
4607     }
4608
4609   if (check_assumed_size_reference (sym, e))
4610     return FAILURE;
4611
4612   /* Deal with forward references to entries during resolve_code, to
4613      satisfy, at least partially, 12.5.2.5.  */
4614   if (gfc_current_ns->entries
4615       && current_entry_id == sym->entry_id
4616       && cs_base
4617       && cs_base->current
4618       && cs_base->current->op != EXEC_ENTRY)
4619     {
4620       gfc_entry_list *entry;
4621       gfc_formal_arglist *formal;
4622       int n;
4623       bool seen;
4624
4625       /* If the symbol is a dummy...  */
4626       if (sym->attr.dummy && sym->ns == gfc_current_ns)
4627         {
4628           entry = gfc_current_ns->entries;
4629           seen = false;
4630
4631           /* ...test if the symbol is a parameter of previous entries.  */
4632           for (; entry && entry->id <= current_entry_id; entry = entry->next)
4633             for (formal = entry->sym->formal; formal; formal = formal->next)
4634               {
4635                 if (formal->sym && sym->name == formal->sym->name)
4636                   seen = true;
4637               }
4638
4639           /*  If it has not been seen as a dummy, this is an error.  */
4640           if (!seen)
4641             {
4642               if (specification_expr)
4643                 gfc_error ("Variable '%s', used in a specification expression"
4644                            ", is referenced at %L before the ENTRY statement "
4645                            "in which it is a parameter",
4646                            sym->name, &cs_base->current->loc);
4647               else
4648                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
4649                            "statement in which it is a parameter",
4650                            sym->name, &cs_base->current->loc);
4651               t = FAILURE;
4652             }
4653         }
4654
4655       /* Now do the same check on the specification expressions.  */
4656       specification_expr = 1;
4657       if (sym->ts.type == BT_CHARACTER
4658           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
4659         t = FAILURE;
4660
4661       if (sym->as)
4662         for (n = 0; n < sym->as->rank; n++)
4663           {
4664              specification_expr = 1;
4665              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
4666                t = FAILURE;
4667              specification_expr = 1;
4668              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
4669                t = FAILURE;
4670           }
4671       specification_expr = 0;
4672
4673       if (t == SUCCESS)
4674         /* Update the symbol's entry level.  */
4675         sym->entry_id = current_entry_id + 1;
4676     }
4677
4678 resolve_procedure:
4679   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
4680     t = FAILURE;
4681
4682   /* F2008, C617 and C1229.  */
4683   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
4684       && gfc_is_coindexed (e))
4685     {
4686       gfc_ref *ref, *ref2 = NULL;
4687
4688       if (e->ts.type == BT_CLASS)
4689         {
4690           gfc_error ("Polymorphic subobject of coindexed object at %L",
4691                      &e->where);
4692           t = FAILURE;
4693         }
4694
4695       for (ref = e->ref; ref; ref = ref->next)
4696         {
4697           if (ref->type == REF_COMPONENT)
4698             ref2 = ref;
4699           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
4700             break;
4701         }
4702
4703       for ( ; ref; ref = ref->next)
4704         if (ref->type == REF_COMPONENT)
4705           break;
4706
4707       /* Expression itself is coindexed object.  */
4708       if (ref == NULL)
4709         {
4710           gfc_component *c;
4711           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
4712           for ( ; c; c = c->next)
4713             if (c->attr.allocatable && c->ts.type == BT_CLASS)
4714               {
4715                 gfc_error ("Coindexed object with polymorphic allocatable "
4716                          "subcomponent at %L", &e->where);
4717                 t = FAILURE;
4718                 break;
4719               }
4720         }
4721     }
4722
4723   return t;
4724 }
4725
4726
4727 /* Checks to see that the correct symbol has been host associated.
4728    The only situation where this arises is that in which a twice
4729    contained function is parsed after the host association is made.
4730    Therefore, on detecting this, change the symbol in the expression
4731    and convert the array reference into an actual arglist if the old
4732    symbol is a variable.  */
4733 static bool
4734 check_host_association (gfc_expr *e)
4735 {
4736   gfc_symbol *sym, *old_sym;
4737   gfc_symtree *st;
4738   int n;
4739   gfc_ref *ref;
4740   gfc_actual_arglist *arg, *tail = NULL;
4741   bool retval = e->expr_type == EXPR_FUNCTION;
4742
4743   /*  If the expression is the result of substitution in
4744       interface.c(gfc_extend_expr) because there is no way in
4745       which the host association can be wrong.  */
4746   if (e->symtree == NULL
4747         || e->symtree->n.sym == NULL
4748         || e->user_operator)
4749     return retval;
4750
4751   old_sym = e->symtree->n.sym;
4752
4753   if (gfc_current_ns->parent
4754         && old_sym->ns != gfc_current_ns)
4755     {
4756       /* Use the 'USE' name so that renamed module symbols are
4757          correctly handled.  */
4758       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
4759
4760       if (sym && old_sym != sym
4761               && sym->ts.type == old_sym->ts.type
4762               && sym->attr.flavor == FL_PROCEDURE
4763               && sym->attr.contained)
4764         {
4765           /* Clear the shape, since it might not be valid.  */
4766           if (e->shape != NULL)
4767             {
4768               for (n = 0; n < e->rank; n++)
4769                 mpz_clear (e->shape[n]);
4770
4771               gfc_free (e->shape);
4772             }
4773
4774           /* Give the expression the right symtree!  */
4775           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
4776           gcc_assert (st != NULL);
4777
4778           if (old_sym->attr.flavor == FL_PROCEDURE
4779                 || e->expr_type == EXPR_FUNCTION)
4780             {
4781               /* Original was function so point to the new symbol, since
4782                  the actual argument list is already attached to the
4783                  expression. */
4784               e->value.function.esym = NULL;
4785               e->symtree = st;
4786             }
4787           else
4788             {
4789               /* Original was variable so convert array references into
4790                  an actual arglist. This does not need any checking now
4791                  since gfc_resolve_function will take care of it.  */
4792               e->value.function.actual = NULL;
4793               e->expr_type = EXPR_FUNCTION;
4794               e->symtree = st;
4795
4796               /* Ambiguity will not arise if the array reference is not
4797                  the last reference.  */
4798               for (ref = e->ref; ref; ref = ref->next)
4799                 if (ref->type == REF_ARRAY && ref->next == NULL)
4800                   break;
4801
4802               gcc_assert (ref->type == REF_ARRAY);
4803
4804               /* Grab the start expressions from the array ref and
4805                  copy them into actual arguments.  */
4806               for (n = 0; n < ref->u.ar.dimen; n++)
4807                 {
4808                   arg = gfc_get_actual_arglist ();
4809                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
4810                   if (e->value.function.actual == NULL)
4811                     tail = e->value.function.actual = arg;
4812                   else
4813                     {
4814                       tail->next = arg;
4815                       tail = arg;
4816                     }
4817                 }
4818
4819               /* Dump the reference list and set the rank.  */
4820               gfc_free_ref_list (e->ref);
4821               e->ref = NULL;
4822               e->rank = sym->as ? sym->as->rank : 0;
4823             }
4824
4825           gfc_resolve_expr (e);
4826           sym->refs++;
4827         }
4828     }
4829   /* This might have changed!  */
4830   return e->expr_type == EXPR_FUNCTION;
4831 }
4832
4833
4834 static void
4835 gfc_resolve_character_operator (gfc_expr *e)
4836 {
4837   gfc_expr *op1 = e->value.op.op1;
4838   gfc_expr *op2 = e->value.op.op2;
4839   gfc_expr *e1 = NULL;
4840   gfc_expr *e2 = NULL;
4841
4842   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
4843
4844   if (op1->ts.u.cl && op1->ts.u.cl->length)
4845     e1 = gfc_copy_expr (op1->ts.u.cl->length);
4846   else if (op1->expr_type == EXPR_CONSTANT)
4847     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
4848                            op1->value.character.length);
4849
4850   if (op2->ts.u.cl && op2->ts.u.cl->length)
4851     e2 = gfc_copy_expr (op2->ts.u.cl->length);
4852   else if (op2->expr_type == EXPR_CONSTANT)
4853     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
4854                            op2->value.character.length);
4855
4856   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4857
4858   if (!e1 || !e2)
4859     return;
4860
4861   e->ts.u.cl->length = gfc_add (e1, e2);
4862   e->ts.u.cl->length->ts.type = BT_INTEGER;
4863   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4864   gfc_simplify_expr (e->ts.u.cl->length, 0);
4865   gfc_resolve_expr (e->ts.u.cl->length);
4866
4867   return;
4868 }
4869
4870
4871 /*  Ensure that an character expression has a charlen and, if possible, a
4872     length expression.  */
4873
4874 static void
4875 fixup_charlen (gfc_expr *e)
4876 {
4877   /* The cases fall through so that changes in expression type and the need
4878      for multiple fixes are picked up.  In all circumstances, a charlen should
4879      be available for the middle end to hang a backend_decl on.  */
4880   switch (e->expr_type)
4881     {
4882     case EXPR_OP:
4883       gfc_resolve_character_operator (e);
4884
4885     case EXPR_ARRAY:
4886       if (e->expr_type == EXPR_ARRAY)
4887         gfc_resolve_character_array_constructor (e);
4888
4889     case EXPR_SUBSTRING:
4890       if (!e->ts.u.cl && e->ref)
4891         gfc_resolve_substring_charlen (e);
4892
4893     default:
4894       if (!e->ts.u.cl)
4895         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4896
4897       break;
4898     }
4899 }
4900
4901
4902 /* Update an actual argument to include the passed-object for type-bound
4903    procedures at the right position.  */
4904
4905 static gfc_actual_arglist*
4906 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
4907                      const char *name)
4908 {
4909   gcc_assert (argpos > 0);
4910
4911   if (argpos == 1)
4912     {
4913       gfc_actual_arglist* result;
4914
4915       result = gfc_get_actual_arglist ();
4916       result->expr = po;
4917       result->next = lst;
4918       if (name)
4919         result->name = name;
4920
4921       return result;
4922     }
4923
4924   if (lst)
4925     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
4926   else
4927     lst = update_arglist_pass (NULL, po, argpos - 1, name);
4928   return lst;
4929 }
4930
4931
4932 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
4933
4934 static gfc_expr*
4935 extract_compcall_passed_object (gfc_expr* e)
4936 {
4937   gfc_expr* po;
4938
4939   gcc_assert (e->expr_type == EXPR_COMPCALL);
4940
4941   if (e->value.compcall.base_object)
4942     po = gfc_copy_expr (e->value.compcall.base_object);
4943   else
4944     {
4945       po = gfc_get_expr ();
4946       po->expr_type = EXPR_VARIABLE;
4947       po->symtree = e->symtree;
4948       po->ref = gfc_copy_ref (e->ref);
4949       po->where = e->where;
4950     }
4951
4952   if (gfc_resolve_expr (po) == FAILURE)
4953     return NULL;
4954
4955   return po;
4956 }
4957
4958
4959 /* Update the arglist of an EXPR_COMPCALL expression to include the
4960    passed-object.  */
4961
4962 static gfc_try
4963 update_compcall_arglist (gfc_expr* e)
4964 {
4965   gfc_expr* po;
4966   gfc_typebound_proc* tbp;
4967
4968   tbp = e->value.compcall.tbp;
4969
4970   if (tbp->error)
4971     return FAILURE;
4972
4973   po = extract_compcall_passed_object (e);
4974   if (!po)
4975     return FAILURE;
4976
4977   if (tbp->nopass || e->value.compcall.ignore_pass)
4978     {
4979       gfc_free_expr (po);
4980       return SUCCESS;
4981     }
4982
4983   gcc_assert (tbp->pass_arg_num > 0);
4984   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
4985                                                   tbp->pass_arg_num,
4986                                                   tbp->pass_arg);
4987
4988   return SUCCESS;
4989 }
4990
4991
4992 /* Extract the passed object from a PPC call (a copy of it).  */
4993
4994 static gfc_expr*
4995 extract_ppc_passed_object (gfc_expr *e)
4996 {
4997   gfc_expr *po;
4998   gfc_ref **ref;
4999
5000   po = gfc_get_expr ();
5001   po->expr_type = EXPR_VARIABLE;
5002   po->symtree = e->symtree;
5003   po->ref = gfc_copy_ref (e->ref);
5004   po->where = e->where;
5005
5006   /* Remove PPC reference.  */
5007   ref = &po->ref;
5008   while ((*ref)->next)
5009     ref = &(*ref)->next;
5010   gfc_free_ref_list (*ref);
5011   *ref = NULL;
5012
5013   if (gfc_resolve_expr (po) == FAILURE)
5014     return NULL;
5015
5016   return po;
5017 }
5018
5019
5020 /* Update the actual arglist of a procedure pointer component to include the
5021    passed-object.  */
5022
5023 static gfc_try
5024 update_ppc_arglist (gfc_expr* e)
5025 {
5026   gfc_expr* po;
5027   gfc_component *ppc;
5028   gfc_typebound_proc* tb;
5029
5030   if (!gfc_is_proc_ptr_comp (e, &ppc))
5031     return FAILURE;
5032
5033   tb = ppc->tb;
5034
5035   if (tb->error)
5036     return FAILURE;
5037   else if (tb->nopass)
5038     return SUCCESS;
5039
5040   po = extract_ppc_passed_object (e);
5041   if (!po)
5042     return FAILURE;
5043
5044   if (po->rank > 0)
5045     {
5046       gfc_error ("Passed-object at %L must be scalar", &e->where);
5047       return FAILURE;
5048     }
5049
5050   gcc_assert (tb->pass_arg_num > 0);
5051   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5052                                                   tb->pass_arg_num,
5053                                                   tb->pass_arg);
5054
5055   return SUCCESS;
5056 }
5057
5058
5059 /* Check that the object a TBP is called on is valid, i.e. it must not be
5060    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5061
5062 static gfc_try
5063 check_typebound_baseobject (gfc_expr* e)
5064 {
5065   gfc_expr* base;
5066
5067   base = extract_compcall_passed_object (e);
5068   if (!base)
5069     return FAILURE;
5070
5071   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5072
5073   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5074     {
5075       gfc_error ("Base object for type-bound procedure call at %L is of"
5076                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5077       return FAILURE;
5078     }
5079
5080   /* If the procedure called is NOPASS, the base object must be scalar.  */
5081   if (e->value.compcall.tbp->nopass && base->rank > 0)
5082     {
5083       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5084                  " be scalar", &e->where);
5085       return FAILURE;
5086     }
5087
5088   /* FIXME: Remove once PR 41177 (this problem) is fixed completely.  */
5089   if (base->rank > 0)
5090     {
5091       gfc_error ("Non-scalar base object at %L currently not implemented",
5092                  &e->where);
5093       return FAILURE;
5094     }
5095
5096   return SUCCESS;
5097 }
5098
5099
5100 /* Resolve a call to a type-bound procedure, either function or subroutine,
5101    statically from the data in an EXPR_COMPCALL expression.  The adapted
5102    arglist and the target-procedure symtree are returned.  */
5103
5104 static gfc_try
5105 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5106                           gfc_actual_arglist** actual)
5107 {
5108   gcc_assert (e->expr_type == EXPR_COMPCALL);
5109   gcc_assert (!e->value.compcall.tbp->is_generic);
5110
5111   /* Update the actual arglist for PASS.  */
5112   if (update_compcall_arglist (e) == FAILURE)
5113     return FAILURE;
5114
5115   *actual = e->value.compcall.actual;
5116   *target = e->value.compcall.tbp->u.specific;
5117
5118   gfc_free_ref_list (e->ref);
5119   e->ref = NULL;
5120   e->value.compcall.actual = NULL;
5121
5122   return SUCCESS;
5123 }
5124
5125
5126 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5127    which of the specific bindings (if any) matches the arglist and transform
5128    the expression into a call of that binding.  */
5129
5130 static gfc_try
5131 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5132 {
5133   gfc_typebound_proc* genproc;
5134   const char* genname;
5135
5136   gcc_assert (e->expr_type == EXPR_COMPCALL);
5137   genname = e->value.compcall.name;
5138   genproc = e->value.compcall.tbp;
5139
5140   if (!genproc->is_generic)
5141     return SUCCESS;
5142
5143   /* Try the bindings on this type and in the inheritance hierarchy.  */
5144   for (; genproc; genproc = genproc->overridden)
5145     {
5146       gfc_tbp_generic* g;
5147
5148       gcc_assert (genproc->is_generic);
5149       for (g = genproc->u.generic; g; g = g->next)
5150         {
5151           gfc_symbol* target;
5152           gfc_actual_arglist* args;
5153           bool matches;
5154
5155           gcc_assert (g->specific);
5156
5157           if (g->specific->error)
5158             continue;
5159
5160           target = g->specific->u.specific->n.sym;
5161
5162           /* Get the right arglist by handling PASS/NOPASS.  */
5163           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5164           if (!g->specific->nopass)
5165             {
5166               gfc_expr* po;
5167               po = extract_compcall_passed_object (e);
5168               if (!po)
5169                 return FAILURE;
5170
5171               gcc_assert (g->specific->pass_arg_num > 0);
5172               gcc_assert (!g->specific->error);
5173               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5174                                           g->specific->pass_arg);
5175             }
5176           resolve_actual_arglist (args, target->attr.proc,
5177                                   is_external_proc (target) && !target->formal);
5178
5179           /* Check if this arglist matches the formal.  */
5180           matches = gfc_arglist_matches_symbol (&args, target);
5181
5182           /* Clean up and break out of the loop if we've found it.  */
5183           gfc_free_actual_arglist (args);
5184           if (matches)
5185             {
5186               e->value.compcall.tbp = g->specific;
5187               /* Pass along the name for CLASS methods, where the vtab
5188                  procedure pointer component has to be referenced.  */
5189               if (name)
5190                 *name = g->specific_st->name;
5191               goto success;
5192             }
5193         }
5194     }
5195
5196   /* Nothing matching found!  */
5197   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5198              " '%s' at %L", genname, &e->where);
5199   return FAILURE;
5200
5201 success:
5202   return SUCCESS;
5203 }
5204
5205
5206 /* Resolve a call to a type-bound subroutine.  */
5207
5208 static gfc_try
5209 resolve_typebound_call (gfc_code* c, const char **name)
5210 {
5211   gfc_actual_arglist* newactual;
5212   gfc_symtree* target;
5213
5214   /* Check that's really a SUBROUTINE.  */
5215   if (!c->expr1->value.compcall.tbp->subroutine)
5216     {
5217       gfc_error ("'%s' at %L should be a SUBROUTINE",
5218                  c->expr1->value.compcall.name, &c->loc);
5219       return FAILURE;
5220     }
5221
5222   if (check_typebound_baseobject (c->expr1) == FAILURE)
5223     return FAILURE;
5224
5225   /* Pass along the name for CLASS methods, where the vtab
5226      procedure pointer component has to be referenced.  */
5227   if (name)
5228     *name = c->expr1->value.compcall.name;
5229
5230   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5231     return FAILURE;
5232
5233   /* Transform into an ordinary EXEC_CALL for now.  */
5234
5235   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5236     return FAILURE;
5237
5238   c->ext.actual = newactual;
5239   c->symtree = target;
5240   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5241
5242   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5243
5244   gfc_free_expr (c->expr1);
5245   c->expr1 = gfc_get_expr ();
5246   c->expr1->expr_type = EXPR_FUNCTION;
5247   c->expr1->symtree = target;
5248   c->expr1->where = c->loc;
5249
5250   return resolve_call (c);
5251 }
5252
5253
5254 /* Resolve a component-call expression.  */
5255 static gfc_try
5256 resolve_compcall (gfc_expr* e, const char **name)
5257 {
5258   gfc_actual_arglist* newactual;
5259   gfc_symtree* target;
5260
5261   /* Check that's really a FUNCTION.  */
5262   if (!e->value.compcall.tbp->function)
5263     {
5264       gfc_error ("'%s' at %L should be a FUNCTION",
5265                  e->value.compcall.name, &e->where);
5266       return FAILURE;
5267     }
5268
5269   /* These must not be assign-calls!  */
5270   gcc_assert (!e->value.compcall.assign);
5271
5272   if (check_typebound_baseobject (e) == FAILURE)
5273     return FAILURE;
5274
5275   /* Pass along the name for CLASS methods, where the vtab
5276      procedure pointer component has to be referenced.  */
5277   if (name)
5278     *name = e->value.compcall.name;
5279
5280   if (resolve_typebound_generic_call (e, name) == FAILURE)
5281     return FAILURE;
5282   gcc_assert (!e->value.compcall.tbp->is_generic);
5283
5284   /* Take the rank from the function's symbol.  */
5285   if (e->value.compcall.tbp->u.specific->n.sym->as)
5286     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5287
5288   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5289      arglist to the TBP's binding target.  */
5290
5291   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5292     return FAILURE;
5293
5294   e->value.function.actual = newactual;
5295   e->value.function.name = NULL;
5296   e->value.function.esym = target->n.sym;
5297   e->value.function.isym = NULL;
5298   e->symtree = target;
5299   e->ts = target->n.sym->ts;
5300   e->expr_type = EXPR_FUNCTION;
5301
5302   /* Resolution is not necessary if this is a class subroutine; this
5303      function only has to identify the specific proc. Resolution of
5304      the call will be done next in resolve_typebound_call.  */
5305   return gfc_resolve_expr (e);
5306 }
5307
5308
5309 /* Get the ultimate declared type from an expression.  In addition,
5310    return the last class/derived type reference and the copy of the
5311    reference list.  */
5312 static gfc_symbol*
5313 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5314                         gfc_expr *e)
5315 {
5316   gfc_symbol *declared;
5317   gfc_ref *ref;
5318
5319   declared = NULL;
5320   *class_ref = NULL;
5321   *new_ref = gfc_copy_ref (e->ref);
5322   for (ref = *new_ref; ref; ref = ref->next)
5323     {
5324       if (ref->type != REF_COMPONENT)
5325         continue;
5326
5327       if (ref->u.c.component->ts.type == BT_CLASS
5328             || ref->u.c.component->ts.type == BT_DERIVED)
5329         {
5330           declared = ref->u.c.component->ts.u.derived;
5331           *class_ref = ref;
5332         }
5333     }
5334
5335   if (declared == NULL)
5336     declared = e->symtree->n.sym->ts.u.derived;
5337
5338   return declared;
5339 }
5340
5341
5342 /* Resolve a typebound function, or 'method'. First separate all
5343    the non-CLASS references by calling resolve_compcall directly.  */
5344
5345 static gfc_try
5346 resolve_typebound_function (gfc_expr* e)
5347 {
5348   gfc_symbol *declared;
5349   gfc_component *c;
5350   gfc_ref *new_ref;
5351   gfc_ref *class_ref;
5352   gfc_symtree *st;
5353   const char *name;
5354   const char *genname;
5355   gfc_typespec ts;
5356
5357   st = e->symtree;
5358   if (st == NULL)
5359     return resolve_compcall (e, NULL);
5360
5361   /* Get the CLASS declared type.  */
5362   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5363
5364   /* Weed out cases of the ultimate component being a derived type.  */
5365   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5366          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5367     {
5368       gfc_free_ref_list (new_ref);
5369       return resolve_compcall (e, NULL);
5370     }
5371
5372   c = gfc_find_component (declared, "$data", true, true);
5373   declared = c->ts.u.derived;
5374
5375   /* Keep the generic name so that the vtab reference can be made.  */
5376   genname = NULL; 
5377   if (e->value.compcall.tbp->is_generic)
5378     genname = e->value.compcall.name;
5379
5380   /* Treat the call as if it is a typebound procedure, in order to roll
5381      out the correct name for the specific function.  */
5382   resolve_compcall (e, &name);
5383   ts = e->ts;
5384
5385   /* Then convert the expression to a procedure pointer component call.  */
5386   e->value.function.esym = NULL;
5387   e->symtree = st;
5388
5389   if (class_ref)  
5390     {
5391       gfc_free_ref_list (class_ref->next);
5392       e->ref = new_ref;
5393     }
5394
5395   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5396   gfc_add_component_ref (e, "$vptr");
5397   if (genname)
5398     {
5399       /* A generic procedure needs the subsidiary vtabs and vtypes for
5400          the specific procedures to have been build.  */
5401       gfc_symbol *vtab;
5402       vtab = gfc_find_derived_vtab (declared, true);
5403       gcc_assert (vtab);
5404       gfc_add_component_ref (e, genname);
5405     }
5406   gfc_add_component_ref (e, name);
5407
5408   /* Recover the typespec for the expression.  This is really only
5409      necessary for generic procedures, where the additional call
5410      to gfc_add_component_ref seems to throw the collection of the
5411      correct typespec.  */
5412   e->ts = ts;
5413   return SUCCESS;
5414 }
5415
5416 /* Resolve a typebound subroutine, or 'method'. First separate all
5417    the non-CLASS references by calling resolve_typebound_call
5418    directly.  */
5419
5420 static gfc_try
5421 resolve_typebound_subroutine (gfc_code *code)
5422 {
5423   gfc_symbol *declared;
5424   gfc_component *c;
5425   gfc_ref *new_ref;
5426   gfc_ref *class_ref;
5427   gfc_symtree *st;
5428   const char *genname;
5429   const char *name;
5430   gfc_typespec ts;
5431
5432   st = code->expr1->symtree;
5433   if (st == NULL)
5434     return resolve_typebound_call (code, NULL);
5435
5436   /* Get the CLASS declared type.  */
5437   declared = get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5438
5439   /* Weed out cases of the ultimate component being a derived type.  */
5440   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5441          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5442     {
5443       gfc_free_ref_list (new_ref);
5444       return resolve_typebound_call (code, NULL);
5445     } 
5446
5447   c = gfc_find_component (declared, "$data", true, true);
5448   declared = c->ts.u.derived;
5449
5450   /* Keep the generic name so that the vtab reference can be made.  */
5451   genname = NULL; 
5452   if (code->expr1->value.compcall.tbp->is_generic)
5453     genname = code->expr1->value.compcall.name;
5454
5455   resolve_typebound_call (code, &name);
5456   ts = code->expr1->ts;
5457
5458   /* Then convert the expression to a procedure pointer component call.  */
5459   code->expr1->value.function.esym = NULL;
5460   code->expr1->symtree = st;
5461
5462   if (class_ref)  
5463     {
5464       gfc_free_ref_list (class_ref->next);
5465       code->expr1->ref = new_ref;
5466     }
5467
5468   /* '$vptr' points to the vtab, which contains the procedure pointers.  */
5469   gfc_add_component_ref (code->expr1, "$vptr");
5470   if (genname)
5471     {
5472       /* A generic procedure needs the subsidiary vtabs and vtypes for
5473          the specific procedures to have been build.  */
5474       gfc_symbol *vtab;
5475       vtab = gfc_find_derived_vtab (declared, true);
5476       gcc_assert (vtab);
5477       gfc_add_component_ref (code->expr1, genname);
5478     }
5479   gfc_add_component_ref (code->expr1, name);
5480
5481   /* Recover the typespec for the expression.  This is really only
5482      necessary for generic procedures, where the additional call
5483      to gfc_add_component_ref seems to throw the collection of the
5484      correct typespec.  */
5485   code->expr1->ts = ts;
5486   return SUCCESS;
5487 }
5488
5489
5490 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5491
5492 static gfc_try
5493 resolve_ppc_call (gfc_code* c)
5494 {
5495   gfc_component *comp;
5496   bool b;
5497
5498   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5499   gcc_assert (b);
5500
5501   c->resolved_sym = c->expr1->symtree->n.sym;
5502   c->expr1->expr_type = EXPR_VARIABLE;
5503
5504   if (!comp->attr.subroutine)
5505     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5506
5507   if (resolve_ref (c->expr1) == FAILURE)
5508     return FAILURE;
5509
5510   if (update_ppc_arglist (c->expr1) == FAILURE)
5511     return FAILURE;
5512
5513   c->ext.actual = c->expr1->value.compcall.actual;
5514
5515   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
5516                               comp->formal == NULL) == FAILURE)
5517     return FAILURE;
5518
5519   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
5520
5521   return SUCCESS;
5522 }
5523
5524
5525 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
5526
5527 static gfc_try
5528 resolve_expr_ppc (gfc_expr* e)
5529 {
5530   gfc_component *comp;
5531   bool b;
5532
5533   b = gfc_is_proc_ptr_comp (e, &comp);
5534   gcc_assert (b);
5535
5536   /* Convert to EXPR_FUNCTION.  */
5537   e->expr_type = EXPR_FUNCTION;
5538   e->value.function.isym = NULL;
5539   e->value.function.actual = e->value.compcall.actual;
5540   e->ts = comp->ts;
5541   if (comp->as != NULL)
5542     e->rank = comp->as->rank;
5543
5544   if (!comp->attr.function)
5545     gfc_add_function (&comp->attr, comp->name, &e->where);
5546
5547   if (resolve_ref (e) == FAILURE)
5548     return FAILURE;
5549
5550   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
5551                               comp->formal == NULL) == FAILURE)
5552     return FAILURE;
5553
5554   if (update_ppc_arglist (e) == FAILURE)
5555     return FAILURE;
5556
5557   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
5558
5559   return SUCCESS;
5560 }
5561
5562
5563 static bool
5564 gfc_is_expandable_expr (gfc_expr *e)
5565 {
5566   gfc_constructor *con;
5567
5568   if (e->expr_type == EXPR_ARRAY)
5569     {
5570       /* Traverse the constructor looking for variables that are flavor
5571          parameter.  Parameters must be expanded since they are fully used at
5572          compile time.  */
5573       con = gfc_constructor_first (e->value.constructor);
5574       for (; con; con = gfc_constructor_next (con))
5575         {
5576           if (con->expr->expr_type == EXPR_VARIABLE
5577               && con->expr->symtree
5578               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
5579               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
5580             return true;
5581           if (con->expr->expr_type == EXPR_ARRAY
5582               && gfc_is_expandable_expr (con->expr))
5583             return true;
5584         }
5585     }
5586
5587   return false;
5588 }
5589
5590 /* Resolve an expression.  That is, make sure that types of operands agree
5591    with their operators, intrinsic operators are converted to function calls
5592    for overloaded types and unresolved function references are resolved.  */
5593
5594 gfc_try
5595 gfc_resolve_expr (gfc_expr *e)
5596 {
5597   gfc_try t;
5598   bool inquiry_save;
5599
5600   if (e == NULL)
5601     return SUCCESS;
5602
5603   /* inquiry_argument only applies to variables.  */
5604   inquiry_save = inquiry_argument;
5605   if (e->expr_type != EXPR_VARIABLE)
5606     inquiry_argument = false;
5607
5608   switch (e->expr_type)
5609     {
5610     case EXPR_OP:
5611       t = resolve_operator (e);
5612       break;
5613
5614     case EXPR_FUNCTION:
5615     case EXPR_VARIABLE:
5616
5617       if (check_host_association (e))
5618         t = resolve_function (e);
5619       else
5620         {
5621           t = resolve_variable (e);
5622           if (t == SUCCESS)
5623             expression_rank (e);
5624         }
5625
5626       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
5627           && e->ref->type != REF_SUBSTRING)
5628         gfc_resolve_substring_charlen (e);
5629
5630       break;
5631
5632     case EXPR_COMPCALL:
5633       t = resolve_typebound_function (e);
5634       break;
5635
5636     case EXPR_SUBSTRING:
5637       t = resolve_ref (e);
5638       break;
5639
5640     case EXPR_CONSTANT:
5641     case EXPR_NULL:
5642       t = SUCCESS;
5643       break;
5644
5645     case EXPR_PPC:
5646       t = resolve_expr_ppc (e);
5647       break;
5648
5649     case EXPR_ARRAY:
5650       t = FAILURE;
5651       if (resolve_ref (e) == FAILURE)
5652         break;
5653
5654       t = gfc_resolve_array_constructor (e);
5655       /* Also try to expand a constructor.  */
5656       if (t == SUCCESS)
5657         {
5658           expression_rank (e);
5659           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
5660             gfc_expand_constructor (e);
5661         }
5662
5663       /* This provides the opportunity for the length of constructors with
5664          character valued function elements to propagate the string length
5665          to the expression.  */
5666       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
5667         {
5668           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
5669              here rather then add a duplicate test for it above.  */ 
5670           gfc_expand_constructor (e);
5671           t = gfc_resolve_character_array_constructor (e);
5672         }
5673
5674       break;
5675
5676     case EXPR_STRUCTURE:
5677       t = resolve_ref (e);
5678       if (t == FAILURE)
5679         break;
5680
5681       t = resolve_structure_cons (e);
5682       if (t == FAILURE)
5683         break;
5684
5685       t = gfc_simplify_expr (e, 0);
5686       break;
5687
5688     default:
5689       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
5690     }
5691
5692   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
5693     fixup_charlen (e);
5694
5695   inquiry_argument = inquiry_save;
5696
5697   return t;
5698 }
5699
5700
5701 /* Resolve an expression from an iterator.  They must be scalar and have
5702    INTEGER or (optionally) REAL type.  */
5703
5704 static gfc_try
5705 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
5706                            const char *name_msgid)
5707 {
5708   if (gfc_resolve_expr (expr) == FAILURE)
5709     return FAILURE;
5710
5711   if (expr->rank != 0)
5712     {
5713       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
5714       return FAILURE;
5715     }
5716
5717   if (expr->ts.type != BT_INTEGER)
5718     {
5719       if (expr->ts.type == BT_REAL)
5720         {
5721           if (real_ok)
5722             return gfc_notify_std (GFC_STD_F95_DEL,
5723                                    "Deleted feature: %s at %L must be integer",
5724                                    _(name_msgid), &expr->where);
5725           else
5726             {
5727               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
5728                          &expr->where);
5729               return FAILURE;
5730             }
5731         }
5732       else
5733         {
5734           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
5735           return FAILURE;
5736         }
5737     }
5738   return SUCCESS;
5739 }
5740
5741
5742 /* Resolve the expressions in an iterator structure.  If REAL_OK is
5743    false allow only INTEGER type iterators, otherwise allow REAL types.  */
5744
5745 gfc_try
5746 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
5747 {
5748   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
5749       == FAILURE)
5750     return FAILURE;
5751
5752   if (gfc_pure (NULL) && gfc_impure_variable (iter->var->symtree->n.sym))
5753     {
5754       gfc_error ("Cannot assign to loop variable in PURE procedure at %L",
5755                  &iter->var->where);
5756       return FAILURE;
5757     }
5758
5759   if (gfc_resolve_iterator_expr (iter->start, real_ok,
5760                                  "Start expression in DO loop") == FAILURE)
5761     return FAILURE;
5762
5763   if (gfc_resolve_iterator_expr (iter->end, real_ok,
5764                                  "End expression in DO loop") == FAILURE)
5765     return FAILURE;
5766
5767   if (gfc_resolve_iterator_expr (iter->step, real_ok,
5768                                  "Step expression in DO loop") == FAILURE)
5769     return FAILURE;
5770
5771   if (iter->step->expr_type == EXPR_CONSTANT)
5772     {
5773       if ((iter->step->ts.type == BT_INTEGER
5774            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
5775           || (iter->step->ts.type == BT_REAL
5776               && mpfr_sgn (iter->step->value.real) == 0))
5777         {
5778           gfc_error ("Step expression in DO loop at %L cannot be zero",
5779                      &iter->step->where);
5780           return FAILURE;
5781         }
5782     }
5783
5784   /* Convert start, end, and step to the same type as var.  */
5785   if (iter->start->ts.kind != iter->var->ts.kind
5786       || iter->start->ts.type != iter->var->ts.type)
5787     gfc_convert_type (iter->start, &iter->var->ts, 2);
5788
5789   if (iter->end->ts.kind != iter->var->ts.kind
5790       || iter->end->ts.type != iter->var->ts.type)
5791     gfc_convert_type (iter->end, &iter->var->ts, 2);
5792
5793   if (iter->step->ts.kind != iter->var->ts.kind
5794       || iter->step->ts.type != iter->var->ts.type)
5795     gfc_convert_type (iter->step, &iter->var->ts, 2);
5796
5797   if (iter->start->expr_type == EXPR_CONSTANT
5798       && iter->end->expr_type == EXPR_CONSTANT
5799       && iter->step->expr_type == EXPR_CONSTANT)
5800     {
5801       int sgn, cmp;
5802       if (iter->start->ts.type == BT_INTEGER)
5803         {
5804           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
5805           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
5806         }
5807       else
5808         {
5809           sgn = mpfr_sgn (iter->step->value.real);
5810           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
5811         }
5812       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
5813         gfc_warning ("DO loop at %L will be executed zero times",
5814                      &iter->step->where);
5815     }
5816
5817   return SUCCESS;
5818 }
5819
5820
5821 /* Traversal function for find_forall_index.  f == 2 signals that
5822    that variable itself is not to be checked - only the references.  */
5823
5824 static bool
5825 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
5826 {
5827   if (expr->expr_type != EXPR_VARIABLE)
5828     return false;
5829   
5830   /* A scalar assignment  */
5831   if (!expr->ref || *f == 1)
5832     {
5833       if (expr->symtree->n.sym == sym)
5834         return true;
5835       else
5836         return false;
5837     }
5838
5839   if (*f == 2)
5840     *f = 1;
5841   return false;
5842 }
5843
5844
5845 /* Check whether the FORALL index appears in the expression or not.
5846    Returns SUCCESS if SYM is found in EXPR.  */
5847
5848 gfc_try
5849 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
5850 {
5851   if (gfc_traverse_expr (expr, sym, forall_index, f))
5852     return SUCCESS;
5853   else
5854     return FAILURE;
5855 }
5856
5857
5858 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
5859    to be a scalar INTEGER variable.  The subscripts and stride are scalar
5860    INTEGERs, and if stride is a constant it must be nonzero.
5861    Furthermore "A subscript or stride in a forall-triplet-spec shall
5862    not contain a reference to any index-name in the
5863    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
5864
5865 static void
5866 resolve_forall_iterators (gfc_forall_iterator *it)
5867 {
5868   gfc_forall_iterator *iter, *iter2;
5869
5870   for (iter = it; iter; iter = iter->next)
5871     {
5872       if (gfc_resolve_expr (iter->var) == SUCCESS
5873           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
5874         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
5875                    &iter->var->where);
5876
5877       if (gfc_resolve_expr (iter->start) == SUCCESS
5878           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
5879         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
5880                    &iter->start->where);
5881       if (iter->var->ts.kind != iter->start->ts.kind)
5882         gfc_convert_type (iter->start, &iter->var->ts, 2);
5883
5884       if (gfc_resolve_expr (iter->end) == SUCCESS
5885           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
5886         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
5887                    &iter->end->where);
5888       if (iter->var->ts.kind != iter->end->ts.kind)
5889         gfc_convert_type (iter->end, &iter->var->ts, 2);
5890
5891       if (gfc_resolve_expr (iter->stride) == SUCCESS)
5892         {
5893           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
5894             gfc_error ("FORALL stride expression at %L must be a scalar %s",
5895                        &iter->stride->where, "INTEGER");
5896
5897           if (iter->stride->expr_type == EXPR_CONSTANT
5898               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
5899             gfc_error ("FORALL stride expression at %L cannot be zero",
5900                        &iter->stride->where);
5901         }
5902       if (iter->var->ts.kind != iter->stride->ts.kind)
5903         gfc_convert_type (iter->stride, &iter->var->ts, 2);
5904     }
5905
5906   for (iter = it; iter; iter = iter->next)
5907     for (iter2 = iter; iter2; iter2 = iter2->next)
5908       {
5909         if (find_forall_index (iter2->start,
5910                                iter->var->symtree->n.sym, 0) == SUCCESS
5911             || find_forall_index (iter2->end,
5912                                   iter->var->symtree->n.sym, 0) == SUCCESS
5913             || find_forall_index (iter2->stride,
5914                                   iter->var->symtree->n.sym, 0) == SUCCESS)
5915           gfc_error ("FORALL index '%s' may not appear in triplet "
5916                      "specification at %L", iter->var->symtree->name,
5917                      &iter2->start->where);
5918       }
5919 }
5920
5921
5922 /* Given a pointer to a symbol that is a derived type, see if it's
5923    inaccessible, i.e. if it's defined in another module and the components are
5924    PRIVATE.  The search is recursive if necessary.  Returns zero if no
5925    inaccessible components are found, nonzero otherwise.  */
5926
5927 static int
5928 derived_inaccessible (gfc_symbol *sym)
5929 {
5930   gfc_component *c;
5931
5932   if (sym->attr.use_assoc && sym->attr.private_comp)
5933     return 1;
5934
5935   for (c = sym->components; c; c = c->next)
5936     {
5937         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
5938           return 1;
5939     }
5940
5941   return 0;
5942 }
5943
5944
5945 /* Resolve the argument of a deallocate expression.  The expression must be
5946    a pointer or a full array.  */
5947
5948 static gfc_try
5949 resolve_deallocate_expr (gfc_expr *e)
5950 {
5951   symbol_attribute attr;
5952   int allocatable, pointer, check_intent_in;
5953   gfc_ref *ref;
5954   gfc_symbol *sym;
5955   gfc_component *c;
5956
5957   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
5958   check_intent_in = 1;
5959
5960   if (gfc_resolve_expr (e) == FAILURE)
5961     return FAILURE;
5962
5963   if (e->expr_type != EXPR_VARIABLE)
5964     goto bad;
5965
5966   sym = e->symtree->n.sym;
5967
5968   if (sym->ts.type == BT_CLASS)
5969     {
5970       allocatable = sym->ts.u.derived->components->attr.allocatable;
5971       pointer = sym->ts.u.derived->components->attr.pointer;
5972     }
5973   else
5974     {
5975       allocatable = sym->attr.allocatable;
5976       pointer = sym->attr.pointer;
5977     }
5978   for (ref = e->ref; ref; ref = ref->next)
5979     {
5980       if (pointer)
5981         check_intent_in = 0;
5982
5983       switch (ref->type)
5984         {
5985         case REF_ARRAY:
5986           if (ref->u.ar.type != AR_FULL)
5987             allocatable = 0;
5988           break;
5989
5990         case REF_COMPONENT:
5991           c = ref->u.c.component;
5992           if (c->ts.type == BT_CLASS)
5993             {
5994               allocatable = c->ts.u.derived->components->attr.allocatable;
5995               pointer = c->ts.u.derived->components->attr.pointer;
5996             }
5997           else
5998             {
5999               allocatable = c->attr.allocatable;
6000               pointer = c->attr.pointer;
6001             }
6002           break;
6003
6004         case REF_SUBSTRING:
6005           allocatable = 0;
6006           break;
6007         }
6008     }
6009
6010   attr = gfc_expr_attr (e);
6011
6012   if (allocatable == 0 && attr.pointer == 0)
6013     {
6014     bad:
6015       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6016                  &e->where);
6017     }
6018
6019   if (check_intent_in && sym->attr.intent == INTENT_IN)
6020     {
6021       gfc_error ("Cannot deallocate INTENT(IN) variable '%s' at %L",
6022                  sym->name, &e->where);
6023       return FAILURE;
6024     }
6025
6026   if (e->ts.type == BT_CLASS)
6027     {
6028       /* Only deallocate the DATA component.  */
6029       gfc_add_component_ref (e, "$data");
6030     }
6031
6032   return SUCCESS;
6033 }
6034
6035
6036 /* Returns true if the expression e contains a reference to the symbol sym.  */
6037 static bool
6038 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6039 {
6040   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6041     return true;
6042
6043   return false;
6044 }
6045
6046 bool
6047 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6048 {
6049   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6050 }
6051
6052
6053 /* Given the expression node e for an allocatable/pointer of derived type to be
6054    allocated, get the expression node to be initialized afterwards (needed for
6055    derived types with default initializers, and derived types with allocatable
6056    components that need nullification.)  */
6057
6058 gfc_expr *
6059 gfc_expr_to_initialize (gfc_expr *e)
6060 {
6061   gfc_expr *result;
6062   gfc_ref *ref;
6063   int i;
6064
6065   result = gfc_copy_expr (e);
6066
6067   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6068   for (ref = result->ref; ref; ref = ref->next)
6069     if (ref->type == REF_ARRAY && ref->next == NULL)
6070       {
6071         ref->u.ar.type = AR_FULL;
6072
6073         for (i = 0; i < ref->u.ar.dimen; i++)
6074           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6075
6076         result->rank = ref->u.ar.dimen;
6077         break;
6078       }
6079
6080   return result;
6081 }
6082
6083
6084 /* Used in resolve_allocate_expr to check that a allocation-object and
6085    a source-expr are conformable.  This does not catch all possible 
6086    cases; in particular a runtime checking is needed.  */
6087
6088 static gfc_try
6089 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6090 {
6091   /* First compare rank.  */
6092   if (e2->ref && e1->rank != e2->ref->u.ar.as->rank)
6093     {
6094       gfc_error ("Source-expr at %L must be scalar or have the "
6095                  "same rank as the allocate-object at %L",
6096                  &e1->where, &e2->where);
6097       return FAILURE;
6098     }
6099
6100   if (e1->shape)
6101     {
6102       int i;
6103       mpz_t s;
6104
6105       mpz_init (s);
6106
6107       for (i = 0; i < e1->rank; i++)
6108         {
6109           if (e2->ref->u.ar.end[i])
6110             {
6111               mpz_set (s, e2->ref->u.ar.end[i]->value.integer);
6112               mpz_sub (s, s, e2->ref->u.ar.start[i]->value.integer);
6113               mpz_add_ui (s, s, 1);
6114             }
6115           else
6116             {
6117               mpz_set (s, e2->ref->u.ar.start[i]->value.integer);
6118             }
6119
6120           if (mpz_cmp (e1->shape[i], s) != 0)
6121             {
6122               gfc_error ("Source-expr at %L and allocate-object at %L must "
6123                          "have the same shape", &e1->where, &e2->where);
6124               mpz_clear (s);
6125               return FAILURE;
6126             }
6127         }
6128
6129       mpz_clear (s);
6130     }
6131
6132   return SUCCESS;
6133 }
6134
6135
6136 /* Resolve the expression in an ALLOCATE statement, doing the additional
6137    checks to see whether the expression is OK or not.  The expression must
6138    have a trailing array reference that gives the size of the array.  */
6139
6140 static gfc_try
6141 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6142 {
6143   int i, pointer, allocatable, dimension, check_intent_in, is_abstract;
6144   int codimension;
6145   symbol_attribute attr;
6146   gfc_ref *ref, *ref2;
6147   gfc_array_ref *ar;
6148   gfc_symbol *sym;
6149   gfc_alloc *a;
6150   gfc_component *c;
6151   gfc_expr *init_e;
6152
6153   /* Check INTENT(IN), unless the object is a sub-component of a pointer.  */
6154   check_intent_in = 1;
6155
6156   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6157      checking of coarrays.  */
6158   for (ref = e->ref; ref; ref = ref->next)
6159     if (ref->next == NULL)
6160       break;
6161
6162   if (ref && ref->type == REF_ARRAY)
6163     ref->u.ar.in_allocate = true;
6164
6165   if (gfc_resolve_expr (e) == FAILURE)
6166     goto failure;
6167
6168   /* Make sure the expression is allocatable or a pointer.  If it is
6169      pointer, the next-to-last reference must be a pointer.  */
6170
6171   ref2 = NULL;
6172   if (e->symtree)
6173     sym = e->symtree->n.sym;
6174
6175   /* Check whether ultimate component is abstract and CLASS.  */
6176   is_abstract = 0;
6177
6178   if (e->expr_type != EXPR_VARIABLE)
6179     {
6180       allocatable = 0;
6181       attr = gfc_expr_attr (e);
6182       pointer = attr.pointer;
6183       dimension = attr.dimension;
6184       codimension = attr.codimension;
6185     }
6186   else
6187     {
6188       if (sym->ts.type == BT_CLASS)
6189         {
6190           allocatable = sym->ts.u.derived->components->attr.allocatable;
6191           pointer = sym->ts.u.derived->components->attr.pointer;
6192           dimension = sym->ts.u.derived->components->attr.dimension;
6193           codimension = sym->ts.u.derived->components->attr.codimension;
6194           is_abstract = sym->ts.u.derived->components->attr.abstract;
6195         }
6196       else
6197         {
6198           allocatable = sym->attr.allocatable;
6199           pointer = sym->attr.pointer;
6200           dimension = sym->attr.dimension;
6201           codimension = sym->attr.codimension;
6202         }
6203
6204       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6205         {
6206           if (pointer)
6207             check_intent_in = 0;
6208
6209           switch (ref->type)
6210             {
6211               case REF_ARRAY:
6212                 if (ref->next != NULL)
6213                   pointer = 0;
6214                 break;
6215
6216               case REF_COMPONENT:
6217                 /* F2008, C644.  */
6218                 if (gfc_is_coindexed (e))
6219                   {
6220                     gfc_error ("Coindexed allocatable object at %L",
6221                                &e->where);
6222                     goto failure;
6223                   }
6224
6225                 c = ref->u.c.component;
6226                 if (c->ts.type == BT_CLASS)
6227                   {
6228                     allocatable = c->ts.u.derived->components->attr.allocatable;
6229                     pointer = c->ts.u.derived->components->attr.pointer;
6230                     dimension = c->ts.u.derived->components->attr.dimension;
6231                     codimension = c->ts.u.derived->components->attr.codimension;
6232                     is_abstract = c->ts.u.derived->components->attr.abstract;
6233                   }
6234                 else
6235                   {
6236                     allocatable = c->attr.allocatable;
6237                     pointer = c->attr.pointer;
6238                     dimension = c->attr.dimension;
6239                     codimension = c->attr.codimension;
6240                     is_abstract = c->attr.abstract;
6241                   }
6242                 break;
6243
6244               case REF_SUBSTRING:
6245                 allocatable = 0;
6246                 pointer = 0;
6247                 break;
6248             }
6249         }
6250     }
6251
6252   if (allocatable == 0 && pointer == 0)
6253     {
6254       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6255                  &e->where);
6256       goto failure;
6257     }
6258
6259   /* Some checks for the SOURCE tag.  */
6260   if (code->expr3)
6261     {
6262       /* Check F03:C631.  */
6263       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6264         {
6265           gfc_error ("Type of entity at %L is type incompatible with "
6266                       "source-expr at %L", &e->where, &code->expr3->where);
6267           goto failure;
6268         }
6269
6270       /* Check F03:C632 and restriction following Note 6.18.  */
6271       if (code->expr3->rank > 0
6272           && conformable_arrays (code->expr3, e) == FAILURE)
6273         goto failure;
6274
6275       /* Check F03:C633.  */
6276       if (code->expr3->ts.kind != e->ts.kind)
6277         {
6278           gfc_error ("The allocate-object at %L and the source-expr at %L "
6279                       "shall have the same kind type parameter",
6280                       &e->where, &code->expr3->where);
6281           goto failure;
6282         }
6283     }
6284   else if (is_abstract&& code->ext.alloc.ts.type == BT_UNKNOWN)
6285     {
6286       gcc_assert (e->ts.type == BT_CLASS);
6287       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6288                  "type-spec or SOURCE=", sym->name, &e->where);
6289       goto failure;
6290     }
6291
6292   if (check_intent_in && sym->attr.intent == INTENT_IN)
6293     {
6294       gfc_error ("Cannot allocate INTENT(IN) variable '%s' at %L",
6295                  sym->name, &e->where);
6296       goto failure;
6297     }
6298     
6299   if (!code->expr3)
6300     {
6301       /* Add default initializer for those derived types that need them.  */
6302       if (e->ts.type == BT_DERIVED
6303           && (init_e = gfc_default_initializer (&e->ts)))
6304         {
6305           gfc_code *init_st = gfc_get_code ();
6306           init_st->loc = code->loc;
6307           init_st->op = EXEC_INIT_ASSIGN;
6308           init_st->expr1 = gfc_expr_to_initialize (e);
6309           init_st->expr2 = init_e;
6310           init_st->next = code->next;
6311           code->next = init_st;
6312         }
6313       else if (e->ts.type == BT_CLASS
6314                && ((code->ext.alloc.ts.type == BT_UNKNOWN
6315                     && (init_e = gfc_default_initializer (&e->ts.u.derived->components->ts)))
6316                    || (code->ext.alloc.ts.type == BT_DERIVED
6317                        && (init_e = gfc_default_initializer (&code->ext.alloc.ts)))))
6318         {
6319           gfc_code *init_st = gfc_get_code ();
6320           init_st->loc = code->loc;
6321           init_st->op = EXEC_INIT_ASSIGN;
6322           init_st->expr1 = gfc_expr_to_initialize (e);
6323           init_st->expr2 = init_e;
6324           init_st->next = code->next;
6325           code->next = init_st;
6326         }
6327     }
6328
6329   if (pointer || (dimension == 0 && codimension == 0))
6330     goto success;
6331
6332   /* Make sure the next-to-last reference node is an array specification.  */
6333
6334   if (ref2 == NULL || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6335       || (dimension && ref2->u.ar.dimen == 0))
6336     {
6337       gfc_error ("Array specification required in ALLOCATE statement "
6338                  "at %L", &e->where);
6339       goto failure;
6340     }
6341
6342   /* Make sure that the array section reference makes sense in the
6343     context of an ALLOCATE specification.  */
6344
6345   ar = &ref2->u.ar;
6346
6347   if (codimension && ar->codimen == 0)
6348     {
6349       gfc_error ("Coarray specification required in ALLOCATE statement "
6350                  "at %L", &e->where);
6351       goto failure;
6352     }
6353
6354   for (i = 0; i < ar->dimen; i++)
6355     {
6356       if (ref2->u.ar.type == AR_ELEMENT)
6357         goto check_symbols;
6358
6359       switch (ar->dimen_type[i])
6360         {
6361         case DIMEN_ELEMENT:
6362           break;
6363
6364         case DIMEN_RANGE:
6365           if (ar->start[i] != NULL
6366               && ar->end[i] != NULL
6367               && ar->stride[i] == NULL)
6368             break;
6369
6370           /* Fall Through...  */
6371
6372         case DIMEN_UNKNOWN:
6373         case DIMEN_VECTOR:
6374         case DIMEN_STAR:
6375           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6376                      &e->where);
6377           goto failure;
6378         }
6379
6380 check_symbols:
6381       for (a = code->ext.alloc.list; a; a = a->next)
6382         {
6383           sym = a->expr->symtree->n.sym;
6384
6385           /* TODO - check derived type components.  */
6386           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6387             continue;
6388
6389           if ((ar->start[i] != NULL
6390                && gfc_find_sym_in_expr (sym, ar->start[i]))
6391               || (ar->end[i] != NULL
6392                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6393             {
6394               gfc_error ("'%s' must not appear in the array specification at "
6395                          "%L in the same ALLOCATE statement where it is "
6396                          "itself allocated", sym->name, &ar->where);
6397               goto failure;
6398             }
6399         }
6400     }
6401
6402   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6403     {
6404       if (ar->dimen_type[i] == DIMEN_ELEMENT
6405           || ar->dimen_type[i] == DIMEN_RANGE)
6406         {
6407           if (i == (ar->dimen + ar->codimen - 1))
6408             {
6409               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6410                          "statement at %L", &e->where);
6411               goto failure;
6412             }
6413           break;
6414         }
6415
6416       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6417           && ar->stride[i] == NULL)
6418         break;
6419
6420       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6421                  &e->where);
6422       goto failure;
6423     }
6424
6425   if (codimension && ar->as->rank == 0)
6426     {
6427       gfc_error ("Sorry, allocatable scalar coarrays are not yet supported "
6428                  "at %L", &e->where);
6429       goto failure;
6430     }
6431
6432 success:
6433   return SUCCESS;
6434
6435 failure:
6436   return FAILURE;
6437 }
6438
6439 static void
6440 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6441 {
6442   gfc_expr *stat, *errmsg, *pe, *qe;
6443   gfc_alloc *a, *p, *q;
6444
6445   stat = code->expr1 ? code->expr1 : NULL;
6446
6447   errmsg = code->expr2 ? code->expr2 : NULL;
6448
6449   /* Check the stat variable.  */
6450   if (stat)
6451     {
6452       if (stat->symtree->n.sym->attr.intent == INTENT_IN)
6453         gfc_error ("Stat-variable '%s' at %L cannot be INTENT(IN)",
6454                    stat->symtree->n.sym->name, &stat->where);
6455
6456       if (gfc_pure (NULL) && gfc_impure_variable (stat->symtree->n.sym))
6457         gfc_error ("Illegal stat-variable at %L for a PURE procedure",
6458                    &stat->where);
6459
6460       if ((stat->ts.type != BT_INTEGER
6461            && !(stat->ref && (stat->ref->type == REF_ARRAY
6462                               || stat->ref->type == REF_COMPONENT)))
6463           || stat->rank > 0)
6464         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
6465                    "variable", &stat->where);
6466
6467       for (p = code->ext.alloc.list; p; p = p->next)
6468         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
6469           gfc_error ("Stat-variable at %L shall not be %sd within "
6470                      "the same %s statement", &stat->where, fcn, fcn);
6471     }
6472
6473   /* Check the errmsg variable.  */
6474   if (errmsg)
6475     {
6476       if (!stat)
6477         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
6478                      &errmsg->where);
6479
6480       if (errmsg->symtree->n.sym->attr.intent == INTENT_IN)
6481         gfc_error ("Errmsg-variable '%s' at %L cannot be INTENT(IN)",
6482                    errmsg->symtree->n.sym->name, &errmsg->where);
6483
6484       if (gfc_pure (NULL) && gfc_impure_variable (errmsg->symtree->n.sym))
6485         gfc_error ("Illegal errmsg-variable at %L for a PURE procedure",
6486                    &errmsg->where);
6487
6488       if ((errmsg->ts.type != BT_CHARACTER
6489            && !(errmsg->ref
6490                 && (errmsg->ref->type == REF_ARRAY
6491                     || errmsg->ref->type == REF_COMPONENT)))
6492           || errmsg->rank > 0 )
6493         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
6494                    "variable", &errmsg->where);
6495
6496       for (p = code->ext.alloc.list; p; p = p->next)
6497         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
6498           gfc_error ("Errmsg-variable at %L shall not be %sd within "
6499                      "the same %s statement", &errmsg->where, fcn, fcn);
6500     }
6501
6502   /* Check that an allocate-object appears only once in the statement.  
6503      FIXME: Checking derived types is disabled.  */
6504   for (p = code->ext.alloc.list; p; p = p->next)
6505     {
6506       pe = p->expr;
6507       if ((pe->ref && pe->ref->type != REF_COMPONENT)
6508            && (pe->symtree->n.sym->ts.type != BT_DERIVED))
6509         {
6510           for (q = p->next; q; q = q->next)
6511             {
6512               qe = q->expr;
6513               if ((qe->ref && qe->ref->type != REF_COMPONENT)
6514                   && (qe->symtree->n.sym->ts.type != BT_DERIVED)
6515                   && (pe->symtree->n.sym->name == qe->symtree->n.sym->name))
6516                 gfc_error ("Allocate-object at %L also appears at %L",
6517                            &pe->where, &qe->where);
6518             }
6519         }
6520     }
6521
6522   if (strcmp (fcn, "ALLOCATE") == 0)
6523     {
6524       for (a = code->ext.alloc.list; a; a = a->next)
6525         resolve_allocate_expr (a->expr, code);
6526     }
6527   else
6528     {
6529       for (a = code->ext.alloc.list; a; a = a->next)
6530         resolve_deallocate_expr (a->expr);
6531     }
6532 }
6533
6534
6535 /************ SELECT CASE resolution subroutines ************/
6536
6537 /* Callback function for our mergesort variant.  Determines interval
6538    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
6539    op1 > op2.  Assumes we're not dealing with the default case.  
6540    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
6541    There are nine situations to check.  */
6542
6543 static int
6544 compare_cases (const gfc_case *op1, const gfc_case *op2)
6545 {
6546   int retval;
6547
6548   if (op1->low == NULL) /* op1 = (:L)  */
6549     {
6550       /* op2 = (:N), so overlap.  */
6551       retval = 0;
6552       /* op2 = (M:) or (M:N),  L < M  */
6553       if (op2->low != NULL
6554           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6555         retval = -1;
6556     }
6557   else if (op1->high == NULL) /* op1 = (K:)  */
6558     {
6559       /* op2 = (M:), so overlap.  */
6560       retval = 0;
6561       /* op2 = (:N) or (M:N), K > N  */
6562       if (op2->high != NULL
6563           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6564         retval = 1;
6565     }
6566   else /* op1 = (K:L)  */
6567     {
6568       if (op2->low == NULL)       /* op2 = (:N), K > N  */
6569         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6570                  ? 1 : 0;
6571       else if (op2->high == NULL) /* op2 = (M:), L < M  */
6572         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6573                  ? -1 : 0;
6574       else                      /* op2 = (M:N)  */
6575         {
6576           retval =  0;
6577           /* L < M  */
6578           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
6579             retval =  -1;
6580           /* K > N  */
6581           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
6582             retval =  1;
6583         }
6584     }
6585
6586   return retval;
6587 }
6588
6589
6590 /* Merge-sort a double linked case list, detecting overlap in the
6591    process.  LIST is the head of the double linked case list before it
6592    is sorted.  Returns the head of the sorted list if we don't see any
6593    overlap, or NULL otherwise.  */
6594
6595 static gfc_case *
6596 check_case_overlap (gfc_case *list)
6597 {
6598   gfc_case *p, *q, *e, *tail;
6599   int insize, nmerges, psize, qsize, cmp, overlap_seen;
6600
6601   /* If the passed list was empty, return immediately.  */
6602   if (!list)
6603     return NULL;
6604
6605   overlap_seen = 0;
6606   insize = 1;
6607
6608   /* Loop unconditionally.  The only exit from this loop is a return
6609      statement, when we've finished sorting the case list.  */
6610   for (;;)
6611     {
6612       p = list;
6613       list = NULL;
6614       tail = NULL;
6615
6616       /* Count the number of merges we do in this pass.  */
6617       nmerges = 0;
6618
6619       /* Loop while there exists a merge to be done.  */
6620       while (p)
6621         {
6622           int i;
6623
6624           /* Count this merge.  */
6625           nmerges++;
6626
6627           /* Cut the list in two pieces by stepping INSIZE places
6628              forward in the list, starting from P.  */
6629           psize = 0;
6630           q = p;
6631           for (i = 0; i < insize; i++)
6632             {
6633               psize++;
6634               q = q->right;
6635               if (!q)
6636                 break;
6637             }
6638           qsize = insize;
6639
6640           /* Now we have two lists.  Merge them!  */
6641           while (psize > 0 || (qsize > 0 && q != NULL))
6642             {
6643               /* See from which the next case to merge comes from.  */
6644               if (psize == 0)
6645                 {
6646                   /* P is empty so the next case must come from Q.  */
6647                   e = q;
6648                   q = q->right;
6649                   qsize--;
6650                 }
6651               else if (qsize == 0 || q == NULL)
6652                 {
6653                   /* Q is empty.  */
6654                   e = p;
6655                   p = p->right;
6656                   psize--;
6657                 }
6658               else
6659                 {
6660                   cmp = compare_cases (p, q);
6661                   if (cmp < 0)
6662                     {
6663                       /* The whole case range for P is less than the
6664                          one for Q.  */
6665                       e = p;
6666                       p = p->right;
6667                       psize--;
6668                     }
6669                   else if (cmp > 0)
6670                     {
6671                       /* The whole case range for Q is greater than
6672                          the case range for P.  */
6673                       e = q;
6674                       q = q->right;
6675                       qsize--;
6676                     }
6677                   else
6678                     {
6679                       /* The cases overlap, or they are the same
6680                          element in the list.  Either way, we must
6681                          issue an error and get the next case from P.  */
6682                       /* FIXME: Sort P and Q by line number.  */
6683                       gfc_error ("CASE label at %L overlaps with CASE "
6684                                  "label at %L", &p->where, &q->where);
6685                       overlap_seen = 1;
6686                       e = p;
6687                       p = p->right;
6688                       psize--;
6689                     }
6690                 }
6691
6692                 /* Add the next element to the merged list.  */
6693               if (tail)
6694                 tail->right = e;
6695               else
6696                 list = e;
6697               e->left = tail;
6698               tail = e;
6699             }
6700
6701           /* P has now stepped INSIZE places along, and so has Q.  So
6702              they're the same.  */
6703           p = q;
6704         }
6705       tail->right = NULL;
6706
6707       /* If we have done only one merge or none at all, we've
6708          finished sorting the cases.  */
6709       if (nmerges <= 1)
6710         {
6711           if (!overlap_seen)
6712             return list;
6713           else
6714             return NULL;
6715         }
6716
6717       /* Otherwise repeat, merging lists twice the size.  */
6718       insize *= 2;
6719     }
6720 }
6721
6722
6723 /* Check to see if an expression is suitable for use in a CASE statement.
6724    Makes sure that all case expressions are scalar constants of the same
6725    type.  Return FAILURE if anything is wrong.  */
6726
6727 static gfc_try
6728 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
6729 {
6730   if (e == NULL) return SUCCESS;
6731
6732   if (e->ts.type != case_expr->ts.type)
6733     {
6734       gfc_error ("Expression in CASE statement at %L must be of type %s",
6735                  &e->where, gfc_basic_typename (case_expr->ts.type));
6736       return FAILURE;
6737     }
6738
6739   /* C805 (R808) For a given case-construct, each case-value shall be of
6740      the same type as case-expr.  For character type, length differences
6741      are allowed, but the kind type parameters shall be the same.  */
6742
6743   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
6744     {
6745       gfc_error ("Expression in CASE statement at %L must be of kind %d",
6746                  &e->where, case_expr->ts.kind);
6747       return FAILURE;
6748     }
6749
6750   /* Convert the case value kind to that of case expression kind, if needed.
6751      FIXME:  Should a warning be issued?  */
6752   if (e->ts.kind != case_expr->ts.kind)
6753     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
6754
6755   if (e->rank != 0)
6756     {
6757       gfc_error ("Expression in CASE statement at %L must be scalar",
6758                  &e->where);
6759       return FAILURE;
6760     }
6761
6762   return SUCCESS;
6763 }
6764
6765
6766 /* Given a completely parsed select statement, we:
6767
6768      - Validate all expressions and code within the SELECT.
6769      - Make sure that the selection expression is not of the wrong type.
6770      - Make sure that no case ranges overlap.
6771      - Eliminate unreachable cases and unreachable code resulting from
6772        removing case labels.
6773
6774    The standard does allow unreachable cases, e.g. CASE (5:3).  But
6775    they are a hassle for code generation, and to prevent that, we just
6776    cut them out here.  This is not necessary for overlapping cases
6777    because they are illegal and we never even try to generate code.
6778
6779    We have the additional caveat that a SELECT construct could have
6780    been a computed GOTO in the source code. Fortunately we can fairly
6781    easily work around that here: The case_expr for a "real" SELECT CASE
6782    is in code->expr1, but for a computed GOTO it is in code->expr2. All
6783    we have to do is make sure that the case_expr is a scalar integer
6784    expression.  */
6785
6786 static void
6787 resolve_select (gfc_code *code)
6788 {
6789   gfc_code *body;
6790   gfc_expr *case_expr;
6791   gfc_case *cp, *default_case, *tail, *head;
6792   int seen_unreachable;
6793   int seen_logical;
6794   int ncases;
6795   bt type;
6796   gfc_try t;
6797
6798   if (code->expr1 == NULL)
6799     {
6800       /* This was actually a computed GOTO statement.  */
6801       case_expr = code->expr2;
6802       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
6803         gfc_error ("Selection expression in computed GOTO statement "
6804                    "at %L must be a scalar integer expression",
6805                    &case_expr->where);
6806
6807       /* Further checking is not necessary because this SELECT was built
6808          by the compiler, so it should always be OK.  Just move the
6809          case_expr from expr2 to expr so that we can handle computed
6810          GOTOs as normal SELECTs from here on.  */
6811       code->expr1 = code->expr2;
6812       code->expr2 = NULL;
6813       return;
6814     }
6815
6816   case_expr = code->expr1;
6817
6818   type = case_expr->ts.type;
6819   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
6820     {
6821       gfc_error ("Argument of SELECT statement at %L cannot be %s",
6822                  &case_expr->where, gfc_typename (&case_expr->ts));
6823
6824       /* Punt. Going on here just produce more garbage error messages.  */
6825       return;
6826     }
6827
6828   if (case_expr->rank != 0)
6829     {
6830       gfc_error ("Argument of SELECT statement at %L must be a scalar "
6831                  "expression", &case_expr->where);
6832
6833       /* Punt.  */
6834       return;
6835     }
6836
6837   /* PR 19168 has a long discussion concerning a mismatch of the kinds
6838      of the SELECT CASE expression and its CASE values.  Walk the lists
6839      of case values, and if we find a mismatch, promote case_expr to
6840      the appropriate kind.  */
6841
6842   if (type == BT_LOGICAL || type == BT_INTEGER)
6843     {
6844       for (body = code->block; body; body = body->block)
6845         {
6846           /* Walk the case label list.  */
6847           for (cp = body->ext.case_list; cp; cp = cp->next)
6848             {
6849               /* Intercept the DEFAULT case.  It does not have a kind.  */
6850               if (cp->low == NULL && cp->high == NULL)
6851                 continue;
6852
6853               /* Unreachable case ranges are discarded, so ignore.  */
6854               if (cp->low != NULL && cp->high != NULL
6855                   && cp->low != cp->high
6856                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
6857                 continue;
6858
6859               /* FIXME: Should a warning be issued?  */
6860               if (cp->low != NULL
6861                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
6862                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
6863
6864               if (cp->high != NULL
6865                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
6866                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
6867             }
6868          }
6869     }
6870
6871   /* Assume there is no DEFAULT case.  */
6872   default_case = NULL;
6873   head = tail = NULL;
6874   ncases = 0;
6875   seen_logical = 0;
6876
6877   for (body = code->block; body; body = body->block)
6878     {
6879       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
6880       t = SUCCESS;
6881       seen_unreachable = 0;
6882
6883       /* Walk the case label list, making sure that all case labels
6884          are legal.  */
6885       for (cp = body->ext.case_list; cp; cp = cp->next)
6886         {
6887           /* Count the number of cases in the whole construct.  */
6888           ncases++;
6889
6890           /* Intercept the DEFAULT case.  */
6891           if (cp->low == NULL && cp->high == NULL)
6892             {
6893               if (default_case != NULL)
6894                 {
6895                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
6896                              "by a second DEFAULT CASE at %L",
6897                              &default_case->where, &cp->where);
6898                   t = FAILURE;
6899                   break;
6900                 }
6901               else
6902                 {
6903                   default_case = cp;
6904                   continue;
6905                 }
6906             }
6907
6908           /* Deal with single value cases and case ranges.  Errors are
6909              issued from the validation function.  */
6910           if(validate_case_label_expr (cp->low, case_expr) != SUCCESS
6911              || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
6912             {
6913               t = FAILURE;
6914               break;
6915             }
6916
6917           if (type == BT_LOGICAL
6918               && ((cp->low == NULL || cp->high == NULL)
6919                   || cp->low != cp->high))
6920             {
6921               gfc_error ("Logical range in CASE statement at %L is not "
6922                          "allowed", &cp->low->where);
6923               t = FAILURE;
6924               break;
6925             }
6926
6927           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
6928             {
6929               int value;
6930               value = cp->low->value.logical == 0 ? 2 : 1;
6931               if (value & seen_logical)
6932                 {
6933                   gfc_error ("constant logical value in CASE statement "
6934                              "is repeated at %L",
6935                              &cp->low->where);
6936                   t = FAILURE;
6937                   break;
6938                 }
6939               seen_logical |= value;
6940             }
6941
6942           if (cp->low != NULL && cp->high != NULL
6943               && cp->low != cp->high
6944               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
6945             {
6946               if (gfc_option.warn_surprising)
6947                 gfc_warning ("Range specification at %L can never "
6948                              "be matched", &cp->where);
6949
6950               cp->unreachable = 1;
6951               seen_unreachable = 1;
6952             }
6953           else
6954             {
6955               /* If the case range can be matched, it can also overlap with
6956                  other cases.  To make sure it does not, we put it in a
6957                  double linked list here.  We sort that with a merge sort
6958                  later on to detect any overlapping cases.  */
6959               if (!head)
6960                 {
6961                   head = tail = cp;
6962                   head->right = head->left = NULL;
6963                 }
6964               else
6965                 {
6966                   tail->right = cp;
6967                   tail->right->left = tail;
6968                   tail = tail->right;
6969                   tail->right = NULL;
6970                 }
6971             }
6972         }
6973
6974       /* It there was a failure in the previous case label, give up
6975          for this case label list.  Continue with the next block.  */
6976       if (t == FAILURE)
6977         continue;
6978
6979       /* See if any case labels that are unreachable have been seen.
6980          If so, we eliminate them.  This is a bit of a kludge because
6981          the case lists for a single case statement (label) is a
6982          single forward linked lists.  */
6983       if (seen_unreachable)
6984       {
6985         /* Advance until the first case in the list is reachable.  */
6986         while (body->ext.case_list != NULL
6987                && body->ext.case_list->unreachable)
6988           {
6989             gfc_case *n = body->ext.case_list;
6990             body->ext.case_list = body->ext.case_list->next;
6991             n->next = NULL;
6992             gfc_free_case_list (n);
6993           }
6994
6995         /* Strip all other unreachable cases.  */
6996         if (body->ext.case_list)
6997           {
6998             for (cp = body->ext.case_list; cp->next; cp = cp->next)
6999               {
7000                 if (cp->next->unreachable)
7001                   {
7002                     gfc_case *n = cp->next;
7003                     cp->next = cp->next->next;
7004                     n->next = NULL;
7005                     gfc_free_case_list (n);
7006                   }
7007               }
7008           }
7009       }
7010     }
7011
7012   /* See if there were overlapping cases.  If the check returns NULL,
7013      there was overlap.  In that case we don't do anything.  If head
7014      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7015      then used during code generation for SELECT CASE constructs with
7016      a case expression of a CHARACTER type.  */
7017   if (head)
7018     {
7019       head = check_case_overlap (head);
7020
7021       /* Prepend the default_case if it is there.  */
7022       if (head != NULL && default_case)
7023         {
7024           default_case->left = NULL;
7025           default_case->right = head;
7026           head->left = default_case;
7027         }
7028     }
7029
7030   /* Eliminate dead blocks that may be the result if we've seen
7031      unreachable case labels for a block.  */
7032   for (body = code; body && body->block; body = body->block)
7033     {
7034       if (body->block->ext.case_list == NULL)
7035         {
7036           /* Cut the unreachable block from the code chain.  */
7037           gfc_code *c = body->block;
7038           body->block = c->block;
7039
7040           /* Kill the dead block, but not the blocks below it.  */
7041           c->block = NULL;
7042           gfc_free_statements (c);
7043         }
7044     }
7045
7046   /* More than two cases is legal but insane for logical selects.
7047      Issue a warning for it.  */
7048   if (gfc_option.warn_surprising && type == BT_LOGICAL
7049       && ncases > 2)
7050     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7051                  &code->loc);
7052 }
7053
7054
7055 /* Check if a derived type is extensible.  */
7056
7057 bool
7058 gfc_type_is_extensible (gfc_symbol *sym)
7059 {
7060   return !(sym->attr.is_bind_c || sym->attr.sequence);
7061 }
7062
7063
7064 /* Resolve a SELECT TYPE statement.  */
7065
7066 static void
7067 resolve_select_type (gfc_code *code)
7068 {
7069   gfc_symbol *selector_type;
7070   gfc_code *body, *new_st, *if_st, *tail;
7071   gfc_code *class_is = NULL, *default_case = NULL;
7072   gfc_case *c;
7073   gfc_symtree *st;
7074   char name[GFC_MAX_SYMBOL_LEN];
7075   gfc_namespace *ns;
7076   int error = 0;
7077
7078   ns = code->ext.ns;
7079   gfc_resolve (ns);
7080
7081   /* Check for F03:C813.  */
7082   if (code->expr1->ts.type != BT_CLASS
7083       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7084     {
7085       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7086                  "at %L", &code->loc);
7087       return;
7088     }
7089
7090   if (code->expr2)
7091     {
7092       if (code->expr1->symtree->n.sym->attr.untyped)
7093         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7094       selector_type = code->expr2->ts.u.derived->components->ts.u.derived;
7095     }
7096   else
7097     selector_type = code->expr1->ts.u.derived->components->ts.u.derived;
7098
7099   /* Loop over TYPE IS / CLASS IS cases.  */
7100   for (body = code->block; body; body = body->block)
7101     {
7102       c = body->ext.case_list;
7103
7104       /* Check F03:C815.  */
7105       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7106           && !gfc_type_is_extensible (c->ts.u.derived))
7107         {
7108           gfc_error ("Derived type '%s' at %L must be extensible",
7109                      c->ts.u.derived->name, &c->where);
7110           error++;
7111           continue;
7112         }
7113
7114       /* Check F03:C816.  */
7115       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7116           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7117         {
7118           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7119                      c->ts.u.derived->name, &c->where, selector_type->name);
7120           error++;
7121           continue;
7122         }
7123
7124       /* Intercept the DEFAULT case.  */
7125       if (c->ts.type == BT_UNKNOWN)
7126         {
7127           /* Check F03:C818.  */
7128           if (default_case)
7129             {
7130               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7131                          "by a second DEFAULT CASE at %L",
7132                          &default_case->ext.case_list->where, &c->where);
7133               error++;
7134               continue;
7135             }
7136           else
7137             default_case = body;
7138         }
7139     }
7140     
7141   if (error>0)
7142     return;
7143
7144   if (code->expr2)
7145     {
7146       /* Insert assignment for selector variable.  */
7147       new_st = gfc_get_code ();
7148       new_st->op = EXEC_ASSIGN;
7149       new_st->expr1 = gfc_copy_expr (code->expr1);
7150       new_st->expr2 = gfc_copy_expr (code->expr2);
7151       ns->code = new_st;
7152     }
7153
7154   /* Put SELECT TYPE statement inside a BLOCK.  */
7155   new_st = gfc_get_code ();
7156   new_st->op = code->op;
7157   new_st->expr1 = code->expr1;
7158   new_st->expr2 = code->expr2;
7159   new_st->block = code->block;
7160   if (!ns->code)
7161     ns->code = new_st;
7162   else
7163     ns->code->next = new_st;
7164   code->op = EXEC_BLOCK;
7165   code->expr1 = code->expr2 =  NULL;
7166   code->block = NULL;
7167
7168   code = new_st;
7169
7170   /* Transform to EXEC_SELECT.  */
7171   code->op = EXEC_SELECT;
7172   gfc_add_component_ref (code->expr1, "$vptr");
7173   gfc_add_component_ref (code->expr1, "$hash");
7174
7175   /* Loop over TYPE IS / CLASS IS cases.  */
7176   for (body = code->block; body; body = body->block)
7177     {
7178       c = body->ext.case_list;
7179
7180       if (c->ts.type == BT_DERIVED)
7181         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7182                                              c->ts.u.derived->hash_value);
7183
7184       else if (c->ts.type == BT_UNKNOWN)
7185         continue;
7186
7187       /* Assign temporary to selector.  */
7188       if (c->ts.type == BT_CLASS)
7189         sprintf (name, "tmp$class$%s", c->ts.u.derived->name);
7190       else
7191         sprintf (name, "tmp$type$%s", c->ts.u.derived->name);
7192       st = gfc_find_symtree (ns->sym_root, name);
7193       new_st = gfc_get_code ();
7194       new_st->expr1 = gfc_get_variable_expr (st);
7195       new_st->expr2 = gfc_get_variable_expr (code->expr1->symtree);
7196       if (c->ts.type == BT_DERIVED)
7197         {
7198           new_st->op = EXEC_POINTER_ASSIGN;
7199           gfc_add_component_ref (new_st->expr2, "$data");
7200         }
7201       else
7202         new_st->op = EXEC_POINTER_ASSIGN;
7203       new_st->next = body->next;
7204       body->next = new_st;
7205     }
7206     
7207   /* Take out CLASS IS cases for separate treatment.  */
7208   body = code;
7209   while (body && body->block)
7210     {
7211       if (body->block->ext.case_list->ts.type == BT_CLASS)
7212         {
7213           /* Add to class_is list.  */
7214           if (class_is == NULL)
7215             { 
7216               class_is = body->block;
7217               tail = class_is;
7218             }
7219           else
7220             {
7221               for (tail = class_is; tail->block; tail = tail->block) ;
7222               tail->block = body->block;
7223               tail = tail->block;
7224             }
7225           /* Remove from EXEC_SELECT list.  */
7226           body->block = body->block->block;
7227           tail->block = NULL;
7228         }
7229       else
7230         body = body->block;
7231     }
7232
7233   if (class_is)
7234     {
7235       gfc_symbol *vtab;
7236       
7237       if (!default_case)
7238         {
7239           /* Add a default case to hold the CLASS IS cases.  */
7240           for (tail = code; tail->block; tail = tail->block) ;
7241           tail->block = gfc_get_code ();
7242           tail = tail->block;
7243           tail->op = EXEC_SELECT_TYPE;
7244           tail->ext.case_list = gfc_get_case ();
7245           tail->ext.case_list->ts.type = BT_UNKNOWN;
7246           tail->next = NULL;
7247           default_case = tail;
7248         }
7249
7250       /* More than one CLASS IS block?  */
7251       if (class_is->block)
7252         {
7253           gfc_code **c1,*c2;
7254           bool swapped;
7255           /* Sort CLASS IS blocks by extension level.  */
7256           do
7257             {
7258               swapped = false;
7259               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
7260                 {
7261                   c2 = (*c1)->block;
7262                   /* F03:C817 (check for doubles).  */
7263                   if ((*c1)->ext.case_list->ts.u.derived->hash_value
7264                       == c2->ext.case_list->ts.u.derived->hash_value)
7265                     {
7266                       gfc_error ("Double CLASS IS block in SELECT TYPE "
7267                                  "statement at %L", &c2->ext.case_list->where);
7268                       return;
7269                     }
7270                   if ((*c1)->ext.case_list->ts.u.derived->attr.extension
7271                       < c2->ext.case_list->ts.u.derived->attr.extension)
7272                     {
7273                       /* Swap.  */
7274                       (*c1)->block = c2->block;
7275                       c2->block = *c1;
7276                       *c1 = c2;
7277                       swapped = true;
7278                     }
7279                 }
7280             }
7281           while (swapped);
7282         }
7283         
7284       /* Generate IF chain.  */
7285       if_st = gfc_get_code ();
7286       if_st->op = EXEC_IF;
7287       new_st = if_st;
7288       for (body = class_is; body; body = body->block)
7289         {
7290           new_st->block = gfc_get_code ();
7291           new_st = new_st->block;
7292           new_st->op = EXEC_IF;
7293           /* Set up IF condition: Call _gfortran_is_extension_of.  */
7294           new_st->expr1 = gfc_get_expr ();
7295           new_st->expr1->expr_type = EXPR_FUNCTION;
7296           new_st->expr1->ts.type = BT_LOGICAL;
7297           new_st->expr1->ts.kind = 4;
7298           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
7299           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
7300           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
7301           /* Set up arguments.  */
7302           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
7303           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
7304           gfc_add_component_ref (new_st->expr1->value.function.actual->expr, "$vptr");
7305           vtab = gfc_find_derived_vtab (body->ext.case_list->ts.u.derived, true);
7306           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
7307           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
7308           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
7309           new_st->next = body->next;
7310         }
7311         if (default_case->next)
7312           {
7313             new_st->block = gfc_get_code ();
7314             new_st = new_st->block;
7315             new_st->op = EXEC_IF;
7316             new_st->next = default_case->next;
7317           }
7318           
7319         /* Replace CLASS DEFAULT code by the IF chain.  */
7320         default_case->next = if_st;
7321     }
7322
7323   resolve_select (code);
7324
7325 }
7326
7327
7328 /* Resolve a transfer statement. This is making sure that:
7329    -- a derived type being transferred has only non-pointer components
7330    -- a derived type being transferred doesn't have private components, unless 
7331       it's being transferred from the module where the type was defined
7332    -- we're not trying to transfer a whole assumed size array.  */
7333
7334 static void
7335 resolve_transfer (gfc_code *code)
7336 {
7337   gfc_typespec *ts;
7338   gfc_symbol *sym;
7339   gfc_ref *ref;
7340   gfc_expr *exp;
7341
7342   exp = code->expr1;
7343
7344   if (exp->expr_type != EXPR_VARIABLE && exp->expr_type != EXPR_FUNCTION)
7345     return;
7346
7347   sym = exp->symtree->n.sym;
7348   ts = &sym->ts;
7349
7350   /* Go to actual component transferred.  */
7351   for (ref = code->expr1->ref; ref; ref = ref->next)
7352     if (ref->type == REF_COMPONENT)
7353       ts = &ref->u.c.component->ts;
7354
7355   if (ts->type == BT_DERIVED)
7356     {
7357       /* Check that transferred derived type doesn't contain POINTER
7358          components.  */
7359       if (ts->u.derived->attr.pointer_comp)
7360         {
7361           gfc_error ("Data transfer element at %L cannot have "
7362                      "POINTER components", &code->loc);
7363           return;
7364         }
7365
7366       if (ts->u.derived->attr.alloc_comp)
7367         {
7368           gfc_error ("Data transfer element at %L cannot have "
7369                      "ALLOCATABLE components", &code->loc);
7370           return;
7371         }
7372
7373       if (derived_inaccessible (ts->u.derived))
7374         {
7375           gfc_error ("Data transfer element at %L cannot have "
7376                      "PRIVATE components",&code->loc);
7377           return;
7378         }
7379     }
7380
7381   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
7382       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
7383     {
7384       gfc_error ("Data transfer element at %L cannot be a full reference to "
7385                  "an assumed-size array", &code->loc);
7386       return;
7387     }
7388 }
7389
7390
7391 /*********** Toplevel code resolution subroutines ***********/
7392
7393 /* Find the set of labels that are reachable from this block.  We also
7394    record the last statement in each block.  */
7395      
7396 static void
7397 find_reachable_labels (gfc_code *block)
7398 {
7399   gfc_code *c;
7400
7401   if (!block)
7402     return;
7403
7404   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
7405
7406   /* Collect labels in this block.  We don't keep those corresponding
7407      to END {IF|SELECT}, these are checked in resolve_branch by going
7408      up through the code_stack.  */
7409   for (c = block; c; c = c->next)
7410     {
7411       if (c->here && c->op != EXEC_END_BLOCK)
7412         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
7413     }
7414
7415   /* Merge with labels from parent block.  */
7416   if (cs_base->prev)
7417     {
7418       gcc_assert (cs_base->prev->reachable_labels);
7419       bitmap_ior_into (cs_base->reachable_labels,
7420                        cs_base->prev->reachable_labels);
7421     }
7422 }
7423
7424
7425 static void
7426 resolve_sync (gfc_code *code)
7427 {
7428   /* Check imageset. The * case matches expr1 == NULL.  */
7429   if (code->expr1)
7430     {
7431       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
7432         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
7433                    "INTEGER expression", &code->expr1->where);
7434       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
7435           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
7436         gfc_error ("Imageset argument at %L must between 1 and num_images()",
7437                    &code->expr1->where);
7438       else if (code->expr1->expr_type == EXPR_ARRAY
7439                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
7440         {
7441            gfc_constructor *cons;
7442            cons = gfc_constructor_first (code->expr1->value.constructor);
7443            for (; cons; cons = gfc_constructor_next (cons))
7444              if (cons->expr->expr_type == EXPR_CONSTANT
7445                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
7446                gfc_error ("Imageset argument at %L must between 1 and "
7447                           "num_images()", &cons->expr->where);
7448         }
7449     }
7450
7451   /* Check STAT.  */
7452   if (code->expr2
7453       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
7454           || code->expr2->expr_type != EXPR_VARIABLE))
7455     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
7456                &code->expr2->where);
7457
7458   /* Check ERRMSG.  */
7459   if (code->expr3
7460       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
7461           || code->expr3->expr_type != EXPR_VARIABLE))
7462     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
7463                &code->expr3->where);
7464 }
7465
7466
7467 /* Given a branch to a label, see if the branch is conforming.
7468    The code node describes where the branch is located.  */
7469
7470 static void
7471 resolve_branch (gfc_st_label *label, gfc_code *code)
7472 {
7473   code_stack *stack;
7474
7475   if (label == NULL)
7476     return;
7477
7478   /* Step one: is this a valid branching target?  */
7479
7480   if (label->defined == ST_LABEL_UNKNOWN)
7481     {
7482       gfc_error ("Label %d referenced at %L is never defined", label->value,
7483                  &label->where);
7484       return;
7485     }
7486
7487   if (label->defined != ST_LABEL_TARGET)
7488     {
7489       gfc_error ("Statement at %L is not a valid branch target statement "
7490                  "for the branch statement at %L", &label->where, &code->loc);
7491       return;
7492     }
7493
7494   /* Step two: make sure this branch is not a branch to itself ;-)  */
7495
7496   if (code->here == label)
7497     {
7498       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
7499       return;
7500     }
7501
7502   /* Step three:  See if the label is in the same block as the
7503      branching statement.  The hard work has been done by setting up
7504      the bitmap reachable_labels.  */
7505
7506   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
7507     {
7508       /* Check now whether there is a CRITICAL construct; if so, check
7509          whether the label is still visible outside of the CRITICAL block,
7510          which is invalid.  */
7511       for (stack = cs_base; stack; stack = stack->prev)
7512         if (stack->current->op == EXEC_CRITICAL
7513             && bitmap_bit_p (stack->reachable_labels, label->value))
7514           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
7515                       " at %L", &code->loc, &label->where);
7516
7517       return;
7518     }
7519
7520   /* Step four:  If we haven't found the label in the bitmap, it may
7521     still be the label of the END of the enclosing block, in which
7522     case we find it by going up the code_stack.  */
7523
7524   for (stack = cs_base; stack; stack = stack->prev)
7525     {
7526       if (stack->current->next && stack->current->next->here == label)
7527         break;
7528       if (stack->current->op == EXEC_CRITICAL)
7529         {
7530           /* Note: A label at END CRITICAL does not leave the CRITICAL
7531              construct as END CRITICAL is still part of it.  */
7532           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
7533                       " at %L", &code->loc, &label->where);
7534           return;
7535         }
7536     }
7537
7538   if (stack)
7539     {
7540       gcc_assert (stack->current->next->op == EXEC_END_BLOCK);
7541       return;
7542     }
7543
7544   /* The label is not in an enclosing block, so illegal.  This was
7545      allowed in Fortran 66, so we allow it as extension.  No
7546      further checks are necessary in this case.  */
7547   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
7548                   "as the GOTO statement at %L", &label->where,
7549                   &code->loc);
7550   return;
7551 }
7552
7553
7554 /* Check whether EXPR1 has the same shape as EXPR2.  */
7555
7556 static gfc_try
7557 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
7558 {
7559   mpz_t shape[GFC_MAX_DIMENSIONS];
7560   mpz_t shape2[GFC_MAX_DIMENSIONS];
7561   gfc_try result = FAILURE;
7562   int i;
7563
7564   /* Compare the rank.  */
7565   if (expr1->rank != expr2->rank)
7566     return result;
7567
7568   /* Compare the size of each dimension.  */
7569   for (i=0; i<expr1->rank; i++)
7570     {
7571       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
7572         goto ignore;
7573
7574       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
7575         goto ignore;
7576
7577       if (mpz_cmp (shape[i], shape2[i]))
7578         goto over;
7579     }
7580
7581   /* When either of the two expression is an assumed size array, we
7582      ignore the comparison of dimension sizes.  */
7583 ignore:
7584   result = SUCCESS;
7585
7586 over:
7587   for (i--; i >= 0; i--)
7588     {
7589       mpz_clear (shape[i]);
7590       mpz_clear (shape2[i]);
7591     }
7592   return result;
7593 }
7594
7595
7596 /* Check whether a WHERE assignment target or a WHERE mask expression
7597    has the same shape as the outmost WHERE mask expression.  */
7598
7599 static void
7600 resolve_where (gfc_code *code, gfc_expr *mask)
7601 {
7602   gfc_code *cblock;
7603   gfc_code *cnext;
7604   gfc_expr *e = NULL;
7605
7606   cblock = code->block;
7607
7608   /* Store the first WHERE mask-expr of the WHERE statement or construct.
7609      In case of nested WHERE, only the outmost one is stored.  */
7610   if (mask == NULL) /* outmost WHERE */
7611     e = cblock->expr1;
7612   else /* inner WHERE */
7613     e = mask;
7614
7615   while (cblock)
7616     {
7617       if (cblock->expr1)
7618         {
7619           /* Check if the mask-expr has a consistent shape with the
7620              outmost WHERE mask-expr.  */
7621           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
7622             gfc_error ("WHERE mask at %L has inconsistent shape",
7623                        &cblock->expr1->where);
7624          }
7625
7626       /* the assignment statement of a WHERE statement, or the first
7627          statement in where-body-construct of a WHERE construct */
7628       cnext = cblock->next;
7629       while (cnext)
7630         {
7631           switch (cnext->op)
7632             {
7633             /* WHERE assignment statement */
7634             case EXEC_ASSIGN:
7635
7636               /* Check shape consistent for WHERE assignment target.  */
7637               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
7638                gfc_error ("WHERE assignment target at %L has "
7639                           "inconsistent shape", &cnext->expr1->where);
7640               break;
7641
7642   
7643             case EXEC_ASSIGN_CALL:
7644               resolve_call (cnext);
7645               if (!cnext->resolved_sym->attr.elemental)
7646                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7647                           &cnext->ext.actual->expr->where);
7648               break;
7649
7650             /* WHERE or WHERE construct is part of a where-body-construct */
7651             case EXEC_WHERE:
7652               resolve_where (cnext, e);
7653               break;
7654
7655             default:
7656               gfc_error ("Unsupported statement inside WHERE at %L",
7657                          &cnext->loc);
7658             }
7659          /* the next statement within the same where-body-construct */
7660          cnext = cnext->next;
7661        }
7662     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7663     cblock = cblock->block;
7664   }
7665 }
7666
7667
7668 /* Resolve assignment in FORALL construct.
7669    NVAR is the number of FORALL index variables, and VAR_EXPR records the
7670    FORALL index variables.  */
7671
7672 static void
7673 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
7674 {
7675   int n;
7676
7677   for (n = 0; n < nvar; n++)
7678     {
7679       gfc_symbol *forall_index;
7680
7681       forall_index = var_expr[n]->symtree->n.sym;
7682
7683       /* Check whether the assignment target is one of the FORALL index
7684          variable.  */
7685       if ((code->expr1->expr_type == EXPR_VARIABLE)
7686           && (code->expr1->symtree->n.sym == forall_index))
7687         gfc_error ("Assignment to a FORALL index variable at %L",
7688                    &code->expr1->where);
7689       else
7690         {
7691           /* If one of the FORALL index variables doesn't appear in the
7692              assignment variable, then there could be a many-to-one
7693              assignment.  Emit a warning rather than an error because the
7694              mask could be resolving this problem.  */
7695           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
7696             gfc_warning ("The FORALL with index '%s' is not used on the "
7697                          "left side of the assignment at %L and so might "
7698                          "cause multiple assignment to this object",
7699                          var_expr[n]->symtree->name, &code->expr1->where);
7700         }
7701     }
7702 }
7703
7704
7705 /* Resolve WHERE statement in FORALL construct.  */
7706
7707 static void
7708 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
7709                                   gfc_expr **var_expr)
7710 {
7711   gfc_code *cblock;
7712   gfc_code *cnext;
7713
7714   cblock = code->block;
7715   while (cblock)
7716     {
7717       /* the assignment statement of a WHERE statement, or the first
7718          statement in where-body-construct of a WHERE construct */
7719       cnext = cblock->next;
7720       while (cnext)
7721         {
7722           switch (cnext->op)
7723             {
7724             /* WHERE assignment statement */
7725             case EXEC_ASSIGN:
7726               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
7727               break;
7728   
7729             /* WHERE operator assignment statement */
7730             case EXEC_ASSIGN_CALL:
7731               resolve_call (cnext);
7732               if (!cnext->resolved_sym->attr.elemental)
7733                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
7734                           &cnext->ext.actual->expr->where);
7735               break;
7736
7737             /* WHERE or WHERE construct is part of a where-body-construct */
7738             case EXEC_WHERE:
7739               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
7740               break;
7741
7742             default:
7743               gfc_error ("Unsupported statement inside WHERE at %L",
7744                          &cnext->loc);
7745             }
7746           /* the next statement within the same where-body-construct */
7747           cnext = cnext->next;
7748         }
7749       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
7750       cblock = cblock->block;
7751     }
7752 }
7753
7754
7755 /* Traverse the FORALL body to check whether the following errors exist:
7756    1. For assignment, check if a many-to-one assignment happens.
7757    2. For WHERE statement, check the WHERE body to see if there is any
7758       many-to-one assignment.  */
7759
7760 static void
7761 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
7762 {
7763   gfc_code *c;
7764
7765   c = code->block->next;
7766   while (c)
7767     {
7768       switch (c->op)
7769         {
7770         case EXEC_ASSIGN:
7771         case EXEC_POINTER_ASSIGN:
7772           gfc_resolve_assign_in_forall (c, nvar, var_expr);
7773           break;
7774
7775         case EXEC_ASSIGN_CALL:
7776           resolve_call (c);
7777           break;
7778
7779         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
7780            there is no need to handle it here.  */
7781         case EXEC_FORALL:
7782           break;
7783         case EXEC_WHERE:
7784           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
7785           break;
7786         default:
7787           break;
7788         }
7789       /* The next statement in the FORALL body.  */
7790       c = c->next;
7791     }
7792 }
7793
7794
7795 /* Counts the number of iterators needed inside a forall construct, including
7796    nested forall constructs. This is used to allocate the needed memory 
7797    in gfc_resolve_forall.  */
7798
7799 static int 
7800 gfc_count_forall_iterators (gfc_code *code)
7801 {
7802   int max_iters, sub_iters, current_iters;
7803   gfc_forall_iterator *fa;
7804
7805   gcc_assert(code->op == EXEC_FORALL);
7806   max_iters = 0;
7807   current_iters = 0;
7808
7809   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7810     current_iters ++;
7811   
7812   code = code->block->next;
7813
7814   while (code)
7815     {          
7816       if (code->op == EXEC_FORALL)
7817         {
7818           sub_iters = gfc_count_forall_iterators (code);
7819           if (sub_iters > max_iters)
7820             max_iters = sub_iters;
7821         }
7822       code = code->next;
7823     }
7824
7825   return current_iters + max_iters;
7826 }
7827
7828
7829 /* Given a FORALL construct, first resolve the FORALL iterator, then call
7830    gfc_resolve_forall_body to resolve the FORALL body.  */
7831
7832 static void
7833 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
7834 {
7835   static gfc_expr **var_expr;
7836   static int total_var = 0;
7837   static int nvar = 0;
7838   int old_nvar, tmp;
7839   gfc_forall_iterator *fa;
7840   int i;
7841
7842   old_nvar = nvar;
7843
7844   /* Start to resolve a FORALL construct   */
7845   if (forall_save == 0)
7846     {
7847       /* Count the total number of FORALL index in the nested FORALL
7848          construct in order to allocate the VAR_EXPR with proper size.  */
7849       total_var = gfc_count_forall_iterators (code);
7850
7851       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
7852       var_expr = (gfc_expr **) gfc_getmem (total_var * sizeof (gfc_expr *));
7853     }
7854
7855   /* The information about FORALL iterator, including FORALL index start, end
7856      and stride. The FORALL index can not appear in start, end or stride.  */
7857   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
7858     {
7859       /* Check if any outer FORALL index name is the same as the current
7860          one.  */
7861       for (i = 0; i < nvar; i++)
7862         {
7863           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
7864             {
7865               gfc_error ("An outer FORALL construct already has an index "
7866                          "with this name %L", &fa->var->where);
7867             }
7868         }
7869
7870       /* Record the current FORALL index.  */
7871       var_expr[nvar] = gfc_copy_expr (fa->var);
7872
7873       nvar++;
7874
7875       /* No memory leak.  */
7876       gcc_assert (nvar <= total_var);
7877     }
7878
7879   /* Resolve the FORALL body.  */
7880   gfc_resolve_forall_body (code, nvar, var_expr);
7881
7882   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
7883   gfc_resolve_blocks (code->block, ns);
7884
7885   tmp = nvar;
7886   nvar = old_nvar;
7887   /* Free only the VAR_EXPRs allocated in this frame.  */
7888   for (i = nvar; i < tmp; i++)
7889      gfc_free_expr (var_expr[i]);
7890
7891   if (nvar == 0)
7892     {
7893       /* We are in the outermost FORALL construct.  */
7894       gcc_assert (forall_save == 0);
7895
7896       /* VAR_EXPR is not needed any more.  */
7897       gfc_free (var_expr);
7898       total_var = 0;
7899     }
7900 }
7901
7902
7903 /* Resolve a BLOCK construct statement.  */
7904
7905 static void
7906 resolve_block_construct (gfc_code* code)
7907 {
7908   /* Eventually, we may want to do some checks here or handle special stuff.
7909      But so far the only thing we can do is resolving the local namespace.  */
7910
7911   gfc_resolve (code->ext.ns);
7912 }
7913
7914
7915 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
7916    DO code nodes.  */
7917
7918 static void resolve_code (gfc_code *, gfc_namespace *);
7919
7920 void
7921 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
7922 {
7923   gfc_try t;
7924
7925   for (; b; b = b->block)
7926     {
7927       t = gfc_resolve_expr (b->expr1);
7928       if (gfc_resolve_expr (b->expr2) == FAILURE)
7929         t = FAILURE;
7930
7931       switch (b->op)
7932         {
7933         case EXEC_IF:
7934           if (t == SUCCESS && b->expr1 != NULL
7935               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
7936             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
7937                        &b->expr1->where);
7938           break;
7939
7940         case EXEC_WHERE:
7941           if (t == SUCCESS
7942               && b->expr1 != NULL
7943               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
7944             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
7945                        &b->expr1->where);
7946           break;
7947
7948         case EXEC_GOTO:
7949           resolve_branch (b->label1, b);
7950           break;
7951
7952         case EXEC_BLOCK:
7953           resolve_block_construct (b);
7954           break;
7955
7956         case EXEC_SELECT:
7957         case EXEC_SELECT_TYPE:
7958         case EXEC_FORALL:
7959         case EXEC_DO:
7960         case EXEC_DO_WHILE:
7961         case EXEC_CRITICAL:
7962         case EXEC_READ:
7963         case EXEC_WRITE:
7964         case EXEC_IOLENGTH:
7965         case EXEC_WAIT:
7966           break;
7967
7968         case EXEC_OMP_ATOMIC:
7969         case EXEC_OMP_CRITICAL:
7970         case EXEC_OMP_DO:
7971         case EXEC_OMP_MASTER:
7972         case EXEC_OMP_ORDERED:
7973         case EXEC_OMP_PARALLEL:
7974         case EXEC_OMP_PARALLEL_DO:
7975         case EXEC_OMP_PARALLEL_SECTIONS:
7976         case EXEC_OMP_PARALLEL_WORKSHARE:
7977         case EXEC_OMP_SECTIONS:
7978         case EXEC_OMP_SINGLE:
7979         case EXEC_OMP_TASK:
7980         case EXEC_OMP_TASKWAIT:
7981         case EXEC_OMP_WORKSHARE:
7982           break;
7983
7984         default:
7985           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
7986         }
7987
7988       resolve_code (b->next, ns);
7989     }
7990 }
7991
7992
7993 /* Does everything to resolve an ordinary assignment.  Returns true
7994    if this is an interface assignment.  */
7995 static bool
7996 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
7997 {
7998   bool rval = false;
7999   gfc_expr *lhs;
8000   gfc_expr *rhs;
8001   int llen = 0;
8002   int rlen = 0;
8003   int n;
8004   gfc_ref *ref;
8005
8006   if (gfc_extend_assign (code, ns) == SUCCESS)
8007     {
8008       gfc_expr** rhsptr;
8009
8010       if (code->op == EXEC_ASSIGN_CALL)
8011         {
8012           lhs = code->ext.actual->expr;
8013           rhsptr = &code->ext.actual->next->expr;
8014         }
8015       else
8016         {
8017           gfc_actual_arglist* args;
8018           gfc_typebound_proc* tbp;
8019
8020           gcc_assert (code->op == EXEC_COMPCALL);
8021
8022           args = code->expr1->value.compcall.actual;
8023           lhs = args->expr;
8024           rhsptr = &args->next->expr;
8025
8026           tbp = code->expr1->value.compcall.tbp;
8027           gcc_assert (!tbp->is_generic);
8028         }
8029
8030       /* Make a temporary rhs when there is a default initializer
8031          and rhs is the same symbol as the lhs.  */
8032       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8033             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8034             && has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8035             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8036         *rhsptr = gfc_get_parentheses (*rhsptr);
8037
8038       return true;
8039     }
8040
8041   lhs = code->expr1;
8042   rhs = code->expr2;
8043
8044   if (rhs->is_boz
8045       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8046                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8047                          &code->loc) == FAILURE)
8048     return false;
8049
8050   /* Handle the case of a BOZ literal on the RHS.  */
8051   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8052     {
8053       int rc;
8054       if (gfc_option.warn_surprising)
8055         gfc_warning ("BOZ literal at %L is bitwise transferred "
8056                      "non-integer symbol '%s'", &code->loc,
8057                      lhs->symtree->n.sym->name);
8058
8059       if (!gfc_convert_boz (rhs, &lhs->ts))
8060         return false;
8061       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8062         {
8063           if (rc == ARITH_UNDERFLOW)
8064             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8065                        ". This check can be disabled with the option "
8066                        "-fno-range-check", &rhs->where);
8067           else if (rc == ARITH_OVERFLOW)
8068             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8069                        ". This check can be disabled with the option "
8070                        "-fno-range-check", &rhs->where);
8071           else if (rc == ARITH_NAN)
8072             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8073                        ". This check can be disabled with the option "
8074                        "-fno-range-check", &rhs->where);
8075           return false;
8076         }
8077     }
8078
8079
8080   if (lhs->ts.type == BT_CHARACTER
8081         && gfc_option.warn_character_truncation)
8082     {
8083       if (lhs->ts.u.cl != NULL
8084             && lhs->ts.u.cl->length != NULL
8085             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8086         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8087
8088       if (rhs->expr_type == EXPR_CONSTANT)
8089         rlen = rhs->value.character.length;
8090
8091       else if (rhs->ts.u.cl != NULL
8092                  && rhs->ts.u.cl->length != NULL
8093                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8094         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8095
8096       if (rlen && llen && rlen > llen)
8097         gfc_warning_now ("CHARACTER expression will be truncated "
8098                          "in assignment (%d/%d) at %L",
8099                          llen, rlen, &code->loc);
8100     }
8101
8102   /* Ensure that a vector index expression for the lvalue is evaluated
8103      to a temporary if the lvalue symbol is referenced in it.  */
8104   if (lhs->rank)
8105     {
8106       for (ref = lhs->ref; ref; ref= ref->next)
8107         if (ref->type == REF_ARRAY)
8108           {
8109             for (n = 0; n < ref->u.ar.dimen; n++)
8110               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8111                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8112                                            ref->u.ar.start[n]))
8113                 ref->u.ar.start[n]
8114                         = gfc_get_parentheses (ref->u.ar.start[n]);
8115           }
8116     }
8117
8118   if (gfc_pure (NULL))
8119     {
8120       if (gfc_impure_variable (lhs->symtree->n.sym))
8121         {
8122           gfc_error ("Cannot assign to variable '%s' in PURE "
8123                      "procedure at %L",
8124                       lhs->symtree->n.sym->name,
8125                       &lhs->where);
8126           return rval;
8127         }
8128
8129       if (lhs->ts.type == BT_DERIVED
8130             && lhs->expr_type == EXPR_VARIABLE
8131             && lhs->ts.u.derived->attr.pointer_comp
8132             && rhs->expr_type == EXPR_VARIABLE
8133             && (gfc_impure_variable (rhs->symtree->n.sym)
8134                 || gfc_is_coindexed (rhs)))
8135         {
8136           /* F2008, C1283.  */
8137           if (gfc_is_coindexed (rhs))
8138             gfc_error ("Coindexed expression at %L is assigned to "
8139                         "a derived type variable with a POINTER "
8140                         "component in a PURE procedure",
8141                         &rhs->where);
8142           else
8143             gfc_error ("The impure variable at %L is assigned to "
8144                         "a derived type variable with a POINTER "
8145                         "component in a PURE procedure (12.6)",
8146                         &rhs->where);
8147           return rval;
8148         }
8149
8150       /* Fortran 2008, C1283.  */
8151       if (gfc_is_coindexed (lhs))
8152         {
8153           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8154                      "procedure", &rhs->where);
8155           return rval;
8156         }
8157     }
8158
8159   /* F03:7.4.1.2.  */
8160   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
8161      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
8162   if (lhs->ts.type == BT_CLASS)
8163     {
8164       gfc_error ("Variable must not be polymorphic in assignment at %L",
8165                  &lhs->where);
8166       return false;
8167     }
8168
8169   /* F2008, Section 7.2.1.2.  */
8170   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
8171     {
8172       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
8173                  "component in assignment at %L", &lhs->where);
8174       return false;
8175     }
8176
8177   gfc_check_assign (lhs, rhs, 1);
8178   return false;
8179 }
8180
8181
8182 /* Given a block of code, recursively resolve everything pointed to by this
8183    code block.  */
8184
8185 static void
8186 resolve_code (gfc_code *code, gfc_namespace *ns)
8187 {
8188   int omp_workshare_save;
8189   int forall_save;
8190   code_stack frame;
8191   gfc_try t;
8192
8193   frame.prev = cs_base;
8194   frame.head = code;
8195   cs_base = &frame;
8196
8197   find_reachable_labels (code);
8198
8199   for (; code; code = code->next)
8200     {
8201       frame.current = code;
8202       forall_save = forall_flag;
8203
8204       if (code->op == EXEC_FORALL)
8205         {
8206           forall_flag = 1;
8207           gfc_resolve_forall (code, ns, forall_save);
8208           forall_flag = 2;
8209         }
8210       else if (code->block)
8211         {
8212           omp_workshare_save = -1;
8213           switch (code->op)
8214             {
8215             case EXEC_OMP_PARALLEL_WORKSHARE:
8216               omp_workshare_save = omp_workshare_flag;
8217               omp_workshare_flag = 1;
8218               gfc_resolve_omp_parallel_blocks (code, ns);
8219               break;
8220             case EXEC_OMP_PARALLEL:
8221             case EXEC_OMP_PARALLEL_DO:
8222             case EXEC_OMP_PARALLEL_SECTIONS:
8223             case EXEC_OMP_TASK:
8224               omp_workshare_save = omp_workshare_flag;
8225               omp_workshare_flag = 0;
8226               gfc_resolve_omp_parallel_blocks (code, ns);
8227               break;
8228             case EXEC_OMP_DO:
8229               gfc_resolve_omp_do_blocks (code, ns);
8230               break;
8231             case EXEC_SELECT_TYPE:
8232               gfc_current_ns = code->ext.ns;
8233               gfc_resolve_blocks (code->block, gfc_current_ns);
8234               gfc_current_ns = ns;
8235               break;
8236             case EXEC_OMP_WORKSHARE:
8237               omp_workshare_save = omp_workshare_flag;
8238               omp_workshare_flag = 1;
8239               /* FALLTHROUGH */
8240             default:
8241               gfc_resolve_blocks (code->block, ns);
8242               break;
8243             }
8244
8245           if (omp_workshare_save != -1)
8246             omp_workshare_flag = omp_workshare_save;
8247         }
8248
8249       t = SUCCESS;
8250       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
8251         t = gfc_resolve_expr (code->expr1);
8252       forall_flag = forall_save;
8253
8254       if (gfc_resolve_expr (code->expr2) == FAILURE)
8255         t = FAILURE;
8256
8257       if (code->op == EXEC_ALLOCATE
8258           && gfc_resolve_expr (code->expr3) == FAILURE)
8259         t = FAILURE;
8260
8261       switch (code->op)
8262         {
8263         case EXEC_NOP:
8264         case EXEC_END_BLOCK:
8265         case EXEC_CYCLE:
8266         case EXEC_PAUSE:
8267         case EXEC_STOP:
8268         case EXEC_ERROR_STOP:
8269         case EXEC_EXIT:
8270         case EXEC_CONTINUE:
8271         case EXEC_DT_END:
8272         case EXEC_ASSIGN_CALL:
8273         case EXEC_CRITICAL:
8274           break;
8275
8276         case EXEC_SYNC_ALL:
8277         case EXEC_SYNC_IMAGES:
8278         case EXEC_SYNC_MEMORY:
8279           resolve_sync (code);
8280           break;
8281
8282         case EXEC_ENTRY:
8283           /* Keep track of which entry we are up to.  */
8284           current_entry_id = code->ext.entry->id;
8285           break;
8286
8287         case EXEC_WHERE:
8288           resolve_where (code, NULL);
8289           break;
8290
8291         case EXEC_GOTO:
8292           if (code->expr1 != NULL)
8293             {
8294               if (code->expr1->ts.type != BT_INTEGER)
8295                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
8296                            "INTEGER variable", &code->expr1->where);
8297               else if (code->expr1->symtree->n.sym->attr.assign != 1)
8298                 gfc_error ("Variable '%s' has not been assigned a target "
8299                            "label at %L", code->expr1->symtree->n.sym->name,
8300                            &code->expr1->where);
8301             }
8302           else
8303             resolve_branch (code->label1, code);
8304           break;
8305
8306         case EXEC_RETURN:
8307           if (code->expr1 != NULL
8308                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
8309             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
8310                        "INTEGER return specifier", &code->expr1->where);
8311           break;
8312
8313         case EXEC_INIT_ASSIGN:
8314         case EXEC_END_PROCEDURE:
8315           break;
8316
8317         case EXEC_ASSIGN:
8318           if (t == FAILURE)
8319             break;
8320
8321           if (resolve_ordinary_assign (code, ns))
8322             {
8323               if (code->op == EXEC_COMPCALL)
8324                 goto compcall;
8325               else
8326                 goto call;
8327             }
8328           break;
8329
8330         case EXEC_LABEL_ASSIGN:
8331           if (code->label1->defined == ST_LABEL_UNKNOWN)
8332             gfc_error ("Label %d referenced at %L is never defined",
8333                        code->label1->value, &code->label1->where);
8334           if (t == SUCCESS
8335               && (code->expr1->expr_type != EXPR_VARIABLE
8336                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
8337                   || code->expr1->symtree->n.sym->ts.kind
8338                      != gfc_default_integer_kind
8339                   || code->expr1->symtree->n.sym->as != NULL))
8340             gfc_error ("ASSIGN statement at %L requires a scalar "
8341                        "default INTEGER variable", &code->expr1->where);
8342           break;
8343
8344         case EXEC_POINTER_ASSIGN:
8345           if (t == FAILURE)
8346             break;
8347
8348           gfc_check_pointer_assign (code->expr1, code->expr2);
8349           break;
8350
8351         case EXEC_ARITHMETIC_IF:
8352           if (t == SUCCESS
8353               && code->expr1->ts.type != BT_INTEGER
8354               && code->expr1->ts.type != BT_REAL)
8355             gfc_error ("Arithmetic IF statement at %L requires a numeric "
8356                        "expression", &code->expr1->where);
8357
8358           resolve_branch (code->label1, code);
8359           resolve_branch (code->label2, code);
8360           resolve_branch (code->label3, code);
8361           break;
8362
8363         case EXEC_IF:
8364           if (t == SUCCESS && code->expr1 != NULL
8365               && (code->expr1->ts.type != BT_LOGICAL
8366                   || code->expr1->rank != 0))
8367             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8368                        &code->expr1->where);
8369           break;
8370
8371         case EXEC_CALL:
8372         call:
8373           resolve_call (code);
8374           break;
8375
8376         case EXEC_COMPCALL:
8377         compcall:
8378           resolve_typebound_subroutine (code);
8379           break;
8380
8381         case EXEC_CALL_PPC:
8382           resolve_ppc_call (code);
8383           break;
8384
8385         case EXEC_SELECT:
8386           /* Select is complicated. Also, a SELECT construct could be
8387              a transformed computed GOTO.  */
8388           resolve_select (code);
8389           break;
8390
8391         case EXEC_SELECT_TYPE:
8392           resolve_select_type (code);
8393           break;
8394
8395         case EXEC_BLOCK:
8396           gfc_resolve (code->ext.ns);
8397           break;
8398
8399         case EXEC_DO:
8400           if (code->ext.iterator != NULL)
8401             {
8402               gfc_iterator *iter = code->ext.iterator;
8403               if (gfc_resolve_iterator (iter, true) != FAILURE)
8404                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
8405             }
8406           break;
8407
8408         case EXEC_DO_WHILE:
8409           if (code->expr1 == NULL)
8410             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
8411           if (t == SUCCESS
8412               && (code->expr1->rank != 0
8413                   || code->expr1->ts.type != BT_LOGICAL))
8414             gfc_error ("Exit condition of DO WHILE loop at %L must be "
8415                        "a scalar LOGICAL expression", &code->expr1->where);
8416           break;
8417
8418         case EXEC_ALLOCATE:
8419           if (t == SUCCESS)
8420             resolve_allocate_deallocate (code, "ALLOCATE");
8421
8422           break;
8423
8424         case EXEC_DEALLOCATE:
8425           if (t == SUCCESS)
8426             resolve_allocate_deallocate (code, "DEALLOCATE");
8427
8428           break;
8429
8430         case EXEC_OPEN:
8431           if (gfc_resolve_open (code->ext.open) == FAILURE)
8432             break;
8433
8434           resolve_branch (code->ext.open->err, code);
8435           break;
8436
8437         case EXEC_CLOSE:
8438           if (gfc_resolve_close (code->ext.close) == FAILURE)
8439             break;
8440
8441           resolve_branch (code->ext.close->err, code);
8442           break;
8443
8444         case EXEC_BACKSPACE:
8445         case EXEC_ENDFILE:
8446         case EXEC_REWIND:
8447         case EXEC_FLUSH:
8448           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
8449             break;
8450
8451           resolve_branch (code->ext.filepos->err, code);
8452           break;
8453
8454         case EXEC_INQUIRE:
8455           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8456               break;
8457
8458           resolve_branch (code->ext.inquire->err, code);
8459           break;
8460
8461         case EXEC_IOLENGTH:
8462           gcc_assert (code->ext.inquire != NULL);
8463           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
8464             break;
8465
8466           resolve_branch (code->ext.inquire->err, code);
8467           break;
8468
8469         case EXEC_WAIT:
8470           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
8471             break;
8472
8473           resolve_branch (code->ext.wait->err, code);
8474           resolve_branch (code->ext.wait->end, code);
8475           resolve_branch (code->ext.wait->eor, code);
8476           break;
8477
8478         case EXEC_READ:
8479         case EXEC_WRITE:
8480           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
8481             break;
8482
8483           resolve_branch (code->ext.dt->err, code);
8484           resolve_branch (code->ext.dt->end, code);
8485           resolve_branch (code->ext.dt->eor, code);
8486           break;
8487
8488         case EXEC_TRANSFER:
8489           resolve_transfer (code);
8490           break;
8491
8492         case EXEC_FORALL:
8493           resolve_forall_iterators (code->ext.forall_iterator);
8494
8495           if (code->expr1 != NULL && code->expr1->ts.type != BT_LOGICAL)
8496             gfc_error ("FORALL mask clause at %L requires a LOGICAL "
8497                        "expression", &code->expr1->where);
8498           break;
8499
8500         case EXEC_OMP_ATOMIC:
8501         case EXEC_OMP_BARRIER:
8502         case EXEC_OMP_CRITICAL:
8503         case EXEC_OMP_FLUSH:
8504         case EXEC_OMP_DO:
8505         case EXEC_OMP_MASTER:
8506         case EXEC_OMP_ORDERED:
8507         case EXEC_OMP_SECTIONS:
8508         case EXEC_OMP_SINGLE:
8509         case EXEC_OMP_TASKWAIT:
8510         case EXEC_OMP_WORKSHARE:
8511           gfc_resolve_omp_directive (code, ns);
8512           break;
8513
8514         case EXEC_OMP_PARALLEL:
8515         case EXEC_OMP_PARALLEL_DO:
8516         case EXEC_OMP_PARALLEL_SECTIONS:
8517         case EXEC_OMP_PARALLEL_WORKSHARE:
8518         case EXEC_OMP_TASK:
8519           omp_workshare_save = omp_workshare_flag;
8520           omp_workshare_flag = 0;
8521           gfc_resolve_omp_directive (code, ns);
8522           omp_workshare_flag = omp_workshare_save;
8523           break;
8524
8525         default:
8526           gfc_internal_error ("resolve_code(): Bad statement code");
8527         }
8528     }
8529
8530   cs_base = frame.prev;
8531 }
8532
8533
8534 /* Resolve initial values and make sure they are compatible with
8535    the variable.  */
8536
8537 static void
8538 resolve_values (gfc_symbol *sym)
8539 {
8540   if (sym->value == NULL)
8541     return;
8542
8543   if (gfc_resolve_expr (sym->value) == FAILURE)
8544     return;
8545
8546   gfc_check_assign_symbol (sym, sym->value);
8547 }
8548
8549
8550 /* Verify the binding labels for common blocks that are BIND(C).  The label
8551    for a BIND(C) common block must be identical in all scoping units in which
8552    the common block is declared.  Further, the binding label can not collide
8553    with any other global entity in the program.  */
8554
8555 static void
8556 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
8557 {
8558   if (comm_block_tree->n.common->is_bind_c == 1)
8559     {
8560       gfc_gsymbol *binding_label_gsym;
8561       gfc_gsymbol *comm_name_gsym;
8562
8563       /* See if a global symbol exists by the common block's name.  It may
8564          be NULL if the common block is use-associated.  */
8565       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
8566                                          comm_block_tree->n.common->name);
8567       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
8568         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
8569                    "with the global entity '%s' at %L",
8570                    comm_block_tree->n.common->binding_label,
8571                    comm_block_tree->n.common->name,
8572                    &(comm_block_tree->n.common->where),
8573                    comm_name_gsym->name, &(comm_name_gsym->where));
8574       else if (comm_name_gsym != NULL
8575                && strcmp (comm_name_gsym->name,
8576                           comm_block_tree->n.common->name) == 0)
8577         {
8578           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
8579              as expected.  */
8580           if (comm_name_gsym->binding_label == NULL)
8581             /* No binding label for common block stored yet; save this one.  */
8582             comm_name_gsym->binding_label =
8583               comm_block_tree->n.common->binding_label;
8584           else
8585             if (strcmp (comm_name_gsym->binding_label,
8586                         comm_block_tree->n.common->binding_label) != 0)
8587               {
8588                 /* Common block names match but binding labels do not.  */
8589                 gfc_error ("Binding label '%s' for common block '%s' at %L "
8590                            "does not match the binding label '%s' for common "
8591                            "block '%s' at %L",
8592                            comm_block_tree->n.common->binding_label,
8593                            comm_block_tree->n.common->name,
8594                            &(comm_block_tree->n.common->where),
8595                            comm_name_gsym->binding_label,
8596                            comm_name_gsym->name,
8597                            &(comm_name_gsym->where));
8598                 return;
8599               }
8600         }
8601
8602       /* There is no binding label (NAME="") so we have nothing further to
8603          check and nothing to add as a global symbol for the label.  */
8604       if (comm_block_tree->n.common->binding_label[0] == '\0' )
8605         return;
8606       
8607       binding_label_gsym =
8608         gfc_find_gsymbol (gfc_gsym_root,
8609                           comm_block_tree->n.common->binding_label);
8610       if (binding_label_gsym == NULL)
8611         {
8612           /* Need to make a global symbol for the binding label to prevent
8613              it from colliding with another.  */
8614           binding_label_gsym =
8615             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
8616           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
8617           binding_label_gsym->type = GSYM_COMMON;
8618         }
8619       else
8620         {
8621           /* If comm_name_gsym is NULL, the name common block is use
8622              associated and the name could be colliding.  */
8623           if (binding_label_gsym->type != GSYM_COMMON)
8624             gfc_error ("Binding label '%s' for common block '%s' at %L "
8625                        "collides with the global entity '%s' at %L",
8626                        comm_block_tree->n.common->binding_label,
8627                        comm_block_tree->n.common->name,
8628                        &(comm_block_tree->n.common->where),
8629                        binding_label_gsym->name,
8630                        &(binding_label_gsym->where));
8631           else if (comm_name_gsym != NULL
8632                    && (strcmp (binding_label_gsym->name,
8633                                comm_name_gsym->binding_label) != 0)
8634                    && (strcmp (binding_label_gsym->sym_name,
8635                                comm_name_gsym->name) != 0))
8636             gfc_error ("Binding label '%s' for common block '%s' at %L "
8637                        "collides with global entity '%s' at %L",
8638                        binding_label_gsym->name, binding_label_gsym->sym_name,
8639                        &(comm_block_tree->n.common->where),
8640                        comm_name_gsym->name, &(comm_name_gsym->where));
8641         }
8642     }
8643   
8644   return;
8645 }
8646
8647
8648 /* Verify any BIND(C) derived types in the namespace so we can report errors
8649    for them once, rather than for each variable declared of that type.  */
8650
8651 static void
8652 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
8653 {
8654   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
8655       && derived_sym->attr.is_bind_c == 1)
8656     verify_bind_c_derived_type (derived_sym);
8657   
8658   return;
8659 }
8660
8661
8662 /* Verify that any binding labels used in a given namespace do not collide 
8663    with the names or binding labels of any global symbols.  */
8664
8665 static void
8666 gfc_verify_binding_labels (gfc_symbol *sym)
8667 {
8668   int has_error = 0;
8669   
8670   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
8671       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
8672     {
8673       gfc_gsymbol *bind_c_sym;
8674
8675       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
8676       if (bind_c_sym != NULL 
8677           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
8678         {
8679           if (sym->attr.if_source == IFSRC_DECL 
8680               && (bind_c_sym->type != GSYM_SUBROUTINE 
8681                   && bind_c_sym->type != GSYM_FUNCTION) 
8682               && ((sym->attr.contained == 1 
8683                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
8684                   || (sym->attr.use_assoc == 1 
8685                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
8686             {
8687               /* Make sure global procedures don't collide with anything.  */
8688               gfc_error ("Binding label '%s' at %L collides with the global "
8689                          "entity '%s' at %L", sym->binding_label,
8690                          &(sym->declared_at), bind_c_sym->name,
8691                          &(bind_c_sym->where));
8692               has_error = 1;
8693             }
8694           else if (sym->attr.contained == 0 
8695                    && (sym->attr.if_source == IFSRC_IFBODY 
8696                        && sym->attr.flavor == FL_PROCEDURE) 
8697                    && (bind_c_sym->sym_name != NULL 
8698                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
8699             {
8700               /* Make sure procedures in interface bodies don't collide.  */
8701               gfc_error ("Binding label '%s' in interface body at %L collides "
8702                          "with the global entity '%s' at %L",
8703                          sym->binding_label,
8704                          &(sym->declared_at), bind_c_sym->name,
8705                          &(bind_c_sym->where));
8706               has_error = 1;
8707             }
8708           else if (sym->attr.contained == 0 
8709                    && sym->attr.if_source == IFSRC_UNKNOWN)
8710             if ((sym->attr.use_assoc && bind_c_sym->mod_name
8711                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
8712                 || sym->attr.use_assoc == 0)
8713               {
8714                 gfc_error ("Binding label '%s' at %L collides with global "
8715                            "entity '%s' at %L", sym->binding_label,
8716                            &(sym->declared_at), bind_c_sym->name,
8717                            &(bind_c_sym->where));
8718                 has_error = 1;
8719               }
8720
8721           if (has_error != 0)
8722             /* Clear the binding label to prevent checking multiple times.  */
8723             sym->binding_label[0] = '\0';
8724         }
8725       else if (bind_c_sym == NULL)
8726         {
8727           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
8728           bind_c_sym->where = sym->declared_at;
8729           bind_c_sym->sym_name = sym->name;
8730
8731           if (sym->attr.use_assoc == 1)
8732             bind_c_sym->mod_name = sym->module;
8733           else
8734             if (sym->ns->proc_name != NULL)
8735               bind_c_sym->mod_name = sym->ns->proc_name->name;
8736
8737           if (sym->attr.contained == 0)
8738             {
8739               if (sym->attr.subroutine)
8740                 bind_c_sym->type = GSYM_SUBROUTINE;
8741               else if (sym->attr.function)
8742                 bind_c_sym->type = GSYM_FUNCTION;
8743             }
8744         }
8745     }
8746   return;
8747 }
8748
8749
8750 /* Resolve an index expression.  */
8751
8752 static gfc_try
8753 resolve_index_expr (gfc_expr *e)
8754 {
8755   if (gfc_resolve_expr (e) == FAILURE)
8756     return FAILURE;
8757
8758   if (gfc_simplify_expr (e, 0) == FAILURE)
8759     return FAILURE;
8760
8761   if (gfc_specification_expr (e) == FAILURE)
8762     return FAILURE;
8763
8764   return SUCCESS;
8765 }
8766
8767 /* Resolve a charlen structure.  */
8768
8769 static gfc_try
8770 resolve_charlen (gfc_charlen *cl)
8771 {
8772   int i, k;
8773
8774   if (cl->resolved)
8775     return SUCCESS;
8776
8777   cl->resolved = 1;
8778
8779   specification_expr = 1;
8780
8781   if (resolve_index_expr (cl->length) == FAILURE)
8782     {
8783       specification_expr = 0;
8784       return FAILURE;
8785     }
8786
8787   /* "If the character length parameter value evaluates to a negative
8788      value, the length of character entities declared is zero."  */
8789   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
8790     {
8791       if (gfc_option.warn_surprising)
8792         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
8793                          " the length has been set to zero",
8794                          &cl->length->where, i);
8795       gfc_replace_expr (cl->length,
8796                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
8797     }
8798
8799   /* Check that the character length is not too large.  */
8800   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
8801   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
8802       && cl->length->ts.type == BT_INTEGER
8803       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
8804     {
8805       gfc_error ("String length at %L is too large", &cl->length->where);
8806       return FAILURE;
8807     }
8808
8809   return SUCCESS;
8810 }
8811
8812
8813 /* Test for non-constant shape arrays.  */
8814
8815 static bool
8816 is_non_constant_shape_array (gfc_symbol *sym)
8817 {
8818   gfc_expr *e;
8819   int i;
8820   bool not_constant;
8821
8822   not_constant = false;
8823   if (sym->as != NULL)
8824     {
8825       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
8826          has not been simplified; parameter array references.  Do the
8827          simplification now.  */
8828       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
8829         {
8830           e = sym->as->lower[i];
8831           if (e && (resolve_index_expr (e) == FAILURE
8832                     || !gfc_is_constant_expr (e)))
8833             not_constant = true;
8834           e = sym->as->upper[i];
8835           if (e && (resolve_index_expr (e) == FAILURE
8836                     || !gfc_is_constant_expr (e)))
8837             not_constant = true;
8838         }
8839     }
8840   return not_constant;
8841 }
8842
8843 /* Given a symbol and an initialization expression, add code to initialize
8844    the symbol to the function entry.  */
8845 static void
8846 build_init_assign (gfc_symbol *sym, gfc_expr *init)
8847 {
8848   gfc_expr *lval;
8849   gfc_code *init_st;
8850   gfc_namespace *ns = sym->ns;
8851
8852   /* Search for the function namespace if this is a contained
8853      function without an explicit result.  */
8854   if (sym->attr.function && sym == sym->result
8855       && sym->name != sym->ns->proc_name->name)
8856     {
8857       ns = ns->contained;
8858       for (;ns; ns = ns->sibling)
8859         if (strcmp (ns->proc_name->name, sym->name) == 0)
8860           break;
8861     }
8862
8863   if (ns == NULL)
8864     {
8865       gfc_free_expr (init);
8866       return;
8867     }
8868
8869   /* Build an l-value expression for the result.  */
8870   lval = gfc_lval_expr_from_sym (sym);
8871
8872   /* Add the code at scope entry.  */
8873   init_st = gfc_get_code ();
8874   init_st->next = ns->code;
8875   ns->code = init_st;
8876
8877   /* Assign the default initializer to the l-value.  */
8878   init_st->loc = sym->declared_at;
8879   init_st->op = EXEC_INIT_ASSIGN;
8880   init_st->expr1 = lval;
8881   init_st->expr2 = init;
8882 }
8883
8884 /* Assign the default initializer to a derived type variable or result.  */
8885
8886 static void
8887 apply_default_init (gfc_symbol *sym)
8888 {
8889   gfc_expr *init = NULL;
8890
8891   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
8892     return;
8893
8894   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
8895     init = gfc_default_initializer (&sym->ts);
8896
8897   if (init == NULL)
8898     return;
8899
8900   build_init_assign (sym, init);
8901 }
8902
8903 /* Build an initializer for a local integer, real, complex, logical, or
8904    character variable, based on the command line flags finit-local-zero,
8905    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
8906    null if the symbol should not have a default initialization.  */
8907 static gfc_expr *
8908 build_default_init_expr (gfc_symbol *sym)
8909 {
8910   int char_len;
8911   gfc_expr *init_expr;
8912   int i;
8913
8914   /* These symbols should never have a default initialization.  */
8915   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
8916       || sym->attr.external
8917       || sym->attr.dummy
8918       || sym->attr.pointer
8919       || sym->attr.in_equivalence
8920       || sym->attr.in_common
8921       || sym->attr.data
8922       || sym->module
8923       || sym->attr.cray_pointee
8924       || sym->attr.cray_pointer)
8925     return NULL;
8926
8927   /* Now we'll try to build an initializer expression.  */
8928   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
8929                                      &sym->declared_at);
8930
8931   /* We will only initialize integers, reals, complex, logicals, and
8932      characters, and only if the corresponding command-line flags
8933      were set.  Otherwise, we free init_expr and return null.  */
8934   switch (sym->ts.type)
8935     {    
8936     case BT_INTEGER:
8937       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
8938         mpz_init_set_si (init_expr->value.integer, 
8939                          gfc_option.flag_init_integer_value);
8940       else
8941         {
8942           gfc_free_expr (init_expr);
8943           init_expr = NULL;
8944         }
8945       break;
8946
8947     case BT_REAL:
8948       mpfr_init (init_expr->value.real);
8949       switch (gfc_option.flag_init_real)
8950         {
8951         case GFC_INIT_REAL_SNAN:
8952           init_expr->is_snan = 1;
8953           /* Fall through.  */
8954         case GFC_INIT_REAL_NAN:
8955           mpfr_set_nan (init_expr->value.real);
8956           break;
8957
8958         case GFC_INIT_REAL_INF:
8959           mpfr_set_inf (init_expr->value.real, 1);
8960           break;
8961
8962         case GFC_INIT_REAL_NEG_INF:
8963           mpfr_set_inf (init_expr->value.real, -1);
8964           break;
8965
8966         case GFC_INIT_REAL_ZERO:
8967           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
8968           break;
8969
8970         default:
8971           gfc_free_expr (init_expr);
8972           init_expr = NULL;
8973           break;
8974         }
8975       break;
8976           
8977     case BT_COMPLEX:
8978       mpc_init2 (init_expr->value.complex, mpfr_get_default_prec());
8979       switch (gfc_option.flag_init_real)
8980         {
8981         case GFC_INIT_REAL_SNAN:
8982           init_expr->is_snan = 1;
8983           /* Fall through.  */
8984         case GFC_INIT_REAL_NAN:
8985           mpfr_set_nan (mpc_realref (init_expr->value.complex));
8986           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
8987           break;
8988
8989         case GFC_INIT_REAL_INF:
8990           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
8991           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
8992           break;
8993
8994         case GFC_INIT_REAL_NEG_INF:
8995           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
8996           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
8997           break;
8998
8999         case GFC_INIT_REAL_ZERO:
9000           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9001           break;
9002
9003         default:
9004           gfc_free_expr (init_expr);
9005           init_expr = NULL;
9006           break;
9007         }
9008       break;
9009           
9010     case BT_LOGICAL:
9011       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9012         init_expr->value.logical = 0;
9013       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9014         init_expr->value.logical = 1;
9015       else
9016         {
9017           gfc_free_expr (init_expr);
9018           init_expr = NULL;
9019         }
9020       break;
9021           
9022     case BT_CHARACTER:
9023       /* For characters, the length must be constant in order to 
9024          create a default initializer.  */
9025       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9026           && sym->ts.u.cl->length
9027           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9028         {
9029           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9030           init_expr->value.character.length = char_len;
9031           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9032           for (i = 0; i < char_len; i++)
9033             init_expr->value.character.string[i]
9034               = (unsigned char) gfc_option.flag_init_character_value;
9035         }
9036       else
9037         {
9038           gfc_free_expr (init_expr);
9039           init_expr = NULL;
9040         }
9041       break;
9042           
9043     default:
9044      gfc_free_expr (init_expr);
9045      init_expr = NULL;
9046     }
9047   return init_expr;
9048 }
9049
9050 /* Add an initialization expression to a local variable.  */
9051 static void
9052 apply_default_init_local (gfc_symbol *sym)
9053 {
9054   gfc_expr *init = NULL;
9055
9056   /* The symbol should be a variable or a function return value.  */
9057   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9058       || (sym->attr.function && sym->result != sym))
9059     return;
9060
9061   /* Try to build the initializer expression.  If we can't initialize
9062      this symbol, then init will be NULL.  */
9063   init = build_default_init_expr (sym);
9064   if (init == NULL)
9065     return;
9066
9067   /* For saved variables, we don't want to add an initializer at 
9068      function entry, so we just add a static initializer.  */
9069   if (sym->attr.save || sym->ns->save_all 
9070       || gfc_option.flag_max_stack_var_size == 0)
9071     {
9072       /* Don't clobber an existing initializer!  */
9073       gcc_assert (sym->value == NULL);
9074       sym->value = init;
9075       return;
9076     }
9077
9078   build_init_assign (sym, init);
9079 }
9080
9081 /* Resolution of common features of flavors variable and procedure.  */
9082
9083 static gfc_try
9084 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9085 {
9086   /* Constraints on deferred shape variable.  */
9087   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9088     {
9089       if (sym->attr.allocatable)
9090         {
9091           if (sym->attr.dimension)
9092             {
9093               gfc_error ("Allocatable array '%s' at %L must have "
9094                          "a deferred shape", sym->name, &sym->declared_at);
9095               return FAILURE;
9096             }
9097           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9098                                    "may not be ALLOCATABLE", sym->name,
9099                                    &sym->declared_at) == FAILURE)
9100             return FAILURE;
9101         }
9102
9103       if (sym->attr.pointer && sym->attr.dimension)
9104         {
9105           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
9106                      sym->name, &sym->declared_at);
9107           return FAILURE;
9108         }
9109
9110     }
9111   else
9112     {
9113       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
9114           && !sym->attr.dummy && sym->ts.type != BT_CLASS)
9115         {
9116           gfc_error ("Array '%s' at %L cannot have a deferred shape",
9117                      sym->name, &sym->declared_at);
9118           return FAILURE;
9119          }
9120     }
9121   return SUCCESS;
9122 }
9123
9124
9125 /* Additional checks for symbols with flavor variable and derived
9126    type.  To be called from resolve_fl_variable.  */
9127
9128 static gfc_try
9129 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
9130 {
9131   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
9132
9133   /* Check to see if a derived type is blocked from being host
9134      associated by the presence of another class I symbol in the same
9135      namespace.  14.6.1.3 of the standard and the discussion on
9136      comp.lang.fortran.  */
9137   if (sym->ns != sym->ts.u.derived->ns
9138       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
9139     {
9140       gfc_symbol *s;
9141       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
9142       if (s && s->attr.flavor != FL_DERIVED)
9143         {
9144           gfc_error ("The type '%s' cannot be host associated at %L "
9145                      "because it is blocked by an incompatible object "
9146                      "of the same name declared at %L",
9147                      sym->ts.u.derived->name, &sym->declared_at,
9148                      &s->declared_at);
9149           return FAILURE;
9150         }
9151     }
9152
9153   /* 4th constraint in section 11.3: "If an object of a type for which
9154      component-initialization is specified (R429) appears in the
9155      specification-part of a module and does not have the ALLOCATABLE
9156      or POINTER attribute, the object shall have the SAVE attribute."
9157
9158      The check for initializers is performed with
9159      has_default_initializer because gfc_default_initializer generates
9160      a hidden default for allocatable components.  */
9161   if (!(sym->value || no_init_flag) && sym->ns->proc_name
9162       && sym->ns->proc_name->attr.flavor == FL_MODULE
9163       && !sym->ns->save_all && !sym->attr.save
9164       && !sym->attr.pointer && !sym->attr.allocatable
9165       && has_default_initializer (sym->ts.u.derived)
9166       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
9167                          "module variable '%s' at %L, needed due to "
9168                          "the default initialization", sym->name,
9169                          &sym->declared_at) == FAILURE)
9170     return FAILURE;
9171
9172   if (sym->ts.type == BT_CLASS)
9173     {
9174       /* C502.  */
9175       if (!gfc_type_is_extensible (sym->ts.u.derived->components->ts.u.derived))
9176         {
9177           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
9178                      sym->ts.u.derived->components->ts.u.derived->name,
9179                      sym->name, &sym->declared_at);
9180           return FAILURE;
9181         }
9182
9183       /* C509.  */
9184       /* Assume that use associated symbols were checked in the module ns.  */ 
9185       if (!sym->attr.class_ok && !sym->attr.use_assoc)
9186         {
9187           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
9188                      "or pointer", sym->name, &sym->declared_at);
9189           return FAILURE;
9190         }
9191     }
9192
9193   /* Assign default initializer.  */
9194   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
9195       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
9196     {
9197       sym->value = gfc_default_initializer (&sym->ts);
9198     }
9199
9200   return SUCCESS;
9201 }
9202
9203
9204 /* Resolve symbols with flavor variable.  */
9205
9206 static gfc_try
9207 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
9208 {
9209   int no_init_flag, automatic_flag;
9210   gfc_expr *e;
9211   const char *auto_save_msg;
9212
9213   auto_save_msg = "Automatic object '%s' at %L cannot have the "
9214                   "SAVE attribute";
9215
9216   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9217     return FAILURE;
9218
9219   /* Set this flag to check that variables are parameters of all entries.
9220      This check is effected by the call to gfc_resolve_expr through
9221      is_non_constant_shape_array.  */
9222   specification_expr = 1;
9223
9224   if (sym->ns->proc_name
9225       && (sym->ns->proc_name->attr.flavor == FL_MODULE
9226           || sym->ns->proc_name->attr.is_main_program)
9227       && !sym->attr.use_assoc
9228       && !sym->attr.allocatable
9229       && !sym->attr.pointer
9230       && is_non_constant_shape_array (sym))
9231     {
9232       /* The shape of a main program or module array needs to be
9233          constant.  */
9234       gfc_error ("The module or main program array '%s' at %L must "
9235                  "have constant shape", sym->name, &sym->declared_at);
9236       specification_expr = 0;
9237       return FAILURE;
9238     }
9239
9240   if (sym->ts.type == BT_CHARACTER)
9241     {
9242       /* Make sure that character string variables with assumed length are
9243          dummy arguments.  */
9244       e = sym->ts.u.cl->length;
9245       if (e == NULL && !sym->attr.dummy && !sym->attr.result)
9246         {
9247           gfc_error ("Entity with assumed character length at %L must be a "
9248                      "dummy argument or a PARAMETER", &sym->declared_at);
9249           return FAILURE;
9250         }
9251
9252       if (e && sym->attr.save && !gfc_is_constant_expr (e))
9253         {
9254           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9255           return FAILURE;
9256         }
9257
9258       if (!gfc_is_constant_expr (e)
9259           && !(e->expr_type == EXPR_VARIABLE
9260                && e->symtree->n.sym->attr.flavor == FL_PARAMETER)
9261           && sym->ns->proc_name
9262           && (sym->ns->proc_name->attr.flavor == FL_MODULE
9263               || sym->ns->proc_name->attr.is_main_program)
9264           && !sym->attr.use_assoc)
9265         {
9266           gfc_error ("'%s' at %L must have constant character length "
9267                      "in this context", sym->name, &sym->declared_at);
9268           return FAILURE;
9269         }
9270     }
9271
9272   if (sym->value == NULL && sym->attr.referenced)
9273     apply_default_init_local (sym); /* Try to apply a default initialization.  */
9274
9275   /* Determine if the symbol may not have an initializer.  */
9276   no_init_flag = automatic_flag = 0;
9277   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
9278       || sym->attr.intrinsic || sym->attr.result)
9279     no_init_flag = 1;
9280   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
9281            && is_non_constant_shape_array (sym))
9282     {
9283       no_init_flag = automatic_flag = 1;
9284
9285       /* Also, they must not have the SAVE attribute.
9286          SAVE_IMPLICIT is checked below.  */
9287       if (sym->attr.save == SAVE_EXPLICIT)
9288         {
9289           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
9290           return FAILURE;
9291         }
9292     }
9293
9294   /* Ensure that any initializer is simplified.  */
9295   if (sym->value)
9296     gfc_simplify_expr (sym->value, 1);
9297
9298   /* Reject illegal initializers.  */
9299   if (!sym->mark && sym->value)
9300     {
9301       if (sym->attr.allocatable)
9302         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
9303                    sym->name, &sym->declared_at);
9304       else if (sym->attr.external)
9305         gfc_error ("External '%s' at %L cannot have an initializer",
9306                    sym->name, &sym->declared_at);
9307       else if (sym->attr.dummy
9308         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
9309         gfc_error ("Dummy '%s' at %L cannot have an initializer",
9310                    sym->name, &sym->declared_at);
9311       else if (sym->attr.intrinsic)
9312         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
9313                    sym->name, &sym->declared_at);
9314       else if (sym->attr.result)
9315         gfc_error ("Function result '%s' at %L cannot have an initializer",
9316                    sym->name, &sym->declared_at);
9317       else if (automatic_flag)
9318         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
9319                    sym->name, &sym->declared_at);
9320       else
9321         goto no_init_error;
9322       return FAILURE;
9323     }
9324
9325 no_init_error:
9326   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
9327     return resolve_fl_variable_derived (sym, no_init_flag);
9328
9329   return SUCCESS;
9330 }
9331
9332
9333 /* Resolve a procedure.  */
9334
9335 static gfc_try
9336 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
9337 {
9338   gfc_formal_arglist *arg;
9339
9340   if (sym->attr.function
9341       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
9342     return FAILURE;
9343
9344   if (sym->ts.type == BT_CHARACTER)
9345     {
9346       gfc_charlen *cl = sym->ts.u.cl;
9347
9348       if (cl && cl->length && gfc_is_constant_expr (cl->length)
9349              && resolve_charlen (cl) == FAILURE)
9350         return FAILURE;
9351
9352       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
9353           && sym->attr.proc == PROC_ST_FUNCTION)
9354         {
9355           gfc_error ("Character-valued statement function '%s' at %L must "
9356                      "have constant length", sym->name, &sym->declared_at);
9357           return FAILURE;
9358         }
9359     }
9360
9361   /* Ensure that derived type for are not of a private type.  Internal
9362      module procedures are excluded by 2.2.3.3 - i.e., they are not
9363      externally accessible and can access all the objects accessible in
9364      the host.  */
9365   if (!(sym->ns->parent
9366         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
9367       && gfc_check_access(sym->attr.access, sym->ns->default_access))
9368     {
9369       gfc_interface *iface;
9370
9371       for (arg = sym->formal; arg; arg = arg->next)
9372         {
9373           if (arg->sym
9374               && arg->sym->ts.type == BT_DERIVED
9375               && !arg->sym->ts.u.derived->attr.use_assoc
9376               && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9377                                     arg->sym->ts.u.derived->ns->default_access)
9378               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
9379                                  "PRIVATE type and cannot be a dummy argument"
9380                                  " of '%s', which is PUBLIC at %L",
9381                                  arg->sym->name, sym->name, &sym->declared_at)
9382                  == FAILURE)
9383             {
9384               /* Stop this message from recurring.  */
9385               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9386               return FAILURE;
9387             }
9388         }
9389
9390       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9391          PRIVATE to the containing module.  */
9392       for (iface = sym->generic; iface; iface = iface->next)
9393         {
9394           for (arg = iface->sym->formal; arg; arg = arg->next)
9395             {
9396               if (arg->sym
9397                   && arg->sym->ts.type == BT_DERIVED
9398                   && !arg->sym->ts.u.derived->attr.use_assoc
9399                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9400                                         arg->sym->ts.u.derived->ns->default_access)
9401                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
9402                                      "'%s' in PUBLIC interface '%s' at %L "
9403                                      "takes dummy arguments of '%s' which is "
9404                                      "PRIVATE", iface->sym->name, sym->name,
9405                                      &iface->sym->declared_at,
9406                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9407                 {
9408                   /* Stop this message from recurring.  */
9409                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9410                   return FAILURE;
9411                 }
9412              }
9413         }
9414
9415       /* PUBLIC interfaces may expose PRIVATE procedures that take types
9416          PRIVATE to the containing module.  */
9417       for (iface = sym->generic; iface; iface = iface->next)
9418         {
9419           for (arg = iface->sym->formal; arg; arg = arg->next)
9420             {
9421               if (arg->sym
9422                   && arg->sym->ts.type == BT_DERIVED
9423                   && !arg->sym->ts.u.derived->attr.use_assoc
9424                   && !gfc_check_access (arg->sym->ts.u.derived->attr.access,
9425                                         arg->sym->ts.u.derived->ns->default_access)
9426                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
9427                                      "'%s' in PUBLIC interface '%s' at %L "
9428                                      "takes dummy arguments of '%s' which is "
9429                                      "PRIVATE", iface->sym->name, sym->name,
9430                                      &iface->sym->declared_at,
9431                                      gfc_typename (&arg->sym->ts)) == FAILURE)
9432                 {
9433                   /* Stop this message from recurring.  */
9434                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
9435                   return FAILURE;
9436                 }
9437              }
9438         }
9439     }
9440
9441   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
9442       && !sym->attr.proc_pointer)
9443     {
9444       gfc_error ("Function '%s' at %L cannot have an initializer",
9445                  sym->name, &sym->declared_at);
9446       return FAILURE;
9447     }
9448
9449   /* An external symbol may not have an initializer because it is taken to be
9450      a procedure. Exception: Procedure Pointers.  */
9451   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
9452     {
9453       gfc_error ("External object '%s' at %L may not have an initializer",
9454                  sym->name, &sym->declared_at);
9455       return FAILURE;
9456     }
9457
9458   /* An elemental function is required to return a scalar 12.7.1  */
9459   if (sym->attr.elemental && sym->attr.function && sym->as)
9460     {
9461       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
9462                  "result", sym->name, &sym->declared_at);
9463       /* Reset so that the error only occurs once.  */
9464       sym->attr.elemental = 0;
9465       return FAILURE;
9466     }
9467
9468   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
9469      char-len-param shall not be array-valued, pointer-valued, recursive
9470      or pure.  ....snip... A character value of * may only be used in the
9471      following ways: (i) Dummy arg of procedure - dummy associates with
9472      actual length; (ii) To declare a named constant; or (iii) External
9473      function - but length must be declared in calling scoping unit.  */
9474   if (sym->attr.function
9475       && sym->ts.type == BT_CHARACTER
9476       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
9477     {
9478       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
9479           || (sym->attr.recursive) || (sym->attr.pure))
9480         {
9481           if (sym->as && sym->as->rank)
9482             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9483                        "array-valued", sym->name, &sym->declared_at);
9484
9485           if (sym->attr.pointer)
9486             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9487                        "pointer-valued", sym->name, &sym->declared_at);
9488
9489           if (sym->attr.pure)
9490             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9491                        "pure", sym->name, &sym->declared_at);
9492
9493           if (sym->attr.recursive)
9494             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
9495                        "recursive", sym->name, &sym->declared_at);
9496
9497           return FAILURE;
9498         }
9499
9500       /* Appendix B.2 of the standard.  Contained functions give an
9501          error anyway.  Fixed-form is likely to be F77/legacy.  */
9502       if (!sym->attr.contained && gfc_current_form != FORM_FIXED)
9503         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
9504                         "CHARACTER(*) function '%s' at %L",
9505                         sym->name, &sym->declared_at);
9506     }
9507
9508   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
9509     {
9510       gfc_formal_arglist *curr_arg;
9511       int has_non_interop_arg = 0;
9512
9513       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
9514                              sym->common_block) == FAILURE)
9515         {
9516           /* Clear these to prevent looking at them again if there was an
9517              error.  */
9518           sym->attr.is_bind_c = 0;
9519           sym->attr.is_c_interop = 0;
9520           sym->ts.is_c_interop = 0;
9521         }
9522       else
9523         {
9524           /* So far, no errors have been found.  */
9525           sym->attr.is_c_interop = 1;
9526           sym->ts.is_c_interop = 1;
9527         }
9528       
9529       curr_arg = sym->formal;
9530       while (curr_arg != NULL)
9531         {
9532           /* Skip implicitly typed dummy args here.  */
9533           if (curr_arg->sym->attr.implicit_type == 0)
9534             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
9535               /* If something is found to fail, record the fact so we
9536                  can mark the symbol for the procedure as not being
9537                  BIND(C) to try and prevent multiple errors being
9538                  reported.  */
9539               has_non_interop_arg = 1;
9540           
9541           curr_arg = curr_arg->next;
9542         }
9543
9544       /* See if any of the arguments were not interoperable and if so, clear
9545          the procedure symbol to prevent duplicate error messages.  */
9546       if (has_non_interop_arg != 0)
9547         {
9548           sym->attr.is_c_interop = 0;
9549           sym->ts.is_c_interop = 0;
9550           sym->attr.is_bind_c = 0;
9551         }
9552     }
9553   
9554   if (!sym->attr.proc_pointer)
9555     {
9556       if (sym->attr.save == SAVE_EXPLICIT)
9557         {
9558           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
9559                      "in '%s' at %L", sym->name, &sym->declared_at);
9560           return FAILURE;
9561         }
9562       if (sym->attr.intent)
9563         {
9564           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
9565                      "in '%s' at %L", sym->name, &sym->declared_at);
9566           return FAILURE;
9567         }
9568       if (sym->attr.subroutine && sym->attr.result)
9569         {
9570           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
9571                      "in '%s' at %L", sym->name, &sym->declared_at);
9572           return FAILURE;
9573         }
9574       if (sym->attr.external && sym->attr.function
9575           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
9576               || sym->attr.contained))
9577         {
9578           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
9579                      "in '%s' at %L", sym->name, &sym->declared_at);
9580           return FAILURE;
9581         }
9582       if (strcmp ("ppr@", sym->name) == 0)
9583         {
9584           gfc_error ("Procedure pointer result '%s' at %L "
9585                      "is missing the pointer attribute",
9586                      sym->ns->proc_name->name, &sym->declared_at);
9587           return FAILURE;
9588         }
9589     }
9590
9591   return SUCCESS;
9592 }
9593
9594
9595 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
9596    been defined and we now know their defined arguments, check that they fulfill
9597    the requirements of the standard for procedures used as finalizers.  */
9598
9599 static gfc_try
9600 gfc_resolve_finalizers (gfc_symbol* derived)
9601 {
9602   gfc_finalizer* list;
9603   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
9604   gfc_try result = SUCCESS;
9605   bool seen_scalar = false;
9606
9607   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
9608     return SUCCESS;
9609
9610   /* Walk over the list of finalizer-procedures, check them, and if any one
9611      does not fit in with the standard's definition, print an error and remove
9612      it from the list.  */
9613   prev_link = &derived->f2k_derived->finalizers;
9614   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
9615     {
9616       gfc_symbol* arg;
9617       gfc_finalizer* i;
9618       int my_rank;
9619
9620       /* Skip this finalizer if we already resolved it.  */
9621       if (list->proc_tree)
9622         {
9623           prev_link = &(list->next);
9624           continue;
9625         }
9626
9627       /* Check this exists and is a SUBROUTINE.  */
9628       if (!list->proc_sym->attr.subroutine)
9629         {
9630           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
9631                      list->proc_sym->name, &list->where);
9632           goto error;
9633         }
9634
9635       /* We should have exactly one argument.  */
9636       if (!list->proc_sym->formal || list->proc_sym->formal->next)
9637         {
9638           gfc_error ("FINAL procedure at %L must have exactly one argument",
9639                      &list->where);
9640           goto error;
9641         }
9642       arg = list->proc_sym->formal->sym;
9643
9644       /* This argument must be of our type.  */
9645       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
9646         {
9647           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
9648                      &arg->declared_at, derived->name);
9649           goto error;
9650         }
9651
9652       /* It must neither be a pointer nor allocatable nor optional.  */
9653       if (arg->attr.pointer)
9654         {
9655           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
9656                      &arg->declared_at);
9657           goto error;
9658         }
9659       if (arg->attr.allocatable)
9660         {
9661           gfc_error ("Argument of FINAL procedure at %L must not be"
9662                      " ALLOCATABLE", &arg->declared_at);
9663           goto error;
9664         }
9665       if (arg->attr.optional)
9666         {
9667           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
9668                      &arg->declared_at);
9669           goto error;
9670         }
9671
9672       /* It must not be INTENT(OUT).  */
9673       if (arg->attr.intent == INTENT_OUT)
9674         {
9675           gfc_error ("Argument of FINAL procedure at %L must not be"
9676                      " INTENT(OUT)", &arg->declared_at);
9677           goto error;
9678         }
9679
9680       /* Warn if the procedure is non-scalar and not assumed shape.  */
9681       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
9682           && arg->as->type != AS_ASSUMED_SHAPE)
9683         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
9684                      " shape argument", &arg->declared_at);
9685
9686       /* Check that it does not match in kind and rank with a FINAL procedure
9687          defined earlier.  To really loop over the *earlier* declarations,
9688          we need to walk the tail of the list as new ones were pushed at the
9689          front.  */
9690       /* TODO: Handle kind parameters once they are implemented.  */
9691       my_rank = (arg->as ? arg->as->rank : 0);
9692       for (i = list->next; i; i = i->next)
9693         {
9694           /* Argument list might be empty; that is an error signalled earlier,
9695              but we nevertheless continued resolving.  */
9696           if (i->proc_sym->formal)
9697             {
9698               gfc_symbol* i_arg = i->proc_sym->formal->sym;
9699               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
9700               if (i_rank == my_rank)
9701                 {
9702                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
9703                              " rank (%d) as '%s'",
9704                              list->proc_sym->name, &list->where, my_rank, 
9705                              i->proc_sym->name);
9706                   goto error;
9707                 }
9708             }
9709         }
9710
9711         /* Is this the/a scalar finalizer procedure?  */
9712         if (!arg->as || arg->as->rank == 0)
9713           seen_scalar = true;
9714
9715         /* Find the symtree for this procedure.  */
9716         gcc_assert (!list->proc_tree);
9717         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
9718
9719         prev_link = &list->next;
9720         continue;
9721
9722         /* Remove wrong nodes immediately from the list so we don't risk any
9723            troubles in the future when they might fail later expectations.  */
9724 error:
9725         result = FAILURE;
9726         i = list;
9727         *prev_link = list->next;
9728         gfc_free_finalizer (i);
9729     }
9730
9731   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
9732      were nodes in the list, must have been for arrays.  It is surely a good
9733      idea to have a scalar version there if there's something to finalize.  */
9734   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
9735     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
9736                  " defined at %L, suggest also scalar one",
9737                  derived->name, &derived->declared_at);
9738
9739   /* TODO:  Remove this error when finalization is finished.  */
9740   gfc_error ("Finalization at %L is not yet implemented",
9741              &derived->declared_at);
9742
9743   return result;
9744 }
9745
9746
9747 /* Check that it is ok for the typebound procedure proc to override the
9748    procedure old.  */
9749
9750 static gfc_try
9751 check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
9752 {
9753   locus where;
9754   const gfc_symbol* proc_target;
9755   const gfc_symbol* old_target;
9756   unsigned proc_pass_arg, old_pass_arg, argpos;
9757   gfc_formal_arglist* proc_formal;
9758   gfc_formal_arglist* old_formal;
9759
9760   /* This procedure should only be called for non-GENERIC proc.  */
9761   gcc_assert (!proc->n.tb->is_generic);
9762
9763   /* If the overwritten procedure is GENERIC, this is an error.  */
9764   if (old->n.tb->is_generic)
9765     {
9766       gfc_error ("Can't overwrite GENERIC '%s' at %L",
9767                  old->name, &proc->n.tb->where);
9768       return FAILURE;
9769     }
9770
9771   where = proc->n.tb->where;
9772   proc_target = proc->n.tb->u.specific->n.sym;
9773   old_target = old->n.tb->u.specific->n.sym;
9774
9775   /* Check that overridden binding is not NON_OVERRIDABLE.  */
9776   if (old->n.tb->non_overridable)
9777     {
9778       gfc_error ("'%s' at %L overrides a procedure binding declared"
9779                  " NON_OVERRIDABLE", proc->name, &where);
9780       return FAILURE;
9781     }
9782
9783   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
9784   if (!old->n.tb->deferred && proc->n.tb->deferred)
9785     {
9786       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
9787                  " non-DEFERRED binding", proc->name, &where);
9788       return FAILURE;
9789     }
9790
9791   /* If the overridden binding is PURE, the overriding must be, too.  */
9792   if (old_target->attr.pure && !proc_target->attr.pure)
9793     {
9794       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
9795                  proc->name, &where);
9796       return FAILURE;
9797     }
9798
9799   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
9800      is not, the overriding must not be either.  */
9801   if (old_target->attr.elemental && !proc_target->attr.elemental)
9802     {
9803       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
9804                  " ELEMENTAL", proc->name, &where);
9805       return FAILURE;
9806     }
9807   if (!old_target->attr.elemental && proc_target->attr.elemental)
9808     {
9809       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
9810                  " be ELEMENTAL, either", proc->name, &where);
9811       return FAILURE;
9812     }
9813
9814   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
9815      SUBROUTINE.  */
9816   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
9817     {
9818       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
9819                  " SUBROUTINE", proc->name, &where);
9820       return FAILURE;
9821     }
9822
9823   /* If the overridden binding is a FUNCTION, the overriding must also be a
9824      FUNCTION and have the same characteristics.  */
9825   if (old_target->attr.function)
9826     {
9827       if (!proc_target->attr.function)
9828         {
9829           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
9830                      " FUNCTION", proc->name, &where);
9831           return FAILURE;
9832         }
9833
9834       /* FIXME:  Do more comprehensive checking (including, for instance, the
9835          rank and array-shape).  */
9836       gcc_assert (proc_target->result && old_target->result);
9837       if (!gfc_compare_types (&proc_target->result->ts,
9838                               &old_target->result->ts))
9839         {
9840           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
9841                      " matching result types", proc->name, &where);
9842           return FAILURE;
9843         }
9844     }
9845
9846   /* If the overridden binding is PUBLIC, the overriding one must not be
9847      PRIVATE.  */
9848   if (old->n.tb->access == ACCESS_PUBLIC
9849       && proc->n.tb->access == ACCESS_PRIVATE)
9850     {
9851       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
9852                  " PRIVATE", proc->name, &where);
9853       return FAILURE;
9854     }
9855
9856   /* Compare the formal argument lists of both procedures.  This is also abused
9857      to find the position of the passed-object dummy arguments of both
9858      bindings as at least the overridden one might not yet be resolved and we
9859      need those positions in the check below.  */
9860   proc_pass_arg = old_pass_arg = 0;
9861   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
9862     proc_pass_arg = 1;
9863   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
9864     old_pass_arg = 1;
9865   argpos = 1;
9866   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
9867        proc_formal && old_formal;
9868        proc_formal = proc_formal->next, old_formal = old_formal->next)
9869     {
9870       if (proc->n.tb->pass_arg
9871           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
9872         proc_pass_arg = argpos;
9873       if (old->n.tb->pass_arg
9874           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
9875         old_pass_arg = argpos;
9876
9877       /* Check that the names correspond.  */
9878       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
9879         {
9880           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
9881                      " to match the corresponding argument of the overridden"
9882                      " procedure", proc_formal->sym->name, proc->name, &where,
9883                      old_formal->sym->name);
9884           return FAILURE;
9885         }
9886
9887       /* Check that the types correspond if neither is the passed-object
9888          argument.  */
9889       /* FIXME:  Do more comprehensive testing here.  */
9890       if (proc_pass_arg != argpos && old_pass_arg != argpos
9891           && !gfc_compare_types (&proc_formal->sym->ts, &old_formal->sym->ts))
9892         {
9893           gfc_error ("Types mismatch for dummy argument '%s' of '%s' %L "
9894                      "in respect to the overridden procedure",
9895                      proc_formal->sym->name, proc->name, &where);
9896           return FAILURE;
9897         }
9898
9899       ++argpos;
9900     }
9901   if (proc_formal || old_formal)
9902     {
9903       gfc_error ("'%s' at %L must have the same number of formal arguments as"
9904                  " the overridden procedure", proc->name, &where);
9905       return FAILURE;
9906     }
9907
9908   /* If the overridden binding is NOPASS, the overriding one must also be
9909      NOPASS.  */
9910   if (old->n.tb->nopass && !proc->n.tb->nopass)
9911     {
9912       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
9913                  " NOPASS", proc->name, &where);
9914       return FAILURE;
9915     }
9916
9917   /* If the overridden binding is PASS(x), the overriding one must also be
9918      PASS and the passed-object dummy arguments must correspond.  */
9919   if (!old->n.tb->nopass)
9920     {
9921       if (proc->n.tb->nopass)
9922         {
9923           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
9924                      " PASS", proc->name, &where);
9925           return FAILURE;
9926         }
9927
9928       if (proc_pass_arg != old_pass_arg)
9929         {
9930           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
9931                      " the same position as the passed-object dummy argument of"
9932                      " the overridden procedure", proc->name, &where);
9933           return FAILURE;
9934         }
9935     }
9936
9937   return SUCCESS;
9938 }
9939
9940
9941 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
9942
9943 static gfc_try
9944 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
9945                              const char* generic_name, locus where)
9946 {
9947   gfc_symbol* sym1;
9948   gfc_symbol* sym2;
9949
9950   gcc_assert (t1->specific && t2->specific);
9951   gcc_assert (!t1->specific->is_generic);
9952   gcc_assert (!t2->specific->is_generic);
9953
9954   sym1 = t1->specific->u.specific->n.sym;
9955   sym2 = t2->specific->u.specific->n.sym;
9956
9957   if (sym1 == sym2)
9958     return SUCCESS;
9959
9960   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
9961   if (sym1->attr.subroutine != sym2->attr.subroutine
9962       || sym1->attr.function != sym2->attr.function)
9963     {
9964       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
9965                  " GENERIC '%s' at %L",
9966                  sym1->name, sym2->name, generic_name, &where);
9967       return FAILURE;
9968     }
9969
9970   /* Compare the interfaces.  */
9971   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
9972     {
9973       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
9974                  sym1->name, sym2->name, generic_name, &where);
9975       return FAILURE;
9976     }
9977
9978   return SUCCESS;
9979 }
9980
9981
9982 /* Worker function for resolving a generic procedure binding; this is used to
9983    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
9984
9985    The difference between those cases is finding possible inherited bindings
9986    that are overridden, as one has to look for them in tb_sym_root,
9987    tb_uop_root or tb_op, respectively.  Thus the caller must already find
9988    the super-type and set p->overridden correctly.  */
9989
9990 static gfc_try
9991 resolve_tb_generic_targets (gfc_symbol* super_type,
9992                             gfc_typebound_proc* p, const char* name)
9993 {
9994   gfc_tbp_generic* target;
9995   gfc_symtree* first_target;
9996   gfc_symtree* inherited;
9997
9998   gcc_assert (p && p->is_generic);
9999
10000   /* Try to find the specific bindings for the symtrees in our target-list.  */
10001   gcc_assert (p->u.generic);
10002   for (target = p->u.generic; target; target = target->next)
10003     if (!target->specific)
10004       {
10005         gfc_typebound_proc* overridden_tbp;
10006         gfc_tbp_generic* g;
10007         const char* target_name;
10008
10009         target_name = target->specific_st->name;
10010
10011         /* Defined for this type directly.  */
10012         if (target->specific_st->n.tb)
10013           {
10014             target->specific = target->specific_st->n.tb;
10015             goto specific_found;
10016           }
10017
10018         /* Look for an inherited specific binding.  */
10019         if (super_type)
10020           {
10021             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10022                                                  true, NULL);
10023
10024             if (inherited)
10025               {
10026                 gcc_assert (inherited->n.tb);
10027                 target->specific = inherited->n.tb;
10028                 goto specific_found;
10029               }
10030           }
10031
10032         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10033                    " at %L", target_name, name, &p->where);
10034         return FAILURE;
10035
10036         /* Once we've found the specific binding, check it is not ambiguous with
10037            other specifics already found or inherited for the same GENERIC.  */
10038 specific_found:
10039         gcc_assert (target->specific);
10040
10041         /* This must really be a specific binding!  */
10042         if (target->specific->is_generic)
10043           {
10044             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10045                        " '%s' is GENERIC, too", name, &p->where, target_name);
10046             return FAILURE;
10047           }
10048
10049         /* Check those already resolved on this type directly.  */
10050         for (g = p->u.generic; g; g = g->next)
10051           if (g != target && g->specific
10052               && check_generic_tbp_ambiguity (target, g, name, p->where)
10053                   == FAILURE)
10054             return FAILURE;
10055
10056         /* Check for ambiguity with inherited specific targets.  */
10057         for (overridden_tbp = p->overridden; overridden_tbp;
10058              overridden_tbp = overridden_tbp->overridden)
10059           if (overridden_tbp->is_generic)
10060             {
10061               for (g = overridden_tbp->u.generic; g; g = g->next)
10062                 {
10063                   gcc_assert (g->specific);
10064                   if (check_generic_tbp_ambiguity (target, g,
10065                                                    name, p->where) == FAILURE)
10066                     return FAILURE;
10067                 }
10068             }
10069       }
10070
10071   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10072   if (p->overridden && !p->overridden->is_generic)
10073     {
10074       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10075                  " the same name", name, &p->where);
10076       return FAILURE;
10077     }
10078
10079   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10080      all must have the same attributes here.  */
10081   first_target = p->u.generic->specific->u.specific;
10082   gcc_assert (first_target);
10083   p->subroutine = first_target->n.sym->attr.subroutine;
10084   p->function = first_target->n.sym->attr.function;
10085
10086   return SUCCESS;
10087 }
10088
10089
10090 /* Resolve a GENERIC procedure binding for a derived type.  */
10091
10092 static gfc_try
10093 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10094 {
10095   gfc_symbol* super_type;
10096
10097   /* Find the overridden binding if any.  */
10098   st->n.tb->overridden = NULL;
10099   super_type = gfc_get_derived_super_type (derived);
10100   if (super_type)
10101     {
10102       gfc_symtree* overridden;
10103       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10104                                             true, NULL);
10105
10106       if (overridden && overridden->n.tb)
10107         st->n.tb->overridden = overridden->n.tb;
10108     }
10109
10110   /* Resolve using worker function.  */
10111   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10112 }
10113
10114
10115 /* Retrieve the target-procedure of an operator binding and do some checks in
10116    common for intrinsic and user-defined type-bound operators.  */
10117
10118 static gfc_symbol*
10119 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10120 {
10121   gfc_symbol* target_proc;
10122
10123   gcc_assert (target->specific && !target->specific->is_generic);
10124   target_proc = target->specific->u.specific->n.sym;
10125   gcc_assert (target_proc);
10126
10127   /* All operator bindings must have a passed-object dummy argument.  */
10128   if (target->specific->nopass)
10129     {
10130       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10131       return NULL;
10132     }
10133
10134   return target_proc;
10135 }
10136
10137
10138 /* Resolve a type-bound intrinsic operator.  */
10139
10140 static gfc_try
10141 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10142                                 gfc_typebound_proc* p)
10143 {
10144   gfc_symbol* super_type;
10145   gfc_tbp_generic* target;
10146   
10147   /* If there's already an error here, do nothing (but don't fail again).  */
10148   if (p->error)
10149     return SUCCESS;
10150
10151   /* Operators should always be GENERIC bindings.  */
10152   gcc_assert (p->is_generic);
10153
10154   /* Look for an overridden binding.  */
10155   super_type = gfc_get_derived_super_type (derived);
10156   if (super_type && super_type->f2k_derived)
10157     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10158                                                      op, true, NULL);
10159   else
10160     p->overridden = NULL;
10161
10162   /* Resolve general GENERIC properties using worker function.  */
10163   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10164     goto error;
10165
10166   /* Check the targets to be procedures of correct interface.  */
10167   for (target = p->u.generic; target; target = target->next)
10168     {
10169       gfc_symbol* target_proc;
10170
10171       target_proc = get_checked_tb_operator_target (target, p->where);
10172       if (!target_proc)
10173         goto error;
10174
10175       if (!gfc_check_operator_interface (target_proc, op, p->where))
10176         goto error;
10177     }
10178
10179   return SUCCESS;
10180
10181 error:
10182   p->error = 1;
10183   return FAILURE;
10184 }
10185
10186
10187 /* Resolve a type-bound user operator (tree-walker callback).  */
10188
10189 static gfc_symbol* resolve_bindings_derived;
10190 static gfc_try resolve_bindings_result;
10191
10192 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10193
10194 static void
10195 resolve_typebound_user_op (gfc_symtree* stree)
10196 {
10197   gfc_symbol* super_type;
10198   gfc_tbp_generic* target;
10199
10200   gcc_assert (stree && stree->n.tb);
10201
10202   if (stree->n.tb->error)
10203     return;
10204
10205   /* Operators should always be GENERIC bindings.  */
10206   gcc_assert (stree->n.tb->is_generic);
10207
10208   /* Find overridden procedure, if any.  */
10209   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10210   if (super_type && super_type->f2k_derived)
10211     {
10212       gfc_symtree* overridden;
10213       overridden = gfc_find_typebound_user_op (super_type, NULL,
10214                                                stree->name, true, NULL);
10215
10216       if (overridden && overridden->n.tb)
10217         stree->n.tb->overridden = overridden->n.tb;
10218     }
10219   else
10220     stree->n.tb->overridden = NULL;
10221
10222   /* Resolve basically using worker function.  */
10223   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10224         == FAILURE)
10225     goto error;
10226
10227   /* Check the targets to be functions of correct interface.  */
10228   for (target = stree->n.tb->u.generic; target; target = target->next)
10229     {
10230       gfc_symbol* target_proc;
10231
10232       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
10233       if (!target_proc)
10234         goto error;
10235
10236       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
10237         goto error;
10238     }
10239
10240   return;
10241
10242 error:
10243   resolve_bindings_result = FAILURE;
10244   stree->n.tb->error = 1;
10245 }
10246
10247
10248 /* Resolve the type-bound procedures for a derived type.  */
10249
10250 static void
10251 resolve_typebound_procedure (gfc_symtree* stree)
10252 {
10253   gfc_symbol* proc;
10254   locus where;
10255   gfc_symbol* me_arg;
10256   gfc_symbol* super_type;
10257   gfc_component* comp;
10258
10259   gcc_assert (stree);
10260
10261   /* Undefined specific symbol from GENERIC target definition.  */
10262   if (!stree->n.tb)
10263     return;
10264
10265   if (stree->n.tb->error)
10266     return;
10267
10268   /* If this is a GENERIC binding, use that routine.  */
10269   if (stree->n.tb->is_generic)
10270     {
10271       if (resolve_typebound_generic (resolve_bindings_derived, stree)
10272             == FAILURE)
10273         goto error;
10274       return;
10275     }
10276
10277   /* Get the target-procedure to check it.  */
10278   gcc_assert (!stree->n.tb->is_generic);
10279   gcc_assert (stree->n.tb->u.specific);
10280   proc = stree->n.tb->u.specific->n.sym;
10281   where = stree->n.tb->where;
10282
10283   /* Default access should already be resolved from the parser.  */
10284   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
10285
10286   /* It should be a module procedure or an external procedure with explicit
10287      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
10288   if ((!proc->attr.subroutine && !proc->attr.function)
10289       || (proc->attr.proc != PROC_MODULE
10290           && proc->attr.if_source != IFSRC_IFBODY)
10291       || (proc->attr.abstract && !stree->n.tb->deferred))
10292     {
10293       gfc_error ("'%s' must be a module procedure or an external procedure with"
10294                  " an explicit interface at %L", proc->name, &where);
10295       goto error;
10296     }
10297   stree->n.tb->subroutine = proc->attr.subroutine;
10298   stree->n.tb->function = proc->attr.function;
10299
10300   /* Find the super-type of the current derived type.  We could do this once and
10301      store in a global if speed is needed, but as long as not I believe this is
10302      more readable and clearer.  */
10303   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10304
10305   /* If PASS, resolve and check arguments if not already resolved / loaded
10306      from a .mod file.  */
10307   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
10308     {
10309       if (stree->n.tb->pass_arg)
10310         {
10311           gfc_formal_arglist* i;
10312
10313           /* If an explicit passing argument name is given, walk the arg-list
10314              and look for it.  */
10315
10316           me_arg = NULL;
10317           stree->n.tb->pass_arg_num = 1;
10318           for (i = proc->formal; i; i = i->next)
10319             {
10320               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
10321                 {
10322                   me_arg = i->sym;
10323                   break;
10324                 }
10325               ++stree->n.tb->pass_arg_num;
10326             }
10327
10328           if (!me_arg)
10329             {
10330               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
10331                          " argument '%s'",
10332                          proc->name, stree->n.tb->pass_arg, &where,
10333                          stree->n.tb->pass_arg);
10334               goto error;
10335             }
10336         }
10337       else
10338         {
10339           /* Otherwise, take the first one; there should in fact be at least
10340              one.  */
10341           stree->n.tb->pass_arg_num = 1;
10342           if (!proc->formal)
10343             {
10344               gfc_error ("Procedure '%s' with PASS at %L must have at"
10345                          " least one argument", proc->name, &where);
10346               goto error;
10347             }
10348           me_arg = proc->formal->sym;
10349         }
10350
10351       /* Now check that the argument-type matches and the passed-object
10352          dummy argument is generally fine.  */
10353
10354       gcc_assert (me_arg);
10355
10356       if (me_arg->ts.type != BT_CLASS)
10357         {
10358           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10359                      " at %L", proc->name, &where);
10360           goto error;
10361         }
10362
10363       if (me_arg->ts.u.derived->components->ts.u.derived
10364           != resolve_bindings_derived)
10365         {
10366           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10367                      " the derived-type '%s'", me_arg->name, proc->name,
10368                      me_arg->name, &where, resolve_bindings_derived->name);
10369           goto error;
10370         }
10371   
10372       gcc_assert (me_arg->ts.type == BT_CLASS);
10373       if (me_arg->ts.u.derived->components->as
10374           && me_arg->ts.u.derived->components->as->rank > 0)
10375         {
10376           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
10377                      " scalar", proc->name, &where);
10378           goto error;
10379         }
10380       if (me_arg->ts.u.derived->components->attr.allocatable)
10381         {
10382           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10383                      " be ALLOCATABLE", proc->name, &where);
10384           goto error;
10385         }
10386       if (me_arg->ts.u.derived->components->attr.class_pointer)
10387         {
10388           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
10389                      " be POINTER", proc->name, &where);
10390           goto error;
10391         }
10392     }
10393
10394   /* If we are extending some type, check that we don't override a procedure
10395      flagged NON_OVERRIDABLE.  */
10396   stree->n.tb->overridden = NULL;
10397   if (super_type)
10398     {
10399       gfc_symtree* overridden;
10400       overridden = gfc_find_typebound_proc (super_type, NULL,
10401                                             stree->name, true, NULL);
10402
10403       if (overridden && overridden->n.tb)
10404         stree->n.tb->overridden = overridden->n.tb;
10405
10406       if (overridden && check_typebound_override (stree, overridden) == FAILURE)
10407         goto error;
10408     }
10409
10410   /* See if there's a name collision with a component directly in this type.  */
10411   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
10412     if (!strcmp (comp->name, stree->name))
10413       {
10414         gfc_error ("Procedure '%s' at %L has the same name as a component of"
10415                    " '%s'",
10416                    stree->name, &where, resolve_bindings_derived->name);
10417         goto error;
10418       }
10419
10420   /* Try to find a name collision with an inherited component.  */
10421   if (super_type && gfc_find_component (super_type, stree->name, true, true))
10422     {
10423       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
10424                  " component of '%s'",
10425                  stree->name, &where, resolve_bindings_derived->name);
10426       goto error;
10427     }
10428
10429   stree->n.tb->error = 0;
10430   return;
10431
10432 error:
10433   resolve_bindings_result = FAILURE;
10434   stree->n.tb->error = 1;
10435 }
10436
10437 static gfc_try
10438 resolve_typebound_procedures (gfc_symbol* derived)
10439 {
10440   int op;
10441
10442   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
10443     return SUCCESS;
10444
10445   resolve_bindings_derived = derived;
10446   resolve_bindings_result = SUCCESS;
10447
10448   if (derived->f2k_derived->tb_sym_root)
10449     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
10450                           &resolve_typebound_procedure);
10451
10452   if (derived->f2k_derived->tb_uop_root)
10453     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
10454                           &resolve_typebound_user_op);
10455
10456   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
10457     {
10458       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
10459       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
10460                                                p) == FAILURE)
10461         resolve_bindings_result = FAILURE;
10462     }
10463
10464   return resolve_bindings_result;
10465 }
10466
10467
10468 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
10469    to give all identical derived types the same backend_decl.  */
10470 static void
10471 add_dt_to_dt_list (gfc_symbol *derived)
10472 {
10473   gfc_dt_list *dt_list;
10474
10475   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
10476     if (derived == dt_list->derived)
10477       break;
10478
10479   if (dt_list == NULL)
10480     {
10481       dt_list = gfc_get_dt_list ();
10482       dt_list->next = gfc_derived_types;
10483       dt_list->derived = derived;
10484       gfc_derived_types = dt_list;
10485     }
10486 }
10487
10488
10489 /* Ensure that a derived-type is really not abstract, meaning that every
10490    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
10491
10492 static gfc_try
10493 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
10494 {
10495   if (!st)
10496     return SUCCESS;
10497
10498   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
10499     return FAILURE;
10500   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
10501     return FAILURE;
10502
10503   if (st->n.tb && st->n.tb->deferred)
10504     {
10505       gfc_symtree* overriding;
10506       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
10507       if (!overriding)
10508         return FAILURE;
10509       gcc_assert (overriding->n.tb);
10510       if (overriding->n.tb->deferred)
10511         {
10512           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
10513                      " '%s' is DEFERRED and not overridden",
10514                      sub->name, &sub->declared_at, st->name);
10515           return FAILURE;
10516         }
10517     }
10518
10519   return SUCCESS;
10520 }
10521
10522 static gfc_try
10523 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
10524 {
10525   /* The algorithm used here is to recursively travel up the ancestry of sub
10526      and for each ancestor-type, check all bindings.  If any of them is
10527      DEFERRED, look it up starting from sub and see if the found (overriding)
10528      binding is not DEFERRED.
10529      This is not the most efficient way to do this, but it should be ok and is
10530      clearer than something sophisticated.  */
10531
10532   gcc_assert (ancestor && ancestor->attr.abstract && !sub->attr.abstract);
10533
10534   /* Walk bindings of this ancestor.  */
10535   if (ancestor->f2k_derived)
10536     {
10537       gfc_try t;
10538       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
10539       if (t == FAILURE)
10540         return FAILURE;
10541     }
10542
10543   /* Find next ancestor type and recurse on it.  */
10544   ancestor = gfc_get_derived_super_type (ancestor);
10545   if (ancestor)
10546     return ensure_not_abstract (sub, ancestor);
10547
10548   return SUCCESS;
10549 }
10550
10551
10552 static void resolve_symbol (gfc_symbol *sym);
10553
10554
10555 /* Resolve the components of a derived type.  */
10556
10557 static gfc_try
10558 resolve_fl_derived (gfc_symbol *sym)
10559 {
10560   gfc_symbol* super_type;
10561   gfc_component *c;
10562   int i;
10563
10564   super_type = gfc_get_derived_super_type (sym);
10565
10566   /* F2008, C432. */
10567   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
10568     {
10569       gfc_error ("As extending type '%s' at %L has a coarray component, "
10570                  "parent type '%s' shall also have one", sym->name,
10571                  &sym->declared_at, super_type->name);
10572       return FAILURE;
10573     }
10574
10575   /* Ensure the extended type gets resolved before we do.  */
10576   if (super_type && resolve_fl_derived (super_type) == FAILURE)
10577     return FAILURE;
10578
10579   /* An ABSTRACT type must be extensible.  */
10580   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
10581     {
10582       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
10583                  sym->name, &sym->declared_at);
10584       return FAILURE;
10585     }
10586
10587   for (c = sym->components; c != NULL; c = c->next)
10588     {
10589       /* F2008, C442.  */
10590       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
10591           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
10592         {
10593           gfc_error ("Coarray component '%s' at %L must be allocatable with "
10594                      "deferred shape", c->name, &c->loc);
10595           return FAILURE;
10596         }
10597
10598       /* F2008, C443.  */
10599       if (c->attr.codimension && c->ts.type == BT_DERIVED
10600           && c->ts.u.derived->ts.is_iso_c)
10601         {
10602           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
10603                      "shall not be a coarray", c->name, &c->loc);
10604           return FAILURE;
10605         }
10606
10607       /* F2008, C444.  */
10608       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
10609           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
10610               || c->attr.allocatable))
10611         {
10612           gfc_error ("Component '%s' at %L with coarray component "
10613                      "shall be a nonpointer, nonallocatable scalar",
10614                      c->name, &c->loc);
10615           return FAILURE;
10616         }
10617
10618       if (c->attr.proc_pointer && c->ts.interface)
10619         {
10620           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
10621             gfc_error ("Interface '%s', used by procedure pointer component "
10622                        "'%s' at %L, is declared in a later PROCEDURE statement",
10623                        c->ts.interface->name, c->name, &c->loc);
10624
10625           /* Get the attributes from the interface (now resolved).  */
10626           if (c->ts.interface->attr.if_source
10627               || c->ts.interface->attr.intrinsic)
10628             {
10629               gfc_symbol *ifc = c->ts.interface;
10630
10631               if (ifc->formal && !ifc->formal_ns)
10632                 resolve_symbol (ifc);
10633
10634               if (ifc->attr.intrinsic)
10635                 resolve_intrinsic (ifc, &ifc->declared_at);
10636
10637               if (ifc->result)
10638                 {
10639                   c->ts = ifc->result->ts;
10640                   c->attr.allocatable = ifc->result->attr.allocatable;
10641                   c->attr.pointer = ifc->result->attr.pointer;
10642                   c->attr.dimension = ifc->result->attr.dimension;
10643                   c->as = gfc_copy_array_spec (ifc->result->as);
10644                 }
10645               else
10646                 {   
10647                   c->ts = ifc->ts;
10648                   c->attr.allocatable = ifc->attr.allocatable;
10649                   c->attr.pointer = ifc->attr.pointer;
10650                   c->attr.dimension = ifc->attr.dimension;
10651                   c->as = gfc_copy_array_spec (ifc->as);
10652                 }
10653               c->ts.interface = ifc;
10654               c->attr.function = ifc->attr.function;
10655               c->attr.subroutine = ifc->attr.subroutine;
10656               gfc_copy_formal_args_ppc (c, ifc);
10657
10658               c->attr.pure = ifc->attr.pure;
10659               c->attr.elemental = ifc->attr.elemental;
10660               c->attr.recursive = ifc->attr.recursive;
10661               c->attr.always_explicit = ifc->attr.always_explicit;
10662               c->attr.ext_attr |= ifc->attr.ext_attr;
10663               /* Replace symbols in array spec.  */
10664               if (c->as)
10665                 {
10666                   int i;
10667                   for (i = 0; i < c->as->rank; i++)
10668                     {
10669                       gfc_expr_replace_comp (c->as->lower[i], c);
10670                       gfc_expr_replace_comp (c->as->upper[i], c);
10671                     }
10672                 }
10673               /* Copy char length.  */
10674               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
10675                 {
10676                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
10677                   gfc_expr_replace_comp (cl->length, c);
10678                   if (cl->length && !cl->resolved
10679                         && gfc_resolve_expr (cl->length) == FAILURE)
10680                     return FAILURE;
10681                   c->ts.u.cl = cl;
10682                 }
10683             }
10684           else if (c->ts.interface->name[0] != '\0' && !sym->attr.vtype)
10685             {
10686               gfc_error ("Interface '%s' of procedure pointer component "
10687                          "'%s' at %L must be explicit", c->ts.interface->name,
10688                          c->name, &c->loc);
10689               return FAILURE;
10690             }
10691         }
10692       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
10693         {
10694           /* Since PPCs are not implicitly typed, a PPC without an explicit
10695              interface must be a subroutine.  */
10696           gfc_add_subroutine (&c->attr, c->name, &c->loc);
10697         }
10698
10699       /* Procedure pointer components: Check PASS arg.  */
10700       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
10701           && !sym->attr.vtype)
10702         {
10703           gfc_symbol* me_arg;
10704
10705           if (c->tb->pass_arg)
10706             {
10707               gfc_formal_arglist* i;
10708
10709               /* If an explicit passing argument name is given, walk the arg-list
10710                 and look for it.  */
10711
10712               me_arg = NULL;
10713               c->tb->pass_arg_num = 1;
10714               for (i = c->formal; i; i = i->next)
10715                 {
10716                   if (!strcmp (i->sym->name, c->tb->pass_arg))
10717                     {
10718                       me_arg = i->sym;
10719                       break;
10720                     }
10721                   c->tb->pass_arg_num++;
10722                 }
10723
10724               if (!me_arg)
10725                 {
10726                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
10727                              "at %L has no argument '%s'", c->name,
10728                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
10729                   c->tb->error = 1;
10730                   return FAILURE;
10731                 }
10732             }
10733           else
10734             {
10735               /* Otherwise, take the first one; there should in fact be at least
10736                 one.  */
10737               c->tb->pass_arg_num = 1;
10738               if (!c->formal)
10739                 {
10740                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
10741                              "must have at least one argument",
10742                              c->name, &c->loc);
10743                   c->tb->error = 1;
10744                   return FAILURE;
10745                 }
10746               me_arg = c->formal->sym;
10747             }
10748
10749           /* Now check that the argument-type matches.  */
10750           gcc_assert (me_arg);
10751           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
10752               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
10753               || (me_arg->ts.type == BT_CLASS
10754                   && me_arg->ts.u.derived->components->ts.u.derived != sym))
10755             {
10756               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
10757                          " the derived type '%s'", me_arg->name, c->name,
10758                          me_arg->name, &c->loc, sym->name);
10759               c->tb->error = 1;
10760               return FAILURE;
10761             }
10762
10763           /* Check for C453.  */
10764           if (me_arg->attr.dimension)
10765             {
10766               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10767                          "must be scalar", me_arg->name, c->name, me_arg->name,
10768                          &c->loc);
10769               c->tb->error = 1;
10770               return FAILURE;
10771             }
10772
10773           if (me_arg->attr.pointer)
10774             {
10775               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10776                          "may not have the POINTER attribute", me_arg->name,
10777                          c->name, me_arg->name, &c->loc);
10778               c->tb->error = 1;
10779               return FAILURE;
10780             }
10781
10782           if (me_arg->attr.allocatable)
10783             {
10784               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
10785                          "may not be ALLOCATABLE", me_arg->name, c->name,
10786                          me_arg->name, &c->loc);
10787               c->tb->error = 1;
10788               return FAILURE;
10789             }
10790
10791           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
10792             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
10793                        " at %L", c->name, &c->loc);
10794
10795         }
10796
10797       /* Check type-spec if this is not the parent-type component.  */
10798       if ((!sym->attr.extension || c != sym->components)
10799           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
10800         return FAILURE;
10801
10802       /* If this type is an extension, set the accessibility of the parent
10803          component.  */
10804       if (super_type && c == sym->components
10805           && strcmp (super_type->name, c->name) == 0)
10806         c->attr.access = super_type->attr.access;
10807       
10808       /* If this type is an extension, see if this component has the same name
10809          as an inherited type-bound procedure.  */
10810       if (super_type && !sym->attr.is_class
10811           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
10812         {
10813           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
10814                      " inherited type-bound procedure",
10815                      c->name, sym->name, &c->loc);
10816           return FAILURE;
10817         }
10818
10819       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
10820         {
10821          if (c->ts.u.cl->length == NULL
10822              || (resolve_charlen (c->ts.u.cl) == FAILURE)
10823              || !gfc_is_constant_expr (c->ts.u.cl->length))
10824            {
10825              gfc_error ("Character length of component '%s' needs to "
10826                         "be a constant specification expression at %L",
10827                         c->name,
10828                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
10829              return FAILURE;
10830            }
10831         }
10832
10833       if (c->ts.type == BT_DERIVED
10834           && sym->component_access != ACCESS_PRIVATE
10835           && gfc_check_access (sym->attr.access, sym->ns->default_access)
10836           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
10837           && !c->ts.u.derived->attr.use_assoc
10838           && !gfc_check_access (c->ts.u.derived->attr.access,
10839                                 c->ts.u.derived->ns->default_access)
10840           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
10841                              "is a PRIVATE type and cannot be a component of "
10842                              "'%s', which is PUBLIC at %L", c->name,
10843                              sym->name, &sym->declared_at) == FAILURE)
10844         return FAILURE;
10845
10846       if (sym->attr.sequence)
10847         {
10848           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
10849             {
10850               gfc_error ("Component %s of SEQUENCE type declared at %L does "
10851                          "not have the SEQUENCE attribute",
10852                          c->ts.u.derived->name, &sym->declared_at);
10853               return FAILURE;
10854             }
10855         }
10856
10857       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && c->attr.pointer
10858           && c->ts.u.derived->components == NULL
10859           && !c->ts.u.derived->attr.zero_comp)
10860         {
10861           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
10862                      "that has not been declared", c->name, sym->name,
10863                      &c->loc);
10864           return FAILURE;
10865         }
10866
10867       if (c->ts.type == BT_CLASS && c->ts.u.derived->components->attr.pointer
10868           && c->ts.u.derived->components->ts.u.derived->components == NULL
10869           && !c->ts.u.derived->components->ts.u.derived->attr.zero_comp)
10870         {
10871           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
10872                      "that has not been declared", c->name, sym->name,
10873                      &c->loc);
10874           return FAILURE;
10875         }
10876
10877       /* C437.  */
10878       if (c->ts.type == BT_CLASS
10879           && !(c->ts.u.derived->components->attr.pointer
10880                || c->ts.u.derived->components->attr.allocatable))
10881         {
10882           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
10883                      "or pointer", c->name, &c->loc);
10884           return FAILURE;
10885         }
10886
10887       /* Ensure that all the derived type components are put on the
10888          derived type list; even in formal namespaces, where derived type
10889          pointer components might not have been declared.  */
10890       if (c->ts.type == BT_DERIVED
10891             && c->ts.u.derived
10892             && c->ts.u.derived->components
10893             && c->attr.pointer
10894             && sym != c->ts.u.derived)
10895         add_dt_to_dt_list (c->ts.u.derived);
10896
10897       if (c->attr.pointer || c->attr.proc_pointer || c->attr.allocatable
10898           || c->as == NULL)
10899         continue;
10900
10901       for (i = 0; i < c->as->rank; i++)
10902         {
10903           if (c->as->lower[i] == NULL
10904               || (resolve_index_expr (c->as->lower[i]) == FAILURE)
10905               || !gfc_is_constant_expr (c->as->lower[i])
10906               || c->as->upper[i] == NULL
10907               || (resolve_index_expr (c->as->upper[i]) == FAILURE)
10908               || !gfc_is_constant_expr (c->as->upper[i]))
10909             {
10910               gfc_error ("Component '%s' of '%s' at %L must have "
10911                          "constant array bounds",
10912                          c->name, sym->name, &c->loc);
10913               return FAILURE;
10914             }
10915         }
10916     }
10917
10918   /* Resolve the type-bound procedures.  */
10919   if (resolve_typebound_procedures (sym) == FAILURE)
10920     return FAILURE;
10921
10922   /* Resolve the finalizer procedures.  */
10923   if (gfc_resolve_finalizers (sym) == FAILURE)
10924     return FAILURE;
10925
10926   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
10927      all DEFERRED bindings are overridden.  */
10928   if (super_type && super_type->attr.abstract && !sym->attr.abstract
10929       && ensure_not_abstract (sym, super_type) == FAILURE)
10930     return FAILURE;
10931
10932   /* Add derived type to the derived type list.  */
10933   add_dt_to_dt_list (sym);
10934
10935   return SUCCESS;
10936 }
10937
10938
10939 static gfc_try
10940 resolve_fl_namelist (gfc_symbol *sym)
10941 {
10942   gfc_namelist *nl;
10943   gfc_symbol *nlsym;
10944
10945   /* Reject PRIVATE objects in a PUBLIC namelist.  */
10946   if (gfc_check_access(sym->attr.access, sym->ns->default_access))
10947     {
10948       for (nl = sym->namelist; nl; nl = nl->next)
10949         {
10950           if (!nl->sym->attr.use_assoc
10951               && !is_sym_host_assoc (nl->sym, sym->ns)
10952               && !gfc_check_access(nl->sym->attr.access,
10953                                 nl->sym->ns->default_access))
10954             {
10955               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
10956                          "cannot be member of PUBLIC namelist '%s' at %L",
10957                          nl->sym->name, sym->name, &sym->declared_at);
10958               return FAILURE;
10959             }
10960
10961           /* Types with private components that came here by USE-association.  */
10962           if (nl->sym->ts.type == BT_DERIVED
10963               && derived_inaccessible (nl->sym->ts.u.derived))
10964             {
10965               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
10966                          "components and cannot be member of namelist '%s' at %L",
10967                          nl->sym->name, sym->name, &sym->declared_at);
10968               return FAILURE;
10969             }
10970
10971           /* Types with private components that are defined in the same module.  */
10972           if (nl->sym->ts.type == BT_DERIVED
10973               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
10974               && !gfc_check_access (nl->sym->ts.u.derived->attr.private_comp
10975                                         ? ACCESS_PRIVATE : ACCESS_UNKNOWN,
10976                                         nl->sym->ns->default_access))
10977             {
10978               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
10979                          "cannot be a member of PUBLIC namelist '%s' at %L",
10980                          nl->sym->name, sym->name, &sym->declared_at);
10981               return FAILURE;
10982             }
10983         }
10984     }
10985
10986   for (nl = sym->namelist; nl; nl = nl->next)
10987     {
10988       /* Reject namelist arrays of assumed shape.  */
10989       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
10990           && gfc_notify_std (GFC_STD_F2003, "NAMELIST array object '%s' "
10991                              "must not have assumed shape in namelist "
10992                              "'%s' at %L", nl->sym->name, sym->name,
10993                              &sym->declared_at) == FAILURE)
10994             return FAILURE;
10995
10996       /* Reject namelist arrays that are not constant shape.  */
10997       if (is_non_constant_shape_array (nl->sym))
10998         {
10999           gfc_error ("NAMELIST array object '%s' must have constant "
11000                      "shape in namelist '%s' at %L", nl->sym->name,
11001                      sym->name, &sym->declared_at);
11002           return FAILURE;
11003         }
11004
11005       /* Namelist objects cannot have allocatable or pointer components.  */
11006       if (nl->sym->ts.type != BT_DERIVED)
11007         continue;
11008
11009       if (nl->sym->ts.u.derived->attr.alloc_comp)
11010         {
11011           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11012                      "have ALLOCATABLE components",
11013                      nl->sym->name, sym->name, &sym->declared_at);
11014           return FAILURE;
11015         }
11016
11017       if (nl->sym->ts.u.derived->attr.pointer_comp)
11018         {
11019           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L cannot "
11020                      "have POINTER components", 
11021                      nl->sym->name, sym->name, &sym->declared_at);
11022           return FAILURE;
11023         }
11024     }
11025
11026
11027   /* 14.1.2 A module or internal procedure represent local entities
11028      of the same type as a namelist member and so are not allowed.  */
11029   for (nl = sym->namelist; nl; nl = nl->next)
11030     {
11031       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11032         continue;
11033
11034       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11035         if ((nl->sym == sym->ns->proc_name)
11036                ||
11037             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11038           continue;
11039
11040       nlsym = NULL;
11041       if (nl->sym && nl->sym->name)
11042         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11043       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11044         {
11045           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11046                      "attribute in '%s' at %L", nlsym->name,
11047                      &sym->declared_at);
11048           return FAILURE;
11049         }
11050     }
11051
11052   return SUCCESS;
11053 }
11054
11055
11056 static gfc_try
11057 resolve_fl_parameter (gfc_symbol *sym)
11058 {
11059   /* A parameter array's shape needs to be constant.  */
11060   if (sym->as != NULL 
11061       && (sym->as->type == AS_DEFERRED
11062           || is_non_constant_shape_array (sym)))
11063     {
11064       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11065                  "or of deferred shape", sym->name, &sym->declared_at);
11066       return FAILURE;
11067     }
11068
11069   /* Make sure a parameter that has been implicitly typed still
11070      matches the implicit type, since PARAMETER statements can precede
11071      IMPLICIT statements.  */
11072   if (sym->attr.implicit_type
11073       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11074                                                              sym->ns)))
11075     {
11076       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11077                  "later IMPLICIT type", sym->name, &sym->declared_at);
11078       return FAILURE;
11079     }
11080
11081   /* Make sure the types of derived parameters are consistent.  This
11082      type checking is deferred until resolution because the type may
11083      refer to a derived type from the host.  */
11084   if (sym->ts.type == BT_DERIVED
11085       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11086     {
11087       gfc_error ("Incompatible derived type in PARAMETER at %L",
11088                  &sym->value->where);
11089       return FAILURE;
11090     }
11091   return SUCCESS;
11092 }
11093
11094
11095 /* Do anything necessary to resolve a symbol.  Right now, we just
11096    assume that an otherwise unknown symbol is a variable.  This sort
11097    of thing commonly happens for symbols in module.  */
11098
11099 static void
11100 resolve_symbol (gfc_symbol *sym)
11101 {
11102   int check_constant, mp_flag;
11103   gfc_symtree *symtree;
11104   gfc_symtree *this_symtree;
11105   gfc_namespace *ns;
11106   gfc_component *c;
11107
11108   if (sym->attr.flavor == FL_UNKNOWN)
11109     {
11110
11111     /* If we find that a flavorless symbol is an interface in one of the
11112        parent namespaces, find its symtree in this namespace, free the
11113        symbol and set the symtree to point to the interface symbol.  */
11114       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11115         {
11116           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11117           if (symtree && symtree->n.sym->generic)
11118             {
11119               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11120                                                sym->name);
11121               sym->refs--;
11122               if (!sym->refs)
11123                 gfc_free_symbol (sym);
11124               symtree->n.sym->refs++;
11125               this_symtree->n.sym = symtree->n.sym;
11126               return;
11127             }
11128         }
11129
11130       /* Otherwise give it a flavor according to such attributes as
11131          it has.  */
11132       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11133         sym->attr.flavor = FL_VARIABLE;
11134       else
11135         {
11136           sym->attr.flavor = FL_PROCEDURE;
11137           if (sym->attr.dimension)
11138             sym->attr.function = 1;
11139         }
11140     }
11141
11142   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11143     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11144
11145   if (sym->attr.procedure && sym->ts.interface
11146       && sym->attr.if_source != IFSRC_DECL)
11147     {
11148       if (sym->ts.interface == sym)
11149         {
11150           gfc_error ("PROCEDURE '%s' at %L may not be used as its own "
11151                      "interface", sym->name, &sym->declared_at);
11152           return;
11153         }
11154       if (sym->ts.interface->attr.procedure)
11155         {
11156           gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared"
11157                      " in a later PROCEDURE statement", sym->ts.interface->name,
11158                      sym->name,&sym->declared_at);
11159           return;
11160         }
11161
11162       /* Get the attributes from the interface (now resolved).  */
11163       if (sym->ts.interface->attr.if_source
11164           || sym->ts.interface->attr.intrinsic)
11165         {
11166           gfc_symbol *ifc = sym->ts.interface;
11167           resolve_symbol (ifc);
11168
11169           if (ifc->attr.intrinsic)
11170             resolve_intrinsic (ifc, &ifc->declared_at);
11171
11172           if (ifc->result)
11173             sym->ts = ifc->result->ts;
11174           else   
11175             sym->ts = ifc->ts;
11176           sym->ts.interface = ifc;
11177           sym->attr.function = ifc->attr.function;
11178           sym->attr.subroutine = ifc->attr.subroutine;
11179           gfc_copy_formal_args (sym, ifc);
11180
11181           sym->attr.allocatable = ifc->attr.allocatable;
11182           sym->attr.pointer = ifc->attr.pointer;
11183           sym->attr.pure = ifc->attr.pure;
11184           sym->attr.elemental = ifc->attr.elemental;
11185           sym->attr.dimension = ifc->attr.dimension;
11186           sym->attr.recursive = ifc->attr.recursive;
11187           sym->attr.always_explicit = ifc->attr.always_explicit;
11188           sym->attr.ext_attr |= ifc->attr.ext_attr;
11189           /* Copy array spec.  */
11190           sym->as = gfc_copy_array_spec (ifc->as);
11191           if (sym->as)
11192             {
11193               int i;
11194               for (i = 0; i < sym->as->rank; i++)
11195                 {
11196                   gfc_expr_replace_symbols (sym->as->lower[i], sym);
11197                   gfc_expr_replace_symbols (sym->as->upper[i], sym);
11198                 }
11199             }
11200           /* Copy char length.  */
11201           if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11202             {
11203               sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11204               gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
11205               if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
11206                     && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
11207                 return;
11208             }
11209         }
11210       else if (sym->ts.interface->name[0] != '\0')
11211         {
11212           gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
11213                     sym->ts.interface->name, sym->name, &sym->declared_at);
11214           return;
11215         }
11216     }
11217
11218   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11219     return;
11220
11221   /* Symbols that are module procedures with results (functions) have
11222      the types and array specification copied for type checking in
11223      procedures that call them, as well as for saving to a module
11224      file.  These symbols can't stand the scrutiny that their results
11225      can.  */
11226   mp_flag = (sym->result != NULL && sym->result != sym);
11227
11228
11229   /* Make sure that the intrinsic is consistent with its internal 
11230      representation. This needs to be done before assigning a default 
11231      type to avoid spurious warnings.  */
11232   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11233       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11234     return;
11235
11236   /* Assign default type to symbols that need one and don't have one.  */
11237   if (sym->ts.type == BT_UNKNOWN)
11238     {
11239       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
11240         gfc_set_default_type (sym, 1, NULL);
11241
11242       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
11243           && !sym->attr.function && !sym->attr.subroutine
11244           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
11245         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
11246
11247       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
11248         {
11249           /* The specific case of an external procedure should emit an error
11250              in the case that there is no implicit type.  */
11251           if (!mp_flag)
11252             gfc_set_default_type (sym, sym->attr.external, NULL);
11253           else
11254             {
11255               /* Result may be in another namespace.  */
11256               resolve_symbol (sym->result);
11257
11258               if (!sym->result->attr.proc_pointer)
11259                 {
11260                   sym->ts = sym->result->ts;
11261                   sym->as = gfc_copy_array_spec (sym->result->as);
11262                   sym->attr.dimension = sym->result->attr.dimension;
11263                   sym->attr.pointer = sym->result->attr.pointer;
11264                   sym->attr.allocatable = sym->result->attr.allocatable;
11265                 }
11266             }
11267         }
11268     }
11269
11270   /* Assumed size arrays and assumed shape arrays must be dummy
11271      arguments.  */
11272
11273   if (sym->as != NULL
11274       && ((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
11275           || sym->as->type == AS_ASSUMED_SHAPE)
11276       && sym->attr.dummy == 0)
11277     {
11278       if (sym->as->type == AS_ASSUMED_SIZE)
11279         gfc_error ("Assumed size array at %L must be a dummy argument",
11280                    &sym->declared_at);
11281       else
11282         gfc_error ("Assumed shape array at %L must be a dummy argument",
11283                    &sym->declared_at);
11284       return;
11285     }
11286
11287   /* Make sure symbols with known intent or optional are really dummy
11288      variable.  Because of ENTRY statement, this has to be deferred
11289      until resolution time.  */
11290
11291   if (!sym->attr.dummy
11292       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
11293     {
11294       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
11295       return;
11296     }
11297
11298   if (sym->attr.value && !sym->attr.dummy)
11299     {
11300       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
11301                  "it is not a dummy argument", sym->name, &sym->declared_at);
11302       return;
11303     }
11304
11305   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
11306     {
11307       gfc_charlen *cl = sym->ts.u.cl;
11308       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
11309         {
11310           gfc_error ("Character dummy variable '%s' at %L with VALUE "
11311                      "attribute must have constant length",
11312                      sym->name, &sym->declared_at);
11313           return;
11314         }
11315
11316       if (sym->ts.is_c_interop
11317           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
11318         {
11319           gfc_error ("C interoperable character dummy variable '%s' at %L "
11320                      "with VALUE attribute must have length one",
11321                      sym->name, &sym->declared_at);
11322           return;
11323         }
11324     }
11325
11326   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
11327      do this for something that was implicitly typed because that is handled
11328      in gfc_set_default_type.  Handle dummy arguments and procedure
11329      definitions separately.  Also, anything that is use associated is not
11330      handled here but instead is handled in the module it is declared in.
11331      Finally, derived type definitions are allowed to be BIND(C) since that
11332      only implies that they're interoperable, and they are checked fully for
11333      interoperability when a variable is declared of that type.  */
11334   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
11335       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
11336       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
11337     {
11338       gfc_try t = SUCCESS;
11339       
11340       /* First, make sure the variable is declared at the
11341          module-level scope (J3/04-007, Section 15.3).  */
11342       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
11343           sym->attr.in_common == 0)
11344         {
11345           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
11346                      "is neither a COMMON block nor declared at the "
11347                      "module level scope", sym->name, &(sym->declared_at));
11348           t = FAILURE;
11349         }
11350       else if (sym->common_head != NULL)
11351         {
11352           t = verify_com_block_vars_c_interop (sym->common_head);
11353         }
11354       else
11355         {
11356           /* If type() declaration, we need to verify that the components
11357              of the given type are all C interoperable, etc.  */
11358           if (sym->ts.type == BT_DERIVED &&
11359               sym->ts.u.derived->attr.is_c_interop != 1)
11360             {
11361               /* Make sure the user marked the derived type as BIND(C).  If
11362                  not, call the verify routine.  This could print an error
11363                  for the derived type more than once if multiple variables
11364                  of that type are declared.  */
11365               if (sym->ts.u.derived->attr.is_bind_c != 1)
11366                 verify_bind_c_derived_type (sym->ts.u.derived);
11367               t = FAILURE;
11368             }
11369           
11370           /* Verify the variable itself as C interoperable if it
11371              is BIND(C).  It is not possible for this to succeed if
11372              the verify_bind_c_derived_type failed, so don't have to handle
11373              any error returned by verify_bind_c_derived_type.  */
11374           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
11375                                  sym->common_block);
11376         }
11377
11378       if (t == FAILURE)
11379         {
11380           /* clear the is_bind_c flag to prevent reporting errors more than
11381              once if something failed.  */
11382           sym->attr.is_bind_c = 0;
11383           return;
11384         }
11385     }
11386
11387   /* If a derived type symbol has reached this point, without its
11388      type being declared, we have an error.  Notice that most
11389      conditions that produce undefined derived types have already
11390      been dealt with.  However, the likes of:
11391      implicit type(t) (t) ..... call foo (t) will get us here if
11392      the type is not declared in the scope of the implicit
11393      statement. Change the type to BT_UNKNOWN, both because it is so
11394      and to prevent an ICE.  */
11395   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
11396       && !sym->ts.u.derived->attr.zero_comp)
11397     {
11398       gfc_error ("The derived type '%s' at %L is of type '%s', "
11399                  "which has not been defined", sym->name,
11400                   &sym->declared_at, sym->ts.u.derived->name);
11401       sym->ts.type = BT_UNKNOWN;
11402       return;
11403     }
11404
11405   /* Make sure that the derived type has been resolved and that the
11406      derived type is visible in the symbol's namespace, if it is a
11407      module function and is not PRIVATE.  */
11408   if (sym->ts.type == BT_DERIVED
11409         && sym->ts.u.derived->attr.use_assoc
11410         && sym->ns->proc_name
11411         && sym->ns->proc_name->attr.flavor == FL_MODULE)
11412     {
11413       gfc_symbol *ds;
11414
11415       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
11416         return;
11417
11418       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
11419       if (!ds && sym->attr.function
11420             && gfc_check_access (sym->attr.access, sym->ns->default_access))
11421         {
11422           symtree = gfc_new_symtree (&sym->ns->sym_root,
11423                                      sym->ts.u.derived->name);
11424           symtree->n.sym = sym->ts.u.derived;
11425           sym->ts.u.derived->refs++;
11426         }
11427     }
11428
11429   /* Unless the derived-type declaration is use associated, Fortran 95
11430      does not allow public entries of private derived types.
11431      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
11432      161 in 95-006r3.  */
11433   if (sym->ts.type == BT_DERIVED
11434       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
11435       && !sym->ts.u.derived->attr.use_assoc
11436       && gfc_check_access (sym->attr.access, sym->ns->default_access)
11437       && !gfc_check_access (sym->ts.u.derived->attr.access,
11438                             sym->ts.u.derived->ns->default_access)
11439       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
11440                          "of PRIVATE derived type '%s'",
11441                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
11442                          : "variable", sym->name, &sym->declared_at,
11443                          sym->ts.u.derived->name) == FAILURE)
11444     return;
11445
11446   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
11447      default initialization is defined (5.1.2.4.4).  */
11448   if (sym->ts.type == BT_DERIVED
11449       && sym->attr.dummy
11450       && sym->attr.intent == INTENT_OUT
11451       && sym->as
11452       && sym->as->type == AS_ASSUMED_SIZE)
11453     {
11454       for (c = sym->ts.u.derived->components; c; c = c->next)
11455         {
11456           if (c->initializer)
11457             {
11458               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
11459                          "ASSUMED SIZE and so cannot have a default initializer",
11460                          sym->name, &sym->declared_at);
11461               return;
11462             }
11463         }
11464     }
11465
11466   /* F2008, C526.  */
11467   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11468        || sym->attr.codimension)
11469       && sym->attr.result)
11470     gfc_error ("Function result '%s' at %L shall not be a coarray or have "
11471                "a coarray component", sym->name, &sym->declared_at);
11472
11473   /* F2008, C524.  */
11474   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
11475       && sym->ts.u.derived->ts.is_iso_c)
11476     gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11477                "shall not be a coarray", sym->name, &sym->declared_at);
11478
11479   /* F2008, C525.  */
11480   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
11481       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
11482           || sym->attr.allocatable))
11483     gfc_error ("Variable '%s' at %L with coarray component "
11484                "shall be a nonpointer, nonallocatable scalar",
11485                sym->name, &sym->declared_at);
11486
11487   /* F2008, C526.  The function-result case was handled above.  */
11488   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11489        || sym->attr.codimension)
11490       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
11491            || sym->ns->proc_name->attr.flavor == FL_MODULE
11492            || sym->ns->proc_name->attr.is_main_program
11493            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
11494     gfc_error ("Variable '%s' at %L is a coarray or has a coarray "
11495                "component and is not ALLOCATABLE, SAVE nor a "
11496                "dummy argument", sym->name, &sym->declared_at);
11497   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
11498   else if (sym->attr.codimension && !sym->attr.allocatable
11499       && sym->as && sym->as->cotype == AS_DEFERRED)
11500     gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
11501                 "deferred shape", sym->name, &sym->declared_at);
11502   else if (sym->attr.codimension && sym->attr.allocatable
11503       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
11504     gfc_error ("Allocatable coarray variable '%s' at %L must have "
11505                "deferred shape", sym->name, &sym->declared_at);
11506
11507
11508   /* F2008, C541.  */
11509   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
11510        || (sym->attr.codimension && sym->attr.allocatable))
11511       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
11512     gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
11513                "allocatable coarray or have coarray components",
11514                sym->name, &sym->declared_at);
11515
11516   if (sym->attr.codimension && sym->attr.dummy
11517       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
11518     gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
11519                "procedure '%s'", sym->name, &sym->declared_at,
11520                sym->ns->proc_name->name);
11521
11522   switch (sym->attr.flavor)
11523     {
11524     case FL_VARIABLE:
11525       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
11526         return;
11527       break;
11528
11529     case FL_PROCEDURE:
11530       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
11531         return;
11532       break;
11533
11534     case FL_NAMELIST:
11535       if (resolve_fl_namelist (sym) == FAILURE)
11536         return;
11537       break;
11538
11539     case FL_PARAMETER:
11540       if (resolve_fl_parameter (sym) == FAILURE)
11541         return;
11542       break;
11543
11544     default:
11545       break;
11546     }
11547
11548   /* Resolve array specifier. Check as well some constraints
11549      on COMMON blocks.  */
11550
11551   check_constant = sym->attr.in_common && !sym->attr.pointer;
11552
11553   /* Set the formal_arg_flag so that check_conflict will not throw
11554      an error for host associated variables in the specification
11555      expression for an array_valued function.  */
11556   if (sym->attr.function && sym->as)
11557     formal_arg_flag = 1;
11558
11559   gfc_resolve_array_spec (sym->as, check_constant);
11560
11561   formal_arg_flag = 0;
11562
11563   /* Resolve formal namespaces.  */
11564   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
11565       && !sym->attr.contained && !sym->attr.intrinsic)
11566     gfc_resolve (sym->formal_ns);
11567
11568   /* Make sure the formal namespace is present.  */
11569   if (sym->formal && !sym->formal_ns)
11570     {
11571       gfc_formal_arglist *formal = sym->formal;
11572       while (formal && !formal->sym)
11573         formal = formal->next;
11574
11575       if (formal)
11576         {
11577           sym->formal_ns = formal->sym->ns;
11578           sym->formal_ns->refs++;
11579         }
11580     }
11581
11582   /* Check threadprivate restrictions.  */
11583   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
11584       && (!sym->attr.in_common
11585           && sym->module == NULL
11586           && (sym->ns->proc_name == NULL
11587               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
11588     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
11589
11590   /* If we have come this far we can apply default-initializers, as
11591      described in 14.7.5, to those variables that have not already
11592      been assigned one.  */
11593   if (sym->ts.type == BT_DERIVED
11594       && sym->attr.referenced
11595       && sym->ns == gfc_current_ns
11596       && !sym->value
11597       && !sym->attr.allocatable
11598       && !sym->attr.alloc_comp)
11599     {
11600       symbol_attribute *a = &sym->attr;
11601
11602       if ((!a->save && !a->dummy && !a->pointer
11603            && !a->in_common && !a->use_assoc
11604            && !(a->function && sym != sym->result))
11605           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
11606         apply_default_init (sym);
11607     }
11608
11609   /* If this symbol has a type-spec, check it.  */
11610   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
11611       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
11612     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
11613           == FAILURE)
11614       return;
11615 }
11616
11617
11618 /************* Resolve DATA statements *************/
11619
11620 static struct
11621 {
11622   gfc_data_value *vnode;
11623   mpz_t left;
11624 }
11625 values;
11626
11627
11628 /* Advance the values structure to point to the next value in the data list.  */
11629
11630 static gfc_try
11631 next_data_value (void)
11632 {
11633   while (mpz_cmp_ui (values.left, 0) == 0)
11634     {
11635
11636       if (values.vnode->next == NULL)
11637         return FAILURE;
11638
11639       values.vnode = values.vnode->next;
11640       mpz_set (values.left, values.vnode->repeat);
11641     }
11642
11643   return SUCCESS;
11644 }
11645
11646
11647 static gfc_try
11648 check_data_variable (gfc_data_variable *var, locus *where)
11649 {
11650   gfc_expr *e;
11651   mpz_t size;
11652   mpz_t offset;
11653   gfc_try t;
11654   ar_type mark = AR_UNKNOWN;
11655   int i;
11656   mpz_t section_index[GFC_MAX_DIMENSIONS];
11657   gfc_ref *ref;
11658   gfc_array_ref *ar;
11659   gfc_symbol *sym;
11660   int has_pointer;
11661
11662   if (gfc_resolve_expr (var->expr) == FAILURE)
11663     return FAILURE;
11664
11665   ar = NULL;
11666   mpz_init_set_si (offset, 0);
11667   e = var->expr;
11668
11669   if (e->expr_type != EXPR_VARIABLE)
11670     gfc_internal_error ("check_data_variable(): Bad expression");
11671
11672   sym = e->symtree->n.sym;
11673
11674   if (sym->ns->is_block_data && !sym->attr.in_common)
11675     {
11676       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
11677                  sym->name, &sym->declared_at);
11678     }
11679
11680   if (e->ref == NULL && sym->as)
11681     {
11682       gfc_error ("DATA array '%s' at %L must be specified in a previous"
11683                  " declaration", sym->name, where);
11684       return FAILURE;
11685     }
11686
11687   has_pointer = sym->attr.pointer;
11688
11689   for (ref = e->ref; ref; ref = ref->next)
11690     {
11691       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
11692         has_pointer = 1;
11693
11694       if (ref->type == REF_ARRAY && ref->u.ar.codimen)
11695         {
11696           gfc_error ("DATA element '%s' at %L cannot have a coindex",
11697                      sym->name, where);
11698           return FAILURE;
11699         }
11700
11701       if (has_pointer
11702             && ref->type == REF_ARRAY
11703             && ref->u.ar.type != AR_FULL)
11704           {
11705             gfc_error ("DATA element '%s' at %L is a pointer and so must "
11706                         "be a full array", sym->name, where);
11707             return FAILURE;
11708           }
11709     }
11710
11711   if (e->rank == 0 || has_pointer)
11712     {
11713       mpz_init_set_ui (size, 1);
11714       ref = NULL;
11715     }
11716   else
11717     {
11718       ref = e->ref;
11719
11720       /* Find the array section reference.  */
11721       for (ref = e->ref; ref; ref = ref->next)
11722         {
11723           if (ref->type != REF_ARRAY)
11724             continue;
11725           if (ref->u.ar.type == AR_ELEMENT)
11726             continue;
11727           break;
11728         }
11729       gcc_assert (ref);
11730
11731       /* Set marks according to the reference pattern.  */
11732       switch (ref->u.ar.type)
11733         {
11734         case AR_FULL:
11735           mark = AR_FULL;
11736           break;
11737
11738         case AR_SECTION:
11739           ar = &ref->u.ar;
11740           /* Get the start position of array section.  */
11741           gfc_get_section_index (ar, section_index, &offset);
11742           mark = AR_SECTION;
11743           break;
11744
11745         default:
11746           gcc_unreachable ();
11747         }
11748
11749       if (gfc_array_size (e, &size) == FAILURE)
11750         {
11751           gfc_error ("Nonconstant array section at %L in DATA statement",
11752                      &e->where);
11753           mpz_clear (offset);
11754           return FAILURE;
11755         }
11756     }
11757
11758   t = SUCCESS;
11759
11760   while (mpz_cmp_ui (size, 0) > 0)
11761     {
11762       if (next_data_value () == FAILURE)
11763         {
11764           gfc_error ("DATA statement at %L has more variables than values",
11765                      where);
11766           t = FAILURE;
11767           break;
11768         }
11769
11770       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
11771       if (t == FAILURE)
11772         break;
11773
11774       /* If we have more than one element left in the repeat count,
11775          and we have more than one element left in the target variable,
11776          then create a range assignment.  */
11777       /* FIXME: Only done for full arrays for now, since array sections
11778          seem tricky.  */
11779       if (mark == AR_FULL && ref && ref->next == NULL
11780           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
11781         {
11782           mpz_t range;
11783
11784           if (mpz_cmp (size, values.left) >= 0)
11785             {
11786               mpz_init_set (range, values.left);
11787               mpz_sub (size, size, values.left);
11788               mpz_set_ui (values.left, 0);
11789             }
11790           else
11791             {
11792               mpz_init_set (range, size);
11793               mpz_sub (values.left, values.left, size);
11794               mpz_set_ui (size, 0);
11795             }
11796
11797           t = gfc_assign_data_value_range (var->expr, values.vnode->expr,
11798                                            offset, range);
11799
11800           mpz_add (offset, offset, range);
11801           mpz_clear (range);
11802
11803           if (t == FAILURE)
11804             break;
11805         }
11806
11807       /* Assign initial value to symbol.  */
11808       else
11809         {
11810           mpz_sub_ui (values.left, values.left, 1);
11811           mpz_sub_ui (size, size, 1);
11812
11813           t = gfc_assign_data_value (var->expr, values.vnode->expr, offset);
11814           if (t == FAILURE)
11815             break;
11816
11817           if (mark == AR_FULL)
11818             mpz_add_ui (offset, offset, 1);
11819
11820           /* Modify the array section indexes and recalculate the offset
11821              for next element.  */
11822           else if (mark == AR_SECTION)
11823             gfc_advance_section (section_index, ar, &offset);
11824         }
11825     }
11826
11827   if (mark == AR_SECTION)
11828     {
11829       for (i = 0; i < ar->dimen; i++)
11830         mpz_clear (section_index[i]);
11831     }
11832
11833   mpz_clear (size);
11834   mpz_clear (offset);
11835
11836   return t;
11837 }
11838
11839
11840 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
11841
11842 /* Iterate over a list of elements in a DATA statement.  */
11843
11844 static gfc_try
11845 traverse_data_list (gfc_data_variable *var, locus *where)
11846 {
11847   mpz_t trip;
11848   iterator_stack frame;
11849   gfc_expr *e, *start, *end, *step;
11850   gfc_try retval = SUCCESS;
11851
11852   mpz_init (frame.value);
11853   mpz_init (trip);
11854
11855   start = gfc_copy_expr (var->iter.start);
11856   end = gfc_copy_expr (var->iter.end);
11857   step = gfc_copy_expr (var->iter.step);
11858
11859   if (gfc_simplify_expr (start, 1) == FAILURE
11860       || start->expr_type != EXPR_CONSTANT)
11861     {
11862       gfc_error ("start of implied-do loop at %L could not be "
11863                  "simplified to a constant value", &start->where);
11864       retval = FAILURE;
11865       goto cleanup;
11866     }
11867   if (gfc_simplify_expr (end, 1) == FAILURE
11868       || end->expr_type != EXPR_CONSTANT)
11869     {
11870       gfc_error ("end of implied-do loop at %L could not be "
11871                  "simplified to a constant value", &start->where);
11872       retval = FAILURE;
11873       goto cleanup;
11874     }
11875   if (gfc_simplify_expr (step, 1) == FAILURE
11876       || step->expr_type != EXPR_CONSTANT)
11877     {
11878       gfc_error ("step of implied-do loop at %L could not be "
11879                  "simplified to a constant value", &start->where);
11880       retval = FAILURE;
11881       goto cleanup;
11882     }
11883
11884   mpz_set (trip, end->value.integer);
11885   mpz_sub (trip, trip, start->value.integer);
11886   mpz_add (trip, trip, step->value.integer);
11887
11888   mpz_div (trip, trip, step->value.integer);
11889
11890   mpz_set (frame.value, start->value.integer);
11891
11892   frame.prev = iter_stack;
11893   frame.variable = var->iter.var->symtree;
11894   iter_stack = &frame;
11895
11896   while (mpz_cmp_ui (trip, 0) > 0)
11897     {
11898       if (traverse_data_var (var->list, where) == FAILURE)
11899         {
11900           retval = FAILURE;
11901           goto cleanup;
11902         }
11903
11904       e = gfc_copy_expr (var->expr);
11905       if (gfc_simplify_expr (e, 1) == FAILURE)
11906         {
11907           gfc_free_expr (e);
11908           retval = FAILURE;
11909           goto cleanup;
11910         }
11911
11912       mpz_add (frame.value, frame.value, step->value.integer);
11913
11914       mpz_sub_ui (trip, trip, 1);
11915     }
11916
11917 cleanup:
11918   mpz_clear (frame.value);
11919   mpz_clear (trip);
11920
11921   gfc_free_expr (start);
11922   gfc_free_expr (end);
11923   gfc_free_expr (step);
11924
11925   iter_stack = frame.prev;
11926   return retval;
11927 }
11928
11929
11930 /* Type resolve variables in the variable list of a DATA statement.  */
11931
11932 static gfc_try
11933 traverse_data_var (gfc_data_variable *var, locus *where)
11934 {
11935   gfc_try t;
11936
11937   for (; var; var = var->next)
11938     {
11939       if (var->expr == NULL)
11940         t = traverse_data_list (var, where);
11941       else
11942         t = check_data_variable (var, where);
11943
11944       if (t == FAILURE)
11945         return FAILURE;
11946     }
11947
11948   return SUCCESS;
11949 }
11950
11951
11952 /* Resolve the expressions and iterators associated with a data statement.
11953    This is separate from the assignment checking because data lists should
11954    only be resolved once.  */
11955
11956 static gfc_try
11957 resolve_data_variables (gfc_data_variable *d)
11958 {
11959   for (; d; d = d->next)
11960     {
11961       if (d->list == NULL)
11962         {
11963           if (gfc_resolve_expr (d->expr) == FAILURE)
11964             return FAILURE;
11965         }
11966       else
11967         {
11968           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
11969             return FAILURE;
11970
11971           if (resolve_data_variables (d->list) == FAILURE)
11972             return FAILURE;
11973         }
11974     }
11975
11976   return SUCCESS;
11977 }
11978
11979
11980 /* Resolve a single DATA statement.  We implement this by storing a pointer to
11981    the value list into static variables, and then recursively traversing the
11982    variables list, expanding iterators and such.  */
11983
11984 static void
11985 resolve_data (gfc_data *d)
11986 {
11987
11988   if (resolve_data_variables (d->var) == FAILURE)
11989     return;
11990
11991   values.vnode = d->value;
11992   if (d->value == NULL)
11993     mpz_set_ui (values.left, 0);
11994   else
11995     mpz_set (values.left, d->value->repeat);
11996
11997   if (traverse_data_var (d->var, &d->where) == FAILURE)
11998     return;
11999
12000   /* At this point, we better not have any values left.  */
12001
12002   if (next_data_value () == SUCCESS)
12003     gfc_error ("DATA statement at %L has more values than variables",
12004                &d->where);
12005 }
12006
12007
12008 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12009    accessed by host or use association, is a dummy argument to a pure function,
12010    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12011    is storage associated with any such variable, shall not be used in the
12012    following contexts: (clients of this function).  */
12013
12014 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12015    procedure.  Returns zero if assignment is OK, nonzero if there is a
12016    problem.  */
12017 int
12018 gfc_impure_variable (gfc_symbol *sym)
12019 {
12020   gfc_symbol *proc;
12021   gfc_namespace *ns;
12022
12023   if (sym->attr.use_assoc || sym->attr.in_common)
12024     return 1;
12025
12026   /* Check if the symbol's ns is inside the pure procedure.  */
12027   for (ns = gfc_current_ns; ns; ns = ns->parent)
12028     {
12029       if (ns == sym->ns)
12030         break;
12031       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12032         return 1;
12033     }
12034
12035   proc = sym->ns->proc_name;
12036   if (sym->attr.dummy && gfc_pure (proc)
12037         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12038                 ||
12039              proc->attr.function))
12040     return 1;
12041
12042   /* TODO: Sort out what can be storage associated, if anything, and include
12043      it here.  In principle equivalences should be scanned but it does not
12044      seem to be possible to storage associate an impure variable this way.  */
12045   return 0;
12046 }
12047
12048
12049 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12050    current namespace is inside a pure procedure.  */
12051
12052 int
12053 gfc_pure (gfc_symbol *sym)
12054 {
12055   symbol_attribute attr;
12056   gfc_namespace *ns;
12057
12058   if (sym == NULL)
12059     {
12060       /* Check if the current namespace or one of its parents
12061         belongs to a pure procedure.  */
12062       for (ns = gfc_current_ns; ns; ns = ns->parent)
12063         {
12064           sym = ns->proc_name;
12065           if (sym == NULL)
12066             return 0;
12067           attr = sym->attr;
12068           if (attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental))
12069             return 1;
12070         }
12071       return 0;
12072     }
12073
12074   attr = sym->attr;
12075
12076   return attr.flavor == FL_PROCEDURE && (attr.pure || attr.elemental);
12077 }
12078
12079
12080 /* Test whether the current procedure is elemental or not.  */
12081
12082 int
12083 gfc_elemental (gfc_symbol *sym)
12084 {
12085   symbol_attribute attr;
12086
12087   if (sym == NULL)
12088     sym = gfc_current_ns->proc_name;
12089   if (sym == NULL)
12090     return 0;
12091   attr = sym->attr;
12092
12093   return attr.flavor == FL_PROCEDURE && attr.elemental;
12094 }
12095
12096
12097 /* Warn about unused labels.  */
12098
12099 static void
12100 warn_unused_fortran_label (gfc_st_label *label)
12101 {
12102   if (label == NULL)
12103     return;
12104
12105   warn_unused_fortran_label (label->left);
12106
12107   if (label->defined == ST_LABEL_UNKNOWN)
12108     return;
12109
12110   switch (label->referenced)
12111     {
12112     case ST_LABEL_UNKNOWN:
12113       gfc_warning ("Label %d at %L defined but not used", label->value,
12114                    &label->where);
12115       break;
12116
12117     case ST_LABEL_BAD_TARGET:
12118       gfc_warning ("Label %d at %L defined but cannot be used",
12119                    label->value, &label->where);
12120       break;
12121
12122     default:
12123       break;
12124     }
12125
12126   warn_unused_fortran_label (label->right);
12127 }
12128
12129
12130 /* Returns the sequence type of a symbol or sequence.  */
12131
12132 static seq_type
12133 sequence_type (gfc_typespec ts)
12134 {
12135   seq_type result;
12136   gfc_component *c;
12137
12138   switch (ts.type)
12139   {
12140     case BT_DERIVED:
12141
12142       if (ts.u.derived->components == NULL)
12143         return SEQ_NONDEFAULT;
12144
12145       result = sequence_type (ts.u.derived->components->ts);
12146       for (c = ts.u.derived->components->next; c; c = c->next)
12147         if (sequence_type (c->ts) != result)
12148           return SEQ_MIXED;
12149
12150       return result;
12151
12152     case BT_CHARACTER:
12153       if (ts.kind != gfc_default_character_kind)
12154           return SEQ_NONDEFAULT;
12155
12156       return SEQ_CHARACTER;
12157
12158     case BT_INTEGER:
12159       if (ts.kind != gfc_default_integer_kind)
12160           return SEQ_NONDEFAULT;
12161
12162       return SEQ_NUMERIC;
12163
12164     case BT_REAL:
12165       if (!(ts.kind == gfc_default_real_kind
12166             || ts.kind == gfc_default_double_kind))
12167           return SEQ_NONDEFAULT;
12168
12169       return SEQ_NUMERIC;
12170
12171     case BT_COMPLEX:
12172       if (ts.kind != gfc_default_complex_kind)
12173           return SEQ_NONDEFAULT;
12174
12175       return SEQ_NUMERIC;
12176
12177     case BT_LOGICAL:
12178       if (ts.kind != gfc_default_logical_kind)
12179           return SEQ_NONDEFAULT;
12180
12181       return SEQ_NUMERIC;
12182
12183     default:
12184       return SEQ_NONDEFAULT;
12185   }
12186 }
12187
12188
12189 /* Resolve derived type EQUIVALENCE object.  */
12190
12191 static gfc_try
12192 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
12193 {
12194   gfc_component *c = derived->components;
12195
12196   if (!derived)
12197     return SUCCESS;
12198
12199   /* Shall not be an object of nonsequence derived type.  */
12200   if (!derived->attr.sequence)
12201     {
12202       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
12203                  "attribute to be an EQUIVALENCE object", sym->name,
12204                  &e->where);
12205       return FAILURE;
12206     }
12207
12208   /* Shall not have allocatable components.  */
12209   if (derived->attr.alloc_comp)
12210     {
12211       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
12212                  "components to be an EQUIVALENCE object",sym->name,
12213                  &e->where);
12214       return FAILURE;
12215     }
12216
12217   if (sym->attr.in_common && has_default_initializer (sym->ts.u.derived))
12218     {
12219       gfc_error ("Derived type variable '%s' at %L with default "
12220                  "initialization cannot be in EQUIVALENCE with a variable "
12221                  "in COMMON", sym->name, &e->where);
12222       return FAILURE;
12223     }
12224
12225   for (; c ; c = c->next)
12226     {
12227       if (c->ts.type == BT_DERIVED
12228           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
12229         return FAILURE;
12230
12231       /* Shall not be an object of sequence derived type containing a pointer
12232          in the structure.  */
12233       if (c->attr.pointer)
12234         {
12235           gfc_error ("Derived type variable '%s' at %L with pointer "
12236                      "component(s) cannot be an EQUIVALENCE object",
12237                      sym->name, &e->where);
12238           return FAILURE;
12239         }
12240     }
12241   return SUCCESS;
12242 }
12243
12244
12245 /* Resolve equivalence object. 
12246    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
12247    an allocatable array, an object of nonsequence derived type, an object of
12248    sequence derived type containing a pointer at any level of component
12249    selection, an automatic object, a function name, an entry name, a result
12250    name, a named constant, a structure component, or a subobject of any of
12251    the preceding objects.  A substring shall not have length zero.  A
12252    derived type shall not have components with default initialization nor
12253    shall two objects of an equivalence group be initialized.
12254    Either all or none of the objects shall have an protected attribute.
12255    The simple constraints are done in symbol.c(check_conflict) and the rest
12256    are implemented here.  */
12257
12258 static void
12259 resolve_equivalence (gfc_equiv *eq)
12260 {
12261   gfc_symbol *sym;
12262   gfc_symbol *first_sym;
12263   gfc_expr *e;
12264   gfc_ref *r;
12265   locus *last_where = NULL;
12266   seq_type eq_type, last_eq_type;
12267   gfc_typespec *last_ts;
12268   int object, cnt_protected;
12269   const char *msg;
12270
12271   last_ts = &eq->expr->symtree->n.sym->ts;
12272
12273   first_sym = eq->expr->symtree->n.sym;
12274
12275   cnt_protected = 0;
12276
12277   for (object = 1; eq; eq = eq->eq, object++)
12278     {
12279       e = eq->expr;
12280
12281       e->ts = e->symtree->n.sym->ts;
12282       /* match_varspec might not know yet if it is seeing
12283          array reference or substring reference, as it doesn't
12284          know the types.  */
12285       if (e->ref && e->ref->type == REF_ARRAY)
12286         {
12287           gfc_ref *ref = e->ref;
12288           sym = e->symtree->n.sym;
12289
12290           if (sym->attr.dimension)
12291             {
12292               ref->u.ar.as = sym->as;
12293               ref = ref->next;
12294             }
12295
12296           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
12297           if (e->ts.type == BT_CHARACTER
12298               && ref
12299               && ref->type == REF_ARRAY
12300               && ref->u.ar.dimen == 1
12301               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
12302               && ref->u.ar.stride[0] == NULL)
12303             {
12304               gfc_expr *start = ref->u.ar.start[0];
12305               gfc_expr *end = ref->u.ar.end[0];
12306               void *mem = NULL;
12307
12308               /* Optimize away the (:) reference.  */
12309               if (start == NULL && end == NULL)
12310                 {
12311                   if (e->ref == ref)
12312                     e->ref = ref->next;
12313                   else
12314                     e->ref->next = ref->next;
12315                   mem = ref;
12316                 }
12317               else
12318                 {
12319                   ref->type = REF_SUBSTRING;
12320                   if (start == NULL)
12321                     start = gfc_get_int_expr (gfc_default_integer_kind,
12322                                               NULL, 1);
12323                   ref->u.ss.start = start;
12324                   if (end == NULL && e->ts.u.cl)
12325                     end = gfc_copy_expr (e->ts.u.cl->length);
12326                   ref->u.ss.end = end;
12327                   ref->u.ss.length = e->ts.u.cl;
12328                   e->ts.u.cl = NULL;
12329                 }
12330               ref = ref->next;
12331               gfc_free (mem);
12332             }
12333
12334           /* Any further ref is an error.  */
12335           if (ref)
12336             {
12337               gcc_assert (ref->type == REF_ARRAY);
12338               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
12339                          &ref->u.ar.where);
12340               continue;
12341             }
12342         }
12343
12344       if (gfc_resolve_expr (e) == FAILURE)
12345         continue;
12346
12347       sym = e->symtree->n.sym;
12348
12349       if (sym->attr.is_protected)
12350         cnt_protected++;
12351       if (cnt_protected > 0 && cnt_protected != object)
12352         {
12353               gfc_error ("Either all or none of the objects in the "
12354                          "EQUIVALENCE set at %L shall have the "
12355                          "PROTECTED attribute",
12356                          &e->where);
12357               break;
12358         }
12359
12360       /* Shall not equivalence common block variables in a PURE procedure.  */
12361       if (sym->ns->proc_name
12362           && sym->ns->proc_name->attr.pure
12363           && sym->attr.in_common)
12364         {
12365           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
12366                      "object in the pure procedure '%s'",
12367                      sym->name, &e->where, sym->ns->proc_name->name);
12368           break;
12369         }
12370
12371       /* Shall not be a named constant.  */
12372       if (e->expr_type == EXPR_CONSTANT)
12373         {
12374           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
12375                      "object", sym->name, &e->where);
12376           continue;
12377         }
12378
12379       if (e->ts.type == BT_DERIVED
12380           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
12381         continue;
12382
12383       /* Check that the types correspond correctly:
12384          Note 5.28:
12385          A numeric sequence structure may be equivalenced to another sequence
12386          structure, an object of default integer type, default real type, double
12387          precision real type, default logical type such that components of the
12388          structure ultimately only become associated to objects of the same
12389          kind. A character sequence structure may be equivalenced to an object
12390          of default character kind or another character sequence structure.
12391          Other objects may be equivalenced only to objects of the same type and
12392          kind parameters.  */
12393
12394       /* Identical types are unconditionally OK.  */
12395       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
12396         goto identical_types;
12397
12398       last_eq_type = sequence_type (*last_ts);
12399       eq_type = sequence_type (sym->ts);
12400
12401       /* Since the pair of objects is not of the same type, mixed or
12402          non-default sequences can be rejected.  */
12403
12404       msg = "Sequence %s with mixed components in EQUIVALENCE "
12405             "statement at %L with different type objects";
12406       if ((object ==2
12407            && last_eq_type == SEQ_MIXED
12408            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
12409               == FAILURE)
12410           || (eq_type == SEQ_MIXED
12411               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12412                                  &e->where) == FAILURE))
12413         continue;
12414
12415       msg = "Non-default type object or sequence %s in EQUIVALENCE "
12416             "statement at %L with objects of different type";
12417       if ((object ==2
12418            && last_eq_type == SEQ_NONDEFAULT
12419            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
12420                               last_where) == FAILURE)
12421           || (eq_type == SEQ_NONDEFAULT
12422               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12423                                  &e->where) == FAILURE))
12424         continue;
12425
12426       msg ="Non-CHARACTER object '%s' in default CHARACTER "
12427            "EQUIVALENCE statement at %L";
12428       if (last_eq_type == SEQ_CHARACTER
12429           && eq_type != SEQ_CHARACTER
12430           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12431                              &e->where) == FAILURE)
12432                 continue;
12433
12434       msg ="Non-NUMERIC object '%s' in default NUMERIC "
12435            "EQUIVALENCE statement at %L";
12436       if (last_eq_type == SEQ_NUMERIC
12437           && eq_type != SEQ_NUMERIC
12438           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
12439                              &e->where) == FAILURE)
12440                 continue;
12441
12442   identical_types:
12443       last_ts =&sym->ts;
12444       last_where = &e->where;
12445
12446       if (!e->ref)
12447         continue;
12448
12449       /* Shall not be an automatic array.  */
12450       if (e->ref->type == REF_ARRAY
12451           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
12452         {
12453           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
12454                      "an EQUIVALENCE object", sym->name, &e->where);
12455           continue;
12456         }
12457
12458       r = e->ref;
12459       while (r)
12460         {
12461           /* Shall not be a structure component.  */
12462           if (r->type == REF_COMPONENT)
12463             {
12464               gfc_error ("Structure component '%s' at %L cannot be an "
12465                          "EQUIVALENCE object",
12466                          r->u.c.component->name, &e->where);
12467               break;
12468             }
12469
12470           /* A substring shall not have length zero.  */
12471           if (r->type == REF_SUBSTRING)
12472             {
12473               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
12474                 {
12475                   gfc_error ("Substring at %L has length zero",
12476                              &r->u.ss.start->where);
12477                   break;
12478                 }
12479             }
12480           r = r->next;
12481         }
12482     }
12483 }
12484
12485
12486 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
12487
12488 static void
12489 resolve_fntype (gfc_namespace *ns)
12490 {
12491   gfc_entry_list *el;
12492   gfc_symbol *sym;
12493
12494   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
12495     return;
12496
12497   /* If there are any entries, ns->proc_name is the entry master
12498      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
12499   if (ns->entries)
12500     sym = ns->entries->sym;
12501   else
12502     sym = ns->proc_name;
12503   if (sym->result == sym
12504       && sym->ts.type == BT_UNKNOWN
12505       && gfc_set_default_type (sym, 0, NULL) == FAILURE
12506       && !sym->attr.untyped)
12507     {
12508       gfc_error ("Function '%s' at %L has no IMPLICIT type",
12509                  sym->name, &sym->declared_at);
12510       sym->attr.untyped = 1;
12511     }
12512
12513   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
12514       && !sym->attr.contained
12515       && !gfc_check_access (sym->ts.u.derived->attr.access,
12516                             sym->ts.u.derived->ns->default_access)
12517       && gfc_check_access (sym->attr.access, sym->ns->default_access))
12518     {
12519       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
12520                       "%L of PRIVATE type '%s'", sym->name,
12521                       &sym->declared_at, sym->ts.u.derived->name);
12522     }
12523
12524     if (ns->entries)
12525     for (el = ns->entries->next; el; el = el->next)
12526       {
12527         if (el->sym->result == el->sym
12528             && el->sym->ts.type == BT_UNKNOWN
12529             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
12530             && !el->sym->attr.untyped)
12531           {
12532             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
12533                        el->sym->name, &el->sym->declared_at);
12534             el->sym->attr.untyped = 1;
12535           }
12536       }
12537 }
12538
12539
12540 /* 12.3.2.1.1 Defined operators.  */
12541
12542 static gfc_try
12543 check_uop_procedure (gfc_symbol *sym, locus where)
12544 {
12545   gfc_formal_arglist *formal;
12546
12547   if (!sym->attr.function)
12548     {
12549       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
12550                  sym->name, &where);
12551       return FAILURE;
12552     }
12553
12554   if (sym->ts.type == BT_CHARACTER
12555       && !(sym->ts.u.cl && sym->ts.u.cl->length)
12556       && !(sym->result && sym->result->ts.u.cl
12557            && sym->result->ts.u.cl->length))
12558     {
12559       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
12560                  "character length", sym->name, &where);
12561       return FAILURE;
12562     }
12563
12564   formal = sym->formal;
12565   if (!formal || !formal->sym)
12566     {
12567       gfc_error ("User operator procedure '%s' at %L must have at least "
12568                  "one argument", sym->name, &where);
12569       return FAILURE;
12570     }
12571
12572   if (formal->sym->attr.intent != INTENT_IN)
12573     {
12574       gfc_error ("First argument of operator interface at %L must be "
12575                  "INTENT(IN)", &where);
12576       return FAILURE;
12577     }
12578
12579   if (formal->sym->attr.optional)
12580     {
12581       gfc_error ("First argument of operator interface at %L cannot be "
12582                  "optional", &where);
12583       return FAILURE;
12584     }
12585
12586   formal = formal->next;
12587   if (!formal || !formal->sym)
12588     return SUCCESS;
12589
12590   if (formal->sym->attr.intent != INTENT_IN)
12591     {
12592       gfc_error ("Second argument of operator interface at %L must be "
12593                  "INTENT(IN)", &where);
12594       return FAILURE;
12595     }
12596
12597   if (formal->sym->attr.optional)
12598     {
12599       gfc_error ("Second argument of operator interface at %L cannot be "
12600                  "optional", &where);
12601       return FAILURE;
12602     }
12603
12604   if (formal->next)
12605     {
12606       gfc_error ("Operator interface at %L must have, at most, two "
12607                  "arguments", &where);
12608       return FAILURE;
12609     }
12610
12611   return SUCCESS;
12612 }
12613
12614 static void
12615 gfc_resolve_uops (gfc_symtree *symtree)
12616 {
12617   gfc_interface *itr;
12618
12619   if (symtree == NULL)
12620     return;
12621
12622   gfc_resolve_uops (symtree->left);
12623   gfc_resolve_uops (symtree->right);
12624
12625   for (itr = symtree->n.uop->op; itr; itr = itr->next)
12626     check_uop_procedure (itr->sym, itr->sym->declared_at);
12627 }
12628
12629
12630 /* Examine all of the expressions associated with a program unit,
12631    assign types to all intermediate expressions, make sure that all
12632    assignments are to compatible types and figure out which names
12633    refer to which functions or subroutines.  It doesn't check code
12634    block, which is handled by resolve_code.  */
12635
12636 static void
12637 resolve_types (gfc_namespace *ns)
12638 {
12639   gfc_namespace *n;
12640   gfc_charlen *cl;
12641   gfc_data *d;
12642   gfc_equiv *eq;
12643   gfc_namespace* old_ns = gfc_current_ns;
12644
12645   /* Check that all IMPLICIT types are ok.  */
12646   if (!ns->seen_implicit_none)
12647     {
12648       unsigned letter;
12649       for (letter = 0; letter != GFC_LETTERS; ++letter)
12650         if (ns->set_flag[letter]
12651             && resolve_typespec_used (&ns->default_type[letter],
12652                                       &ns->implicit_loc[letter],
12653                                       NULL) == FAILURE)
12654           return;
12655     }
12656
12657   gfc_current_ns = ns;
12658
12659   resolve_entries (ns);
12660
12661   resolve_common_vars (ns->blank_common.head, false);
12662   resolve_common_blocks (ns->common_root);
12663
12664   resolve_contained_functions (ns);
12665
12666   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
12667
12668   for (cl = ns->cl_list; cl; cl = cl->next)
12669     resolve_charlen (cl);
12670
12671   gfc_traverse_ns (ns, resolve_symbol);
12672
12673   resolve_fntype (ns);
12674
12675   for (n = ns->contained; n; n = n->sibling)
12676     {
12677       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
12678         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
12679                    "also be PURE", n->proc_name->name,
12680                    &n->proc_name->declared_at);
12681
12682       resolve_types (n);
12683     }
12684
12685   forall_flag = 0;
12686   gfc_check_interfaces (ns);
12687
12688   gfc_traverse_ns (ns, resolve_values);
12689
12690   if (ns->save_all)
12691     gfc_save_all (ns);
12692
12693   iter_stack = NULL;
12694   for (d = ns->data; d; d = d->next)
12695     resolve_data (d);
12696
12697   iter_stack = NULL;
12698   gfc_traverse_ns (ns, gfc_formalize_init_value);
12699
12700   gfc_traverse_ns (ns, gfc_verify_binding_labels);
12701
12702   if (ns->common_root != NULL)
12703     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
12704
12705   for (eq = ns->equiv; eq; eq = eq->next)
12706     resolve_equivalence (eq);
12707
12708   /* Warn about unused labels.  */
12709   if (warn_unused_label)
12710     warn_unused_fortran_label (ns->st_labels);
12711
12712   gfc_resolve_uops (ns->uop_root);
12713
12714   gfc_current_ns = old_ns;
12715 }
12716
12717
12718 /* Call resolve_code recursively.  */
12719
12720 static void
12721 resolve_codes (gfc_namespace *ns)
12722 {
12723   gfc_namespace *n;
12724   bitmap_obstack old_obstack;
12725
12726   for (n = ns->contained; n; n = n->sibling)
12727     resolve_codes (n);
12728
12729   gfc_current_ns = ns;
12730
12731   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
12732   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
12733     cs_base = NULL;
12734
12735   /* Set to an out of range value.  */
12736   current_entry_id = -1;
12737
12738   old_obstack = labels_obstack;
12739   bitmap_obstack_initialize (&labels_obstack);
12740
12741   resolve_code (ns->code, ns);
12742
12743   bitmap_obstack_release (&labels_obstack);
12744   labels_obstack = old_obstack;
12745 }
12746
12747
12748 /* This function is called after a complete program unit has been compiled.
12749    Its purpose is to examine all of the expressions associated with a program
12750    unit, assign types to all intermediate expressions, make sure that all
12751    assignments are to compatible types and figure out which names refer to
12752    which functions or subroutines.  */
12753
12754 void
12755 gfc_resolve (gfc_namespace *ns)
12756 {
12757   gfc_namespace *old_ns;
12758   code_stack *old_cs_base;
12759
12760   if (ns->resolved)
12761     return;
12762
12763   ns->resolved = -1;
12764   old_ns = gfc_current_ns;
12765   old_cs_base = cs_base;
12766
12767   resolve_types (ns);
12768   resolve_codes (ns);
12769
12770   gfc_current_ns = old_ns;
12771   cs_base = old_cs_base;
12772   ns->resolved = 1;
12773 }