OSDN Git Service

e99e1997cde26c69c52970957929436e0e479b2d
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
3    2010, 2011
4    Free Software Foundation, Inc.
5    Contributed by Andy Vaught
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "flags.h"
26 #include "gfortran.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "arith.h"  /* For gfc_compare_expr().  */
30 #include "dependency.h"
31 #include "data.h"
32 #include "target-memory.h" /* for gfc_simplify_transfer */
33 #include "constructor.h"
34
35 /* Types used in equivalence statements.  */
36
37 typedef enum seq_type
38 {
39   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
40 }
41 seq_type;
42
43 /* Stack to keep track of the nesting of blocks as we move through the
44    code.  See resolve_branch() and resolve_code().  */
45
46 typedef struct code_stack
47 {
48   struct gfc_code *head, *current;
49   struct code_stack *prev;
50
51   /* This bitmap keeps track of the targets valid for a branch from
52      inside this block except for END {IF|SELECT}s of enclosing
53      blocks.  */
54   bitmap reachable_labels;
55 }
56 code_stack;
57
58 static code_stack *cs_base = NULL;
59
60
61 /* Nonzero if we're inside a FORALL or DO CONCURRENT block.  */
62
63 static int forall_flag;
64 static int do_concurrent_flag;
65
66 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
67
68 static int omp_workshare_flag;
69
70 /* Nonzero if we are processing a formal arglist. The corresponding function
71    resets the flag each time that it is read.  */
72 static int formal_arg_flag = 0;
73
74 /* True if we are resolving a specification expression.  */
75 static int specification_expr = 0;
76
77 /* The id of the last entry seen.  */
78 static int current_entry_id;
79
80 /* We use bitmaps to determine if a branch target is valid.  */
81 static bitmap_obstack labels_obstack;
82
83 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
84 static bool inquiry_argument = false;
85
86 int
87 gfc_is_formal_arg (void)
88 {
89   return formal_arg_flag;
90 }
91
92 /* Is the symbol host associated?  */
93 static bool
94 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
95 {
96   for (ns = ns->parent; ns; ns = ns->parent)
97     {      
98       if (sym->ns == ns)
99         return true;
100     }
101
102   return false;
103 }
104
105 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
106    an ABSTRACT derived-type.  If where is not NULL, an error message with that
107    locus is printed, optionally using name.  */
108
109 static gfc_try
110 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
111 {
112   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
113     {
114       if (where)
115         {
116           if (name)
117             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
118                        name, where, ts->u.derived->name);
119           else
120             gfc_error ("ABSTRACT type '%s' used at %L",
121                        ts->u.derived->name, where);
122         }
123
124       return FAILURE;
125     }
126
127   return SUCCESS;
128 }
129
130
131 static void resolve_symbol (gfc_symbol *sym);
132 static gfc_try resolve_intrinsic (gfc_symbol *sym, locus *loc);
133
134
135 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
136
137 static gfc_try
138 resolve_procedure_interface (gfc_symbol *sym)
139 {
140   if (sym->ts.interface == sym)
141     {
142       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
143                  sym->name, &sym->declared_at);
144       return FAILURE;
145     }
146   if (sym->ts.interface->attr.procedure)
147     {
148       gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
149                  "in a later PROCEDURE statement", sym->ts.interface->name,
150                  sym->name, &sym->declared_at);
151       return FAILURE;
152     }
153
154   /* Get the attributes from the interface (now resolved).  */
155   if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
156     {
157       gfc_symbol *ifc = sym->ts.interface;
158       resolve_symbol (ifc);
159
160       if (ifc->attr.intrinsic)
161         resolve_intrinsic (ifc, &ifc->declared_at);
162
163       if (ifc->result)
164         {
165           sym->ts = ifc->result->ts;
166           sym->result = sym;
167         }
168       else   
169         sym->ts = ifc->ts;
170       sym->ts.interface = ifc;
171       sym->attr.function = ifc->attr.function;
172       sym->attr.subroutine = ifc->attr.subroutine;
173       gfc_copy_formal_args (sym, ifc);
174
175       sym->attr.allocatable = ifc->attr.allocatable;
176       sym->attr.pointer = ifc->attr.pointer;
177       sym->attr.pure = ifc->attr.pure;
178       sym->attr.elemental = ifc->attr.elemental;
179       sym->attr.dimension = ifc->attr.dimension;
180       sym->attr.contiguous = ifc->attr.contiguous;
181       sym->attr.recursive = ifc->attr.recursive;
182       sym->attr.always_explicit = ifc->attr.always_explicit;
183       sym->attr.ext_attr |= ifc->attr.ext_attr;
184       sym->attr.is_bind_c = ifc->attr.is_bind_c;
185       /* Copy array spec.  */
186       sym->as = gfc_copy_array_spec (ifc->as);
187       if (sym->as)
188         {
189           int i;
190           for (i = 0; i < sym->as->rank; i++)
191             {
192               gfc_expr_replace_symbols (sym->as->lower[i], sym);
193               gfc_expr_replace_symbols (sym->as->upper[i], sym);
194             }
195         }
196       /* Copy char length.  */
197       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
198         {
199           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
200           gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
201           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
202               && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
203             return FAILURE;
204         }
205     }
206   else if (sym->ts.interface->name[0] != '\0')
207     {
208       gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
209                  sym->ts.interface->name, sym->name, &sym->declared_at);
210       return FAILURE;
211     }
212
213   return SUCCESS;
214 }
215
216
217 /* Resolve types of formal argument lists.  These have to be done early so that
218    the formal argument lists of module procedures can be copied to the
219    containing module before the individual procedures are resolved
220    individually.  We also resolve argument lists of procedures in interface
221    blocks because they are self-contained scoping units.
222
223    Since a dummy argument cannot be a non-dummy procedure, the only
224    resort left for untyped names are the IMPLICIT types.  */
225
226 static void
227 resolve_formal_arglist (gfc_symbol *proc)
228 {
229   gfc_formal_arglist *f;
230   gfc_symbol *sym;
231   int i;
232
233   if (proc->result != NULL)
234     sym = proc->result;
235   else
236     sym = proc;
237
238   if (gfc_elemental (proc)
239       || sym->attr.pointer || sym->attr.allocatable
240       || (sym->as && sym->as->rank > 0))
241     {
242       proc->attr.always_explicit = 1;
243       sym->attr.always_explicit = 1;
244     }
245
246   formal_arg_flag = 1;
247
248   for (f = proc->formal; f; f = f->next)
249     {
250       sym = f->sym;
251
252       if (sym == NULL)
253         {
254           /* Alternate return placeholder.  */
255           if (gfc_elemental (proc))
256             gfc_error ("Alternate return specifier in elemental subroutine "
257                        "'%s' at %L is not allowed", proc->name,
258                        &proc->declared_at);
259           if (proc->attr.function)
260             gfc_error ("Alternate return specifier in function "
261                        "'%s' at %L is not allowed", proc->name,
262                        &proc->declared_at);
263           continue;
264         }
265       else if (sym->attr.procedure && sym->ts.interface
266                && sym->attr.if_source != IFSRC_DECL)
267         resolve_procedure_interface (sym);
268
269       if (sym->attr.if_source != IFSRC_UNKNOWN)
270         resolve_formal_arglist (sym);
271
272       if (sym->attr.subroutine || sym->attr.external)
273         {
274           if (sym->attr.flavor == FL_UNKNOWN)
275             gfc_add_flavor (&sym->attr, FL_PROCEDURE, sym->name, &sym->declared_at);
276         }
277       else
278         {
279           if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
280               && (!sym->attr.function || sym->result == sym))
281             gfc_set_default_type (sym, 1, sym->ns);
282         }
283
284       gfc_resolve_array_spec (sym->as, 0);
285
286       /* We can't tell if an array with dimension (:) is assumed or deferred
287          shape until we know if it has the pointer or allocatable attributes.
288       */
289       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
290           && !(sym->attr.pointer || sym->attr.allocatable)
291           && sym->attr.flavor != FL_PROCEDURE)
292         {
293           sym->as->type = AS_ASSUMED_SHAPE;
294           for (i = 0; i < sym->as->rank; i++)
295             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
296                                                   NULL, 1);
297         }
298
299       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
300           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
301           || sym->attr.optional)
302         {
303           proc->attr.always_explicit = 1;
304           if (proc->result)
305             proc->result->attr.always_explicit = 1;
306         }
307
308       /* If the flavor is unknown at this point, it has to be a variable.
309          A procedure specification would have already set the type.  */
310
311       if (sym->attr.flavor == FL_UNKNOWN)
312         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
313
314       if (gfc_pure (proc))
315         {
316           if (sym->attr.flavor == FL_PROCEDURE)
317             {
318               /* F08:C1279.  */
319               if (!gfc_pure (sym))
320                 {
321                   gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
322                             "also be PURE", sym->name, &sym->declared_at);
323                   continue;
324                 }
325             }
326           else if (!sym->attr.pointer)
327             {
328               if (proc->attr.function && sym->attr.intent != INTENT_IN)
329                 {
330                   if (sym->attr.value)
331                     gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s'"
332                                     " of pure function '%s' at %L with VALUE "
333                                     "attribute but without INTENT(IN)",
334                                     sym->name, proc->name, &sym->declared_at);
335                   else
336                     gfc_error ("Argument '%s' of pure function '%s' at %L must "
337                                "be INTENT(IN) or VALUE", sym->name, proc->name,
338                                &sym->declared_at);
339                 }
340
341               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
342                 {
343                   if (sym->attr.value)
344                     gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s'"
345                                     " of pure subroutine '%s' at %L with VALUE "
346                                     "attribute but without INTENT", sym->name,
347                                     proc->name, &sym->declared_at);
348                   else
349                     gfc_error ("Argument '%s' of pure subroutine '%s' at %L "
350                                "must have its INTENT specified or have the "
351                                "VALUE attribute", sym->name, proc->name,
352                                &sym->declared_at);
353                 }
354             }
355         }
356
357       if (proc->attr.implicit_pure)
358         {
359           if (sym->attr.flavor == FL_PROCEDURE)
360             {
361               if (!gfc_pure(sym))
362                 proc->attr.implicit_pure = 0;
363             }
364           else if (!sym->attr.pointer)
365             {
366               if (proc->attr.function && sym->attr.intent != INTENT_IN)
367                 proc->attr.implicit_pure = 0;
368
369               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
370                 proc->attr.implicit_pure = 0;
371             }
372         }
373
374       if (gfc_elemental (proc))
375         {
376           /* F08:C1289.  */
377           if (sym->attr.codimension)
378             {
379               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
380                          "procedure", sym->name, &sym->declared_at);
381               continue;
382             }
383
384           if (sym->as != NULL)
385             {
386               gfc_error ("Argument '%s' of elemental procedure at %L must "
387                          "be scalar", sym->name, &sym->declared_at);
388               continue;
389             }
390
391           if (sym->attr.allocatable)
392             {
393               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
394                          "have the ALLOCATABLE attribute", sym->name,
395                          &sym->declared_at);
396               continue;
397             }
398
399           if (sym->attr.pointer)
400             {
401               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
402                          "have the POINTER attribute", sym->name,
403                          &sym->declared_at);
404               continue;
405             }
406
407           if (sym->attr.flavor == FL_PROCEDURE)
408             {
409               gfc_error ("Dummy procedure '%s' not allowed in elemental "
410                          "procedure '%s' at %L", sym->name, proc->name,
411                          &sym->declared_at);
412               continue;
413             }
414
415           if (sym->attr.intent == INTENT_UNKNOWN)
416             {
417               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
418                          "have its INTENT specified", sym->name, proc->name,
419                          &sym->declared_at);
420               continue;
421             }
422         }
423
424       /* Each dummy shall be specified to be scalar.  */
425       if (proc->attr.proc == PROC_ST_FUNCTION)
426         {
427           if (sym->as != NULL)
428             {
429               gfc_error ("Argument '%s' of statement function at %L must "
430                          "be scalar", sym->name, &sym->declared_at);
431               continue;
432             }
433
434           if (sym->ts.type == BT_CHARACTER)
435             {
436               gfc_charlen *cl = sym->ts.u.cl;
437               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
438                 {
439                   gfc_error ("Character-valued argument '%s' of statement "
440                              "function at %L must have constant length",
441                              sym->name, &sym->declared_at);
442                   continue;
443                 }
444             }
445         }
446     }
447   formal_arg_flag = 0;
448 }
449
450
451 /* Work function called when searching for symbols that have argument lists
452    associated with them.  */
453
454 static void
455 find_arglists (gfc_symbol *sym)
456 {
457   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns
458       || sym->attr.flavor == FL_DERIVED)
459     return;
460
461   resolve_formal_arglist (sym);
462 }
463
464
465 /* Given a namespace, resolve all formal argument lists within the namespace.
466  */
467
468 static void
469 resolve_formal_arglists (gfc_namespace *ns)
470 {
471   if (ns == NULL)
472     return;
473
474   gfc_traverse_ns (ns, find_arglists);
475 }
476
477
478 static void
479 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
480 {
481   gfc_try t;
482
483   /* If this namespace is not a function or an entry master function,
484      ignore it.  */
485   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
486       || sym->attr.entry_master)
487     return;
488
489   /* Try to find out of what the return type is.  */
490   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
491     {
492       t = gfc_set_default_type (sym->result, 0, ns);
493
494       if (t == FAILURE && !sym->result->attr.untyped)
495         {
496           if (sym->result == sym)
497             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
498                        sym->name, &sym->declared_at);
499           else if (!sym->result->attr.proc_pointer)
500             gfc_error ("Result '%s' of contained function '%s' at %L has "
501                        "no IMPLICIT type", sym->result->name, sym->name,
502                        &sym->result->declared_at);
503           sym->result->attr.untyped = 1;
504         }
505     }
506
507   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
508      type, lists the only ways a character length value of * can be used:
509      dummy arguments of procedures, named constants, and function results
510      in external functions.  Internal function results and results of module
511      procedures are not on this list, ergo, not permitted.  */
512
513   if (sym->result->ts.type == BT_CHARACTER)
514     {
515       gfc_charlen *cl = sym->result->ts.u.cl;
516       if ((!cl || !cl->length) && !sym->result->ts.deferred)
517         {
518           /* See if this is a module-procedure and adapt error message
519              accordingly.  */
520           bool module_proc;
521           gcc_assert (ns->parent && ns->parent->proc_name);
522           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
523
524           gfc_error ("Character-valued %s '%s' at %L must not be"
525                      " assumed length",
526                      module_proc ? _("module procedure")
527                                  : _("internal function"),
528                      sym->name, &sym->declared_at);
529         }
530     }
531 }
532
533
534 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
535    introduce duplicates.  */
536
537 static void
538 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
539 {
540   gfc_formal_arglist *f, *new_arglist;
541   gfc_symbol *new_sym;
542
543   for (; new_args != NULL; new_args = new_args->next)
544     {
545       new_sym = new_args->sym;
546       /* See if this arg is already in the formal argument list.  */
547       for (f = proc->formal; f; f = f->next)
548         {
549           if (new_sym == f->sym)
550             break;
551         }
552
553       if (f)
554         continue;
555
556       /* Add a new argument.  Argument order is not important.  */
557       new_arglist = gfc_get_formal_arglist ();
558       new_arglist->sym = new_sym;
559       new_arglist->next = proc->formal;
560       proc->formal  = new_arglist;
561     }
562 }
563
564
565 /* Flag the arguments that are not present in all entries.  */
566
567 static void
568 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
569 {
570   gfc_formal_arglist *f, *head;
571   head = new_args;
572
573   for (f = proc->formal; f; f = f->next)
574     {
575       if (f->sym == NULL)
576         continue;
577
578       for (new_args = head; new_args; new_args = new_args->next)
579         {
580           if (new_args->sym == f->sym)
581             break;
582         }
583
584       if (new_args)
585         continue;
586
587       f->sym->attr.not_always_present = 1;
588     }
589 }
590
591
592 /* Resolve alternate entry points.  If a symbol has multiple entry points we
593    create a new master symbol for the main routine, and turn the existing
594    symbol into an entry point.  */
595
596 static void
597 resolve_entries (gfc_namespace *ns)
598 {
599   gfc_namespace *old_ns;
600   gfc_code *c;
601   gfc_symbol *proc;
602   gfc_entry_list *el;
603   char name[GFC_MAX_SYMBOL_LEN + 1];
604   static int master_count = 0;
605
606   if (ns->proc_name == NULL)
607     return;
608
609   /* No need to do anything if this procedure doesn't have alternate entry
610      points.  */
611   if (!ns->entries)
612     return;
613
614   /* We may already have resolved alternate entry points.  */
615   if (ns->proc_name->attr.entry_master)
616     return;
617
618   /* If this isn't a procedure something has gone horribly wrong.  */
619   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
620
621   /* Remember the current namespace.  */
622   old_ns = gfc_current_ns;
623
624   gfc_current_ns = ns;
625
626   /* Add the main entry point to the list of entry points.  */
627   el = gfc_get_entry_list ();
628   el->sym = ns->proc_name;
629   el->id = 0;
630   el->next = ns->entries;
631   ns->entries = el;
632   ns->proc_name->attr.entry = 1;
633
634   /* If it is a module function, it needs to be in the right namespace
635      so that gfc_get_fake_result_decl can gather up the results. The
636      need for this arose in get_proc_name, where these beasts were
637      left in their own namespace, to keep prior references linked to
638      the entry declaration.*/
639   if (ns->proc_name->attr.function
640       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
641     el->sym->ns = ns;
642
643   /* Do the same for entries where the master is not a module
644      procedure.  These are retained in the module namespace because
645      of the module procedure declaration.  */
646   for (el = el->next; el; el = el->next)
647     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
648           && el->sym->attr.mod_proc)
649       el->sym->ns = ns;
650   el = ns->entries;
651
652   /* Add an entry statement for it.  */
653   c = gfc_get_code ();
654   c->op = EXEC_ENTRY;
655   c->ext.entry = el;
656   c->next = ns->code;
657   ns->code = c;
658
659   /* Create a new symbol for the master function.  */
660   /* Give the internal function a unique name (within this file).
661      Also include the function name so the user has some hope of figuring
662      out what is going on.  */
663   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
664             master_count++, ns->proc_name->name);
665   gfc_get_ha_symbol (name, &proc);
666   gcc_assert (proc != NULL);
667
668   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
669   if (ns->proc_name->attr.subroutine)
670     gfc_add_subroutine (&proc->attr, proc->name, NULL);
671   else
672     {
673       gfc_symbol *sym;
674       gfc_typespec *ts, *fts;
675       gfc_array_spec *as, *fas;
676       gfc_add_function (&proc->attr, proc->name, NULL);
677       proc->result = proc;
678       fas = ns->entries->sym->as;
679       fas = fas ? fas : ns->entries->sym->result->as;
680       fts = &ns->entries->sym->result->ts;
681       if (fts->type == BT_UNKNOWN)
682         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
683       for (el = ns->entries->next; el; el = el->next)
684         {
685           ts = &el->sym->result->ts;
686           as = el->sym->as;
687           as = as ? as : el->sym->result->as;
688           if (ts->type == BT_UNKNOWN)
689             ts = gfc_get_default_type (el->sym->result->name, NULL);
690
691           if (! gfc_compare_types (ts, fts)
692               || (el->sym->result->attr.dimension
693                   != ns->entries->sym->result->attr.dimension)
694               || (el->sym->result->attr.pointer
695                   != ns->entries->sym->result->attr.pointer))
696             break;
697           else if (as && fas && ns->entries->sym->result != el->sym->result
698                       && gfc_compare_array_spec (as, fas) == 0)
699             gfc_error ("Function %s at %L has entries with mismatched "
700                        "array specifications", ns->entries->sym->name,
701                        &ns->entries->sym->declared_at);
702           /* The characteristics need to match and thus both need to have
703              the same string length, i.e. both len=*, or both len=4.
704              Having both len=<variable> is also possible, but difficult to
705              check at compile time.  */
706           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
707                    && (((ts->u.cl->length && !fts->u.cl->length)
708                         ||(!ts->u.cl->length && fts->u.cl->length))
709                        || (ts->u.cl->length
710                            && ts->u.cl->length->expr_type
711                               != fts->u.cl->length->expr_type)
712                        || (ts->u.cl->length
713                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
714                            && mpz_cmp (ts->u.cl->length->value.integer,
715                                        fts->u.cl->length->value.integer) != 0)))
716             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
717                             "entries returning variables of different "
718                             "string lengths", ns->entries->sym->name,
719                             &ns->entries->sym->declared_at);
720         }
721
722       if (el == NULL)
723         {
724           sym = ns->entries->sym->result;
725           /* All result types the same.  */
726           proc->ts = *fts;
727           if (sym->attr.dimension)
728             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
729           if (sym->attr.pointer)
730             gfc_add_pointer (&proc->attr, NULL);
731         }
732       else
733         {
734           /* Otherwise the result will be passed through a union by
735              reference.  */
736           proc->attr.mixed_entry_master = 1;
737           for (el = ns->entries; el; el = el->next)
738             {
739               sym = el->sym->result;
740               if (sym->attr.dimension)
741                 {
742                   if (el == ns->entries)
743                     gfc_error ("FUNCTION result %s can't be an array in "
744                                "FUNCTION %s at %L", sym->name,
745                                ns->entries->sym->name, &sym->declared_at);
746                   else
747                     gfc_error ("ENTRY result %s can't be an array in "
748                                "FUNCTION %s at %L", sym->name,
749                                ns->entries->sym->name, &sym->declared_at);
750                 }
751               else if (sym->attr.pointer)
752                 {
753                   if (el == ns->entries)
754                     gfc_error ("FUNCTION result %s can't be a POINTER in "
755                                "FUNCTION %s at %L", sym->name,
756                                ns->entries->sym->name, &sym->declared_at);
757                   else
758                     gfc_error ("ENTRY result %s can't be a POINTER in "
759                                "FUNCTION %s at %L", sym->name,
760                                ns->entries->sym->name, &sym->declared_at);
761                 }
762               else
763                 {
764                   ts = &sym->ts;
765                   if (ts->type == BT_UNKNOWN)
766                     ts = gfc_get_default_type (sym->name, NULL);
767                   switch (ts->type)
768                     {
769                     case BT_INTEGER:
770                       if (ts->kind == gfc_default_integer_kind)
771                         sym = NULL;
772                       break;
773                     case BT_REAL:
774                       if (ts->kind == gfc_default_real_kind
775                           || ts->kind == gfc_default_double_kind)
776                         sym = NULL;
777                       break;
778                     case BT_COMPLEX:
779                       if (ts->kind == gfc_default_complex_kind)
780                         sym = NULL;
781                       break;
782                     case BT_LOGICAL:
783                       if (ts->kind == gfc_default_logical_kind)
784                         sym = NULL;
785                       break;
786                     case BT_UNKNOWN:
787                       /* We will issue error elsewhere.  */
788                       sym = NULL;
789                       break;
790                     default:
791                       break;
792                     }
793                   if (sym)
794                     {
795                       if (el == ns->entries)
796                         gfc_error ("FUNCTION result %s can't be of type %s "
797                                    "in FUNCTION %s at %L", sym->name,
798                                    gfc_typename (ts), ns->entries->sym->name,
799                                    &sym->declared_at);
800                       else
801                         gfc_error ("ENTRY result %s can't be of type %s "
802                                    "in FUNCTION %s at %L", sym->name,
803                                    gfc_typename (ts), ns->entries->sym->name,
804                                    &sym->declared_at);
805                     }
806                 }
807             }
808         }
809     }
810   proc->attr.access = ACCESS_PRIVATE;
811   proc->attr.entry_master = 1;
812
813   /* Merge all the entry point arguments.  */
814   for (el = ns->entries; el; el = el->next)
815     merge_argument_lists (proc, el->sym->formal);
816
817   /* Check the master formal arguments for any that are not
818      present in all entry points.  */
819   for (el = ns->entries; el; el = el->next)
820     check_argument_lists (proc, el->sym->formal);
821
822   /* Use the master function for the function body.  */
823   ns->proc_name = proc;
824
825   /* Finalize the new symbols.  */
826   gfc_commit_symbols ();
827
828   /* Restore the original namespace.  */
829   gfc_current_ns = old_ns;
830 }
831
832
833 /* Resolve common variables.  */
834 static void
835 resolve_common_vars (gfc_symbol *sym, bool named_common)
836 {
837   gfc_symbol *csym = sym;
838
839   for (; csym; csym = csym->common_next)
840     {
841       if (csym->value || csym->attr.data)
842         {
843           if (!csym->ns->is_block_data)
844             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
845                             "but only in BLOCK DATA initialization is "
846                             "allowed", csym->name, &csym->declared_at);
847           else if (!named_common)
848             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
849                             "in a blank COMMON but initialization is only "
850                             "allowed in named common blocks", csym->name,
851                             &csym->declared_at);
852         }
853
854       if (csym->ts.type != BT_DERIVED)
855         continue;
856
857       if (!(csym->ts.u.derived->attr.sequence
858             || csym->ts.u.derived->attr.is_bind_c))
859         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
860                        "has neither the SEQUENCE nor the BIND(C) "
861                        "attribute", csym->name, &csym->declared_at);
862       if (csym->ts.u.derived->attr.alloc_comp)
863         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
864                        "has an ultimate component that is "
865                        "allocatable", csym->name, &csym->declared_at);
866       if (gfc_has_default_initializer (csym->ts.u.derived))
867         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
868                        "may not have default initializer", csym->name,
869                        &csym->declared_at);
870
871       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
872         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
873     }
874 }
875
876 /* Resolve common blocks.  */
877 static void
878 resolve_common_blocks (gfc_symtree *common_root)
879 {
880   gfc_symbol *sym;
881
882   if (common_root == NULL)
883     return;
884
885   if (common_root->left)
886     resolve_common_blocks (common_root->left);
887   if (common_root->right)
888     resolve_common_blocks (common_root->right);
889
890   resolve_common_vars (common_root->n.common->head, true);
891
892   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
893   if (sym == NULL)
894     return;
895
896   if (sym->attr.flavor == FL_PARAMETER)
897     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
898                sym->name, &common_root->n.common->where, &sym->declared_at);
899
900   if (sym->attr.external)
901     gfc_error ("COMMON block '%s' at %L can not have the EXTERNAL attribute",
902                sym->name, &common_root->n.common->where);
903
904   if (sym->attr.intrinsic)
905     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
906                sym->name, &common_root->n.common->where);
907   else if (sym->attr.result
908            || gfc_is_function_return_value (sym, gfc_current_ns))
909     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
910                     "that is also a function result", sym->name,
911                     &common_root->n.common->where);
912   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
913            && sym->attr.proc != PROC_ST_FUNCTION)
914     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
915                     "that is also a global procedure", sym->name,
916                     &common_root->n.common->where);
917 }
918
919
920 /* Resolve contained function types.  Because contained functions can call one
921    another, they have to be worked out before any of the contained procedures
922    can be resolved.
923
924    The good news is that if a function doesn't already have a type, the only
925    way it can get one is through an IMPLICIT type or a RESULT variable, because
926    by definition contained functions are contained namespace they're contained
927    in, not in a sibling or parent namespace.  */
928
929 static void
930 resolve_contained_functions (gfc_namespace *ns)
931 {
932   gfc_namespace *child;
933   gfc_entry_list *el;
934
935   resolve_formal_arglists (ns);
936
937   for (child = ns->contained; child; child = child->sibling)
938     {
939       /* Resolve alternate entry points first.  */
940       resolve_entries (child);
941
942       /* Then check function return types.  */
943       resolve_contained_fntype (child->proc_name, child);
944       for (el = child->entries; el; el = el->next)
945         resolve_contained_fntype (el->sym, child);
946     }
947 }
948
949
950 static gfc_try resolve_fl_derived0 (gfc_symbol *sym);
951
952
953 /* Resolve all of the elements of a structure constructor and make sure that
954    the types are correct. The 'init' flag indicates that the given
955    constructor is an initializer.  */
956
957 static gfc_try
958 resolve_structure_cons (gfc_expr *expr, int init)
959 {
960   gfc_constructor *cons;
961   gfc_component *comp;
962   gfc_try t;
963   symbol_attribute a;
964
965   t = SUCCESS;
966
967   if (expr->ts.type == BT_DERIVED)
968     resolve_fl_derived0 (expr->ts.u.derived);
969
970   cons = gfc_constructor_first (expr->value.constructor);
971
972   /* See if the user is trying to invoke a structure constructor for one of
973      the iso_c_binding derived types.  */
974   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
975       && expr->ts.u.derived->ts.is_iso_c && cons
976       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
977     {
978       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
979                  expr->ts.u.derived->name, &(expr->where));
980       return FAILURE;
981     }
982
983   /* Return if structure constructor is c_null_(fun)prt.  */
984   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
985       && expr->ts.u.derived->ts.is_iso_c && cons
986       && cons->expr && cons->expr->expr_type == EXPR_NULL)
987     return SUCCESS;
988
989   /* A constructor may have references if it is the result of substituting a
990      parameter variable.  In this case we just pull out the component we
991      want.  */
992   if (expr->ref)
993     comp = expr->ref->u.c.sym->components;
994   else
995     comp = expr->ts.u.derived->components;
996
997   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
998     {
999       int rank;
1000
1001       if (!cons->expr)
1002         continue;
1003
1004       if (gfc_resolve_expr (cons->expr) == FAILURE)
1005         {
1006           t = FAILURE;
1007           continue;
1008         }
1009
1010       rank = comp->as ? comp->as->rank : 0;
1011       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
1012           && (comp->attr.allocatable || cons->expr->rank))
1013         {
1014           gfc_error ("The rank of the element in the structure "
1015                      "constructor at %L does not match that of the "
1016                      "component (%d/%d)", &cons->expr->where,
1017                      cons->expr->rank, rank);
1018           t = FAILURE;
1019         }
1020
1021       /* If we don't have the right type, try to convert it.  */
1022
1023       if (!comp->attr.proc_pointer &&
1024           !gfc_compare_types (&cons->expr->ts, &comp->ts))
1025         {
1026           t = FAILURE;
1027           if (strcmp (comp->name, "_extends") == 0)
1028             {
1029               /* Can afford to be brutal with the _extends initializer.
1030                  The derived type can get lost because it is PRIVATE
1031                  but it is not usage constrained by the standard.  */
1032               cons->expr->ts = comp->ts;
1033               t = SUCCESS;
1034             }
1035           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1036             gfc_error ("The element in the structure constructor at %L, "
1037                        "for pointer component '%s', is %s but should be %s",
1038                        &cons->expr->where, comp->name,
1039                        gfc_basic_typename (cons->expr->ts.type),
1040                        gfc_basic_typename (comp->ts.type));
1041           else
1042             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1043         }
1044
1045       /* For strings, the length of the constructor should be the same as
1046          the one of the structure, ensure this if the lengths are known at
1047          compile time and when we are dealing with PARAMETER or structure
1048          constructors.  */
1049       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1050           && comp->ts.u.cl->length
1051           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1052           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1053           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1054           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1055                       comp->ts.u.cl->length->value.integer) != 0)
1056         {
1057           if (cons->expr->expr_type == EXPR_VARIABLE
1058               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1059             {
1060               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1061                  to make use of the gfc_resolve_character_array_constructor
1062                  machinery.  The expression is later simplified away to
1063                  an array of string literals.  */
1064               gfc_expr *para = cons->expr;
1065               cons->expr = gfc_get_expr ();
1066               cons->expr->ts = para->ts;
1067               cons->expr->where = para->where;
1068               cons->expr->expr_type = EXPR_ARRAY;
1069               cons->expr->rank = para->rank;
1070               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1071               gfc_constructor_append_expr (&cons->expr->value.constructor,
1072                                            para, &cons->expr->where);
1073             }
1074           if (cons->expr->expr_type == EXPR_ARRAY)
1075             {
1076               gfc_constructor *p;
1077               p = gfc_constructor_first (cons->expr->value.constructor);
1078               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1079                 {
1080                   gfc_charlen *cl, *cl2;
1081
1082                   cl2 = NULL;
1083                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1084                     {
1085                       if (cl == cons->expr->ts.u.cl)
1086                         break;
1087                       cl2 = cl;
1088                     }
1089
1090                   gcc_assert (cl);
1091
1092                   if (cl2)
1093                     cl2->next = cl->next;
1094
1095                   gfc_free_expr (cl->length);
1096                   free (cl);
1097                 }
1098
1099               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1100               cons->expr->ts.u.cl->length_from_typespec = true;
1101               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1102               gfc_resolve_character_array_constructor (cons->expr);
1103             }
1104         }
1105
1106       if (cons->expr->expr_type == EXPR_NULL
1107           && !(comp->attr.pointer || comp->attr.allocatable
1108                || comp->attr.proc_pointer
1109                || (comp->ts.type == BT_CLASS
1110                    && (CLASS_DATA (comp)->attr.class_pointer
1111                        || CLASS_DATA (comp)->attr.allocatable))))
1112         {
1113           t = FAILURE;
1114           gfc_error ("The NULL in the structure constructor at %L is "
1115                      "being applied to component '%s', which is neither "
1116                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1117                      comp->name);
1118         }
1119
1120       if (comp->attr.proc_pointer && comp->ts.interface)
1121         {
1122           /* Check procedure pointer interface.  */
1123           gfc_symbol *s2 = NULL;
1124           gfc_component *c2;
1125           const char *name;
1126           char err[200];
1127
1128           if (gfc_is_proc_ptr_comp (cons->expr, &c2))
1129             {
1130               s2 = c2->ts.interface;
1131               name = c2->name;
1132             }
1133           else if (cons->expr->expr_type == EXPR_FUNCTION)
1134             {
1135               s2 = cons->expr->symtree->n.sym->result;
1136               name = cons->expr->symtree->n.sym->result->name;
1137             }
1138           else if (cons->expr->expr_type != EXPR_NULL)
1139             {
1140               s2 = cons->expr->symtree->n.sym;
1141               name = cons->expr->symtree->n.sym->name;
1142             }
1143
1144           if (s2 && !gfc_compare_interfaces (comp->ts.interface, s2, name, 0, 1,
1145                                              err, sizeof (err)))
1146             {
1147               gfc_error ("Interface mismatch for procedure-pointer component "
1148                          "'%s' in structure constructor at %L: %s",
1149                          comp->name, &cons->expr->where, err);
1150               return FAILURE;
1151             }
1152         }
1153
1154       if (!comp->attr.pointer || comp->attr.proc_pointer
1155           || cons->expr->expr_type == EXPR_NULL)
1156         continue;
1157
1158       a = gfc_expr_attr (cons->expr);
1159
1160       if (!a.pointer && !a.target)
1161         {
1162           t = FAILURE;
1163           gfc_error ("The element in the structure constructor at %L, "
1164                      "for pointer component '%s' should be a POINTER or "
1165                      "a TARGET", &cons->expr->where, comp->name);
1166         }
1167
1168       if (init)
1169         {
1170           /* F08:C461. Additional checks for pointer initialization.  */
1171           if (a.allocatable)
1172             {
1173               t = FAILURE;
1174               gfc_error ("Pointer initialization target at %L "
1175                          "must not be ALLOCATABLE ", &cons->expr->where);
1176             }
1177           if (!a.save)
1178             {
1179               t = FAILURE;
1180               gfc_error ("Pointer initialization target at %L "
1181                          "must have the SAVE attribute", &cons->expr->where);
1182             }
1183         }
1184
1185       /* F2003, C1272 (3).  */
1186       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1187           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1188               || gfc_is_coindexed (cons->expr)))
1189         {
1190           t = FAILURE;
1191           gfc_error ("Invalid expression in the structure constructor for "
1192                      "pointer component '%s' at %L in PURE procedure",
1193                      comp->name, &cons->expr->where);
1194         }
1195
1196       if (gfc_implicit_pure (NULL)
1197             && cons->expr->expr_type == EXPR_VARIABLE
1198             && (gfc_impure_variable (cons->expr->symtree->n.sym)
1199                 || gfc_is_coindexed (cons->expr)))
1200         gfc_current_ns->proc_name->attr.implicit_pure = 0;
1201
1202     }
1203
1204   return t;
1205 }
1206
1207
1208 /****************** Expression name resolution ******************/
1209
1210 /* Returns 0 if a symbol was not declared with a type or
1211    attribute declaration statement, nonzero otherwise.  */
1212
1213 static int
1214 was_declared (gfc_symbol *sym)
1215 {
1216   symbol_attribute a;
1217
1218   a = sym->attr;
1219
1220   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1221     return 1;
1222
1223   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1224       || a.optional || a.pointer || a.save || a.target || a.volatile_
1225       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1226       || a.asynchronous || a.codimension)
1227     return 1;
1228
1229   return 0;
1230 }
1231
1232
1233 /* Determine if a symbol is generic or not.  */
1234
1235 static int
1236 generic_sym (gfc_symbol *sym)
1237 {
1238   gfc_symbol *s;
1239
1240   if (sym->attr.generic ||
1241       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1242     return 1;
1243
1244   if (was_declared (sym) || sym->ns->parent == NULL)
1245     return 0;
1246
1247   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1248   
1249   if (s != NULL)
1250     {
1251       if (s == sym)
1252         return 0;
1253       else
1254         return generic_sym (s);
1255     }
1256
1257   return 0;
1258 }
1259
1260
1261 /* Determine if a symbol is specific or not.  */
1262
1263 static int
1264 specific_sym (gfc_symbol *sym)
1265 {
1266   gfc_symbol *s;
1267
1268   if (sym->attr.if_source == IFSRC_IFBODY
1269       || sym->attr.proc == PROC_MODULE
1270       || sym->attr.proc == PROC_INTERNAL
1271       || sym->attr.proc == PROC_ST_FUNCTION
1272       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1273       || sym->attr.external)
1274     return 1;
1275
1276   if (was_declared (sym) || sym->ns->parent == NULL)
1277     return 0;
1278
1279   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1280
1281   return (s == NULL) ? 0 : specific_sym (s);
1282 }
1283
1284
1285 /* Figure out if the procedure is specific, generic or unknown.  */
1286
1287 typedef enum
1288 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1289 proc_type;
1290
1291 static proc_type
1292 procedure_kind (gfc_symbol *sym)
1293 {
1294   if (generic_sym (sym))
1295     return PTYPE_GENERIC;
1296
1297   if (specific_sym (sym))
1298     return PTYPE_SPECIFIC;
1299
1300   return PTYPE_UNKNOWN;
1301 }
1302
1303 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1304    is nonzero when matching actual arguments.  */
1305
1306 static int need_full_assumed_size = 0;
1307
1308 static bool
1309 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1310 {
1311   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1312       return false;
1313
1314   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1315      What should it be?  */
1316   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1317           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1318                && (e->ref->u.ar.type == AR_FULL))
1319     {
1320       gfc_error ("The upper bound in the last dimension must "
1321                  "appear in the reference to the assumed size "
1322                  "array '%s' at %L", sym->name, &e->where);
1323       return true;
1324     }
1325   return false;
1326 }
1327
1328
1329 /* Look for bad assumed size array references in argument expressions
1330   of elemental and array valued intrinsic procedures.  Since this is
1331   called from procedure resolution functions, it only recurses at
1332   operators.  */
1333
1334 static bool
1335 resolve_assumed_size_actual (gfc_expr *e)
1336 {
1337   if (e == NULL)
1338    return false;
1339
1340   switch (e->expr_type)
1341     {
1342     case EXPR_VARIABLE:
1343       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1344         return true;
1345       break;
1346
1347     case EXPR_OP:
1348       if (resolve_assumed_size_actual (e->value.op.op1)
1349           || resolve_assumed_size_actual (e->value.op.op2))
1350         return true;
1351       break;
1352
1353     default:
1354       break;
1355     }
1356   return false;
1357 }
1358
1359
1360 /* Check a generic procedure, passed as an actual argument, to see if
1361    there is a matching specific name.  If none, it is an error, and if
1362    more than one, the reference is ambiguous.  */
1363 static int
1364 count_specific_procs (gfc_expr *e)
1365 {
1366   int n;
1367   gfc_interface *p;
1368   gfc_symbol *sym;
1369         
1370   n = 0;
1371   sym = e->symtree->n.sym;
1372
1373   for (p = sym->generic; p; p = p->next)
1374     if (strcmp (sym->name, p->sym->name) == 0)
1375       {
1376         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1377                                        sym->name);
1378         n++;
1379       }
1380
1381   if (n > 1)
1382     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1383                &e->where);
1384
1385   if (n == 0)
1386     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1387                "argument at %L", sym->name, &e->where);
1388
1389   return n;
1390 }
1391
1392
1393 /* See if a call to sym could possibly be a not allowed RECURSION because of
1394    a missing RECURIVE declaration.  This means that either sym is the current
1395    context itself, or sym is the parent of a contained procedure calling its
1396    non-RECURSIVE containing procedure.
1397    This also works if sym is an ENTRY.  */
1398
1399 static bool
1400 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1401 {
1402   gfc_symbol* proc_sym;
1403   gfc_symbol* context_proc;
1404   gfc_namespace* real_context;
1405
1406   if (sym->attr.flavor == FL_PROGRAM
1407       || sym->attr.flavor == FL_DERIVED)
1408     return false;
1409
1410   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1411
1412   /* If we've got an ENTRY, find real procedure.  */
1413   if (sym->attr.entry && sym->ns->entries)
1414     proc_sym = sym->ns->entries->sym;
1415   else
1416     proc_sym = sym;
1417
1418   /* If sym is RECURSIVE, all is well of course.  */
1419   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1420     return false;
1421
1422   /* Find the context procedure's "real" symbol if it has entries.
1423      We look for a procedure symbol, so recurse on the parents if we don't
1424      find one (like in case of a BLOCK construct).  */
1425   for (real_context = context; ; real_context = real_context->parent)
1426     {
1427       /* We should find something, eventually!  */
1428       gcc_assert (real_context);
1429
1430       context_proc = (real_context->entries ? real_context->entries->sym
1431                                             : real_context->proc_name);
1432
1433       /* In some special cases, there may not be a proc_name, like for this
1434          invalid code:
1435          real(bad_kind()) function foo () ...
1436          when checking the call to bad_kind ().
1437          In these cases, we simply return here and assume that the
1438          call is ok.  */
1439       if (!context_proc)
1440         return false;
1441
1442       if (context_proc->attr.flavor != FL_LABEL)
1443         break;
1444     }
1445
1446   /* A call from sym's body to itself is recursion, of course.  */
1447   if (context_proc == proc_sym)
1448     return true;
1449
1450   /* The same is true if context is a contained procedure and sym the
1451      containing one.  */
1452   if (context_proc->attr.contained)
1453     {
1454       gfc_symbol* parent_proc;
1455
1456       gcc_assert (context->parent);
1457       parent_proc = (context->parent->entries ? context->parent->entries->sym
1458                                               : context->parent->proc_name);
1459
1460       if (parent_proc == proc_sym)
1461         return true;
1462     }
1463
1464   return false;
1465 }
1466
1467
1468 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1469    its typespec and formal argument list.  */
1470
1471 static gfc_try
1472 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1473 {
1474   gfc_intrinsic_sym* isym = NULL;
1475   const char* symstd;
1476
1477   if (sym->formal)
1478     return SUCCESS;
1479
1480   /* Already resolved.  */
1481   if (sym->from_intmod && sym->ts.type != BT_UNKNOWN)
1482     return SUCCESS;
1483
1484   /* We already know this one is an intrinsic, so we don't call
1485      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1486      gfc_find_subroutine directly to check whether it is a function or
1487      subroutine.  */
1488
1489   if (sym->intmod_sym_id)
1490     isym = gfc_intrinsic_function_by_id ((gfc_isym_id) sym->intmod_sym_id);
1491   else
1492     isym = gfc_find_function (sym->name);
1493
1494   if (isym)
1495     {
1496       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1497           && !sym->attr.implicit_type)
1498         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1499                       " ignored", sym->name, &sym->declared_at);
1500
1501       if (!sym->attr.function &&
1502           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1503         return FAILURE;
1504
1505       sym->ts = isym->ts;
1506     }
1507   else if ((isym = gfc_find_subroutine (sym->name)))
1508     {
1509       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1510         {
1511           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1512                       " specifier", sym->name, &sym->declared_at);
1513           return FAILURE;
1514         }
1515
1516       if (!sym->attr.subroutine &&
1517           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1518         return FAILURE;
1519     }
1520   else
1521     {
1522       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1523                  &sym->declared_at);
1524       return FAILURE;
1525     }
1526
1527   gfc_copy_formal_args_intr (sym, isym);
1528
1529   /* Check it is actually available in the standard settings.  */
1530   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1531       == FAILURE)
1532     {
1533       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1534                  " available in the current standard settings but %s.  Use"
1535                  " an appropriate -std=* option or enable -fall-intrinsics"
1536                  " in order to use it.",
1537                  sym->name, &sym->declared_at, symstd);
1538       return FAILURE;
1539     }
1540
1541   return SUCCESS;
1542 }
1543
1544
1545 /* Resolve a procedure expression, like passing it to a called procedure or as
1546    RHS for a procedure pointer assignment.  */
1547
1548 static gfc_try
1549 resolve_procedure_expression (gfc_expr* expr)
1550 {
1551   gfc_symbol* sym;
1552
1553   if (expr->expr_type != EXPR_VARIABLE)
1554     return SUCCESS;
1555   gcc_assert (expr->symtree);
1556
1557   sym = expr->symtree->n.sym;
1558
1559   if (sym->attr.intrinsic)
1560     resolve_intrinsic (sym, &expr->where);
1561
1562   if (sym->attr.flavor != FL_PROCEDURE
1563       || (sym->attr.function && sym->result == sym))
1564     return SUCCESS;
1565
1566   /* A non-RECURSIVE procedure that is used as procedure expression within its
1567      own body is in danger of being called recursively.  */
1568   if (is_illegal_recursion (sym, gfc_current_ns))
1569     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1570                  " itself recursively.  Declare it RECURSIVE or use"
1571                  " -frecursive", sym->name, &expr->where);
1572   
1573   return SUCCESS;
1574 }
1575
1576
1577 /* Resolve an actual argument list.  Most of the time, this is just
1578    resolving the expressions in the list.
1579    The exception is that we sometimes have to decide whether arguments
1580    that look like procedure arguments are really simple variable
1581    references.  */
1582
1583 static gfc_try
1584 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1585                         bool no_formal_args)
1586 {
1587   gfc_symbol *sym;
1588   gfc_symtree *parent_st;
1589   gfc_expr *e;
1590   int save_need_full_assumed_size;
1591
1592   for (; arg; arg = arg->next)
1593     {
1594       e = arg->expr;
1595       if (e == NULL)
1596         {
1597           /* Check the label is a valid branching target.  */
1598           if (arg->label)
1599             {
1600               if (arg->label->defined == ST_LABEL_UNKNOWN)
1601                 {
1602                   gfc_error ("Label %d referenced at %L is never defined",
1603                              arg->label->value, &arg->label->where);
1604                   return FAILURE;
1605                 }
1606             }
1607           continue;
1608         }
1609
1610       if (e->expr_type == EXPR_VARIABLE
1611             && e->symtree->n.sym->attr.generic
1612             && no_formal_args
1613             && count_specific_procs (e) != 1)
1614         return FAILURE;
1615
1616       if (e->ts.type != BT_PROCEDURE)
1617         {
1618           save_need_full_assumed_size = need_full_assumed_size;
1619           if (e->expr_type != EXPR_VARIABLE)
1620             need_full_assumed_size = 0;
1621           if (gfc_resolve_expr (e) != SUCCESS)
1622             return FAILURE;
1623           need_full_assumed_size = save_need_full_assumed_size;
1624           goto argument_list;
1625         }
1626
1627       /* See if the expression node should really be a variable reference.  */
1628
1629       sym = e->symtree->n.sym;
1630
1631       if (sym->attr.flavor == FL_PROCEDURE
1632           || sym->attr.intrinsic
1633           || sym->attr.external)
1634         {
1635           int actual_ok;
1636
1637           /* If a procedure is not already determined to be something else
1638              check if it is intrinsic.  */
1639           if (!sym->attr.intrinsic
1640               && !(sym->attr.external || sym->attr.use_assoc
1641                    || sym->attr.if_source == IFSRC_IFBODY)
1642               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1643             sym->attr.intrinsic = 1;
1644
1645           if (sym->attr.proc == PROC_ST_FUNCTION)
1646             {
1647               gfc_error ("Statement function '%s' at %L is not allowed as an "
1648                          "actual argument", sym->name, &e->where);
1649             }
1650
1651           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1652                                                sym->attr.subroutine);
1653           if (sym->attr.intrinsic && actual_ok == 0)
1654             {
1655               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1656                          "actual argument", sym->name, &e->where);
1657             }
1658
1659           if (sym->attr.contained && !sym->attr.use_assoc
1660               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1661             {
1662               if (gfc_notify_std (GFC_STD_F2008,
1663                                   "Fortran 2008: Internal procedure '%s' is"
1664                                   " used as actual argument at %L",
1665                                   sym->name, &e->where) == FAILURE)
1666                 return FAILURE;
1667             }
1668
1669           if (sym->attr.elemental && !sym->attr.intrinsic)
1670             {
1671               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1672                          "allowed as an actual argument at %L", sym->name,
1673                          &e->where);
1674             }
1675
1676           /* Check if a generic interface has a specific procedure
1677             with the same name before emitting an error.  */
1678           if (sym->attr.generic && count_specific_procs (e) != 1)
1679             return FAILURE;
1680           
1681           /* Just in case a specific was found for the expression.  */
1682           sym = e->symtree->n.sym;
1683
1684           /* If the symbol is the function that names the current (or
1685              parent) scope, then we really have a variable reference.  */
1686
1687           if (gfc_is_function_return_value (sym, sym->ns))
1688             goto got_variable;
1689
1690           /* If all else fails, see if we have a specific intrinsic.  */
1691           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1692             {
1693               gfc_intrinsic_sym *isym;
1694
1695               isym = gfc_find_function (sym->name);
1696               if (isym == NULL || !isym->specific)
1697                 {
1698                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1699                              "for the reference '%s' at %L", sym->name,
1700                              &e->where);
1701                   return FAILURE;
1702                 }
1703               sym->ts = isym->ts;
1704               sym->attr.intrinsic = 1;
1705               sym->attr.function = 1;
1706             }
1707
1708           if (gfc_resolve_expr (e) == FAILURE)
1709             return FAILURE;
1710           goto argument_list;
1711         }
1712
1713       /* See if the name is a module procedure in a parent unit.  */
1714
1715       if (was_declared (sym) || sym->ns->parent == NULL)
1716         goto got_variable;
1717
1718       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1719         {
1720           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1721           return FAILURE;
1722         }
1723
1724       if (parent_st == NULL)
1725         goto got_variable;
1726
1727       sym = parent_st->n.sym;
1728       e->symtree = parent_st;           /* Point to the right thing.  */
1729
1730       if (sym->attr.flavor == FL_PROCEDURE
1731           || sym->attr.intrinsic
1732           || sym->attr.external)
1733         {
1734           if (gfc_resolve_expr (e) == FAILURE)
1735             return FAILURE;
1736           goto argument_list;
1737         }
1738
1739     got_variable:
1740       e->expr_type = EXPR_VARIABLE;
1741       e->ts = sym->ts;
1742       if (sym->as != NULL)
1743         {
1744           e->rank = sym->as->rank;
1745           e->ref = gfc_get_ref ();
1746           e->ref->type = REF_ARRAY;
1747           e->ref->u.ar.type = AR_FULL;
1748           e->ref->u.ar.as = sym->as;
1749         }
1750
1751       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1752          primary.c (match_actual_arg). If above code determines that it
1753          is a  variable instead, it needs to be resolved as it was not
1754          done at the beginning of this function.  */
1755       save_need_full_assumed_size = need_full_assumed_size;
1756       if (e->expr_type != EXPR_VARIABLE)
1757         need_full_assumed_size = 0;
1758       if (gfc_resolve_expr (e) != SUCCESS)
1759         return FAILURE;
1760       need_full_assumed_size = save_need_full_assumed_size;
1761
1762     argument_list:
1763       /* Check argument list functions %VAL, %LOC and %REF.  There is
1764          nothing to do for %REF.  */
1765       if (arg->name && arg->name[0] == '%')
1766         {
1767           if (strncmp ("%VAL", arg->name, 4) == 0)
1768             {
1769               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1770                 {
1771                   gfc_error ("By-value argument at %L is not of numeric "
1772                              "type", &e->where);
1773                   return FAILURE;
1774                 }
1775
1776               if (e->rank)
1777                 {
1778                   gfc_error ("By-value argument at %L cannot be an array or "
1779                              "an array section", &e->where);
1780                 return FAILURE;
1781                 }
1782
1783               /* Intrinsics are still PROC_UNKNOWN here.  However,
1784                  since same file external procedures are not resolvable
1785                  in gfortran, it is a good deal easier to leave them to
1786                  intrinsic.c.  */
1787               if (ptype != PROC_UNKNOWN
1788                   && ptype != PROC_DUMMY
1789                   && ptype != PROC_EXTERNAL
1790                   && ptype != PROC_MODULE)
1791                 {
1792                   gfc_error ("By-value argument at %L is not allowed "
1793                              "in this context", &e->where);
1794                   return FAILURE;
1795                 }
1796             }
1797
1798           /* Statement functions have already been excluded above.  */
1799           else if (strncmp ("%LOC", arg->name, 4) == 0
1800                    && e->ts.type == BT_PROCEDURE)
1801             {
1802               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1803                 {
1804                   gfc_error ("Passing internal procedure at %L by location "
1805                              "not allowed", &e->where);
1806                   return FAILURE;
1807                 }
1808             }
1809         }
1810
1811       /* Fortran 2008, C1237.  */
1812       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1813           && gfc_has_ultimate_pointer (e))
1814         {
1815           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1816                      "component", &e->where);
1817           return FAILURE;
1818         }
1819     }
1820
1821   return SUCCESS;
1822 }
1823
1824
1825 /* Do the checks of the actual argument list that are specific to elemental
1826    procedures.  If called with c == NULL, we have a function, otherwise if
1827    expr == NULL, we have a subroutine.  */
1828
1829 static gfc_try
1830 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1831 {
1832   gfc_actual_arglist *arg0;
1833   gfc_actual_arglist *arg;
1834   gfc_symbol *esym = NULL;
1835   gfc_intrinsic_sym *isym = NULL;
1836   gfc_expr *e = NULL;
1837   gfc_intrinsic_arg *iformal = NULL;
1838   gfc_formal_arglist *eformal = NULL;
1839   bool formal_optional = false;
1840   bool set_by_optional = false;
1841   int i;
1842   int rank = 0;
1843
1844   /* Is this an elemental procedure?  */
1845   if (expr && expr->value.function.actual != NULL)
1846     {
1847       if (expr->value.function.esym != NULL
1848           && expr->value.function.esym->attr.elemental)
1849         {
1850           arg0 = expr->value.function.actual;
1851           esym = expr->value.function.esym;
1852         }
1853       else if (expr->value.function.isym != NULL
1854                && expr->value.function.isym->elemental)
1855         {
1856           arg0 = expr->value.function.actual;
1857           isym = expr->value.function.isym;
1858         }
1859       else
1860         return SUCCESS;
1861     }
1862   else if (c && c->ext.actual != NULL)
1863     {
1864       arg0 = c->ext.actual;
1865       
1866       if (c->resolved_sym)
1867         esym = c->resolved_sym;
1868       else
1869         esym = c->symtree->n.sym;
1870       gcc_assert (esym);
1871
1872       if (!esym->attr.elemental)
1873         return SUCCESS;
1874     }
1875   else
1876     return SUCCESS;
1877
1878   /* The rank of an elemental is the rank of its array argument(s).  */
1879   for (arg = arg0; arg; arg = arg->next)
1880     {
1881       if (arg->expr != NULL && arg->expr->rank > 0)
1882         {
1883           rank = arg->expr->rank;
1884           if (arg->expr->expr_type == EXPR_VARIABLE
1885               && arg->expr->symtree->n.sym->attr.optional)
1886             set_by_optional = true;
1887
1888           /* Function specific; set the result rank and shape.  */
1889           if (expr)
1890             {
1891               expr->rank = rank;
1892               if (!expr->shape && arg->expr->shape)
1893                 {
1894                   expr->shape = gfc_get_shape (rank);
1895                   for (i = 0; i < rank; i++)
1896                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1897                 }
1898             }
1899           break;
1900         }
1901     }
1902
1903   /* If it is an array, it shall not be supplied as an actual argument
1904      to an elemental procedure unless an array of the same rank is supplied
1905      as an actual argument corresponding to a nonoptional dummy argument of
1906      that elemental procedure(12.4.1.5).  */
1907   formal_optional = false;
1908   if (isym)
1909     iformal = isym->formal;
1910   else
1911     eformal = esym->formal;
1912
1913   for (arg = arg0; arg; arg = arg->next)
1914     {
1915       if (eformal)
1916         {
1917           if (eformal->sym && eformal->sym->attr.optional)
1918             formal_optional = true;
1919           eformal = eformal->next;
1920         }
1921       else if (isym && iformal)
1922         {
1923           if (iformal->optional)
1924             formal_optional = true;
1925           iformal = iformal->next;
1926         }
1927       else if (isym)
1928         formal_optional = true;
1929
1930       if (pedantic && arg->expr != NULL
1931           && arg->expr->expr_type == EXPR_VARIABLE
1932           && arg->expr->symtree->n.sym->attr.optional
1933           && formal_optional
1934           && arg->expr->rank
1935           && (set_by_optional || arg->expr->rank != rank)
1936           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1937         {
1938           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1939                        "MISSING, it cannot be the actual argument of an "
1940                        "ELEMENTAL procedure unless there is a non-optional "
1941                        "argument with the same rank (12.4.1.5)",
1942                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1943           return FAILURE;
1944         }
1945     }
1946
1947   for (arg = arg0; arg; arg = arg->next)
1948     {
1949       if (arg->expr == NULL || arg->expr->rank == 0)
1950         continue;
1951
1952       /* Being elemental, the last upper bound of an assumed size array
1953          argument must be present.  */
1954       if (resolve_assumed_size_actual (arg->expr))
1955         return FAILURE;
1956
1957       /* Elemental procedure's array actual arguments must conform.  */
1958       if (e != NULL)
1959         {
1960           if (gfc_check_conformance (arg->expr, e,
1961                                      "elemental procedure") == FAILURE)
1962             return FAILURE;
1963         }
1964       else
1965         e = arg->expr;
1966     }
1967
1968   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1969      is an array, the intent inout/out variable needs to be also an array.  */
1970   if (rank > 0 && esym && expr == NULL)
1971     for (eformal = esym->formal, arg = arg0; arg && eformal;
1972          arg = arg->next, eformal = eformal->next)
1973       if ((eformal->sym->attr.intent == INTENT_OUT
1974            || eformal->sym->attr.intent == INTENT_INOUT)
1975           && arg->expr && arg->expr->rank == 0)
1976         {
1977           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1978                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1979                      "actual argument is an array", &arg->expr->where,
1980                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1981                      : "INOUT", eformal->sym->name, esym->name);
1982           return FAILURE;
1983         }
1984   return SUCCESS;
1985 }
1986
1987
1988 /* This function does the checking of references to global procedures
1989    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1990    77 and 95 standards.  It checks for a gsymbol for the name, making
1991    one if it does not already exist.  If it already exists, then the
1992    reference being resolved must correspond to the type of gsymbol.
1993    Otherwise, the new symbol is equipped with the attributes of the
1994    reference.  The corresponding code that is called in creating
1995    global entities is parse.c.
1996
1997    In addition, for all but -std=legacy, the gsymbols are used to
1998    check the interfaces of external procedures from the same file.
1999    The namespace of the gsymbol is resolved and then, once this is
2000    done the interface is checked.  */
2001
2002
2003 static bool
2004 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
2005 {
2006   if (!gsym_ns->proc_name->attr.recursive)
2007     return true;
2008
2009   if (sym->ns == gsym_ns)
2010     return false;
2011
2012   if (sym->ns->parent && sym->ns->parent == gsym_ns)
2013     return false;
2014
2015   return true;
2016 }
2017
2018 static bool
2019 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
2020 {
2021   if (gsym_ns->entries)
2022     {
2023       gfc_entry_list *entry = gsym_ns->entries;
2024
2025       for (; entry; entry = entry->next)
2026         {
2027           if (strcmp (sym->name, entry->sym->name) == 0)
2028             {
2029               if (strcmp (gsym_ns->proc_name->name,
2030                           sym->ns->proc_name->name) == 0)
2031                 return false;
2032
2033               if (sym->ns->parent
2034                   && strcmp (gsym_ns->proc_name->name,
2035                              sym->ns->parent->proc_name->name) == 0)
2036                 return false;
2037             }
2038         }
2039     }
2040   return true;
2041 }
2042
2043 static void
2044 resolve_global_procedure (gfc_symbol *sym, locus *where,
2045                           gfc_actual_arglist **actual, int sub)
2046 {
2047   gfc_gsymbol * gsym;
2048   gfc_namespace *ns;
2049   enum gfc_symbol_type type;
2050
2051   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
2052
2053   gsym = gfc_get_gsymbol (sym->name);
2054
2055   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2056     gfc_global_used (gsym, where);
2057
2058   if (gfc_option.flag_whole_file
2059         && (sym->attr.if_source == IFSRC_UNKNOWN
2060             || sym->attr.if_source == IFSRC_IFBODY)
2061         && gsym->type != GSYM_UNKNOWN
2062         && gsym->ns
2063         && gsym->ns->resolved != -1
2064         && gsym->ns->proc_name
2065         && not_in_recursive (sym, gsym->ns)
2066         && not_entry_self_reference (sym, gsym->ns))
2067     {
2068       gfc_symbol *def_sym;
2069
2070       /* Resolve the gsymbol namespace if needed.  */
2071       if (!gsym->ns->resolved)
2072         {
2073           gfc_dt_list *old_dt_list;
2074           struct gfc_omp_saved_state old_omp_state;
2075
2076           /* Stash away derived types so that the backend_decls do not
2077              get mixed up.  */
2078           old_dt_list = gfc_derived_types;
2079           gfc_derived_types = NULL;
2080           /* And stash away openmp state.  */
2081           gfc_omp_save_and_clear_state (&old_omp_state);
2082
2083           gfc_resolve (gsym->ns);
2084
2085           /* Store the new derived types with the global namespace.  */
2086           if (gfc_derived_types)
2087             gsym->ns->derived_types = gfc_derived_types;
2088
2089           /* Restore the derived types of this namespace.  */
2090           gfc_derived_types = old_dt_list;
2091           /* And openmp state.  */
2092           gfc_omp_restore_state (&old_omp_state);
2093         }
2094
2095       /* Make sure that translation for the gsymbol occurs before
2096          the procedure currently being resolved.  */
2097       ns = gfc_global_ns_list;
2098       for (; ns && ns != gsym->ns; ns = ns->sibling)
2099         {
2100           if (ns->sibling == gsym->ns)
2101             {
2102               ns->sibling = gsym->ns->sibling;
2103               gsym->ns->sibling = gfc_global_ns_list;
2104               gfc_global_ns_list = gsym->ns;
2105               break;
2106             }
2107         }
2108
2109       def_sym = gsym->ns->proc_name;
2110       if (def_sym->attr.entry_master)
2111         {
2112           gfc_entry_list *entry;
2113           for (entry = gsym->ns->entries; entry; entry = entry->next)
2114             if (strcmp (entry->sym->name, sym->name) == 0)
2115               {
2116                 def_sym = entry->sym;
2117                 break;
2118               }
2119         }
2120
2121       /* Differences in constant character lengths.  */
2122       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2123         {
2124           long int l1 = 0, l2 = 0;
2125           gfc_charlen *cl1 = sym->ts.u.cl;
2126           gfc_charlen *cl2 = def_sym->ts.u.cl;
2127
2128           if (cl1 != NULL
2129               && cl1->length != NULL
2130               && cl1->length->expr_type == EXPR_CONSTANT)
2131             l1 = mpz_get_si (cl1->length->value.integer);
2132
2133           if (cl2 != NULL
2134               && cl2->length != NULL
2135               && cl2->length->expr_type == EXPR_CONSTANT)
2136             l2 = mpz_get_si (cl2->length->value.integer);
2137
2138           if (l1 && l2 && l1 != l2)
2139             gfc_error ("Character length mismatch in return type of "
2140                        "function '%s' at %L (%ld/%ld)", sym->name,
2141                        &sym->declared_at, l1, l2);
2142         }
2143
2144      /* Type mismatch of function return type and expected type.  */
2145      if (sym->attr.function
2146          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2147         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2148                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2149                    gfc_typename (&def_sym->ts));
2150
2151       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2152         {
2153           gfc_formal_arglist *arg = def_sym->formal;
2154           for ( ; arg; arg = arg->next)
2155             if (!arg->sym)
2156               continue;
2157             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2158             else if (arg->sym->attr.allocatable
2159                      || arg->sym->attr.asynchronous
2160                      || arg->sym->attr.optional
2161                      || arg->sym->attr.pointer
2162                      || arg->sym->attr.target
2163                      || arg->sym->attr.value
2164                      || arg->sym->attr.volatile_)
2165               {
2166                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2167                            "has an attribute that requires an explicit "
2168                            "interface for this procedure", arg->sym->name,
2169                            sym->name, &sym->declared_at);
2170                 break;
2171               }
2172             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2173             else if (arg->sym && arg->sym->as
2174                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2175               {
2176                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2177                            "argument '%s' must have an explicit interface",
2178                            sym->name, &sym->declared_at, arg->sym->name);
2179                 break;
2180               }
2181             /* F2008, 12.4.2.2 (2c)  */
2182             else if (arg->sym->attr.codimension)
2183               {
2184                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2185                            "'%s' must have an explicit interface",
2186                            sym->name, &sym->declared_at, arg->sym->name);
2187                 break;
2188               }
2189             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2190             else if (false) /* TODO: is a parametrized derived type  */
2191               {
2192                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2193                            "type argument '%s' must have an explicit "
2194                            "interface", sym->name, &sym->declared_at,
2195                            arg->sym->name);
2196                 break;
2197               }
2198             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2199             else if (arg->sym->ts.type == BT_CLASS)
2200               {
2201                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2202                            "argument '%s' must have an explicit interface",
2203                            sym->name, &sym->declared_at, arg->sym->name);
2204                 break;
2205               }
2206         }
2207
2208       if (def_sym->attr.function)
2209         {
2210           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2211           if (def_sym->as && def_sym->as->rank
2212               && (!sym->as || sym->as->rank != def_sym->as->rank))
2213             gfc_error ("The reference to function '%s' at %L either needs an "
2214                        "explicit INTERFACE or the rank is incorrect", sym->name,
2215                        where);
2216
2217           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2218           if ((def_sym->result->attr.pointer
2219                || def_sym->result->attr.allocatable)
2220                && (sym->attr.if_source != IFSRC_IFBODY
2221                    || def_sym->result->attr.pointer
2222                         != sym->result->attr.pointer
2223                    || def_sym->result->attr.allocatable
2224                         != sym->result->attr.allocatable))
2225             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2226                        "result must have an explicit interface", sym->name,
2227                        where);
2228
2229           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2230           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2231               && def_sym->ts.type == BT_CHARACTER && def_sym->ts.u.cl->length != NULL)
2232             {
2233               gfc_charlen *cl = sym->ts.u.cl;
2234
2235               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2236                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2237                 {
2238                   gfc_error ("Nonconstant character-length function '%s' at %L "
2239                              "must have an explicit interface", sym->name,
2240                              &sym->declared_at);
2241                 }
2242             }
2243         }
2244
2245       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2246       if (def_sym->attr.elemental && !sym->attr.elemental)
2247         {
2248           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2249                      "interface", sym->name, &sym->declared_at);
2250         }
2251
2252       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2253       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2254         {
2255           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2256                      "an explicit interface", sym->name, &sym->declared_at);
2257         }
2258
2259       if (gfc_option.flag_whole_file == 1
2260           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2261               && !(gfc_option.warn_std & GFC_STD_GNU)))
2262         gfc_errors_to_warnings (1);
2263
2264       if (sym->attr.if_source != IFSRC_IFBODY)  
2265         gfc_procedure_use (def_sym, actual, where);
2266
2267       gfc_errors_to_warnings (0);
2268     }
2269
2270   if (gsym->type == GSYM_UNKNOWN)
2271     {
2272       gsym->type = type;
2273       gsym->where = *where;
2274     }
2275
2276   gsym->used = 1;
2277 }
2278
2279
2280 /************* Function resolution *************/
2281
2282 /* Resolve a function call known to be generic.
2283    Section 14.1.2.4.1.  */
2284
2285 static match
2286 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2287 {
2288   gfc_symbol *s;
2289
2290   if (sym->attr.generic)
2291     {
2292       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2293       if (s != NULL)
2294         {
2295           expr->value.function.name = s->name;
2296           expr->value.function.esym = s;
2297
2298           if (s->ts.type != BT_UNKNOWN)
2299             expr->ts = s->ts;
2300           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2301             expr->ts = s->result->ts;
2302
2303           if (s->as != NULL)
2304             expr->rank = s->as->rank;
2305           else if (s->result != NULL && s->result->as != NULL)
2306             expr->rank = s->result->as->rank;
2307
2308           gfc_set_sym_referenced (expr->value.function.esym);
2309
2310           return MATCH_YES;
2311         }
2312
2313       /* TODO: Need to search for elemental references in generic
2314          interface.  */
2315     }
2316
2317   if (sym->attr.intrinsic)
2318     return gfc_intrinsic_func_interface (expr, 0);
2319
2320   return MATCH_NO;
2321 }
2322
2323
2324 static gfc_try
2325 resolve_generic_f (gfc_expr *expr)
2326 {
2327   gfc_symbol *sym;
2328   match m;
2329   gfc_interface *intr = NULL;
2330
2331   sym = expr->symtree->n.sym;
2332
2333   for (;;)
2334     {
2335       m = resolve_generic_f0 (expr, sym);
2336       if (m == MATCH_YES)
2337         return SUCCESS;
2338       else if (m == MATCH_ERROR)
2339         return FAILURE;
2340
2341 generic:
2342       if (!intr)
2343         for (intr = sym->generic; intr; intr = intr->next)
2344           if (intr->sym->attr.flavor == FL_DERIVED)
2345             break;
2346
2347       if (sym->ns->parent == NULL)
2348         break;
2349       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2350
2351       if (sym == NULL)
2352         break;
2353       if (!generic_sym (sym))
2354         goto generic;
2355     }
2356
2357   /* Last ditch attempt.  See if the reference is to an intrinsic
2358      that possesses a matching interface.  14.1.2.4  */
2359   if (sym  && !intr && !gfc_is_intrinsic (sym, 0, expr->where))
2360     {
2361       gfc_error ("There is no specific function for the generic '%s' "
2362                  "at %L", expr->symtree->n.sym->name, &expr->where);
2363       return FAILURE;
2364     }
2365
2366   if (intr)
2367     {
2368       if (gfc_convert_to_structure_constructor (expr, intr->sym, NULL, NULL,
2369                                                 false) != SUCCESS)
2370         return FAILURE;
2371       return resolve_structure_cons (expr, 0);
2372     }
2373
2374   m = gfc_intrinsic_func_interface (expr, 0);
2375   if (m == MATCH_YES)
2376     return SUCCESS;
2377
2378   if (m == MATCH_NO)
2379     gfc_error ("Generic function '%s' at %L is not consistent with a "
2380                "specific intrinsic interface", expr->symtree->n.sym->name,
2381                &expr->where);
2382
2383   return FAILURE;
2384 }
2385
2386
2387 /* Resolve a function call known to be specific.  */
2388
2389 static match
2390 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2391 {
2392   match m;
2393
2394   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2395     {
2396       if (sym->attr.dummy)
2397         {
2398           sym->attr.proc = PROC_DUMMY;
2399           goto found;
2400         }
2401
2402       sym->attr.proc = PROC_EXTERNAL;
2403       goto found;
2404     }
2405
2406   if (sym->attr.proc == PROC_MODULE
2407       || sym->attr.proc == PROC_ST_FUNCTION
2408       || sym->attr.proc == PROC_INTERNAL)
2409     goto found;
2410
2411   if (sym->attr.intrinsic)
2412     {
2413       m = gfc_intrinsic_func_interface (expr, 1);
2414       if (m == MATCH_YES)
2415         return MATCH_YES;
2416       if (m == MATCH_NO)
2417         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2418                    "with an intrinsic", sym->name, &expr->where);
2419
2420       return MATCH_ERROR;
2421     }
2422
2423   return MATCH_NO;
2424
2425 found:
2426   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2427
2428   if (sym->result)
2429     expr->ts = sym->result->ts;
2430   else
2431     expr->ts = sym->ts;
2432   expr->value.function.name = sym->name;
2433   expr->value.function.esym = sym;
2434   if (sym->as != NULL)
2435     expr->rank = sym->as->rank;
2436
2437   return MATCH_YES;
2438 }
2439
2440
2441 static gfc_try
2442 resolve_specific_f (gfc_expr *expr)
2443 {
2444   gfc_symbol *sym;
2445   match m;
2446
2447   sym = expr->symtree->n.sym;
2448
2449   for (;;)
2450     {
2451       m = resolve_specific_f0 (sym, expr);
2452       if (m == MATCH_YES)
2453         return SUCCESS;
2454       if (m == MATCH_ERROR)
2455         return FAILURE;
2456
2457       if (sym->ns->parent == NULL)
2458         break;
2459
2460       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2461
2462       if (sym == NULL)
2463         break;
2464     }
2465
2466   gfc_error ("Unable to resolve the specific function '%s' at %L",
2467              expr->symtree->n.sym->name, &expr->where);
2468
2469   return SUCCESS;
2470 }
2471
2472
2473 /* Resolve a procedure call not known to be generic nor specific.  */
2474
2475 static gfc_try
2476 resolve_unknown_f (gfc_expr *expr)
2477 {
2478   gfc_symbol *sym;
2479   gfc_typespec *ts;
2480
2481   sym = expr->symtree->n.sym;
2482
2483   if (sym->attr.dummy)
2484     {
2485       sym->attr.proc = PROC_DUMMY;
2486       expr->value.function.name = sym->name;
2487       goto set_type;
2488     }
2489
2490   /* See if we have an intrinsic function reference.  */
2491
2492   if (gfc_is_intrinsic (sym, 0, expr->where))
2493     {
2494       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2495         return SUCCESS;
2496       return FAILURE;
2497     }
2498
2499   /* The reference is to an external name.  */
2500
2501   sym->attr.proc = PROC_EXTERNAL;
2502   expr->value.function.name = sym->name;
2503   expr->value.function.esym = expr->symtree->n.sym;
2504
2505   if (sym->as != NULL)
2506     expr->rank = sym->as->rank;
2507
2508   /* Type of the expression is either the type of the symbol or the
2509      default type of the symbol.  */
2510
2511 set_type:
2512   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2513
2514   if (sym->ts.type != BT_UNKNOWN)
2515     expr->ts = sym->ts;
2516   else
2517     {
2518       ts = gfc_get_default_type (sym->name, sym->ns);
2519
2520       if (ts->type == BT_UNKNOWN)
2521         {
2522           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2523                      sym->name, &expr->where);
2524           return FAILURE;
2525         }
2526       else
2527         expr->ts = *ts;
2528     }
2529
2530   return SUCCESS;
2531 }
2532
2533
2534 /* Return true, if the symbol is an external procedure.  */
2535 static bool
2536 is_external_proc (gfc_symbol *sym)
2537 {
2538   if (!sym->attr.dummy && !sym->attr.contained
2539         && !(sym->attr.intrinsic
2540               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2541         && sym->attr.proc != PROC_ST_FUNCTION
2542         && !sym->attr.proc_pointer
2543         && !sym->attr.use_assoc
2544         && sym->name)
2545     return true;
2546
2547   return false;
2548 }
2549
2550
2551 /* Figure out if a function reference is pure or not.  Also set the name
2552    of the function for a potential error message.  Return nonzero if the
2553    function is PURE, zero if not.  */
2554 static int
2555 pure_stmt_function (gfc_expr *, gfc_symbol *);
2556
2557 static int
2558 pure_function (gfc_expr *e, const char **name)
2559 {
2560   int pure;
2561
2562   *name = NULL;
2563
2564   if (e->symtree != NULL
2565         && e->symtree->n.sym != NULL
2566         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2567     return pure_stmt_function (e, e->symtree->n.sym);
2568
2569   if (e->value.function.esym)
2570     {
2571       pure = gfc_pure (e->value.function.esym);
2572       *name = e->value.function.esym->name;
2573     }
2574   else if (e->value.function.isym)
2575     {
2576       pure = e->value.function.isym->pure
2577              || e->value.function.isym->elemental;
2578       *name = e->value.function.isym->name;
2579     }
2580   else
2581     {
2582       /* Implicit functions are not pure.  */
2583       pure = 0;
2584       *name = e->value.function.name;
2585     }
2586
2587   return pure;
2588 }
2589
2590
2591 static bool
2592 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2593                  int *f ATTRIBUTE_UNUSED)
2594 {
2595   const char *name;
2596
2597   /* Don't bother recursing into other statement functions
2598      since they will be checked individually for purity.  */
2599   if (e->expr_type != EXPR_FUNCTION
2600         || !e->symtree
2601         || e->symtree->n.sym == sym
2602         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2603     return false;
2604
2605   return pure_function (e, &name) ? false : true;
2606 }
2607
2608
2609 static int
2610 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2611 {
2612   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2613 }
2614
2615
2616 static gfc_try
2617 is_scalar_expr_ptr (gfc_expr *expr)
2618 {
2619   gfc_try retval = SUCCESS;
2620   gfc_ref *ref;
2621   int start;
2622   int end;
2623
2624   /* See if we have a gfc_ref, which means we have a substring, array
2625      reference, or a component.  */
2626   if (expr->ref != NULL)
2627     {
2628       ref = expr->ref;
2629       while (ref->next != NULL)
2630         ref = ref->next;
2631
2632       switch (ref->type)
2633         {
2634         case REF_SUBSTRING:
2635           if (ref->u.ss.start == NULL || ref->u.ss.end == NULL
2636               || gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) != 0)
2637             retval = FAILURE;
2638           break;
2639
2640         case REF_ARRAY:
2641           if (ref->u.ar.type == AR_ELEMENT)
2642             retval = SUCCESS;
2643           else if (ref->u.ar.type == AR_FULL)
2644             {
2645               /* The user can give a full array if the array is of size 1.  */
2646               if (ref->u.ar.as != NULL
2647                   && ref->u.ar.as->rank == 1
2648                   && ref->u.ar.as->type == AS_EXPLICIT
2649                   && ref->u.ar.as->lower[0] != NULL
2650                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2651                   && ref->u.ar.as->upper[0] != NULL
2652                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2653                 {
2654                   /* If we have a character string, we need to check if
2655                      its length is one.  */
2656                   if (expr->ts.type == BT_CHARACTER)
2657                     {
2658                       if (expr->ts.u.cl == NULL
2659                           || expr->ts.u.cl->length == NULL
2660                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2661                           != 0)
2662                         retval = FAILURE;
2663                     }
2664                   else
2665                     {
2666                       /* We have constant lower and upper bounds.  If the
2667                          difference between is 1, it can be considered a
2668                          scalar.  
2669                          FIXME: Use gfc_dep_compare_expr instead.  */
2670                       start = (int) mpz_get_si
2671                                 (ref->u.ar.as->lower[0]->value.integer);
2672                       end = (int) mpz_get_si
2673                                 (ref->u.ar.as->upper[0]->value.integer);
2674                       if (end - start + 1 != 1)
2675                         retval = FAILURE;
2676                    }
2677                 }
2678               else
2679                 retval = FAILURE;
2680             }
2681           else
2682             retval = FAILURE;
2683           break;
2684         default:
2685           retval = SUCCESS;
2686           break;
2687         }
2688     }
2689   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2690     {
2691       /* Character string.  Make sure it's of length 1.  */
2692       if (expr->ts.u.cl == NULL
2693           || expr->ts.u.cl->length == NULL
2694           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2695         retval = FAILURE;
2696     }
2697   else if (expr->rank != 0)
2698     retval = FAILURE;
2699
2700   return retval;
2701 }
2702
2703
2704 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2705    and, in the case of c_associated, set the binding label based on
2706    the arguments.  */
2707
2708 static gfc_try
2709 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2710                           gfc_symbol **new_sym)
2711 {
2712   char name[GFC_MAX_SYMBOL_LEN + 1];
2713   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2714   int optional_arg = 0;
2715   gfc_try retval = SUCCESS;
2716   gfc_symbol *args_sym;
2717   gfc_typespec *arg_ts;
2718   symbol_attribute arg_attr;
2719
2720   if (args->expr->expr_type == EXPR_CONSTANT
2721       || args->expr->expr_type == EXPR_OP
2722       || args->expr->expr_type == EXPR_NULL)
2723     {
2724       gfc_error ("Argument to '%s' at %L is not a variable",
2725                  sym->name, &(args->expr->where));
2726       return FAILURE;
2727     }
2728
2729   args_sym = args->expr->symtree->n.sym;
2730
2731   /* The typespec for the actual arg should be that stored in the expr
2732      and not necessarily that of the expr symbol (args_sym), because
2733      the actual expression could be a part-ref of the expr symbol.  */
2734   arg_ts = &(args->expr->ts);
2735   arg_attr = gfc_expr_attr (args->expr);
2736     
2737   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2738     {
2739       /* If the user gave two args then they are providing something for
2740          the optional arg (the second cptr).  Therefore, set the name and
2741          binding label to the c_associated for two cptrs.  Otherwise,
2742          set c_associated to expect one cptr.  */
2743       if (args->next)
2744         {
2745           /* two args.  */
2746           sprintf (name, "%s_2", sym->name);
2747           sprintf (binding_label, "%s_2", sym->binding_label);
2748           optional_arg = 1;
2749         }
2750       else
2751         {
2752           /* one arg.  */
2753           sprintf (name, "%s_1", sym->name);
2754           sprintf (binding_label, "%s_1", sym->binding_label);
2755           optional_arg = 0;
2756         }
2757
2758       /* Get a new symbol for the version of c_associated that
2759          will get called.  */
2760       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2761     }
2762   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2763            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2764     {
2765       sprintf (name, "%s", sym->name);
2766       sprintf (binding_label, "%s", sym->binding_label);
2767
2768       /* Error check the call.  */
2769       if (args->next != NULL)
2770         {
2771           gfc_error_now ("More actual than formal arguments in '%s' "
2772                          "call at %L", name, &(args->expr->where));
2773           retval = FAILURE;
2774         }
2775       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2776         {
2777           gfc_ref *ref;
2778           bool seen_section;
2779
2780           /* Make sure we have either the target or pointer attribute.  */
2781           if (!arg_attr.target && !arg_attr.pointer)
2782             {
2783               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2784                              "a TARGET or an associated pointer",
2785                              args_sym->name,
2786                              sym->name, &(args->expr->where));
2787               retval = FAILURE;
2788             }
2789
2790           if (gfc_is_coindexed (args->expr))
2791             {
2792               gfc_error_now ("Coindexed argument not permitted"
2793                              " in '%s' call at %L", name,
2794                              &(args->expr->where));
2795               retval = FAILURE;
2796             }
2797
2798           /* Follow references to make sure there are no array
2799              sections.  */
2800           seen_section = false;
2801
2802           for (ref=args->expr->ref; ref; ref = ref->next)
2803             {
2804               if (ref->type == REF_ARRAY)
2805                 {
2806                   if (ref->u.ar.type == AR_SECTION)
2807                     seen_section = true;
2808
2809                   if (ref->u.ar.type != AR_ELEMENT)
2810                     {
2811                       gfc_ref *r;
2812                       for (r = ref->next; r; r=r->next)
2813                         if (r->type == REF_COMPONENT)
2814                           {
2815                             gfc_error_now ("Array section not permitted"
2816                                            " in '%s' call at %L", name,
2817                                            &(args->expr->where));
2818                             retval = FAILURE;
2819                             break;
2820                           }
2821                     }
2822                 }
2823             }
2824
2825           if (seen_section && retval == SUCCESS)
2826             gfc_warning ("Array section in '%s' call at %L", name,
2827                          &(args->expr->where));
2828                          
2829           /* See if we have interoperable type and type param.  */
2830           if (gfc_verify_c_interop (arg_ts) == SUCCESS
2831               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2832             {
2833               if (args_sym->attr.target == 1)
2834                 {
2835                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2836                      has the target attribute and is interoperable.  */
2837                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2838                      allocatable variable that has the TARGET attribute and
2839                      is not an array of zero size.  */
2840                   if (args_sym->attr.allocatable == 1)
2841                     {
2842                       if (args_sym->attr.dimension != 0 
2843                           && (args_sym->as && args_sym->as->rank == 0))
2844                         {
2845                           gfc_error_now ("Allocatable variable '%s' used as a "
2846                                          "parameter to '%s' at %L must not be "
2847                                          "an array of zero size",
2848                                          args_sym->name, sym->name,
2849                                          &(args->expr->where));
2850                           retval = FAILURE;
2851                         }
2852                     }
2853                   else
2854                     {
2855                       /* A non-allocatable target variable with C
2856                          interoperable type and type parameters must be
2857                          interoperable.  */
2858                       if (args_sym && args_sym->attr.dimension)
2859                         {
2860                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2861                             {
2862                               gfc_error ("Assumed-shape array '%s' at %L "
2863                                          "cannot be an argument to the "
2864                                          "procedure '%s' because "
2865                                          "it is not C interoperable",
2866                                          args_sym->name,
2867                                          &(args->expr->where), sym->name);
2868                               retval = FAILURE;
2869                             }
2870                           else if (args_sym->as->type == AS_DEFERRED)
2871                             {
2872                               gfc_error ("Deferred-shape array '%s' at %L "
2873                                          "cannot be an argument to the "
2874                                          "procedure '%s' because "
2875                                          "it is not C interoperable",
2876                                          args_sym->name,
2877                                          &(args->expr->where), sym->name);
2878                               retval = FAILURE;
2879                             }
2880                         }
2881                               
2882                       /* Make sure it's not a character string.  Arrays of
2883                          any type should be ok if the variable is of a C
2884                          interoperable type.  */
2885                       if (arg_ts->type == BT_CHARACTER)
2886                         if (arg_ts->u.cl != NULL
2887                             && (arg_ts->u.cl->length == NULL
2888                                 || arg_ts->u.cl->length->expr_type
2889                                    != EXPR_CONSTANT
2890                                 || mpz_cmp_si
2891                                     (arg_ts->u.cl->length->value.integer, 1)
2892                                    != 0)
2893                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2894                           {
2895                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2896                                            "at %L must have a length of 1",
2897                                            args_sym->name, sym->name,
2898                                            &(args->expr->where));
2899                             retval = FAILURE;
2900                           }
2901                     }
2902                 }
2903               else if (arg_attr.pointer
2904                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2905                 {
2906                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2907                      scalar pointer.  */
2908                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2909                                  "associated scalar POINTER", args_sym->name,
2910                                  sym->name, &(args->expr->where));
2911                   retval = FAILURE;
2912                 }
2913             }
2914           else
2915             {
2916               /* The parameter is not required to be C interoperable.  If it
2917                  is not C interoperable, it must be a nonpolymorphic scalar
2918                  with no length type parameters.  It still must have either
2919                  the pointer or target attribute, and it can be
2920                  allocatable (but must be allocated when c_loc is called).  */
2921               if (args->expr->rank != 0 
2922                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2923                 {
2924                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2925                                  "scalar", args_sym->name, sym->name,
2926                                  &(args->expr->where));
2927                   retval = FAILURE;
2928                 }
2929               else if (arg_ts->type == BT_CHARACTER 
2930                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2931                 {
2932                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2933                                  "%L must have a length of 1",
2934                                  args_sym->name, sym->name,
2935                                  &(args->expr->where));
2936                   retval = FAILURE;
2937                 }
2938               else if (arg_ts->type == BT_CLASS)
2939                 {
2940                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2941                                  "polymorphic", args_sym->name, sym->name,
2942                                  &(args->expr->where));
2943                   retval = FAILURE;
2944                 }
2945             }
2946         }
2947       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2948         {
2949           if (args_sym->attr.flavor != FL_PROCEDURE)
2950             {
2951               /* TODO: Update this error message to allow for procedure
2952                  pointers once they are implemented.  */
2953               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2954                              "procedure",
2955                              args_sym->name, sym->name,
2956                              &(args->expr->where));
2957               retval = FAILURE;
2958             }
2959           else if (args_sym->attr.is_bind_c != 1)
2960             {
2961               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2962                              "BIND(C)",
2963                              args_sym->name, sym->name,
2964                              &(args->expr->where));
2965               retval = FAILURE;
2966             }
2967         }
2968       
2969       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2970       *new_sym = sym;
2971     }
2972   else
2973     {
2974       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2975                           "iso_c_binding function: '%s'!\n", sym->name);
2976     }
2977
2978   return retval;
2979 }
2980
2981
2982 /* Resolve a function call, which means resolving the arguments, then figuring
2983    out which entity the name refers to.  */
2984
2985 static gfc_try
2986 resolve_function (gfc_expr *expr)
2987 {
2988   gfc_actual_arglist *arg;
2989   gfc_symbol *sym;
2990   const char *name;
2991   gfc_try t;
2992   int temp;
2993   procedure_type p = PROC_INTRINSIC;
2994   bool no_formal_args;
2995
2996   sym = NULL;
2997   if (expr->symtree)
2998     sym = expr->symtree->n.sym;
2999
3000   /* If this is a procedure pointer component, it has already been resolved.  */
3001   if (gfc_is_proc_ptr_comp (expr, NULL))
3002     return SUCCESS;
3003   
3004   if (sym && sym->attr.intrinsic
3005       && resolve_intrinsic (sym, &expr->where) == FAILURE)
3006     return FAILURE;
3007
3008   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
3009     {
3010       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
3011       return FAILURE;
3012     }
3013
3014   /* If this ia a deferred TBP with an abstract interface (which may
3015      of course be referenced), expr->value.function.esym will be set.  */
3016   if (sym && sym->attr.abstract && !expr->value.function.esym)
3017     {
3018       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3019                  sym->name, &expr->where);
3020       return FAILURE;
3021     }
3022
3023   /* Switch off assumed size checking and do this again for certain kinds
3024      of procedure, once the procedure itself is resolved.  */
3025   need_full_assumed_size++;
3026
3027   if (expr->symtree && expr->symtree->n.sym)
3028     p = expr->symtree->n.sym->attr.proc;
3029
3030   if (expr->value.function.isym && expr->value.function.isym->inquiry)
3031     inquiry_argument = true;
3032   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
3033
3034   if (resolve_actual_arglist (expr->value.function.actual,
3035                               p, no_formal_args) == FAILURE)
3036     {
3037       inquiry_argument = false;
3038       return FAILURE;
3039     }
3040
3041   inquiry_argument = false;
3042  
3043   /* Need to setup the call to the correct c_associated, depending on
3044      the number of cptrs to user gives to compare.  */
3045   if (sym && sym->attr.is_iso_c == 1)
3046     {
3047       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
3048           == FAILURE)
3049         return FAILURE;
3050       
3051       /* Get the symtree for the new symbol (resolved func).
3052          the old one will be freed later, when it's no longer used.  */
3053       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
3054     }
3055   
3056   /* Resume assumed_size checking.  */
3057   need_full_assumed_size--;
3058
3059   /* If the procedure is external, check for usage.  */
3060   if (sym && is_external_proc (sym))
3061     resolve_global_procedure (sym, &expr->where,
3062                               &expr->value.function.actual, 0);
3063
3064   if (sym && sym->ts.type == BT_CHARACTER
3065       && sym->ts.u.cl
3066       && sym->ts.u.cl->length == NULL
3067       && !sym->attr.dummy
3068       && !sym->ts.deferred
3069       && expr->value.function.esym == NULL
3070       && !sym->attr.contained)
3071     {
3072       /* Internal procedures are taken care of in resolve_contained_fntype.  */
3073       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
3074                  "be used at %L since it is not a dummy argument",
3075                  sym->name, &expr->where);
3076       return FAILURE;
3077     }
3078
3079   /* See if function is already resolved.  */
3080
3081   if (expr->value.function.name != NULL)
3082     {
3083       if (expr->ts.type == BT_UNKNOWN)
3084         expr->ts = sym->ts;
3085       t = SUCCESS;
3086     }
3087   else
3088     {
3089       /* Apply the rules of section 14.1.2.  */
3090
3091       switch (procedure_kind (sym))
3092         {
3093         case PTYPE_GENERIC:
3094           t = resolve_generic_f (expr);
3095           break;
3096
3097         case PTYPE_SPECIFIC:
3098           t = resolve_specific_f (expr);
3099           break;
3100
3101         case PTYPE_UNKNOWN:
3102           t = resolve_unknown_f (expr);
3103           break;
3104
3105         default:
3106           gfc_internal_error ("resolve_function(): bad function type");
3107         }
3108     }
3109
3110   /* If the expression is still a function (it might have simplified),
3111      then we check to see if we are calling an elemental function.  */
3112
3113   if (expr->expr_type != EXPR_FUNCTION)
3114     return t;
3115
3116   temp = need_full_assumed_size;
3117   need_full_assumed_size = 0;
3118
3119   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3120     return FAILURE;
3121
3122   if (omp_workshare_flag
3123       && expr->value.function.esym
3124       && ! gfc_elemental (expr->value.function.esym))
3125     {
3126       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3127                  "in WORKSHARE construct", expr->value.function.esym->name,
3128                  &expr->where);
3129       t = FAILURE;
3130     }
3131
3132 #define GENERIC_ID expr->value.function.isym->id
3133   else if (expr->value.function.actual != NULL
3134            && expr->value.function.isym != NULL
3135            && GENERIC_ID != GFC_ISYM_LBOUND
3136            && GENERIC_ID != GFC_ISYM_LEN
3137            && GENERIC_ID != GFC_ISYM_LOC
3138            && GENERIC_ID != GFC_ISYM_PRESENT)
3139     {
3140       /* Array intrinsics must also have the last upper bound of an
3141          assumed size array argument.  UBOUND and SIZE have to be
3142          excluded from the check if the second argument is anything
3143          than a constant.  */
3144
3145       for (arg = expr->value.function.actual; arg; arg = arg->next)
3146         {
3147           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3148               && arg->next != NULL && arg->next->expr)
3149             {
3150               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3151                 break;
3152
3153               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3154                 break;
3155
3156               if ((int)mpz_get_si (arg->next->expr->value.integer)
3157                         < arg->expr->rank)
3158                 break;
3159             }
3160
3161           if (arg->expr != NULL
3162               && arg->expr->rank > 0
3163               && resolve_assumed_size_actual (arg->expr))
3164             return FAILURE;
3165         }
3166     }
3167 #undef GENERIC_ID
3168
3169   need_full_assumed_size = temp;
3170   name = NULL;
3171
3172   if (!pure_function (expr, &name) && name)
3173     {
3174       if (forall_flag)
3175         {
3176           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
3177                      "FORALL %s", name, &expr->where,
3178                      forall_flag == 2 ? "mask" : "block");
3179           t = FAILURE;
3180         }
3181       else if (do_concurrent_flag)
3182         {
3183           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
3184                      "DO CONCURRENT %s", name, &expr->where,
3185                      do_concurrent_flag == 2 ? "mask" : "block");
3186           t = FAILURE;
3187         }
3188       else if (gfc_pure (NULL))
3189         {
3190           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3191                      "procedure within a PURE procedure", name, &expr->where);
3192           t = FAILURE;
3193         }
3194
3195       if (gfc_implicit_pure (NULL))
3196         gfc_current_ns->proc_name->attr.implicit_pure = 0;
3197     }
3198
3199   /* Functions without the RECURSIVE attribution are not allowed to
3200    * call themselves.  */
3201   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3202     {
3203       gfc_symbol *esym;
3204       esym = expr->value.function.esym;
3205
3206       if (is_illegal_recursion (esym, gfc_current_ns))
3207       {
3208         if (esym->attr.entry && esym->ns->entries)
3209           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3210                      " function '%s' is not RECURSIVE",
3211                      esym->name, &expr->where, esym->ns->entries->sym->name);
3212         else
3213           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3214                      " is not RECURSIVE", esym->name, &expr->where);
3215
3216         t = FAILURE;
3217       }
3218     }
3219
3220   /* Character lengths of use associated functions may contains references to
3221      symbols not referenced from the current program unit otherwise.  Make sure
3222      those symbols are marked as referenced.  */
3223
3224   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3225       && expr->value.function.esym->attr.use_assoc)
3226     {
3227       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3228     }
3229
3230   /* Make sure that the expression has a typespec that works.  */
3231   if (expr->ts.type == BT_UNKNOWN)
3232     {
3233       if (expr->symtree->n.sym->result
3234             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3235             && !expr->symtree->n.sym->result->attr.proc_pointer)
3236         expr->ts = expr->symtree->n.sym->result->ts;
3237     }
3238
3239   return t;
3240 }
3241
3242
3243 /************* Subroutine resolution *************/
3244
3245 static void
3246 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3247 {
3248   if (gfc_pure (sym))
3249     return;
3250
3251   if (forall_flag)
3252     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3253                sym->name, &c->loc);
3254   else if (do_concurrent_flag)
3255     gfc_error ("Subroutine call to '%s' in DO CONCURRENT block at %L is not "
3256                "PURE", sym->name, &c->loc);
3257   else if (gfc_pure (NULL))
3258     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3259                &c->loc);
3260
3261   if (gfc_implicit_pure (NULL))
3262     gfc_current_ns->proc_name->attr.implicit_pure = 0;
3263 }
3264
3265
3266 static match
3267 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3268 {
3269   gfc_symbol *s;
3270
3271   if (sym->attr.generic)
3272     {
3273       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3274       if (s != NULL)
3275         {
3276           c->resolved_sym = s;
3277           pure_subroutine (c, s);
3278           return MATCH_YES;
3279         }
3280
3281       /* TODO: Need to search for elemental references in generic interface.  */
3282     }
3283
3284   if (sym->attr.intrinsic)
3285     return gfc_intrinsic_sub_interface (c, 0);
3286
3287   return MATCH_NO;
3288 }
3289
3290
3291 static gfc_try
3292 resolve_generic_s (gfc_code *c)
3293 {
3294   gfc_symbol *sym;
3295   match m;
3296
3297   sym = c->symtree->n.sym;
3298
3299   for (;;)
3300     {
3301       m = resolve_generic_s0 (c, sym);
3302       if (m == MATCH_YES)
3303         return SUCCESS;
3304       else if (m == MATCH_ERROR)
3305         return FAILURE;
3306
3307 generic:
3308       if (sym->ns->parent == NULL)
3309         break;
3310       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3311
3312       if (sym == NULL)
3313         break;
3314       if (!generic_sym (sym))
3315         goto generic;
3316     }
3317
3318   /* Last ditch attempt.  See if the reference is to an intrinsic
3319      that possesses a matching interface.  14.1.2.4  */
3320   sym = c->symtree->n.sym;
3321
3322   if (!gfc_is_intrinsic (sym, 1, c->loc))
3323     {
3324       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3325                  sym->name, &c->loc);
3326       return FAILURE;
3327     }
3328
3329   m = gfc_intrinsic_sub_interface (c, 0);
3330   if (m == MATCH_YES)
3331     return SUCCESS;
3332   if (m == MATCH_NO)
3333     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3334                "intrinsic subroutine interface", sym->name, &c->loc);
3335
3336   return FAILURE;
3337 }
3338
3339
3340 /* Set the name and binding label of the subroutine symbol in the call
3341    expression represented by 'c' to include the type and kind of the
3342    second parameter.  This function is for resolving the appropriate
3343    version of c_f_pointer() and c_f_procpointer().  For example, a
3344    call to c_f_pointer() for a default integer pointer could have a
3345    name of c_f_pointer_i4.  If no second arg exists, which is an error
3346    for these two functions, it defaults to the generic symbol's name
3347    and binding label.  */
3348
3349 static void
3350 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3351                     char *name, char *binding_label)
3352 {
3353   gfc_expr *arg = NULL;
3354   char type;
3355   int kind;
3356
3357   /* The second arg of c_f_pointer and c_f_procpointer determines
3358      the type and kind for the procedure name.  */
3359   arg = c->ext.actual->next->expr;
3360
3361   if (arg != NULL)
3362     {
3363       /* Set up the name to have the given symbol's name,
3364          plus the type and kind.  */
3365       /* a derived type is marked with the type letter 'u' */
3366       if (arg->ts.type == BT_DERIVED)
3367         {
3368           type = 'd';
3369           kind = 0; /* set the kind as 0 for now */
3370         }
3371       else
3372         {
3373           type = gfc_type_letter (arg->ts.type);
3374           kind = arg->ts.kind;
3375         }
3376
3377       if (arg->ts.type == BT_CHARACTER)
3378         /* Kind info for character strings not needed.  */
3379         kind = 0;
3380
3381       sprintf (name, "%s_%c%d", sym->name, type, kind);
3382       /* Set up the binding label as the given symbol's label plus
3383          the type and kind.  */
3384       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
3385     }
3386   else
3387     {
3388       /* If the second arg is missing, set the name and label as
3389          was, cause it should at least be found, and the missing
3390          arg error will be caught by compare_parameters().  */
3391       sprintf (name, "%s", sym->name);
3392       sprintf (binding_label, "%s", sym->binding_label);
3393     }
3394    
3395   return;
3396 }
3397
3398
3399 /* Resolve a generic version of the iso_c_binding procedure given
3400    (sym) to the specific one based on the type and kind of the
3401    argument(s).  Currently, this function resolves c_f_pointer() and
3402    c_f_procpointer based on the type and kind of the second argument
3403    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3404    Upon successfully exiting, c->resolved_sym will hold the resolved
3405    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3406    otherwise.  */
3407
3408 match
3409 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3410 {
3411   gfc_symbol *new_sym;
3412   /* this is fine, since we know the names won't use the max */
3413   char name[GFC_MAX_SYMBOL_LEN + 1];
3414   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
3415   /* default to success; will override if find error */
3416   match m = MATCH_YES;
3417
3418   /* Make sure the actual arguments are in the necessary order (based on the 
3419      formal args) before resolving.  */
3420   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3421
3422   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3423       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3424     {
3425       set_name_and_label (c, sym, name, binding_label);
3426       
3427       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3428         {
3429           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3430             {
3431               /* Make sure we got a third arg if the second arg has non-zero
3432                  rank.  We must also check that the type and rank are
3433                  correct since we short-circuit this check in
3434                  gfc_procedure_use() (called above to sort actual args).  */
3435               if (c->ext.actual->next->expr->rank != 0)
3436                 {
3437                   if(c->ext.actual->next->next == NULL 
3438                      || c->ext.actual->next->next->expr == NULL)
3439                     {
3440                       m = MATCH_ERROR;
3441                       gfc_error ("Missing SHAPE parameter for call to %s "
3442                                  "at %L", sym->name, &(c->loc));
3443                     }
3444                   else if (c->ext.actual->next->next->expr->ts.type
3445                            != BT_INTEGER
3446                            || c->ext.actual->next->next->expr->rank != 1)
3447                     {
3448                       m = MATCH_ERROR;
3449                       gfc_error ("SHAPE parameter for call to %s at %L must "
3450                                  "be a rank 1 INTEGER array", sym->name,
3451                                  &(c->loc));
3452                     }
3453                 }
3454             }
3455         }
3456       
3457       if (m != MATCH_ERROR)
3458         {
3459           /* the 1 means to add the optional arg to formal list */
3460           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3461          
3462           /* for error reporting, say it's declared where the original was */
3463           new_sym->declared_at = sym->declared_at;
3464         }
3465     }
3466   else
3467     {
3468       /* no differences for c_loc or c_funloc */
3469       new_sym = sym;
3470     }
3471
3472   /* set the resolved symbol */
3473   if (m != MATCH_ERROR)
3474     c->resolved_sym = new_sym;
3475   else
3476     c->resolved_sym = sym;
3477   
3478   return m;
3479 }
3480
3481
3482 /* Resolve a subroutine call known to be specific.  */
3483
3484 static match
3485 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3486 {
3487   match m;
3488
3489   if(sym->attr.is_iso_c)
3490     {
3491       m = gfc_iso_c_sub_interface (c,sym);
3492       return m;
3493     }
3494   
3495   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3496     {
3497       if (sym->attr.dummy)
3498         {
3499           sym->attr.proc = PROC_DUMMY;
3500           goto found;
3501         }
3502
3503       sym->attr.proc = PROC_EXTERNAL;
3504       goto found;
3505     }
3506
3507   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3508     goto found;
3509
3510   if (sym->attr.intrinsic)
3511     {
3512       m = gfc_intrinsic_sub_interface (c, 1);
3513       if (m == MATCH_YES)
3514         return MATCH_YES;
3515       if (m == MATCH_NO)
3516         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3517                    "with an intrinsic", sym->name, &c->loc);
3518
3519       return MATCH_ERROR;
3520     }
3521
3522   return MATCH_NO;
3523
3524 found:
3525   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3526
3527   c->resolved_sym = sym;
3528   pure_subroutine (c, sym);
3529
3530   return MATCH_YES;
3531 }
3532
3533
3534 static gfc_try
3535 resolve_specific_s (gfc_code *c)
3536 {
3537   gfc_symbol *sym;
3538   match m;
3539
3540   sym = c->symtree->n.sym;
3541
3542   for (;;)
3543     {
3544       m = resolve_specific_s0 (c, sym);
3545       if (m == MATCH_YES)
3546         return SUCCESS;
3547       if (m == MATCH_ERROR)
3548         return FAILURE;
3549
3550       if (sym->ns->parent == NULL)
3551         break;
3552
3553       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3554
3555       if (sym == NULL)
3556         break;
3557     }
3558
3559   sym = c->symtree->n.sym;
3560   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3561              sym->name, &c->loc);
3562
3563   return FAILURE;
3564 }
3565
3566
3567 /* Resolve a subroutine call not known to be generic nor specific.  */
3568
3569 static gfc_try
3570 resolve_unknown_s (gfc_code *c)
3571 {
3572   gfc_symbol *sym;
3573
3574   sym = c->symtree->n.sym;
3575
3576   if (sym->attr.dummy)
3577     {
3578       sym->attr.proc = PROC_DUMMY;
3579       goto found;
3580     }
3581
3582   /* See if we have an intrinsic function reference.  */
3583
3584   if (gfc_is_intrinsic (sym, 1, c->loc))
3585     {
3586       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3587         return SUCCESS;
3588       return FAILURE;
3589     }
3590
3591   /* The reference is to an external name.  */
3592
3593 found:
3594   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3595
3596   c->resolved_sym = sym;
3597
3598   pure_subroutine (c, sym);
3599
3600   return SUCCESS;
3601 }
3602
3603
3604 /* Resolve a subroutine call.  Although it was tempting to use the same code
3605    for functions, subroutines and functions are stored differently and this
3606    makes things awkward.  */
3607
3608 static gfc_try
3609 resolve_call (gfc_code *c)
3610 {
3611   gfc_try t;
3612   procedure_type ptype = PROC_INTRINSIC;
3613   gfc_symbol *csym, *sym;
3614   bool no_formal_args;
3615
3616   csym = c->symtree ? c->symtree->n.sym : NULL;
3617
3618   if (csym && csym->ts.type != BT_UNKNOWN)
3619     {
3620       gfc_error ("'%s' at %L has a type, which is not consistent with "
3621                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3622       return FAILURE;
3623     }
3624
3625   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3626     {
3627       gfc_symtree *st;
3628       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3629       sym = st ? st->n.sym : NULL;
3630       if (sym && csym != sym
3631               && sym->ns == gfc_current_ns
3632               && sym->attr.flavor == FL_PROCEDURE
3633               && sym->attr.contained)
3634         {
3635           sym->refs++;
3636           if (csym->attr.generic)
3637             c->symtree->n.sym = sym;
3638           else
3639             c->symtree = st;
3640           csym = c->symtree->n.sym;
3641         }
3642     }
3643
3644   /* If this ia a deferred TBP with an abstract interface
3645      (which may of course be referenced), c->expr1 will be set.  */
3646   if (csym && csym->attr.abstract && !c->expr1)
3647     {
3648       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3649                  csym->name, &c->loc);
3650       return FAILURE;
3651     }
3652
3653   /* Subroutines without the RECURSIVE attribution are not allowed to
3654    * call themselves.  */
3655   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3656     {
3657       if (csym->attr.entry && csym->ns->entries)
3658         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3659                    " subroutine '%s' is not RECURSIVE",
3660                    csym->name, &c->loc, csym->ns->entries->sym->name);
3661       else
3662         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3663                    " is not RECURSIVE", csym->name, &c->loc);
3664
3665       t = FAILURE;
3666     }
3667
3668   /* Switch off assumed size checking and do this again for certain kinds
3669      of procedure, once the procedure itself is resolved.  */
3670   need_full_assumed_size++;
3671
3672   if (csym)
3673     ptype = csym->attr.proc;
3674
3675   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3676   if (resolve_actual_arglist (c->ext.actual, ptype,
3677                               no_formal_args) == FAILURE)
3678     return FAILURE;
3679
3680   /* Resume assumed_size checking.  */
3681   need_full_assumed_size--;
3682
3683   /* If external, check for usage.  */
3684   if (csym && is_external_proc (csym))
3685     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3686
3687   t = SUCCESS;
3688   if (c->resolved_sym == NULL)
3689     {
3690       c->resolved_isym = NULL;
3691       switch (procedure_kind (csym))
3692         {
3693         case PTYPE_GENERIC:
3694           t = resolve_generic_s (c);
3695           break;
3696
3697         case PTYPE_SPECIFIC:
3698           t = resolve_specific_s (c);
3699           break;
3700
3701         case PTYPE_UNKNOWN:
3702           t = resolve_unknown_s (c);
3703           break;
3704
3705         default:
3706           gfc_internal_error ("resolve_subroutine(): bad function type");
3707         }
3708     }
3709
3710   /* Some checks of elemental subroutine actual arguments.  */
3711   if (resolve_elemental_actual (NULL, c) == FAILURE)
3712     return FAILURE;
3713
3714   return t;
3715 }
3716
3717
3718 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3719    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3720    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3721    if their shapes do not match.  If either op1->shape or op2->shape is
3722    NULL, return SUCCESS.  */
3723
3724 static gfc_try
3725 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3726 {
3727   gfc_try t;
3728   int i;
3729
3730   t = SUCCESS;
3731
3732   if (op1->shape != NULL && op2->shape != NULL)
3733     {
3734       for (i = 0; i < op1->rank; i++)
3735         {
3736           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3737            {
3738              gfc_error ("Shapes for operands at %L and %L are not conformable",
3739                          &op1->where, &op2->where);
3740              t = FAILURE;
3741              break;
3742            }
3743         }
3744     }
3745
3746   return t;
3747 }
3748
3749
3750 /* Resolve an operator expression node.  This can involve replacing the
3751    operation with a user defined function call.  */
3752
3753 static gfc_try
3754 resolve_operator (gfc_expr *e)
3755 {
3756   gfc_expr *op1, *op2;
3757   char msg[200];
3758   bool dual_locus_error;
3759   gfc_try t;
3760
3761   /* Resolve all subnodes-- give them types.  */
3762
3763   switch (e->value.op.op)
3764     {
3765     default:
3766       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3767         return FAILURE;
3768
3769     /* Fall through...  */
3770
3771     case INTRINSIC_NOT:
3772     case INTRINSIC_UPLUS:
3773     case INTRINSIC_UMINUS:
3774     case INTRINSIC_PARENTHESES:
3775       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3776         return FAILURE;
3777       break;
3778     }
3779
3780   /* Typecheck the new node.  */
3781
3782   op1 = e->value.op.op1;
3783   op2 = e->value.op.op2;
3784   dual_locus_error = false;
3785
3786   if ((op1 && op1->expr_type == EXPR_NULL)
3787       || (op2 && op2->expr_type == EXPR_NULL))
3788     {
3789       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3790       goto bad_op;
3791     }
3792
3793   switch (e->value.op.op)
3794     {
3795     case INTRINSIC_UPLUS:
3796     case INTRINSIC_UMINUS:
3797       if (op1->ts.type == BT_INTEGER
3798           || op1->ts.type == BT_REAL
3799           || op1->ts.type == BT_COMPLEX)
3800         {
3801           e->ts = op1->ts;
3802           break;
3803         }
3804
3805       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3806                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3807       goto bad_op;
3808
3809     case INTRINSIC_PLUS:
3810     case INTRINSIC_MINUS:
3811     case INTRINSIC_TIMES:
3812     case INTRINSIC_DIVIDE:
3813     case INTRINSIC_POWER:
3814       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3815         {
3816           gfc_type_convert_binary (e, 1);
3817           break;
3818         }
3819
3820       sprintf (msg,
3821                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3822                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3823                gfc_typename (&op2->ts));
3824       goto bad_op;
3825
3826     case INTRINSIC_CONCAT:
3827       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3828           && op1->ts.kind == op2->ts.kind)
3829         {
3830           e->ts.type = BT_CHARACTER;
3831           e->ts.kind = op1->ts.kind;
3832           break;
3833         }
3834
3835       sprintf (msg,
3836                _("Operands of string concatenation operator at %%L are %s/%s"),
3837                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3838       goto bad_op;
3839
3840     case INTRINSIC_AND:
3841     case INTRINSIC_OR:
3842     case INTRINSIC_EQV:
3843     case INTRINSIC_NEQV:
3844       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3845         {
3846           e->ts.type = BT_LOGICAL;
3847           e->ts.kind = gfc_kind_max (op1, op2);
3848           if (op1->ts.kind < e->ts.kind)
3849             gfc_convert_type (op1, &e->ts, 2);
3850           else if (op2->ts.kind < e->ts.kind)
3851             gfc_convert_type (op2, &e->ts, 2);
3852           break;
3853         }
3854
3855       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3856                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3857                gfc_typename (&op2->ts));
3858
3859       goto bad_op;
3860
3861     case INTRINSIC_NOT:
3862       if (op1->ts.type == BT_LOGICAL)
3863         {
3864           e->ts.type = BT_LOGICAL;
3865           e->ts.kind = op1->ts.kind;
3866           break;
3867         }
3868
3869       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3870                gfc_typename (&op1->ts));
3871       goto bad_op;
3872
3873     case INTRINSIC_GT:
3874     case INTRINSIC_GT_OS:
3875     case INTRINSIC_GE:
3876     case INTRINSIC_GE_OS:
3877     case INTRINSIC_LT:
3878     case INTRINSIC_LT_OS:
3879     case INTRINSIC_LE:
3880     case INTRINSIC_LE_OS:
3881       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3882         {
3883           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3884           goto bad_op;
3885         }
3886
3887       /* Fall through...  */
3888
3889     case INTRINSIC_EQ:
3890     case INTRINSIC_EQ_OS:
3891     case INTRINSIC_NE:
3892     case INTRINSIC_NE_OS:
3893       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3894           && op1->ts.kind == op2->ts.kind)
3895         {
3896           e->ts.type = BT_LOGICAL;
3897           e->ts.kind = gfc_default_logical_kind;
3898           break;
3899         }
3900
3901       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3902         {
3903           gfc_type_convert_binary (e, 1);
3904
3905           e->ts.type = BT_LOGICAL;
3906           e->ts.kind = gfc_default_logical_kind;
3907           break;
3908         }
3909
3910       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3911         sprintf (msg,
3912                  _("Logicals at %%L must be compared with %s instead of %s"),
3913                  (e->value.op.op == INTRINSIC_EQ 
3914                   || e->value.op.op == INTRINSIC_EQ_OS)
3915                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3916       else
3917         sprintf (msg,
3918                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3919                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3920                  gfc_typename (&op2->ts));
3921
3922       goto bad_op;
3923
3924     case INTRINSIC_USER:
3925       if (e->value.op.uop->op == NULL)
3926         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3927       else if (op2 == NULL)
3928         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3929                  e->value.op.uop->name, gfc_typename (&op1->ts));
3930       else
3931         {
3932           sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3933                    e->value.op.uop->name, gfc_typename (&op1->ts),
3934                    gfc_typename (&op2->ts));
3935           e->value.op.uop->op->sym->attr.referenced = 1;
3936         }
3937
3938       goto bad_op;
3939
3940     case INTRINSIC_PARENTHESES:
3941       e->ts = op1->ts;
3942       if (e->ts.type == BT_CHARACTER)
3943         e->ts.u.cl = op1->ts.u.cl;
3944       break;
3945
3946     default:
3947       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3948     }
3949
3950   /* Deal with arrayness of an operand through an operator.  */
3951
3952   t = SUCCESS;
3953
3954   switch (e->value.op.op)
3955     {
3956     case INTRINSIC_PLUS:
3957     case INTRINSIC_MINUS:
3958     case INTRINSIC_TIMES:
3959     case INTRINSIC_DIVIDE:
3960     case INTRINSIC_POWER:
3961     case INTRINSIC_CONCAT:
3962     case INTRINSIC_AND:
3963     case INTRINSIC_OR:
3964     case INTRINSIC_EQV:
3965     case INTRINSIC_NEQV:
3966     case INTRINSIC_EQ:
3967     case INTRINSIC_EQ_OS:
3968     case INTRINSIC_NE:
3969     case INTRINSIC_NE_OS:
3970     case INTRINSIC_GT:
3971     case INTRINSIC_GT_OS:
3972     case INTRINSIC_GE:
3973     case INTRINSIC_GE_OS:
3974     case INTRINSIC_LT:
3975     case INTRINSIC_LT_OS:
3976     case INTRINSIC_LE:
3977     case INTRINSIC_LE_OS:
3978
3979       if (op1->rank == 0 && op2->rank == 0)
3980         e->rank = 0;
3981
3982       if (op1->rank == 0 && op2->rank != 0)
3983         {
3984           e->rank = op2->rank;
3985
3986           if (e->shape == NULL)
3987             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3988         }
3989
3990       if (op1->rank != 0 && op2->rank == 0)
3991         {
3992           e->rank = op1->rank;
3993
3994           if (e->shape == NULL)
3995             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3996         }
3997
3998       if (op1->rank != 0 && op2->rank != 0)
3999         {
4000           if (op1->rank == op2->rank)
4001             {
4002               e->rank = op1->rank;
4003               if (e->shape == NULL)
4004                 {
4005                   t = compare_shapes (op1, op2);
4006                   if (t == FAILURE)
4007                     e->shape = NULL;
4008                   else
4009                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
4010                 }
4011             }
4012           else
4013             {
4014               /* Allow higher level expressions to work.  */
4015               e->rank = 0;
4016
4017               /* Try user-defined operators, and otherwise throw an error.  */
4018               dual_locus_error = true;
4019               sprintf (msg,
4020                        _("Inconsistent ranks for operator at %%L and %%L"));
4021               goto bad_op;
4022             }
4023         }
4024
4025       break;
4026
4027     case INTRINSIC_PARENTHESES:
4028     case INTRINSIC_NOT:
4029     case INTRINSIC_UPLUS:
4030     case INTRINSIC_UMINUS:
4031       /* Simply copy arrayness attribute */
4032       e->rank = op1->rank;
4033
4034       if (e->shape == NULL)
4035         e->shape = gfc_copy_shape (op1->shape, op1->rank);
4036
4037       break;
4038
4039     default:
4040       break;
4041     }
4042
4043   /* Attempt to simplify the expression.  */
4044   if (t == SUCCESS)
4045     {
4046       t = gfc_simplify_expr (e, 0);
4047       /* Some calls do not succeed in simplification and return FAILURE
4048          even though there is no error; e.g. variable references to
4049          PARAMETER arrays.  */
4050       if (!gfc_is_constant_expr (e))
4051         t = SUCCESS;
4052     }
4053   return t;
4054
4055 bad_op:
4056
4057   {
4058     match m = gfc_extend_expr (e);
4059     if (m == MATCH_YES)
4060       return SUCCESS;
4061     if (m == MATCH_ERROR)
4062       return FAILURE;
4063   }
4064
4065   if (dual_locus_error)
4066     gfc_error (msg, &op1->where, &op2->where);
4067   else
4068     gfc_error (msg, &e->where);
4069
4070   return FAILURE;
4071 }
4072
4073
4074 /************** Array resolution subroutines **************/
4075
4076 typedef enum
4077 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
4078 comparison;
4079
4080 /* Compare two integer expressions.  */
4081
4082 static comparison
4083 compare_bound (gfc_expr *a, gfc_expr *b)
4084 {
4085   int i;
4086
4087   if (a == NULL || a->expr_type != EXPR_CONSTANT
4088       || b == NULL || b->expr_type != EXPR_CONSTANT)
4089     return CMP_UNKNOWN;
4090
4091   /* If either of the types isn't INTEGER, we must have
4092      raised an error earlier.  */
4093
4094   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
4095     return CMP_UNKNOWN;
4096
4097   i = mpz_cmp (a->value.integer, b->value.integer);
4098
4099   if (i < 0)
4100     return CMP_LT;
4101   if (i > 0)
4102     return CMP_GT;
4103   return CMP_EQ;
4104 }
4105
4106
4107 /* Compare an integer expression with an integer.  */
4108
4109 static comparison
4110 compare_bound_int (gfc_expr *a, int b)
4111 {
4112   int i;
4113
4114   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4115     return CMP_UNKNOWN;
4116
4117   if (a->ts.type != BT_INTEGER)
4118     gfc_internal_error ("compare_bound_int(): Bad expression");
4119
4120   i = mpz_cmp_si (a->value.integer, b);
4121
4122   if (i < 0)
4123     return CMP_LT;
4124   if (i > 0)
4125     return CMP_GT;
4126   return CMP_EQ;
4127 }
4128
4129
4130 /* Compare an integer expression with a mpz_t.  */
4131
4132 static comparison
4133 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4134 {
4135   int i;
4136
4137   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4138     return CMP_UNKNOWN;
4139
4140   if (a->ts.type != BT_INTEGER)
4141     gfc_internal_error ("compare_bound_int(): Bad expression");
4142
4143   i = mpz_cmp (a->value.integer, b);
4144
4145   if (i < 0)
4146     return CMP_LT;
4147   if (i > 0)
4148     return CMP_GT;
4149   return CMP_EQ;
4150 }
4151
4152
4153 /* Compute the last value of a sequence given by a triplet.  
4154    Return 0 if it wasn't able to compute the last value, or if the
4155    sequence if empty, and 1 otherwise.  */
4156
4157 static int
4158 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4159                                 gfc_expr *stride, mpz_t last)
4160 {
4161   mpz_t rem;
4162
4163   if (start == NULL || start->expr_type != EXPR_CONSTANT
4164       || end == NULL || end->expr_type != EXPR_CONSTANT
4165       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4166     return 0;
4167
4168   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4169       || (stride != NULL && stride->ts.type != BT_INTEGER))
4170     return 0;
4171
4172   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4173     {
4174       if (compare_bound (start, end) == CMP_GT)
4175         return 0;
4176       mpz_set (last, end->value.integer);
4177       return 1;
4178     }
4179
4180   if (compare_bound_int (stride, 0) == CMP_GT)
4181     {
4182       /* Stride is positive */
4183       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4184         return 0;
4185     }
4186   else
4187     {
4188       /* Stride is negative */
4189       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4190         return 0;
4191     }
4192
4193   mpz_init (rem);
4194   mpz_sub (rem, end->value.integer, start->value.integer);
4195   mpz_tdiv_r (rem, rem, stride->value.integer);
4196   mpz_sub (last, end->value.integer, rem);
4197   mpz_clear (rem);
4198
4199   return 1;
4200 }
4201
4202
4203 /* Compare a single dimension of an array reference to the array
4204    specification.  */
4205
4206 static gfc_try
4207 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4208 {
4209   mpz_t last_value;
4210
4211   if (ar->dimen_type[i] == DIMEN_STAR)
4212     {
4213       gcc_assert (ar->stride[i] == NULL);
4214       /* This implies [*] as [*:] and [*:3] are not possible.  */
4215       if (ar->start[i] == NULL)
4216         {
4217           gcc_assert (ar->end[i] == NULL);
4218           return SUCCESS;
4219         }
4220     }
4221
4222 /* Given start, end and stride values, calculate the minimum and
4223    maximum referenced indexes.  */
4224
4225   switch (ar->dimen_type[i])
4226     {
4227     case DIMEN_VECTOR:
4228     case DIMEN_THIS_IMAGE:
4229       break;
4230
4231     case DIMEN_STAR:
4232     case DIMEN_ELEMENT:
4233       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4234         {
4235           if (i < as->rank)
4236             gfc_warning ("Array reference at %L is out of bounds "
4237                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4238                          mpz_get_si (ar->start[i]->value.integer),
4239                          mpz_get_si (as->lower[i]->value.integer), i+1);
4240           else
4241             gfc_warning ("Array reference at %L is out of bounds "
4242                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4243                          mpz_get_si (ar->start[i]->value.integer),
4244                          mpz_get_si (as->lower[i]->value.integer),
4245                          i + 1 - as->rank);
4246           return SUCCESS;
4247         }
4248       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4249         {
4250           if (i < as->rank)
4251             gfc_warning ("Array reference at %L is out of bounds "
4252                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4253                          mpz_get_si (ar->start[i]->value.integer),
4254                          mpz_get_si (as->upper[i]->value.integer), i+1);
4255           else
4256             gfc_warning ("Array reference at %L is out of bounds "
4257                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4258                          mpz_get_si (ar->start[i]->value.integer),
4259                          mpz_get_si (as->upper[i]->value.integer),
4260                          i + 1 - as->rank);
4261           return SUCCESS;
4262         }
4263
4264       break;
4265
4266     case DIMEN_RANGE:
4267       {
4268 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4269 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4270
4271         comparison comp_start_end = compare_bound (AR_START, AR_END);
4272
4273         /* Check for zero stride, which is not allowed.  */
4274         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4275           {
4276             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4277             return FAILURE;
4278           }
4279
4280         /* if start == len || (stride > 0 && start < len)
4281                            || (stride < 0 && start > len),
4282            then the array section contains at least one element.  In this
4283            case, there is an out-of-bounds access if
4284            (start < lower || start > upper).  */
4285         if (compare_bound (AR_START, AR_END) == CMP_EQ
4286             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4287                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4288             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4289                 && comp_start_end == CMP_GT))
4290           {
4291             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4292               {
4293                 gfc_warning ("Lower array reference at %L is out of bounds "
4294                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4295                        mpz_get_si (AR_START->value.integer),
4296                        mpz_get_si (as->lower[i]->value.integer), i+1);
4297                 return SUCCESS;
4298               }
4299             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4300               {
4301                 gfc_warning ("Lower array reference at %L is out of bounds "
4302                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4303                        mpz_get_si (AR_START->value.integer),
4304                        mpz_get_si (as->upper[i]->value.integer), i+1);
4305                 return SUCCESS;
4306               }
4307           }
4308
4309         /* If we can compute the highest index of the array section,
4310            then it also has to be between lower and upper.  */
4311         mpz_init (last_value);
4312         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4313                                             last_value))
4314           {
4315             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4316               {
4317                 gfc_warning ("Upper array reference at %L is out of bounds "
4318                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4319                        mpz_get_si (last_value),
4320                        mpz_get_si (as->lower[i]->value.integer), i+1);
4321                 mpz_clear (last_value);
4322                 return SUCCESS;
4323               }
4324             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4325               {
4326                 gfc_warning ("Upper array reference at %L is out of bounds "
4327                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4328                        mpz_get_si (last_value),
4329                        mpz_get_si (as->upper[i]->value.integer), i+1);
4330                 mpz_clear (last_value);
4331                 return SUCCESS;
4332               }
4333           }
4334         mpz_clear (last_value);
4335
4336 #undef AR_START
4337 #undef AR_END
4338       }
4339       break;
4340
4341     default:
4342       gfc_internal_error ("check_dimension(): Bad array reference");
4343     }
4344
4345   return SUCCESS;
4346 }
4347
4348
4349 /* Compare an array reference with an array specification.  */
4350
4351 static gfc_try
4352 compare_spec_to_ref (gfc_array_ref *ar)
4353 {
4354   gfc_array_spec *as;
4355   int i;
4356
4357   as = ar->as;
4358   i = as->rank - 1;
4359   /* TODO: Full array sections are only allowed as actual parameters.  */
4360   if (as->type == AS_ASSUMED_SIZE
4361       && (/*ar->type == AR_FULL
4362           ||*/ (ar->type == AR_SECTION
4363               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4364     {
4365       gfc_error ("Rightmost upper bound of assumed size array section "
4366                  "not specified at %L", &ar->where);
4367       return FAILURE;
4368     }
4369
4370   if (ar->type == AR_FULL)
4371     return SUCCESS;
4372
4373   if (as->rank != ar->dimen)
4374     {
4375       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4376                  &ar->where, ar->dimen, as->rank);
4377       return FAILURE;
4378     }
4379
4380   /* ar->codimen == 0 is a local array.  */
4381   if (as->corank != ar->codimen && ar->codimen != 0)
4382     {
4383       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4384                  &ar->where, ar->codimen, as->corank);
4385       return FAILURE;
4386     }
4387
4388   for (i = 0; i < as->rank; i++)
4389     if (check_dimension (i, ar, as) == FAILURE)
4390       return FAILURE;
4391
4392   /* Local access has no coarray spec.  */
4393   if (ar->codimen != 0)
4394     for (i = as->rank; i < as->rank + as->corank; i++)
4395       {
4396         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate
4397             && ar->dimen_type[i] != DIMEN_THIS_IMAGE)
4398           {
4399             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4400                        i + 1 - as->rank, &ar->where);
4401             return FAILURE;
4402           }
4403         if (check_dimension (i, ar, as) == FAILURE)
4404           return FAILURE;
4405       }
4406
4407   return SUCCESS;
4408 }
4409
4410
4411 /* Resolve one part of an array index.  */
4412
4413 static gfc_try
4414 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4415                      int force_index_integer_kind)
4416 {
4417   gfc_typespec ts;
4418
4419   if (index == NULL)
4420     return SUCCESS;
4421
4422   if (gfc_resolve_expr (index) == FAILURE)
4423     return FAILURE;
4424
4425   if (check_scalar && index->rank != 0)
4426     {
4427       gfc_error ("Array index at %L must be scalar", &index->where);
4428       return FAILURE;
4429     }
4430
4431   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4432     {
4433       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4434                  &index->where, gfc_basic_typename (index->ts.type));
4435       return FAILURE;
4436     }
4437
4438   if (index->ts.type == BT_REAL)
4439     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4440                         &index->where) == FAILURE)
4441       return FAILURE;
4442
4443   if ((index->ts.kind != gfc_index_integer_kind
4444        && force_index_integer_kind)
4445       || index->ts.type != BT_INTEGER)
4446     {
4447       gfc_clear_ts (&ts);
4448       ts.type = BT_INTEGER;
4449       ts.kind = gfc_index_integer_kind;
4450
4451       gfc_convert_type_warn (index, &ts, 2, 0);
4452     }
4453
4454   return SUCCESS;
4455 }
4456
4457 /* Resolve one part of an array index.  */
4458
4459 gfc_try
4460 gfc_resolve_index (gfc_expr *index, int check_scalar)
4461 {
4462   return gfc_resolve_index_1 (index, check_scalar, 1);
4463 }
4464
4465 /* Resolve a dim argument to an intrinsic function.  */
4466
4467 gfc_try
4468 gfc_resolve_dim_arg (gfc_expr *dim)
4469 {
4470   if (dim == NULL)
4471     return SUCCESS;
4472
4473   if (gfc_resolve_expr (dim) == FAILURE)
4474     return FAILURE;
4475
4476   if (dim->rank != 0)
4477     {
4478       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4479       return FAILURE;
4480
4481     }
4482
4483   if (dim->ts.type != BT_INTEGER)
4484     {
4485       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4486       return FAILURE;
4487     }
4488
4489   if (dim->ts.kind != gfc_index_integer_kind)
4490     {
4491       gfc_typespec ts;
4492
4493       gfc_clear_ts (&ts);
4494       ts.type = BT_INTEGER;
4495       ts.kind = gfc_index_integer_kind;
4496
4497       gfc_convert_type_warn (dim, &ts, 2, 0);
4498     }
4499
4500   return SUCCESS;
4501 }
4502
4503 /* Given an expression that contains array references, update those array
4504    references to point to the right array specifications.  While this is
4505    filled in during matching, this information is difficult to save and load
4506    in a module, so we take care of it here.
4507
4508    The idea here is that the original array reference comes from the
4509    base symbol.  We traverse the list of reference structures, setting
4510    the stored reference to references.  Component references can
4511    provide an additional array specification.  */
4512
4513 static void
4514 find_array_spec (gfc_expr *e)
4515 {
4516   gfc_array_spec *as;
4517   gfc_component *c;
4518   gfc_ref *ref;
4519
4520   if (e->symtree->n.sym->ts.type == BT_CLASS)
4521     as = CLASS_DATA (e->symtree->n.sym)->as;
4522   else
4523     as = e->symtree->n.sym->as;
4524
4525   for (ref = e->ref; ref; ref = ref->next)
4526     switch (ref->type)
4527       {
4528       case REF_ARRAY:
4529         if (as == NULL)
4530           gfc_internal_error ("find_array_spec(): Missing spec");
4531
4532         ref->u.ar.as = as;
4533         as = NULL;
4534         break;
4535
4536       case REF_COMPONENT:
4537         c = ref->u.c.component;
4538         if (c->attr.dimension)
4539           {
4540             if (as != NULL)
4541               gfc_internal_error ("find_array_spec(): unused as(1)");
4542             as = c->as;
4543           }
4544
4545         break;
4546
4547       case REF_SUBSTRING:
4548         break;
4549       }
4550
4551   if (as != NULL)
4552     gfc_internal_error ("find_array_spec(): unused as(2)");
4553 }
4554
4555
4556 /* Resolve an array reference.  */
4557
4558 static gfc_try
4559 resolve_array_ref (gfc_array_ref *ar)
4560 {
4561   int i, check_scalar;
4562   gfc_expr *e;
4563
4564   for (i = 0; i < ar->dimen + ar->codimen; i++)
4565     {
4566       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4567
4568       /* Do not force gfc_index_integer_kind for the start.  We can
4569          do fine with any integer kind.  This avoids temporary arrays
4570          created for indexing with a vector.  */
4571       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4572         return FAILURE;
4573       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4574         return FAILURE;
4575       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4576         return FAILURE;
4577
4578       e = ar->start[i];
4579
4580       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4581         switch (e->rank)
4582           {
4583           case 0:
4584             ar->dimen_type[i] = DIMEN_ELEMENT;
4585             break;
4586
4587           case 1:
4588             ar->dimen_type[i] = DIMEN_VECTOR;
4589             if (e->expr_type == EXPR_VARIABLE
4590                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4591               ar->start[i] = gfc_get_parentheses (e);
4592             break;
4593
4594           default:
4595             gfc_error ("Array index at %L is an array of rank %d",
4596                        &ar->c_where[i], e->rank);
4597             return FAILURE;
4598           }
4599
4600       /* Fill in the upper bound, which may be lower than the
4601          specified one for something like a(2:10:5), which is
4602          identical to a(2:7:5).  Only relevant for strides not equal
4603          to one.  Don't try a division by zero.  */
4604       if (ar->dimen_type[i] == DIMEN_RANGE
4605           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4606           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0
4607           && mpz_cmp_si (ar->stride[i]->value.integer, 0L) != 0)
4608         {
4609           mpz_t size, end;
4610
4611           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4612             {
4613               if (ar->end[i] == NULL)
4614                 {
4615                   ar->end[i] =
4616                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4617                                            &ar->where);
4618                   mpz_set (ar->end[i]->value.integer, end);
4619                 }
4620               else if (ar->end[i]->ts.type == BT_INTEGER
4621                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4622                 {
4623                   mpz_set (ar->end[i]->value.integer, end);
4624                 }
4625               else
4626                 gcc_unreachable ();
4627
4628               mpz_clear (size);
4629               mpz_clear (end);
4630             }
4631         }
4632     }
4633
4634   if (ar->type == AR_FULL)
4635     {
4636       if (ar->as->rank == 0)
4637         ar->type = AR_ELEMENT;
4638
4639       /* Make sure array is the same as array(:,:), this way
4640          we don't need to special case all the time.  */
4641       ar->dimen = ar->as->rank;
4642       for (i = 0; i < ar->dimen; i++)
4643         {
4644           ar->dimen_type[i] = DIMEN_RANGE;
4645
4646           gcc_assert (ar->start[i] == NULL);
4647           gcc_assert (ar->end[i] == NULL);
4648           gcc_assert (ar->stride[i] == NULL);
4649         }
4650     }
4651
4652   /* If the reference type is unknown, figure out what kind it is.  */
4653
4654   if (ar->type == AR_UNKNOWN)
4655     {
4656       ar->type = AR_ELEMENT;
4657       for (i = 0; i < ar->dimen; i++)
4658         if (ar->dimen_type[i] == DIMEN_RANGE
4659             || ar->dimen_type[i] == DIMEN_VECTOR)
4660           {
4661             ar->type = AR_SECTION;
4662             break;
4663           }
4664     }
4665
4666   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4667     return FAILURE;
4668
4669   if (ar->as->corank && ar->codimen == 0)
4670     {
4671       int n;
4672       ar->codimen = ar->as->corank;
4673       for (n = ar->dimen; n < ar->dimen + ar->codimen; n++)
4674         ar->dimen_type[n] = DIMEN_THIS_IMAGE;
4675     }
4676
4677   return SUCCESS;
4678 }
4679
4680
4681 static gfc_try
4682 resolve_substring (gfc_ref *ref)
4683 {
4684   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4685
4686   if (ref->u.ss.start != NULL)
4687     {
4688       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4689         return FAILURE;
4690
4691       if (ref->u.ss.start->ts.type != BT_INTEGER)
4692         {
4693           gfc_error ("Substring start index at %L must be of type INTEGER",
4694                      &ref->u.ss.start->where);
4695           return FAILURE;
4696         }
4697
4698       if (ref->u.ss.start->rank != 0)
4699         {
4700           gfc_error ("Substring start index at %L must be scalar",
4701                      &ref->u.ss.start->where);
4702           return FAILURE;
4703         }
4704
4705       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4706           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4707               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4708         {
4709           gfc_error ("Substring start index at %L is less than one",
4710                      &ref->u.ss.start->where);
4711           return FAILURE;
4712         }
4713     }
4714
4715   if (ref->u.ss.end != NULL)
4716     {
4717       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4718         return FAILURE;
4719
4720       if (ref->u.ss.end->ts.type != BT_INTEGER)
4721         {
4722           gfc_error ("Substring end index at %L must be of type INTEGER",
4723                      &ref->u.ss.end->where);
4724           return FAILURE;
4725         }
4726
4727       if (ref->u.ss.end->rank != 0)
4728         {
4729           gfc_error ("Substring end index at %L must be scalar",
4730                      &ref->u.ss.end->where);
4731           return FAILURE;
4732         }
4733
4734       if (ref->u.ss.length != NULL
4735           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4736           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4737               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4738         {
4739           gfc_error ("Substring end index at %L exceeds the string length",
4740                      &ref->u.ss.start->where);
4741           return FAILURE;
4742         }
4743
4744       if (compare_bound_mpz_t (ref->u.ss.end,
4745                                gfc_integer_kinds[k].huge) == CMP_GT
4746           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4747               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4748         {
4749           gfc_error ("Substring end index at %L is too large",
4750                      &ref->u.ss.end->where);
4751           return FAILURE;
4752         }
4753     }
4754
4755   return SUCCESS;
4756 }
4757
4758
4759 /* This function supplies missing substring charlens.  */
4760
4761 void
4762 gfc_resolve_substring_charlen (gfc_expr *e)
4763 {
4764   gfc_ref *char_ref;
4765   gfc_expr *start, *end;
4766
4767   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4768     if (char_ref->type == REF_SUBSTRING)
4769       break;
4770
4771   if (!char_ref)
4772     return;
4773
4774   gcc_assert (char_ref->next == NULL);
4775
4776   if (e->ts.u.cl)
4777     {
4778       if (e->ts.u.cl->length)
4779         gfc_free_expr (e->ts.u.cl->length);
4780       else if (e->expr_type == EXPR_VARIABLE
4781                  && e->symtree->n.sym->attr.dummy)
4782         return;
4783     }
4784
4785   e->ts.type = BT_CHARACTER;
4786   e->ts.kind = gfc_default_character_kind;
4787
4788   if (!e->ts.u.cl)
4789     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4790
4791   if (char_ref->u.ss.start)
4792     start = gfc_copy_expr (char_ref->u.ss.start);
4793   else
4794     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4795
4796   if (char_ref->u.ss.end)
4797     end = gfc_copy_expr (char_ref->u.ss.end);
4798   else if (e->expr_type == EXPR_VARIABLE)
4799     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4800   else
4801     end = NULL;
4802
4803   if (!start || !end)
4804     return;
4805
4806   /* Length = (end - start +1).  */
4807   e->ts.u.cl->length = gfc_subtract (end, start);
4808   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4809                                 gfc_get_int_expr (gfc_default_integer_kind,
4810                                                   NULL, 1));
4811
4812   e->ts.u.cl->length->ts.type = BT_INTEGER;
4813   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4814
4815   /* Make sure that the length is simplified.  */
4816   gfc_simplify_expr (e->ts.u.cl->length, 1);
4817   gfc_resolve_expr (e->ts.u.cl->length);
4818 }
4819
4820
4821 /* Resolve subtype references.  */
4822
4823 static gfc_try
4824 resolve_ref (gfc_expr *expr)
4825 {
4826   int current_part_dimension, n_components, seen_part_dimension;
4827   gfc_ref *ref;
4828
4829   for (ref = expr->ref; ref; ref = ref->next)
4830     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4831       {
4832         find_array_spec (expr);
4833         break;
4834       }
4835
4836   for (ref = expr->ref; ref; ref = ref->next)
4837     switch (ref->type)
4838       {
4839       case REF_ARRAY:
4840         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4841           return FAILURE;
4842         break;
4843
4844       case REF_COMPONENT:
4845         break;
4846
4847       case REF_SUBSTRING:
4848         if (resolve_substring (ref) == FAILURE)
4849           return FAILURE;
4850         break;
4851       }
4852
4853   /* Check constraints on part references.  */
4854
4855   current_part_dimension = 0;
4856   seen_part_dimension = 0;
4857   n_components = 0;
4858
4859   for (ref = expr->ref; ref; ref = ref->next)
4860     {
4861       switch (ref->type)
4862         {
4863         case REF_ARRAY:
4864           switch (ref->u.ar.type)
4865             {
4866             case AR_FULL:
4867               /* Coarray scalar.  */
4868               if (ref->u.ar.as->rank == 0)
4869                 {
4870                   current_part_dimension = 0;
4871                   break;
4872                 }
4873               /* Fall through.  */
4874             case AR_SECTION:
4875               current_part_dimension = 1;
4876               break;
4877
4878             case AR_ELEMENT:
4879               current_part_dimension = 0;
4880               break;
4881
4882             case AR_UNKNOWN:
4883               gfc_internal_error ("resolve_ref(): Bad array reference");
4884             }
4885
4886           break;
4887
4888         case REF_COMPONENT:
4889           if (current_part_dimension || seen_part_dimension)
4890             {
4891               /* F03:C614.  */
4892               if (ref->u.c.component->attr.pointer
4893                   || ref->u.c.component->attr.proc_pointer)
4894                 {
4895                   gfc_error ("Component to the right of a part reference "
4896                              "with nonzero rank must not have the POINTER "
4897                              "attribute at %L", &expr->where);
4898                   return FAILURE;
4899                 }
4900               else if (ref->u.c.component->attr.allocatable)
4901                 {
4902                   gfc_error ("Component to the right of a part reference "
4903                              "with nonzero rank must not have the ALLOCATABLE "
4904                              "attribute at %L", &expr->where);
4905                   return FAILURE;
4906                 }
4907             }
4908
4909           n_components++;
4910           break;
4911
4912         case REF_SUBSTRING:
4913           break;
4914         }
4915
4916       if (((ref->type == REF_COMPONENT && n_components > 1)
4917            || ref->next == NULL)
4918           && current_part_dimension
4919           && seen_part_dimension)
4920         {
4921           gfc_error ("Two or more part references with nonzero rank must "
4922                      "not be specified at %L", &expr->where);
4923           return FAILURE;
4924         }
4925
4926       if (ref->type == REF_COMPONENT)
4927         {
4928           if (current_part_dimension)
4929             seen_part_dimension = 1;
4930
4931           /* reset to make sure */
4932           current_part_dimension = 0;
4933         }
4934     }
4935
4936   return SUCCESS;
4937 }
4938
4939
4940 /* Given an expression, determine its shape.  This is easier than it sounds.
4941    Leaves the shape array NULL if it is not possible to determine the shape.  */
4942
4943 static void
4944 expression_shape (gfc_expr *e)
4945 {
4946   mpz_t array[GFC_MAX_DIMENSIONS];
4947   int i;
4948
4949   if (e->rank == 0 || e->shape != NULL)
4950     return;
4951
4952   for (i = 0; i < e->rank; i++)
4953     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4954       goto fail;
4955
4956   e->shape = gfc_get_shape (e->rank);
4957
4958   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4959
4960   return;
4961
4962 fail:
4963   for (i--; i >= 0; i--)
4964     mpz_clear (array[i]);
4965 }
4966
4967
4968 /* Given a variable expression node, compute the rank of the expression by
4969    examining the base symbol and any reference structures it may have.  */
4970
4971 static void
4972 expression_rank (gfc_expr *e)
4973 {
4974   gfc_ref *ref;
4975   int i, rank;
4976
4977   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4978      could lead to serious confusion...  */
4979   gcc_assert (e->expr_type != EXPR_COMPCALL);
4980
4981   if (e->ref == NULL)
4982     {
4983       if (e->expr_type == EXPR_ARRAY)
4984         goto done;
4985       /* Constructors can have a rank different from one via RESHAPE().  */
4986
4987       if (e->symtree == NULL)
4988         {
4989           e->rank = 0;
4990           goto done;
4991         }
4992
4993       e->rank = (e->symtree->n.sym->as == NULL)
4994                 ? 0 : e->symtree->n.sym->as->rank;
4995       goto done;
4996     }
4997
4998   rank = 0;
4999
5000   for (ref = e->ref; ref; ref = ref->next)
5001     {
5002       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
5003           && ref->u.c.component->attr.function && !ref->next)
5004         rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
5005
5006       if (ref->type != REF_ARRAY)
5007         continue;
5008
5009       if (ref->u.ar.type == AR_FULL)
5010         {
5011           rank = ref->u.ar.as->rank;
5012           break;
5013         }
5014
5015       if (ref->u.ar.type == AR_SECTION)
5016         {
5017           /* Figure out the rank of the section.  */
5018           if (rank != 0)
5019             gfc_internal_error ("expression_rank(): Two array specs");
5020
5021           for (i = 0; i < ref->u.ar.dimen; i++)
5022             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
5023                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
5024               rank++;
5025
5026           break;
5027         }
5028     }
5029
5030   e->rank = rank;
5031
5032 done:
5033   expression_shape (e);
5034 }
5035
5036
5037 /* Resolve a variable expression.  */
5038
5039 static gfc_try
5040 resolve_variable (gfc_expr *e)
5041 {
5042   gfc_symbol *sym;
5043   gfc_try t;
5044
5045   t = SUCCESS;
5046
5047   if (e->symtree == NULL)
5048     return FAILURE;
5049   sym = e->symtree->n.sym;
5050
5051   /* If this is an associate-name, it may be parsed with an array reference
5052      in error even though the target is scalar.  Fail directly in this case.  */
5053   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
5054     return FAILURE;
5055
5056   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.generic)
5057     sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
5058
5059   /* On the other hand, the parser may not have known this is an array;
5060      in this case, we have to add a FULL reference.  */
5061   if (sym->assoc && sym->attr.dimension && !e->ref)
5062     {
5063       e->ref = gfc_get_ref ();
5064       e->ref->type = REF_ARRAY;
5065       e->ref->u.ar.type = AR_FULL;
5066       e->ref->u.ar.dimen = 0;
5067     }
5068
5069   if (e->ref && resolve_ref (e) == FAILURE)
5070     return FAILURE;
5071
5072   if (sym->attr.flavor == FL_PROCEDURE
5073       && (!sym->attr.function
5074           || (sym->attr.function && sym->result
5075               && sym->result->attr.proc_pointer
5076               && !sym->result->attr.function)))
5077     {
5078       e->ts.type = BT_PROCEDURE;
5079       goto resolve_procedure;
5080     }
5081
5082   if (sym->ts.type != BT_UNKNOWN)
5083     gfc_variable_attr (e, &e->ts);
5084   else
5085     {
5086       /* Must be a simple variable reference.  */
5087       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
5088         return FAILURE;
5089       e->ts = sym->ts;
5090     }
5091
5092   if (check_assumed_size_reference (sym, e))
5093     return FAILURE;
5094
5095   /* Deal with forward references to entries during resolve_code, to
5096      satisfy, at least partially, 12.5.2.5.  */
5097   if (gfc_current_ns->entries
5098       && current_entry_id == sym->entry_id
5099       && cs_base
5100       && cs_base->current
5101       && cs_base->current->op != EXEC_ENTRY)
5102     {
5103       gfc_entry_list *entry;
5104       gfc_formal_arglist *formal;
5105       int n;
5106       bool seen;
5107
5108       /* If the symbol is a dummy...  */
5109       if (sym->attr.dummy && sym->ns == gfc_current_ns)
5110         {
5111           entry = gfc_current_ns->entries;
5112           seen = false;
5113
5114           /* ...test if the symbol is a parameter of previous entries.  */
5115           for (; entry && entry->id <= current_entry_id; entry = entry->next)
5116             for (formal = entry->sym->formal; formal; formal = formal->next)
5117               {
5118                 if (formal->sym && sym->name == formal->sym->name)
5119                   seen = true;
5120               }
5121
5122           /*  If it has not been seen as a dummy, this is an error.  */
5123           if (!seen)
5124             {
5125               if (specification_expr)
5126                 gfc_error ("Variable '%s', used in a specification expression"
5127                            ", is referenced at %L before the ENTRY statement "
5128                            "in which it is a parameter",
5129                            sym->name, &cs_base->current->loc);
5130               else
5131                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5132                            "statement in which it is a parameter",
5133                            sym->name, &cs_base->current->loc);
5134               t = FAILURE;
5135             }
5136         }
5137
5138       /* Now do the same check on the specification expressions.  */
5139       specification_expr = 1;
5140       if (sym->ts.type == BT_CHARACTER
5141           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5142         t = FAILURE;
5143
5144       if (sym->as)
5145         for (n = 0; n < sym->as->rank; n++)
5146           {
5147              specification_expr = 1;
5148              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5149                t = FAILURE;
5150              specification_expr = 1;
5151              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5152                t = FAILURE;
5153           }
5154       specification_expr = 0;
5155
5156       if (t == SUCCESS)
5157         /* Update the symbol's entry level.  */
5158         sym->entry_id = current_entry_id + 1;
5159     }
5160
5161   /* If a symbol has been host_associated mark it.  This is used latter,
5162      to identify if aliasing is possible via host association.  */
5163   if (sym->attr.flavor == FL_VARIABLE
5164         && gfc_current_ns->parent
5165         && (gfc_current_ns->parent == sym->ns
5166               || (gfc_current_ns->parent->parent
5167                     && gfc_current_ns->parent->parent == sym->ns)))
5168     sym->attr.host_assoc = 1;
5169
5170 resolve_procedure:
5171   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5172     t = FAILURE;
5173
5174   /* F2008, C617 and C1229.  */
5175   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5176       && gfc_is_coindexed (e))
5177     {
5178       gfc_ref *ref, *ref2 = NULL;
5179
5180       for (ref = e->ref; ref; ref = ref->next)
5181         {
5182           if (ref->type == REF_COMPONENT)
5183             ref2 = ref;
5184           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5185             break;
5186         }
5187
5188       for ( ; ref; ref = ref->next)
5189         if (ref->type == REF_COMPONENT)
5190           break;
5191
5192       /* Expression itself is not coindexed object.  */
5193       if (ref && e->ts.type == BT_CLASS)
5194         {
5195           gfc_error ("Polymorphic subobject of coindexed object at %L",
5196                      &e->where);
5197           t = FAILURE;
5198         }
5199
5200       /* Expression itself is coindexed object.  */
5201       if (ref == NULL)
5202         {
5203           gfc_component *c;
5204           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5205           for ( ; c; c = c->next)
5206             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5207               {
5208                 gfc_error ("Coindexed object with polymorphic allocatable "
5209                          "subcomponent at %L", &e->where);
5210                 t = FAILURE;
5211                 break;
5212               }
5213         }
5214     }
5215
5216   return t;
5217 }
5218
5219
5220 /* Checks to see that the correct symbol has been host associated.
5221    The only situation where this arises is that in which a twice
5222    contained function is parsed after the host association is made.
5223    Therefore, on detecting this, change the symbol in the expression
5224    and convert the array reference into an actual arglist if the old
5225    symbol is a variable.  */
5226 static bool
5227 check_host_association (gfc_expr *e)
5228 {
5229   gfc_symbol *sym, *old_sym;
5230   gfc_symtree *st;
5231   int n;
5232   gfc_ref *ref;
5233   gfc_actual_arglist *arg, *tail = NULL;
5234   bool retval = e->expr_type == EXPR_FUNCTION;
5235
5236   /*  If the expression is the result of substitution in
5237       interface.c(gfc_extend_expr) because there is no way in
5238       which the host association can be wrong.  */
5239   if (e->symtree == NULL
5240         || e->symtree->n.sym == NULL
5241         || e->user_operator)
5242     return retval;
5243
5244   old_sym = e->symtree->n.sym;
5245
5246   if (gfc_current_ns->parent
5247         && old_sym->ns != gfc_current_ns)
5248     {
5249       /* Use the 'USE' name so that renamed module symbols are
5250          correctly handled.  */
5251       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5252
5253       if (sym && old_sym != sym
5254               && sym->ts.type == old_sym->ts.type
5255               && sym->attr.flavor == FL_PROCEDURE
5256               && sym->attr.contained)
5257         {
5258           /* Clear the shape, since it might not be valid.  */
5259           gfc_free_shape (&e->shape, e->rank);
5260
5261           /* Give the expression the right symtree!  */
5262           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5263           gcc_assert (st != NULL);
5264
5265           if (old_sym->attr.flavor == FL_PROCEDURE
5266                 || e->expr_type == EXPR_FUNCTION)
5267             {
5268               /* Original was function so point to the new symbol, since
5269                  the actual argument list is already attached to the
5270                  expression. */
5271               e->value.function.esym = NULL;
5272               e->symtree = st;
5273             }
5274           else
5275             {
5276               /* Original was variable so convert array references into
5277                  an actual arglist. This does not need any checking now
5278                  since resolve_function will take care of it.  */
5279               e->value.function.actual = NULL;
5280               e->expr_type = EXPR_FUNCTION;
5281               e->symtree = st;
5282
5283               /* Ambiguity will not arise if the array reference is not
5284                  the last reference.  */
5285               for (ref = e->ref; ref; ref = ref->next)
5286                 if (ref->type == REF_ARRAY && ref->next == NULL)
5287                   break;
5288
5289               gcc_assert (ref->type == REF_ARRAY);
5290
5291               /* Grab the start expressions from the array ref and
5292                  copy them into actual arguments.  */
5293               for (n = 0; n < ref->u.ar.dimen; n++)
5294                 {
5295                   arg = gfc_get_actual_arglist ();
5296                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5297                   if (e->value.function.actual == NULL)
5298                     tail = e->value.function.actual = arg;
5299                   else
5300                     {
5301                       tail->next = arg;
5302                       tail = arg;
5303                     }
5304                 }
5305
5306               /* Dump the reference list and set the rank.  */
5307               gfc_free_ref_list (e->ref);
5308               e->ref = NULL;
5309               e->rank = sym->as ? sym->as->rank : 0;
5310             }
5311
5312           gfc_resolve_expr (e);
5313           sym->refs++;
5314         }
5315     }
5316   /* This might have changed!  */
5317   return e->expr_type == EXPR_FUNCTION;
5318 }
5319
5320
5321 static void
5322 gfc_resolve_character_operator (gfc_expr *e)
5323 {
5324   gfc_expr *op1 = e->value.op.op1;
5325   gfc_expr *op2 = e->value.op.op2;
5326   gfc_expr *e1 = NULL;
5327   gfc_expr *e2 = NULL;
5328
5329   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5330
5331   if (op1->ts.u.cl && op1->ts.u.cl->length)
5332     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5333   else if (op1->expr_type == EXPR_CONSTANT)
5334     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5335                            op1->value.character.length);
5336
5337   if (op2->ts.u.cl && op2->ts.u.cl->length)
5338     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5339   else if (op2->expr_type == EXPR_CONSTANT)
5340     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5341                            op2->value.character.length);
5342
5343   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5344
5345   if (!e1 || !e2)
5346     return;
5347
5348   e->ts.u.cl->length = gfc_add (e1, e2);
5349   e->ts.u.cl->length->ts.type = BT_INTEGER;
5350   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5351   gfc_simplify_expr (e->ts.u.cl->length, 0);
5352   gfc_resolve_expr (e->ts.u.cl->length);
5353
5354   return;
5355 }
5356
5357
5358 /*  Ensure that an character expression has a charlen and, if possible, a
5359     length expression.  */
5360
5361 static void
5362 fixup_charlen (gfc_expr *e)
5363 {
5364   /* The cases fall through so that changes in expression type and the need
5365      for multiple fixes are picked up.  In all circumstances, a charlen should
5366      be available for the middle end to hang a backend_decl on.  */
5367   switch (e->expr_type)
5368     {
5369     case EXPR_OP:
5370       gfc_resolve_character_operator (e);
5371
5372     case EXPR_ARRAY:
5373       if (e->expr_type == EXPR_ARRAY)
5374         gfc_resolve_character_array_constructor (e);
5375
5376     case EXPR_SUBSTRING:
5377       if (!e->ts.u.cl && e->ref)
5378         gfc_resolve_substring_charlen (e);
5379
5380     default:
5381       if (!e->ts.u.cl)
5382         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5383
5384       break;
5385     }
5386 }
5387
5388
5389 /* Update an actual argument to include the passed-object for type-bound
5390    procedures at the right position.  */
5391
5392 static gfc_actual_arglist*
5393 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5394                      const char *name)
5395 {
5396   gcc_assert (argpos > 0);
5397
5398   if (argpos == 1)
5399     {
5400       gfc_actual_arglist* result;
5401
5402       result = gfc_get_actual_arglist ();
5403       result->expr = po;
5404       result->next = lst;
5405       if (name)
5406         result->name = name;
5407
5408       return result;
5409     }
5410
5411   if (lst)
5412     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5413   else
5414     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5415   return lst;
5416 }
5417
5418
5419 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5420
5421 static gfc_expr*
5422 extract_compcall_passed_object (gfc_expr* e)
5423 {
5424   gfc_expr* po;
5425
5426   gcc_assert (e->expr_type == EXPR_COMPCALL);
5427
5428   if (e->value.compcall.base_object)
5429     po = gfc_copy_expr (e->value.compcall.base_object);
5430   else
5431     {
5432       po = gfc_get_expr ();
5433       po->expr_type = EXPR_VARIABLE;
5434       po->symtree = e->symtree;
5435       po->ref = gfc_copy_ref (e->ref);
5436       po->where = e->where;
5437     }
5438
5439   if (gfc_resolve_expr (po) == FAILURE)
5440     return NULL;
5441
5442   return po;
5443 }
5444
5445
5446 /* Update the arglist of an EXPR_COMPCALL expression to include the
5447    passed-object.  */
5448
5449 static gfc_try
5450 update_compcall_arglist (gfc_expr* e)
5451 {
5452   gfc_expr* po;
5453   gfc_typebound_proc* tbp;
5454
5455   tbp = e->value.compcall.tbp;
5456
5457   if (tbp->error)
5458     return FAILURE;
5459
5460   po = extract_compcall_passed_object (e);
5461   if (!po)
5462     return FAILURE;
5463
5464   if (tbp->nopass || e->value.compcall.ignore_pass)
5465     {
5466       gfc_free_expr (po);
5467       return SUCCESS;
5468     }
5469
5470   gcc_assert (tbp->pass_arg_num > 0);
5471   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5472                                                   tbp->pass_arg_num,
5473                                                   tbp->pass_arg);
5474
5475   return SUCCESS;
5476 }
5477
5478
5479 /* Extract the passed object from a PPC call (a copy of it).  */
5480
5481 static gfc_expr*
5482 extract_ppc_passed_object (gfc_expr *e)
5483 {
5484   gfc_expr *po;
5485   gfc_ref **ref;
5486
5487   po = gfc_get_expr ();
5488   po->expr_type = EXPR_VARIABLE;
5489   po->symtree = e->symtree;
5490   po->ref = gfc_copy_ref (e->ref);
5491   po->where = e->where;
5492
5493   /* Remove PPC reference.  */
5494   ref = &po->ref;
5495   while ((*ref)->next)
5496     ref = &(*ref)->next;
5497   gfc_free_ref_list (*ref);
5498   *ref = NULL;
5499
5500   if (gfc_resolve_expr (po) == FAILURE)
5501     return NULL;
5502
5503   return po;
5504 }
5505
5506
5507 /* Update the actual arglist of a procedure pointer component to include the
5508    passed-object.  */
5509
5510 static gfc_try
5511 update_ppc_arglist (gfc_expr* e)
5512 {
5513   gfc_expr* po;
5514   gfc_component *ppc;
5515   gfc_typebound_proc* tb;
5516
5517   if (!gfc_is_proc_ptr_comp (e, &ppc))
5518     return FAILURE;
5519
5520   tb = ppc->tb;
5521
5522   if (tb->error)
5523     return FAILURE;
5524   else if (tb->nopass)
5525     return SUCCESS;
5526
5527   po = extract_ppc_passed_object (e);
5528   if (!po)
5529     return FAILURE;
5530
5531   /* F08:R739.  */
5532   if (po->rank > 0)
5533     {
5534       gfc_error ("Passed-object at %L must be scalar", &e->where);
5535       return FAILURE;
5536     }
5537
5538   /* F08:C611.  */
5539   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
5540     {
5541       gfc_error ("Base object for procedure-pointer component call at %L is of"
5542                  " ABSTRACT type '%s'", &e->where, po->ts.u.derived->name);
5543       return FAILURE;
5544     }
5545
5546   gcc_assert (tb->pass_arg_num > 0);
5547   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5548                                                   tb->pass_arg_num,
5549                                                   tb->pass_arg);
5550
5551   return SUCCESS;
5552 }
5553
5554
5555 /* Check that the object a TBP is called on is valid, i.e. it must not be
5556    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5557
5558 static gfc_try
5559 check_typebound_baseobject (gfc_expr* e)
5560 {
5561   gfc_expr* base;
5562   gfc_try return_value = FAILURE;
5563
5564   base = extract_compcall_passed_object (e);
5565   if (!base)
5566     return FAILURE;
5567
5568   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5569
5570   /* F08:C611.  */
5571   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5572     {
5573       gfc_error ("Base object for type-bound procedure call at %L is of"
5574                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5575       goto cleanup;
5576     }
5577
5578   /* F08:C1230. If the procedure called is NOPASS,
5579      the base object must be scalar.  */
5580   if (e->value.compcall.tbp->nopass && base->rank > 0)
5581     {
5582       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5583                  " be scalar", &e->where);
5584       goto cleanup;
5585     }
5586
5587   return_value = SUCCESS;
5588
5589 cleanup:
5590   gfc_free_expr (base);
5591   return return_value;
5592 }
5593
5594
5595 /* Resolve a call to a type-bound procedure, either function or subroutine,
5596    statically from the data in an EXPR_COMPCALL expression.  The adapted
5597    arglist and the target-procedure symtree are returned.  */
5598
5599 static gfc_try
5600 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5601                           gfc_actual_arglist** actual)
5602 {
5603   gcc_assert (e->expr_type == EXPR_COMPCALL);
5604   gcc_assert (!e->value.compcall.tbp->is_generic);
5605
5606   /* Update the actual arglist for PASS.  */
5607   if (update_compcall_arglist (e) == FAILURE)
5608     return FAILURE;
5609
5610   *actual = e->value.compcall.actual;
5611   *target = e->value.compcall.tbp->u.specific;
5612
5613   gfc_free_ref_list (e->ref);
5614   e->ref = NULL;
5615   e->value.compcall.actual = NULL;
5616
5617   return SUCCESS;
5618 }
5619
5620
5621 /* Get the ultimate declared type from an expression.  In addition,
5622    return the last class/derived type reference and the copy of the
5623    reference list.  */
5624 static gfc_symbol*
5625 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5626                         gfc_expr *e)
5627 {
5628   gfc_symbol *declared;
5629   gfc_ref *ref;
5630
5631   declared = NULL;
5632   if (class_ref)
5633     *class_ref = NULL;
5634   if (new_ref)
5635     *new_ref = gfc_copy_ref (e->ref);
5636
5637   for (ref = e->ref; ref; ref = ref->next)
5638     {
5639       if (ref->type != REF_COMPONENT)
5640         continue;
5641
5642       if (ref->u.c.component->ts.type == BT_CLASS
5643             || ref->u.c.component->ts.type == BT_DERIVED)
5644         {
5645           declared = ref->u.c.component->ts.u.derived;
5646           if (class_ref)
5647             *class_ref = ref;
5648         }
5649     }
5650
5651   if (declared == NULL)
5652     declared = e->symtree->n.sym->ts.u.derived;
5653
5654   return declared;
5655 }
5656
5657
5658 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5659    which of the specific bindings (if any) matches the arglist and transform
5660    the expression into a call of that binding.  */
5661
5662 static gfc_try
5663 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5664 {
5665   gfc_typebound_proc* genproc;
5666   const char* genname;
5667   gfc_symtree *st;
5668   gfc_symbol *derived;
5669
5670   gcc_assert (e->expr_type == EXPR_COMPCALL);
5671   genname = e->value.compcall.name;
5672   genproc = e->value.compcall.tbp;
5673
5674   if (!genproc->is_generic)
5675     return SUCCESS;
5676
5677   /* Try the bindings on this type and in the inheritance hierarchy.  */
5678   for (; genproc; genproc = genproc->overridden)
5679     {
5680       gfc_tbp_generic* g;
5681
5682       gcc_assert (genproc->is_generic);
5683       for (g = genproc->u.generic; g; g = g->next)
5684         {
5685           gfc_symbol* target;
5686           gfc_actual_arglist* args;
5687           bool matches;
5688
5689           gcc_assert (g->specific);
5690
5691           if (g->specific->error)
5692             continue;
5693
5694           target = g->specific->u.specific->n.sym;
5695
5696           /* Get the right arglist by handling PASS/NOPASS.  */
5697           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5698           if (!g->specific->nopass)
5699             {
5700               gfc_expr* po;
5701               po = extract_compcall_passed_object (e);
5702               if (!po)
5703                 return FAILURE;
5704
5705               gcc_assert (g->specific->pass_arg_num > 0);
5706               gcc_assert (!g->specific->error);
5707               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5708                                           g->specific->pass_arg);
5709             }
5710           resolve_actual_arglist (args, target->attr.proc,
5711                                   is_external_proc (target) && !target->formal);
5712
5713           /* Check if this arglist matches the formal.  */
5714           matches = gfc_arglist_matches_symbol (&args, target);
5715
5716           /* Clean up and break out of the loop if we've found it.  */
5717           gfc_free_actual_arglist (args);
5718           if (matches)
5719             {
5720               e->value.compcall.tbp = g->specific;
5721               genname = g->specific_st->name;
5722               /* Pass along the name for CLASS methods, where the vtab
5723                  procedure pointer component has to be referenced.  */
5724               if (name)
5725                 *name = genname;
5726               goto success;
5727             }
5728         }
5729     }
5730
5731   /* Nothing matching found!  */
5732   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5733              " '%s' at %L", genname, &e->where);
5734   return FAILURE;
5735
5736 success:
5737   /* Make sure that we have the right specific instance for the name.  */
5738   derived = get_declared_from_expr (NULL, NULL, e);
5739
5740   st = gfc_find_typebound_proc (derived, NULL, genname, true, &e->where);
5741   if (st)
5742     e->value.compcall.tbp = st->n.tb;
5743
5744   return SUCCESS;
5745 }
5746
5747
5748 /* Resolve a call to a type-bound subroutine.  */
5749
5750 static gfc_try
5751 resolve_typebound_call (gfc_code* c, const char **name)
5752 {
5753   gfc_actual_arglist* newactual;
5754   gfc_symtree* target;
5755
5756   /* Check that's really a SUBROUTINE.  */
5757   if (!c->expr1->value.compcall.tbp->subroutine)
5758     {
5759       gfc_error ("'%s' at %L should be a SUBROUTINE",
5760                  c->expr1->value.compcall.name, &c->loc);
5761       return FAILURE;
5762     }
5763
5764   if (check_typebound_baseobject (c->expr1) == FAILURE)
5765     return FAILURE;
5766
5767   /* Pass along the name for CLASS methods, where the vtab
5768      procedure pointer component has to be referenced.  */
5769   if (name)
5770     *name = c->expr1->value.compcall.name;
5771
5772   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5773     return FAILURE;
5774
5775   /* Transform into an ordinary EXEC_CALL for now.  */
5776
5777   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5778     return FAILURE;
5779
5780   c->ext.actual = newactual;
5781   c->symtree = target;
5782   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5783
5784   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5785
5786   gfc_free_expr (c->expr1);
5787   c->expr1 = gfc_get_expr ();
5788   c->expr1->expr_type = EXPR_FUNCTION;
5789   c->expr1->symtree = target;
5790   c->expr1->where = c->loc;
5791
5792   return resolve_call (c);
5793 }
5794
5795
5796 /* Resolve a component-call expression.  */
5797 static gfc_try
5798 resolve_compcall (gfc_expr* e, const char **name)
5799 {
5800   gfc_actual_arglist* newactual;
5801   gfc_symtree* target;
5802
5803   /* Check that's really a FUNCTION.  */
5804   if (!e->value.compcall.tbp->function)
5805     {
5806       gfc_error ("'%s' at %L should be a FUNCTION",
5807                  e->value.compcall.name, &e->where);
5808       return FAILURE;
5809     }
5810
5811   /* These must not be assign-calls!  */
5812   gcc_assert (!e->value.compcall.assign);
5813
5814   if (check_typebound_baseobject (e) == FAILURE)
5815     return FAILURE;
5816
5817   /* Pass along the name for CLASS methods, where the vtab
5818      procedure pointer component has to be referenced.  */
5819   if (name)
5820     *name = e->value.compcall.name;
5821
5822   if (resolve_typebound_generic_call (e, name) == FAILURE)
5823     return FAILURE;
5824   gcc_assert (!e->value.compcall.tbp->is_generic);
5825
5826   /* Take the rank from the function's symbol.  */
5827   if (e->value.compcall.tbp->u.specific->n.sym->as)
5828     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5829
5830   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5831      arglist to the TBP's binding target.  */
5832
5833   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5834     return FAILURE;
5835
5836   e->value.function.actual = newactual;
5837   e->value.function.name = NULL;
5838   e->value.function.esym = target->n.sym;
5839   e->value.function.isym = NULL;
5840   e->symtree = target;
5841   e->ts = target->n.sym->ts;
5842   e->expr_type = EXPR_FUNCTION;
5843
5844   /* Resolution is not necessary if this is a class subroutine; this
5845      function only has to identify the specific proc. Resolution of
5846      the call will be done next in resolve_typebound_call.  */
5847   return gfc_resolve_expr (e);
5848 }
5849
5850
5851
5852 /* Resolve a typebound function, or 'method'. First separate all
5853    the non-CLASS references by calling resolve_compcall directly.  */
5854
5855 static gfc_try
5856 resolve_typebound_function (gfc_expr* e)
5857 {
5858   gfc_symbol *declared;
5859   gfc_component *c;
5860   gfc_ref *new_ref;
5861   gfc_ref *class_ref;
5862   gfc_symtree *st;
5863   const char *name;
5864   gfc_typespec ts;
5865   gfc_expr *expr;
5866   bool overridable;
5867
5868   st = e->symtree;
5869
5870   /* Deal with typebound operators for CLASS objects.  */
5871   expr = e->value.compcall.base_object;
5872   overridable = !e->value.compcall.tbp->non_overridable;
5873   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
5874     {
5875       /* Since the typebound operators are generic, we have to ensure
5876          that any delays in resolution are corrected and that the vtab
5877          is present.  */
5878       ts = expr->ts;
5879       declared = ts.u.derived;
5880       c = gfc_find_component (declared, "_vptr", true, true);
5881       if (c->ts.u.derived == NULL)
5882         c->ts.u.derived = gfc_find_derived_vtab (declared);
5883
5884       if (resolve_compcall (e, &name) == FAILURE)
5885         return FAILURE;
5886
5887       /* Use the generic name if it is there.  */
5888       name = name ? name : e->value.function.esym->name;
5889       e->symtree = expr->symtree;
5890       e->ref = gfc_copy_ref (expr->ref);
5891       gfc_add_vptr_component (e);
5892       gfc_add_component_ref (e, name);
5893       e->value.function.esym = NULL;
5894       return SUCCESS;
5895     }
5896
5897   if (st == NULL)
5898     return resolve_compcall (e, NULL);
5899
5900   if (resolve_ref (e) == FAILURE)
5901     return FAILURE;
5902
5903   /* Get the CLASS declared type.  */
5904   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5905
5906   /* Weed out cases of the ultimate component being a derived type.  */
5907   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5908          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5909     {
5910       gfc_free_ref_list (new_ref);
5911       return resolve_compcall (e, NULL);
5912     }
5913
5914   c = gfc_find_component (declared, "_data", true, true);
5915   declared = c->ts.u.derived;
5916
5917   /* Treat the call as if it is a typebound procedure, in order to roll
5918      out the correct name for the specific function.  */
5919   if (resolve_compcall (e, &name) == FAILURE)
5920     return FAILURE;
5921   ts = e->ts;
5922
5923   if (overridable)
5924     {
5925       /* Convert the expression to a procedure pointer component call.  */
5926       e->value.function.esym = NULL;
5927       e->symtree = st;
5928
5929       if (new_ref)  
5930         e->ref = new_ref;
5931
5932       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5933       gfc_add_vptr_component (e);
5934       gfc_add_component_ref (e, name);
5935
5936       /* Recover the typespec for the expression.  This is really only
5937         necessary for generic procedures, where the additional call
5938         to gfc_add_component_ref seems to throw the collection of the
5939         correct typespec.  */
5940       e->ts = ts;
5941     }
5942
5943   return SUCCESS;
5944 }
5945
5946 /* Resolve a typebound subroutine, or 'method'. First separate all
5947    the non-CLASS references by calling resolve_typebound_call
5948    directly.  */
5949
5950 static gfc_try
5951 resolve_typebound_subroutine (gfc_code *code)
5952 {
5953   gfc_symbol *declared;
5954   gfc_component *c;
5955   gfc_ref *new_ref;
5956   gfc_ref *class_ref;
5957   gfc_symtree *st;
5958   const char *name;
5959   gfc_typespec ts;
5960   gfc_expr *expr;
5961   bool overridable;
5962
5963   st = code->expr1->symtree;
5964
5965   /* Deal with typebound operators for CLASS objects.  */
5966   expr = code->expr1->value.compcall.base_object;
5967   overridable = !code->expr1->value.compcall.tbp->non_overridable;
5968   if (expr && expr->ts.type == BT_CLASS && code->expr1->value.compcall.name)
5969     {
5970       /* Since the typebound operators are generic, we have to ensure
5971          that any delays in resolution are corrected and that the vtab
5972          is present.  */
5973       declared = expr->ts.u.derived;
5974       c = gfc_find_component (declared, "_vptr", true, true);
5975       if (c->ts.u.derived == NULL)
5976         c->ts.u.derived = gfc_find_derived_vtab (declared);
5977
5978       if (resolve_typebound_call (code, &name) == FAILURE)
5979         return FAILURE;
5980
5981       /* Use the generic name if it is there.  */
5982       name = name ? name : code->expr1->value.function.esym->name;
5983       code->expr1->symtree = expr->symtree;
5984       code->expr1->ref = gfc_copy_ref (expr->ref);
5985       gfc_add_vptr_component (code->expr1);
5986       gfc_add_component_ref (code->expr1, name);
5987       code->expr1->value.function.esym = NULL;
5988       return SUCCESS;
5989     }
5990
5991   if (st == NULL)
5992     return resolve_typebound_call (code, NULL);
5993
5994   if (resolve_ref (code->expr1) == FAILURE)
5995     return FAILURE;
5996
5997   /* Get the CLASS declared type.  */
5998   get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5999
6000   /* Weed out cases of the ultimate component being a derived type.  */
6001   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
6002          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
6003     {
6004       gfc_free_ref_list (new_ref);
6005       return resolve_typebound_call (code, NULL);
6006     }
6007
6008   if (resolve_typebound_call (code, &name) == FAILURE)
6009     return FAILURE;
6010   ts = code->expr1->ts;
6011
6012   if (overridable)
6013     {
6014       /* Convert the expression to a procedure pointer component call.  */
6015       code->expr1->value.function.esym = NULL;
6016       code->expr1->symtree = st;
6017
6018       if (new_ref)
6019         code->expr1->ref = new_ref;
6020
6021       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
6022       gfc_add_vptr_component (code->expr1);
6023       gfc_add_component_ref (code->expr1, name);
6024
6025       /* Recover the typespec for the expression.  This is really only
6026         necessary for generic procedures, where the additional call
6027         to gfc_add_component_ref seems to throw the collection of the
6028         correct typespec.  */
6029       code->expr1->ts = ts;
6030     }
6031
6032   return SUCCESS;
6033 }
6034
6035
6036 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
6037
6038 static gfc_try
6039 resolve_ppc_call (gfc_code* c)
6040 {
6041   gfc_component *comp;
6042   bool b;
6043
6044   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
6045   gcc_assert (b);
6046
6047   c->resolved_sym = c->expr1->symtree->n.sym;
6048   c->expr1->expr_type = EXPR_VARIABLE;
6049
6050   if (!comp->attr.subroutine)
6051     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
6052
6053   if (resolve_ref (c->expr1) == FAILURE)
6054     return FAILURE;
6055
6056   if (update_ppc_arglist (c->expr1) == FAILURE)
6057     return FAILURE;
6058
6059   c->ext.actual = c->expr1->value.compcall.actual;
6060
6061   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
6062                               comp->formal == NULL) == FAILURE)
6063     return FAILURE;
6064
6065   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
6066
6067   return SUCCESS;
6068 }
6069
6070
6071 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
6072
6073 static gfc_try
6074 resolve_expr_ppc (gfc_expr* e)
6075 {
6076   gfc_component *comp;
6077   bool b;
6078
6079   b = gfc_is_proc_ptr_comp (e, &comp);
6080   gcc_assert (b);
6081
6082   /* Convert to EXPR_FUNCTION.  */
6083   e->expr_type = EXPR_FUNCTION;
6084   e->value.function.isym = NULL;
6085   e->value.function.actual = e->value.compcall.actual;
6086   e->ts = comp->ts;
6087   if (comp->as != NULL)
6088     e->rank = comp->as->rank;
6089
6090   if (!comp->attr.function)
6091     gfc_add_function (&comp->attr, comp->name, &e->where);
6092
6093   if (resolve_ref (e) == FAILURE)
6094     return FAILURE;
6095
6096   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
6097                               comp->formal == NULL) == FAILURE)
6098     return FAILURE;
6099
6100   if (update_ppc_arglist (e) == FAILURE)
6101     return FAILURE;
6102
6103   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6104
6105   return SUCCESS;
6106 }
6107
6108
6109 static bool
6110 gfc_is_expandable_expr (gfc_expr *e)
6111 {
6112   gfc_constructor *con;
6113
6114   if (e->expr_type == EXPR_ARRAY)
6115     {
6116       /* Traverse the constructor looking for variables that are flavor
6117          parameter.  Parameters must be expanded since they are fully used at
6118          compile time.  */
6119       con = gfc_constructor_first (e->value.constructor);
6120       for (; con; con = gfc_constructor_next (con))
6121         {
6122           if (con->expr->expr_type == EXPR_VARIABLE
6123               && con->expr->symtree
6124               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6125               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6126             return true;
6127           if (con->expr->expr_type == EXPR_ARRAY
6128               && gfc_is_expandable_expr (con->expr))
6129             return true;
6130         }
6131     }
6132
6133   return false;
6134 }
6135
6136 /* Resolve an expression.  That is, make sure that types of operands agree
6137    with their operators, intrinsic operators are converted to function calls
6138    for overloaded types and unresolved function references are resolved.  */
6139
6140 gfc_try
6141 gfc_resolve_expr (gfc_expr *e)
6142 {
6143   gfc_try t;
6144   bool inquiry_save;
6145
6146   if (e == NULL)
6147     return SUCCESS;
6148
6149   /* inquiry_argument only applies to variables.  */
6150   inquiry_save = inquiry_argument;
6151   if (e->expr_type != EXPR_VARIABLE)
6152     inquiry_argument = false;
6153
6154   switch (e->expr_type)
6155     {
6156     case EXPR_OP:
6157       t = resolve_operator (e);
6158       break;
6159
6160     case EXPR_FUNCTION:
6161     case EXPR_VARIABLE:
6162
6163       if (check_host_association (e))
6164         t = resolve_function (e);
6165       else
6166         {
6167           t = resolve_variable (e);
6168           if (t == SUCCESS)
6169             expression_rank (e);
6170         }
6171
6172       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6173           && e->ref->type != REF_SUBSTRING)
6174         gfc_resolve_substring_charlen (e);
6175
6176       break;
6177
6178     case EXPR_COMPCALL:
6179       t = resolve_typebound_function (e);
6180       break;
6181
6182     case EXPR_SUBSTRING:
6183       t = resolve_ref (e);
6184       break;
6185
6186     case EXPR_CONSTANT:
6187     case EXPR_NULL:
6188       t = SUCCESS;
6189       break;
6190
6191     case EXPR_PPC:
6192       t = resolve_expr_ppc (e);
6193       break;
6194
6195     case EXPR_ARRAY:
6196       t = FAILURE;
6197       if (resolve_ref (e) == FAILURE)
6198         break;
6199
6200       t = gfc_resolve_array_constructor (e);
6201       /* Also try to expand a constructor.  */
6202       if (t == SUCCESS)
6203         {
6204           expression_rank (e);
6205           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6206             gfc_expand_constructor (e, false);
6207         }
6208
6209       /* This provides the opportunity for the length of constructors with
6210          character valued function elements to propagate the string length
6211          to the expression.  */
6212       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6213         {
6214           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6215              here rather then add a duplicate test for it above.  */ 
6216           gfc_expand_constructor (e, false);
6217           t = gfc_resolve_character_array_constructor (e);
6218         }
6219
6220       break;
6221
6222     case EXPR_STRUCTURE:
6223       t = resolve_ref (e);
6224       if (t == FAILURE)
6225         break;
6226
6227       t = resolve_structure_cons (e, 0);
6228       if (t == FAILURE)
6229         break;
6230
6231       t = gfc_simplify_expr (e, 0);
6232       break;
6233
6234     default:
6235       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6236     }
6237
6238   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6239     fixup_charlen (e);
6240
6241   inquiry_argument = inquiry_save;
6242
6243   return t;
6244 }
6245
6246
6247 /* Resolve an expression from an iterator.  They must be scalar and have
6248    INTEGER or (optionally) REAL type.  */
6249
6250 static gfc_try
6251 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6252                            const char *name_msgid)
6253 {
6254   if (gfc_resolve_expr (expr) == FAILURE)
6255     return FAILURE;
6256
6257   if (expr->rank != 0)
6258     {
6259       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6260       return FAILURE;
6261     }
6262
6263   if (expr->ts.type != BT_INTEGER)
6264     {
6265       if (expr->ts.type == BT_REAL)
6266         {
6267           if (real_ok)
6268             return gfc_notify_std (GFC_STD_F95_DEL,
6269                                    "Deleted feature: %s at %L must be integer",
6270                                    _(name_msgid), &expr->where);
6271           else
6272             {
6273               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6274                          &expr->where);
6275               return FAILURE;
6276             }
6277         }
6278       else
6279         {
6280           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6281           return FAILURE;
6282         }
6283     }
6284   return SUCCESS;
6285 }
6286
6287
6288 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6289    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6290
6291 gfc_try
6292 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6293 {
6294   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6295       == FAILURE)
6296     return FAILURE;
6297
6298   if (gfc_check_vardef_context (iter->var, false, false, _("iterator variable"))
6299       == FAILURE)
6300     return FAILURE;
6301
6302   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6303                                  "Start expression in DO loop") == FAILURE)
6304     return FAILURE;
6305
6306   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6307                                  "End expression in DO loop") == FAILURE)
6308     return FAILURE;
6309
6310   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6311                                  "Step expression in DO loop") == FAILURE)
6312     return FAILURE;
6313
6314   if (iter->step->expr_type == EXPR_CONSTANT)
6315     {
6316       if ((iter->step->ts.type == BT_INTEGER
6317            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6318           || (iter->step->ts.type == BT_REAL
6319               && mpfr_sgn (iter->step->value.real) == 0))
6320         {
6321           gfc_error ("Step expression in DO loop at %L cannot be zero",
6322                      &iter->step->where);
6323           return FAILURE;
6324         }
6325     }
6326
6327   /* Convert start, end, and step to the same type as var.  */
6328   if (iter->start->ts.kind != iter->var->ts.kind
6329       || iter->start->ts.type != iter->var->ts.type)
6330     gfc_convert_type (iter->start, &iter->var->ts, 2);
6331
6332   if (iter->end->ts.kind != iter->var->ts.kind
6333       || iter->end->ts.type != iter->var->ts.type)
6334     gfc_convert_type (iter->end, &iter->var->ts, 2);
6335
6336   if (iter->step->ts.kind != iter->var->ts.kind
6337       || iter->step->ts.type != iter->var->ts.type)
6338     gfc_convert_type (iter->step, &iter->var->ts, 2);
6339
6340   if (iter->start->expr_type == EXPR_CONSTANT
6341       && iter->end->expr_type == EXPR_CONSTANT
6342       && iter->step->expr_type == EXPR_CONSTANT)
6343     {
6344       int sgn, cmp;
6345       if (iter->start->ts.type == BT_INTEGER)
6346         {
6347           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6348           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6349         }
6350       else
6351         {
6352           sgn = mpfr_sgn (iter->step->value.real);
6353           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6354         }
6355       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6356         gfc_warning ("DO loop at %L will be executed zero times",
6357                      &iter->step->where);
6358     }
6359
6360   return SUCCESS;
6361 }
6362
6363
6364 /* Traversal function for find_forall_index.  f == 2 signals that
6365    that variable itself is not to be checked - only the references.  */
6366
6367 static bool
6368 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6369 {
6370   if (expr->expr_type != EXPR_VARIABLE)
6371     return false;
6372   
6373   /* A scalar assignment  */
6374   if (!expr->ref || *f == 1)
6375     {
6376       if (expr->symtree->n.sym == sym)
6377         return true;
6378       else
6379         return false;
6380     }
6381
6382   if (*f == 2)
6383     *f = 1;
6384   return false;
6385 }
6386
6387
6388 /* Check whether the FORALL index appears in the expression or not.
6389    Returns SUCCESS if SYM is found in EXPR.  */
6390
6391 gfc_try
6392 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6393 {
6394   if (gfc_traverse_expr (expr, sym, forall_index, f))
6395     return SUCCESS;
6396   else
6397     return FAILURE;
6398 }
6399
6400
6401 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6402    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6403    INTEGERs, and if stride is a constant it must be nonzero.
6404    Furthermore "A subscript or stride in a forall-triplet-spec shall
6405    not contain a reference to any index-name in the
6406    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6407
6408 static void
6409 resolve_forall_iterators (gfc_forall_iterator *it)
6410 {
6411   gfc_forall_iterator *iter, *iter2;
6412
6413   for (iter = it; iter; iter = iter->next)
6414     {
6415       if (gfc_resolve_expr (iter->var) == SUCCESS
6416           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6417         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6418                    &iter->var->where);
6419
6420       if (gfc_resolve_expr (iter->start) == SUCCESS
6421           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6422         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6423                    &iter->start->where);
6424       if (iter->var->ts.kind != iter->start->ts.kind)
6425         gfc_convert_type (iter->start, &iter->var->ts, 1);
6426
6427       if (gfc_resolve_expr (iter->end) == SUCCESS
6428           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6429         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6430                    &iter->end->where);
6431       if (iter->var->ts.kind != iter->end->ts.kind)
6432         gfc_convert_type (iter->end, &iter->var->ts, 1);
6433
6434       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6435         {
6436           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6437             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6438                        &iter->stride->where, "INTEGER");
6439
6440           if (iter->stride->expr_type == EXPR_CONSTANT
6441               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6442             gfc_error ("FORALL stride expression at %L cannot be zero",
6443                        &iter->stride->where);
6444         }
6445       if (iter->var->ts.kind != iter->stride->ts.kind)
6446         gfc_convert_type (iter->stride, &iter->var->ts, 1);
6447     }
6448
6449   for (iter = it; iter; iter = iter->next)
6450     for (iter2 = iter; iter2; iter2 = iter2->next)
6451       {
6452         if (find_forall_index (iter2->start,
6453                                iter->var->symtree->n.sym, 0) == SUCCESS
6454             || find_forall_index (iter2->end,
6455                                   iter->var->symtree->n.sym, 0) == SUCCESS
6456             || find_forall_index (iter2->stride,
6457                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6458           gfc_error ("FORALL index '%s' may not appear in triplet "
6459                      "specification at %L", iter->var->symtree->name,
6460                      &iter2->start->where);
6461       }
6462 }
6463
6464
6465 /* Given a pointer to a symbol that is a derived type, see if it's
6466    inaccessible, i.e. if it's defined in another module and the components are
6467    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6468    inaccessible components are found, nonzero otherwise.  */
6469
6470 static int
6471 derived_inaccessible (gfc_symbol *sym)
6472 {
6473   gfc_component *c;
6474
6475   if (sym->attr.use_assoc && sym->attr.private_comp)
6476     return 1;
6477
6478   for (c = sym->components; c; c = c->next)
6479     {
6480         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6481           return 1;
6482     }
6483
6484   return 0;
6485 }
6486
6487
6488 /* Resolve the argument of a deallocate expression.  The expression must be
6489    a pointer or a full array.  */
6490
6491 static gfc_try
6492 resolve_deallocate_expr (gfc_expr *e)
6493 {
6494   symbol_attribute attr;
6495   int allocatable, pointer;
6496   gfc_ref *ref;
6497   gfc_symbol *sym;
6498   gfc_component *c;
6499
6500   if (gfc_resolve_expr (e) == FAILURE)
6501     return FAILURE;
6502
6503   if (e->expr_type != EXPR_VARIABLE)
6504     goto bad;
6505
6506   sym = e->symtree->n.sym;
6507
6508   if (sym->ts.type == BT_CLASS)
6509     {
6510       allocatable = CLASS_DATA (sym)->attr.allocatable;
6511       pointer = CLASS_DATA (sym)->attr.class_pointer;
6512     }
6513   else
6514     {
6515       allocatable = sym->attr.allocatable;
6516       pointer = sym->attr.pointer;
6517     }
6518   for (ref = e->ref; ref; ref = ref->next)
6519     {
6520       switch (ref->type)
6521         {
6522         case REF_ARRAY:
6523           if (ref->u.ar.type != AR_FULL
6524               && !(ref->u.ar.type == AR_ELEMENT && ref->u.ar.as->rank == 0
6525                    && ref->u.ar.codimen && gfc_ref_this_image (ref)))
6526             allocatable = 0;
6527           break;
6528
6529         case REF_COMPONENT:
6530           c = ref->u.c.component;
6531           if (c->ts.type == BT_CLASS)
6532             {
6533               allocatable = CLASS_DATA (c)->attr.allocatable;
6534               pointer = CLASS_DATA (c)->attr.class_pointer;
6535             }
6536           else
6537             {
6538               allocatable = c->attr.allocatable;
6539               pointer = c->attr.pointer;
6540             }
6541           break;
6542
6543         case REF_SUBSTRING:
6544           allocatable = 0;
6545           break;
6546         }
6547     }
6548
6549   attr = gfc_expr_attr (e);
6550
6551   if (allocatable == 0 && attr.pointer == 0)
6552     {
6553     bad:
6554       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6555                  &e->where);
6556       return FAILURE;
6557     }
6558
6559   /* F2008, C644.  */
6560   if (gfc_is_coindexed (e))
6561     {
6562       gfc_error ("Coindexed allocatable object at %L", &e->where);
6563       return FAILURE;
6564     }
6565
6566   if (pointer
6567       && gfc_check_vardef_context (e, true, true, _("DEALLOCATE object"))
6568          == FAILURE)
6569     return FAILURE;
6570   if (gfc_check_vardef_context (e, false, true, _("DEALLOCATE object"))
6571       == FAILURE)
6572     return FAILURE;
6573
6574   return SUCCESS;
6575 }
6576
6577
6578 /* Returns true if the expression e contains a reference to the symbol sym.  */
6579 static bool
6580 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6581 {
6582   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6583     return true;
6584
6585   return false;
6586 }
6587
6588 bool
6589 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6590 {
6591   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6592 }
6593
6594
6595 /* Given the expression node e for an allocatable/pointer of derived type to be
6596    allocated, get the expression node to be initialized afterwards (needed for
6597    derived types with default initializers, and derived types with allocatable
6598    components that need nullification.)  */
6599
6600 gfc_expr *
6601 gfc_expr_to_initialize (gfc_expr *e)
6602 {
6603   gfc_expr *result;
6604   gfc_ref *ref;
6605   int i;
6606
6607   result = gfc_copy_expr (e);
6608
6609   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6610   for (ref = result->ref; ref; ref = ref->next)
6611     if (ref->type == REF_ARRAY && ref->next == NULL)
6612       {
6613         ref->u.ar.type = AR_FULL;
6614
6615         for (i = 0; i < ref->u.ar.dimen; i++)
6616           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6617
6618         break;
6619       }
6620
6621   gfc_free_shape (&result->shape, result->rank);
6622
6623   /* Recalculate rank, shape, etc.  */
6624   gfc_resolve_expr (result);
6625   return result;
6626 }
6627
6628
6629 /* If the last ref of an expression is an array ref, return a copy of the
6630    expression with that one removed.  Otherwise, a copy of the original
6631    expression.  This is used for allocate-expressions and pointer assignment
6632    LHS, where there may be an array specification that needs to be stripped
6633    off when using gfc_check_vardef_context.  */
6634
6635 static gfc_expr*
6636 remove_last_array_ref (gfc_expr* e)
6637 {
6638   gfc_expr* e2;
6639   gfc_ref** r;
6640
6641   e2 = gfc_copy_expr (e);
6642   for (r = &e2->ref; *r; r = &(*r)->next)
6643     if ((*r)->type == REF_ARRAY && !(*r)->next)
6644       {
6645         gfc_free_ref_list (*r);
6646         *r = NULL;
6647         break;
6648       }
6649
6650   return e2;
6651 }
6652
6653
6654 /* Used in resolve_allocate_expr to check that a allocation-object and
6655    a source-expr are conformable.  This does not catch all possible 
6656    cases; in particular a runtime checking is needed.  */
6657
6658 static gfc_try
6659 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6660 {
6661   gfc_ref *tail;
6662   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6663   
6664   /* First compare rank.  */
6665   if (tail && e1->rank != tail->u.ar.as->rank)
6666     {
6667       gfc_error ("Source-expr at %L must be scalar or have the "
6668                  "same rank as the allocate-object at %L",
6669                  &e1->where, &e2->where);
6670       return FAILURE;
6671     }
6672
6673   if (e1->shape)
6674     {
6675       int i;
6676       mpz_t s;
6677
6678       mpz_init (s);
6679
6680       for (i = 0; i < e1->rank; i++)
6681         {
6682           if (tail->u.ar.end[i])
6683             {
6684               mpz_set (s, tail->u.ar.end[i]->value.integer);
6685               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6686               mpz_add_ui (s, s, 1);
6687             }
6688           else
6689             {
6690               mpz_set (s, tail->u.ar.start[i]->value.integer);
6691             }
6692
6693           if (mpz_cmp (e1->shape[i], s) != 0)
6694             {
6695               gfc_error ("Source-expr at %L and allocate-object at %L must "
6696                          "have the same shape", &e1->where, &e2->where);
6697               mpz_clear (s);
6698               return FAILURE;
6699             }
6700         }
6701
6702       mpz_clear (s);
6703     }
6704
6705   return SUCCESS;
6706 }
6707
6708
6709 /* Resolve the expression in an ALLOCATE statement, doing the additional
6710    checks to see whether the expression is OK or not.  The expression must
6711    have a trailing array reference that gives the size of the array.  */
6712
6713 static gfc_try
6714 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6715 {
6716   int i, pointer, allocatable, dimension, is_abstract;
6717   int codimension;
6718   bool coindexed;
6719   symbol_attribute attr;
6720   gfc_ref *ref, *ref2;
6721   gfc_expr *e2;
6722   gfc_array_ref *ar;
6723   gfc_symbol *sym = NULL;
6724   gfc_alloc *a;
6725   gfc_component *c;
6726   gfc_try t;
6727
6728   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6729      checking of coarrays.  */
6730   for (ref = e->ref; ref; ref = ref->next)
6731     if (ref->next == NULL)
6732       break;
6733
6734   if (ref && ref->type == REF_ARRAY)
6735     ref->u.ar.in_allocate = true;
6736
6737   if (gfc_resolve_expr (e) == FAILURE)
6738     goto failure;
6739
6740   /* Make sure the expression is allocatable or a pointer.  If it is
6741      pointer, the next-to-last reference must be a pointer.  */
6742
6743   ref2 = NULL;
6744   if (e->symtree)
6745     sym = e->symtree->n.sym;
6746
6747   /* Check whether ultimate component is abstract and CLASS.  */
6748   is_abstract = 0;
6749
6750   if (e->expr_type != EXPR_VARIABLE)
6751     {
6752       allocatable = 0;
6753       attr = gfc_expr_attr (e);
6754       pointer = attr.pointer;
6755       dimension = attr.dimension;
6756       codimension = attr.codimension;
6757     }
6758   else
6759     {
6760       if (sym->ts.type == BT_CLASS && CLASS_DATA (sym))
6761         {
6762           allocatable = CLASS_DATA (sym)->attr.allocatable;
6763           pointer = CLASS_DATA (sym)->attr.class_pointer;
6764           dimension = CLASS_DATA (sym)->attr.dimension;
6765           codimension = CLASS_DATA (sym)->attr.codimension;
6766           is_abstract = CLASS_DATA (sym)->attr.abstract;
6767         }
6768       else
6769         {
6770           allocatable = sym->attr.allocatable;
6771           pointer = sym->attr.pointer;
6772           dimension = sym->attr.dimension;
6773           codimension = sym->attr.codimension;
6774         }
6775
6776       coindexed = false;
6777
6778       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6779         {
6780           switch (ref->type)
6781             {
6782               case REF_ARRAY:
6783                 if (ref->u.ar.codimen > 0)
6784                   {
6785                     int n;
6786                     for (n = ref->u.ar.dimen;
6787                          n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
6788                       if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
6789                         {
6790                           coindexed = true;
6791                           break;
6792                         }
6793                    }
6794
6795                 if (ref->next != NULL)
6796                   pointer = 0;
6797                 break;
6798
6799               case REF_COMPONENT:
6800                 /* F2008, C644.  */
6801                 if (coindexed)
6802                   {
6803                     gfc_error ("Coindexed allocatable object at %L",
6804                                &e->where);
6805                     goto failure;
6806                   }
6807
6808                 c = ref->u.c.component;
6809                 if (c->ts.type == BT_CLASS)
6810                   {
6811                     allocatable = CLASS_DATA (c)->attr.allocatable;
6812                     pointer = CLASS_DATA (c)->attr.class_pointer;
6813                     dimension = CLASS_DATA (c)->attr.dimension;
6814                     codimension = CLASS_DATA (c)->attr.codimension;
6815                     is_abstract = CLASS_DATA (c)->attr.abstract;
6816                   }
6817                 else
6818                   {
6819                     allocatable = c->attr.allocatable;
6820                     pointer = c->attr.pointer;
6821                     dimension = c->attr.dimension;
6822                     codimension = c->attr.codimension;
6823                     is_abstract = c->attr.abstract;
6824                   }
6825                 break;
6826
6827               case REF_SUBSTRING:
6828                 allocatable = 0;
6829                 pointer = 0;
6830                 break;
6831             }
6832         }
6833     }
6834
6835   if (allocatable == 0 && pointer == 0)
6836     {
6837       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6838                  &e->where);
6839       goto failure;
6840     }
6841
6842   /* Some checks for the SOURCE tag.  */
6843   if (code->expr3)
6844     {
6845       /* Check F03:C631.  */
6846       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6847         {
6848           gfc_error ("Type of entity at %L is type incompatible with "
6849                       "source-expr at %L", &e->where, &code->expr3->where);
6850           goto failure;
6851         }
6852
6853       /* Check F03:C632 and restriction following Note 6.18.  */
6854       if (code->expr3->rank > 0
6855           && conformable_arrays (code->expr3, e) == FAILURE)
6856         goto failure;
6857
6858       /* Check F03:C633.  */
6859       if (code->expr3->ts.kind != e->ts.kind)
6860         {
6861           gfc_error ("The allocate-object at %L and the source-expr at %L "
6862                       "shall have the same kind type parameter",
6863                       &e->where, &code->expr3->where);
6864           goto failure;
6865         }
6866
6867       /* Check F2008, C642.  */
6868       if (code->expr3->ts.type == BT_DERIVED
6869           && ((codimension && gfc_expr_attr (code->expr3).lock_comp)
6870               || (code->expr3->ts.u.derived->from_intmod
6871                      == INTMOD_ISO_FORTRAN_ENV
6872                   && code->expr3->ts.u.derived->intmod_sym_id
6873                      == ISOFORTRAN_LOCK_TYPE)))
6874         {
6875           gfc_error ("The source-expr at %L shall neither be of type "
6876                      "LOCK_TYPE nor have a LOCK_TYPE component if "
6877                       "allocate-object at %L is a coarray",
6878                       &code->expr3->where, &e->where);
6879           goto failure;
6880         }
6881     }
6882
6883   /* Check F08:C629.  */
6884   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6885       && !code->expr3)
6886     {
6887       gcc_assert (e->ts.type == BT_CLASS);
6888       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6889                  "type-spec or source-expr", sym->name, &e->where);
6890       goto failure;
6891     }
6892
6893   /* In the variable definition context checks, gfc_expr_attr is used
6894      on the expression.  This is fooled by the array specification
6895      present in e, thus we have to eliminate that one temporarily.  */
6896   e2 = remove_last_array_ref (e);
6897   t = SUCCESS;
6898   if (t == SUCCESS && pointer)
6899     t = gfc_check_vardef_context (e2, true, true, _("ALLOCATE object"));
6900   if (t == SUCCESS)
6901     t = gfc_check_vardef_context (e2, false, true, _("ALLOCATE object"));
6902   gfc_free_expr (e2);
6903   if (t == FAILURE)
6904     goto failure;
6905
6906   if (e->ts.type == BT_CLASS && CLASS_DATA (e)->attr.dimension
6907         && !code->expr3 && code->ext.alloc.ts.type == BT_DERIVED)
6908     {
6909       /* For class arrays, the initialization with SOURCE is done
6910          using _copy and trans_call. It is convenient to exploit that
6911          when the allocated type is different from the declared type but
6912          no SOURCE exists by setting expr3.  */
6913       code->expr3 = gfc_default_initializer (&code->ext.alloc.ts); 
6914     }
6915   else if (!code->expr3)
6916     {
6917       /* Set up default initializer if needed.  */
6918       gfc_typespec ts;
6919       gfc_expr *init_e;
6920
6921       if (code->ext.alloc.ts.type == BT_DERIVED)
6922         ts = code->ext.alloc.ts;
6923       else
6924         ts = e->ts;
6925
6926       if (ts.type == BT_CLASS)
6927         ts = ts.u.derived->components->ts;
6928
6929       if (ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&ts)))
6930         {
6931           gfc_code *init_st = gfc_get_code ();
6932           init_st->loc = code->loc;
6933           init_st->op = EXEC_INIT_ASSIGN;
6934           init_st->expr1 = gfc_expr_to_initialize (e);
6935           init_st->expr2 = init_e;
6936           init_st->next = code->next;
6937           code->next = init_st;
6938         }
6939     }
6940   else if (code->expr3->mold && code->expr3->ts.type == BT_DERIVED)
6941     {
6942       /* Default initialization via MOLD (non-polymorphic).  */
6943       gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
6944       gfc_resolve_expr (rhs);
6945       gfc_free_expr (code->expr3);
6946       code->expr3 = rhs;
6947     }
6948
6949   if (e->ts.type == BT_CLASS)
6950     {
6951       /* Make sure the vtab symbol is present when
6952          the module variables are generated.  */
6953       gfc_typespec ts = e->ts;
6954       if (code->expr3)
6955         ts = code->expr3->ts;
6956       else if (code->ext.alloc.ts.type == BT_DERIVED)
6957         ts = code->ext.alloc.ts;
6958       gfc_find_derived_vtab (ts.u.derived);
6959       if (dimension)
6960         e = gfc_expr_to_initialize (e);
6961     }
6962
6963   if (dimension == 0 && codimension == 0)
6964     goto success;
6965
6966   /* Make sure the last reference node is an array specifiction.  */
6967
6968   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6969       || (dimension && ref2->u.ar.dimen == 0))
6970     {
6971       gfc_error ("Array specification required in ALLOCATE statement "
6972                  "at %L", &e->where);
6973       goto failure;
6974     }
6975
6976   /* Make sure that the array section reference makes sense in the
6977     context of an ALLOCATE specification.  */
6978
6979   ar = &ref2->u.ar;
6980
6981   if (codimension)
6982     for (i = ar->dimen; i < ar->dimen + ar->codimen; i++)
6983       if (ar->dimen_type[i] == DIMEN_THIS_IMAGE)
6984         {
6985           gfc_error ("Coarray specification required in ALLOCATE statement "
6986                      "at %L", &e->where);
6987           goto failure;
6988         }
6989
6990   for (i = 0; i < ar->dimen; i++)
6991     {
6992       if (ref2->u.ar.type == AR_ELEMENT)
6993         goto check_symbols;
6994
6995       switch (ar->dimen_type[i])
6996         {
6997         case DIMEN_ELEMENT:
6998           break;
6999
7000         case DIMEN_RANGE:
7001           if (ar->start[i] != NULL
7002               && ar->end[i] != NULL
7003               && ar->stride[i] == NULL)
7004             break;
7005
7006           /* Fall Through...  */
7007
7008         case DIMEN_UNKNOWN:
7009         case DIMEN_VECTOR:
7010         case DIMEN_STAR:
7011         case DIMEN_THIS_IMAGE:
7012           gfc_error ("Bad array specification in ALLOCATE statement at %L",
7013                      &e->where);
7014           goto failure;
7015         }
7016
7017 check_symbols:
7018       for (a = code->ext.alloc.list; a; a = a->next)
7019         {
7020           sym = a->expr->symtree->n.sym;
7021
7022           /* TODO - check derived type components.  */
7023           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
7024             continue;
7025
7026           if ((ar->start[i] != NULL
7027                && gfc_find_sym_in_expr (sym, ar->start[i]))
7028               || (ar->end[i] != NULL
7029                   && gfc_find_sym_in_expr (sym, ar->end[i])))
7030             {
7031               gfc_error ("'%s' must not appear in the array specification at "
7032                          "%L in the same ALLOCATE statement where it is "
7033                          "itself allocated", sym->name, &ar->where);
7034               goto failure;
7035             }
7036         }
7037     }
7038
7039   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
7040     {
7041       if (ar->dimen_type[i] == DIMEN_ELEMENT
7042           || ar->dimen_type[i] == DIMEN_RANGE)
7043         {
7044           if (i == (ar->dimen + ar->codimen - 1))
7045             {
7046               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
7047                          "statement at %L", &e->where);
7048               goto failure;
7049             }
7050           break;
7051         }
7052
7053       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
7054           && ar->stride[i] == NULL)
7055         break;
7056
7057       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
7058                  &e->where);
7059       goto failure;
7060     }
7061
7062 success:
7063   return SUCCESS;
7064
7065 failure:
7066   return FAILURE;
7067 }
7068
7069 static void
7070 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
7071 {
7072   gfc_expr *stat, *errmsg, *pe, *qe;
7073   gfc_alloc *a, *p, *q;
7074
7075   stat = code->expr1;
7076   errmsg = code->expr2;
7077
7078   /* Check the stat variable.  */
7079   if (stat)
7080     {
7081       gfc_check_vardef_context (stat, false, false, _("STAT variable"));
7082
7083       if ((stat->ts.type != BT_INTEGER
7084            && !(stat->ref && (stat->ref->type == REF_ARRAY
7085                               || stat->ref->type == REF_COMPONENT)))
7086           || stat->rank > 0)
7087         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
7088                    "variable", &stat->where);
7089
7090       for (p = code->ext.alloc.list; p; p = p->next)
7091         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
7092           {
7093             gfc_ref *ref1, *ref2;
7094             bool found = true;
7095
7096             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
7097                  ref1 = ref1->next, ref2 = ref2->next)
7098               {
7099                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7100                   continue;
7101                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7102                   {
7103                     found = false;
7104                     break;
7105                   }
7106               }
7107
7108             if (found)
7109               {
7110                 gfc_error ("Stat-variable at %L shall not be %sd within "
7111                            "the same %s statement", &stat->where, fcn, fcn);
7112                 break;
7113               }
7114           }
7115     }
7116
7117   /* Check the errmsg variable.  */
7118   if (errmsg)
7119     {
7120       if (!stat)
7121         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
7122                      &errmsg->where);
7123
7124       gfc_check_vardef_context (errmsg, false, false, _("ERRMSG variable"));
7125
7126       if ((errmsg->ts.type != BT_CHARACTER
7127            && !(errmsg->ref
7128                 && (errmsg->ref->type == REF_ARRAY
7129                     || errmsg->ref->type == REF_COMPONENT)))
7130           || errmsg->rank > 0 )
7131         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
7132                    "variable", &errmsg->where);
7133
7134       for (p = code->ext.alloc.list; p; p = p->next)
7135         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
7136           {
7137             gfc_ref *ref1, *ref2;
7138             bool found = true;
7139
7140             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
7141                  ref1 = ref1->next, ref2 = ref2->next)
7142               {
7143                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7144                   continue;
7145                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7146                   {
7147                     found = false;
7148                     break;
7149                   }
7150               }
7151
7152             if (found)
7153               {
7154                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
7155                            "the same %s statement", &errmsg->where, fcn, fcn);
7156                 break;
7157               }
7158           }
7159     }
7160
7161   /* Check that an allocate-object appears only once in the statement.  
7162      FIXME: Checking derived types is disabled.  */
7163   for (p = code->ext.alloc.list; p; p = p->next)
7164     {
7165       pe = p->expr;
7166       for (q = p->next; q; q = q->next)
7167         {
7168           qe = q->expr;
7169           if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
7170             {
7171               /* This is a potential collision.  */
7172               gfc_ref *pr = pe->ref;
7173               gfc_ref *qr = qe->ref;
7174               
7175               /* Follow the references  until
7176                  a) They start to differ, in which case there is no error;
7177                  you can deallocate a%b and a%c in a single statement
7178                  b) Both of them stop, which is an error
7179                  c) One of them stops, which is also an error.  */
7180               while (1)
7181                 {
7182                   if (pr == NULL && qr == NULL)
7183                     {
7184                       gfc_error ("Allocate-object at %L also appears at %L",
7185                                  &pe->where, &qe->where);
7186                       break;
7187                     }
7188                   else if (pr != NULL && qr == NULL)
7189                     {
7190                       gfc_error ("Allocate-object at %L is subobject of"
7191                                  " object at %L", &pe->where, &qe->where);
7192                       break;
7193                     }
7194                   else if (pr == NULL && qr != NULL)
7195                     {
7196                       gfc_error ("Allocate-object at %L is subobject of"
7197                                  " object at %L", &qe->where, &pe->where);
7198                       break;
7199                     }
7200                   /* Here, pr != NULL && qr != NULL  */
7201                   gcc_assert(pr->type == qr->type);
7202                   if (pr->type == REF_ARRAY)
7203                     {
7204                       /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
7205                          which are legal.  */
7206                       gcc_assert (qr->type == REF_ARRAY);
7207
7208                       if (pr->next && qr->next)
7209                         {
7210                           gfc_array_ref *par = &(pr->u.ar);
7211                           gfc_array_ref *qar = &(qr->u.ar);
7212                           if (gfc_dep_compare_expr (par->start[0],
7213                                                     qar->start[0]) != 0)
7214                               break;
7215                         }
7216                     }
7217                   else
7218                     {
7219                       if (pr->u.c.component->name != qr->u.c.component->name)
7220                         break;
7221                     }
7222                   
7223                   pr = pr->next;
7224                   qr = qr->next;
7225                 }
7226             }
7227         }
7228     }
7229
7230   if (strcmp (fcn, "ALLOCATE") == 0)
7231     {
7232       for (a = code->ext.alloc.list; a; a = a->next)
7233         resolve_allocate_expr (a->expr, code);
7234     }
7235   else
7236     {
7237       for (a = code->ext.alloc.list; a; a = a->next)
7238         resolve_deallocate_expr (a->expr);
7239     }
7240 }
7241
7242
7243 /************ SELECT CASE resolution subroutines ************/
7244
7245 /* Callback function for our mergesort variant.  Determines interval
7246    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7247    op1 > op2.  Assumes we're not dealing with the default case.  
7248    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7249    There are nine situations to check.  */
7250
7251 static int
7252 compare_cases (const gfc_case *op1, const gfc_case *op2)
7253 {
7254   int retval;
7255
7256   if (op1->low == NULL) /* op1 = (:L)  */
7257     {
7258       /* op2 = (:N), so overlap.  */
7259       retval = 0;
7260       /* op2 = (M:) or (M:N),  L < M  */
7261       if (op2->low != NULL
7262           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7263         retval = -1;
7264     }
7265   else if (op1->high == NULL) /* op1 = (K:)  */
7266     {
7267       /* op2 = (M:), so overlap.  */
7268       retval = 0;
7269       /* op2 = (:N) or (M:N), K > N  */
7270       if (op2->high != NULL
7271           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7272         retval = 1;
7273     }
7274   else /* op1 = (K:L)  */
7275     {
7276       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7277         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7278                  ? 1 : 0;
7279       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7280         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7281                  ? -1 : 0;
7282       else                      /* op2 = (M:N)  */
7283         {
7284           retval =  0;
7285           /* L < M  */
7286           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7287             retval =  -1;
7288           /* K > N  */
7289           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7290             retval =  1;
7291         }
7292     }
7293
7294   return retval;
7295 }
7296
7297
7298 /* Merge-sort a double linked case list, detecting overlap in the
7299    process.  LIST is the head of the double linked case list before it
7300    is sorted.  Returns the head of the sorted list if we don't see any
7301    overlap, or NULL otherwise.  */
7302
7303 static gfc_case *
7304 check_case_overlap (gfc_case *list)
7305 {
7306   gfc_case *p, *q, *e, *tail;
7307   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7308
7309   /* If the passed list was empty, return immediately.  */
7310   if (!list)
7311     return NULL;
7312
7313   overlap_seen = 0;
7314   insize = 1;
7315
7316   /* Loop unconditionally.  The only exit from this loop is a return
7317      statement, when we've finished sorting the case list.  */
7318   for (;;)
7319     {
7320       p = list;
7321       list = NULL;
7322       tail = NULL;
7323
7324       /* Count the number of merges we do in this pass.  */
7325       nmerges = 0;
7326
7327       /* Loop while there exists a merge to be done.  */
7328       while (p)
7329         {
7330           int i;
7331
7332           /* Count this merge.  */
7333           nmerges++;
7334
7335           /* Cut the list in two pieces by stepping INSIZE places
7336              forward in the list, starting from P.  */
7337           psize = 0;
7338           q = p;
7339           for (i = 0; i < insize; i++)
7340             {
7341               psize++;
7342               q = q->right;
7343               if (!q)
7344                 break;
7345             }
7346           qsize = insize;
7347
7348           /* Now we have two lists.  Merge them!  */
7349           while (psize > 0 || (qsize > 0 && q != NULL))
7350             {
7351               /* See from which the next case to merge comes from.  */
7352               if (psize == 0)
7353                 {
7354                   /* P is empty so the next case must come from Q.  */
7355                   e = q;
7356                   q = q->right;
7357                   qsize--;
7358                 }
7359               else if (qsize == 0 || q == NULL)
7360                 {
7361                   /* Q is empty.  */
7362                   e = p;
7363                   p = p->right;
7364                   psize--;
7365                 }
7366               else
7367                 {
7368                   cmp = compare_cases (p, q);
7369                   if (cmp < 0)
7370                     {
7371                       /* The whole case range for P is less than the
7372                          one for Q.  */
7373                       e = p;
7374                       p = p->right;
7375                       psize--;
7376                     }
7377                   else if (cmp > 0)
7378                     {
7379                       /* The whole case range for Q is greater than
7380                          the case range for P.  */
7381                       e = q;
7382                       q = q->right;
7383                       qsize--;
7384                     }
7385                   else
7386                     {
7387                       /* The cases overlap, or they are the same
7388                          element in the list.  Either way, we must
7389                          issue an error and get the next case from P.  */
7390                       /* FIXME: Sort P and Q by line number.  */
7391                       gfc_error ("CASE label at %L overlaps with CASE "
7392                                  "label at %L", &p->where, &q->where);
7393                       overlap_seen = 1;
7394                       e = p;
7395                       p = p->right;
7396                       psize--;
7397                     }
7398                 }
7399
7400                 /* Add the next element to the merged list.  */
7401               if (tail)
7402                 tail->right = e;
7403               else
7404                 list = e;
7405               e->left = tail;
7406               tail = e;
7407             }
7408
7409           /* P has now stepped INSIZE places along, and so has Q.  So
7410              they're the same.  */
7411           p = q;
7412         }
7413       tail->right = NULL;
7414
7415       /* If we have done only one merge or none at all, we've
7416          finished sorting the cases.  */
7417       if (nmerges <= 1)
7418         {
7419           if (!overlap_seen)
7420             return list;
7421           else
7422             return NULL;
7423         }
7424
7425       /* Otherwise repeat, merging lists twice the size.  */
7426       insize *= 2;
7427     }
7428 }
7429
7430
7431 /* Check to see if an expression is suitable for use in a CASE statement.
7432    Makes sure that all case expressions are scalar constants of the same
7433    type.  Return FAILURE if anything is wrong.  */
7434
7435 static gfc_try
7436 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7437 {
7438   if (e == NULL) return SUCCESS;
7439
7440   if (e->ts.type != case_expr->ts.type)
7441     {
7442       gfc_error ("Expression in CASE statement at %L must be of type %s",
7443                  &e->where, gfc_basic_typename (case_expr->ts.type));
7444       return FAILURE;
7445     }
7446
7447   /* C805 (R808) For a given case-construct, each case-value shall be of
7448      the same type as case-expr.  For character type, length differences
7449      are allowed, but the kind type parameters shall be the same.  */
7450
7451   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7452     {
7453       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7454                  &e->where, case_expr->ts.kind);
7455       return FAILURE;
7456     }
7457
7458   /* Convert the case value kind to that of case expression kind,
7459      if needed */
7460
7461   if (e->ts.kind != case_expr->ts.kind)
7462     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7463
7464   if (e->rank != 0)
7465     {
7466       gfc_error ("Expression in CASE statement at %L must be scalar",
7467                  &e->where);
7468       return FAILURE;
7469     }
7470
7471   return SUCCESS;
7472 }
7473
7474
7475 /* Given a completely parsed select statement, we:
7476
7477      - Validate all expressions and code within the SELECT.
7478      - Make sure that the selection expression is not of the wrong type.
7479      - Make sure that no case ranges overlap.
7480      - Eliminate unreachable cases and unreachable code resulting from
7481        removing case labels.
7482
7483    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7484    they are a hassle for code generation, and to prevent that, we just
7485    cut them out here.  This is not necessary for overlapping cases
7486    because they are illegal and we never even try to generate code.
7487
7488    We have the additional caveat that a SELECT construct could have
7489    been a computed GOTO in the source code. Fortunately we can fairly
7490    easily work around that here: The case_expr for a "real" SELECT CASE
7491    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7492    we have to do is make sure that the case_expr is a scalar integer
7493    expression.  */
7494
7495 static void
7496 resolve_select (gfc_code *code)
7497 {
7498   gfc_code *body;
7499   gfc_expr *case_expr;
7500   gfc_case *cp, *default_case, *tail, *head;
7501   int seen_unreachable;
7502   int seen_logical;
7503   int ncases;
7504   bt type;
7505   gfc_try t;
7506
7507   if (code->expr1 == NULL)
7508     {
7509       /* This was actually a computed GOTO statement.  */
7510       case_expr = code->expr2;
7511       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7512         gfc_error ("Selection expression in computed GOTO statement "
7513                    "at %L must be a scalar integer expression",
7514                    &case_expr->where);
7515
7516       /* Further checking is not necessary because this SELECT was built
7517          by the compiler, so it should always be OK.  Just move the
7518          case_expr from expr2 to expr so that we can handle computed
7519          GOTOs as normal SELECTs from here on.  */
7520       code->expr1 = code->expr2;
7521       code->expr2 = NULL;
7522       return;
7523     }
7524
7525   case_expr = code->expr1;
7526
7527   type = case_expr->ts.type;
7528   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7529     {
7530       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7531                  &case_expr->where, gfc_typename (&case_expr->ts));
7532
7533       /* Punt. Going on here just produce more garbage error messages.  */
7534       return;
7535     }
7536
7537   /* Raise a warning if an INTEGER case value exceeds the range of
7538      the case-expr. Later, all expressions will be promoted to the
7539      largest kind of all case-labels.  */
7540
7541   if (type == BT_INTEGER)
7542     for (body = code->block; body; body = body->block)
7543       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7544         {
7545           if (cp->low
7546               && gfc_check_integer_range (cp->low->value.integer,
7547                                           case_expr->ts.kind) != ARITH_OK)
7548             gfc_warning ("Expression in CASE statement at %L is "
7549                          "not in the range of %s", &cp->low->where,
7550                          gfc_typename (&case_expr->ts));
7551
7552           if (cp->high
7553               && cp->low != cp->high
7554               && gfc_check_integer_range (cp->high->value.integer,
7555                                           case_expr->ts.kind) != ARITH_OK)
7556             gfc_warning ("Expression in CASE statement at %L is "
7557                          "not in the range of %s", &cp->high->where,
7558                          gfc_typename (&case_expr->ts));
7559         }
7560
7561   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7562      of the SELECT CASE expression and its CASE values.  Walk the lists
7563      of case values, and if we find a mismatch, promote case_expr to
7564      the appropriate kind.  */
7565
7566   if (type == BT_LOGICAL || type == BT_INTEGER)
7567     {
7568       for (body = code->block; body; body = body->block)
7569         {
7570           /* Walk the case label list.  */
7571           for (cp = body->ext.block.case_list; cp; cp = cp->next)
7572             {
7573               /* Intercept the DEFAULT case.  It does not have a kind.  */
7574               if (cp->low == NULL && cp->high == NULL)
7575                 continue;
7576
7577               /* Unreachable case ranges are discarded, so ignore.  */
7578               if (cp->low != NULL && cp->high != NULL
7579                   && cp->low != cp->high
7580                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7581                 continue;
7582
7583               if (cp->low != NULL
7584                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7585                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7586
7587               if (cp->high != NULL
7588                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7589                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7590             }
7591          }
7592     }
7593
7594   /* Assume there is no DEFAULT case.  */
7595   default_case = NULL;
7596   head = tail = NULL;
7597   ncases = 0;
7598   seen_logical = 0;
7599
7600   for (body = code->block; body; body = body->block)
7601     {
7602       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7603       t = SUCCESS;
7604       seen_unreachable = 0;
7605
7606       /* Walk the case label list, making sure that all case labels
7607          are legal.  */
7608       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7609         {
7610           /* Count the number of cases in the whole construct.  */
7611           ncases++;
7612
7613           /* Intercept the DEFAULT case.  */
7614           if (cp->low == NULL && cp->high == NULL)
7615             {
7616               if (default_case != NULL)
7617                 {
7618                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7619                              "by a second DEFAULT CASE at %L",
7620                              &default_case->where, &cp->where);
7621                   t = FAILURE;
7622                   break;
7623                 }
7624               else
7625                 {
7626                   default_case = cp;
7627                   continue;
7628                 }
7629             }
7630
7631           /* Deal with single value cases and case ranges.  Errors are
7632              issued from the validation function.  */
7633           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7634               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7635             {
7636               t = FAILURE;
7637               break;
7638             }
7639
7640           if (type == BT_LOGICAL
7641               && ((cp->low == NULL || cp->high == NULL)
7642                   || cp->low != cp->high))
7643             {
7644               gfc_error ("Logical range in CASE statement at %L is not "
7645                          "allowed", &cp->low->where);
7646               t = FAILURE;
7647               break;
7648             }
7649
7650           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7651             {
7652               int value;
7653               value = cp->low->value.logical == 0 ? 2 : 1;
7654               if (value & seen_logical)
7655                 {
7656                   gfc_error ("Constant logical value in CASE statement "
7657                              "is repeated at %L",
7658                              &cp->low->where);
7659                   t = FAILURE;
7660                   break;
7661                 }
7662               seen_logical |= value;
7663             }
7664
7665           if (cp->low != NULL && cp->high != NULL
7666               && cp->low != cp->high
7667               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7668             {
7669               if (gfc_option.warn_surprising)
7670                 gfc_warning ("Range specification at %L can never "
7671                              "be matched", &cp->where);
7672
7673               cp->unreachable = 1;
7674               seen_unreachable = 1;
7675             }
7676           else
7677             {
7678               /* If the case range can be matched, it can also overlap with
7679                  other cases.  To make sure it does not, we put it in a
7680                  double linked list here.  We sort that with a merge sort
7681                  later on to detect any overlapping cases.  */
7682               if (!head)
7683                 {
7684                   head = tail = cp;
7685                   head->right = head->left = NULL;
7686                 }
7687               else
7688                 {
7689                   tail->right = cp;
7690                   tail->right->left = tail;
7691                   tail = tail->right;
7692                   tail->right = NULL;
7693                 }
7694             }
7695         }
7696
7697       /* It there was a failure in the previous case label, give up
7698          for this case label list.  Continue with the next block.  */
7699       if (t == FAILURE)
7700         continue;
7701
7702       /* See if any case labels that are unreachable have been seen.
7703          If so, we eliminate them.  This is a bit of a kludge because
7704          the case lists for a single case statement (label) is a
7705          single forward linked lists.  */
7706       if (seen_unreachable)
7707       {
7708         /* Advance until the first case in the list is reachable.  */
7709         while (body->ext.block.case_list != NULL
7710                && body->ext.block.case_list->unreachable)
7711           {
7712             gfc_case *n = body->ext.block.case_list;
7713             body->ext.block.case_list = body->ext.block.case_list->next;
7714             n->next = NULL;
7715             gfc_free_case_list (n);
7716           }
7717
7718         /* Strip all other unreachable cases.  */
7719         if (body->ext.block.case_list)
7720           {
7721             for (cp = body->ext.block.case_list; cp->next; cp = cp->next)
7722               {
7723                 if (cp->next->unreachable)
7724                   {
7725                     gfc_case *n = cp->next;
7726                     cp->next = cp->next->next;
7727                     n->next = NULL;
7728                     gfc_free_case_list (n);
7729                   }
7730               }
7731           }
7732       }
7733     }
7734
7735   /* See if there were overlapping cases.  If the check returns NULL,
7736      there was overlap.  In that case we don't do anything.  If head
7737      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7738      then used during code generation for SELECT CASE constructs with
7739      a case expression of a CHARACTER type.  */
7740   if (head)
7741     {
7742       head = check_case_overlap (head);
7743
7744       /* Prepend the default_case if it is there.  */
7745       if (head != NULL && default_case)
7746         {
7747           default_case->left = NULL;
7748           default_case->right = head;
7749           head->left = default_case;
7750         }
7751     }
7752
7753   /* Eliminate dead blocks that may be the result if we've seen
7754      unreachable case labels for a block.  */
7755   for (body = code; body && body->block; body = body->block)
7756     {
7757       if (body->block->ext.block.case_list == NULL)
7758         {
7759           /* Cut the unreachable block from the code chain.  */
7760           gfc_code *c = body->block;
7761           body->block = c->block;
7762
7763           /* Kill the dead block, but not the blocks below it.  */
7764           c->block = NULL;
7765           gfc_free_statements (c);
7766         }
7767     }
7768
7769   /* More than two cases is legal but insane for logical selects.
7770      Issue a warning for it.  */
7771   if (gfc_option.warn_surprising && type == BT_LOGICAL
7772       && ncases > 2)
7773     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7774                  &code->loc);
7775 }
7776
7777
7778 /* Check if a derived type is extensible.  */
7779
7780 bool
7781 gfc_type_is_extensible (gfc_symbol *sym)
7782 {
7783   return !(sym->attr.is_bind_c || sym->attr.sequence);
7784 }
7785
7786
7787 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7788    correct as well as possibly the array-spec.  */
7789
7790 static void
7791 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7792 {
7793   gfc_expr* target;
7794
7795   gcc_assert (sym->assoc);
7796   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7797
7798   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7799      case, return.  Resolution will be called later manually again when
7800      this is done.  */
7801   target = sym->assoc->target;
7802   if (!target)
7803     return;
7804   gcc_assert (!sym->assoc->dangling);
7805
7806   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7807     return;
7808
7809   /* For variable targets, we get some attributes from the target.  */
7810   if (target->expr_type == EXPR_VARIABLE)
7811     {
7812       gfc_symbol* tsym;
7813
7814       gcc_assert (target->symtree);
7815       tsym = target->symtree->n.sym;
7816
7817       sym->attr.asynchronous = tsym->attr.asynchronous;
7818       sym->attr.volatile_ = tsym->attr.volatile_;
7819
7820       sym->attr.target = (tsym->attr.target || tsym->attr.pointer);
7821
7822       if (sym->ts.type == BT_DERIVED && target->symtree->n.sym->ts.type == BT_CLASS)
7823         target->rank = sym->as ? sym->as->rank : 0;
7824     }
7825
7826   /* Get type if this was not already set.  Note that it can be
7827      some other type than the target in case this is a SELECT TYPE
7828      selector!  So we must not update when the type is already there.  */
7829   if (sym->ts.type == BT_UNKNOWN)
7830     sym->ts = target->ts;
7831   gcc_assert (sym->ts.type != BT_UNKNOWN);
7832
7833   /* See if this is a valid association-to-variable.  */
7834   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
7835                           && !gfc_has_vector_subscript (target));
7836
7837   /* Finally resolve if this is an array or not.  */
7838   if (sym->attr.dimension
7839         && (target->ts.type == BT_CLASS
7840               ? !CLASS_DATA (target)->attr.dimension
7841               : target->rank == 0))
7842     {
7843       gfc_error ("Associate-name '%s' at %L is used as array",
7844                  sym->name, &sym->declared_at);
7845       sym->attr.dimension = 0;
7846       return;
7847     }
7848   if (target->rank > 0)
7849     sym->attr.dimension = 1;
7850
7851   if (sym->attr.dimension)
7852     {
7853       sym->as = gfc_get_array_spec ();
7854       sym->as->rank = target->rank;
7855       sym->as->type = AS_DEFERRED;
7856
7857       /* Target must not be coindexed, thus the associate-variable
7858          has no corank.  */
7859       sym->as->corank = 0;
7860     }
7861 }
7862
7863
7864 /* Resolve a SELECT TYPE statement.  */
7865
7866 static void
7867 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
7868 {
7869   gfc_symbol *selector_type;
7870   gfc_code *body, *new_st, *if_st, *tail;
7871   gfc_code *class_is = NULL, *default_case = NULL;
7872   gfc_case *c;
7873   gfc_symtree *st;
7874   char name[GFC_MAX_SYMBOL_LEN];
7875   gfc_namespace *ns;
7876   int error = 0;
7877
7878   ns = code->ext.block.ns;
7879   gfc_resolve (ns);
7880
7881   /* Check for F03:C813.  */
7882   if (code->expr1->ts.type != BT_CLASS
7883       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7884     {
7885       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7886                  "at %L", &code->loc);
7887       return;
7888     }
7889
7890   if (code->expr2)
7891     {
7892       if (code->expr1->symtree->n.sym->attr.untyped)
7893         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7894       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7895     }
7896   else
7897     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7898
7899   /* Loop over TYPE IS / CLASS IS cases.  */
7900   for (body = code->block; body; body = body->block)
7901     {
7902       c = body->ext.block.case_list;
7903
7904       /* Check F03:C815.  */
7905       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7906           && !gfc_type_is_extensible (c->ts.u.derived))
7907         {
7908           gfc_error ("Derived type '%s' at %L must be extensible",
7909                      c->ts.u.derived->name, &c->where);
7910           error++;
7911           continue;
7912         }
7913
7914       /* Check F03:C816.  */
7915       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7916           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7917         {
7918           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7919                      c->ts.u.derived->name, &c->where, selector_type->name);
7920           error++;
7921           continue;
7922         }
7923
7924       /* Intercept the DEFAULT case.  */
7925       if (c->ts.type == BT_UNKNOWN)
7926         {
7927           /* Check F03:C818.  */
7928           if (default_case)
7929             {
7930               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7931                          "by a second DEFAULT CASE at %L",
7932                          &default_case->ext.block.case_list->where, &c->where);
7933               error++;
7934               continue;
7935             }
7936
7937           default_case = body;
7938         }
7939     }
7940     
7941   if (error > 0)
7942     return;
7943
7944   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7945      target if present.  If there are any EXIT statements referring to the
7946      SELECT TYPE construct, this is no problem because the gfc_code
7947      reference stays the same and EXIT is equally possible from the BLOCK
7948      it is changed to.  */
7949   code->op = EXEC_BLOCK;
7950   if (code->expr2)
7951     {
7952       gfc_association_list* assoc;
7953
7954       assoc = gfc_get_association_list ();
7955       assoc->st = code->expr1->symtree;
7956       assoc->target = gfc_copy_expr (code->expr2);
7957       assoc->target->where = code->expr2->where;
7958       /* assoc->variable will be set by resolve_assoc_var.  */
7959       
7960       code->ext.block.assoc = assoc;
7961       code->expr1->symtree->n.sym->assoc = assoc;
7962
7963       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7964     }
7965   else
7966     code->ext.block.assoc = NULL;
7967
7968   /* Add EXEC_SELECT to switch on type.  */
7969   new_st = gfc_get_code ();
7970   new_st->op = code->op;
7971   new_st->expr1 = code->expr1;
7972   new_st->expr2 = code->expr2;
7973   new_st->block = code->block;
7974   code->expr1 = code->expr2 =  NULL;
7975   code->block = NULL;
7976   if (!ns->code)
7977     ns->code = new_st;
7978   else
7979     ns->code->next = new_st;
7980   code = new_st;
7981   code->op = EXEC_SELECT;
7982   gfc_add_vptr_component (code->expr1);
7983   gfc_add_hash_component (code->expr1);
7984
7985   /* Loop over TYPE IS / CLASS IS cases.  */
7986   for (body = code->block; body; body = body->block)
7987     {
7988       c = body->ext.block.case_list;
7989
7990       if (c->ts.type == BT_DERIVED)
7991         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7992                                              c->ts.u.derived->hash_value);
7993
7994       else if (c->ts.type == BT_UNKNOWN)
7995         continue;
7996
7997       /* Associate temporary to selector.  This should only be done
7998          when this case is actually true, so build a new ASSOCIATE
7999          that does precisely this here (instead of using the
8000          'global' one).  */
8001
8002       if (c->ts.type == BT_CLASS)
8003         sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
8004       else
8005         sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
8006       st = gfc_find_symtree (ns->sym_root, name);
8007       gcc_assert (st->n.sym->assoc);
8008       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
8009       st->n.sym->assoc->target->where = code->expr1->where;
8010       if (c->ts.type == BT_DERIVED)
8011         gfc_add_data_component (st->n.sym->assoc->target);
8012
8013       new_st = gfc_get_code ();
8014       new_st->op = EXEC_BLOCK;
8015       new_st->ext.block.ns = gfc_build_block_ns (ns);
8016       new_st->ext.block.ns->code = body->next;
8017       body->next = new_st;
8018
8019       /* Chain in the new list only if it is marked as dangling.  Otherwise
8020          there is a CASE label overlap and this is already used.  Just ignore,
8021          the error is diagonsed elsewhere.  */
8022       if (st->n.sym->assoc->dangling)
8023         {
8024           new_st->ext.block.assoc = st->n.sym->assoc;
8025           st->n.sym->assoc->dangling = 0;
8026         }
8027
8028       resolve_assoc_var (st->n.sym, false);
8029     }
8030     
8031   /* Take out CLASS IS cases for separate treatment.  */
8032   body = code;
8033   while (body && body->block)
8034     {
8035       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
8036         {
8037           /* Add to class_is list.  */
8038           if (class_is == NULL)
8039             { 
8040               class_is = body->block;
8041               tail = class_is;
8042             }
8043           else
8044             {
8045               for (tail = class_is; tail->block; tail = tail->block) ;
8046               tail->block = body->block;
8047               tail = tail->block;
8048             }
8049           /* Remove from EXEC_SELECT list.  */
8050           body->block = body->block->block;
8051           tail->block = NULL;
8052         }
8053       else
8054         body = body->block;
8055     }
8056
8057   if (class_is)
8058     {
8059       gfc_symbol *vtab;
8060       
8061       if (!default_case)
8062         {
8063           /* Add a default case to hold the CLASS IS cases.  */
8064           for (tail = code; tail->block; tail = tail->block) ;
8065           tail->block = gfc_get_code ();
8066           tail = tail->block;
8067           tail->op = EXEC_SELECT_TYPE;
8068           tail->ext.block.case_list = gfc_get_case ();
8069           tail->ext.block.case_list->ts.type = BT_UNKNOWN;
8070           tail->next = NULL;
8071           default_case = tail;
8072         }
8073
8074       /* More than one CLASS IS block?  */
8075       if (class_is->block)
8076         {
8077           gfc_code **c1,*c2;
8078           bool swapped;
8079           /* Sort CLASS IS blocks by extension level.  */
8080           do
8081             {
8082               swapped = false;
8083               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
8084                 {
8085                   c2 = (*c1)->block;
8086                   /* F03:C817 (check for doubles).  */
8087                   if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
8088                       == c2->ext.block.case_list->ts.u.derived->hash_value)
8089                     {
8090                       gfc_error ("Double CLASS IS block in SELECT TYPE "
8091                                  "statement at %L",
8092                                  &c2->ext.block.case_list->where);
8093                       return;
8094                     }
8095                   if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
8096                       < c2->ext.block.case_list->ts.u.derived->attr.extension)
8097                     {
8098                       /* Swap.  */
8099                       (*c1)->block = c2->block;
8100                       c2->block = *c1;
8101                       *c1 = c2;
8102                       swapped = true;
8103                     }
8104                 }
8105             }
8106           while (swapped);
8107         }
8108         
8109       /* Generate IF chain.  */
8110       if_st = gfc_get_code ();
8111       if_st->op = EXEC_IF;
8112       new_st = if_st;
8113       for (body = class_is; body; body = body->block)
8114         {
8115           new_st->block = gfc_get_code ();
8116           new_st = new_st->block;
8117           new_st->op = EXEC_IF;
8118           /* Set up IF condition: Call _gfortran_is_extension_of.  */
8119           new_st->expr1 = gfc_get_expr ();
8120           new_st->expr1->expr_type = EXPR_FUNCTION;
8121           new_st->expr1->ts.type = BT_LOGICAL;
8122           new_st->expr1->ts.kind = 4;
8123           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
8124           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
8125           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
8126           /* Set up arguments.  */
8127           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
8128           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
8129           new_st->expr1->value.function.actual->expr->where = code->loc;
8130           gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
8131           vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
8132           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
8133           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
8134           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
8135           new_st->next = body->next;
8136         }
8137         if (default_case->next)
8138           {
8139             new_st->block = gfc_get_code ();
8140             new_st = new_st->block;
8141             new_st->op = EXEC_IF;
8142             new_st->next = default_case->next;
8143           }
8144           
8145         /* Replace CLASS DEFAULT code by the IF chain.  */
8146         default_case->next = if_st;
8147     }
8148
8149   /* Resolve the internal code.  This can not be done earlier because
8150      it requires that the sym->assoc of selectors is set already.  */
8151   gfc_current_ns = ns;
8152   gfc_resolve_blocks (code->block, gfc_current_ns);
8153   gfc_current_ns = old_ns;
8154
8155   resolve_select (code);
8156 }
8157
8158
8159 /* Resolve a transfer statement. This is making sure that:
8160    -- a derived type being transferred has only non-pointer components
8161    -- a derived type being transferred doesn't have private components, unless 
8162       it's being transferred from the module where the type was defined
8163    -- we're not trying to transfer a whole assumed size array.  */
8164
8165 static void
8166 resolve_transfer (gfc_code *code)
8167 {
8168   gfc_typespec *ts;
8169   gfc_symbol *sym;
8170   gfc_ref *ref;
8171   gfc_expr *exp;
8172
8173   exp = code->expr1;
8174
8175   while (exp != NULL && exp->expr_type == EXPR_OP
8176          && exp->value.op.op == INTRINSIC_PARENTHESES)
8177     exp = exp->value.op.op1;
8178
8179   if (exp && exp->expr_type == EXPR_NULL && exp->ts.type == BT_UNKNOWN)
8180     {
8181       gfc_error ("NULL intrinsic at %L in data transfer statement requires "
8182                  "MOLD=", &exp->where);
8183       return;
8184     }
8185
8186   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
8187                       && exp->expr_type != EXPR_FUNCTION))
8188     return;
8189
8190   /* If we are reading, the variable will be changed.  Note that
8191      code->ext.dt may be NULL if the TRANSFER is related to
8192      an INQUIRE statement -- but in this case, we are not reading, either.  */
8193   if (code->ext.dt && code->ext.dt->dt_io_kind->value.iokind == M_READ
8194       && gfc_check_vardef_context (exp, false, false, _("item in READ"))
8195          == FAILURE)
8196     return;
8197
8198   sym = exp->symtree->n.sym;
8199   ts = &sym->ts;
8200
8201   /* Go to actual component transferred.  */
8202   for (ref = exp->ref; ref; ref = ref->next)
8203     if (ref->type == REF_COMPONENT)
8204       ts = &ref->u.c.component->ts;
8205
8206   if (ts->type == BT_CLASS)
8207     {
8208       /* FIXME: Test for defined input/output.  */
8209       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
8210                 "it is processed by a defined input/output procedure",
8211                 &code->loc);
8212       return;
8213     }
8214
8215   if (ts->type == BT_DERIVED)
8216     {
8217       /* Check that transferred derived type doesn't contain POINTER
8218          components.  */
8219       if (ts->u.derived->attr.pointer_comp)
8220         {
8221           gfc_error ("Data transfer element at %L cannot have POINTER "
8222                      "components unless it is processed by a defined "
8223                      "input/output procedure", &code->loc);
8224           return;
8225         }
8226
8227       /* F08:C935.  */
8228       if (ts->u.derived->attr.proc_pointer_comp)
8229         {
8230           gfc_error ("Data transfer element at %L cannot have "
8231                      "procedure pointer components", &code->loc);
8232           return;
8233         }
8234
8235       if (ts->u.derived->attr.alloc_comp)
8236         {
8237           gfc_error ("Data transfer element at %L cannot have ALLOCATABLE "
8238                      "components unless it is processed by a defined "
8239                      "input/output procedure", &code->loc);
8240           return;
8241         }
8242
8243       if (derived_inaccessible (ts->u.derived))
8244         {
8245           gfc_error ("Data transfer element at %L cannot have "
8246                      "PRIVATE components",&code->loc);
8247           return;
8248         }
8249     }
8250
8251   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE && exp->ref
8252       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
8253     {
8254       gfc_error ("Data transfer element at %L cannot be a full reference to "
8255                  "an assumed-size array", &code->loc);
8256       return;
8257     }
8258 }
8259
8260
8261 /*********** Toplevel code resolution subroutines ***********/
8262
8263 /* Find the set of labels that are reachable from this block.  We also
8264    record the last statement in each block.  */
8265      
8266 static void
8267 find_reachable_labels (gfc_code *block)
8268 {
8269   gfc_code *c;
8270
8271   if (!block)
8272     return;
8273
8274   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8275
8276   /* Collect labels in this block.  We don't keep those corresponding
8277      to END {IF|SELECT}, these are checked in resolve_branch by going
8278      up through the code_stack.  */
8279   for (c = block; c; c = c->next)
8280     {
8281       if (c->here && c->op != EXEC_END_NESTED_BLOCK)
8282         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8283     }
8284
8285   /* Merge with labels from parent block.  */
8286   if (cs_base->prev)
8287     {
8288       gcc_assert (cs_base->prev->reachable_labels);
8289       bitmap_ior_into (cs_base->reachable_labels,
8290                        cs_base->prev->reachable_labels);
8291     }
8292 }
8293
8294
8295 static void
8296 resolve_lock_unlock (gfc_code *code)
8297 {
8298   if (code->expr1->ts.type != BT_DERIVED
8299       || code->expr1->expr_type != EXPR_VARIABLE
8300       || code->expr1->ts.u.derived->from_intmod != INTMOD_ISO_FORTRAN_ENV
8301       || code->expr1->ts.u.derived->intmod_sym_id != ISOFORTRAN_LOCK_TYPE
8302       || code->expr1->rank != 0
8303       || (!gfc_is_coarray (code->expr1) && !gfc_is_coindexed (code->expr1)))
8304     gfc_error ("Lock variable at %L must be a scalar of type LOCK_TYPE",
8305                &code->expr1->where);
8306
8307   /* Check STAT.  */
8308   if (code->expr2
8309       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8310           || code->expr2->expr_type != EXPR_VARIABLE))
8311     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8312                &code->expr2->where);
8313
8314   if (code->expr2
8315       && gfc_check_vardef_context (code->expr2, false, false,
8316                                    _("STAT variable")) == FAILURE)
8317     return;
8318
8319   /* Check ERRMSG.  */
8320   if (code->expr3
8321       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8322           || code->expr3->expr_type != EXPR_VARIABLE))
8323     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8324                &code->expr3->where);
8325
8326   if (code->expr3
8327       && gfc_check_vardef_context (code->expr3, false, false,
8328                                    _("ERRMSG variable")) == FAILURE)
8329     return;
8330
8331   /* Check ACQUIRED_LOCK.  */
8332   if (code->expr4
8333       && (code->expr4->ts.type != BT_LOGICAL || code->expr4->rank != 0
8334           || code->expr4->expr_type != EXPR_VARIABLE))
8335     gfc_error ("ACQUIRED_LOCK= argument at %L must be a scalar LOGICAL "
8336                "variable", &code->expr4->where);
8337
8338   if (code->expr4
8339       && gfc_check_vardef_context (code->expr4, false, false,
8340                                    _("ACQUIRED_LOCK variable")) == FAILURE)
8341     return;
8342 }
8343
8344
8345 static void
8346 resolve_sync (gfc_code *code)
8347 {
8348   /* Check imageset. The * case matches expr1 == NULL.  */
8349   if (code->expr1)
8350     {
8351       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8352         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8353                    "INTEGER expression", &code->expr1->where);
8354       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8355           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8356         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8357                    &code->expr1->where);
8358       else if (code->expr1->expr_type == EXPR_ARRAY
8359                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8360         {
8361            gfc_constructor *cons;
8362            cons = gfc_constructor_first (code->expr1->value.constructor);
8363            for (; cons; cons = gfc_constructor_next (cons))
8364              if (cons->expr->expr_type == EXPR_CONSTANT
8365                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8366                gfc_error ("Imageset argument at %L must between 1 and "
8367                           "num_images()", &cons->expr->where);
8368         }
8369     }
8370
8371   /* Check STAT.  */
8372   if (code->expr2
8373       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8374           || code->expr2->expr_type != EXPR_VARIABLE))
8375     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8376                &code->expr2->where);
8377
8378   /* Check ERRMSG.  */
8379   if (code->expr3
8380       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8381           || code->expr3->expr_type != EXPR_VARIABLE))
8382     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8383                &code->expr3->where);
8384 }
8385
8386
8387 /* Given a branch to a label, see if the branch is conforming.
8388    The code node describes where the branch is located.  */
8389
8390 static void
8391 resolve_branch (gfc_st_label *label, gfc_code *code)
8392 {
8393   code_stack *stack;
8394
8395   if (label == NULL)
8396     return;
8397
8398   /* Step one: is this a valid branching target?  */
8399
8400   if (label->defined == ST_LABEL_UNKNOWN)
8401     {
8402       gfc_error ("Label %d referenced at %L is never defined", label->value,
8403                  &label->where);
8404       return;
8405     }
8406
8407   if (label->defined != ST_LABEL_TARGET)
8408     {
8409       gfc_error ("Statement at %L is not a valid branch target statement "
8410                  "for the branch statement at %L", &label->where, &code->loc);
8411       return;
8412     }
8413
8414   /* Step two: make sure this branch is not a branch to itself ;-)  */
8415
8416   if (code->here == label)
8417     {
8418       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8419       return;
8420     }
8421
8422   /* Step three:  See if the label is in the same block as the
8423      branching statement.  The hard work has been done by setting up
8424      the bitmap reachable_labels.  */
8425
8426   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8427     {
8428       /* Check now whether there is a CRITICAL construct; if so, check
8429          whether the label is still visible outside of the CRITICAL block,
8430          which is invalid.  */
8431       for (stack = cs_base; stack; stack = stack->prev)
8432         {
8433           if (stack->current->op == EXEC_CRITICAL
8434               && bitmap_bit_p (stack->reachable_labels, label->value))
8435             gfc_error ("GOTO statement at %L leaves CRITICAL construct for "
8436                       "label at %L", &code->loc, &label->where);
8437           else if (stack->current->op == EXEC_DO_CONCURRENT
8438                    && bitmap_bit_p (stack->reachable_labels, label->value))
8439             gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct "
8440                       "for label at %L", &code->loc, &label->where);
8441         }
8442
8443       return;
8444     }
8445
8446   /* Step four:  If we haven't found the label in the bitmap, it may
8447     still be the label of the END of the enclosing block, in which
8448     case we find it by going up the code_stack.  */
8449
8450   for (stack = cs_base; stack; stack = stack->prev)
8451     {
8452       if (stack->current->next && stack->current->next->here == label)
8453         break;
8454       if (stack->current->op == EXEC_CRITICAL)
8455         {
8456           /* Note: A label at END CRITICAL does not leave the CRITICAL
8457              construct as END CRITICAL is still part of it.  */
8458           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8459                       " at %L", &code->loc, &label->where);
8460           return;
8461         }
8462       else if (stack->current->op == EXEC_DO_CONCURRENT)
8463         {
8464           gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct for "
8465                      "label at %L", &code->loc, &label->where);
8466           return;
8467         }
8468     }
8469
8470   if (stack)
8471     {
8472       gcc_assert (stack->current->next->op == EXEC_END_NESTED_BLOCK);
8473       return;
8474     }
8475
8476   /* The label is not in an enclosing block, so illegal.  This was
8477      allowed in Fortran 66, so we allow it as extension.  No
8478      further checks are necessary in this case.  */
8479   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8480                   "as the GOTO statement at %L", &label->where,
8481                   &code->loc);
8482   return;
8483 }
8484
8485
8486 /* Check whether EXPR1 has the same shape as EXPR2.  */
8487
8488 static gfc_try
8489 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8490 {
8491   mpz_t shape[GFC_MAX_DIMENSIONS];
8492   mpz_t shape2[GFC_MAX_DIMENSIONS];
8493   gfc_try result = FAILURE;
8494   int i;
8495
8496   /* Compare the rank.  */
8497   if (expr1->rank != expr2->rank)
8498     return result;
8499
8500   /* Compare the size of each dimension.  */
8501   for (i=0; i<expr1->rank; i++)
8502     {
8503       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8504         goto ignore;
8505
8506       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8507         goto ignore;
8508
8509       if (mpz_cmp (shape[i], shape2[i]))
8510         goto over;
8511     }
8512
8513   /* When either of the two expression is an assumed size array, we
8514      ignore the comparison of dimension sizes.  */
8515 ignore:
8516   result = SUCCESS;
8517
8518 over:
8519   gfc_clear_shape (shape, i);
8520   gfc_clear_shape (shape2, i);
8521   return result;
8522 }
8523
8524
8525 /* Check whether a WHERE assignment target or a WHERE mask expression
8526    has the same shape as the outmost WHERE mask expression.  */
8527
8528 static void
8529 resolve_where (gfc_code *code, gfc_expr *mask)
8530 {
8531   gfc_code *cblock;
8532   gfc_code *cnext;
8533   gfc_expr *e = NULL;
8534
8535   cblock = code->block;
8536
8537   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8538      In case of nested WHERE, only the outmost one is stored.  */
8539   if (mask == NULL) /* outmost WHERE */
8540     e = cblock->expr1;
8541   else /* inner WHERE */
8542     e = mask;
8543
8544   while (cblock)
8545     {
8546       if (cblock->expr1)
8547         {
8548           /* Check if the mask-expr has a consistent shape with the
8549              outmost WHERE mask-expr.  */
8550           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8551             gfc_error ("WHERE mask at %L has inconsistent shape",
8552                        &cblock->expr1->where);
8553          }
8554
8555       /* the assignment statement of a WHERE statement, or the first
8556          statement in where-body-construct of a WHERE construct */
8557       cnext = cblock->next;
8558       while (cnext)
8559         {
8560           switch (cnext->op)
8561             {
8562             /* WHERE assignment statement */
8563             case EXEC_ASSIGN:
8564
8565               /* Check shape consistent for WHERE assignment target.  */
8566               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8567                gfc_error ("WHERE assignment target at %L has "
8568                           "inconsistent shape", &cnext->expr1->where);
8569               break;
8570
8571   
8572             case EXEC_ASSIGN_CALL:
8573               resolve_call (cnext);
8574               if (!cnext->resolved_sym->attr.elemental)
8575                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8576                           &cnext->ext.actual->expr->where);
8577               break;
8578
8579             /* WHERE or WHERE construct is part of a where-body-construct */
8580             case EXEC_WHERE:
8581               resolve_where (cnext, e);
8582               break;
8583
8584             default:
8585               gfc_error ("Unsupported statement inside WHERE at %L",
8586                          &cnext->loc);
8587             }
8588          /* the next statement within the same where-body-construct */
8589          cnext = cnext->next;
8590        }
8591     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8592     cblock = cblock->block;
8593   }
8594 }
8595
8596
8597 /* Resolve assignment in FORALL construct.
8598    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8599    FORALL index variables.  */
8600
8601 static void
8602 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8603 {
8604   int n;
8605
8606   for (n = 0; n < nvar; n++)
8607     {
8608       gfc_symbol *forall_index;
8609
8610       forall_index = var_expr[n]->symtree->n.sym;
8611
8612       /* Check whether the assignment target is one of the FORALL index
8613          variable.  */
8614       if ((code->expr1->expr_type == EXPR_VARIABLE)
8615           && (code->expr1->symtree->n.sym == forall_index))
8616         gfc_error ("Assignment to a FORALL index variable at %L",
8617                    &code->expr1->where);
8618       else
8619         {
8620           /* If one of the FORALL index variables doesn't appear in the
8621              assignment variable, then there could be a many-to-one
8622              assignment.  Emit a warning rather than an error because the
8623              mask could be resolving this problem.  */
8624           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8625             gfc_warning ("The FORALL with index '%s' is not used on the "
8626                          "left side of the assignment at %L and so might "
8627                          "cause multiple assignment to this object",
8628                          var_expr[n]->symtree->name, &code->expr1->where);
8629         }
8630     }
8631 }
8632
8633
8634 /* Resolve WHERE statement in FORALL construct.  */
8635
8636 static void
8637 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8638                                   gfc_expr **var_expr)
8639 {
8640   gfc_code *cblock;
8641   gfc_code *cnext;
8642
8643   cblock = code->block;
8644   while (cblock)
8645     {
8646       /* the assignment statement of a WHERE statement, or the first
8647          statement in where-body-construct of a WHERE construct */
8648       cnext = cblock->next;
8649       while (cnext)
8650         {
8651           switch (cnext->op)
8652             {
8653             /* WHERE assignment statement */
8654             case EXEC_ASSIGN:
8655               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8656               break;
8657   
8658             /* WHERE operator assignment statement */
8659             case EXEC_ASSIGN_CALL:
8660               resolve_call (cnext);
8661               if (!cnext->resolved_sym->attr.elemental)
8662                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8663                           &cnext->ext.actual->expr->where);
8664               break;
8665
8666             /* WHERE or WHERE construct is part of a where-body-construct */
8667             case EXEC_WHERE:
8668               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8669               break;
8670
8671             default:
8672               gfc_error ("Unsupported statement inside WHERE at %L",
8673                          &cnext->loc);
8674             }
8675           /* the next statement within the same where-body-construct */
8676           cnext = cnext->next;
8677         }
8678       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8679       cblock = cblock->block;
8680     }
8681 }
8682
8683
8684 /* Traverse the FORALL body to check whether the following errors exist:
8685    1. For assignment, check if a many-to-one assignment happens.
8686    2. For WHERE statement, check the WHERE body to see if there is any
8687       many-to-one assignment.  */
8688
8689 static void
8690 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8691 {
8692   gfc_code *c;
8693
8694   c = code->block->next;
8695   while (c)
8696     {
8697       switch (c->op)
8698         {
8699         case EXEC_ASSIGN:
8700         case EXEC_POINTER_ASSIGN:
8701           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8702           break;
8703
8704         case EXEC_ASSIGN_CALL:
8705           resolve_call (c);
8706           break;
8707
8708         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8709            there is no need to handle it here.  */
8710         case EXEC_FORALL:
8711           break;
8712         case EXEC_WHERE:
8713           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8714           break;
8715         default:
8716           break;
8717         }
8718       /* The next statement in the FORALL body.  */
8719       c = c->next;
8720     }
8721 }
8722
8723
8724 /* Counts the number of iterators needed inside a forall construct, including
8725    nested forall constructs. This is used to allocate the needed memory 
8726    in gfc_resolve_forall.  */
8727
8728 static int 
8729 gfc_count_forall_iterators (gfc_code *code)
8730 {
8731   int max_iters, sub_iters, current_iters;
8732   gfc_forall_iterator *fa;
8733
8734   gcc_assert(code->op == EXEC_FORALL);
8735   max_iters = 0;
8736   current_iters = 0;
8737
8738   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8739     current_iters ++;
8740   
8741   code = code->block->next;
8742
8743   while (code)
8744     {          
8745       if (code->op == EXEC_FORALL)
8746         {
8747           sub_iters = gfc_count_forall_iterators (code);
8748           if (sub_iters > max_iters)
8749             max_iters = sub_iters;
8750         }
8751       code = code->next;
8752     }
8753
8754   return current_iters + max_iters;
8755 }
8756
8757
8758 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8759    gfc_resolve_forall_body to resolve the FORALL body.  */
8760
8761 static void
8762 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8763 {
8764   static gfc_expr **var_expr;
8765   static int total_var = 0;
8766   static int nvar = 0;
8767   int old_nvar, tmp;
8768   gfc_forall_iterator *fa;
8769   int i;
8770
8771   old_nvar = nvar;
8772
8773   /* Start to resolve a FORALL construct   */
8774   if (forall_save == 0)
8775     {
8776       /* Count the total number of FORALL index in the nested FORALL
8777          construct in order to allocate the VAR_EXPR with proper size.  */
8778       total_var = gfc_count_forall_iterators (code);
8779
8780       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8781       var_expr = XCNEWVEC (gfc_expr *, total_var);
8782     }
8783
8784   /* The information about FORALL iterator, including FORALL index start, end
8785      and stride. The FORALL index can not appear in start, end or stride.  */
8786   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8787     {
8788       /* Check if any outer FORALL index name is the same as the current
8789          one.  */
8790       for (i = 0; i < nvar; i++)
8791         {
8792           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8793             {
8794               gfc_error ("An outer FORALL construct already has an index "
8795                          "with this name %L", &fa->var->where);
8796             }
8797         }
8798
8799       /* Record the current FORALL index.  */
8800       var_expr[nvar] = gfc_copy_expr (fa->var);
8801
8802       nvar++;
8803
8804       /* No memory leak.  */
8805       gcc_assert (nvar <= total_var);
8806     }
8807
8808   /* Resolve the FORALL body.  */
8809   gfc_resolve_forall_body (code, nvar, var_expr);
8810
8811   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8812   gfc_resolve_blocks (code->block, ns);
8813
8814   tmp = nvar;
8815   nvar = old_nvar;
8816   /* Free only the VAR_EXPRs allocated in this frame.  */
8817   for (i = nvar; i < tmp; i++)
8818      gfc_free_expr (var_expr[i]);
8819
8820   if (nvar == 0)
8821     {
8822       /* We are in the outermost FORALL construct.  */
8823       gcc_assert (forall_save == 0);
8824
8825       /* VAR_EXPR is not needed any more.  */
8826       free (var_expr);
8827       total_var = 0;
8828     }
8829 }
8830
8831
8832 /* Resolve a BLOCK construct statement.  */
8833
8834 static void
8835 resolve_block_construct (gfc_code* code)
8836 {
8837   /* Resolve the BLOCK's namespace.  */
8838   gfc_resolve (code->ext.block.ns);
8839
8840   /* For an ASSOCIATE block, the associations (and their targets) are already
8841      resolved during resolve_symbol.  */
8842 }
8843
8844
8845 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8846    DO code nodes.  */
8847
8848 static void resolve_code (gfc_code *, gfc_namespace *);
8849
8850 void
8851 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8852 {
8853   gfc_try t;
8854
8855   for (; b; b = b->block)
8856     {
8857       t = gfc_resolve_expr (b->expr1);
8858       if (gfc_resolve_expr (b->expr2) == FAILURE)
8859         t = FAILURE;
8860
8861       switch (b->op)
8862         {
8863         case EXEC_IF:
8864           if (t == SUCCESS && b->expr1 != NULL
8865               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8866             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8867                        &b->expr1->where);
8868           break;
8869
8870         case EXEC_WHERE:
8871           if (t == SUCCESS
8872               && b->expr1 != NULL
8873               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8874             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8875                        &b->expr1->where);
8876           break;
8877
8878         case EXEC_GOTO:
8879           resolve_branch (b->label1, b);
8880           break;
8881
8882         case EXEC_BLOCK:
8883           resolve_block_construct (b);
8884           break;
8885
8886         case EXEC_SELECT:
8887         case EXEC_SELECT_TYPE:
8888         case EXEC_FORALL:
8889         case EXEC_DO:
8890         case EXEC_DO_WHILE:
8891         case EXEC_DO_CONCURRENT:
8892         case EXEC_CRITICAL:
8893         case EXEC_READ:
8894         case EXEC_WRITE:
8895         case EXEC_IOLENGTH:
8896         case EXEC_WAIT:
8897           break;
8898
8899         case EXEC_OMP_ATOMIC:
8900         case EXEC_OMP_CRITICAL:
8901         case EXEC_OMP_DO:
8902         case EXEC_OMP_MASTER:
8903         case EXEC_OMP_ORDERED:
8904         case EXEC_OMP_PARALLEL:
8905         case EXEC_OMP_PARALLEL_DO:
8906         case EXEC_OMP_PARALLEL_SECTIONS:
8907         case EXEC_OMP_PARALLEL_WORKSHARE:
8908         case EXEC_OMP_SECTIONS:
8909         case EXEC_OMP_SINGLE:
8910         case EXEC_OMP_TASK:
8911         case EXEC_OMP_TASKWAIT:
8912         case EXEC_OMP_TASKYIELD:
8913         case EXEC_OMP_WORKSHARE:
8914           break;
8915
8916         default:
8917           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8918         }
8919
8920       resolve_code (b->next, ns);
8921     }
8922 }
8923
8924
8925 /* Does everything to resolve an ordinary assignment.  Returns true
8926    if this is an interface assignment.  */
8927 static bool
8928 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8929 {
8930   bool rval = false;
8931   gfc_expr *lhs;
8932   gfc_expr *rhs;
8933   int llen = 0;
8934   int rlen = 0;
8935   int n;
8936   gfc_ref *ref;
8937
8938   if (gfc_extend_assign (code, ns) == SUCCESS)
8939     {
8940       gfc_expr** rhsptr;
8941
8942       if (code->op == EXEC_ASSIGN_CALL)
8943         {
8944           lhs = code->ext.actual->expr;
8945           rhsptr = &code->ext.actual->next->expr;
8946         }
8947       else
8948         {
8949           gfc_actual_arglist* args;
8950           gfc_typebound_proc* tbp;
8951
8952           gcc_assert (code->op == EXEC_COMPCALL);
8953
8954           args = code->expr1->value.compcall.actual;
8955           lhs = args->expr;
8956           rhsptr = &args->next->expr;
8957
8958           tbp = code->expr1->value.compcall.tbp;
8959           gcc_assert (!tbp->is_generic);
8960         }
8961
8962       /* Make a temporary rhs when there is a default initializer
8963          and rhs is the same symbol as the lhs.  */
8964       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8965             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8966             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8967             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8968         *rhsptr = gfc_get_parentheses (*rhsptr);
8969
8970       return true;
8971     }
8972
8973   lhs = code->expr1;
8974   rhs = code->expr2;
8975
8976   if (rhs->is_boz
8977       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8978                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8979                          &code->loc) == FAILURE)
8980     return false;
8981
8982   /* Handle the case of a BOZ literal on the RHS.  */
8983   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8984     {
8985       int rc;
8986       if (gfc_option.warn_surprising)
8987         gfc_warning ("BOZ literal at %L is bitwise transferred "
8988                      "non-integer symbol '%s'", &code->loc,
8989                      lhs->symtree->n.sym->name);
8990
8991       if (!gfc_convert_boz (rhs, &lhs->ts))
8992         return false;
8993       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8994         {
8995           if (rc == ARITH_UNDERFLOW)
8996             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8997                        ". This check can be disabled with the option "
8998                        "-fno-range-check", &rhs->where);
8999           else if (rc == ARITH_OVERFLOW)
9000             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
9001                        ". This check can be disabled with the option "
9002                        "-fno-range-check", &rhs->where);
9003           else if (rc == ARITH_NAN)
9004             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
9005                        ". This check can be disabled with the option "
9006                        "-fno-range-check", &rhs->where);
9007           return false;
9008         }
9009     }
9010
9011   if (lhs->ts.type == BT_CHARACTER
9012         && gfc_option.warn_character_truncation)
9013     {
9014       if (lhs->ts.u.cl != NULL
9015             && lhs->ts.u.cl->length != NULL
9016             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9017         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
9018
9019       if (rhs->expr_type == EXPR_CONSTANT)
9020         rlen = rhs->value.character.length;
9021
9022       else if (rhs->ts.u.cl != NULL
9023                  && rhs->ts.u.cl->length != NULL
9024                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9025         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
9026
9027       if (rlen && llen && rlen > llen)
9028         gfc_warning_now ("CHARACTER expression will be truncated "
9029                          "in assignment (%d/%d) at %L",
9030                          llen, rlen, &code->loc);
9031     }
9032
9033   /* Ensure that a vector index expression for the lvalue is evaluated
9034      to a temporary if the lvalue symbol is referenced in it.  */
9035   if (lhs->rank)
9036     {
9037       for (ref = lhs->ref; ref; ref= ref->next)
9038         if (ref->type == REF_ARRAY)
9039           {
9040             for (n = 0; n < ref->u.ar.dimen; n++)
9041               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
9042                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
9043                                            ref->u.ar.start[n]))
9044                 ref->u.ar.start[n]
9045                         = gfc_get_parentheses (ref->u.ar.start[n]);
9046           }
9047     }
9048
9049   if (gfc_pure (NULL))
9050     {
9051       if (lhs->ts.type == BT_DERIVED
9052             && lhs->expr_type == EXPR_VARIABLE
9053             && lhs->ts.u.derived->attr.pointer_comp
9054             && rhs->expr_type == EXPR_VARIABLE
9055             && (gfc_impure_variable (rhs->symtree->n.sym)
9056                 || gfc_is_coindexed (rhs)))
9057         {
9058           /* F2008, C1283.  */
9059           if (gfc_is_coindexed (rhs))
9060             gfc_error ("Coindexed expression at %L is assigned to "
9061                         "a derived type variable with a POINTER "
9062                         "component in a PURE procedure",
9063                         &rhs->where);
9064           else
9065             gfc_error ("The impure variable at %L is assigned to "
9066                         "a derived type variable with a POINTER "
9067                         "component in a PURE procedure (12.6)",
9068                         &rhs->where);
9069           return rval;
9070         }
9071
9072       /* Fortran 2008, C1283.  */
9073       if (gfc_is_coindexed (lhs))
9074         {
9075           gfc_error ("Assignment to coindexed variable at %L in a PURE "
9076                      "procedure", &rhs->where);
9077           return rval;
9078         }
9079     }
9080
9081   if (gfc_implicit_pure (NULL))
9082     {
9083       if (lhs->expr_type == EXPR_VARIABLE
9084             && lhs->symtree->n.sym != gfc_current_ns->proc_name
9085             && lhs->symtree->n.sym->ns != gfc_current_ns)
9086         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9087
9088       if (lhs->ts.type == BT_DERIVED
9089             && lhs->expr_type == EXPR_VARIABLE
9090             && lhs->ts.u.derived->attr.pointer_comp
9091             && rhs->expr_type == EXPR_VARIABLE
9092             && (gfc_impure_variable (rhs->symtree->n.sym)
9093                 || gfc_is_coindexed (rhs)))
9094         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9095
9096       /* Fortran 2008, C1283.  */
9097       if (gfc_is_coindexed (lhs))
9098         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9099     }
9100
9101   /* F03:7.4.1.2.  */
9102   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
9103      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
9104   if (lhs->ts.type == BT_CLASS)
9105     {
9106       gfc_error ("Variable must not be polymorphic in assignment at %L",
9107                  &lhs->where);
9108       return false;
9109     }
9110
9111   /* F2008, Section 7.2.1.2.  */
9112   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
9113     {
9114       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
9115                  "component in assignment at %L", &lhs->where);
9116       return false;
9117     }
9118
9119   gfc_check_assign (lhs, rhs, 1);
9120   return false;
9121 }
9122
9123
9124 /* Given a block of code, recursively resolve everything pointed to by this
9125    code block.  */
9126
9127 static void
9128 resolve_code (gfc_code *code, gfc_namespace *ns)
9129 {
9130   int omp_workshare_save;
9131   int forall_save, do_concurrent_save;
9132   code_stack frame;
9133   gfc_try t;
9134
9135   frame.prev = cs_base;
9136   frame.head = code;
9137   cs_base = &frame;
9138
9139   find_reachable_labels (code);
9140
9141   for (; code; code = code->next)
9142     {
9143       frame.current = code;
9144       forall_save = forall_flag;
9145       do_concurrent_save = do_concurrent_flag;
9146
9147       if (code->op == EXEC_FORALL)
9148         {
9149           forall_flag = 1;
9150           gfc_resolve_forall (code, ns, forall_save);
9151           forall_flag = 2;
9152         }
9153       else if (code->block)
9154         {
9155           omp_workshare_save = -1;
9156           switch (code->op)
9157             {
9158             case EXEC_OMP_PARALLEL_WORKSHARE:
9159               omp_workshare_save = omp_workshare_flag;
9160               omp_workshare_flag = 1;
9161               gfc_resolve_omp_parallel_blocks (code, ns);
9162               break;
9163             case EXEC_OMP_PARALLEL:
9164             case EXEC_OMP_PARALLEL_DO:
9165             case EXEC_OMP_PARALLEL_SECTIONS:
9166             case EXEC_OMP_TASK:
9167               omp_workshare_save = omp_workshare_flag;
9168               omp_workshare_flag = 0;
9169               gfc_resolve_omp_parallel_blocks (code, ns);
9170               break;
9171             case EXEC_OMP_DO:
9172               gfc_resolve_omp_do_blocks (code, ns);
9173               break;
9174             case EXEC_SELECT_TYPE:
9175               /* Blocks are handled in resolve_select_type because we have
9176                  to transform the SELECT TYPE into ASSOCIATE first.  */
9177               break;
9178             case EXEC_DO_CONCURRENT:
9179               do_concurrent_flag = 1;
9180               gfc_resolve_blocks (code->block, ns);
9181               do_concurrent_flag = 2;
9182               break;
9183             case EXEC_OMP_WORKSHARE:
9184               omp_workshare_save = omp_workshare_flag;
9185               omp_workshare_flag = 1;
9186               /* FALLTHROUGH */
9187             default:
9188               gfc_resolve_blocks (code->block, ns);
9189               break;
9190             }
9191
9192           if (omp_workshare_save != -1)
9193             omp_workshare_flag = omp_workshare_save;
9194         }
9195
9196       t = SUCCESS;
9197       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
9198         t = gfc_resolve_expr (code->expr1);
9199       forall_flag = forall_save;
9200       do_concurrent_flag = do_concurrent_save;
9201
9202       if (gfc_resolve_expr (code->expr2) == FAILURE)
9203         t = FAILURE;
9204
9205       if (code->op == EXEC_ALLOCATE
9206           && gfc_resolve_expr (code->expr3) == FAILURE)
9207         t = FAILURE;
9208
9209       switch (code->op)
9210         {
9211         case EXEC_NOP:
9212         case EXEC_END_BLOCK:
9213         case EXEC_END_NESTED_BLOCK:
9214         case EXEC_CYCLE:
9215         case EXEC_PAUSE:
9216         case EXEC_STOP:
9217         case EXEC_ERROR_STOP:
9218         case EXEC_EXIT:
9219         case EXEC_CONTINUE:
9220         case EXEC_DT_END:
9221         case EXEC_ASSIGN_CALL:
9222         case EXEC_CRITICAL:
9223           break;
9224
9225         case EXEC_SYNC_ALL:
9226         case EXEC_SYNC_IMAGES:
9227         case EXEC_SYNC_MEMORY:
9228           resolve_sync (code);
9229           break;
9230
9231         case EXEC_LOCK:
9232         case EXEC_UNLOCK:
9233           resolve_lock_unlock (code);
9234           break;
9235
9236         case EXEC_ENTRY:
9237           /* Keep track of which entry we are up to.  */
9238           current_entry_id = code->ext.entry->id;
9239           break;
9240
9241         case EXEC_WHERE:
9242           resolve_where (code, NULL);
9243           break;
9244
9245         case EXEC_GOTO:
9246           if (code->expr1 != NULL)
9247             {
9248               if (code->expr1->ts.type != BT_INTEGER)
9249                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
9250                            "INTEGER variable", &code->expr1->where);
9251               else if (code->expr1->symtree->n.sym->attr.assign != 1)
9252                 gfc_error ("Variable '%s' has not been assigned a target "
9253                            "label at %L", code->expr1->symtree->n.sym->name,
9254                            &code->expr1->where);
9255             }
9256           else
9257             resolve_branch (code->label1, code);
9258           break;
9259
9260         case EXEC_RETURN:
9261           if (code->expr1 != NULL
9262                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
9263             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
9264                        "INTEGER return specifier", &code->expr1->where);
9265           break;
9266
9267         case EXEC_INIT_ASSIGN:
9268         case EXEC_END_PROCEDURE:
9269           break;
9270
9271         case EXEC_ASSIGN:
9272           if (t == FAILURE)
9273             break;
9274
9275           if (gfc_check_vardef_context (code->expr1, false, false,
9276                                         _("assignment")) == FAILURE)
9277             break;
9278
9279           if (resolve_ordinary_assign (code, ns))
9280             {
9281               if (code->op == EXEC_COMPCALL)
9282                 goto compcall;
9283               else
9284                 goto call;
9285             }
9286           break;
9287
9288         case EXEC_LABEL_ASSIGN:
9289           if (code->label1->defined == ST_LABEL_UNKNOWN)
9290             gfc_error ("Label %d referenced at %L is never defined",
9291                        code->label1->value, &code->label1->where);
9292           if (t == SUCCESS
9293               && (code->expr1->expr_type != EXPR_VARIABLE
9294                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
9295                   || code->expr1->symtree->n.sym->ts.kind
9296                      != gfc_default_integer_kind
9297                   || code->expr1->symtree->n.sym->as != NULL))
9298             gfc_error ("ASSIGN statement at %L requires a scalar "
9299                        "default INTEGER variable", &code->expr1->where);
9300           break;
9301
9302         case EXEC_POINTER_ASSIGN:
9303           {
9304             gfc_expr* e;
9305
9306             if (t == FAILURE)
9307               break;
9308
9309             /* This is both a variable definition and pointer assignment
9310                context, so check both of them.  For rank remapping, a final
9311                array ref may be present on the LHS and fool gfc_expr_attr
9312                used in gfc_check_vardef_context.  Remove it.  */
9313             e = remove_last_array_ref (code->expr1);
9314             t = gfc_check_vardef_context (e, true, false,
9315                                           _("pointer assignment"));
9316             if (t == SUCCESS)
9317               t = gfc_check_vardef_context (e, false, false,
9318                                             _("pointer assignment"));
9319             gfc_free_expr (e);
9320             if (t == FAILURE)
9321               break;
9322
9323             gfc_check_pointer_assign (code->expr1, code->expr2);
9324             break;
9325           }
9326
9327         case EXEC_ARITHMETIC_IF:
9328           if (t == SUCCESS
9329               && code->expr1->ts.type != BT_INTEGER
9330               && code->expr1->ts.type != BT_REAL)
9331             gfc_error ("Arithmetic IF statement at %L requires a numeric "
9332                        "expression", &code->expr1->where);
9333
9334           resolve_branch (code->label1, code);
9335           resolve_branch (code->label2, code);
9336           resolve_branch (code->label3, code);
9337           break;
9338
9339         case EXEC_IF:
9340           if (t == SUCCESS && code->expr1 != NULL
9341               && (code->expr1->ts.type != BT_LOGICAL
9342                   || code->expr1->rank != 0))
9343             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9344                        &code->expr1->where);
9345           break;
9346
9347         case EXEC_CALL:
9348         call:
9349           resolve_call (code);
9350           break;
9351
9352         case EXEC_COMPCALL:
9353         compcall:
9354           resolve_typebound_subroutine (code);
9355           break;
9356
9357         case EXEC_CALL_PPC:
9358           resolve_ppc_call (code);
9359           break;
9360
9361         case EXEC_SELECT:
9362           /* Select is complicated. Also, a SELECT construct could be
9363              a transformed computed GOTO.  */
9364           resolve_select (code);
9365           break;
9366
9367         case EXEC_SELECT_TYPE:
9368           resolve_select_type (code, ns);
9369           break;
9370
9371         case EXEC_BLOCK:
9372           resolve_block_construct (code);
9373           break;
9374
9375         case EXEC_DO:
9376           if (code->ext.iterator != NULL)
9377             {
9378               gfc_iterator *iter = code->ext.iterator;
9379               if (gfc_resolve_iterator (iter, true) != FAILURE)
9380                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9381             }
9382           break;
9383
9384         case EXEC_DO_WHILE:
9385           if (code->expr1 == NULL)
9386             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9387           if (t == SUCCESS
9388               && (code->expr1->rank != 0
9389                   || code->expr1->ts.type != BT_LOGICAL))
9390             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9391                        "a scalar LOGICAL expression", &code->expr1->where);
9392           break;
9393
9394         case EXEC_ALLOCATE:
9395           if (t == SUCCESS)
9396             resolve_allocate_deallocate (code, "ALLOCATE");
9397
9398           break;
9399
9400         case EXEC_DEALLOCATE:
9401           if (t == SUCCESS)
9402             resolve_allocate_deallocate (code, "DEALLOCATE");
9403
9404           break;
9405
9406         case EXEC_OPEN:
9407           if (gfc_resolve_open (code->ext.open) == FAILURE)
9408             break;
9409
9410           resolve_branch (code->ext.open->err, code);
9411           break;
9412
9413         case EXEC_CLOSE:
9414           if (gfc_resolve_close (code->ext.close) == FAILURE)
9415             break;
9416
9417           resolve_branch (code->ext.close->err, code);
9418           break;
9419
9420         case EXEC_BACKSPACE:
9421         case EXEC_ENDFILE:
9422         case EXEC_REWIND:
9423         case EXEC_FLUSH:
9424           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9425             break;
9426
9427           resolve_branch (code->ext.filepos->err, code);
9428           break;
9429
9430         case EXEC_INQUIRE:
9431           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9432               break;
9433
9434           resolve_branch (code->ext.inquire->err, code);
9435           break;
9436
9437         case EXEC_IOLENGTH:
9438           gcc_assert (code->ext.inquire != NULL);
9439           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9440             break;
9441
9442           resolve_branch (code->ext.inquire->err, code);
9443           break;
9444
9445         case EXEC_WAIT:
9446           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9447             break;
9448
9449           resolve_branch (code->ext.wait->err, code);
9450           resolve_branch (code->ext.wait->end, code);
9451           resolve_branch (code->ext.wait->eor, code);
9452           break;
9453
9454         case EXEC_READ:
9455         case EXEC_WRITE:
9456           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9457             break;
9458
9459           resolve_branch (code->ext.dt->err, code);
9460           resolve_branch (code->ext.dt->end, code);
9461           resolve_branch (code->ext.dt->eor, code);
9462           break;
9463
9464         case EXEC_TRANSFER:
9465           resolve_transfer (code);
9466           break;
9467
9468         case EXEC_DO_CONCURRENT:
9469         case EXEC_FORALL:
9470           resolve_forall_iterators (code->ext.forall_iterator);
9471
9472           if (code->expr1 != NULL
9473               && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
9474             gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
9475                        "expression", &code->expr1->where);
9476           break;
9477
9478         case EXEC_OMP_ATOMIC:
9479         case EXEC_OMP_BARRIER:
9480         case EXEC_OMP_CRITICAL:
9481         case EXEC_OMP_FLUSH:
9482         case EXEC_OMP_DO:
9483         case EXEC_OMP_MASTER:
9484         case EXEC_OMP_ORDERED:
9485         case EXEC_OMP_SECTIONS:
9486         case EXEC_OMP_SINGLE:
9487         case EXEC_OMP_TASKWAIT:
9488         case EXEC_OMP_TASKYIELD:
9489         case EXEC_OMP_WORKSHARE:
9490           gfc_resolve_omp_directive (code, ns);
9491           break;
9492
9493         case EXEC_OMP_PARALLEL:
9494         case EXEC_OMP_PARALLEL_DO:
9495         case EXEC_OMP_PARALLEL_SECTIONS:
9496         case EXEC_OMP_PARALLEL_WORKSHARE:
9497         case EXEC_OMP_TASK:
9498           omp_workshare_save = omp_workshare_flag;
9499           omp_workshare_flag = 0;
9500           gfc_resolve_omp_directive (code, ns);
9501           omp_workshare_flag = omp_workshare_save;
9502           break;
9503
9504         default:
9505           gfc_internal_error ("resolve_code(): Bad statement code");
9506         }
9507     }
9508
9509   cs_base = frame.prev;
9510 }
9511
9512
9513 /* Resolve initial values and make sure they are compatible with
9514    the variable.  */
9515
9516 static void
9517 resolve_values (gfc_symbol *sym)
9518 {
9519   gfc_try t;
9520
9521   if (sym->value == NULL || sym->attr.use_assoc)
9522     return;
9523
9524   if (sym->value->expr_type == EXPR_STRUCTURE)
9525     t= resolve_structure_cons (sym->value, 1);
9526   else 
9527     t = gfc_resolve_expr (sym->value);
9528
9529   if (t == FAILURE)
9530     return;
9531
9532   gfc_check_assign_symbol (sym, sym->value);
9533 }
9534
9535
9536 /* Verify the binding labels for common blocks that are BIND(C).  The label
9537    for a BIND(C) common block must be identical in all scoping units in which
9538    the common block is declared.  Further, the binding label can not collide
9539    with any other global entity in the program.  */
9540
9541 static void
9542 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9543 {
9544   if (comm_block_tree->n.common->is_bind_c == 1)
9545     {
9546       gfc_gsymbol *binding_label_gsym;
9547       gfc_gsymbol *comm_name_gsym;
9548
9549       /* See if a global symbol exists by the common block's name.  It may
9550          be NULL if the common block is use-associated.  */
9551       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9552                                          comm_block_tree->n.common->name);
9553       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9554         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9555                    "with the global entity '%s' at %L",
9556                    comm_block_tree->n.common->binding_label,
9557                    comm_block_tree->n.common->name,
9558                    &(comm_block_tree->n.common->where),
9559                    comm_name_gsym->name, &(comm_name_gsym->where));
9560       else if (comm_name_gsym != NULL
9561                && strcmp (comm_name_gsym->name,
9562                           comm_block_tree->n.common->name) == 0)
9563         {
9564           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9565              as expected.  */
9566           if (comm_name_gsym->binding_label == NULL)
9567             /* No binding label for common block stored yet; save this one.  */
9568             comm_name_gsym->binding_label =
9569               comm_block_tree->n.common->binding_label;
9570           else
9571             if (strcmp (comm_name_gsym->binding_label,
9572                         comm_block_tree->n.common->binding_label) != 0)
9573               {
9574                 /* Common block names match but binding labels do not.  */
9575                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9576                            "does not match the binding label '%s' for common "
9577                            "block '%s' at %L",
9578                            comm_block_tree->n.common->binding_label,
9579                            comm_block_tree->n.common->name,
9580                            &(comm_block_tree->n.common->where),
9581                            comm_name_gsym->binding_label,
9582                            comm_name_gsym->name,
9583                            &(comm_name_gsym->where));
9584                 return;
9585               }
9586         }
9587
9588       /* There is no binding label (NAME="") so we have nothing further to
9589          check and nothing to add as a global symbol for the label.  */
9590       if (comm_block_tree->n.common->binding_label[0] == '\0' )
9591         return;
9592       
9593       binding_label_gsym =
9594         gfc_find_gsymbol (gfc_gsym_root,
9595                           comm_block_tree->n.common->binding_label);
9596       if (binding_label_gsym == NULL)
9597         {
9598           /* Need to make a global symbol for the binding label to prevent
9599              it from colliding with another.  */
9600           binding_label_gsym =
9601             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9602           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9603           binding_label_gsym->type = GSYM_COMMON;
9604         }
9605       else
9606         {
9607           /* If comm_name_gsym is NULL, the name common block is use
9608              associated and the name could be colliding.  */
9609           if (binding_label_gsym->type != GSYM_COMMON)
9610             gfc_error ("Binding label '%s' for common block '%s' at %L "
9611                        "collides with the global entity '%s' at %L",
9612                        comm_block_tree->n.common->binding_label,
9613                        comm_block_tree->n.common->name,
9614                        &(comm_block_tree->n.common->where),
9615                        binding_label_gsym->name,
9616                        &(binding_label_gsym->where));
9617           else if (comm_name_gsym != NULL
9618                    && (strcmp (binding_label_gsym->name,
9619                                comm_name_gsym->binding_label) != 0)
9620                    && (strcmp (binding_label_gsym->sym_name,
9621                                comm_name_gsym->name) != 0))
9622             gfc_error ("Binding label '%s' for common block '%s' at %L "
9623                        "collides with global entity '%s' at %L",
9624                        binding_label_gsym->name, binding_label_gsym->sym_name,
9625                        &(comm_block_tree->n.common->where),
9626                        comm_name_gsym->name, &(comm_name_gsym->where));
9627         }
9628     }
9629   
9630   return;
9631 }
9632
9633
9634 /* Verify any BIND(C) derived types in the namespace so we can report errors
9635    for them once, rather than for each variable declared of that type.  */
9636
9637 static void
9638 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9639 {
9640   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9641       && derived_sym->attr.is_bind_c == 1)
9642     verify_bind_c_derived_type (derived_sym);
9643   
9644   return;
9645 }
9646
9647
9648 /* Verify that any binding labels used in a given namespace do not collide 
9649    with the names or binding labels of any global symbols.  */
9650
9651 static void
9652 gfc_verify_binding_labels (gfc_symbol *sym)
9653 {
9654   int has_error = 0;
9655   
9656   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
9657       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
9658     {
9659       gfc_gsymbol *bind_c_sym;
9660
9661       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9662       if (bind_c_sym != NULL 
9663           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9664         {
9665           if (sym->attr.if_source == IFSRC_DECL 
9666               && (bind_c_sym->type != GSYM_SUBROUTINE 
9667                   && bind_c_sym->type != GSYM_FUNCTION) 
9668               && ((sym->attr.contained == 1 
9669                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
9670                   || (sym->attr.use_assoc == 1 
9671                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9672             {
9673               /* Make sure global procedures don't collide with anything.  */
9674               gfc_error ("Binding label '%s' at %L collides with the global "
9675                          "entity '%s' at %L", sym->binding_label,
9676                          &(sym->declared_at), bind_c_sym->name,
9677                          &(bind_c_sym->where));
9678               has_error = 1;
9679             }
9680           else if (sym->attr.contained == 0 
9681                    && (sym->attr.if_source == IFSRC_IFBODY 
9682                        && sym->attr.flavor == FL_PROCEDURE) 
9683                    && (bind_c_sym->sym_name != NULL 
9684                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9685             {
9686               /* Make sure procedures in interface bodies don't collide.  */
9687               gfc_error ("Binding label '%s' in interface body at %L collides "
9688                          "with the global entity '%s' at %L",
9689                          sym->binding_label,
9690                          &(sym->declared_at), bind_c_sym->name,
9691                          &(bind_c_sym->where));
9692               has_error = 1;
9693             }
9694           else if (sym->attr.contained == 0 
9695                    && sym->attr.if_source == IFSRC_UNKNOWN)
9696             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9697                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
9698                 || sym->attr.use_assoc == 0)
9699               {
9700                 gfc_error ("Binding label '%s' at %L collides with global "
9701                            "entity '%s' at %L", sym->binding_label,
9702                            &(sym->declared_at), bind_c_sym->name,
9703                            &(bind_c_sym->where));
9704                 has_error = 1;
9705               }
9706
9707           if (has_error != 0)
9708             /* Clear the binding label to prevent checking multiple times.  */
9709             sym->binding_label[0] = '\0';
9710         }
9711       else if (bind_c_sym == NULL)
9712         {
9713           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9714           bind_c_sym->where = sym->declared_at;
9715           bind_c_sym->sym_name = sym->name;
9716
9717           if (sym->attr.use_assoc == 1)
9718             bind_c_sym->mod_name = sym->module;
9719           else
9720             if (sym->ns->proc_name != NULL)
9721               bind_c_sym->mod_name = sym->ns->proc_name->name;
9722
9723           if (sym->attr.contained == 0)
9724             {
9725               if (sym->attr.subroutine)
9726                 bind_c_sym->type = GSYM_SUBROUTINE;
9727               else if (sym->attr.function)
9728                 bind_c_sym->type = GSYM_FUNCTION;
9729             }
9730         }
9731     }
9732   return;
9733 }
9734
9735
9736 /* Resolve an index expression.  */
9737
9738 static gfc_try
9739 resolve_index_expr (gfc_expr *e)
9740 {
9741   if (gfc_resolve_expr (e) == FAILURE)
9742     return FAILURE;
9743
9744   if (gfc_simplify_expr (e, 0) == FAILURE)
9745     return FAILURE;
9746
9747   if (gfc_specification_expr (e) == FAILURE)
9748     return FAILURE;
9749
9750   return SUCCESS;
9751 }
9752
9753
9754 /* Resolve a charlen structure.  */
9755
9756 static gfc_try
9757 resolve_charlen (gfc_charlen *cl)
9758 {
9759   int i, k;
9760
9761   if (cl->resolved)
9762     return SUCCESS;
9763
9764   cl->resolved = 1;
9765
9766   specification_expr = 1;
9767
9768   if (resolve_index_expr (cl->length) == FAILURE)
9769     {
9770       specification_expr = 0;
9771       return FAILURE;
9772     }
9773
9774   /* "If the character length parameter value evaluates to a negative
9775      value, the length of character entities declared is zero."  */
9776   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9777     {
9778       if (gfc_option.warn_surprising)
9779         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9780                          " the length has been set to zero",
9781                          &cl->length->where, i);
9782       gfc_replace_expr (cl->length,
9783                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9784     }
9785
9786   /* Check that the character length is not too large.  */
9787   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9788   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9789       && cl->length->ts.type == BT_INTEGER
9790       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9791     {
9792       gfc_error ("String length at %L is too large", &cl->length->where);
9793       return FAILURE;
9794     }
9795
9796   return SUCCESS;
9797 }
9798
9799
9800 /* Test for non-constant shape arrays.  */
9801
9802 static bool
9803 is_non_constant_shape_array (gfc_symbol *sym)
9804 {
9805   gfc_expr *e;
9806   int i;
9807   bool not_constant;
9808
9809   not_constant = false;
9810   if (sym->as != NULL)
9811     {
9812       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9813          has not been simplified; parameter array references.  Do the
9814          simplification now.  */
9815       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9816         {
9817           e = sym->as->lower[i];
9818           if (e && (resolve_index_expr (e) == FAILURE
9819                     || !gfc_is_constant_expr (e)))
9820             not_constant = true;
9821           e = sym->as->upper[i];
9822           if (e && (resolve_index_expr (e) == FAILURE
9823                     || !gfc_is_constant_expr (e)))
9824             not_constant = true;
9825         }
9826     }
9827   return not_constant;
9828 }
9829
9830 /* Given a symbol and an initialization expression, add code to initialize
9831    the symbol to the function entry.  */
9832 static void
9833 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9834 {
9835   gfc_expr *lval;
9836   gfc_code *init_st;
9837   gfc_namespace *ns = sym->ns;
9838
9839   /* Search for the function namespace if this is a contained
9840      function without an explicit result.  */
9841   if (sym->attr.function && sym == sym->result
9842       && sym->name != sym->ns->proc_name->name)
9843     {
9844       ns = ns->contained;
9845       for (;ns; ns = ns->sibling)
9846         if (strcmp (ns->proc_name->name, sym->name) == 0)
9847           break;
9848     }
9849
9850   if (ns == NULL)
9851     {
9852       gfc_free_expr (init);
9853       return;
9854     }
9855
9856   /* Build an l-value expression for the result.  */
9857   lval = gfc_lval_expr_from_sym (sym);
9858
9859   /* Add the code at scope entry.  */
9860   init_st = gfc_get_code ();
9861   init_st->next = ns->code;
9862   ns->code = init_st;
9863
9864   /* Assign the default initializer to the l-value.  */
9865   init_st->loc = sym->declared_at;
9866   init_st->op = EXEC_INIT_ASSIGN;
9867   init_st->expr1 = lval;
9868   init_st->expr2 = init;
9869 }
9870
9871 /* Assign the default initializer to a derived type variable or result.  */
9872
9873 static void
9874 apply_default_init (gfc_symbol *sym)
9875 {
9876   gfc_expr *init = NULL;
9877
9878   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9879     return;
9880
9881   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
9882     init = gfc_default_initializer (&sym->ts);
9883
9884   if (init == NULL && sym->ts.type != BT_CLASS)
9885     return;
9886
9887   build_init_assign (sym, init);
9888   sym->attr.referenced = 1;
9889 }
9890
9891 /* Build an initializer for a local integer, real, complex, logical, or
9892    character variable, based on the command line flags finit-local-zero,
9893    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9894    null if the symbol should not have a default initialization.  */
9895 static gfc_expr *
9896 build_default_init_expr (gfc_symbol *sym)
9897 {
9898   int char_len;
9899   gfc_expr *init_expr;
9900   int i;
9901
9902   /* These symbols should never have a default initialization.  */
9903   if (sym->attr.allocatable
9904       || sym->attr.external
9905       || sym->attr.dummy
9906       || sym->attr.pointer
9907       || sym->attr.in_equivalence
9908       || sym->attr.in_common
9909       || sym->attr.data
9910       || sym->module
9911       || sym->attr.cray_pointee
9912       || sym->attr.cray_pointer)
9913     return NULL;
9914
9915   /* Now we'll try to build an initializer expression.  */
9916   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
9917                                      &sym->declared_at);
9918
9919   /* We will only initialize integers, reals, complex, logicals, and
9920      characters, and only if the corresponding command-line flags
9921      were set.  Otherwise, we free init_expr and return null.  */
9922   switch (sym->ts.type)
9923     {    
9924     case BT_INTEGER:
9925       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9926         mpz_set_si (init_expr->value.integer, 
9927                          gfc_option.flag_init_integer_value);
9928       else
9929         {
9930           gfc_free_expr (init_expr);
9931           init_expr = NULL;
9932         }
9933       break;
9934
9935     case BT_REAL:
9936       switch (gfc_option.flag_init_real)
9937         {
9938         case GFC_INIT_REAL_SNAN:
9939           init_expr->is_snan = 1;
9940           /* Fall through.  */
9941         case GFC_INIT_REAL_NAN:
9942           mpfr_set_nan (init_expr->value.real);
9943           break;
9944
9945         case GFC_INIT_REAL_INF:
9946           mpfr_set_inf (init_expr->value.real, 1);
9947           break;
9948
9949         case GFC_INIT_REAL_NEG_INF:
9950           mpfr_set_inf (init_expr->value.real, -1);
9951           break;
9952
9953         case GFC_INIT_REAL_ZERO:
9954           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9955           break;
9956
9957         default:
9958           gfc_free_expr (init_expr);
9959           init_expr = NULL;
9960           break;
9961         }
9962       break;
9963           
9964     case BT_COMPLEX:
9965       switch (gfc_option.flag_init_real)
9966         {
9967         case GFC_INIT_REAL_SNAN:
9968           init_expr->is_snan = 1;
9969           /* Fall through.  */
9970         case GFC_INIT_REAL_NAN:
9971           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9972           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9973           break;
9974
9975         case GFC_INIT_REAL_INF:
9976           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
9977           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
9978           break;
9979
9980         case GFC_INIT_REAL_NEG_INF:
9981           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9982           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9983           break;
9984
9985         case GFC_INIT_REAL_ZERO:
9986           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9987           break;
9988
9989         default:
9990           gfc_free_expr (init_expr);
9991           init_expr = NULL;
9992           break;
9993         }
9994       break;
9995           
9996     case BT_LOGICAL:
9997       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9998         init_expr->value.logical = 0;
9999       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
10000         init_expr->value.logical = 1;
10001       else
10002         {
10003           gfc_free_expr (init_expr);
10004           init_expr = NULL;
10005         }
10006       break;
10007           
10008     case BT_CHARACTER:
10009       /* For characters, the length must be constant in order to 
10010          create a default initializer.  */
10011       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
10012           && sym->ts.u.cl->length
10013           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
10014         {
10015           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
10016           init_expr->value.character.length = char_len;
10017           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
10018           for (i = 0; i < char_len; i++)
10019             init_expr->value.character.string[i]
10020               = (unsigned char) gfc_option.flag_init_character_value;
10021         }
10022       else
10023         {
10024           gfc_free_expr (init_expr);
10025           init_expr = NULL;
10026         }
10027       break;
10028           
10029     default:
10030      gfc_free_expr (init_expr);
10031      init_expr = NULL;
10032     }
10033   return init_expr;
10034 }
10035
10036 /* Add an initialization expression to a local variable.  */
10037 static void
10038 apply_default_init_local (gfc_symbol *sym)
10039 {
10040   gfc_expr *init = NULL;
10041
10042   /* The symbol should be a variable or a function return value.  */
10043   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
10044       || (sym->attr.function && sym->result != sym))
10045     return;
10046
10047   /* Try to build the initializer expression.  If we can't initialize
10048      this symbol, then init will be NULL.  */
10049   init = build_default_init_expr (sym);
10050   if (init == NULL)
10051     return;
10052
10053   /* For saved variables, we don't want to add an initializer at 
10054      function entry, so we just add a static initializer.  */
10055   if (sym->attr.save || sym->ns->save_all 
10056       || gfc_option.flag_max_stack_var_size == 0)
10057     {
10058       /* Don't clobber an existing initializer!  */
10059       gcc_assert (sym->value == NULL);
10060       sym->value = init;
10061       return;
10062     }
10063
10064   build_init_assign (sym, init);
10065 }
10066
10067
10068 /* Resolution of common features of flavors variable and procedure.  */
10069
10070 static gfc_try
10071 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
10072 {
10073   /* Avoid double diagnostics for function result symbols.  */
10074   if ((sym->result || sym->attr.result) && !sym->attr.dummy
10075       && (sym->ns != gfc_current_ns))
10076     return SUCCESS;
10077
10078   /* Constraints on deferred shape variable.  */
10079   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
10080     {
10081       if (sym->attr.allocatable)
10082         {
10083           if (sym->attr.dimension)
10084             {
10085               gfc_error ("Allocatable array '%s' at %L must have "
10086                          "a deferred shape", sym->name, &sym->declared_at);
10087               return FAILURE;
10088             }
10089           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
10090                                    "may not be ALLOCATABLE", sym->name,
10091                                    &sym->declared_at) == FAILURE)
10092             return FAILURE;
10093         }
10094
10095       if (sym->attr.pointer && sym->attr.dimension)
10096         {
10097           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
10098                      sym->name, &sym->declared_at);
10099           return FAILURE;
10100         }
10101     }
10102   else
10103     {
10104       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
10105           && sym->ts.type != BT_CLASS && !sym->assoc)
10106         {
10107           gfc_error ("Array '%s' at %L cannot have a deferred shape",
10108                      sym->name, &sym->declared_at);
10109           return FAILURE;
10110          }
10111     }
10112
10113   /* Constraints on polymorphic variables.  */
10114   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
10115     {
10116       /* F03:C502.  */
10117       if (sym->attr.class_ok
10118           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
10119         {
10120           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
10121                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
10122                      &sym->declared_at);
10123           return FAILURE;
10124         }
10125
10126       /* F03:C509.  */
10127       /* Assume that use associated symbols were checked in the module ns.
10128          Class-variables that are associate-names are also something special
10129          and excepted from the test.  */
10130       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
10131         {
10132           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
10133                      "or pointer", sym->name, &sym->declared_at);
10134           return FAILURE;
10135         }
10136     }
10137     
10138   return SUCCESS;
10139 }
10140
10141
10142 /* Additional checks for symbols with flavor variable and derived
10143    type.  To be called from resolve_fl_variable.  */
10144
10145 static gfc_try
10146 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
10147 {
10148   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
10149
10150   /* Check to see if a derived type is blocked from being host
10151      associated by the presence of another class I symbol in the same
10152      namespace.  14.6.1.3 of the standard and the discussion on
10153      comp.lang.fortran.  */
10154   if (sym->ns != sym->ts.u.derived->ns
10155       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
10156     {
10157       gfc_symbol *s;
10158       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
10159       if (s && s->attr.generic)
10160         s = gfc_find_dt_in_generic (s);
10161       if (s && s->attr.flavor != FL_DERIVED)
10162         {
10163           gfc_error ("The type '%s' cannot be host associated at %L "
10164                      "because it is blocked by an incompatible object "
10165                      "of the same name declared at %L",
10166                      sym->ts.u.derived->name, &sym->declared_at,
10167                      &s->declared_at);
10168           return FAILURE;
10169         }
10170     }
10171
10172   /* 4th constraint in section 11.3: "If an object of a type for which
10173      component-initialization is specified (R429) appears in the
10174      specification-part of a module and does not have the ALLOCATABLE
10175      or POINTER attribute, the object shall have the SAVE attribute."
10176
10177      The check for initializers is performed with
10178      gfc_has_default_initializer because gfc_default_initializer generates
10179      a hidden default for allocatable components.  */
10180   if (!(sym->value || no_init_flag) && sym->ns->proc_name
10181       && sym->ns->proc_name->attr.flavor == FL_MODULE
10182       && !sym->ns->save_all && !sym->attr.save
10183       && !sym->attr.pointer && !sym->attr.allocatable
10184       && gfc_has_default_initializer (sym->ts.u.derived)
10185       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
10186                          "module variable '%s' at %L, needed due to "
10187                          "the default initialization", sym->name,
10188                          &sym->declared_at) == FAILURE)
10189     return FAILURE;
10190
10191   /* Assign default initializer.  */
10192   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
10193       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
10194     {
10195       sym->value = gfc_default_initializer (&sym->ts);
10196     }
10197
10198   return SUCCESS;
10199 }
10200
10201
10202 /* Resolve symbols with flavor variable.  */
10203
10204 static gfc_try
10205 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
10206 {
10207   int no_init_flag, automatic_flag;
10208   gfc_expr *e;
10209   const char *auto_save_msg;
10210
10211   auto_save_msg = "Automatic object '%s' at %L cannot have the "
10212                   "SAVE attribute";
10213
10214   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10215     return FAILURE;
10216
10217   /* Set this flag to check that variables are parameters of all entries.
10218      This check is effected by the call to gfc_resolve_expr through
10219      is_non_constant_shape_array.  */
10220   specification_expr = 1;
10221
10222   if (sym->ns->proc_name
10223       && (sym->ns->proc_name->attr.flavor == FL_MODULE
10224           || sym->ns->proc_name->attr.is_main_program)
10225       && !sym->attr.use_assoc
10226       && !sym->attr.allocatable
10227       && !sym->attr.pointer
10228       && is_non_constant_shape_array (sym))
10229     {
10230       /* The shape of a main program or module array needs to be
10231          constant.  */
10232       gfc_error ("The module or main program array '%s' at %L must "
10233                  "have constant shape", sym->name, &sym->declared_at);
10234       specification_expr = 0;
10235       return FAILURE;
10236     }
10237
10238   /* Constraints on deferred type parameter.  */
10239   if (sym->ts.deferred && !(sym->attr.pointer || sym->attr.allocatable))
10240     {
10241       gfc_error ("Entity '%s' at %L has a deferred type parameter and "
10242                  "requires either the pointer or allocatable attribute",
10243                      sym->name, &sym->declared_at);
10244       return FAILURE;
10245     }
10246
10247   if (sym->ts.type == BT_CHARACTER)
10248     {
10249       /* Make sure that character string variables with assumed length are
10250          dummy arguments.  */
10251       e = sym->ts.u.cl->length;
10252       if (e == NULL && !sym->attr.dummy && !sym->attr.result
10253           && !sym->ts.deferred)
10254         {
10255           gfc_error ("Entity with assumed character length at %L must be a "
10256                      "dummy argument or a PARAMETER", &sym->declared_at);
10257           return FAILURE;
10258         }
10259
10260       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
10261         {
10262           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10263           return FAILURE;
10264         }
10265
10266       if (!gfc_is_constant_expr (e)
10267           && !(e->expr_type == EXPR_VARIABLE
10268                && e->symtree->n.sym->attr.flavor == FL_PARAMETER))
10269         {
10270           if (!sym->attr.use_assoc && sym->ns->proc_name
10271               && (sym->ns->proc_name->attr.flavor == FL_MODULE
10272                   || sym->ns->proc_name->attr.is_main_program))
10273             {
10274               gfc_error ("'%s' at %L must have constant character length "
10275                         "in this context", sym->name, &sym->declared_at);
10276               return FAILURE;
10277             }
10278           if (sym->attr.in_common)
10279             {
10280               gfc_error ("COMMON variable '%s' at %L must have constant "
10281                          "character length", sym->name, &sym->declared_at);
10282               return FAILURE;
10283             }
10284         }
10285     }
10286
10287   if (sym->value == NULL && sym->attr.referenced)
10288     apply_default_init_local (sym); /* Try to apply a default initialization.  */
10289
10290   /* Determine if the symbol may not have an initializer.  */
10291   no_init_flag = automatic_flag = 0;
10292   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
10293       || sym->attr.intrinsic || sym->attr.result)
10294     no_init_flag = 1;
10295   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
10296            && is_non_constant_shape_array (sym))
10297     {
10298       no_init_flag = automatic_flag = 1;
10299
10300       /* Also, they must not have the SAVE attribute.
10301          SAVE_IMPLICIT is checked below.  */
10302       if (sym->as && sym->attr.codimension)
10303         {
10304           int corank = sym->as->corank;
10305           sym->as->corank = 0;
10306           no_init_flag = automatic_flag = is_non_constant_shape_array (sym);
10307           sym->as->corank = corank;
10308         }
10309       if (automatic_flag && sym->attr.save == SAVE_EXPLICIT)
10310         {
10311           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10312           return FAILURE;
10313         }
10314     }
10315
10316   /* Ensure that any initializer is simplified.  */
10317   if (sym->value)
10318     gfc_simplify_expr (sym->value, 1);
10319
10320   /* Reject illegal initializers.  */
10321   if (!sym->mark && sym->value)
10322     {
10323       if (sym->attr.allocatable || (sym->ts.type == BT_CLASS
10324                                     && CLASS_DATA (sym)->attr.allocatable))
10325         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
10326                    sym->name, &sym->declared_at);
10327       else if (sym->attr.external)
10328         gfc_error ("External '%s' at %L cannot have an initializer",
10329                    sym->name, &sym->declared_at);
10330       else if (sym->attr.dummy
10331         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
10332         gfc_error ("Dummy '%s' at %L cannot have an initializer",
10333                    sym->name, &sym->declared_at);
10334       else if (sym->attr.intrinsic)
10335         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
10336                    sym->name, &sym->declared_at);
10337       else if (sym->attr.result)
10338         gfc_error ("Function result '%s' at %L cannot have an initializer",
10339                    sym->name, &sym->declared_at);
10340       else if (automatic_flag)
10341         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
10342                    sym->name, &sym->declared_at);
10343       else
10344         goto no_init_error;
10345       return FAILURE;
10346     }
10347
10348 no_init_error:
10349   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
10350     return resolve_fl_variable_derived (sym, no_init_flag);
10351
10352   return SUCCESS;
10353 }
10354
10355
10356 /* Resolve a procedure.  */
10357
10358 static gfc_try
10359 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
10360 {
10361   gfc_formal_arglist *arg;
10362
10363   if (sym->attr.function
10364       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10365     return FAILURE;
10366
10367   if (sym->ts.type == BT_CHARACTER)
10368     {
10369       gfc_charlen *cl = sym->ts.u.cl;
10370
10371       if (cl && cl->length && gfc_is_constant_expr (cl->length)
10372              && resolve_charlen (cl) == FAILURE)
10373         return FAILURE;
10374
10375       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10376           && sym->attr.proc == PROC_ST_FUNCTION)
10377         {
10378           gfc_error ("Character-valued statement function '%s' at %L must "
10379                      "have constant length", sym->name, &sym->declared_at);
10380           return FAILURE;
10381         }
10382     }
10383
10384   /* Ensure that derived type for are not of a private type.  Internal
10385      module procedures are excluded by 2.2.3.3 - i.e., they are not
10386      externally accessible and can access all the objects accessible in
10387      the host.  */
10388   if (!(sym->ns->parent
10389         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
10390       && gfc_check_symbol_access (sym))
10391     {
10392       gfc_interface *iface;
10393
10394       for (arg = sym->formal; arg; arg = arg->next)
10395         {
10396           if (arg->sym
10397               && arg->sym->ts.type == BT_DERIVED
10398               && !arg->sym->ts.u.derived->attr.use_assoc
10399               && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10400               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
10401                                  "PRIVATE type and cannot be a dummy argument"
10402                                  " of '%s', which is PUBLIC at %L",
10403                                  arg->sym->name, sym->name, &sym->declared_at)
10404                  == FAILURE)
10405             {
10406               /* Stop this message from recurring.  */
10407               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10408               return FAILURE;
10409             }
10410         }
10411
10412       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10413          PRIVATE to the containing module.  */
10414       for (iface = sym->generic; iface; iface = iface->next)
10415         {
10416           for (arg = iface->sym->formal; arg; arg = arg->next)
10417             {
10418               if (arg->sym
10419                   && arg->sym->ts.type == BT_DERIVED
10420                   && !arg->sym->ts.u.derived->attr.use_assoc
10421                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10422                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10423                                      "'%s' in PUBLIC interface '%s' at %L "
10424                                      "takes dummy arguments of '%s' which is "
10425                                      "PRIVATE", iface->sym->name, sym->name,
10426                                      &iface->sym->declared_at,
10427                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10428                 {
10429                   /* Stop this message from recurring.  */
10430                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10431                   return FAILURE;
10432                 }
10433              }
10434         }
10435
10436       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10437          PRIVATE to the containing module.  */
10438       for (iface = sym->generic; iface; iface = iface->next)
10439         {
10440           for (arg = iface->sym->formal; arg; arg = arg->next)
10441             {
10442               if (arg->sym
10443                   && arg->sym->ts.type == BT_DERIVED
10444                   && !arg->sym->ts.u.derived->attr.use_assoc
10445                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10446                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10447                                      "'%s' in PUBLIC interface '%s' at %L "
10448                                      "takes dummy arguments of '%s' which is "
10449                                      "PRIVATE", iface->sym->name, sym->name,
10450                                      &iface->sym->declared_at,
10451                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10452                 {
10453                   /* Stop this message from recurring.  */
10454                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10455                   return FAILURE;
10456                 }
10457              }
10458         }
10459     }
10460
10461   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10462       && !sym->attr.proc_pointer)
10463     {
10464       gfc_error ("Function '%s' at %L cannot have an initializer",
10465                  sym->name, &sym->declared_at);
10466       return FAILURE;
10467     }
10468
10469   /* An external symbol may not have an initializer because it is taken to be
10470      a procedure. Exception: Procedure Pointers.  */
10471   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10472     {
10473       gfc_error ("External object '%s' at %L may not have an initializer",
10474                  sym->name, &sym->declared_at);
10475       return FAILURE;
10476     }
10477
10478   /* An elemental function is required to return a scalar 12.7.1  */
10479   if (sym->attr.elemental && sym->attr.function && sym->as)
10480     {
10481       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10482                  "result", sym->name, &sym->declared_at);
10483       /* Reset so that the error only occurs once.  */
10484       sym->attr.elemental = 0;
10485       return FAILURE;
10486     }
10487
10488   if (sym->attr.proc == PROC_ST_FUNCTION
10489       && (sym->attr.allocatable || sym->attr.pointer))
10490     {
10491       gfc_error ("Statement function '%s' at %L may not have pointer or "
10492                  "allocatable attribute", sym->name, &sym->declared_at);
10493       return FAILURE;
10494     }
10495
10496   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10497      char-len-param shall not be array-valued, pointer-valued, recursive
10498      or pure.  ....snip... A character value of * may only be used in the
10499      following ways: (i) Dummy arg of procedure - dummy associates with
10500      actual length; (ii) To declare a named constant; or (iii) External
10501      function - but length must be declared in calling scoping unit.  */
10502   if (sym->attr.function
10503       && sym->ts.type == BT_CHARACTER
10504       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10505     {
10506       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10507           || (sym->attr.recursive) || (sym->attr.pure))
10508         {
10509           if (sym->as && sym->as->rank)
10510             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10511                        "array-valued", sym->name, &sym->declared_at);
10512
10513           if (sym->attr.pointer)
10514             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10515                        "pointer-valued", sym->name, &sym->declared_at);
10516
10517           if (sym->attr.pure)
10518             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10519                        "pure", sym->name, &sym->declared_at);
10520
10521           if (sym->attr.recursive)
10522             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10523                        "recursive", sym->name, &sym->declared_at);
10524
10525           return FAILURE;
10526         }
10527
10528       /* Appendix B.2 of the standard.  Contained functions give an
10529          error anyway.  Fixed-form is likely to be F77/legacy. Deferred
10530          character length is an F2003 feature.  */
10531       if (!sym->attr.contained
10532             && gfc_current_form != FORM_FIXED
10533             && !sym->ts.deferred)
10534         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10535                         "CHARACTER(*) function '%s' at %L",
10536                         sym->name, &sym->declared_at);
10537     }
10538
10539   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10540     {
10541       gfc_formal_arglist *curr_arg;
10542       int has_non_interop_arg = 0;
10543
10544       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10545                              sym->common_block) == FAILURE)
10546         {
10547           /* Clear these to prevent looking at them again if there was an
10548              error.  */
10549           sym->attr.is_bind_c = 0;
10550           sym->attr.is_c_interop = 0;
10551           sym->ts.is_c_interop = 0;
10552         }
10553       else
10554         {
10555           /* So far, no errors have been found.  */
10556           sym->attr.is_c_interop = 1;
10557           sym->ts.is_c_interop = 1;
10558         }
10559       
10560       curr_arg = sym->formal;
10561       while (curr_arg != NULL)
10562         {
10563           /* Skip implicitly typed dummy args here.  */
10564           if (curr_arg->sym->attr.implicit_type == 0)
10565             if (gfc_verify_c_interop_param (curr_arg->sym) == FAILURE)
10566               /* If something is found to fail, record the fact so we
10567                  can mark the symbol for the procedure as not being
10568                  BIND(C) to try and prevent multiple errors being
10569                  reported.  */
10570               has_non_interop_arg = 1;
10571           
10572           curr_arg = curr_arg->next;
10573         }
10574
10575       /* See if any of the arguments were not interoperable and if so, clear
10576          the procedure symbol to prevent duplicate error messages.  */
10577       if (has_non_interop_arg != 0)
10578         {
10579           sym->attr.is_c_interop = 0;
10580           sym->ts.is_c_interop = 0;
10581           sym->attr.is_bind_c = 0;
10582         }
10583     }
10584   
10585   if (!sym->attr.proc_pointer)
10586     {
10587       if (sym->attr.save == SAVE_EXPLICIT)
10588         {
10589           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10590                      "in '%s' at %L", sym->name, &sym->declared_at);
10591           return FAILURE;
10592         }
10593       if (sym->attr.intent)
10594         {
10595           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10596                      "in '%s' at %L", sym->name, &sym->declared_at);
10597           return FAILURE;
10598         }
10599       if (sym->attr.subroutine && sym->attr.result)
10600         {
10601           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10602                      "in '%s' at %L", sym->name, &sym->declared_at);
10603           return FAILURE;
10604         }
10605       if (sym->attr.external && sym->attr.function
10606           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10607               || sym->attr.contained))
10608         {
10609           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10610                      "in '%s' at %L", sym->name, &sym->declared_at);
10611           return FAILURE;
10612         }
10613       if (strcmp ("ppr@", sym->name) == 0)
10614         {
10615           gfc_error ("Procedure pointer result '%s' at %L "
10616                      "is missing the pointer attribute",
10617                      sym->ns->proc_name->name, &sym->declared_at);
10618           return FAILURE;
10619         }
10620     }
10621
10622   return SUCCESS;
10623 }
10624
10625
10626 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10627    been defined and we now know their defined arguments, check that they fulfill
10628    the requirements of the standard for procedures used as finalizers.  */
10629
10630 static gfc_try
10631 gfc_resolve_finalizers (gfc_symbol* derived)
10632 {
10633   gfc_finalizer* list;
10634   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10635   gfc_try result = SUCCESS;
10636   bool seen_scalar = false;
10637
10638   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10639     return SUCCESS;
10640
10641   /* Walk over the list of finalizer-procedures, check them, and if any one
10642      does not fit in with the standard's definition, print an error and remove
10643      it from the list.  */
10644   prev_link = &derived->f2k_derived->finalizers;
10645   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10646     {
10647       gfc_symbol* arg;
10648       gfc_finalizer* i;
10649       int my_rank;
10650
10651       /* Skip this finalizer if we already resolved it.  */
10652       if (list->proc_tree)
10653         {
10654           prev_link = &(list->next);
10655           continue;
10656         }
10657
10658       /* Check this exists and is a SUBROUTINE.  */
10659       if (!list->proc_sym->attr.subroutine)
10660         {
10661           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10662                      list->proc_sym->name, &list->where);
10663           goto error;
10664         }
10665
10666       /* We should have exactly one argument.  */
10667       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10668         {
10669           gfc_error ("FINAL procedure at %L must have exactly one argument",
10670                      &list->where);
10671           goto error;
10672         }
10673       arg = list->proc_sym->formal->sym;
10674
10675       /* This argument must be of our type.  */
10676       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10677         {
10678           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10679                      &arg->declared_at, derived->name);
10680           goto error;
10681         }
10682
10683       /* It must neither be a pointer nor allocatable nor optional.  */
10684       if (arg->attr.pointer)
10685         {
10686           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10687                      &arg->declared_at);
10688           goto error;
10689         }
10690       if (arg->attr.allocatable)
10691         {
10692           gfc_error ("Argument of FINAL procedure at %L must not be"
10693                      " ALLOCATABLE", &arg->declared_at);
10694           goto error;
10695         }
10696       if (arg->attr.optional)
10697         {
10698           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10699                      &arg->declared_at);
10700           goto error;
10701         }
10702
10703       /* It must not be INTENT(OUT).  */
10704       if (arg->attr.intent == INTENT_OUT)
10705         {
10706           gfc_error ("Argument of FINAL procedure at %L must not be"
10707                      " INTENT(OUT)", &arg->declared_at);
10708           goto error;
10709         }
10710
10711       /* Warn if the procedure is non-scalar and not assumed shape.  */
10712       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10713           && arg->as->type != AS_ASSUMED_SHAPE)
10714         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10715                      " shape argument", &arg->declared_at);
10716
10717       /* Check that it does not match in kind and rank with a FINAL procedure
10718          defined earlier.  To really loop over the *earlier* declarations,
10719          we need to walk the tail of the list as new ones were pushed at the
10720          front.  */
10721       /* TODO: Handle kind parameters once they are implemented.  */
10722       my_rank = (arg->as ? arg->as->rank : 0);
10723       for (i = list->next; i; i = i->next)
10724         {
10725           /* Argument list might be empty; that is an error signalled earlier,
10726              but we nevertheless continued resolving.  */
10727           if (i->proc_sym->formal)
10728             {
10729               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10730               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10731               if (i_rank == my_rank)
10732                 {
10733                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10734                              " rank (%d) as '%s'",
10735                              list->proc_sym->name, &list->where, my_rank, 
10736                              i->proc_sym->name);
10737                   goto error;
10738                 }
10739             }
10740         }
10741
10742         /* Is this the/a scalar finalizer procedure?  */
10743         if (!arg->as || arg->as->rank == 0)
10744           seen_scalar = true;
10745
10746         /* Find the symtree for this procedure.  */
10747         gcc_assert (!list->proc_tree);
10748         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10749
10750         prev_link = &list->next;
10751         continue;
10752
10753         /* Remove wrong nodes immediately from the list so we don't risk any
10754            troubles in the future when they might fail later expectations.  */
10755 error:
10756         result = FAILURE;
10757         i = list;
10758         *prev_link = list->next;
10759         gfc_free_finalizer (i);
10760     }
10761
10762   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10763      were nodes in the list, must have been for arrays.  It is surely a good
10764      idea to have a scalar version there if there's something to finalize.  */
10765   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10766     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10767                  " defined at %L, suggest also scalar one",
10768                  derived->name, &derived->declared_at);
10769
10770   /* TODO:  Remove this error when finalization is finished.  */
10771   gfc_error ("Finalization at %L is not yet implemented",
10772              &derived->declared_at);
10773
10774   return result;
10775 }
10776
10777
10778 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10779
10780 static gfc_try
10781 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10782                              const char* generic_name, locus where)
10783 {
10784   gfc_symbol* sym1;
10785   gfc_symbol* sym2;
10786
10787   gcc_assert (t1->specific && t2->specific);
10788   gcc_assert (!t1->specific->is_generic);
10789   gcc_assert (!t2->specific->is_generic);
10790
10791   sym1 = t1->specific->u.specific->n.sym;
10792   sym2 = t2->specific->u.specific->n.sym;
10793
10794   if (sym1 == sym2)
10795     return SUCCESS;
10796
10797   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10798   if (sym1->attr.subroutine != sym2->attr.subroutine
10799       || sym1->attr.function != sym2->attr.function)
10800     {
10801       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10802                  " GENERIC '%s' at %L",
10803                  sym1->name, sym2->name, generic_name, &where);
10804       return FAILURE;
10805     }
10806
10807   /* Compare the interfaces.  */
10808   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10809     {
10810       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10811                  sym1->name, sym2->name, generic_name, &where);
10812       return FAILURE;
10813     }
10814
10815   return SUCCESS;
10816 }
10817
10818
10819 /* Worker function for resolving a generic procedure binding; this is used to
10820    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10821
10822    The difference between those cases is finding possible inherited bindings
10823    that are overridden, as one has to look for them in tb_sym_root,
10824    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10825    the super-type and set p->overridden correctly.  */
10826
10827 static gfc_try
10828 resolve_tb_generic_targets (gfc_symbol* super_type,
10829                             gfc_typebound_proc* p, const char* name)
10830 {
10831   gfc_tbp_generic* target;
10832   gfc_symtree* first_target;
10833   gfc_symtree* inherited;
10834
10835   gcc_assert (p && p->is_generic);
10836
10837   /* Try to find the specific bindings for the symtrees in our target-list.  */
10838   gcc_assert (p->u.generic);
10839   for (target = p->u.generic; target; target = target->next)
10840     if (!target->specific)
10841       {
10842         gfc_typebound_proc* overridden_tbp;
10843         gfc_tbp_generic* g;
10844         const char* target_name;
10845
10846         target_name = target->specific_st->name;
10847
10848         /* Defined for this type directly.  */
10849         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
10850           {
10851             target->specific = target->specific_st->n.tb;
10852             goto specific_found;
10853           }
10854
10855         /* Look for an inherited specific binding.  */
10856         if (super_type)
10857           {
10858             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10859                                                  true, NULL);
10860
10861             if (inherited)
10862               {
10863                 gcc_assert (inherited->n.tb);
10864                 target->specific = inherited->n.tb;
10865                 goto specific_found;
10866               }
10867           }
10868
10869         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10870                    " at %L", target_name, name, &p->where);
10871         return FAILURE;
10872
10873         /* Once we've found the specific binding, check it is not ambiguous with
10874            other specifics already found or inherited for the same GENERIC.  */
10875 specific_found:
10876         gcc_assert (target->specific);
10877
10878         /* This must really be a specific binding!  */
10879         if (target->specific->is_generic)
10880           {
10881             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10882                        " '%s' is GENERIC, too", name, &p->where, target_name);
10883             return FAILURE;
10884           }
10885
10886         /* Check those already resolved on this type directly.  */
10887         for (g = p->u.generic; g; g = g->next)
10888           if (g != target && g->specific
10889               && check_generic_tbp_ambiguity (target, g, name, p->where)
10890                   == FAILURE)
10891             return FAILURE;
10892
10893         /* Check for ambiguity with inherited specific targets.  */
10894         for (overridden_tbp = p->overridden; overridden_tbp;
10895              overridden_tbp = overridden_tbp->overridden)
10896           if (overridden_tbp->is_generic)
10897             {
10898               for (g = overridden_tbp->u.generic; g; g = g->next)
10899                 {
10900                   gcc_assert (g->specific);
10901                   if (check_generic_tbp_ambiguity (target, g,
10902                                                    name, p->where) == FAILURE)
10903                     return FAILURE;
10904                 }
10905             }
10906       }
10907
10908   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10909   if (p->overridden && !p->overridden->is_generic)
10910     {
10911       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10912                  " the same name", name, &p->where);
10913       return FAILURE;
10914     }
10915
10916   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10917      all must have the same attributes here.  */
10918   first_target = p->u.generic->specific->u.specific;
10919   gcc_assert (first_target);
10920   p->subroutine = first_target->n.sym->attr.subroutine;
10921   p->function = first_target->n.sym->attr.function;
10922
10923   return SUCCESS;
10924 }
10925
10926
10927 /* Resolve a GENERIC procedure binding for a derived type.  */
10928
10929 static gfc_try
10930 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10931 {
10932   gfc_symbol* super_type;
10933
10934   /* Find the overridden binding if any.  */
10935   st->n.tb->overridden = NULL;
10936   super_type = gfc_get_derived_super_type (derived);
10937   if (super_type)
10938     {
10939       gfc_symtree* overridden;
10940       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10941                                             true, NULL);
10942
10943       if (overridden && overridden->n.tb)
10944         st->n.tb->overridden = overridden->n.tb;
10945     }
10946
10947   /* Resolve using worker function.  */
10948   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10949 }
10950
10951
10952 /* Retrieve the target-procedure of an operator binding and do some checks in
10953    common for intrinsic and user-defined type-bound operators.  */
10954
10955 static gfc_symbol*
10956 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10957 {
10958   gfc_symbol* target_proc;
10959
10960   gcc_assert (target->specific && !target->specific->is_generic);
10961   target_proc = target->specific->u.specific->n.sym;
10962   gcc_assert (target_proc);
10963
10964   /* All operator bindings must have a passed-object dummy argument.  */
10965   if (target->specific->nopass)
10966     {
10967       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10968       return NULL;
10969     }
10970
10971   return target_proc;
10972 }
10973
10974
10975 /* Resolve a type-bound intrinsic operator.  */
10976
10977 static gfc_try
10978 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10979                                 gfc_typebound_proc* p)
10980 {
10981   gfc_symbol* super_type;
10982   gfc_tbp_generic* target;
10983   
10984   /* If there's already an error here, do nothing (but don't fail again).  */
10985   if (p->error)
10986     return SUCCESS;
10987
10988   /* Operators should always be GENERIC bindings.  */
10989   gcc_assert (p->is_generic);
10990
10991   /* Look for an overridden binding.  */
10992   super_type = gfc_get_derived_super_type (derived);
10993   if (super_type && super_type->f2k_derived)
10994     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10995                                                      op, true, NULL);
10996   else
10997     p->overridden = NULL;
10998
10999   /* Resolve general GENERIC properties using worker function.  */
11000   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
11001     goto error;
11002
11003   /* Check the targets to be procedures of correct interface.  */
11004   for (target = p->u.generic; target; target = target->next)
11005     {
11006       gfc_symbol* target_proc;
11007
11008       target_proc = get_checked_tb_operator_target (target, p->where);
11009       if (!target_proc)
11010         goto error;
11011
11012       if (!gfc_check_operator_interface (target_proc, op, p->where))
11013         goto error;
11014     }
11015
11016   return SUCCESS;
11017
11018 error:
11019   p->error = 1;
11020   return FAILURE;
11021 }
11022
11023
11024 /* Resolve a type-bound user operator (tree-walker callback).  */
11025
11026 static gfc_symbol* resolve_bindings_derived;
11027 static gfc_try resolve_bindings_result;
11028
11029 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
11030
11031 static void
11032 resolve_typebound_user_op (gfc_symtree* stree)
11033 {
11034   gfc_symbol* super_type;
11035   gfc_tbp_generic* target;
11036
11037   gcc_assert (stree && stree->n.tb);
11038
11039   if (stree->n.tb->error)
11040     return;
11041
11042   /* Operators should always be GENERIC bindings.  */
11043   gcc_assert (stree->n.tb->is_generic);
11044
11045   /* Find overridden procedure, if any.  */
11046   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11047   if (super_type && super_type->f2k_derived)
11048     {
11049       gfc_symtree* overridden;
11050       overridden = gfc_find_typebound_user_op (super_type, NULL,
11051                                                stree->name, true, NULL);
11052
11053       if (overridden && overridden->n.tb)
11054         stree->n.tb->overridden = overridden->n.tb;
11055     }
11056   else
11057     stree->n.tb->overridden = NULL;
11058
11059   /* Resolve basically using worker function.  */
11060   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
11061         == FAILURE)
11062     goto error;
11063
11064   /* Check the targets to be functions of correct interface.  */
11065   for (target = stree->n.tb->u.generic; target; target = target->next)
11066     {
11067       gfc_symbol* target_proc;
11068
11069       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
11070       if (!target_proc)
11071         goto error;
11072
11073       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
11074         goto error;
11075     }
11076
11077   return;
11078
11079 error:
11080   resolve_bindings_result = FAILURE;
11081   stree->n.tb->error = 1;
11082 }
11083
11084
11085 /* Resolve the type-bound procedures for a derived type.  */
11086
11087 static void
11088 resolve_typebound_procedure (gfc_symtree* stree)
11089 {
11090   gfc_symbol* proc;
11091   locus where;
11092   gfc_symbol* me_arg;
11093   gfc_symbol* super_type;
11094   gfc_component* comp;
11095
11096   gcc_assert (stree);
11097
11098   /* Undefined specific symbol from GENERIC target definition.  */
11099   if (!stree->n.tb)
11100     return;
11101
11102   if (stree->n.tb->error)
11103     return;
11104
11105   /* If this is a GENERIC binding, use that routine.  */
11106   if (stree->n.tb->is_generic)
11107     {
11108       if (resolve_typebound_generic (resolve_bindings_derived, stree)
11109             == FAILURE)
11110         goto error;
11111       return;
11112     }
11113
11114   /* Get the target-procedure to check it.  */
11115   gcc_assert (!stree->n.tb->is_generic);
11116   gcc_assert (stree->n.tb->u.specific);
11117   proc = stree->n.tb->u.specific->n.sym;
11118   where = stree->n.tb->where;
11119
11120   /* Default access should already be resolved from the parser.  */
11121   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
11122
11123   /* It should be a module procedure or an external procedure with explicit
11124      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
11125   if ((!proc->attr.subroutine && !proc->attr.function)
11126       || (proc->attr.proc != PROC_MODULE
11127           && proc->attr.if_source != IFSRC_IFBODY)
11128       || (proc->attr.abstract && !stree->n.tb->deferred))
11129     {
11130       gfc_error ("'%s' must be a module procedure or an external procedure with"
11131                  " an explicit interface at %L", proc->name, &where);
11132       goto error;
11133     }
11134   stree->n.tb->subroutine = proc->attr.subroutine;
11135   stree->n.tb->function = proc->attr.function;
11136
11137   /* Find the super-type of the current derived type.  We could do this once and
11138      store in a global if speed is needed, but as long as not I believe this is
11139      more readable and clearer.  */
11140   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11141
11142   /* If PASS, resolve and check arguments if not already resolved / loaded
11143      from a .mod file.  */
11144   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
11145     {
11146       if (stree->n.tb->pass_arg)
11147         {
11148           gfc_formal_arglist* i;
11149
11150           /* If an explicit passing argument name is given, walk the arg-list
11151              and look for it.  */
11152
11153           me_arg = NULL;
11154           stree->n.tb->pass_arg_num = 1;
11155           for (i = proc->formal; i; i = i->next)
11156             {
11157               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
11158                 {
11159                   me_arg = i->sym;
11160                   break;
11161                 }
11162               ++stree->n.tb->pass_arg_num;
11163             }
11164
11165           if (!me_arg)
11166             {
11167               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
11168                          " argument '%s'",
11169                          proc->name, stree->n.tb->pass_arg, &where,
11170                          stree->n.tb->pass_arg);
11171               goto error;
11172             }
11173         }
11174       else
11175         {
11176           /* Otherwise, take the first one; there should in fact be at least
11177              one.  */
11178           stree->n.tb->pass_arg_num = 1;
11179           if (!proc->formal)
11180             {
11181               gfc_error ("Procedure '%s' with PASS at %L must have at"
11182                          " least one argument", proc->name, &where);
11183               goto error;
11184             }
11185           me_arg = proc->formal->sym;
11186         }
11187
11188       /* Now check that the argument-type matches and the passed-object
11189          dummy argument is generally fine.  */
11190
11191       gcc_assert (me_arg);
11192
11193       if (me_arg->ts.type != BT_CLASS)
11194         {
11195           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11196                      " at %L", proc->name, &where);
11197           goto error;
11198         }
11199
11200       if (CLASS_DATA (me_arg)->ts.u.derived
11201           != resolve_bindings_derived)
11202         {
11203           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11204                      " the derived-type '%s'", me_arg->name, proc->name,
11205                      me_arg->name, &where, resolve_bindings_derived->name);
11206           goto error;
11207         }
11208   
11209       gcc_assert (me_arg->ts.type == BT_CLASS);
11210       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
11211         {
11212           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
11213                      " scalar", proc->name, &where);
11214           goto error;
11215         }
11216       if (CLASS_DATA (me_arg)->attr.allocatable)
11217         {
11218           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11219                      " be ALLOCATABLE", proc->name, &where);
11220           goto error;
11221         }
11222       if (CLASS_DATA (me_arg)->attr.class_pointer)
11223         {
11224           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11225                      " be POINTER", proc->name, &where);
11226           goto error;
11227         }
11228     }
11229
11230   /* If we are extending some type, check that we don't override a procedure
11231      flagged NON_OVERRIDABLE.  */
11232   stree->n.tb->overridden = NULL;
11233   if (super_type)
11234     {
11235       gfc_symtree* overridden;
11236       overridden = gfc_find_typebound_proc (super_type, NULL,
11237                                             stree->name, true, NULL);
11238
11239       if (overridden)
11240         {
11241           if (overridden->n.tb)
11242             stree->n.tb->overridden = overridden->n.tb;
11243
11244           if (gfc_check_typebound_override (stree, overridden) == FAILURE)
11245             goto error;
11246         }
11247     }
11248
11249   /* See if there's a name collision with a component directly in this type.  */
11250   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11251     if (!strcmp (comp->name, stree->name))
11252       {
11253         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11254                    " '%s'",
11255                    stree->name, &where, resolve_bindings_derived->name);
11256         goto error;
11257       }
11258
11259   /* Try to find a name collision with an inherited component.  */
11260   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11261     {
11262       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11263                  " component of '%s'",
11264                  stree->name, &where, resolve_bindings_derived->name);
11265       goto error;
11266     }
11267
11268   stree->n.tb->error = 0;
11269   return;
11270
11271 error:
11272   resolve_bindings_result = FAILURE;
11273   stree->n.tb->error = 1;
11274 }
11275
11276
11277 static gfc_try
11278 resolve_typebound_procedures (gfc_symbol* derived)
11279 {
11280   int op;
11281   gfc_symbol* super_type;
11282
11283   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11284     return SUCCESS;
11285   
11286   super_type = gfc_get_derived_super_type (derived);
11287   if (super_type)
11288     resolve_typebound_procedures (super_type);
11289
11290   resolve_bindings_derived = derived;
11291   resolve_bindings_result = SUCCESS;
11292
11293   /* Make sure the vtab has been generated.  */
11294   gfc_find_derived_vtab (derived);
11295
11296   if (derived->f2k_derived->tb_sym_root)
11297     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11298                           &resolve_typebound_procedure);
11299
11300   if (derived->f2k_derived->tb_uop_root)
11301     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11302                           &resolve_typebound_user_op);
11303
11304   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11305     {
11306       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11307       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11308                                                p) == FAILURE)
11309         resolve_bindings_result = FAILURE;
11310     }
11311
11312   return resolve_bindings_result;
11313 }
11314
11315
11316 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11317    to give all identical derived types the same backend_decl.  */
11318 static void
11319 add_dt_to_dt_list (gfc_symbol *derived)
11320 {
11321   gfc_dt_list *dt_list;
11322
11323   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11324     if (derived == dt_list->derived)
11325       return;
11326
11327   dt_list = gfc_get_dt_list ();
11328   dt_list->next = gfc_derived_types;
11329   dt_list->derived = derived;
11330   gfc_derived_types = dt_list;
11331 }
11332
11333
11334 /* Ensure that a derived-type is really not abstract, meaning that every
11335    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11336
11337 static gfc_try
11338 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11339 {
11340   if (!st)
11341     return SUCCESS;
11342
11343   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11344     return FAILURE;
11345   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11346     return FAILURE;
11347
11348   if (st->n.tb && st->n.tb->deferred)
11349     {
11350       gfc_symtree* overriding;
11351       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11352       if (!overriding)
11353         return FAILURE;
11354       gcc_assert (overriding->n.tb);
11355       if (overriding->n.tb->deferred)
11356         {
11357           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11358                      " '%s' is DEFERRED and not overridden",
11359                      sub->name, &sub->declared_at, st->name);
11360           return FAILURE;
11361         }
11362     }
11363
11364   return SUCCESS;
11365 }
11366
11367 static gfc_try
11368 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11369 {
11370   /* The algorithm used here is to recursively travel up the ancestry of sub
11371      and for each ancestor-type, check all bindings.  If any of them is
11372      DEFERRED, look it up starting from sub and see if the found (overriding)
11373      binding is not DEFERRED.
11374      This is not the most efficient way to do this, but it should be ok and is
11375      clearer than something sophisticated.  */
11376
11377   gcc_assert (ancestor && !sub->attr.abstract);
11378   
11379   if (!ancestor->attr.abstract)
11380     return SUCCESS;
11381
11382   /* Walk bindings of this ancestor.  */
11383   if (ancestor->f2k_derived)
11384     {
11385       gfc_try t;
11386       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11387       if (t == FAILURE)
11388         return FAILURE;
11389     }
11390
11391   /* Find next ancestor type and recurse on it.  */
11392   ancestor = gfc_get_derived_super_type (ancestor);
11393   if (ancestor)
11394     return ensure_not_abstract (sub, ancestor);
11395
11396   return SUCCESS;
11397 }
11398
11399
11400 /* Resolve the components of a derived type. This does not have to wait until
11401    resolution stage, but can be done as soon as the dt declaration has been
11402    parsed.  */
11403
11404 static gfc_try
11405 resolve_fl_derived0 (gfc_symbol *sym)
11406 {
11407   gfc_symbol* super_type;
11408   gfc_component *c;
11409
11410   super_type = gfc_get_derived_super_type (sym);
11411
11412   /* F2008, C432. */
11413   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11414     {
11415       gfc_error ("As extending type '%s' at %L has a coarray component, "
11416                  "parent type '%s' shall also have one", sym->name,
11417                  &sym->declared_at, super_type->name);
11418       return FAILURE;
11419     }
11420
11421   /* Ensure the extended type gets resolved before we do.  */
11422   if (super_type && resolve_fl_derived0 (super_type) == FAILURE)
11423     return FAILURE;
11424
11425   /* An ABSTRACT type must be extensible.  */
11426   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11427     {
11428       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11429                  sym->name, &sym->declared_at);
11430       return FAILURE;
11431     }
11432
11433   for (c = sym->components; c != NULL; c = c->next)
11434     {
11435       /* See PRs 51550, 47545, 48654, 49050, 51075 - and 45170.  */
11436       if (c->ts.type == BT_CHARACTER && c->ts.deferred)
11437         {
11438           gfc_error ("Deferred-length character component '%s' at %L is not "
11439                      "yet supported", c->name, &c->loc);
11440           return FAILURE;
11441         }
11442
11443       /* F2008, C442.  */
11444       if ((!sym->attr.is_class || c != sym->components)
11445           && c->attr.codimension
11446           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11447         {
11448           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11449                      "deferred shape", c->name, &c->loc);
11450           return FAILURE;
11451         }
11452
11453       /* F2008, C443.  */
11454       if (c->attr.codimension && c->ts.type == BT_DERIVED
11455           && c->ts.u.derived->ts.is_iso_c)
11456         {
11457           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11458                      "shall not be a coarray", c->name, &c->loc);
11459           return FAILURE;
11460         }
11461
11462       /* F2008, C444.  */
11463       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11464           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11465               || c->attr.allocatable))
11466         {
11467           gfc_error ("Component '%s' at %L with coarray component "
11468                      "shall be a nonpointer, nonallocatable scalar",
11469                      c->name, &c->loc);
11470           return FAILURE;
11471         }
11472
11473       /* F2008, C448.  */
11474       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11475         {
11476           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11477                      "is not an array pointer", c->name, &c->loc);
11478           return FAILURE;
11479         }
11480
11481       if (c->attr.proc_pointer && c->ts.interface)
11482         {
11483           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11484             gfc_error ("Interface '%s', used by procedure pointer component "
11485                        "'%s' at %L, is declared in a later PROCEDURE statement",
11486                        c->ts.interface->name, c->name, &c->loc);
11487
11488           /* Get the attributes from the interface (now resolved).  */
11489           if (c->ts.interface->attr.if_source
11490               || c->ts.interface->attr.intrinsic)
11491             {
11492               gfc_symbol *ifc = c->ts.interface;
11493
11494               if (ifc->formal && !ifc->formal_ns)
11495                 resolve_symbol (ifc);
11496
11497               if (ifc->attr.intrinsic)
11498                 resolve_intrinsic (ifc, &ifc->declared_at);
11499
11500               if (ifc->result)
11501                 {
11502                   c->ts = ifc->result->ts;
11503                   c->attr.allocatable = ifc->result->attr.allocatable;
11504                   c->attr.pointer = ifc->result->attr.pointer;
11505                   c->attr.dimension = ifc->result->attr.dimension;
11506                   c->as = gfc_copy_array_spec (ifc->result->as);
11507                 }
11508               else
11509                 {   
11510                   c->ts = ifc->ts;
11511                   c->attr.allocatable = ifc->attr.allocatable;
11512                   c->attr.pointer = ifc->attr.pointer;
11513                   c->attr.dimension = ifc->attr.dimension;
11514                   c->as = gfc_copy_array_spec (ifc->as);
11515                 }
11516               c->ts.interface = ifc;
11517               c->attr.function = ifc->attr.function;
11518               c->attr.subroutine = ifc->attr.subroutine;
11519               gfc_copy_formal_args_ppc (c, ifc);
11520
11521               c->attr.pure = ifc->attr.pure;
11522               c->attr.elemental = ifc->attr.elemental;
11523               c->attr.recursive = ifc->attr.recursive;
11524               c->attr.always_explicit = ifc->attr.always_explicit;
11525               c->attr.ext_attr |= ifc->attr.ext_attr;
11526               /* Replace symbols in array spec.  */
11527               if (c->as)
11528                 {
11529                   int i;
11530                   for (i = 0; i < c->as->rank; i++)
11531                     {
11532                       gfc_expr_replace_comp (c->as->lower[i], c);
11533                       gfc_expr_replace_comp (c->as->upper[i], c);
11534                     }
11535                 }
11536               /* Copy char length.  */
11537               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11538                 {
11539                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11540                   gfc_expr_replace_comp (cl->length, c);
11541                   if (cl->length && !cl->resolved
11542                         && gfc_resolve_expr (cl->length) == FAILURE)
11543                     return FAILURE;
11544                   c->ts.u.cl = cl;
11545                 }
11546             }
11547           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11548             {
11549               gfc_error ("Interface '%s' of procedure pointer component "
11550                          "'%s' at %L must be explicit", c->ts.interface->name,
11551                          c->name, &c->loc);
11552               return FAILURE;
11553             }
11554         }
11555       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11556         {
11557           /* Since PPCs are not implicitly typed, a PPC without an explicit
11558              interface must be a subroutine.  */
11559           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11560         }
11561
11562       /* Procedure pointer components: Check PASS arg.  */
11563       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11564           && !sym->attr.vtype)
11565         {
11566           gfc_symbol* me_arg;
11567
11568           if (c->tb->pass_arg)
11569             {
11570               gfc_formal_arglist* i;
11571
11572               /* If an explicit passing argument name is given, walk the arg-list
11573                 and look for it.  */
11574
11575               me_arg = NULL;
11576               c->tb->pass_arg_num = 1;
11577               for (i = c->formal; i; i = i->next)
11578                 {
11579                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11580                     {
11581                       me_arg = i->sym;
11582                       break;
11583                     }
11584                   c->tb->pass_arg_num++;
11585                 }
11586
11587               if (!me_arg)
11588                 {
11589                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11590                              "at %L has no argument '%s'", c->name,
11591                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11592                   c->tb->error = 1;
11593                   return FAILURE;
11594                 }
11595             }
11596           else
11597             {
11598               /* Otherwise, take the first one; there should in fact be at least
11599                 one.  */
11600               c->tb->pass_arg_num = 1;
11601               if (!c->formal)
11602                 {
11603                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11604                              "must have at least one argument",
11605                              c->name, &c->loc);
11606                   c->tb->error = 1;
11607                   return FAILURE;
11608                 }
11609               me_arg = c->formal->sym;
11610             }
11611
11612           /* Now check that the argument-type matches.  */
11613           gcc_assert (me_arg);
11614           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11615               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11616               || (me_arg->ts.type == BT_CLASS
11617                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11618             {
11619               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11620                          " the derived type '%s'", me_arg->name, c->name,
11621                          me_arg->name, &c->loc, sym->name);
11622               c->tb->error = 1;
11623               return FAILURE;
11624             }
11625
11626           /* Check for C453.  */
11627           if (me_arg->attr.dimension)
11628             {
11629               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11630                          "must be scalar", me_arg->name, c->name, me_arg->name,
11631                          &c->loc);
11632               c->tb->error = 1;
11633               return FAILURE;
11634             }
11635
11636           if (me_arg->attr.pointer)
11637             {
11638               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11639                          "may not have the POINTER attribute", me_arg->name,
11640                          c->name, me_arg->name, &c->loc);
11641               c->tb->error = 1;
11642               return FAILURE;
11643             }
11644
11645           if (me_arg->attr.allocatable)
11646             {
11647               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11648                          "may not be ALLOCATABLE", me_arg->name, c->name,
11649                          me_arg->name, &c->loc);
11650               c->tb->error = 1;
11651               return FAILURE;
11652             }
11653
11654           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11655             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11656                        " at %L", c->name, &c->loc);
11657
11658         }
11659
11660       /* Check type-spec if this is not the parent-type component.  */
11661       if ((!sym->attr.extension || c != sym->components) && !sym->attr.vtype
11662           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11663         return FAILURE;
11664
11665       /* If this type is an extension, set the accessibility of the parent
11666          component.  */
11667       if (super_type && c == sym->components
11668           && strcmp (super_type->name, c->name) == 0)
11669         c->attr.access = super_type->attr.access;
11670       
11671       /* If this type is an extension, see if this component has the same name
11672          as an inherited type-bound procedure.  */
11673       if (super_type && !sym->attr.is_class
11674           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11675         {
11676           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11677                      " inherited type-bound procedure",
11678                      c->name, sym->name, &c->loc);
11679           return FAILURE;
11680         }
11681
11682       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
11683             && !c->ts.deferred)
11684         {
11685          if (c->ts.u.cl->length == NULL
11686              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11687              || !gfc_is_constant_expr (c->ts.u.cl->length))
11688            {
11689              gfc_error ("Character length of component '%s' needs to "
11690                         "be a constant specification expression at %L",
11691                         c->name,
11692                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11693              return FAILURE;
11694            }
11695         }
11696
11697       if (c->ts.type == BT_CHARACTER && c->ts.deferred
11698           && !c->attr.pointer && !c->attr.allocatable)
11699         {
11700           gfc_error ("Character component '%s' of '%s' at %L with deferred "
11701                      "length must be a POINTER or ALLOCATABLE",
11702                      c->name, sym->name, &c->loc);
11703           return FAILURE;
11704         }
11705
11706       if (c->ts.type == BT_DERIVED
11707           && sym->component_access != ACCESS_PRIVATE
11708           && gfc_check_symbol_access (sym)
11709           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11710           && !c->ts.u.derived->attr.use_assoc
11711           && !gfc_check_symbol_access (c->ts.u.derived)
11712           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11713                              "is a PRIVATE type and cannot be a component of "
11714                              "'%s', which is PUBLIC at %L", c->name,
11715                              sym->name, &sym->declared_at) == FAILURE)
11716         return FAILURE;
11717
11718       if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
11719         {
11720           gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
11721                      "type %s", c->name, &c->loc, sym->name);
11722           return FAILURE;
11723         }
11724
11725       if (sym->attr.sequence)
11726         {
11727           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11728             {
11729               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11730                          "not have the SEQUENCE attribute",
11731                          c->ts.u.derived->name, &sym->declared_at);
11732               return FAILURE;
11733             }
11734         }
11735
11736       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.generic)
11737         c->ts.u.derived = gfc_find_dt_in_generic (c->ts.u.derived);
11738       else if (c->ts.type == BT_CLASS && c->attr.class_ok
11739                && CLASS_DATA (c)->ts.u.derived->attr.generic)
11740         CLASS_DATA (c)->ts.u.derived
11741                         = gfc_find_dt_in_generic (CLASS_DATA (c)->ts.u.derived);
11742
11743       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && !sym->attr.vtype
11744           && c->attr.pointer && c->ts.u.derived->components == NULL
11745           && !c->ts.u.derived->attr.zero_comp)
11746         {
11747           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11748                      "that has not been declared", c->name, sym->name,
11749                      &c->loc);
11750           return FAILURE;
11751         }
11752
11753       if (c->ts.type == BT_CLASS && c->attr.class_ok
11754           && CLASS_DATA (c)->attr.class_pointer
11755           && CLASS_DATA (c)->ts.u.derived->components == NULL
11756           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11757         {
11758           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11759                      "that has not been declared", c->name, sym->name,
11760                      &c->loc);
11761           return FAILURE;
11762         }
11763
11764       /* C437.  */
11765       if (c->ts.type == BT_CLASS && c->attr.flavor != FL_PROCEDURE
11766           && (!c->attr.class_ok
11767               || !(CLASS_DATA (c)->attr.class_pointer
11768                    || CLASS_DATA (c)->attr.allocatable)))
11769         {
11770           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11771                      "or pointer", c->name, &c->loc);
11772           return FAILURE;
11773         }
11774
11775       /* Ensure that all the derived type components are put on the
11776          derived type list; even in formal namespaces, where derived type
11777          pointer components might not have been declared.  */
11778       if (c->ts.type == BT_DERIVED
11779             && c->ts.u.derived
11780             && c->ts.u.derived->components
11781             && c->attr.pointer
11782             && sym != c->ts.u.derived)
11783         add_dt_to_dt_list (c->ts.u.derived);
11784
11785       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11786                                            || c->attr.proc_pointer
11787                                            || c->attr.allocatable)) == FAILURE)
11788         return FAILURE;
11789     }
11790
11791   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11792      all DEFERRED bindings are overridden.  */
11793   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11794       && !sym->attr.is_class
11795       && ensure_not_abstract (sym, super_type) == FAILURE)
11796     return FAILURE;
11797
11798   /* Add derived type to the derived type list.  */
11799   add_dt_to_dt_list (sym);
11800
11801   return SUCCESS;
11802 }
11803
11804
11805 /* The following procedure does the full resolution of a derived type,
11806    including resolution of all type-bound procedures (if present). In contrast
11807    to 'resolve_fl_derived0' this can only be done after the module has been
11808    parsed completely.  */
11809
11810 static gfc_try
11811 resolve_fl_derived (gfc_symbol *sym)
11812 {
11813   gfc_symbol *gen_dt = NULL;
11814
11815   if (!sym->attr.is_class)
11816     gfc_find_symbol (sym->name, sym->ns, 0, &gen_dt);
11817   if (gen_dt && gen_dt->generic && gen_dt->generic->next
11818       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Generic name '%s' of "
11819                          "function '%s' at %L being the same name as derived "
11820                          "type at %L", sym->name,
11821                          gen_dt->generic->sym == sym
11822                            ? gen_dt->generic->next->sym->name
11823                            : gen_dt->generic->sym->name,
11824                          gen_dt->generic->sym == sym
11825                            ? &gen_dt->generic->next->sym->declared_at
11826                            : &gen_dt->generic->sym->declared_at,
11827                          &sym->declared_at) == FAILURE)
11828     return FAILURE;
11829
11830   if (sym->attr.is_class && sym->ts.u.derived == NULL)
11831     {
11832       /* Fix up incomplete CLASS symbols.  */
11833       gfc_component *data = gfc_find_component (sym, "_data", true, true);
11834       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true);
11835       if (vptr->ts.u.derived == NULL)
11836         {
11837           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
11838           gcc_assert (vtab);
11839           vptr->ts.u.derived = vtab->ts.u.derived;
11840         }
11841     }
11842   
11843   if (resolve_fl_derived0 (sym) == FAILURE)
11844     return FAILURE;
11845   
11846   /* Resolve the type-bound procedures.  */
11847   if (resolve_typebound_procedures (sym) == FAILURE)
11848     return FAILURE;
11849
11850   /* Resolve the finalizer procedures.  */
11851   if (gfc_resolve_finalizers (sym) == FAILURE)
11852     return FAILURE;
11853   
11854   return SUCCESS;
11855 }
11856
11857
11858 static gfc_try
11859 resolve_fl_namelist (gfc_symbol *sym)
11860 {
11861   gfc_namelist *nl;
11862   gfc_symbol *nlsym;
11863
11864   for (nl = sym->namelist; nl; nl = nl->next)
11865     {
11866       /* Check again, the check in match only works if NAMELIST comes
11867          after the decl.  */
11868       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SIZE)
11869         {
11870           gfc_error ("Assumed size array '%s' in namelist '%s' at %L is not "
11871                      "allowed", nl->sym->name, sym->name, &sym->declared_at);
11872           return FAILURE;
11873         }
11874
11875       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11876           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: NAMELIST array "
11877                              "object '%s' with assumed shape in namelist "
11878                              "'%s' at %L", nl->sym->name, sym->name,
11879                              &sym->declared_at) == FAILURE)
11880         return FAILURE;
11881
11882       if (is_non_constant_shape_array (nl->sym)
11883           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST array "
11884                              "object '%s' with nonconstant shape in namelist "
11885                              "'%s' at %L", nl->sym->name, sym->name,
11886                              &sym->declared_at) == FAILURE)
11887         return FAILURE;
11888
11889       if (nl->sym->ts.type == BT_CHARACTER
11890           && (nl->sym->ts.u.cl->length == NULL
11891               || !gfc_is_constant_expr (nl->sym->ts.u.cl->length))
11892           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
11893                              "'%s' with nonconstant character length in "
11894                              "namelist '%s' at %L", nl->sym->name, sym->name,
11895                              &sym->declared_at) == FAILURE)
11896         return FAILURE;
11897
11898       /* FIXME: Once UDDTIO is implemented, the following can be
11899          removed.  */
11900       if (nl->sym->ts.type == BT_CLASS)
11901         {
11902           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L is "
11903                      "polymorphic and requires a defined input/output "
11904                      "procedure", nl->sym->name, sym->name, &sym->declared_at);
11905           return FAILURE;
11906         }
11907
11908       if (nl->sym->ts.type == BT_DERIVED
11909           && (nl->sym->ts.u.derived->attr.alloc_comp
11910               || nl->sym->ts.u.derived->attr.pointer_comp))
11911         {
11912           if (gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
11913                               "'%s' in namelist '%s' at %L with ALLOCATABLE "
11914                               "or POINTER components", nl->sym->name,
11915                               sym->name, &sym->declared_at) == FAILURE)
11916             return FAILURE;
11917
11918          /* FIXME: Once UDDTIO is implemented, the following can be
11919             removed.  */
11920           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L has "
11921                      "ALLOCATABLE or POINTER components and thus requires "
11922                      "a defined input/output procedure", nl->sym->name,
11923                      sym->name, &sym->declared_at);
11924           return FAILURE;
11925         }
11926     }
11927
11928   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11929   if (gfc_check_symbol_access (sym))
11930     {
11931       for (nl = sym->namelist; nl; nl = nl->next)
11932         {
11933           if (!nl->sym->attr.use_assoc
11934               && !is_sym_host_assoc (nl->sym, sym->ns)
11935               && !gfc_check_symbol_access (nl->sym))
11936             {
11937               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11938                          "cannot be member of PUBLIC namelist '%s' at %L",
11939                          nl->sym->name, sym->name, &sym->declared_at);
11940               return FAILURE;
11941             }
11942
11943           /* Types with private components that came here by USE-association.  */
11944           if (nl->sym->ts.type == BT_DERIVED
11945               && derived_inaccessible (nl->sym->ts.u.derived))
11946             {
11947               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11948                          "components and cannot be member of namelist '%s' at %L",
11949                          nl->sym->name, sym->name, &sym->declared_at);
11950               return FAILURE;
11951             }
11952
11953           /* Types with private components that are defined in the same module.  */
11954           if (nl->sym->ts.type == BT_DERIVED
11955               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11956               && nl->sym->ts.u.derived->attr.private_comp)
11957             {
11958               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11959                          "cannot be a member of PUBLIC namelist '%s' at %L",
11960                          nl->sym->name, sym->name, &sym->declared_at);
11961               return FAILURE;
11962             }
11963         }
11964     }
11965
11966
11967   /* 14.1.2 A module or internal procedure represent local entities
11968      of the same type as a namelist member and so are not allowed.  */
11969   for (nl = sym->namelist; nl; nl = nl->next)
11970     {
11971       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11972         continue;
11973
11974       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11975         if ((nl->sym == sym->ns->proc_name)
11976                ||
11977             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11978           continue;
11979
11980       nlsym = NULL;
11981       if (nl->sym && nl->sym->name)
11982         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11983       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11984         {
11985           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11986                      "attribute in '%s' at %L", nlsym->name,
11987                      &sym->declared_at);
11988           return FAILURE;
11989         }
11990     }
11991
11992   return SUCCESS;
11993 }
11994
11995
11996 static gfc_try
11997 resolve_fl_parameter (gfc_symbol *sym)
11998 {
11999   /* A parameter array's shape needs to be constant.  */
12000   if (sym->as != NULL 
12001       && (sym->as->type == AS_DEFERRED
12002           || is_non_constant_shape_array (sym)))
12003     {
12004       gfc_error ("Parameter array '%s' at %L cannot be automatic "
12005                  "or of deferred shape", sym->name, &sym->declared_at);
12006       return FAILURE;
12007     }
12008
12009   /* Make sure a parameter that has been implicitly typed still
12010      matches the implicit type, since PARAMETER statements can precede
12011      IMPLICIT statements.  */
12012   if (sym->attr.implicit_type
12013       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
12014                                                              sym->ns)))
12015     {
12016       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
12017                  "later IMPLICIT type", sym->name, &sym->declared_at);
12018       return FAILURE;
12019     }
12020
12021   /* Make sure the types of derived parameters are consistent.  This
12022      type checking is deferred until resolution because the type may
12023      refer to a derived type from the host.  */
12024   if (sym->ts.type == BT_DERIVED && sym->value
12025       && !gfc_compare_types (&sym->ts, &sym->value->ts))
12026     {
12027       gfc_error ("Incompatible derived type in PARAMETER at %L",
12028                  &sym->value->where);
12029       return FAILURE;
12030     }
12031   return SUCCESS;
12032 }
12033
12034
12035 /* Do anything necessary to resolve a symbol.  Right now, we just
12036    assume that an otherwise unknown symbol is a variable.  This sort
12037    of thing commonly happens for symbols in module.  */
12038
12039 static void
12040 resolve_symbol (gfc_symbol *sym)
12041 {
12042   int check_constant, mp_flag;
12043   gfc_symtree *symtree;
12044   gfc_symtree *this_symtree;
12045   gfc_namespace *ns;
12046   gfc_component *c;
12047
12048   if (sym->attr.flavor == FL_UNKNOWN)
12049     {
12050
12051     /* If we find that a flavorless symbol is an interface in one of the
12052        parent namespaces, find its symtree in this namespace, free the
12053        symbol and set the symtree to point to the interface symbol.  */
12054       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
12055         {
12056           symtree = gfc_find_symtree (ns->sym_root, sym->name);
12057           if (symtree && (symtree->n.sym->generic ||
12058                           (symtree->n.sym->attr.flavor == FL_PROCEDURE
12059                            && sym->ns->construct_entities)))
12060             {
12061               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
12062                                                sym->name);
12063               gfc_release_symbol (sym);
12064               symtree->n.sym->refs++;
12065               this_symtree->n.sym = symtree->n.sym;
12066               return;
12067             }
12068         }
12069
12070       /* Otherwise give it a flavor according to such attributes as
12071          it has.  */
12072       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
12073         sym->attr.flavor = FL_VARIABLE;
12074       else
12075         {
12076           sym->attr.flavor = FL_PROCEDURE;
12077           if (sym->attr.dimension)
12078             sym->attr.function = 1;
12079         }
12080     }
12081
12082   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
12083     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
12084
12085   if (sym->attr.procedure && sym->ts.interface
12086       && sym->attr.if_source != IFSRC_DECL
12087       && resolve_procedure_interface (sym) == FAILURE)
12088     return;
12089
12090   if (sym->attr.is_protected && !sym->attr.proc_pointer
12091       && (sym->attr.procedure || sym->attr.external))
12092     {
12093       if (sym->attr.external)
12094         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
12095                    "at %L", &sym->declared_at);
12096       else
12097         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
12098                    "at %L", &sym->declared_at);
12099
12100       return;
12101     }
12102
12103
12104   /* F2008, C530. */
12105   if (sym->attr.contiguous
12106       && (!sym->attr.dimension || (sym->as->type != AS_ASSUMED_SHAPE
12107                                    && !sym->attr.pointer)))
12108     {
12109       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
12110                   "array pointer or an assumed-shape array", sym->name,
12111                   &sym->declared_at);
12112       return;
12113     }
12114
12115   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
12116     return;
12117
12118   /* Symbols that are module procedures with results (functions) have
12119      the types and array specification copied for type checking in
12120      procedures that call them, as well as for saving to a module
12121      file.  These symbols can't stand the scrutiny that their results
12122      can.  */
12123   mp_flag = (sym->result != NULL && sym->result != sym);
12124
12125   /* Make sure that the intrinsic is consistent with its internal 
12126      representation. This needs to be done before assigning a default 
12127      type to avoid spurious warnings.  */
12128   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
12129       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
12130     return;
12131
12132   /* Resolve associate names.  */
12133   if (sym->assoc)
12134     resolve_assoc_var (sym, true);
12135
12136   /* Assign default type to symbols that need one and don't have one.  */
12137   if (sym->ts.type == BT_UNKNOWN)
12138     {
12139       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
12140         gfc_set_default_type (sym, 1, NULL);
12141
12142       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
12143           && !sym->attr.function && !sym->attr.subroutine
12144           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
12145         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
12146
12147       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12148         {
12149           /* The specific case of an external procedure should emit an error
12150              in the case that there is no implicit type.  */
12151           if (!mp_flag)
12152             gfc_set_default_type (sym, sym->attr.external, NULL);
12153           else
12154             {
12155               /* Result may be in another namespace.  */
12156               resolve_symbol (sym->result);
12157
12158               if (!sym->result->attr.proc_pointer)
12159                 {
12160                   sym->ts = sym->result->ts;
12161                   sym->as = gfc_copy_array_spec (sym->result->as);
12162                   sym->attr.dimension = sym->result->attr.dimension;
12163                   sym->attr.pointer = sym->result->attr.pointer;
12164                   sym->attr.allocatable = sym->result->attr.allocatable;
12165                   sym->attr.contiguous = sym->result->attr.contiguous;
12166                 }
12167             }
12168         }
12169     }
12170   else if (mp_flag && sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12171     gfc_resolve_array_spec (sym->result->as, false);
12172
12173   /* Assumed size arrays and assumed shape arrays must be dummy
12174      arguments.  Array-spec's of implied-shape should have been resolved to
12175      AS_EXPLICIT already.  */
12176
12177   if (sym->as)
12178     {
12179       gcc_assert (sym->as->type != AS_IMPLIED_SHAPE);
12180       if (((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
12181            || sym->as->type == AS_ASSUMED_SHAPE)
12182           && sym->attr.dummy == 0)
12183         {
12184           if (sym->as->type == AS_ASSUMED_SIZE)
12185             gfc_error ("Assumed size array at %L must be a dummy argument",
12186                        &sym->declared_at);
12187           else
12188             gfc_error ("Assumed shape array at %L must be a dummy argument",
12189                        &sym->declared_at);
12190           return;
12191         }
12192     }
12193
12194   /* Make sure symbols with known intent or optional are really dummy
12195      variable.  Because of ENTRY statement, this has to be deferred
12196      until resolution time.  */
12197
12198   if (!sym->attr.dummy
12199       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
12200     {
12201       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
12202       return;
12203     }
12204
12205   if (sym->attr.value && !sym->attr.dummy)
12206     {
12207       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
12208                  "it is not a dummy argument", sym->name, &sym->declared_at);
12209       return;
12210     }
12211
12212   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
12213     {
12214       gfc_charlen *cl = sym->ts.u.cl;
12215       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12216         {
12217           gfc_error ("Character dummy variable '%s' at %L with VALUE "
12218                      "attribute must have constant length",
12219                      sym->name, &sym->declared_at);
12220           return;
12221         }
12222
12223       if (sym->ts.is_c_interop
12224           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
12225         {
12226           gfc_error ("C interoperable character dummy variable '%s' at %L "
12227                      "with VALUE attribute must have length one",
12228                      sym->name, &sym->declared_at);
12229           return;
12230         }
12231     }
12232
12233   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
12234       && sym->ts.u.derived->attr.generic)
12235     {
12236       sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
12237       if (!sym->ts.u.derived)
12238         {
12239           gfc_error ("The derived type '%s' at %L is of type '%s', "
12240                      "which has not been defined", sym->name,
12241                      &sym->declared_at, sym->ts.u.derived->name);
12242           sym->ts.type = BT_UNKNOWN;
12243           return;
12244         }
12245     }
12246
12247   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
12248      do this for something that was implicitly typed because that is handled
12249      in gfc_set_default_type.  Handle dummy arguments and procedure
12250      definitions separately.  Also, anything that is use associated is not
12251      handled here but instead is handled in the module it is declared in.
12252      Finally, derived type definitions are allowed to be BIND(C) since that
12253      only implies that they're interoperable, and they are checked fully for
12254      interoperability when a variable is declared of that type.  */
12255   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
12256       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
12257       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
12258     {
12259       gfc_try t = SUCCESS;
12260       
12261       /* First, make sure the variable is declared at the
12262          module-level scope (J3/04-007, Section 15.3).  */
12263       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
12264           sym->attr.in_common == 0)
12265         {
12266           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
12267                      "is neither a COMMON block nor declared at the "
12268                      "module level scope", sym->name, &(sym->declared_at));
12269           t = FAILURE;
12270         }
12271       else if (sym->common_head != NULL)
12272         {
12273           t = verify_com_block_vars_c_interop (sym->common_head);
12274         }
12275       else
12276         {
12277           /* If type() declaration, we need to verify that the components
12278              of the given type are all C interoperable, etc.  */
12279           if (sym->ts.type == BT_DERIVED &&
12280               sym->ts.u.derived->attr.is_c_interop != 1)
12281             {
12282               /* Make sure the user marked the derived type as BIND(C).  If
12283                  not, call the verify routine.  This could print an error
12284                  for the derived type more than once if multiple variables
12285                  of that type are declared.  */
12286               if (sym->ts.u.derived->attr.is_bind_c != 1)
12287                 verify_bind_c_derived_type (sym->ts.u.derived);
12288               t = FAILURE;
12289             }
12290           
12291           /* Verify the variable itself as C interoperable if it
12292              is BIND(C).  It is not possible for this to succeed if
12293              the verify_bind_c_derived_type failed, so don't have to handle
12294              any error returned by verify_bind_c_derived_type.  */
12295           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12296                                  sym->common_block);
12297         }
12298
12299       if (t == FAILURE)
12300         {
12301           /* clear the is_bind_c flag to prevent reporting errors more than
12302              once if something failed.  */
12303           sym->attr.is_bind_c = 0;
12304           return;
12305         }
12306     }
12307
12308   /* If a derived type symbol has reached this point, without its
12309      type being declared, we have an error.  Notice that most
12310      conditions that produce undefined derived types have already
12311      been dealt with.  However, the likes of:
12312      implicit type(t) (t) ..... call foo (t) will get us here if
12313      the type is not declared in the scope of the implicit
12314      statement. Change the type to BT_UNKNOWN, both because it is so
12315      and to prevent an ICE.  */
12316   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
12317       && sym->ts.u.derived->components == NULL
12318       && !sym->ts.u.derived->attr.zero_comp)
12319     {
12320       gfc_error ("The derived type '%s' at %L is of type '%s', "
12321                  "which has not been defined", sym->name,
12322                   &sym->declared_at, sym->ts.u.derived->name);
12323       sym->ts.type = BT_UNKNOWN;
12324       return;
12325     }
12326
12327   /* Make sure that the derived type has been resolved and that the
12328      derived type is visible in the symbol's namespace, if it is a
12329      module function and is not PRIVATE.  */
12330   if (sym->ts.type == BT_DERIVED
12331         && sym->ts.u.derived->attr.use_assoc
12332         && sym->ns->proc_name
12333         && sym->ns->proc_name->attr.flavor == FL_MODULE
12334         && resolve_fl_derived (sym->ts.u.derived) == FAILURE)
12335     return;
12336
12337   /* Unless the derived-type declaration is use associated, Fortran 95
12338      does not allow public entries of private derived types.
12339      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12340      161 in 95-006r3.  */
12341   if (sym->ts.type == BT_DERIVED
12342       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12343       && !sym->ts.u.derived->attr.use_assoc
12344       && gfc_check_symbol_access (sym)
12345       && !gfc_check_symbol_access (sym->ts.u.derived)
12346       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12347                          "of PRIVATE derived type '%s'",
12348                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12349                          : "variable", sym->name, &sym->declared_at,
12350                          sym->ts.u.derived->name) == FAILURE)
12351     return;
12352
12353   /* F2008, C1302.  */
12354   if (sym->ts.type == BT_DERIVED
12355       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
12356            && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
12357           || sym->ts.u.derived->attr.lock_comp)
12358       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
12359     {
12360       gfc_error ("Variable %s at %L of type LOCK_TYPE or with subcomponent of "
12361                  "type LOCK_TYPE must be a coarray", sym->name,
12362                  &sym->declared_at);
12363       return;
12364     }
12365
12366   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12367      default initialization is defined (5.1.2.4.4).  */
12368   if (sym->ts.type == BT_DERIVED
12369       && sym->attr.dummy
12370       && sym->attr.intent == INTENT_OUT
12371       && sym->as
12372       && sym->as->type == AS_ASSUMED_SIZE)
12373     {
12374       for (c = sym->ts.u.derived->components; c; c = c->next)
12375         {
12376           if (c->initializer)
12377             {
12378               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12379                          "ASSUMED SIZE and so cannot have a default initializer",
12380                          sym->name, &sym->declared_at);
12381               return;
12382             }
12383         }
12384     }
12385
12386   /* F2008, C542.  */
12387   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
12388       && sym->attr.intent == INTENT_OUT && sym->attr.lock_comp)
12389     {
12390       gfc_error ("Dummy argument '%s' at %L of LOCK_TYPE shall not be "
12391                  "INTENT(OUT)", sym->name, &sym->declared_at);
12392       return;
12393     }
12394
12395   /* F2008, C525.  */
12396   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12397        || sym->attr.codimension)
12398       && (sym->attr.result || sym->result == sym))
12399     {
12400       gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12401                  "a coarray component", sym->name, &sym->declared_at);
12402       return;
12403     }
12404
12405   /* F2008, C524.  */
12406   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12407       && sym->ts.u.derived->ts.is_iso_c)
12408     {
12409       gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12410                  "shall not be a coarray", sym->name, &sym->declared_at);
12411       return;
12412     }
12413
12414   /* F2008, C525.  */
12415   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
12416       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
12417           || sym->attr.allocatable))
12418     {
12419       gfc_error ("Variable '%s' at %L with coarray component "
12420                  "shall be a nonpointer, nonallocatable scalar",
12421                  sym->name, &sym->declared_at);
12422       return;
12423     }
12424
12425   /* F2008, C526.  The function-result case was handled above.  */
12426   if (sym->attr.codimension
12427       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
12428            || sym->ns->save_all
12429            || sym->ns->proc_name->attr.flavor == FL_MODULE
12430            || sym->ns->proc_name->attr.is_main_program
12431            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12432     {
12433       gfc_error ("Variable '%s' at %L is a coarray and is not ALLOCATABLE, SAVE "
12434                  "nor a dummy argument", sym->name, &sym->declared_at);
12435       return;
12436     }
12437   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
12438   else if (sym->attr.codimension && !sym->attr.allocatable
12439       && sym->as && sym->as->cotype == AS_DEFERRED)
12440     {
12441       gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12442                  "deferred shape", sym->name, &sym->declared_at);
12443       return;
12444     }
12445   else if (sym->attr.codimension && sym->attr.allocatable
12446       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
12447     {
12448       gfc_error ("Allocatable coarray variable '%s' at %L must have "
12449                  "deferred shape", sym->name, &sym->declared_at);
12450       return;
12451     }
12452
12453   /* F2008, C541.  */
12454   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12455        || (sym->attr.codimension && sym->attr.allocatable))
12456       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12457     {
12458       gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12459                  "allocatable coarray or have coarray components",
12460                  sym->name, &sym->declared_at);
12461       return;
12462     }
12463
12464   if (sym->attr.codimension && sym->attr.dummy
12465       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12466     {
12467       gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12468                  "procedure '%s'", sym->name, &sym->declared_at,
12469                  sym->ns->proc_name->name);
12470       return;
12471     }
12472
12473   switch (sym->attr.flavor)
12474     {
12475     case FL_VARIABLE:
12476       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12477         return;
12478       break;
12479
12480     case FL_PROCEDURE:
12481       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12482         return;
12483       break;
12484
12485     case FL_NAMELIST:
12486       if (resolve_fl_namelist (sym) == FAILURE)
12487         return;
12488       break;
12489
12490     case FL_PARAMETER:
12491       if (resolve_fl_parameter (sym) == FAILURE)
12492         return;
12493       break;
12494
12495     default:
12496       break;
12497     }
12498
12499   /* Resolve array specifier. Check as well some constraints
12500      on COMMON blocks.  */
12501
12502   check_constant = sym->attr.in_common && !sym->attr.pointer;
12503
12504   /* Set the formal_arg_flag so that check_conflict will not throw
12505      an error for host associated variables in the specification
12506      expression for an array_valued function.  */
12507   if (sym->attr.function && sym->as)
12508     formal_arg_flag = 1;
12509
12510   gfc_resolve_array_spec (sym->as, check_constant);
12511
12512   formal_arg_flag = 0;
12513
12514   /* Resolve formal namespaces.  */
12515   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12516       && !sym->attr.contained && !sym->attr.intrinsic)
12517     gfc_resolve (sym->formal_ns);
12518
12519   /* Make sure the formal namespace is present.  */
12520   if (sym->formal && !sym->formal_ns)
12521     {
12522       gfc_formal_arglist *formal = sym->formal;
12523       while (formal && !formal->sym)
12524         formal = formal->next;
12525
12526       if (formal)
12527         {
12528           sym->formal_ns = formal->sym->ns;
12529           sym->formal_ns->refs++;
12530         }
12531     }
12532
12533   /* Check threadprivate restrictions.  */
12534   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12535       && (!sym->attr.in_common
12536           && sym->module == NULL
12537           && (sym->ns->proc_name == NULL
12538               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12539     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12540
12541   /* If we have come this far we can apply default-initializers, as
12542      described in 14.7.5, to those variables that have not already
12543      been assigned one.  */
12544   if (sym->ts.type == BT_DERIVED
12545       && sym->ns == gfc_current_ns
12546       && !sym->value
12547       && !sym->attr.allocatable
12548       && !sym->attr.alloc_comp)
12549     {
12550       symbol_attribute *a = &sym->attr;
12551
12552       if ((!a->save && !a->dummy && !a->pointer
12553            && !a->in_common && !a->use_assoc
12554            && (a->referenced || a->result)
12555            && !(a->function && sym != sym->result))
12556           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12557         apply_default_init (sym);
12558     }
12559
12560   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
12561       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
12562       && !CLASS_DATA (sym)->attr.class_pointer
12563       && !CLASS_DATA (sym)->attr.allocatable)
12564     apply_default_init (sym);
12565
12566   /* If this symbol has a type-spec, check it.  */
12567   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12568       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12569     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12570           == FAILURE)
12571       return;
12572 }
12573
12574
12575 /************* Resolve DATA statements *************/
12576
12577 static struct
12578 {
12579   gfc_data_value *vnode;
12580   mpz_t left;
12581 }
12582 values;
12583
12584
12585 /* Advance the values structure to point to the next value in the data list.  */
12586
12587 static gfc_try
12588 next_data_value (void)
12589 {
12590   while (mpz_cmp_ui (values.left, 0) == 0)
12591     {
12592
12593       if (values.vnode->next == NULL)
12594         return FAILURE;
12595
12596       values.vnode = values.vnode->next;
12597       mpz_set (values.left, values.vnode->repeat);
12598     }
12599
12600   return SUCCESS;
12601 }
12602
12603
12604 static gfc_try
12605 check_data_variable (gfc_data_variable *var, locus *where)
12606 {
12607   gfc_expr *e;
12608   mpz_t size;
12609   mpz_t offset;
12610   gfc_try t;
12611   ar_type mark = AR_UNKNOWN;
12612   int i;
12613   mpz_t section_index[GFC_MAX_DIMENSIONS];
12614   gfc_ref *ref;
12615   gfc_array_ref *ar;
12616   gfc_symbol *sym;
12617   int has_pointer;
12618
12619   if (gfc_resolve_expr (var->expr) == FAILURE)
12620     return FAILURE;
12621
12622   ar = NULL;
12623   mpz_init_set_si (offset, 0);
12624   e = var->expr;
12625
12626   if (e->expr_type != EXPR_VARIABLE)
12627     gfc_internal_error ("check_data_variable(): Bad expression");
12628
12629   sym = e->symtree->n.sym;
12630
12631   if (sym->ns->is_block_data && !sym->attr.in_common)
12632     {
12633       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12634                  sym->name, &sym->declared_at);
12635     }
12636
12637   if (e->ref == NULL && sym->as)
12638     {
12639       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12640                  " declaration", sym->name, where);
12641       return FAILURE;
12642     }
12643
12644   has_pointer = sym->attr.pointer;
12645
12646   if (gfc_is_coindexed (e))
12647     {
12648       gfc_error ("DATA element '%s' at %L cannot have a coindex", sym->name,
12649                  where);
12650       return FAILURE;
12651     }
12652
12653   for (ref = e->ref; ref; ref = ref->next)
12654     {
12655       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12656         has_pointer = 1;
12657
12658       if (has_pointer
12659             && ref->type == REF_ARRAY
12660             && ref->u.ar.type != AR_FULL)
12661           {
12662             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12663                         "be a full array", sym->name, where);
12664             return FAILURE;
12665           }
12666     }
12667
12668   if (e->rank == 0 || has_pointer)
12669     {
12670       mpz_init_set_ui (size, 1);
12671       ref = NULL;
12672     }
12673   else
12674     {
12675       ref = e->ref;
12676
12677       /* Find the array section reference.  */
12678       for (ref = e->ref; ref; ref = ref->next)
12679         {
12680           if (ref->type != REF_ARRAY)
12681             continue;
12682           if (ref->u.ar.type == AR_ELEMENT)
12683             continue;
12684           break;
12685         }
12686       gcc_assert (ref);
12687
12688       /* Set marks according to the reference pattern.  */
12689       switch (ref->u.ar.type)
12690         {
12691         case AR_FULL:
12692           mark = AR_FULL;
12693           break;
12694
12695         case AR_SECTION:
12696           ar = &ref->u.ar;
12697           /* Get the start position of array section.  */
12698           gfc_get_section_index (ar, section_index, &offset);
12699           mark = AR_SECTION;
12700           break;
12701
12702         default:
12703           gcc_unreachable ();
12704         }
12705
12706       if (gfc_array_size (e, &size) == FAILURE)
12707         {
12708           gfc_error ("Nonconstant array section at %L in DATA statement",
12709                      &e->where);
12710           mpz_clear (offset);
12711           return FAILURE;
12712         }
12713     }
12714
12715   t = SUCCESS;
12716
12717   while (mpz_cmp_ui (size, 0) > 0)
12718     {
12719       if (next_data_value () == FAILURE)
12720         {
12721           gfc_error ("DATA statement at %L has more variables than values",
12722                      where);
12723           t = FAILURE;
12724           break;
12725         }
12726
12727       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12728       if (t == FAILURE)
12729         break;
12730
12731       /* If we have more than one element left in the repeat count,
12732          and we have more than one element left in the target variable,
12733          then create a range assignment.  */
12734       /* FIXME: Only done for full arrays for now, since array sections
12735          seem tricky.  */
12736       if (mark == AR_FULL && ref && ref->next == NULL
12737           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12738         {
12739           mpz_t range;
12740
12741           if (mpz_cmp (size, values.left) >= 0)
12742             {
12743               mpz_init_set (range, values.left);
12744               mpz_sub (size, size, values.left);
12745               mpz_set_ui (values.left, 0);
12746             }
12747           else
12748             {
12749               mpz_init_set (range, size);
12750               mpz_sub (values.left, values.left, size);
12751               mpz_set_ui (size, 0);
12752             }
12753
12754           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12755                                      offset, &range);
12756
12757           mpz_add (offset, offset, range);
12758           mpz_clear (range);
12759
12760           if (t == FAILURE)
12761             break;
12762         }
12763
12764       /* Assign initial value to symbol.  */
12765       else
12766         {
12767           mpz_sub_ui (values.left, values.left, 1);
12768           mpz_sub_ui (size, size, 1);
12769
12770           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12771                                      offset, NULL);
12772           if (t == FAILURE)
12773             break;
12774
12775           if (mark == AR_FULL)
12776             mpz_add_ui (offset, offset, 1);
12777
12778           /* Modify the array section indexes and recalculate the offset
12779              for next element.  */
12780           else if (mark == AR_SECTION)
12781             gfc_advance_section (section_index, ar, &offset);
12782         }
12783     }
12784
12785   if (mark == AR_SECTION)
12786     {
12787       for (i = 0; i < ar->dimen; i++)
12788         mpz_clear (section_index[i]);
12789     }
12790
12791   mpz_clear (size);
12792   mpz_clear (offset);
12793
12794   return t;
12795 }
12796
12797
12798 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
12799
12800 /* Iterate over a list of elements in a DATA statement.  */
12801
12802 static gfc_try
12803 traverse_data_list (gfc_data_variable *var, locus *where)
12804 {
12805   mpz_t trip;
12806   iterator_stack frame;
12807   gfc_expr *e, *start, *end, *step;
12808   gfc_try retval = SUCCESS;
12809
12810   mpz_init (frame.value);
12811   mpz_init (trip);
12812
12813   start = gfc_copy_expr (var->iter.start);
12814   end = gfc_copy_expr (var->iter.end);
12815   step = gfc_copy_expr (var->iter.step);
12816
12817   if (gfc_simplify_expr (start, 1) == FAILURE
12818       || start->expr_type != EXPR_CONSTANT)
12819     {
12820       gfc_error ("start of implied-do loop at %L could not be "
12821                  "simplified to a constant value", &start->where);
12822       retval = FAILURE;
12823       goto cleanup;
12824     }
12825   if (gfc_simplify_expr (end, 1) == FAILURE
12826       || end->expr_type != EXPR_CONSTANT)
12827     {
12828       gfc_error ("end of implied-do loop at %L could not be "
12829                  "simplified to a constant value", &start->where);
12830       retval = FAILURE;
12831       goto cleanup;
12832     }
12833   if (gfc_simplify_expr (step, 1) == FAILURE
12834       || step->expr_type != EXPR_CONSTANT)
12835     {
12836       gfc_error ("step of implied-do loop at %L could not be "
12837                  "simplified to a constant value", &start->where);
12838       retval = FAILURE;
12839       goto cleanup;
12840     }
12841
12842   mpz_set (trip, end->value.integer);
12843   mpz_sub (trip, trip, start->value.integer);
12844   mpz_add (trip, trip, step->value.integer);
12845
12846   mpz_div (trip, trip, step->value.integer);
12847
12848   mpz_set (frame.value, start->value.integer);
12849
12850   frame.prev = iter_stack;
12851   frame.variable = var->iter.var->symtree;
12852   iter_stack = &frame;
12853
12854   while (mpz_cmp_ui (trip, 0) > 0)
12855     {
12856       if (traverse_data_var (var->list, where) == FAILURE)
12857         {
12858           retval = FAILURE;
12859           goto cleanup;
12860         }
12861
12862       e = gfc_copy_expr (var->expr);
12863       if (gfc_simplify_expr (e, 1) == FAILURE)
12864         {
12865           gfc_free_expr (e);
12866           retval = FAILURE;
12867           goto cleanup;
12868         }
12869
12870       mpz_add (frame.value, frame.value, step->value.integer);
12871
12872       mpz_sub_ui (trip, trip, 1);
12873     }
12874
12875 cleanup:
12876   mpz_clear (frame.value);
12877   mpz_clear (trip);
12878
12879   gfc_free_expr (start);
12880   gfc_free_expr (end);
12881   gfc_free_expr (step);
12882
12883   iter_stack = frame.prev;
12884   return retval;
12885 }
12886
12887
12888 /* Type resolve variables in the variable list of a DATA statement.  */
12889
12890 static gfc_try
12891 traverse_data_var (gfc_data_variable *var, locus *where)
12892 {
12893   gfc_try t;
12894
12895   for (; var; var = var->next)
12896     {
12897       if (var->expr == NULL)
12898         t = traverse_data_list (var, where);
12899       else
12900         t = check_data_variable (var, where);
12901
12902       if (t == FAILURE)
12903         return FAILURE;
12904     }
12905
12906   return SUCCESS;
12907 }
12908
12909
12910 /* Resolve the expressions and iterators associated with a data statement.
12911    This is separate from the assignment checking because data lists should
12912    only be resolved once.  */
12913
12914 static gfc_try
12915 resolve_data_variables (gfc_data_variable *d)
12916 {
12917   for (; d; d = d->next)
12918     {
12919       if (d->list == NULL)
12920         {
12921           if (gfc_resolve_expr (d->expr) == FAILURE)
12922             return FAILURE;
12923         }
12924       else
12925         {
12926           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12927             return FAILURE;
12928
12929           if (resolve_data_variables (d->list) == FAILURE)
12930             return FAILURE;
12931         }
12932     }
12933
12934   return SUCCESS;
12935 }
12936
12937
12938 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12939    the value list into static variables, and then recursively traversing the
12940    variables list, expanding iterators and such.  */
12941
12942 static void
12943 resolve_data (gfc_data *d)
12944 {
12945
12946   if (resolve_data_variables (d->var) == FAILURE)
12947     return;
12948
12949   values.vnode = d->value;
12950   if (d->value == NULL)
12951     mpz_set_ui (values.left, 0);
12952   else
12953     mpz_set (values.left, d->value->repeat);
12954
12955   if (traverse_data_var (d->var, &d->where) == FAILURE)
12956     return;
12957
12958   /* At this point, we better not have any values left.  */
12959
12960   if (next_data_value () == SUCCESS)
12961     gfc_error ("DATA statement at %L has more values than variables",
12962                &d->where);
12963 }
12964
12965
12966 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12967    accessed by host or use association, is a dummy argument to a pure function,
12968    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12969    is storage associated with any such variable, shall not be used in the
12970    following contexts: (clients of this function).  */
12971
12972 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12973    procedure.  Returns zero if assignment is OK, nonzero if there is a
12974    problem.  */
12975 int
12976 gfc_impure_variable (gfc_symbol *sym)
12977 {
12978   gfc_symbol *proc;
12979   gfc_namespace *ns;
12980
12981   if (sym->attr.use_assoc || sym->attr.in_common)
12982     return 1;
12983
12984   /* Check if the symbol's ns is inside the pure procedure.  */
12985   for (ns = gfc_current_ns; ns; ns = ns->parent)
12986     {
12987       if (ns == sym->ns)
12988         break;
12989       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12990         return 1;
12991     }
12992
12993   proc = sym->ns->proc_name;
12994   if (sym->attr.dummy && gfc_pure (proc)
12995         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12996                 ||
12997              proc->attr.function))
12998     return 1;
12999
13000   /* TODO: Sort out what can be storage associated, if anything, and include
13001      it here.  In principle equivalences should be scanned but it does not
13002      seem to be possible to storage associate an impure variable this way.  */
13003   return 0;
13004 }
13005
13006
13007 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
13008    current namespace is inside a pure procedure.  */
13009
13010 int
13011 gfc_pure (gfc_symbol *sym)
13012 {
13013   symbol_attribute attr;
13014   gfc_namespace *ns;
13015
13016   if (sym == NULL)
13017     {
13018       /* Check if the current namespace or one of its parents
13019         belongs to a pure procedure.  */
13020       for (ns = gfc_current_ns; ns; ns = ns->parent)
13021         {
13022           sym = ns->proc_name;
13023           if (sym == NULL)
13024             return 0;
13025           attr = sym->attr;
13026           if (attr.flavor == FL_PROCEDURE && attr.pure)
13027             return 1;
13028         }
13029       return 0;
13030     }
13031
13032   attr = sym->attr;
13033
13034   return attr.flavor == FL_PROCEDURE && attr.pure;
13035 }
13036
13037
13038 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
13039    checks if the current namespace is implicitly pure.  Note that this
13040    function returns false for a PURE procedure.  */
13041
13042 int
13043 gfc_implicit_pure (gfc_symbol *sym)
13044 {
13045   symbol_attribute attr;
13046
13047   if (sym == NULL)
13048     {
13049       /* Check if the current namespace is implicit_pure.  */
13050       sym = gfc_current_ns->proc_name;
13051       if (sym == NULL)
13052         return 0;
13053       attr = sym->attr;
13054       if (attr.flavor == FL_PROCEDURE
13055             && attr.implicit_pure && !attr.pure)
13056         return 1;
13057       return 0;
13058     }
13059
13060   attr = sym->attr;
13061
13062   return attr.flavor == FL_PROCEDURE && attr.implicit_pure && !attr.pure;
13063 }
13064
13065
13066 /* Test whether the current procedure is elemental or not.  */
13067
13068 int
13069 gfc_elemental (gfc_symbol *sym)
13070 {
13071   symbol_attribute attr;
13072
13073   if (sym == NULL)
13074     sym = gfc_current_ns->proc_name;
13075   if (sym == NULL)
13076     return 0;
13077   attr = sym->attr;
13078
13079   return attr.flavor == FL_PROCEDURE && attr.elemental;
13080 }
13081
13082
13083 /* Warn about unused labels.  */
13084
13085 static void
13086 warn_unused_fortran_label (gfc_st_label *label)
13087 {
13088   if (label == NULL)
13089     return;
13090
13091   warn_unused_fortran_label (label->left);
13092
13093   if (label->defined == ST_LABEL_UNKNOWN)
13094     return;
13095
13096   switch (label->referenced)
13097     {
13098     case ST_LABEL_UNKNOWN:
13099       gfc_warning ("Label %d at %L defined but not used", label->value,
13100                    &label->where);
13101       break;
13102
13103     case ST_LABEL_BAD_TARGET:
13104       gfc_warning ("Label %d at %L defined but cannot be used",
13105                    label->value, &label->where);
13106       break;
13107
13108     default:
13109       break;
13110     }
13111
13112   warn_unused_fortran_label (label->right);
13113 }
13114
13115
13116 /* Returns the sequence type of a symbol or sequence.  */
13117
13118 static seq_type
13119 sequence_type (gfc_typespec ts)
13120 {
13121   seq_type result;
13122   gfc_component *c;
13123
13124   switch (ts.type)
13125   {
13126     case BT_DERIVED:
13127
13128       if (ts.u.derived->components == NULL)
13129         return SEQ_NONDEFAULT;
13130
13131       result = sequence_type (ts.u.derived->components->ts);
13132       for (c = ts.u.derived->components->next; c; c = c->next)
13133         if (sequence_type (c->ts) != result)
13134           return SEQ_MIXED;
13135
13136       return result;
13137
13138     case BT_CHARACTER:
13139       if (ts.kind != gfc_default_character_kind)
13140           return SEQ_NONDEFAULT;
13141
13142       return SEQ_CHARACTER;
13143
13144     case BT_INTEGER:
13145       if (ts.kind != gfc_default_integer_kind)
13146           return SEQ_NONDEFAULT;
13147
13148       return SEQ_NUMERIC;
13149
13150     case BT_REAL:
13151       if (!(ts.kind == gfc_default_real_kind
13152             || ts.kind == gfc_default_double_kind))
13153           return SEQ_NONDEFAULT;
13154
13155       return SEQ_NUMERIC;
13156
13157     case BT_COMPLEX:
13158       if (ts.kind != gfc_default_complex_kind)
13159           return SEQ_NONDEFAULT;
13160
13161       return SEQ_NUMERIC;
13162
13163     case BT_LOGICAL:
13164       if (ts.kind != gfc_default_logical_kind)
13165           return SEQ_NONDEFAULT;
13166
13167       return SEQ_NUMERIC;
13168
13169     default:
13170       return SEQ_NONDEFAULT;
13171   }
13172 }
13173
13174
13175 /* Resolve derived type EQUIVALENCE object.  */
13176
13177 static gfc_try
13178 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
13179 {
13180   gfc_component *c = derived->components;
13181
13182   if (!derived)
13183     return SUCCESS;
13184
13185   /* Shall not be an object of nonsequence derived type.  */
13186   if (!derived->attr.sequence)
13187     {
13188       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
13189                  "attribute to be an EQUIVALENCE object", sym->name,
13190                  &e->where);
13191       return FAILURE;
13192     }
13193
13194   /* Shall not have allocatable components.  */
13195   if (derived->attr.alloc_comp)
13196     {
13197       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
13198                  "components to be an EQUIVALENCE object",sym->name,
13199                  &e->where);
13200       return FAILURE;
13201     }
13202
13203   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
13204     {
13205       gfc_error ("Derived type variable '%s' at %L with default "
13206                  "initialization cannot be in EQUIVALENCE with a variable "
13207                  "in COMMON", sym->name, &e->where);
13208       return FAILURE;
13209     }
13210
13211   for (; c ; c = c->next)
13212     {
13213       if (c->ts.type == BT_DERIVED
13214           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
13215         return FAILURE;
13216
13217       /* Shall not be an object of sequence derived type containing a pointer
13218          in the structure.  */
13219       if (c->attr.pointer)
13220         {
13221           gfc_error ("Derived type variable '%s' at %L with pointer "
13222                      "component(s) cannot be an EQUIVALENCE object",
13223                      sym->name, &e->where);
13224           return FAILURE;
13225         }
13226     }
13227   return SUCCESS;
13228 }
13229
13230
13231 /* Resolve equivalence object. 
13232    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
13233    an allocatable array, an object of nonsequence derived type, an object of
13234    sequence derived type containing a pointer at any level of component
13235    selection, an automatic object, a function name, an entry name, a result
13236    name, a named constant, a structure component, or a subobject of any of
13237    the preceding objects.  A substring shall not have length zero.  A
13238    derived type shall not have components with default initialization nor
13239    shall two objects of an equivalence group be initialized.
13240    Either all or none of the objects shall have an protected attribute.
13241    The simple constraints are done in symbol.c(check_conflict) and the rest
13242    are implemented here.  */
13243
13244 static void
13245 resolve_equivalence (gfc_equiv *eq)
13246 {
13247   gfc_symbol *sym;
13248   gfc_symbol *first_sym;
13249   gfc_expr *e;
13250   gfc_ref *r;
13251   locus *last_where = NULL;
13252   seq_type eq_type, last_eq_type;
13253   gfc_typespec *last_ts;
13254   int object, cnt_protected;
13255   const char *msg;
13256
13257   last_ts = &eq->expr->symtree->n.sym->ts;
13258
13259   first_sym = eq->expr->symtree->n.sym;
13260
13261   cnt_protected = 0;
13262
13263   for (object = 1; eq; eq = eq->eq, object++)
13264     {
13265       e = eq->expr;
13266
13267       e->ts = e->symtree->n.sym->ts;
13268       /* match_varspec might not know yet if it is seeing
13269          array reference or substring reference, as it doesn't
13270          know the types.  */
13271       if (e->ref && e->ref->type == REF_ARRAY)
13272         {
13273           gfc_ref *ref = e->ref;
13274           sym = e->symtree->n.sym;
13275
13276           if (sym->attr.dimension)
13277             {
13278               ref->u.ar.as = sym->as;
13279               ref = ref->next;
13280             }
13281
13282           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
13283           if (e->ts.type == BT_CHARACTER
13284               && ref
13285               && ref->type == REF_ARRAY
13286               && ref->u.ar.dimen == 1
13287               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
13288               && ref->u.ar.stride[0] == NULL)
13289             {
13290               gfc_expr *start = ref->u.ar.start[0];
13291               gfc_expr *end = ref->u.ar.end[0];
13292               void *mem = NULL;
13293
13294               /* Optimize away the (:) reference.  */
13295               if (start == NULL && end == NULL)
13296                 {
13297                   if (e->ref == ref)
13298                     e->ref = ref->next;
13299                   else
13300                     e->ref->next = ref->next;
13301                   mem = ref;
13302                 }
13303               else
13304                 {
13305                   ref->type = REF_SUBSTRING;
13306                   if (start == NULL)
13307                     start = gfc_get_int_expr (gfc_default_integer_kind,
13308                                               NULL, 1);
13309                   ref->u.ss.start = start;
13310                   if (end == NULL && e->ts.u.cl)
13311                     end = gfc_copy_expr (e->ts.u.cl->length);
13312                   ref->u.ss.end = end;
13313                   ref->u.ss.length = e->ts.u.cl;
13314                   e->ts.u.cl = NULL;
13315                 }
13316               ref = ref->next;
13317               free (mem);
13318             }
13319
13320           /* Any further ref is an error.  */
13321           if (ref)
13322             {
13323               gcc_assert (ref->type == REF_ARRAY);
13324               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
13325                          &ref->u.ar.where);
13326               continue;
13327             }
13328         }
13329
13330       if (gfc_resolve_expr (e) == FAILURE)
13331         continue;
13332
13333       sym = e->symtree->n.sym;
13334
13335       if (sym->attr.is_protected)
13336         cnt_protected++;
13337       if (cnt_protected > 0 && cnt_protected != object)
13338         {
13339               gfc_error ("Either all or none of the objects in the "
13340                          "EQUIVALENCE set at %L shall have the "
13341                          "PROTECTED attribute",
13342                          &e->where);
13343               break;
13344         }
13345
13346       /* Shall not equivalence common block variables in a PURE procedure.  */
13347       if (sym->ns->proc_name
13348           && sym->ns->proc_name->attr.pure
13349           && sym->attr.in_common)
13350         {
13351           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
13352                      "object in the pure procedure '%s'",
13353                      sym->name, &e->where, sym->ns->proc_name->name);
13354           break;
13355         }
13356
13357       /* Shall not be a named constant.  */
13358       if (e->expr_type == EXPR_CONSTANT)
13359         {
13360           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
13361                      "object", sym->name, &e->where);
13362           continue;
13363         }
13364
13365       if (e->ts.type == BT_DERIVED
13366           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
13367         continue;
13368
13369       /* Check that the types correspond correctly:
13370          Note 5.28:
13371          A numeric sequence structure may be equivalenced to another sequence
13372          structure, an object of default integer type, default real type, double
13373          precision real type, default logical type such that components of the
13374          structure ultimately only become associated to objects of the same
13375          kind. A character sequence structure may be equivalenced to an object
13376          of default character kind or another character sequence structure.
13377          Other objects may be equivalenced only to objects of the same type and
13378          kind parameters.  */
13379
13380       /* Identical types are unconditionally OK.  */
13381       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
13382         goto identical_types;
13383
13384       last_eq_type = sequence_type (*last_ts);
13385       eq_type = sequence_type (sym->ts);
13386
13387       /* Since the pair of objects is not of the same type, mixed or
13388          non-default sequences can be rejected.  */
13389
13390       msg = "Sequence %s with mixed components in EQUIVALENCE "
13391             "statement at %L with different type objects";
13392       if ((object ==2
13393            && last_eq_type == SEQ_MIXED
13394            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
13395               == FAILURE)
13396           || (eq_type == SEQ_MIXED
13397               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13398                                  &e->where) == FAILURE))
13399         continue;
13400
13401       msg = "Non-default type object or sequence %s in EQUIVALENCE "
13402             "statement at %L with objects of different type";
13403       if ((object ==2
13404            && last_eq_type == SEQ_NONDEFAULT
13405            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
13406                               last_where) == FAILURE)
13407           || (eq_type == SEQ_NONDEFAULT
13408               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13409                                  &e->where) == FAILURE))
13410         continue;
13411
13412       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13413            "EQUIVALENCE statement at %L";
13414       if (last_eq_type == SEQ_CHARACTER
13415           && eq_type != SEQ_CHARACTER
13416           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13417                              &e->where) == FAILURE)
13418                 continue;
13419
13420       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13421            "EQUIVALENCE statement at %L";
13422       if (last_eq_type == SEQ_NUMERIC
13423           && eq_type != SEQ_NUMERIC
13424           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13425                              &e->where) == FAILURE)
13426                 continue;
13427
13428   identical_types:
13429       last_ts =&sym->ts;
13430       last_where = &e->where;
13431
13432       if (!e->ref)
13433         continue;
13434
13435       /* Shall not be an automatic array.  */
13436       if (e->ref->type == REF_ARRAY
13437           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13438         {
13439           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13440                      "an EQUIVALENCE object", sym->name, &e->where);
13441           continue;
13442         }
13443
13444       r = e->ref;
13445       while (r)
13446         {
13447           /* Shall not be a structure component.  */
13448           if (r->type == REF_COMPONENT)
13449             {
13450               gfc_error ("Structure component '%s' at %L cannot be an "
13451                          "EQUIVALENCE object",
13452                          r->u.c.component->name, &e->where);
13453               break;
13454             }
13455
13456           /* A substring shall not have length zero.  */
13457           if (r->type == REF_SUBSTRING)
13458             {
13459               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13460                 {
13461                   gfc_error ("Substring at %L has length zero",
13462                              &r->u.ss.start->where);
13463                   break;
13464                 }
13465             }
13466           r = r->next;
13467         }
13468     }
13469 }
13470
13471
13472 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13473
13474 static void
13475 resolve_fntype (gfc_namespace *ns)
13476 {
13477   gfc_entry_list *el;
13478   gfc_symbol *sym;
13479
13480   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13481     return;
13482
13483   /* If there are any entries, ns->proc_name is the entry master
13484      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13485   if (ns->entries)
13486     sym = ns->entries->sym;
13487   else
13488     sym = ns->proc_name;
13489   if (sym->result == sym
13490       && sym->ts.type == BT_UNKNOWN
13491       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13492       && !sym->attr.untyped)
13493     {
13494       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13495                  sym->name, &sym->declared_at);
13496       sym->attr.untyped = 1;
13497     }
13498
13499   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13500       && !sym->attr.contained
13501       && !gfc_check_symbol_access (sym->ts.u.derived)
13502       && gfc_check_symbol_access (sym))
13503     {
13504       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13505                       "%L of PRIVATE type '%s'", sym->name,
13506                       &sym->declared_at, sym->ts.u.derived->name);
13507     }
13508
13509     if (ns->entries)
13510     for (el = ns->entries->next; el; el = el->next)
13511       {
13512         if (el->sym->result == el->sym
13513             && el->sym->ts.type == BT_UNKNOWN
13514             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13515             && !el->sym->attr.untyped)
13516           {
13517             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13518                        el->sym->name, &el->sym->declared_at);
13519             el->sym->attr.untyped = 1;
13520           }
13521       }
13522 }
13523
13524
13525 /* 12.3.2.1.1 Defined operators.  */
13526
13527 static gfc_try
13528 check_uop_procedure (gfc_symbol *sym, locus where)
13529 {
13530   gfc_formal_arglist *formal;
13531
13532   if (!sym->attr.function)
13533     {
13534       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13535                  sym->name, &where);
13536       return FAILURE;
13537     }
13538
13539   if (sym->ts.type == BT_CHARACTER
13540       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13541       && !(sym->result && sym->result->ts.u.cl
13542            && sym->result->ts.u.cl->length))
13543     {
13544       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13545                  "character length", sym->name, &where);
13546       return FAILURE;
13547     }
13548
13549   formal = sym->formal;
13550   if (!formal || !formal->sym)
13551     {
13552       gfc_error ("User operator procedure '%s' at %L must have at least "
13553                  "one argument", sym->name, &where);
13554       return FAILURE;
13555     }
13556
13557   if (formal->sym->attr.intent != INTENT_IN)
13558     {
13559       gfc_error ("First argument of operator interface at %L must be "
13560                  "INTENT(IN)", &where);
13561       return FAILURE;
13562     }
13563
13564   if (formal->sym->attr.optional)
13565     {
13566       gfc_error ("First argument of operator interface at %L cannot be "
13567                  "optional", &where);
13568       return FAILURE;
13569     }
13570
13571   formal = formal->next;
13572   if (!formal || !formal->sym)
13573     return SUCCESS;
13574
13575   if (formal->sym->attr.intent != INTENT_IN)
13576     {
13577       gfc_error ("Second argument of operator interface at %L must be "
13578                  "INTENT(IN)", &where);
13579       return FAILURE;
13580     }
13581
13582   if (formal->sym->attr.optional)
13583     {
13584       gfc_error ("Second argument of operator interface at %L cannot be "
13585                  "optional", &where);
13586       return FAILURE;
13587     }
13588
13589   if (formal->next)
13590     {
13591       gfc_error ("Operator interface at %L must have, at most, two "
13592                  "arguments", &where);
13593       return FAILURE;
13594     }
13595
13596   return SUCCESS;
13597 }
13598
13599 static void
13600 gfc_resolve_uops (gfc_symtree *symtree)
13601 {
13602   gfc_interface *itr;
13603
13604   if (symtree == NULL)
13605     return;
13606
13607   gfc_resolve_uops (symtree->left);
13608   gfc_resolve_uops (symtree->right);
13609
13610   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13611     check_uop_procedure (itr->sym, itr->sym->declared_at);
13612 }
13613
13614
13615 /* Examine all of the expressions associated with a program unit,
13616    assign types to all intermediate expressions, make sure that all
13617    assignments are to compatible types and figure out which names
13618    refer to which functions or subroutines.  It doesn't check code
13619    block, which is handled by resolve_code.  */
13620
13621 static void
13622 resolve_types (gfc_namespace *ns)
13623 {
13624   gfc_namespace *n;
13625   gfc_charlen *cl;
13626   gfc_data *d;
13627   gfc_equiv *eq;
13628   gfc_namespace* old_ns = gfc_current_ns;
13629
13630   /* Check that all IMPLICIT types are ok.  */
13631   if (!ns->seen_implicit_none)
13632     {
13633       unsigned letter;
13634       for (letter = 0; letter != GFC_LETTERS; ++letter)
13635         if (ns->set_flag[letter]
13636             && resolve_typespec_used (&ns->default_type[letter],
13637                                       &ns->implicit_loc[letter],
13638                                       NULL) == FAILURE)
13639           return;
13640     }
13641
13642   gfc_current_ns = ns;
13643
13644   resolve_entries (ns);
13645
13646   resolve_common_vars (ns->blank_common.head, false);
13647   resolve_common_blocks (ns->common_root);
13648
13649   resolve_contained_functions (ns);
13650
13651   if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE
13652       && ns->proc_name->attr.if_source == IFSRC_IFBODY)
13653     resolve_formal_arglist (ns->proc_name);
13654
13655   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13656
13657   for (cl = ns->cl_list; cl; cl = cl->next)
13658     resolve_charlen (cl);
13659
13660   gfc_traverse_ns (ns, resolve_symbol);
13661
13662   resolve_fntype (ns);
13663
13664   for (n = ns->contained; n; n = n->sibling)
13665     {
13666       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13667         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13668                    "also be PURE", n->proc_name->name,
13669                    &n->proc_name->declared_at);
13670
13671       resolve_types (n);
13672     }
13673
13674   forall_flag = 0;
13675   do_concurrent_flag = 0;
13676   gfc_check_interfaces (ns);
13677
13678   gfc_traverse_ns (ns, resolve_values);
13679
13680   if (ns->save_all)
13681     gfc_save_all (ns);
13682
13683   iter_stack = NULL;
13684   for (d = ns->data; d; d = d->next)
13685     resolve_data (d);
13686
13687   iter_stack = NULL;
13688   gfc_traverse_ns (ns, gfc_formalize_init_value);
13689
13690   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13691
13692   if (ns->common_root != NULL)
13693     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13694
13695   for (eq = ns->equiv; eq; eq = eq->next)
13696     resolve_equivalence (eq);
13697
13698   /* Warn about unused labels.  */
13699   if (warn_unused_label)
13700     warn_unused_fortran_label (ns->st_labels);
13701
13702   gfc_resolve_uops (ns->uop_root);
13703
13704   gfc_current_ns = old_ns;
13705 }
13706
13707
13708 /* Call resolve_code recursively.  */
13709
13710 static void
13711 resolve_codes (gfc_namespace *ns)
13712 {
13713   gfc_namespace *n;
13714   bitmap_obstack old_obstack;
13715
13716   if (ns->resolved == 1)
13717     return;
13718
13719   for (n = ns->contained; n; n = n->sibling)
13720     resolve_codes (n);
13721
13722   gfc_current_ns = ns;
13723
13724   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13725   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13726     cs_base = NULL;
13727
13728   /* Set to an out of range value.  */
13729   current_entry_id = -1;
13730
13731   old_obstack = labels_obstack;
13732   bitmap_obstack_initialize (&labels_obstack);
13733
13734   resolve_code (ns->code, ns);
13735
13736   bitmap_obstack_release (&labels_obstack);
13737   labels_obstack = old_obstack;
13738 }
13739
13740
13741 /* This function is called after a complete program unit has been compiled.
13742    Its purpose is to examine all of the expressions associated with a program
13743    unit, assign types to all intermediate expressions, make sure that all
13744    assignments are to compatible types and figure out which names refer to
13745    which functions or subroutines.  */
13746
13747 void
13748 gfc_resolve (gfc_namespace *ns)
13749 {
13750   gfc_namespace *old_ns;
13751   code_stack *old_cs_base;
13752
13753   if (ns->resolved)
13754     return;
13755
13756   ns->resolved = -1;
13757   old_ns = gfc_current_ns;
13758   old_cs_base = cs_base;
13759
13760   resolve_types (ns);
13761   resolve_codes (ns);
13762
13763   gfc_current_ns = old_ns;
13764   cs_base = old_cs_base;
13765   ns->resolved = 1;
13766
13767   gfc_run_passes (ns);
13768 }