OSDN Git Service

2011-08-22 Mikael Morin <mikael.morin@gcc.gnu.org>
[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 block.  */
62
63 static int forall_flag;
64
65 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
66
67 static int omp_workshare_flag;
68
69 /* Nonzero if we are processing a formal arglist. The corresponding function
70    resets the flag each time that it is read.  */
71 static int formal_arg_flag = 0;
72
73 /* True if we are resolving a specification expression.  */
74 static int specification_expr = 0;
75
76 /* The id of the last entry seen.  */
77 static int current_entry_id;
78
79 /* We use bitmaps to determine if a branch target is valid.  */
80 static bitmap_obstack labels_obstack;
81
82 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
83 static bool inquiry_argument = false;
84
85 int
86 gfc_is_formal_arg (void)
87 {
88   return formal_arg_flag;
89 }
90
91 /* Is the symbol host associated?  */
92 static bool
93 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
94 {
95   for (ns = ns->parent; ns; ns = ns->parent)
96     {      
97       if (sym->ns == ns)
98         return true;
99     }
100
101   return false;
102 }
103
104 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
105    an ABSTRACT derived-type.  If where is not NULL, an error message with that
106    locus is printed, optionally using name.  */
107
108 static gfc_try
109 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
110 {
111   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
112     {
113       if (where)
114         {
115           if (name)
116             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
117                        name, where, ts->u.derived->name);
118           else
119             gfc_error ("ABSTRACT type '%s' used at %L",
120                        ts->u.derived->name, where);
121         }
122
123       return FAILURE;
124     }
125
126   return SUCCESS;
127 }
128
129
130 static void resolve_symbol (gfc_symbol *sym);
131 static gfc_try resolve_intrinsic (gfc_symbol *sym, locus *loc);
132
133
134 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
135
136 static gfc_try
137 resolve_procedure_interface (gfc_symbol *sym)
138 {
139   if (sym->ts.interface == sym)
140     {
141       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
142                  sym->name, &sym->declared_at);
143       return FAILURE;
144     }
145   if (sym->ts.interface->attr.procedure)
146     {
147       gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
148                  "in a later PROCEDURE statement", sym->ts.interface->name,
149                  sym->name, &sym->declared_at);
150       return FAILURE;
151     }
152
153   /* Get the attributes from the interface (now resolved).  */
154   if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
155     {
156       gfc_symbol *ifc = sym->ts.interface;
157       resolve_symbol (ifc);
158
159       if (ifc->attr.intrinsic)
160         resolve_intrinsic (ifc, &ifc->declared_at);
161
162       if (ifc->result)
163         {
164           sym->ts = ifc->result->ts;
165           sym->result = sym;
166         }
167       else   
168         sym->ts = ifc->ts;
169       sym->ts.interface = ifc;
170       sym->attr.function = ifc->attr.function;
171       sym->attr.subroutine = ifc->attr.subroutine;
172       gfc_copy_formal_args (sym, ifc);
173
174       sym->attr.allocatable = ifc->attr.allocatable;
175       sym->attr.pointer = ifc->attr.pointer;
176       sym->attr.pure = ifc->attr.pure;
177       sym->attr.elemental = ifc->attr.elemental;
178       sym->attr.dimension = ifc->attr.dimension;
179       sym->attr.contiguous = ifc->attr.contiguous;
180       sym->attr.recursive = ifc->attr.recursive;
181       sym->attr.always_explicit = ifc->attr.always_explicit;
182       sym->attr.ext_attr |= ifc->attr.ext_attr;
183       sym->attr.is_bind_c = ifc->attr.is_bind_c;
184       /* Copy array spec.  */
185       sym->as = gfc_copy_array_spec (ifc->as);
186       if (sym->as)
187         {
188           int i;
189           for (i = 0; i < sym->as->rank; i++)
190             {
191               gfc_expr_replace_symbols (sym->as->lower[i], sym);
192               gfc_expr_replace_symbols (sym->as->upper[i], sym);
193             }
194         }
195       /* Copy char length.  */
196       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
197         {
198           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
199           gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
200           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
201               && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
202             return FAILURE;
203         }
204     }
205   else if (sym->ts.interface->name[0] != '\0')
206     {
207       gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
208                  sym->ts.interface->name, sym->name, &sym->declared_at);
209       return FAILURE;
210     }
211
212   return SUCCESS;
213 }
214
215
216 /* Resolve types of formal argument lists.  These have to be done early so that
217    the formal argument lists of module procedures can be copied to the
218    containing module before the individual procedures are resolved
219    individually.  We also resolve argument lists of procedures in interface
220    blocks because they are self-contained scoping units.
221
222    Since a dummy argument cannot be a non-dummy procedure, the only
223    resort left for untyped names are the IMPLICIT types.  */
224
225 static void
226 resolve_formal_arglist (gfc_symbol *proc)
227 {
228   gfc_formal_arglist *f;
229   gfc_symbol *sym;
230   int i;
231
232   if (proc->result != NULL)
233     sym = proc->result;
234   else
235     sym = proc;
236
237   if (gfc_elemental (proc)
238       || sym->attr.pointer || sym->attr.allocatable
239       || (sym->as && sym->as->rank > 0))
240     {
241       proc->attr.always_explicit = 1;
242       sym->attr.always_explicit = 1;
243     }
244
245   formal_arg_flag = 1;
246
247   for (f = proc->formal; f; f = f->next)
248     {
249       sym = f->sym;
250
251       if (sym == NULL)
252         {
253           /* Alternate return placeholder.  */
254           if (gfc_elemental (proc))
255             gfc_error ("Alternate return specifier in elemental subroutine "
256                        "'%s' at %L is not allowed", proc->name,
257                        &proc->declared_at);
258           if (proc->attr.function)
259             gfc_error ("Alternate return specifier in function "
260                        "'%s' at %L is not allowed", proc->name,
261                        &proc->declared_at);
262           continue;
263         }
264       else if (sym->attr.procedure && sym->ts.interface
265                && sym->attr.if_source != IFSRC_DECL)
266         resolve_procedure_interface (sym);
267
268       if (sym->attr.if_source != IFSRC_UNKNOWN)
269         resolve_formal_arglist (sym);
270
271       if (sym->attr.subroutine || sym->attr.external || sym->attr.intrinsic)
272         {
273           if (gfc_pure (proc) && !gfc_pure (sym))
274             {
275               gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
276                          "also be PURE", sym->name, &sym->declared_at);
277               continue;
278             }
279
280           if (proc->attr.implicit_pure && !gfc_pure(sym))
281             proc->attr.implicit_pure = 0;
282
283           if (gfc_elemental (proc))
284             {
285               gfc_error ("Dummy procedure at %L not allowed in ELEMENTAL "
286                          "procedure", &sym->declared_at);
287               continue;
288             }
289
290           if (sym->attr.function
291                 && sym->ts.type == BT_UNKNOWN
292                 && sym->attr.intrinsic)
293             {
294               gfc_intrinsic_sym *isym;
295               isym = gfc_find_function (sym->name);
296               if (isym == NULL || !isym->specific)
297                 {
298                   gfc_error ("Unable to find a specific INTRINSIC procedure "
299                              "for the reference '%s' at %L", sym->name,
300                              &sym->declared_at);
301                 }
302               sym->ts = isym->ts;
303             }
304
305           continue;
306         }
307
308       if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
309           && (!sym->attr.function || sym->result == sym))
310         gfc_set_default_type (sym, 1, sym->ns);
311
312       gfc_resolve_array_spec (sym->as, 0);
313
314       /* We can't tell if an array with dimension (:) is assumed or deferred
315          shape until we know if it has the pointer or allocatable attributes.
316       */
317       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
318           && !(sym->attr.pointer || sym->attr.allocatable)
319           && sym->attr.flavor != FL_PROCEDURE)
320         {
321           sym->as->type = AS_ASSUMED_SHAPE;
322           for (i = 0; i < sym->as->rank; i++)
323             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
324                                                   NULL, 1);
325         }
326
327       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
328           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
329           || sym->attr.optional)
330         {
331           proc->attr.always_explicit = 1;
332           if (proc->result)
333             proc->result->attr.always_explicit = 1;
334         }
335
336       /* If the flavor is unknown at this point, it has to be a variable.
337          A procedure specification would have already set the type.  */
338
339       if (sym->attr.flavor == FL_UNKNOWN)
340         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
341
342       if (gfc_pure (proc) && !sym->attr.pointer
343           && sym->attr.flavor != FL_PROCEDURE)
344         {
345           if (proc->attr.function && sym->attr.intent != INTENT_IN)
346             {
347               if (sym->attr.value)
348                 gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s' "
349                                 "of pure function '%s' at %L with VALUE "
350                                 "attribute but without INTENT(IN)", sym->name,
351                                 proc->name, &sym->declared_at);
352               else
353                 gfc_error ("Argument '%s' of pure function '%s' at %L must be "
354                            "INTENT(IN) or VALUE", sym->name, proc->name,
355                            &sym->declared_at);
356             }
357
358           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
359             {
360               if (sym->attr.value)
361                 gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s' "
362                                 "of pure subroutine '%s' at %L with VALUE "
363                                 "attribute but without INTENT", sym->name,
364                                 proc->name, &sym->declared_at);
365               else
366                 gfc_error ("Argument '%s' of pure subroutine '%s' at %L must "
367                        "have its INTENT specified or have the VALUE "
368                        "attribute", sym->name, proc->name, &sym->declared_at);
369             }
370         }
371
372       if (proc->attr.implicit_pure && !sym->attr.pointer
373           && sym->attr.flavor != FL_PROCEDURE)
374         {
375           if (proc->attr.function && sym->attr.intent != INTENT_IN)
376             proc->attr.implicit_pure = 0;
377
378           if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
379             proc->attr.implicit_pure = 0;
380         }
381
382       if (gfc_elemental (proc))
383         {
384           /* F2008, C1289.  */
385           if (sym->attr.codimension)
386             {
387               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
388                          "procedure", sym->name, &sym->declared_at);
389               continue;
390             }
391
392           if (sym->as != NULL)
393             {
394               gfc_error ("Argument '%s' of elemental procedure at %L must "
395                          "be scalar", sym->name, &sym->declared_at);
396               continue;
397             }
398
399           if (sym->attr.allocatable)
400             {
401               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
402                          "have the ALLOCATABLE attribute", sym->name,
403                          &sym->declared_at);
404               continue;
405             }
406
407           if (sym->attr.pointer)
408             {
409               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
410                          "have the POINTER attribute", sym->name,
411                          &sym->declared_at);
412               continue;
413             }
414
415           if (sym->attr.flavor == FL_PROCEDURE)
416             {
417               gfc_error ("Dummy procedure '%s' not allowed in elemental "
418                          "procedure '%s' at %L", sym->name, proc->name,
419                          &sym->declared_at);
420               continue;
421             }
422
423           if (sym->attr.intent == INTENT_UNKNOWN)
424             {
425               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
426                          "have its INTENT specified", sym->name, proc->name,
427                          &sym->declared_at);
428               continue;
429             }
430         }
431
432       /* Each dummy shall be specified to be scalar.  */
433       if (proc->attr.proc == PROC_ST_FUNCTION)
434         {
435           if (sym->as != NULL)
436             {
437               gfc_error ("Argument '%s' of statement function at %L must "
438                          "be scalar", sym->name, &sym->declared_at);
439               continue;
440             }
441
442           if (sym->ts.type == BT_CHARACTER)
443             {
444               gfc_charlen *cl = sym->ts.u.cl;
445               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
446                 {
447                   gfc_error ("Character-valued argument '%s' of statement "
448                              "function at %L must have constant length",
449                              sym->name, &sym->declared_at);
450                   continue;
451                 }
452             }
453         }
454     }
455   formal_arg_flag = 0;
456 }
457
458
459 /* Work function called when searching for symbols that have argument lists
460    associated with them.  */
461
462 static void
463 find_arglists (gfc_symbol *sym)
464 {
465   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns)
466     return;
467
468   resolve_formal_arglist (sym);
469 }
470
471
472 /* Given a namespace, resolve all formal argument lists within the namespace.
473  */
474
475 static void
476 resolve_formal_arglists (gfc_namespace *ns)
477 {
478   if (ns == NULL)
479     return;
480
481   gfc_traverse_ns (ns, find_arglists);
482 }
483
484
485 static void
486 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
487 {
488   gfc_try t;
489
490   /* If this namespace is not a function or an entry master function,
491      ignore it.  */
492   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
493       || sym->attr.entry_master)
494     return;
495
496   /* Try to find out of what the return type is.  */
497   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
498     {
499       t = gfc_set_default_type (sym->result, 0, ns);
500
501       if (t == FAILURE && !sym->result->attr.untyped)
502         {
503           if (sym->result == sym)
504             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
505                        sym->name, &sym->declared_at);
506           else if (!sym->result->attr.proc_pointer)
507             gfc_error ("Result '%s' of contained function '%s' at %L has "
508                        "no IMPLICIT type", sym->result->name, sym->name,
509                        &sym->result->declared_at);
510           sym->result->attr.untyped = 1;
511         }
512     }
513
514   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character 
515      type, lists the only ways a character length value of * can be used:
516      dummy arguments of procedures, named constants, and function results
517      in external functions.  Internal function results and results of module
518      procedures are not on this list, ergo, not permitted.  */
519
520   if (sym->result->ts.type == BT_CHARACTER)
521     {
522       gfc_charlen *cl = sym->result->ts.u.cl;
523       if ((!cl || !cl->length) && !sym->result->ts.deferred)
524         {
525           /* See if this is a module-procedure and adapt error message
526              accordingly.  */
527           bool module_proc;
528           gcc_assert (ns->parent && ns->parent->proc_name);
529           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
530
531           gfc_error ("Character-valued %s '%s' at %L must not be"
532                      " assumed length",
533                      module_proc ? _("module procedure")
534                                  : _("internal function"),
535                      sym->name, &sym->declared_at);
536         }
537     }
538 }
539
540
541 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
542    introduce duplicates.  */
543
544 static void
545 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
546 {
547   gfc_formal_arglist *f, *new_arglist;
548   gfc_symbol *new_sym;
549
550   for (; new_args != NULL; new_args = new_args->next)
551     {
552       new_sym = new_args->sym;
553       /* See if this arg is already in the formal argument list.  */
554       for (f = proc->formal; f; f = f->next)
555         {
556           if (new_sym == f->sym)
557             break;
558         }
559
560       if (f)
561         continue;
562
563       /* Add a new argument.  Argument order is not important.  */
564       new_arglist = gfc_get_formal_arglist ();
565       new_arglist->sym = new_sym;
566       new_arglist->next = proc->formal;
567       proc->formal  = new_arglist;
568     }
569 }
570
571
572 /* Flag the arguments that are not present in all entries.  */
573
574 static void
575 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
576 {
577   gfc_formal_arglist *f, *head;
578   head = new_args;
579
580   for (f = proc->formal; f; f = f->next)
581     {
582       if (f->sym == NULL)
583         continue;
584
585       for (new_args = head; new_args; new_args = new_args->next)
586         {
587           if (new_args->sym == f->sym)
588             break;
589         }
590
591       if (new_args)
592         continue;
593
594       f->sym->attr.not_always_present = 1;
595     }
596 }
597
598
599 /* Resolve alternate entry points.  If a symbol has multiple entry points we
600    create a new master symbol for the main routine, and turn the existing
601    symbol into an entry point.  */
602
603 static void
604 resolve_entries (gfc_namespace *ns)
605 {
606   gfc_namespace *old_ns;
607   gfc_code *c;
608   gfc_symbol *proc;
609   gfc_entry_list *el;
610   char name[GFC_MAX_SYMBOL_LEN + 1];
611   static int master_count = 0;
612
613   if (ns->proc_name == NULL)
614     return;
615
616   /* No need to do anything if this procedure doesn't have alternate entry
617      points.  */
618   if (!ns->entries)
619     return;
620
621   /* We may already have resolved alternate entry points.  */
622   if (ns->proc_name->attr.entry_master)
623     return;
624
625   /* If this isn't a procedure something has gone horribly wrong.  */
626   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
627
628   /* Remember the current namespace.  */
629   old_ns = gfc_current_ns;
630
631   gfc_current_ns = ns;
632
633   /* Add the main entry point to the list of entry points.  */
634   el = gfc_get_entry_list ();
635   el->sym = ns->proc_name;
636   el->id = 0;
637   el->next = ns->entries;
638   ns->entries = el;
639   ns->proc_name->attr.entry = 1;
640
641   /* If it is a module function, it needs to be in the right namespace
642      so that gfc_get_fake_result_decl can gather up the results. The
643      need for this arose in get_proc_name, where these beasts were
644      left in their own namespace, to keep prior references linked to
645      the entry declaration.*/
646   if (ns->proc_name->attr.function
647       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
648     el->sym->ns = ns;
649
650   /* Do the same for entries where the master is not a module
651      procedure.  These are retained in the module namespace because
652      of the module procedure declaration.  */
653   for (el = el->next; el; el = el->next)
654     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
655           && el->sym->attr.mod_proc)
656       el->sym->ns = ns;
657   el = ns->entries;
658
659   /* Add an entry statement for it.  */
660   c = gfc_get_code ();
661   c->op = EXEC_ENTRY;
662   c->ext.entry = el;
663   c->next = ns->code;
664   ns->code = c;
665
666   /* Create a new symbol for the master function.  */
667   /* Give the internal function a unique name (within this file).
668      Also include the function name so the user has some hope of figuring
669      out what is going on.  */
670   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
671             master_count++, ns->proc_name->name);
672   gfc_get_ha_symbol (name, &proc);
673   gcc_assert (proc != NULL);
674
675   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
676   if (ns->proc_name->attr.subroutine)
677     gfc_add_subroutine (&proc->attr, proc->name, NULL);
678   else
679     {
680       gfc_symbol *sym;
681       gfc_typespec *ts, *fts;
682       gfc_array_spec *as, *fas;
683       gfc_add_function (&proc->attr, proc->name, NULL);
684       proc->result = proc;
685       fas = ns->entries->sym->as;
686       fas = fas ? fas : ns->entries->sym->result->as;
687       fts = &ns->entries->sym->result->ts;
688       if (fts->type == BT_UNKNOWN)
689         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
690       for (el = ns->entries->next; el; el = el->next)
691         {
692           ts = &el->sym->result->ts;
693           as = el->sym->as;
694           as = as ? as : el->sym->result->as;
695           if (ts->type == BT_UNKNOWN)
696             ts = gfc_get_default_type (el->sym->result->name, NULL);
697
698           if (! gfc_compare_types (ts, fts)
699               || (el->sym->result->attr.dimension
700                   != ns->entries->sym->result->attr.dimension)
701               || (el->sym->result->attr.pointer
702                   != ns->entries->sym->result->attr.pointer))
703             break;
704           else if (as && fas && ns->entries->sym->result != el->sym->result
705                       && gfc_compare_array_spec (as, fas) == 0)
706             gfc_error ("Function %s at %L has entries with mismatched "
707                        "array specifications", ns->entries->sym->name,
708                        &ns->entries->sym->declared_at);
709           /* The characteristics need to match and thus both need to have
710              the same string length, i.e. both len=*, or both len=4.
711              Having both len=<variable> is also possible, but difficult to
712              check at compile time.  */
713           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
714                    && (((ts->u.cl->length && !fts->u.cl->length)
715                         ||(!ts->u.cl->length && fts->u.cl->length))
716                        || (ts->u.cl->length
717                            && ts->u.cl->length->expr_type
718                               != fts->u.cl->length->expr_type)
719                        || (ts->u.cl->length
720                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
721                            && mpz_cmp (ts->u.cl->length->value.integer,
722                                        fts->u.cl->length->value.integer) != 0)))
723             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
724                             "entries returning variables of different "
725                             "string lengths", ns->entries->sym->name,
726                             &ns->entries->sym->declared_at);
727         }
728
729       if (el == NULL)
730         {
731           sym = ns->entries->sym->result;
732           /* All result types the same.  */
733           proc->ts = *fts;
734           if (sym->attr.dimension)
735             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
736           if (sym->attr.pointer)
737             gfc_add_pointer (&proc->attr, NULL);
738         }
739       else
740         {
741           /* Otherwise the result will be passed through a union by
742              reference.  */
743           proc->attr.mixed_entry_master = 1;
744           for (el = ns->entries; el; el = el->next)
745             {
746               sym = el->sym->result;
747               if (sym->attr.dimension)
748                 {
749                   if (el == ns->entries)
750                     gfc_error ("FUNCTION result %s can't be an array in "
751                                "FUNCTION %s at %L", sym->name,
752                                ns->entries->sym->name, &sym->declared_at);
753                   else
754                     gfc_error ("ENTRY result %s can't be an array in "
755                                "FUNCTION %s at %L", sym->name,
756                                ns->entries->sym->name, &sym->declared_at);
757                 }
758               else if (sym->attr.pointer)
759                 {
760                   if (el == ns->entries)
761                     gfc_error ("FUNCTION result %s can't be a POINTER in "
762                                "FUNCTION %s at %L", sym->name,
763                                ns->entries->sym->name, &sym->declared_at);
764                   else
765                     gfc_error ("ENTRY result %s can't be a POINTER in "
766                                "FUNCTION %s at %L", sym->name,
767                                ns->entries->sym->name, &sym->declared_at);
768                 }
769               else
770                 {
771                   ts = &sym->ts;
772                   if (ts->type == BT_UNKNOWN)
773                     ts = gfc_get_default_type (sym->name, NULL);
774                   switch (ts->type)
775                     {
776                     case BT_INTEGER:
777                       if (ts->kind == gfc_default_integer_kind)
778                         sym = NULL;
779                       break;
780                     case BT_REAL:
781                       if (ts->kind == gfc_default_real_kind
782                           || ts->kind == gfc_default_double_kind)
783                         sym = NULL;
784                       break;
785                     case BT_COMPLEX:
786                       if (ts->kind == gfc_default_complex_kind)
787                         sym = NULL;
788                       break;
789                     case BT_LOGICAL:
790                       if (ts->kind == gfc_default_logical_kind)
791                         sym = NULL;
792                       break;
793                     case BT_UNKNOWN:
794                       /* We will issue error elsewhere.  */
795                       sym = NULL;
796                       break;
797                     default:
798                       break;
799                     }
800                   if (sym)
801                     {
802                       if (el == ns->entries)
803                         gfc_error ("FUNCTION result %s can't be of type %s "
804                                    "in FUNCTION %s at %L", sym->name,
805                                    gfc_typename (ts), ns->entries->sym->name,
806                                    &sym->declared_at);
807                       else
808                         gfc_error ("ENTRY result %s can't be of type %s "
809                                    "in FUNCTION %s at %L", sym->name,
810                                    gfc_typename (ts), ns->entries->sym->name,
811                                    &sym->declared_at);
812                     }
813                 }
814             }
815         }
816     }
817   proc->attr.access = ACCESS_PRIVATE;
818   proc->attr.entry_master = 1;
819
820   /* Merge all the entry point arguments.  */
821   for (el = ns->entries; el; el = el->next)
822     merge_argument_lists (proc, el->sym->formal);
823
824   /* Check the master formal arguments for any that are not
825      present in all entry points.  */
826   for (el = ns->entries; el; el = el->next)
827     check_argument_lists (proc, el->sym->formal);
828
829   /* Use the master function for the function body.  */
830   ns->proc_name = proc;
831
832   /* Finalize the new symbols.  */
833   gfc_commit_symbols ();
834
835   /* Restore the original namespace.  */
836   gfc_current_ns = old_ns;
837 }
838
839
840 /* Resolve common variables.  */
841 static void
842 resolve_common_vars (gfc_symbol *sym, bool named_common)
843 {
844   gfc_symbol *csym = sym;
845
846   for (; csym; csym = csym->common_next)
847     {
848       if (csym->value || csym->attr.data)
849         {
850           if (!csym->ns->is_block_data)
851             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
852                             "but only in BLOCK DATA initialization is "
853                             "allowed", csym->name, &csym->declared_at);
854           else if (!named_common)
855             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
856                             "in a blank COMMON but initialization is only "
857                             "allowed in named common blocks", csym->name,
858                             &csym->declared_at);
859         }
860
861       if (csym->ts.type != BT_DERIVED)
862         continue;
863
864       if (!(csym->ts.u.derived->attr.sequence
865             || csym->ts.u.derived->attr.is_bind_c))
866         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
867                        "has neither the SEQUENCE nor the BIND(C) "
868                        "attribute", csym->name, &csym->declared_at);
869       if (csym->ts.u.derived->attr.alloc_comp)
870         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
871                        "has an ultimate component that is "
872                        "allocatable", csym->name, &csym->declared_at);
873       if (gfc_has_default_initializer (csym->ts.u.derived))
874         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
875                        "may not have default initializer", csym->name,
876                        &csym->declared_at);
877
878       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
879         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
880     }
881 }
882
883 /* Resolve common blocks.  */
884 static void
885 resolve_common_blocks (gfc_symtree *common_root)
886 {
887   gfc_symbol *sym;
888
889   if (common_root == NULL)
890     return;
891
892   if (common_root->left)
893     resolve_common_blocks (common_root->left);
894   if (common_root->right)
895     resolve_common_blocks (common_root->right);
896
897   resolve_common_vars (common_root->n.common->head, true);
898
899   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
900   if (sym == NULL)
901     return;
902
903   if (sym->attr.flavor == FL_PARAMETER)
904     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
905                sym->name, &common_root->n.common->where, &sym->declared_at);
906
907   if (sym->attr.intrinsic)
908     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
909                sym->name, &common_root->n.common->where);
910   else if (sym->attr.result
911            || gfc_is_function_return_value (sym, gfc_current_ns))
912     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
913                     "that is also a function result", sym->name,
914                     &common_root->n.common->where);
915   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
916            && sym->attr.proc != PROC_ST_FUNCTION)
917     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
918                     "that is also a global procedure", sym->name,
919                     &common_root->n.common->where);
920 }
921
922
923 /* Resolve contained function types.  Because contained functions can call one
924    another, they have to be worked out before any of the contained procedures
925    can be resolved.
926
927    The good news is that if a function doesn't already have a type, the only
928    way it can get one is through an IMPLICIT type or a RESULT variable, because
929    by definition contained functions are contained namespace they're contained
930    in, not in a sibling or parent namespace.  */
931
932 static void
933 resolve_contained_functions (gfc_namespace *ns)
934 {
935   gfc_namespace *child;
936   gfc_entry_list *el;
937
938   resolve_formal_arglists (ns);
939
940   for (child = ns->contained; child; child = child->sibling)
941     {
942       /* Resolve alternate entry points first.  */
943       resolve_entries (child);
944
945       /* Then check function return types.  */
946       resolve_contained_fntype (child->proc_name, child);
947       for (el = child->entries; el; el = el->next)
948         resolve_contained_fntype (el->sym, child);
949     }
950 }
951
952
953 static gfc_try resolve_fl_derived0 (gfc_symbol *sym);
954
955
956 /* Resolve all of the elements of a structure constructor and make sure that
957    the types are correct. The 'init' flag indicates that the given
958    constructor is an initializer.  */
959
960 static gfc_try
961 resolve_structure_cons (gfc_expr *expr, int init)
962 {
963   gfc_constructor *cons;
964   gfc_component *comp;
965   gfc_try t;
966   symbol_attribute a;
967
968   t = SUCCESS;
969
970   if (expr->ts.type == BT_DERIVED)
971     resolve_fl_derived0 (expr->ts.u.derived);
972
973   cons = gfc_constructor_first (expr->value.constructor);
974   /* A constructor may have references if it is the result of substituting a
975      parameter variable.  In this case we just pull out the component we
976      want.  */
977   if (expr->ref)
978     comp = expr->ref->u.c.sym->components;
979   else
980     comp = expr->ts.u.derived->components;
981
982   /* See if the user is trying to invoke a structure constructor for one of
983      the iso_c_binding derived types.  */
984   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
985       && expr->ts.u.derived->ts.is_iso_c && cons
986       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
987     {
988       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
989                  expr->ts.u.derived->name, &(expr->where));
990       return FAILURE;
991     }
992
993   /* Return if structure constructor is c_null_(fun)prt.  */
994   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
995       && expr->ts.u.derived->ts.is_iso_c && cons
996       && cons->expr && cons->expr->expr_type == EXPR_NULL)
997     return SUCCESS;
998
999   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
1000     {
1001       int rank;
1002
1003       if (!cons->expr)
1004         continue;
1005
1006       if (gfc_resolve_expr (cons->expr) == FAILURE)
1007         {
1008           t = FAILURE;
1009           continue;
1010         }
1011
1012       rank = comp->as ? comp->as->rank : 0;
1013       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
1014           && (comp->attr.allocatable || cons->expr->rank))
1015         {
1016           gfc_error ("The rank of the element in the derived type "
1017                      "constructor at %L does not match that of the "
1018                      "component (%d/%d)", &cons->expr->where,
1019                      cons->expr->rank, rank);
1020           t = FAILURE;
1021         }
1022
1023       /* If we don't have the right type, try to convert it.  */
1024
1025       if (!comp->attr.proc_pointer &&
1026           !gfc_compare_types (&cons->expr->ts, &comp->ts))
1027         {
1028           t = FAILURE;
1029           if (strcmp (comp->name, "_extends") == 0)
1030             {
1031               /* Can afford to be brutal with the _extends initializer.
1032                  The derived type can get lost because it is PRIVATE
1033                  but it is not usage constrained by the standard.  */
1034               cons->expr->ts = comp->ts;
1035               t = SUCCESS;
1036             }
1037           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1038             gfc_error ("The element in the derived type constructor at %L, "
1039                        "for pointer component '%s', is %s but should be %s",
1040                        &cons->expr->where, comp->name,
1041                        gfc_basic_typename (cons->expr->ts.type),
1042                        gfc_basic_typename (comp->ts.type));
1043           else
1044             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1045         }
1046
1047       /* For strings, the length of the constructor should be the same as
1048          the one of the structure, ensure this if the lengths are known at
1049          compile time and when we are dealing with PARAMETER or structure
1050          constructors.  */
1051       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1052           && comp->ts.u.cl->length
1053           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1054           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1055           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1056           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1057                       comp->ts.u.cl->length->value.integer) != 0)
1058         {
1059           if (cons->expr->expr_type == EXPR_VARIABLE
1060               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1061             {
1062               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1063                  to make use of the gfc_resolve_character_array_constructor
1064                  machinery.  The expression is later simplified away to
1065                  an array of string literals.  */
1066               gfc_expr *para = cons->expr;
1067               cons->expr = gfc_get_expr ();
1068               cons->expr->ts = para->ts;
1069               cons->expr->where = para->where;
1070               cons->expr->expr_type = EXPR_ARRAY;
1071               cons->expr->rank = para->rank;
1072               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1073               gfc_constructor_append_expr (&cons->expr->value.constructor,
1074                                            para, &cons->expr->where);
1075             }
1076           if (cons->expr->expr_type == EXPR_ARRAY)
1077             {
1078               gfc_constructor *p;
1079               p = gfc_constructor_first (cons->expr->value.constructor);
1080               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1081                 {
1082                   gfc_charlen *cl, *cl2;
1083
1084                   cl2 = NULL;
1085                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1086                     {
1087                       if (cl == cons->expr->ts.u.cl)
1088                         break;
1089                       cl2 = cl;
1090                     }
1091
1092                   gcc_assert (cl);
1093
1094                   if (cl2)
1095                     cl2->next = cl->next;
1096
1097                   gfc_free_expr (cl->length);
1098                   free (cl);
1099                 }
1100
1101               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1102               cons->expr->ts.u.cl->length_from_typespec = true;
1103               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1104               gfc_resolve_character_array_constructor (cons->expr);
1105             }
1106         }
1107
1108       if (cons->expr->expr_type == EXPR_NULL
1109           && !(comp->attr.pointer || comp->attr.allocatable
1110                || comp->attr.proc_pointer
1111                || (comp->ts.type == BT_CLASS
1112                    && (CLASS_DATA (comp)->attr.class_pointer
1113                        || CLASS_DATA (comp)->attr.allocatable))))
1114         {
1115           t = FAILURE;
1116           gfc_error ("The NULL in the derived type constructor at %L is "
1117                      "being applied to component '%s', which is neither "
1118                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1119                      comp->name);
1120         }
1121
1122       if (!comp->attr.pointer || comp->attr.proc_pointer
1123           || cons->expr->expr_type == EXPR_NULL)
1124         continue;
1125
1126       a = gfc_expr_attr (cons->expr);
1127
1128       if (!a.pointer && !a.target)
1129         {
1130           t = FAILURE;
1131           gfc_error ("The element in the derived type constructor at %L, "
1132                      "for pointer component '%s' should be a POINTER or "
1133                      "a TARGET", &cons->expr->where, comp->name);
1134         }
1135
1136       if (init)
1137         {
1138           /* F08:C461. Additional checks for pointer initialization.  */
1139           if (a.allocatable)
1140             {
1141               t = FAILURE;
1142               gfc_error ("Pointer initialization target at %L "
1143                          "must not be ALLOCATABLE ", &cons->expr->where);
1144             }
1145           if (!a.save)
1146             {
1147               t = FAILURE;
1148               gfc_error ("Pointer initialization target at %L "
1149                          "must have the SAVE attribute", &cons->expr->where);
1150             }
1151         }
1152
1153       /* F2003, C1272 (3).  */
1154       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1155           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1156               || gfc_is_coindexed (cons->expr)))
1157         {
1158           t = FAILURE;
1159           gfc_error ("Invalid expression in the derived type constructor for "
1160                      "pointer component '%s' at %L in PURE procedure",
1161                      comp->name, &cons->expr->where);
1162         }
1163
1164       if (gfc_implicit_pure (NULL)
1165             && cons->expr->expr_type == EXPR_VARIABLE
1166             && (gfc_impure_variable (cons->expr->symtree->n.sym)
1167                 || gfc_is_coindexed (cons->expr)))
1168         gfc_current_ns->proc_name->attr.implicit_pure = 0;
1169
1170     }
1171
1172   return t;
1173 }
1174
1175
1176 /****************** Expression name resolution ******************/
1177
1178 /* Returns 0 if a symbol was not declared with a type or
1179    attribute declaration statement, nonzero otherwise.  */
1180
1181 static int
1182 was_declared (gfc_symbol *sym)
1183 {
1184   symbol_attribute a;
1185
1186   a = sym->attr;
1187
1188   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1189     return 1;
1190
1191   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1192       || a.optional || a.pointer || a.save || a.target || a.volatile_
1193       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1194       || a.asynchronous || a.codimension)
1195     return 1;
1196
1197   return 0;
1198 }
1199
1200
1201 /* Determine if a symbol is generic or not.  */
1202
1203 static int
1204 generic_sym (gfc_symbol *sym)
1205 {
1206   gfc_symbol *s;
1207
1208   if (sym->attr.generic ||
1209       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1210     return 1;
1211
1212   if (was_declared (sym) || sym->ns->parent == NULL)
1213     return 0;
1214
1215   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1216   
1217   if (s != NULL)
1218     {
1219       if (s == sym)
1220         return 0;
1221       else
1222         return generic_sym (s);
1223     }
1224
1225   return 0;
1226 }
1227
1228
1229 /* Determine if a symbol is specific or not.  */
1230
1231 static int
1232 specific_sym (gfc_symbol *sym)
1233 {
1234   gfc_symbol *s;
1235
1236   if (sym->attr.if_source == IFSRC_IFBODY
1237       || sym->attr.proc == PROC_MODULE
1238       || sym->attr.proc == PROC_INTERNAL
1239       || sym->attr.proc == PROC_ST_FUNCTION
1240       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1241       || sym->attr.external)
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   return (s == NULL) ? 0 : specific_sym (s);
1250 }
1251
1252
1253 /* Figure out if the procedure is specific, generic or unknown.  */
1254
1255 typedef enum
1256 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1257 proc_type;
1258
1259 static proc_type
1260 procedure_kind (gfc_symbol *sym)
1261 {
1262   if (generic_sym (sym))
1263     return PTYPE_GENERIC;
1264
1265   if (specific_sym (sym))
1266     return PTYPE_SPECIFIC;
1267
1268   return PTYPE_UNKNOWN;
1269 }
1270
1271 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1272    is nonzero when matching actual arguments.  */
1273
1274 static int need_full_assumed_size = 0;
1275
1276 static bool
1277 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1278 {
1279   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1280       return false;
1281
1282   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1283      What should it be?  */
1284   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1285           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1286                && (e->ref->u.ar.type == AR_FULL))
1287     {
1288       gfc_error ("The upper bound in the last dimension must "
1289                  "appear in the reference to the assumed size "
1290                  "array '%s' at %L", sym->name, &e->where);
1291       return true;
1292     }
1293   return false;
1294 }
1295
1296
1297 /* Look for bad assumed size array references in argument expressions
1298   of elemental and array valued intrinsic procedures.  Since this is
1299   called from procedure resolution functions, it only recurses at
1300   operators.  */
1301
1302 static bool
1303 resolve_assumed_size_actual (gfc_expr *e)
1304 {
1305   if (e == NULL)
1306    return false;
1307
1308   switch (e->expr_type)
1309     {
1310     case EXPR_VARIABLE:
1311       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1312         return true;
1313       break;
1314
1315     case EXPR_OP:
1316       if (resolve_assumed_size_actual (e->value.op.op1)
1317           || resolve_assumed_size_actual (e->value.op.op2))
1318         return true;
1319       break;
1320
1321     default:
1322       break;
1323     }
1324   return false;
1325 }
1326
1327
1328 /* Check a generic procedure, passed as an actual argument, to see if
1329    there is a matching specific name.  If none, it is an error, and if
1330    more than one, the reference is ambiguous.  */
1331 static int
1332 count_specific_procs (gfc_expr *e)
1333 {
1334   int n;
1335   gfc_interface *p;
1336   gfc_symbol *sym;
1337         
1338   n = 0;
1339   sym = e->symtree->n.sym;
1340
1341   for (p = sym->generic; p; p = p->next)
1342     if (strcmp (sym->name, p->sym->name) == 0)
1343       {
1344         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1345                                        sym->name);
1346         n++;
1347       }
1348
1349   if (n > 1)
1350     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1351                &e->where);
1352
1353   if (n == 0)
1354     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1355                "argument at %L", sym->name, &e->where);
1356
1357   return n;
1358 }
1359
1360
1361 /* See if a call to sym could possibly be a not allowed RECURSION because of
1362    a missing RECURIVE declaration.  This means that either sym is the current
1363    context itself, or sym is the parent of a contained procedure calling its
1364    non-RECURSIVE containing procedure.
1365    This also works if sym is an ENTRY.  */
1366
1367 static bool
1368 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1369 {
1370   gfc_symbol* proc_sym;
1371   gfc_symbol* context_proc;
1372   gfc_namespace* real_context;
1373
1374   if (sym->attr.flavor == FL_PROGRAM)
1375     return false;
1376
1377   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1378
1379   /* If we've got an ENTRY, find real procedure.  */
1380   if (sym->attr.entry && sym->ns->entries)
1381     proc_sym = sym->ns->entries->sym;
1382   else
1383     proc_sym = sym;
1384
1385   /* If sym is RECURSIVE, all is well of course.  */
1386   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1387     return false;
1388
1389   /* Find the context procedure's "real" symbol if it has entries.
1390      We look for a procedure symbol, so recurse on the parents if we don't
1391      find one (like in case of a BLOCK construct).  */
1392   for (real_context = context; ; real_context = real_context->parent)
1393     {
1394       /* We should find something, eventually!  */
1395       gcc_assert (real_context);
1396
1397       context_proc = (real_context->entries ? real_context->entries->sym
1398                                             : real_context->proc_name);
1399
1400       /* In some special cases, there may not be a proc_name, like for this
1401          invalid code:
1402          real(bad_kind()) function foo () ...
1403          when checking the call to bad_kind ().
1404          In these cases, we simply return here and assume that the
1405          call is ok.  */
1406       if (!context_proc)
1407         return false;
1408
1409       if (context_proc->attr.flavor != FL_LABEL)
1410         break;
1411     }
1412
1413   /* A call from sym's body to itself is recursion, of course.  */
1414   if (context_proc == proc_sym)
1415     return true;
1416
1417   /* The same is true if context is a contained procedure and sym the
1418      containing one.  */
1419   if (context_proc->attr.contained)
1420     {
1421       gfc_symbol* parent_proc;
1422
1423       gcc_assert (context->parent);
1424       parent_proc = (context->parent->entries ? context->parent->entries->sym
1425                                               : context->parent->proc_name);
1426
1427       if (parent_proc == proc_sym)
1428         return true;
1429     }
1430
1431   return false;
1432 }
1433
1434
1435 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1436    its typespec and formal argument list.  */
1437
1438 static gfc_try
1439 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1440 {
1441   gfc_intrinsic_sym* isym = NULL;
1442   const char* symstd;
1443
1444   if (sym->formal)
1445     return SUCCESS;
1446
1447   /* Already resolved.  */
1448   if (sym->from_intmod && sym->ts.type != BT_UNKNOWN)
1449     return SUCCESS;
1450
1451   /* We already know this one is an intrinsic, so we don't call
1452      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1453      gfc_find_subroutine directly to check whether it is a function or
1454      subroutine.  */
1455
1456   if (sym->intmod_sym_id)
1457     isym = gfc_intrinsic_function_by_id ((gfc_isym_id) sym->intmod_sym_id);
1458   else
1459     isym = gfc_find_function (sym->name);
1460
1461   if (isym)
1462     {
1463       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1464           && !sym->attr.implicit_type)
1465         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1466                       " ignored", sym->name, &sym->declared_at);
1467
1468       if (!sym->attr.function &&
1469           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1470         return FAILURE;
1471
1472       sym->ts = isym->ts;
1473     }
1474   else if ((isym = gfc_find_subroutine (sym->name)))
1475     {
1476       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1477         {
1478           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1479                       " specifier", sym->name, &sym->declared_at);
1480           return FAILURE;
1481         }
1482
1483       if (!sym->attr.subroutine &&
1484           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1485         return FAILURE;
1486     }
1487   else
1488     {
1489       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1490                  &sym->declared_at);
1491       return FAILURE;
1492     }
1493
1494   gfc_copy_formal_args_intr (sym, isym);
1495
1496   /* Check it is actually available in the standard settings.  */
1497   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1498       == FAILURE)
1499     {
1500       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1501                  " available in the current standard settings but %s.  Use"
1502                  " an appropriate -std=* option or enable -fall-intrinsics"
1503                  " in order to use it.",
1504                  sym->name, &sym->declared_at, symstd);
1505       return FAILURE;
1506     }
1507
1508   return SUCCESS;
1509 }
1510
1511
1512 /* Resolve a procedure expression, like passing it to a called procedure or as
1513    RHS for a procedure pointer assignment.  */
1514
1515 static gfc_try
1516 resolve_procedure_expression (gfc_expr* expr)
1517 {
1518   gfc_symbol* sym;
1519
1520   if (expr->expr_type != EXPR_VARIABLE)
1521     return SUCCESS;
1522   gcc_assert (expr->symtree);
1523
1524   sym = expr->symtree->n.sym;
1525
1526   if (sym->attr.intrinsic)
1527     resolve_intrinsic (sym, &expr->where);
1528
1529   if (sym->attr.flavor != FL_PROCEDURE
1530       || (sym->attr.function && sym->result == sym))
1531     return SUCCESS;
1532
1533   /* A non-RECURSIVE procedure that is used as procedure expression within its
1534      own body is in danger of being called recursively.  */
1535   if (is_illegal_recursion (sym, gfc_current_ns))
1536     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1537                  " itself recursively.  Declare it RECURSIVE or use"
1538                  " -frecursive", sym->name, &expr->where);
1539   
1540   return SUCCESS;
1541 }
1542
1543
1544 /* Resolve an actual argument list.  Most of the time, this is just
1545    resolving the expressions in the list.
1546    The exception is that we sometimes have to decide whether arguments
1547    that look like procedure arguments are really simple variable
1548    references.  */
1549
1550 static gfc_try
1551 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1552                         bool no_formal_args)
1553 {
1554   gfc_symbol *sym;
1555   gfc_symtree *parent_st;
1556   gfc_expr *e;
1557   int save_need_full_assumed_size;
1558
1559   for (; arg; arg = arg->next)
1560     {
1561       e = arg->expr;
1562       if (e == NULL)
1563         {
1564           /* Check the label is a valid branching target.  */
1565           if (arg->label)
1566             {
1567               if (arg->label->defined == ST_LABEL_UNKNOWN)
1568                 {
1569                   gfc_error ("Label %d referenced at %L is never defined",
1570                              arg->label->value, &arg->label->where);
1571                   return FAILURE;
1572                 }
1573             }
1574           continue;
1575         }
1576
1577       if (e->expr_type == EXPR_VARIABLE
1578             && e->symtree->n.sym->attr.generic
1579             && no_formal_args
1580             && count_specific_procs (e) != 1)
1581         return FAILURE;
1582
1583       if (e->ts.type != BT_PROCEDURE)
1584         {
1585           save_need_full_assumed_size = need_full_assumed_size;
1586           if (e->expr_type != EXPR_VARIABLE)
1587             need_full_assumed_size = 0;
1588           if (gfc_resolve_expr (e) != SUCCESS)
1589             return FAILURE;
1590           need_full_assumed_size = save_need_full_assumed_size;
1591           goto argument_list;
1592         }
1593
1594       /* See if the expression node should really be a variable reference.  */
1595
1596       sym = e->symtree->n.sym;
1597
1598       if (sym->attr.flavor == FL_PROCEDURE
1599           || sym->attr.intrinsic
1600           || sym->attr.external)
1601         {
1602           int actual_ok;
1603
1604           /* If a procedure is not already determined to be something else
1605              check if it is intrinsic.  */
1606           if (!sym->attr.intrinsic
1607               && !(sym->attr.external || sym->attr.use_assoc
1608                    || sym->attr.if_source == IFSRC_IFBODY)
1609               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1610             sym->attr.intrinsic = 1;
1611
1612           if (sym->attr.proc == PROC_ST_FUNCTION)
1613             {
1614               gfc_error ("Statement function '%s' at %L is not allowed as an "
1615                          "actual argument", sym->name, &e->where);
1616             }
1617
1618           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1619                                                sym->attr.subroutine);
1620           if (sym->attr.intrinsic && actual_ok == 0)
1621             {
1622               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1623                          "actual argument", sym->name, &e->where);
1624             }
1625
1626           if (sym->attr.contained && !sym->attr.use_assoc
1627               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1628             {
1629               if (gfc_notify_std (GFC_STD_F2008,
1630                                   "Fortran 2008: Internal procedure '%s' is"
1631                                   " used as actual argument at %L",
1632                                   sym->name, &e->where) == FAILURE)
1633                 return FAILURE;
1634             }
1635
1636           if (sym->attr.elemental && !sym->attr.intrinsic)
1637             {
1638               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1639                          "allowed as an actual argument at %L", sym->name,
1640                          &e->where);
1641             }
1642
1643           /* Check if a generic interface has a specific procedure
1644             with the same name before emitting an error.  */
1645           if (sym->attr.generic && count_specific_procs (e) != 1)
1646             return FAILURE;
1647           
1648           /* Just in case a specific was found for the expression.  */
1649           sym = e->symtree->n.sym;
1650
1651           /* If the symbol is the function that names the current (or
1652              parent) scope, then we really have a variable reference.  */
1653
1654           if (gfc_is_function_return_value (sym, sym->ns))
1655             goto got_variable;
1656
1657           /* If all else fails, see if we have a specific intrinsic.  */
1658           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1659             {
1660               gfc_intrinsic_sym *isym;
1661
1662               isym = gfc_find_function (sym->name);
1663               if (isym == NULL || !isym->specific)
1664                 {
1665                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1666                              "for the reference '%s' at %L", sym->name,
1667                              &e->where);
1668                   return FAILURE;
1669                 }
1670               sym->ts = isym->ts;
1671               sym->attr.intrinsic = 1;
1672               sym->attr.function = 1;
1673             }
1674
1675           if (gfc_resolve_expr (e) == FAILURE)
1676             return FAILURE;
1677           goto argument_list;
1678         }
1679
1680       /* See if the name is a module procedure in a parent unit.  */
1681
1682       if (was_declared (sym) || sym->ns->parent == NULL)
1683         goto got_variable;
1684
1685       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1686         {
1687           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1688           return FAILURE;
1689         }
1690
1691       if (parent_st == NULL)
1692         goto got_variable;
1693
1694       sym = parent_st->n.sym;
1695       e->symtree = parent_st;           /* Point to the right thing.  */
1696
1697       if (sym->attr.flavor == FL_PROCEDURE
1698           || sym->attr.intrinsic
1699           || sym->attr.external)
1700         {
1701           if (gfc_resolve_expr (e) == FAILURE)
1702             return FAILURE;
1703           goto argument_list;
1704         }
1705
1706     got_variable:
1707       e->expr_type = EXPR_VARIABLE;
1708       e->ts = sym->ts;
1709       if (sym->as != NULL)
1710         {
1711           e->rank = sym->as->rank;
1712           e->ref = gfc_get_ref ();
1713           e->ref->type = REF_ARRAY;
1714           e->ref->u.ar.type = AR_FULL;
1715           e->ref->u.ar.as = sym->as;
1716         }
1717
1718       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1719          primary.c (match_actual_arg). If above code determines that it
1720          is a  variable instead, it needs to be resolved as it was not
1721          done at the beginning of this function.  */
1722       save_need_full_assumed_size = need_full_assumed_size;
1723       if (e->expr_type != EXPR_VARIABLE)
1724         need_full_assumed_size = 0;
1725       if (gfc_resolve_expr (e) != SUCCESS)
1726         return FAILURE;
1727       need_full_assumed_size = save_need_full_assumed_size;
1728
1729     argument_list:
1730       /* Check argument list functions %VAL, %LOC and %REF.  There is
1731          nothing to do for %REF.  */
1732       if (arg->name && arg->name[0] == '%')
1733         {
1734           if (strncmp ("%VAL", arg->name, 4) == 0)
1735             {
1736               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1737                 {
1738                   gfc_error ("By-value argument at %L is not of numeric "
1739                              "type", &e->where);
1740                   return FAILURE;
1741                 }
1742
1743               if (e->rank)
1744                 {
1745                   gfc_error ("By-value argument at %L cannot be an array or "
1746                              "an array section", &e->where);
1747                 return FAILURE;
1748                 }
1749
1750               /* Intrinsics are still PROC_UNKNOWN here.  However,
1751                  since same file external procedures are not resolvable
1752                  in gfortran, it is a good deal easier to leave them to
1753                  intrinsic.c.  */
1754               if (ptype != PROC_UNKNOWN
1755                   && ptype != PROC_DUMMY
1756                   && ptype != PROC_EXTERNAL
1757                   && ptype != PROC_MODULE)
1758                 {
1759                   gfc_error ("By-value argument at %L is not allowed "
1760                              "in this context", &e->where);
1761                   return FAILURE;
1762                 }
1763             }
1764
1765           /* Statement functions have already been excluded above.  */
1766           else if (strncmp ("%LOC", arg->name, 4) == 0
1767                    && e->ts.type == BT_PROCEDURE)
1768             {
1769               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1770                 {
1771                   gfc_error ("Passing internal procedure at %L by location "
1772                              "not allowed", &e->where);
1773                   return FAILURE;
1774                 }
1775             }
1776         }
1777
1778       /* Fortran 2008, C1237.  */
1779       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1780           && gfc_has_ultimate_pointer (e))
1781         {
1782           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1783                      "component", &e->where);
1784           return FAILURE;
1785         }
1786     }
1787
1788   return SUCCESS;
1789 }
1790
1791
1792 /* Do the checks of the actual argument list that are specific to elemental
1793    procedures.  If called with c == NULL, we have a function, otherwise if
1794    expr == NULL, we have a subroutine.  */
1795
1796 static gfc_try
1797 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1798 {
1799   gfc_actual_arglist *arg0;
1800   gfc_actual_arglist *arg;
1801   gfc_symbol *esym = NULL;
1802   gfc_intrinsic_sym *isym = NULL;
1803   gfc_expr *e = NULL;
1804   gfc_intrinsic_arg *iformal = NULL;
1805   gfc_formal_arglist *eformal = NULL;
1806   bool formal_optional = false;
1807   bool set_by_optional = false;
1808   int i;
1809   int rank = 0;
1810
1811   /* Is this an elemental procedure?  */
1812   if (expr && expr->value.function.actual != NULL)
1813     {
1814       if (expr->value.function.esym != NULL
1815           && expr->value.function.esym->attr.elemental)
1816         {
1817           arg0 = expr->value.function.actual;
1818           esym = expr->value.function.esym;
1819         }
1820       else if (expr->value.function.isym != NULL
1821                && expr->value.function.isym->elemental)
1822         {
1823           arg0 = expr->value.function.actual;
1824           isym = expr->value.function.isym;
1825         }
1826       else
1827         return SUCCESS;
1828     }
1829   else if (c && c->ext.actual != NULL)
1830     {
1831       arg0 = c->ext.actual;
1832       
1833       if (c->resolved_sym)
1834         esym = c->resolved_sym;
1835       else
1836         esym = c->symtree->n.sym;
1837       gcc_assert (esym);
1838
1839       if (!esym->attr.elemental)
1840         return SUCCESS;
1841     }
1842   else
1843     return SUCCESS;
1844
1845   /* The rank of an elemental is the rank of its array argument(s).  */
1846   for (arg = arg0; arg; arg = arg->next)
1847     {
1848       if (arg->expr != NULL && arg->expr->rank > 0)
1849         {
1850           rank = arg->expr->rank;
1851           if (arg->expr->expr_type == EXPR_VARIABLE
1852               && arg->expr->symtree->n.sym->attr.optional)
1853             set_by_optional = true;
1854
1855           /* Function specific; set the result rank and shape.  */
1856           if (expr)
1857             {
1858               expr->rank = rank;
1859               if (!expr->shape && arg->expr->shape)
1860                 {
1861                   expr->shape = gfc_get_shape (rank);
1862                   for (i = 0; i < rank; i++)
1863                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1864                 }
1865             }
1866           break;
1867         }
1868     }
1869
1870   /* If it is an array, it shall not be supplied as an actual argument
1871      to an elemental procedure unless an array of the same rank is supplied
1872      as an actual argument corresponding to a nonoptional dummy argument of
1873      that elemental procedure(12.4.1.5).  */
1874   formal_optional = false;
1875   if (isym)
1876     iformal = isym->formal;
1877   else
1878     eformal = esym->formal;
1879
1880   for (arg = arg0; arg; arg = arg->next)
1881     {
1882       if (eformal)
1883         {
1884           if (eformal->sym && eformal->sym->attr.optional)
1885             formal_optional = true;
1886           eformal = eformal->next;
1887         }
1888       else if (isym && iformal)
1889         {
1890           if (iformal->optional)
1891             formal_optional = true;
1892           iformal = iformal->next;
1893         }
1894       else if (isym)
1895         formal_optional = true;
1896
1897       if (pedantic && arg->expr != NULL
1898           && arg->expr->expr_type == EXPR_VARIABLE
1899           && arg->expr->symtree->n.sym->attr.optional
1900           && formal_optional
1901           && arg->expr->rank
1902           && (set_by_optional || arg->expr->rank != rank)
1903           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1904         {
1905           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1906                        "MISSING, it cannot be the actual argument of an "
1907                        "ELEMENTAL procedure unless there is a non-optional "
1908                        "argument with the same rank (12.4.1.5)",
1909                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1910           return FAILURE;
1911         }
1912     }
1913
1914   for (arg = arg0; arg; arg = arg->next)
1915     {
1916       if (arg->expr == NULL || arg->expr->rank == 0)
1917         continue;
1918
1919       /* Being elemental, the last upper bound of an assumed size array
1920          argument must be present.  */
1921       if (resolve_assumed_size_actual (arg->expr))
1922         return FAILURE;
1923
1924       /* Elemental procedure's array actual arguments must conform.  */
1925       if (e != NULL)
1926         {
1927           if (gfc_check_conformance (arg->expr, e,
1928                                      "elemental procedure") == FAILURE)
1929             return FAILURE;
1930         }
1931       else
1932         e = arg->expr;
1933     }
1934
1935   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1936      is an array, the intent inout/out variable needs to be also an array.  */
1937   if (rank > 0 && esym && expr == NULL)
1938     for (eformal = esym->formal, arg = arg0; arg && eformal;
1939          arg = arg->next, eformal = eformal->next)
1940       if ((eformal->sym->attr.intent == INTENT_OUT
1941            || eformal->sym->attr.intent == INTENT_INOUT)
1942           && arg->expr && arg->expr->rank == 0)
1943         {
1944           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1945                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1946                      "actual argument is an array", &arg->expr->where,
1947                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1948                      : "INOUT", eformal->sym->name, esym->name);
1949           return FAILURE;
1950         }
1951   return SUCCESS;
1952 }
1953
1954
1955 /* This function does the checking of references to global procedures
1956    as defined in sections 18.1 and 14.1, respectively, of the Fortran
1957    77 and 95 standards.  It checks for a gsymbol for the name, making
1958    one if it does not already exist.  If it already exists, then the
1959    reference being resolved must correspond to the type of gsymbol.
1960    Otherwise, the new symbol is equipped with the attributes of the
1961    reference.  The corresponding code that is called in creating
1962    global entities is parse.c.
1963
1964    In addition, for all but -std=legacy, the gsymbols are used to
1965    check the interfaces of external procedures from the same file.
1966    The namespace of the gsymbol is resolved and then, once this is
1967    done the interface is checked.  */
1968
1969
1970 static bool
1971 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
1972 {
1973   if (!gsym_ns->proc_name->attr.recursive)
1974     return true;
1975
1976   if (sym->ns == gsym_ns)
1977     return false;
1978
1979   if (sym->ns->parent && sym->ns->parent == gsym_ns)
1980     return false;
1981
1982   return true;
1983 }
1984
1985 static bool
1986 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
1987 {
1988   if (gsym_ns->entries)
1989     {
1990       gfc_entry_list *entry = gsym_ns->entries;
1991
1992       for (; entry; entry = entry->next)
1993         {
1994           if (strcmp (sym->name, entry->sym->name) == 0)
1995             {
1996               if (strcmp (gsym_ns->proc_name->name,
1997                           sym->ns->proc_name->name) == 0)
1998                 return false;
1999
2000               if (sym->ns->parent
2001                   && strcmp (gsym_ns->proc_name->name,
2002                              sym->ns->parent->proc_name->name) == 0)
2003                 return false;
2004             }
2005         }
2006     }
2007   return true;
2008 }
2009
2010 static void
2011 resolve_global_procedure (gfc_symbol *sym, locus *where,
2012                           gfc_actual_arglist **actual, int sub)
2013 {
2014   gfc_gsymbol * gsym;
2015   gfc_namespace *ns;
2016   enum gfc_symbol_type type;
2017
2018   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
2019
2020   gsym = gfc_get_gsymbol (sym->name);
2021
2022   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2023     gfc_global_used (gsym, where);
2024
2025   if (gfc_option.flag_whole_file
2026         && (sym->attr.if_source == IFSRC_UNKNOWN
2027             || sym->attr.if_source == IFSRC_IFBODY)
2028         && gsym->type != GSYM_UNKNOWN
2029         && gsym->ns
2030         && gsym->ns->resolved != -1
2031         && gsym->ns->proc_name
2032         && not_in_recursive (sym, gsym->ns)
2033         && not_entry_self_reference (sym, gsym->ns))
2034     {
2035       gfc_symbol *def_sym;
2036
2037       /* Resolve the gsymbol namespace if needed.  */
2038       if (!gsym->ns->resolved)
2039         {
2040           gfc_dt_list *old_dt_list;
2041           struct gfc_omp_saved_state old_omp_state;
2042
2043           /* Stash away derived types so that the backend_decls do not
2044              get mixed up.  */
2045           old_dt_list = gfc_derived_types;
2046           gfc_derived_types = NULL;
2047           /* And stash away openmp state.  */
2048           gfc_omp_save_and_clear_state (&old_omp_state);
2049
2050           gfc_resolve (gsym->ns);
2051
2052           /* Store the new derived types with the global namespace.  */
2053           if (gfc_derived_types)
2054             gsym->ns->derived_types = gfc_derived_types;
2055
2056           /* Restore the derived types of this namespace.  */
2057           gfc_derived_types = old_dt_list;
2058           /* And openmp state.  */
2059           gfc_omp_restore_state (&old_omp_state);
2060         }
2061
2062       /* Make sure that translation for the gsymbol occurs before
2063          the procedure currently being resolved.  */
2064       ns = gfc_global_ns_list;
2065       for (; ns && ns != gsym->ns; ns = ns->sibling)
2066         {
2067           if (ns->sibling == gsym->ns)
2068             {
2069               ns->sibling = gsym->ns->sibling;
2070               gsym->ns->sibling = gfc_global_ns_list;
2071               gfc_global_ns_list = gsym->ns;
2072               break;
2073             }
2074         }
2075
2076       def_sym = gsym->ns->proc_name;
2077       if (def_sym->attr.entry_master)
2078         {
2079           gfc_entry_list *entry;
2080           for (entry = gsym->ns->entries; entry; entry = entry->next)
2081             if (strcmp (entry->sym->name, sym->name) == 0)
2082               {
2083                 def_sym = entry->sym;
2084                 break;
2085               }
2086         }
2087
2088       /* Differences in constant character lengths.  */
2089       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2090         {
2091           long int l1 = 0, l2 = 0;
2092           gfc_charlen *cl1 = sym->ts.u.cl;
2093           gfc_charlen *cl2 = def_sym->ts.u.cl;
2094
2095           if (cl1 != NULL
2096               && cl1->length != NULL
2097               && cl1->length->expr_type == EXPR_CONSTANT)
2098             l1 = mpz_get_si (cl1->length->value.integer);
2099
2100           if (cl2 != NULL
2101               && cl2->length != NULL
2102               && cl2->length->expr_type == EXPR_CONSTANT)
2103             l2 = mpz_get_si (cl2->length->value.integer);
2104
2105           if (l1 && l2 && l1 != l2)
2106             gfc_error ("Character length mismatch in return type of "
2107                        "function '%s' at %L (%ld/%ld)", sym->name,
2108                        &sym->declared_at, l1, l2);
2109         }
2110
2111      /* Type mismatch of function return type and expected type.  */
2112      if (sym->attr.function
2113          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2114         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2115                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2116                    gfc_typename (&def_sym->ts));
2117
2118       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2119         {
2120           gfc_formal_arglist *arg = def_sym->formal;
2121           for ( ; arg; arg = arg->next)
2122             if (!arg->sym)
2123               continue;
2124             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2125             else if (arg->sym->attr.allocatable
2126                      || arg->sym->attr.asynchronous
2127                      || arg->sym->attr.optional
2128                      || arg->sym->attr.pointer
2129                      || arg->sym->attr.target
2130                      || arg->sym->attr.value
2131                      || arg->sym->attr.volatile_)
2132               {
2133                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2134                            "has an attribute that requires an explicit "
2135                            "interface for this procedure", arg->sym->name,
2136                            sym->name, &sym->declared_at);
2137                 break;
2138               }
2139             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2140             else if (arg->sym && arg->sym->as
2141                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2142               {
2143                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2144                            "argument '%s' must have an explicit interface",
2145                            sym->name, &sym->declared_at, arg->sym->name);
2146                 break;
2147               }
2148             /* F2008, 12.4.2.2 (2c)  */
2149             else if (arg->sym->attr.codimension)
2150               {
2151                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2152                            "'%s' must have an explicit interface",
2153                            sym->name, &sym->declared_at, arg->sym->name);
2154                 break;
2155               }
2156             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2157             else if (false) /* TODO: is a parametrized derived type  */
2158               {
2159                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2160                            "type argument '%s' must have an explicit "
2161                            "interface", sym->name, &sym->declared_at,
2162                            arg->sym->name);
2163                 break;
2164               }
2165             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2166             else if (arg->sym->ts.type == BT_CLASS)
2167               {
2168                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2169                            "argument '%s' must have an explicit interface",
2170                            sym->name, &sym->declared_at, arg->sym->name);
2171                 break;
2172               }
2173         }
2174
2175       if (def_sym->attr.function)
2176         {
2177           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2178           if (def_sym->as && def_sym->as->rank
2179               && (!sym->as || sym->as->rank != def_sym->as->rank))
2180             gfc_error ("The reference to function '%s' at %L either needs an "
2181                        "explicit INTERFACE or the rank is incorrect", sym->name,
2182                        where);
2183
2184           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2185           if ((def_sym->result->attr.pointer
2186                || def_sym->result->attr.allocatable)
2187                && (sym->attr.if_source != IFSRC_IFBODY
2188                    || def_sym->result->attr.pointer
2189                         != sym->result->attr.pointer
2190                    || def_sym->result->attr.allocatable
2191                         != sym->result->attr.allocatable))
2192             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2193                        "result must have an explicit interface", sym->name,
2194                        where);
2195
2196           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2197           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2198               && def_sym->ts.type == BT_CHARACTER && def_sym->ts.u.cl->length != NULL)
2199             {
2200               gfc_charlen *cl = sym->ts.u.cl;
2201
2202               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2203                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2204                 {
2205                   gfc_error ("Nonconstant character-length function '%s' at %L "
2206                              "must have an explicit interface", sym->name,
2207                              &sym->declared_at);
2208                 }
2209             }
2210         }
2211
2212       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2213       if (def_sym->attr.elemental && !sym->attr.elemental)
2214         {
2215           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2216                      "interface", sym->name, &sym->declared_at);
2217         }
2218
2219       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2220       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2221         {
2222           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2223                      "an explicit interface", sym->name, &sym->declared_at);
2224         }
2225
2226       if (gfc_option.flag_whole_file == 1
2227           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2228               && !(gfc_option.warn_std & GFC_STD_GNU)))
2229         gfc_errors_to_warnings (1);
2230
2231       if (sym->attr.if_source != IFSRC_IFBODY)  
2232         gfc_procedure_use (def_sym, actual, where);
2233
2234       gfc_errors_to_warnings (0);
2235     }
2236
2237   if (gsym->type == GSYM_UNKNOWN)
2238     {
2239       gsym->type = type;
2240       gsym->where = *where;
2241     }
2242
2243   gsym->used = 1;
2244 }
2245
2246
2247 /************* Function resolution *************/
2248
2249 /* Resolve a function call known to be generic.
2250    Section 14.1.2.4.1.  */
2251
2252 static match
2253 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2254 {
2255   gfc_symbol *s;
2256
2257   if (sym->attr.generic)
2258     {
2259       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2260       if (s != NULL)
2261         {
2262           expr->value.function.name = s->name;
2263           expr->value.function.esym = s;
2264
2265           if (s->ts.type != BT_UNKNOWN)
2266             expr->ts = s->ts;
2267           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2268             expr->ts = s->result->ts;
2269
2270           if (s->as != NULL)
2271             expr->rank = s->as->rank;
2272           else if (s->result != NULL && s->result->as != NULL)
2273             expr->rank = s->result->as->rank;
2274
2275           gfc_set_sym_referenced (expr->value.function.esym);
2276
2277           return MATCH_YES;
2278         }
2279
2280       /* TODO: Need to search for elemental references in generic
2281          interface.  */
2282     }
2283
2284   if (sym->attr.intrinsic)
2285     return gfc_intrinsic_func_interface (expr, 0);
2286
2287   return MATCH_NO;
2288 }
2289
2290
2291 static gfc_try
2292 resolve_generic_f (gfc_expr *expr)
2293 {
2294   gfc_symbol *sym;
2295   match m;
2296
2297   sym = expr->symtree->n.sym;
2298
2299   for (;;)
2300     {
2301       m = resolve_generic_f0 (expr, sym);
2302       if (m == MATCH_YES)
2303         return SUCCESS;
2304       else if (m == MATCH_ERROR)
2305         return FAILURE;
2306
2307 generic:
2308       if (sym->ns->parent == NULL)
2309         break;
2310       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2311
2312       if (sym == NULL)
2313         break;
2314       if (!generic_sym (sym))
2315         goto generic;
2316     }
2317
2318   /* Last ditch attempt.  See if the reference is to an intrinsic
2319      that possesses a matching interface.  14.1.2.4  */
2320   if (sym && !gfc_is_intrinsic (sym, 0, expr->where))
2321     {
2322       gfc_error ("There is no specific function for the generic '%s' at %L",
2323                  expr->symtree->n.sym->name, &expr->where);
2324       return FAILURE;
2325     }
2326
2327   m = gfc_intrinsic_func_interface (expr, 0);
2328   if (m == MATCH_YES)
2329     return SUCCESS;
2330   if (m == MATCH_NO)
2331     gfc_error ("Generic function '%s' at %L is not consistent with a "
2332                "specific intrinsic interface", expr->symtree->n.sym->name,
2333                &expr->where);
2334
2335   return FAILURE;
2336 }
2337
2338
2339 /* Resolve a function call known to be specific.  */
2340
2341 static match
2342 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2343 {
2344   match m;
2345
2346   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2347     {
2348       if (sym->attr.dummy)
2349         {
2350           sym->attr.proc = PROC_DUMMY;
2351           goto found;
2352         }
2353
2354       sym->attr.proc = PROC_EXTERNAL;
2355       goto found;
2356     }
2357
2358   if (sym->attr.proc == PROC_MODULE
2359       || sym->attr.proc == PROC_ST_FUNCTION
2360       || sym->attr.proc == PROC_INTERNAL)
2361     goto found;
2362
2363   if (sym->attr.intrinsic)
2364     {
2365       m = gfc_intrinsic_func_interface (expr, 1);
2366       if (m == MATCH_YES)
2367         return MATCH_YES;
2368       if (m == MATCH_NO)
2369         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2370                    "with an intrinsic", sym->name, &expr->where);
2371
2372       return MATCH_ERROR;
2373     }
2374
2375   return MATCH_NO;
2376
2377 found:
2378   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2379
2380   if (sym->result)
2381     expr->ts = sym->result->ts;
2382   else
2383     expr->ts = sym->ts;
2384   expr->value.function.name = sym->name;
2385   expr->value.function.esym = sym;
2386   if (sym->as != NULL)
2387     expr->rank = sym->as->rank;
2388
2389   return MATCH_YES;
2390 }
2391
2392
2393 static gfc_try
2394 resolve_specific_f (gfc_expr *expr)
2395 {
2396   gfc_symbol *sym;
2397   match m;
2398
2399   sym = expr->symtree->n.sym;
2400
2401   for (;;)
2402     {
2403       m = resolve_specific_f0 (sym, expr);
2404       if (m == MATCH_YES)
2405         return SUCCESS;
2406       if (m == MATCH_ERROR)
2407         return FAILURE;
2408
2409       if (sym->ns->parent == NULL)
2410         break;
2411
2412       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2413
2414       if (sym == NULL)
2415         break;
2416     }
2417
2418   gfc_error ("Unable to resolve the specific function '%s' at %L",
2419              expr->symtree->n.sym->name, &expr->where);
2420
2421   return SUCCESS;
2422 }
2423
2424
2425 /* Resolve a procedure call not known to be generic nor specific.  */
2426
2427 static gfc_try
2428 resolve_unknown_f (gfc_expr *expr)
2429 {
2430   gfc_symbol *sym;
2431   gfc_typespec *ts;
2432
2433   sym = expr->symtree->n.sym;
2434
2435   if (sym->attr.dummy)
2436     {
2437       sym->attr.proc = PROC_DUMMY;
2438       expr->value.function.name = sym->name;
2439       goto set_type;
2440     }
2441
2442   /* See if we have an intrinsic function reference.  */
2443
2444   if (gfc_is_intrinsic (sym, 0, expr->where))
2445     {
2446       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2447         return SUCCESS;
2448       return FAILURE;
2449     }
2450
2451   /* The reference is to an external name.  */
2452
2453   sym->attr.proc = PROC_EXTERNAL;
2454   expr->value.function.name = sym->name;
2455   expr->value.function.esym = expr->symtree->n.sym;
2456
2457   if (sym->as != NULL)
2458     expr->rank = sym->as->rank;
2459
2460   /* Type of the expression is either the type of the symbol or the
2461      default type of the symbol.  */
2462
2463 set_type:
2464   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2465
2466   if (sym->ts.type != BT_UNKNOWN)
2467     expr->ts = sym->ts;
2468   else
2469     {
2470       ts = gfc_get_default_type (sym->name, sym->ns);
2471
2472       if (ts->type == BT_UNKNOWN)
2473         {
2474           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2475                      sym->name, &expr->where);
2476           return FAILURE;
2477         }
2478       else
2479         expr->ts = *ts;
2480     }
2481
2482   return SUCCESS;
2483 }
2484
2485
2486 /* Return true, if the symbol is an external procedure.  */
2487 static bool
2488 is_external_proc (gfc_symbol *sym)
2489 {
2490   if (!sym->attr.dummy && !sym->attr.contained
2491         && !(sym->attr.intrinsic
2492               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2493         && sym->attr.proc != PROC_ST_FUNCTION
2494         && !sym->attr.proc_pointer
2495         && !sym->attr.use_assoc
2496         && sym->name)
2497     return true;
2498
2499   return false;
2500 }
2501
2502
2503 /* Figure out if a function reference is pure or not.  Also set the name
2504    of the function for a potential error message.  Return nonzero if the
2505    function is PURE, zero if not.  */
2506 static int
2507 pure_stmt_function (gfc_expr *, gfc_symbol *);
2508
2509 static int
2510 pure_function (gfc_expr *e, const char **name)
2511 {
2512   int pure;
2513
2514   *name = NULL;
2515
2516   if (e->symtree != NULL
2517         && e->symtree->n.sym != NULL
2518         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2519     return pure_stmt_function (e, e->symtree->n.sym);
2520
2521   if (e->value.function.esym)
2522     {
2523       pure = gfc_pure (e->value.function.esym);
2524       *name = e->value.function.esym->name;
2525     }
2526   else if (e->value.function.isym)
2527     {
2528       pure = e->value.function.isym->pure
2529              || e->value.function.isym->elemental;
2530       *name = e->value.function.isym->name;
2531     }
2532   else
2533     {
2534       /* Implicit functions are not pure.  */
2535       pure = 0;
2536       *name = e->value.function.name;
2537     }
2538
2539   return pure;
2540 }
2541
2542
2543 static bool
2544 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2545                  int *f ATTRIBUTE_UNUSED)
2546 {
2547   const char *name;
2548
2549   /* Don't bother recursing into other statement functions
2550      since they will be checked individually for purity.  */
2551   if (e->expr_type != EXPR_FUNCTION
2552         || !e->symtree
2553         || e->symtree->n.sym == sym
2554         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2555     return false;
2556
2557   return pure_function (e, &name) ? false : true;
2558 }
2559
2560
2561 static int
2562 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2563 {
2564   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2565 }
2566
2567
2568 static gfc_try
2569 is_scalar_expr_ptr (gfc_expr *expr)
2570 {
2571   gfc_try retval = SUCCESS;
2572   gfc_ref *ref;
2573   int start;
2574   int end;
2575
2576   /* See if we have a gfc_ref, which means we have a substring, array
2577      reference, or a component.  */
2578   if (expr->ref != NULL)
2579     {
2580       ref = expr->ref;
2581       while (ref->next != NULL)
2582         ref = ref->next;
2583
2584       switch (ref->type)
2585         {
2586         case REF_SUBSTRING:
2587           if (ref->u.ss.start == NULL || ref->u.ss.end == NULL
2588               || gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) != 0)
2589             retval = FAILURE;
2590           break;
2591
2592         case REF_ARRAY:
2593           if (ref->u.ar.type == AR_ELEMENT)
2594             retval = SUCCESS;
2595           else if (ref->u.ar.type == AR_FULL)
2596             {
2597               /* The user can give a full array if the array is of size 1.  */
2598               if (ref->u.ar.as != NULL
2599                   && ref->u.ar.as->rank == 1
2600                   && ref->u.ar.as->type == AS_EXPLICIT
2601                   && ref->u.ar.as->lower[0] != NULL
2602                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2603                   && ref->u.ar.as->upper[0] != NULL
2604                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2605                 {
2606                   /* If we have a character string, we need to check if
2607                      its length is one.  */
2608                   if (expr->ts.type == BT_CHARACTER)
2609                     {
2610                       if (expr->ts.u.cl == NULL
2611                           || expr->ts.u.cl->length == NULL
2612                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2613                           != 0)
2614                         retval = FAILURE;
2615                     }
2616                   else
2617                     {
2618                       /* We have constant lower and upper bounds.  If the
2619                          difference between is 1, it can be considered a
2620                          scalar.  
2621                          FIXME: Use gfc_dep_compare_expr instead.  */
2622                       start = (int) mpz_get_si
2623                                 (ref->u.ar.as->lower[0]->value.integer);
2624                       end = (int) mpz_get_si
2625                                 (ref->u.ar.as->upper[0]->value.integer);
2626                       if (end - start + 1 != 1)
2627                         retval = FAILURE;
2628                    }
2629                 }
2630               else
2631                 retval = FAILURE;
2632             }
2633           else
2634             retval = FAILURE;
2635           break;
2636         default:
2637           retval = SUCCESS;
2638           break;
2639         }
2640     }
2641   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2642     {
2643       /* Character string.  Make sure it's of length 1.  */
2644       if (expr->ts.u.cl == NULL
2645           || expr->ts.u.cl->length == NULL
2646           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2647         retval = FAILURE;
2648     }
2649   else if (expr->rank != 0)
2650     retval = FAILURE;
2651
2652   return retval;
2653 }
2654
2655
2656 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2657    and, in the case of c_associated, set the binding label based on
2658    the arguments.  */
2659
2660 static gfc_try
2661 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2662                           gfc_symbol **new_sym)
2663 {
2664   char name[GFC_MAX_SYMBOL_LEN + 1];
2665   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
2666   int optional_arg = 0;
2667   gfc_try retval = SUCCESS;
2668   gfc_symbol *args_sym;
2669   gfc_typespec *arg_ts;
2670   symbol_attribute arg_attr;
2671
2672   if (args->expr->expr_type == EXPR_CONSTANT
2673       || args->expr->expr_type == EXPR_OP
2674       || args->expr->expr_type == EXPR_NULL)
2675     {
2676       gfc_error ("Argument to '%s' at %L is not a variable",
2677                  sym->name, &(args->expr->where));
2678       return FAILURE;
2679     }
2680
2681   args_sym = args->expr->symtree->n.sym;
2682
2683   /* The typespec for the actual arg should be that stored in the expr
2684      and not necessarily that of the expr symbol (args_sym), because
2685      the actual expression could be a part-ref of the expr symbol.  */
2686   arg_ts = &(args->expr->ts);
2687   arg_attr = gfc_expr_attr (args->expr);
2688     
2689   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2690     {
2691       /* If the user gave two args then they are providing something for
2692          the optional arg (the second cptr).  Therefore, set the name and
2693          binding label to the c_associated for two cptrs.  Otherwise,
2694          set c_associated to expect one cptr.  */
2695       if (args->next)
2696         {
2697           /* two args.  */
2698           sprintf (name, "%s_2", sym->name);
2699           sprintf (binding_label, "%s_2", sym->binding_label);
2700           optional_arg = 1;
2701         }
2702       else
2703         {
2704           /* one arg.  */
2705           sprintf (name, "%s_1", sym->name);
2706           sprintf (binding_label, "%s_1", sym->binding_label);
2707           optional_arg = 0;
2708         }
2709
2710       /* Get a new symbol for the version of c_associated that
2711          will get called.  */
2712       *new_sym = get_iso_c_sym (sym, name, binding_label, optional_arg);
2713     }
2714   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2715            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2716     {
2717       sprintf (name, "%s", sym->name);
2718       sprintf (binding_label, "%s", sym->binding_label);
2719
2720       /* Error check the call.  */
2721       if (args->next != NULL)
2722         {
2723           gfc_error_now ("More actual than formal arguments in '%s' "
2724                          "call at %L", name, &(args->expr->where));
2725           retval = FAILURE;
2726         }
2727       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2728         {
2729           gfc_ref *ref;
2730           bool seen_section;
2731
2732           /* Make sure we have either the target or pointer attribute.  */
2733           if (!arg_attr.target && !arg_attr.pointer)
2734             {
2735               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2736                              "a TARGET or an associated pointer",
2737                              args_sym->name,
2738                              sym->name, &(args->expr->where));
2739               retval = FAILURE;
2740             }
2741
2742           if (gfc_is_coindexed (args->expr))
2743             {
2744               gfc_error_now ("Coindexed argument not permitted"
2745                              " in '%s' call at %L", name,
2746                              &(args->expr->where));
2747               retval = FAILURE;
2748             }
2749
2750           /* Follow references to make sure there are no array
2751              sections.  */
2752           seen_section = false;
2753
2754           for (ref=args->expr->ref; ref; ref = ref->next)
2755             {
2756               if (ref->type == REF_ARRAY)
2757                 {
2758                   if (ref->u.ar.type == AR_SECTION)
2759                     seen_section = true;
2760
2761                   if (ref->u.ar.type != AR_ELEMENT)
2762                     {
2763                       gfc_ref *r;
2764                       for (r = ref->next; r; r=r->next)
2765                         if (r->type == REF_COMPONENT)
2766                           {
2767                             gfc_error_now ("Array section not permitted"
2768                                            " in '%s' call at %L", name,
2769                                            &(args->expr->where));
2770                             retval = FAILURE;
2771                             break;
2772                           }
2773                     }
2774                 }
2775             }
2776
2777           if (seen_section && retval == SUCCESS)
2778             gfc_warning ("Array section in '%s' call at %L", name,
2779                          &(args->expr->where));
2780                          
2781           /* See if we have interoperable type and type param.  */
2782           if (verify_c_interop (arg_ts) == SUCCESS
2783               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2784             {
2785               if (args_sym->attr.target == 1)
2786                 {
2787                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2788                      has the target attribute and is interoperable.  */
2789                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2790                      allocatable variable that has the TARGET attribute and
2791                      is not an array of zero size.  */
2792                   if (args_sym->attr.allocatable == 1)
2793                     {
2794                       if (args_sym->attr.dimension != 0 
2795                           && (args_sym->as && args_sym->as->rank == 0))
2796                         {
2797                           gfc_error_now ("Allocatable variable '%s' used as a "
2798                                          "parameter to '%s' at %L must not be "
2799                                          "an array of zero size",
2800                                          args_sym->name, sym->name,
2801                                          &(args->expr->where));
2802                           retval = FAILURE;
2803                         }
2804                     }
2805                   else
2806                     {
2807                       /* A non-allocatable target variable with C
2808                          interoperable type and type parameters must be
2809                          interoperable.  */
2810                       if (args_sym && args_sym->attr.dimension)
2811                         {
2812                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2813                             {
2814                               gfc_error ("Assumed-shape array '%s' at %L "
2815                                          "cannot be an argument to the "
2816                                          "procedure '%s' because "
2817                                          "it is not C interoperable",
2818                                          args_sym->name,
2819                                          &(args->expr->where), sym->name);
2820                               retval = FAILURE;
2821                             }
2822                           else if (args_sym->as->type == AS_DEFERRED)
2823                             {
2824                               gfc_error ("Deferred-shape array '%s' at %L "
2825                                          "cannot be an argument to the "
2826                                          "procedure '%s' because "
2827                                          "it is not C interoperable",
2828                                          args_sym->name,
2829                                          &(args->expr->where), sym->name);
2830                               retval = FAILURE;
2831                             }
2832                         }
2833                               
2834                       /* Make sure it's not a character string.  Arrays of
2835                          any type should be ok if the variable is of a C
2836                          interoperable type.  */
2837                       if (arg_ts->type == BT_CHARACTER)
2838                         if (arg_ts->u.cl != NULL
2839                             && (arg_ts->u.cl->length == NULL
2840                                 || arg_ts->u.cl->length->expr_type
2841                                    != EXPR_CONSTANT
2842                                 || mpz_cmp_si
2843                                     (arg_ts->u.cl->length->value.integer, 1)
2844                                    != 0)
2845                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2846                           {
2847                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2848                                            "at %L must have a length of 1",
2849                                            args_sym->name, sym->name,
2850                                            &(args->expr->where));
2851                             retval = FAILURE;
2852                           }
2853                     }
2854                 }
2855               else if (arg_attr.pointer
2856                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2857                 {
2858                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2859                      scalar pointer.  */
2860                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2861                                  "associated scalar POINTER", args_sym->name,
2862                                  sym->name, &(args->expr->where));
2863                   retval = FAILURE;
2864                 }
2865             }
2866           else
2867             {
2868               /* The parameter is not required to be C interoperable.  If it
2869                  is not C interoperable, it must be a nonpolymorphic scalar
2870                  with no length type parameters.  It still must have either
2871                  the pointer or target attribute, and it can be
2872                  allocatable (but must be allocated when c_loc is called).  */
2873               if (args->expr->rank != 0 
2874                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2875                 {
2876                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2877                                  "scalar", args_sym->name, sym->name,
2878                                  &(args->expr->where));
2879                   retval = FAILURE;
2880                 }
2881               else if (arg_ts->type == BT_CHARACTER 
2882                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2883                 {
2884                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2885                                  "%L must have a length of 1",
2886                                  args_sym->name, sym->name,
2887                                  &(args->expr->where));
2888                   retval = FAILURE;
2889                 }
2890               else if (arg_ts->type == BT_CLASS)
2891                 {
2892                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2893                                  "polymorphic", args_sym->name, sym->name,
2894                                  &(args->expr->where));
2895                   retval = FAILURE;
2896                 }
2897             }
2898         }
2899       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2900         {
2901           if (args_sym->attr.flavor != FL_PROCEDURE)
2902             {
2903               /* TODO: Update this error message to allow for procedure
2904                  pointers once they are implemented.  */
2905               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2906                              "procedure",
2907                              args_sym->name, sym->name,
2908                              &(args->expr->where));
2909               retval = FAILURE;
2910             }
2911           else if (args_sym->attr.is_bind_c != 1)
2912             {
2913               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2914                              "BIND(C)",
2915                              args_sym->name, sym->name,
2916                              &(args->expr->where));
2917               retval = FAILURE;
2918             }
2919         }
2920       
2921       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2922       *new_sym = sym;
2923     }
2924   else
2925     {
2926       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2927                           "iso_c_binding function: '%s'!\n", sym->name);
2928     }
2929
2930   return retval;
2931 }
2932
2933
2934 /* Resolve a function call, which means resolving the arguments, then figuring
2935    out which entity the name refers to.  */
2936
2937 static gfc_try
2938 resolve_function (gfc_expr *expr)
2939 {
2940   gfc_actual_arglist *arg;
2941   gfc_symbol *sym;
2942   const char *name;
2943   gfc_try t;
2944   int temp;
2945   procedure_type p = PROC_INTRINSIC;
2946   bool no_formal_args;
2947
2948   sym = NULL;
2949   if (expr->symtree)
2950     sym = expr->symtree->n.sym;
2951
2952   /* If this is a procedure pointer component, it has already been resolved.  */
2953   if (gfc_is_proc_ptr_comp (expr, NULL))
2954     return SUCCESS;
2955   
2956   if (sym && sym->attr.intrinsic
2957       && resolve_intrinsic (sym, &expr->where) == FAILURE)
2958     return FAILURE;
2959
2960   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
2961     {
2962       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
2963       return FAILURE;
2964     }
2965
2966   /* If this ia a deferred TBP with an abstract interface (which may
2967      of course be referenced), expr->value.function.esym will be set.  */
2968   if (sym && sym->attr.abstract && !expr->value.function.esym)
2969     {
2970       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
2971                  sym->name, &expr->where);
2972       return FAILURE;
2973     }
2974
2975   /* Switch off assumed size checking and do this again for certain kinds
2976      of procedure, once the procedure itself is resolved.  */
2977   need_full_assumed_size++;
2978
2979   if (expr->symtree && expr->symtree->n.sym)
2980     p = expr->symtree->n.sym->attr.proc;
2981
2982   if (expr->value.function.isym && expr->value.function.isym->inquiry)
2983     inquiry_argument = true;
2984   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
2985
2986   if (resolve_actual_arglist (expr->value.function.actual,
2987                               p, no_formal_args) == FAILURE)
2988     {
2989       inquiry_argument = false;
2990       return FAILURE;
2991     }
2992
2993   inquiry_argument = false;
2994  
2995   /* Need to setup the call to the correct c_associated, depending on
2996      the number of cptrs to user gives to compare.  */
2997   if (sym && sym->attr.is_iso_c == 1)
2998     {
2999       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
3000           == FAILURE)
3001         return FAILURE;
3002       
3003       /* Get the symtree for the new symbol (resolved func).
3004          the old one will be freed later, when it's no longer used.  */
3005       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
3006     }
3007   
3008   /* Resume assumed_size checking.  */
3009   need_full_assumed_size--;
3010
3011   /* If the procedure is external, check for usage.  */
3012   if (sym && is_external_proc (sym))
3013     resolve_global_procedure (sym, &expr->where,
3014                               &expr->value.function.actual, 0);
3015
3016   if (sym && sym->ts.type == BT_CHARACTER
3017       && sym->ts.u.cl
3018       && sym->ts.u.cl->length == NULL
3019       && !sym->attr.dummy
3020       && !sym->ts.deferred
3021       && expr->value.function.esym == NULL
3022       && !sym->attr.contained)
3023     {
3024       /* Internal procedures are taken care of in resolve_contained_fntype.  */
3025       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
3026                  "be used at %L since it is not a dummy argument",
3027                  sym->name, &expr->where);
3028       return FAILURE;
3029     }
3030
3031   /* See if function is already resolved.  */
3032
3033   if (expr->value.function.name != NULL)
3034     {
3035       if (expr->ts.type == BT_UNKNOWN)
3036         expr->ts = sym->ts;
3037       t = SUCCESS;
3038     }
3039   else
3040     {
3041       /* Apply the rules of section 14.1.2.  */
3042
3043       switch (procedure_kind (sym))
3044         {
3045         case PTYPE_GENERIC:
3046           t = resolve_generic_f (expr);
3047           break;
3048
3049         case PTYPE_SPECIFIC:
3050           t = resolve_specific_f (expr);
3051           break;
3052
3053         case PTYPE_UNKNOWN:
3054           t = resolve_unknown_f (expr);
3055           break;
3056
3057         default:
3058           gfc_internal_error ("resolve_function(): bad function type");
3059         }
3060     }
3061
3062   /* If the expression is still a function (it might have simplified),
3063      then we check to see if we are calling an elemental function.  */
3064
3065   if (expr->expr_type != EXPR_FUNCTION)
3066     return t;
3067
3068   temp = need_full_assumed_size;
3069   need_full_assumed_size = 0;
3070
3071   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3072     return FAILURE;
3073
3074   if (omp_workshare_flag
3075       && expr->value.function.esym
3076       && ! gfc_elemental (expr->value.function.esym))
3077     {
3078       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3079                  "in WORKSHARE construct", expr->value.function.esym->name,
3080                  &expr->where);
3081       t = FAILURE;
3082     }
3083
3084 #define GENERIC_ID expr->value.function.isym->id
3085   else if (expr->value.function.actual != NULL
3086            && expr->value.function.isym != NULL
3087            && GENERIC_ID != GFC_ISYM_LBOUND
3088            && GENERIC_ID != GFC_ISYM_LEN
3089            && GENERIC_ID != GFC_ISYM_LOC
3090            && GENERIC_ID != GFC_ISYM_PRESENT)
3091     {
3092       /* Array intrinsics must also have the last upper bound of an
3093          assumed size array argument.  UBOUND and SIZE have to be
3094          excluded from the check if the second argument is anything
3095          than a constant.  */
3096
3097       for (arg = expr->value.function.actual; arg; arg = arg->next)
3098         {
3099           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3100               && arg->next != NULL && arg->next->expr)
3101             {
3102               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3103                 break;
3104
3105               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3106                 break;
3107
3108               if ((int)mpz_get_si (arg->next->expr->value.integer)
3109                         < arg->expr->rank)
3110                 break;
3111             }
3112
3113           if (arg->expr != NULL
3114               && arg->expr->rank > 0
3115               && resolve_assumed_size_actual (arg->expr))
3116             return FAILURE;
3117         }
3118     }
3119 #undef GENERIC_ID
3120
3121   need_full_assumed_size = temp;
3122   name = NULL;
3123
3124   if (!pure_function (expr, &name) && name)
3125     {
3126       if (forall_flag)
3127         {
3128           gfc_error ("reference to non-PURE function '%s' at %L inside a "
3129                      "FORALL %s", name, &expr->where,
3130                      forall_flag == 2 ? "mask" : "block");
3131           t = FAILURE;
3132         }
3133       else if (gfc_pure (NULL))
3134         {
3135           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3136                      "procedure within a PURE procedure", name, &expr->where);
3137           t = FAILURE;
3138         }
3139     }
3140
3141   if (!pure_function (expr, &name) && name && gfc_implicit_pure (NULL))
3142     gfc_current_ns->proc_name->attr.implicit_pure = 0;
3143
3144   /* Functions without the RECURSIVE attribution are not allowed to
3145    * call themselves.  */
3146   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3147     {
3148       gfc_symbol *esym;
3149       esym = expr->value.function.esym;
3150
3151       if (is_illegal_recursion (esym, gfc_current_ns))
3152       {
3153         if (esym->attr.entry && esym->ns->entries)
3154           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3155                      " function '%s' is not RECURSIVE",
3156                      esym->name, &expr->where, esym->ns->entries->sym->name);
3157         else
3158           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3159                      " is not RECURSIVE", esym->name, &expr->where);
3160
3161         t = FAILURE;
3162       }
3163     }
3164
3165   /* Character lengths of use associated functions may contains references to
3166      symbols not referenced from the current program unit otherwise.  Make sure
3167      those symbols are marked as referenced.  */
3168
3169   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3170       && expr->value.function.esym->attr.use_assoc)
3171     {
3172       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3173     }
3174
3175   /* Make sure that the expression has a typespec that works.  */
3176   if (expr->ts.type == BT_UNKNOWN)
3177     {
3178       if (expr->symtree->n.sym->result
3179             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3180             && !expr->symtree->n.sym->result->attr.proc_pointer)
3181         expr->ts = expr->symtree->n.sym->result->ts;
3182     }
3183
3184   return t;
3185 }
3186
3187
3188 /************* Subroutine resolution *************/
3189
3190 static void
3191 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3192 {
3193   if (gfc_pure (sym))
3194     return;
3195
3196   if (forall_flag)
3197     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3198                sym->name, &c->loc);
3199   else if (gfc_pure (NULL))
3200     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3201                &c->loc);
3202 }
3203
3204
3205 static match
3206 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3207 {
3208   gfc_symbol *s;
3209
3210   if (sym->attr.generic)
3211     {
3212       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3213       if (s != NULL)
3214         {
3215           c->resolved_sym = s;
3216           pure_subroutine (c, s);
3217           return MATCH_YES;
3218         }
3219
3220       /* TODO: Need to search for elemental references in generic interface.  */
3221     }
3222
3223   if (sym->attr.intrinsic)
3224     return gfc_intrinsic_sub_interface (c, 0);
3225
3226   return MATCH_NO;
3227 }
3228
3229
3230 static gfc_try
3231 resolve_generic_s (gfc_code *c)
3232 {
3233   gfc_symbol *sym;
3234   match m;
3235
3236   sym = c->symtree->n.sym;
3237
3238   for (;;)
3239     {
3240       m = resolve_generic_s0 (c, sym);
3241       if (m == MATCH_YES)
3242         return SUCCESS;
3243       else if (m == MATCH_ERROR)
3244         return FAILURE;
3245
3246 generic:
3247       if (sym->ns->parent == NULL)
3248         break;
3249       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3250
3251       if (sym == NULL)
3252         break;
3253       if (!generic_sym (sym))
3254         goto generic;
3255     }
3256
3257   /* Last ditch attempt.  See if the reference is to an intrinsic
3258      that possesses a matching interface.  14.1.2.4  */
3259   sym = c->symtree->n.sym;
3260
3261   if (!gfc_is_intrinsic (sym, 1, c->loc))
3262     {
3263       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3264                  sym->name, &c->loc);
3265       return FAILURE;
3266     }
3267
3268   m = gfc_intrinsic_sub_interface (c, 0);
3269   if (m == MATCH_YES)
3270     return SUCCESS;
3271   if (m == MATCH_NO)
3272     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3273                "intrinsic subroutine interface", sym->name, &c->loc);
3274
3275   return FAILURE;
3276 }
3277
3278
3279 /* Set the name and binding label of the subroutine symbol in the call
3280    expression represented by 'c' to include the type and kind of the
3281    second parameter.  This function is for resolving the appropriate
3282    version of c_f_pointer() and c_f_procpointer().  For example, a
3283    call to c_f_pointer() for a default integer pointer could have a
3284    name of c_f_pointer_i4.  If no second arg exists, which is an error
3285    for these two functions, it defaults to the generic symbol's name
3286    and binding label.  */
3287
3288 static void
3289 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3290                     char *name, char *binding_label)
3291 {
3292   gfc_expr *arg = NULL;
3293   char type;
3294   int kind;
3295
3296   /* The second arg of c_f_pointer and c_f_procpointer determines
3297      the type and kind for the procedure name.  */
3298   arg = c->ext.actual->next->expr;
3299
3300   if (arg != NULL)
3301     {
3302       /* Set up the name to have the given symbol's name,
3303          plus the type and kind.  */
3304       /* a derived type is marked with the type letter 'u' */
3305       if (arg->ts.type == BT_DERIVED)
3306         {
3307           type = 'd';
3308           kind = 0; /* set the kind as 0 for now */
3309         }
3310       else
3311         {
3312           type = gfc_type_letter (arg->ts.type);
3313           kind = arg->ts.kind;
3314         }
3315
3316       if (arg->ts.type == BT_CHARACTER)
3317         /* Kind info for character strings not needed.  */
3318         kind = 0;
3319
3320       sprintf (name, "%s_%c%d", sym->name, type, kind);
3321       /* Set up the binding label as the given symbol's label plus
3322          the type and kind.  */
3323       sprintf (binding_label, "%s_%c%d", sym->binding_label, type, kind);
3324     }
3325   else
3326     {
3327       /* If the second arg is missing, set the name and label as
3328          was, cause it should at least be found, and the missing
3329          arg error will be caught by compare_parameters().  */
3330       sprintf (name, "%s", sym->name);
3331       sprintf (binding_label, "%s", sym->binding_label);
3332     }
3333    
3334   return;
3335 }
3336
3337
3338 /* Resolve a generic version of the iso_c_binding procedure given
3339    (sym) to the specific one based on the type and kind of the
3340    argument(s).  Currently, this function resolves c_f_pointer() and
3341    c_f_procpointer based on the type and kind of the second argument
3342    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3343    Upon successfully exiting, c->resolved_sym will hold the resolved
3344    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3345    otherwise.  */
3346
3347 match
3348 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3349 {
3350   gfc_symbol *new_sym;
3351   /* this is fine, since we know the names won't use the max */
3352   char name[GFC_MAX_SYMBOL_LEN + 1];
3353   char binding_label[GFC_MAX_BINDING_LABEL_LEN + 1];
3354   /* default to success; will override if find error */
3355   match m = MATCH_YES;
3356
3357   /* Make sure the actual arguments are in the necessary order (based on the 
3358      formal args) before resolving.  */
3359   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3360
3361   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3362       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3363     {
3364       set_name_and_label (c, sym, name, binding_label);
3365       
3366       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3367         {
3368           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3369             {
3370               /* Make sure we got a third arg if the second arg has non-zero
3371                  rank.  We must also check that the type and rank are
3372                  correct since we short-circuit this check in
3373                  gfc_procedure_use() (called above to sort actual args).  */
3374               if (c->ext.actual->next->expr->rank != 0)
3375                 {
3376                   if(c->ext.actual->next->next == NULL 
3377                      || c->ext.actual->next->next->expr == NULL)
3378                     {
3379                       m = MATCH_ERROR;
3380                       gfc_error ("Missing SHAPE parameter for call to %s "
3381                                  "at %L", sym->name, &(c->loc));
3382                     }
3383                   else if (c->ext.actual->next->next->expr->ts.type
3384                            != BT_INTEGER
3385                            || c->ext.actual->next->next->expr->rank != 1)
3386                     {
3387                       m = MATCH_ERROR;
3388                       gfc_error ("SHAPE parameter for call to %s at %L must "
3389                                  "be a rank 1 INTEGER array", sym->name,
3390                                  &(c->loc));
3391                     }
3392                 }
3393             }
3394         }
3395       
3396       if (m != MATCH_ERROR)
3397         {
3398           /* the 1 means to add the optional arg to formal list */
3399           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3400          
3401           /* for error reporting, say it's declared where the original was */
3402           new_sym->declared_at = sym->declared_at;
3403         }
3404     }
3405   else
3406     {
3407       /* no differences for c_loc or c_funloc */
3408       new_sym = sym;
3409     }
3410
3411   /* set the resolved symbol */
3412   if (m != MATCH_ERROR)
3413     c->resolved_sym = new_sym;
3414   else
3415     c->resolved_sym = sym;
3416   
3417   return m;
3418 }
3419
3420
3421 /* Resolve a subroutine call known to be specific.  */
3422
3423 static match
3424 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3425 {
3426   match m;
3427
3428   if(sym->attr.is_iso_c)
3429     {
3430       m = gfc_iso_c_sub_interface (c,sym);
3431       return m;
3432     }
3433   
3434   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3435     {
3436       if (sym->attr.dummy)
3437         {
3438           sym->attr.proc = PROC_DUMMY;
3439           goto found;
3440         }
3441
3442       sym->attr.proc = PROC_EXTERNAL;
3443       goto found;
3444     }
3445
3446   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3447     goto found;
3448
3449   if (sym->attr.intrinsic)
3450     {
3451       m = gfc_intrinsic_sub_interface (c, 1);
3452       if (m == MATCH_YES)
3453         return MATCH_YES;
3454       if (m == MATCH_NO)
3455         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3456                    "with an intrinsic", sym->name, &c->loc);
3457
3458       return MATCH_ERROR;
3459     }
3460
3461   return MATCH_NO;
3462
3463 found:
3464   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3465
3466   c->resolved_sym = sym;
3467   pure_subroutine (c, sym);
3468
3469   return MATCH_YES;
3470 }
3471
3472
3473 static gfc_try
3474 resolve_specific_s (gfc_code *c)
3475 {
3476   gfc_symbol *sym;
3477   match m;
3478
3479   sym = c->symtree->n.sym;
3480
3481   for (;;)
3482     {
3483       m = resolve_specific_s0 (c, sym);
3484       if (m == MATCH_YES)
3485         return SUCCESS;
3486       if (m == MATCH_ERROR)
3487         return FAILURE;
3488
3489       if (sym->ns->parent == NULL)
3490         break;
3491
3492       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3493
3494       if (sym == NULL)
3495         break;
3496     }
3497
3498   sym = c->symtree->n.sym;
3499   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3500              sym->name, &c->loc);
3501
3502   return FAILURE;
3503 }
3504
3505
3506 /* Resolve a subroutine call not known to be generic nor specific.  */
3507
3508 static gfc_try
3509 resolve_unknown_s (gfc_code *c)
3510 {
3511   gfc_symbol *sym;
3512
3513   sym = c->symtree->n.sym;
3514
3515   if (sym->attr.dummy)
3516     {
3517       sym->attr.proc = PROC_DUMMY;
3518       goto found;
3519     }
3520
3521   /* See if we have an intrinsic function reference.  */
3522
3523   if (gfc_is_intrinsic (sym, 1, c->loc))
3524     {
3525       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3526         return SUCCESS;
3527       return FAILURE;
3528     }
3529
3530   /* The reference is to an external name.  */
3531
3532 found:
3533   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3534
3535   c->resolved_sym = sym;
3536
3537   pure_subroutine (c, sym);
3538
3539   return SUCCESS;
3540 }
3541
3542
3543 /* Resolve a subroutine call.  Although it was tempting to use the same code
3544    for functions, subroutines and functions are stored differently and this
3545    makes things awkward.  */
3546
3547 static gfc_try
3548 resolve_call (gfc_code *c)
3549 {
3550   gfc_try t;
3551   procedure_type ptype = PROC_INTRINSIC;
3552   gfc_symbol *csym, *sym;
3553   bool no_formal_args;
3554
3555   csym = c->symtree ? c->symtree->n.sym : NULL;
3556
3557   if (csym && csym->ts.type != BT_UNKNOWN)
3558     {
3559       gfc_error ("'%s' at %L has a type, which is not consistent with "
3560                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3561       return FAILURE;
3562     }
3563
3564   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3565     {
3566       gfc_symtree *st;
3567       gfc_find_sym_tree (csym->name, gfc_current_ns, 1, &st);
3568       sym = st ? st->n.sym : NULL;
3569       if (sym && csym != sym
3570               && sym->ns == gfc_current_ns
3571               && sym->attr.flavor == FL_PROCEDURE
3572               && sym->attr.contained)
3573         {
3574           sym->refs++;
3575           if (csym->attr.generic)
3576             c->symtree->n.sym = sym;
3577           else
3578             c->symtree = st;
3579           csym = c->symtree->n.sym;
3580         }
3581     }
3582
3583   /* If this ia a deferred TBP with an abstract interface
3584      (which may of course be referenced), c->expr1 will be set.  */
3585   if (csym && csym->attr.abstract && !c->expr1)
3586     {
3587       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3588                  csym->name, &c->loc);
3589       return FAILURE;
3590     }
3591
3592   /* Subroutines without the RECURSIVE attribution are not allowed to
3593    * call themselves.  */
3594   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3595     {
3596       if (csym->attr.entry && csym->ns->entries)
3597         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3598                    " subroutine '%s' is not RECURSIVE",
3599                    csym->name, &c->loc, csym->ns->entries->sym->name);
3600       else
3601         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3602                    " is not RECURSIVE", csym->name, &c->loc);
3603
3604       t = FAILURE;
3605     }
3606
3607   /* Switch off assumed size checking and do this again for certain kinds
3608      of procedure, once the procedure itself is resolved.  */
3609   need_full_assumed_size++;
3610
3611   if (csym)
3612     ptype = csym->attr.proc;
3613
3614   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3615   if (resolve_actual_arglist (c->ext.actual, ptype,
3616                               no_formal_args) == FAILURE)
3617     return FAILURE;
3618
3619   /* Resume assumed_size checking.  */
3620   need_full_assumed_size--;
3621
3622   /* If external, check for usage.  */
3623   if (csym && is_external_proc (csym))
3624     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3625
3626   t = SUCCESS;
3627   if (c->resolved_sym == NULL)
3628     {
3629       c->resolved_isym = NULL;
3630       switch (procedure_kind (csym))
3631         {
3632         case PTYPE_GENERIC:
3633           t = resolve_generic_s (c);
3634           break;
3635
3636         case PTYPE_SPECIFIC:
3637           t = resolve_specific_s (c);
3638           break;
3639
3640         case PTYPE_UNKNOWN:
3641           t = resolve_unknown_s (c);
3642           break;
3643
3644         default:
3645           gfc_internal_error ("resolve_subroutine(): bad function type");
3646         }
3647     }
3648
3649   /* Some checks of elemental subroutine actual arguments.  */
3650   if (resolve_elemental_actual (NULL, c) == FAILURE)
3651     return FAILURE;
3652
3653   return t;
3654 }
3655
3656
3657 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3658    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3659    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3660    if their shapes do not match.  If either op1->shape or op2->shape is
3661    NULL, return SUCCESS.  */
3662
3663 static gfc_try
3664 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3665 {
3666   gfc_try t;
3667   int i;
3668
3669   t = SUCCESS;
3670
3671   if (op1->shape != NULL && op2->shape != NULL)
3672     {
3673       for (i = 0; i < op1->rank; i++)
3674         {
3675           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3676            {
3677              gfc_error ("Shapes for operands at %L and %L are not conformable",
3678                          &op1->where, &op2->where);
3679              t = FAILURE;
3680              break;
3681            }
3682         }
3683     }
3684
3685   return t;
3686 }
3687
3688
3689 /* Resolve an operator expression node.  This can involve replacing the
3690    operation with a user defined function call.  */
3691
3692 static gfc_try
3693 resolve_operator (gfc_expr *e)
3694 {
3695   gfc_expr *op1, *op2;
3696   char msg[200];
3697   bool dual_locus_error;
3698   gfc_try t;
3699
3700   /* Resolve all subnodes-- give them types.  */
3701
3702   switch (e->value.op.op)
3703     {
3704     default:
3705       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3706         return FAILURE;
3707
3708     /* Fall through...  */
3709
3710     case INTRINSIC_NOT:
3711     case INTRINSIC_UPLUS:
3712     case INTRINSIC_UMINUS:
3713     case INTRINSIC_PARENTHESES:
3714       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3715         return FAILURE;
3716       break;
3717     }
3718
3719   /* Typecheck the new node.  */
3720
3721   op1 = e->value.op.op1;
3722   op2 = e->value.op.op2;
3723   dual_locus_error = false;
3724
3725   if ((op1 && op1->expr_type == EXPR_NULL)
3726       || (op2 && op2->expr_type == EXPR_NULL))
3727     {
3728       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3729       goto bad_op;
3730     }
3731
3732   switch (e->value.op.op)
3733     {
3734     case INTRINSIC_UPLUS:
3735     case INTRINSIC_UMINUS:
3736       if (op1->ts.type == BT_INTEGER
3737           || op1->ts.type == BT_REAL
3738           || op1->ts.type == BT_COMPLEX)
3739         {
3740           e->ts = op1->ts;
3741           break;
3742         }
3743
3744       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3745                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3746       goto bad_op;
3747
3748     case INTRINSIC_PLUS:
3749     case INTRINSIC_MINUS:
3750     case INTRINSIC_TIMES:
3751     case INTRINSIC_DIVIDE:
3752     case INTRINSIC_POWER:
3753       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3754         {
3755           gfc_type_convert_binary (e, 1);
3756           break;
3757         }
3758
3759       sprintf (msg,
3760                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3761                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3762                gfc_typename (&op2->ts));
3763       goto bad_op;
3764
3765     case INTRINSIC_CONCAT:
3766       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3767           && op1->ts.kind == op2->ts.kind)
3768         {
3769           e->ts.type = BT_CHARACTER;
3770           e->ts.kind = op1->ts.kind;
3771           break;
3772         }
3773
3774       sprintf (msg,
3775                _("Operands of string concatenation operator at %%L are %s/%s"),
3776                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3777       goto bad_op;
3778
3779     case INTRINSIC_AND:
3780     case INTRINSIC_OR:
3781     case INTRINSIC_EQV:
3782     case INTRINSIC_NEQV:
3783       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3784         {
3785           e->ts.type = BT_LOGICAL;
3786           e->ts.kind = gfc_kind_max (op1, op2);
3787           if (op1->ts.kind < e->ts.kind)
3788             gfc_convert_type (op1, &e->ts, 2);
3789           else if (op2->ts.kind < e->ts.kind)
3790             gfc_convert_type (op2, &e->ts, 2);
3791           break;
3792         }
3793
3794       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3795                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3796                gfc_typename (&op2->ts));
3797
3798       goto bad_op;
3799
3800     case INTRINSIC_NOT:
3801       if (op1->ts.type == BT_LOGICAL)
3802         {
3803           e->ts.type = BT_LOGICAL;
3804           e->ts.kind = op1->ts.kind;
3805           break;
3806         }
3807
3808       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3809                gfc_typename (&op1->ts));
3810       goto bad_op;
3811
3812     case INTRINSIC_GT:
3813     case INTRINSIC_GT_OS:
3814     case INTRINSIC_GE:
3815     case INTRINSIC_GE_OS:
3816     case INTRINSIC_LT:
3817     case INTRINSIC_LT_OS:
3818     case INTRINSIC_LE:
3819     case INTRINSIC_LE_OS:
3820       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3821         {
3822           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3823           goto bad_op;
3824         }
3825
3826       /* Fall through...  */
3827
3828     case INTRINSIC_EQ:
3829     case INTRINSIC_EQ_OS:
3830     case INTRINSIC_NE:
3831     case INTRINSIC_NE_OS:
3832       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3833           && op1->ts.kind == op2->ts.kind)
3834         {
3835           e->ts.type = BT_LOGICAL;
3836           e->ts.kind = gfc_default_logical_kind;
3837           break;
3838         }
3839
3840       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3841         {
3842           gfc_type_convert_binary (e, 1);
3843
3844           e->ts.type = BT_LOGICAL;
3845           e->ts.kind = gfc_default_logical_kind;
3846           break;
3847         }
3848
3849       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3850         sprintf (msg,
3851                  _("Logicals at %%L must be compared with %s instead of %s"),
3852                  (e->value.op.op == INTRINSIC_EQ 
3853                   || e->value.op.op == INTRINSIC_EQ_OS)
3854                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3855       else
3856         sprintf (msg,
3857                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3858                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3859                  gfc_typename (&op2->ts));
3860
3861       goto bad_op;
3862
3863     case INTRINSIC_USER:
3864       if (e->value.op.uop->op == NULL)
3865         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3866       else if (op2 == NULL)
3867         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3868                  e->value.op.uop->name, gfc_typename (&op1->ts));
3869       else
3870         {
3871           sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3872                    e->value.op.uop->name, gfc_typename (&op1->ts),
3873                    gfc_typename (&op2->ts));
3874           e->value.op.uop->op->sym->attr.referenced = 1;
3875         }
3876
3877       goto bad_op;
3878
3879     case INTRINSIC_PARENTHESES:
3880       e->ts = op1->ts;
3881       if (e->ts.type == BT_CHARACTER)
3882         e->ts.u.cl = op1->ts.u.cl;
3883       break;
3884
3885     default:
3886       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3887     }
3888
3889   /* Deal with arrayness of an operand through an operator.  */
3890
3891   t = SUCCESS;
3892
3893   switch (e->value.op.op)
3894     {
3895     case INTRINSIC_PLUS:
3896     case INTRINSIC_MINUS:
3897     case INTRINSIC_TIMES:
3898     case INTRINSIC_DIVIDE:
3899     case INTRINSIC_POWER:
3900     case INTRINSIC_CONCAT:
3901     case INTRINSIC_AND:
3902     case INTRINSIC_OR:
3903     case INTRINSIC_EQV:
3904     case INTRINSIC_NEQV:
3905     case INTRINSIC_EQ:
3906     case INTRINSIC_EQ_OS:
3907     case INTRINSIC_NE:
3908     case INTRINSIC_NE_OS:
3909     case INTRINSIC_GT:
3910     case INTRINSIC_GT_OS:
3911     case INTRINSIC_GE:
3912     case INTRINSIC_GE_OS:
3913     case INTRINSIC_LT:
3914     case INTRINSIC_LT_OS:
3915     case INTRINSIC_LE:
3916     case INTRINSIC_LE_OS:
3917
3918       if (op1->rank == 0 && op2->rank == 0)
3919         e->rank = 0;
3920
3921       if (op1->rank == 0 && op2->rank != 0)
3922         {
3923           e->rank = op2->rank;
3924
3925           if (e->shape == NULL)
3926             e->shape = gfc_copy_shape (op2->shape, op2->rank);
3927         }
3928
3929       if (op1->rank != 0 && op2->rank == 0)
3930         {
3931           e->rank = op1->rank;
3932
3933           if (e->shape == NULL)
3934             e->shape = gfc_copy_shape (op1->shape, op1->rank);
3935         }
3936
3937       if (op1->rank != 0 && op2->rank != 0)
3938         {
3939           if (op1->rank == op2->rank)
3940             {
3941               e->rank = op1->rank;
3942               if (e->shape == NULL)
3943                 {
3944                   t = compare_shapes (op1, op2);
3945                   if (t == FAILURE)
3946                     e->shape = NULL;
3947                   else
3948                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
3949                 }
3950             }
3951           else
3952             {
3953               /* Allow higher level expressions to work.  */
3954               e->rank = 0;
3955
3956               /* Try user-defined operators, and otherwise throw an error.  */
3957               dual_locus_error = true;
3958               sprintf (msg,
3959                        _("Inconsistent ranks for operator at %%L and %%L"));
3960               goto bad_op;
3961             }
3962         }
3963
3964       break;
3965
3966     case INTRINSIC_PARENTHESES:
3967     case INTRINSIC_NOT:
3968     case INTRINSIC_UPLUS:
3969     case INTRINSIC_UMINUS:
3970       /* Simply copy arrayness attribute */
3971       e->rank = op1->rank;
3972
3973       if (e->shape == NULL)
3974         e->shape = gfc_copy_shape (op1->shape, op1->rank);
3975
3976       break;
3977
3978     default:
3979       break;
3980     }
3981
3982   /* Attempt to simplify the expression.  */
3983   if (t == SUCCESS)
3984     {
3985       t = gfc_simplify_expr (e, 0);
3986       /* Some calls do not succeed in simplification and return FAILURE
3987          even though there is no error; e.g. variable references to
3988          PARAMETER arrays.  */
3989       if (!gfc_is_constant_expr (e))
3990         t = SUCCESS;
3991     }
3992   return t;
3993
3994 bad_op:
3995
3996   {
3997     bool real_error;
3998     if (gfc_extend_expr (e, &real_error) == SUCCESS)
3999       return SUCCESS;
4000
4001     if (real_error)
4002       return FAILURE;
4003   }
4004
4005   if (dual_locus_error)
4006     gfc_error (msg, &op1->where, &op2->where);
4007   else
4008     gfc_error (msg, &e->where);
4009
4010   return FAILURE;
4011 }
4012
4013
4014 /************** Array resolution subroutines **************/
4015
4016 typedef enum
4017 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
4018 comparison;
4019
4020 /* Compare two integer expressions.  */
4021
4022 static comparison
4023 compare_bound (gfc_expr *a, gfc_expr *b)
4024 {
4025   int i;
4026
4027   if (a == NULL || a->expr_type != EXPR_CONSTANT
4028       || b == NULL || b->expr_type != EXPR_CONSTANT)
4029     return CMP_UNKNOWN;
4030
4031   /* If either of the types isn't INTEGER, we must have
4032      raised an error earlier.  */
4033
4034   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
4035     return CMP_UNKNOWN;
4036
4037   i = mpz_cmp (a->value.integer, b->value.integer);
4038
4039   if (i < 0)
4040     return CMP_LT;
4041   if (i > 0)
4042     return CMP_GT;
4043   return CMP_EQ;
4044 }
4045
4046
4047 /* Compare an integer expression with an integer.  */
4048
4049 static comparison
4050 compare_bound_int (gfc_expr *a, int b)
4051 {
4052   int i;
4053
4054   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4055     return CMP_UNKNOWN;
4056
4057   if (a->ts.type != BT_INTEGER)
4058     gfc_internal_error ("compare_bound_int(): Bad expression");
4059
4060   i = mpz_cmp_si (a->value.integer, b);
4061
4062   if (i < 0)
4063     return CMP_LT;
4064   if (i > 0)
4065     return CMP_GT;
4066   return CMP_EQ;
4067 }
4068
4069
4070 /* Compare an integer expression with a mpz_t.  */
4071
4072 static comparison
4073 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4074 {
4075   int i;
4076
4077   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4078     return CMP_UNKNOWN;
4079
4080   if (a->ts.type != BT_INTEGER)
4081     gfc_internal_error ("compare_bound_int(): Bad expression");
4082
4083   i = mpz_cmp (a->value.integer, b);
4084
4085   if (i < 0)
4086     return CMP_LT;
4087   if (i > 0)
4088     return CMP_GT;
4089   return CMP_EQ;
4090 }
4091
4092
4093 /* Compute the last value of a sequence given by a triplet.  
4094    Return 0 if it wasn't able to compute the last value, or if the
4095    sequence if empty, and 1 otherwise.  */
4096
4097 static int
4098 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4099                                 gfc_expr *stride, mpz_t last)
4100 {
4101   mpz_t rem;
4102
4103   if (start == NULL || start->expr_type != EXPR_CONSTANT
4104       || end == NULL || end->expr_type != EXPR_CONSTANT
4105       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4106     return 0;
4107
4108   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4109       || (stride != NULL && stride->ts.type != BT_INTEGER))
4110     return 0;
4111
4112   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4113     {
4114       if (compare_bound (start, end) == CMP_GT)
4115         return 0;
4116       mpz_set (last, end->value.integer);
4117       return 1;
4118     }
4119
4120   if (compare_bound_int (stride, 0) == CMP_GT)
4121     {
4122       /* Stride is positive */
4123       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4124         return 0;
4125     }
4126   else
4127     {
4128       /* Stride is negative */
4129       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4130         return 0;
4131     }
4132
4133   mpz_init (rem);
4134   mpz_sub (rem, end->value.integer, start->value.integer);
4135   mpz_tdiv_r (rem, rem, stride->value.integer);
4136   mpz_sub (last, end->value.integer, rem);
4137   mpz_clear (rem);
4138
4139   return 1;
4140 }
4141
4142
4143 /* Compare a single dimension of an array reference to the array
4144    specification.  */
4145
4146 static gfc_try
4147 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4148 {
4149   mpz_t last_value;
4150
4151   if (ar->dimen_type[i] == DIMEN_STAR)
4152     {
4153       gcc_assert (ar->stride[i] == NULL);
4154       /* This implies [*] as [*:] and [*:3] are not possible.  */
4155       if (ar->start[i] == NULL)
4156         {
4157           gcc_assert (ar->end[i] == NULL);
4158           return SUCCESS;
4159         }
4160     }
4161
4162 /* Given start, end and stride values, calculate the minimum and
4163    maximum referenced indexes.  */
4164
4165   switch (ar->dimen_type[i])
4166     {
4167     case DIMEN_VECTOR:
4168     case DIMEN_THIS_IMAGE:
4169       break;
4170
4171     case DIMEN_STAR:
4172     case DIMEN_ELEMENT:
4173       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4174         {
4175           if (i < as->rank)
4176             gfc_warning ("Array reference at %L is out of bounds "
4177                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4178                          mpz_get_si (ar->start[i]->value.integer),
4179                          mpz_get_si (as->lower[i]->value.integer), i+1);
4180           else
4181             gfc_warning ("Array reference at %L is out of bounds "
4182                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4183                          mpz_get_si (ar->start[i]->value.integer),
4184                          mpz_get_si (as->lower[i]->value.integer),
4185                          i + 1 - as->rank);
4186           return SUCCESS;
4187         }
4188       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4189         {
4190           if (i < as->rank)
4191             gfc_warning ("Array reference at %L is out of bounds "
4192                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4193                          mpz_get_si (ar->start[i]->value.integer),
4194                          mpz_get_si (as->upper[i]->value.integer), i+1);
4195           else
4196             gfc_warning ("Array reference at %L is out of bounds "
4197                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4198                          mpz_get_si (ar->start[i]->value.integer),
4199                          mpz_get_si (as->upper[i]->value.integer),
4200                          i + 1 - as->rank);
4201           return SUCCESS;
4202         }
4203
4204       break;
4205
4206     case DIMEN_RANGE:
4207       {
4208 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4209 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4210
4211         comparison comp_start_end = compare_bound (AR_START, AR_END);
4212
4213         /* Check for zero stride, which is not allowed.  */
4214         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4215           {
4216             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4217             return FAILURE;
4218           }
4219
4220         /* if start == len || (stride > 0 && start < len)
4221                            || (stride < 0 && start > len),
4222            then the array section contains at least one element.  In this
4223            case, there is an out-of-bounds access if
4224            (start < lower || start > upper).  */
4225         if (compare_bound (AR_START, AR_END) == CMP_EQ
4226             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4227                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4228             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4229                 && comp_start_end == CMP_GT))
4230           {
4231             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4232               {
4233                 gfc_warning ("Lower array reference at %L is out of bounds "
4234                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4235                        mpz_get_si (AR_START->value.integer),
4236                        mpz_get_si (as->lower[i]->value.integer), i+1);
4237                 return SUCCESS;
4238               }
4239             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4240               {
4241                 gfc_warning ("Lower array reference at %L is out of bounds "
4242                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4243                        mpz_get_si (AR_START->value.integer),
4244                        mpz_get_si (as->upper[i]->value.integer), i+1);
4245                 return SUCCESS;
4246               }
4247           }
4248
4249         /* If we can compute the highest index of the array section,
4250            then it also has to be between lower and upper.  */
4251         mpz_init (last_value);
4252         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4253                                             last_value))
4254           {
4255             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4256               {
4257                 gfc_warning ("Upper array reference at %L is out of bounds "
4258                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4259                        mpz_get_si (last_value),
4260                        mpz_get_si (as->lower[i]->value.integer), i+1);
4261                 mpz_clear (last_value);
4262                 return SUCCESS;
4263               }
4264             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4265               {
4266                 gfc_warning ("Upper array reference at %L is out of bounds "
4267                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4268                        mpz_get_si (last_value),
4269                        mpz_get_si (as->upper[i]->value.integer), i+1);
4270                 mpz_clear (last_value);
4271                 return SUCCESS;
4272               }
4273           }
4274         mpz_clear (last_value);
4275
4276 #undef AR_START
4277 #undef AR_END
4278       }
4279       break;
4280
4281     default:
4282       gfc_internal_error ("check_dimension(): Bad array reference");
4283     }
4284
4285   return SUCCESS;
4286 }
4287
4288
4289 /* Compare an array reference with an array specification.  */
4290
4291 static gfc_try
4292 compare_spec_to_ref (gfc_array_ref *ar)
4293 {
4294   gfc_array_spec *as;
4295   int i;
4296
4297   as = ar->as;
4298   i = as->rank - 1;
4299   /* TODO: Full array sections are only allowed as actual parameters.  */
4300   if (as->type == AS_ASSUMED_SIZE
4301       && (/*ar->type == AR_FULL
4302           ||*/ (ar->type == AR_SECTION
4303               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4304     {
4305       gfc_error ("Rightmost upper bound of assumed size array section "
4306                  "not specified at %L", &ar->where);
4307       return FAILURE;
4308     }
4309
4310   if (ar->type == AR_FULL)
4311     return SUCCESS;
4312
4313   if (as->rank != ar->dimen)
4314     {
4315       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4316                  &ar->where, ar->dimen, as->rank);
4317       return FAILURE;
4318     }
4319
4320   /* ar->codimen == 0 is a local array.  */
4321   if (as->corank != ar->codimen && ar->codimen != 0)
4322     {
4323       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4324                  &ar->where, ar->codimen, as->corank);
4325       return FAILURE;
4326     }
4327
4328   for (i = 0; i < as->rank; i++)
4329     if (check_dimension (i, ar, as) == FAILURE)
4330       return FAILURE;
4331
4332   /* Local access has no coarray spec.  */
4333   if (ar->codimen != 0)
4334     for (i = as->rank; i < as->rank + as->corank; i++)
4335       {
4336         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate
4337             && ar->dimen_type[i] != DIMEN_THIS_IMAGE)
4338           {
4339             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4340                        i + 1 - as->rank, &ar->where);
4341             return FAILURE;
4342           }
4343         if (check_dimension (i, ar, as) == FAILURE)
4344           return FAILURE;
4345       }
4346
4347   if (as->corank && ar->codimen == 0)
4348     {
4349       int n;
4350       ar->codimen = as->corank;
4351       for (n = ar->dimen; n < ar->dimen + ar->codimen; n++)
4352         ar->dimen_type[n] = DIMEN_THIS_IMAGE;
4353     }
4354
4355   return SUCCESS;
4356 }
4357
4358
4359 /* Resolve one part of an array index.  */
4360
4361 static gfc_try
4362 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4363                      int force_index_integer_kind)
4364 {
4365   gfc_typespec ts;
4366
4367   if (index == NULL)
4368     return SUCCESS;
4369
4370   if (gfc_resolve_expr (index) == FAILURE)
4371     return FAILURE;
4372
4373   if (check_scalar && index->rank != 0)
4374     {
4375       gfc_error ("Array index at %L must be scalar", &index->where);
4376       return FAILURE;
4377     }
4378
4379   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4380     {
4381       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4382                  &index->where, gfc_basic_typename (index->ts.type));
4383       return FAILURE;
4384     }
4385
4386   if (index->ts.type == BT_REAL)
4387     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4388                         &index->where) == FAILURE)
4389       return FAILURE;
4390
4391   if ((index->ts.kind != gfc_index_integer_kind
4392        && force_index_integer_kind)
4393       || index->ts.type != BT_INTEGER)
4394     {
4395       gfc_clear_ts (&ts);
4396       ts.type = BT_INTEGER;
4397       ts.kind = gfc_index_integer_kind;
4398
4399       gfc_convert_type_warn (index, &ts, 2, 0);
4400     }
4401
4402   return SUCCESS;
4403 }
4404
4405 /* Resolve one part of an array index.  */
4406
4407 gfc_try
4408 gfc_resolve_index (gfc_expr *index, int check_scalar)
4409 {
4410   return gfc_resolve_index_1 (index, check_scalar, 1);
4411 }
4412
4413 /* Resolve a dim argument to an intrinsic function.  */
4414
4415 gfc_try
4416 gfc_resolve_dim_arg (gfc_expr *dim)
4417 {
4418   if (dim == NULL)
4419     return SUCCESS;
4420
4421   if (gfc_resolve_expr (dim) == FAILURE)
4422     return FAILURE;
4423
4424   if (dim->rank != 0)
4425     {
4426       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4427       return FAILURE;
4428
4429     }
4430
4431   if (dim->ts.type != BT_INTEGER)
4432     {
4433       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4434       return FAILURE;
4435     }
4436
4437   if (dim->ts.kind != gfc_index_integer_kind)
4438     {
4439       gfc_typespec ts;
4440
4441       gfc_clear_ts (&ts);
4442       ts.type = BT_INTEGER;
4443       ts.kind = gfc_index_integer_kind;
4444
4445       gfc_convert_type_warn (dim, &ts, 2, 0);
4446     }
4447
4448   return SUCCESS;
4449 }
4450
4451 /* Given an expression that contains array references, update those array
4452    references to point to the right array specifications.  While this is
4453    filled in during matching, this information is difficult to save and load
4454    in a module, so we take care of it here.
4455
4456    The idea here is that the original array reference comes from the
4457    base symbol.  We traverse the list of reference structures, setting
4458    the stored reference to references.  Component references can
4459    provide an additional array specification.  */
4460
4461 static void
4462 find_array_spec (gfc_expr *e)
4463 {
4464   gfc_array_spec *as;
4465   gfc_component *c;
4466   gfc_symbol *derived;
4467   gfc_ref *ref;
4468
4469   if (e->symtree->n.sym->ts.type == BT_CLASS)
4470     as = CLASS_DATA (e->symtree->n.sym)->as;
4471   else
4472     as = e->symtree->n.sym->as;
4473   derived = NULL;
4474
4475   for (ref = e->ref; ref; ref = ref->next)
4476     switch (ref->type)
4477       {
4478       case REF_ARRAY:
4479         if (as == NULL)
4480           gfc_internal_error ("find_array_spec(): Missing spec");
4481
4482         ref->u.ar.as = as;
4483         as = NULL;
4484         break;
4485
4486       case REF_COMPONENT:
4487         if (derived == NULL)
4488           derived = e->symtree->n.sym->ts.u.derived;
4489
4490         if (derived->attr.is_class)
4491           derived = derived->components->ts.u.derived;
4492
4493         c = derived->components;
4494
4495         for (; c; c = c->next)
4496           if (c == ref->u.c.component)
4497             {
4498               /* Track the sequence of component references.  */
4499               if (c->ts.type == BT_DERIVED)
4500                 derived = c->ts.u.derived;
4501               break;
4502             }
4503
4504         if (c == NULL)
4505           gfc_internal_error ("find_array_spec(): Component not found");
4506
4507         if (c->attr.dimension)
4508           {
4509             if (as != NULL)
4510               gfc_internal_error ("find_array_spec(): unused as(1)");
4511             as = c->as;
4512           }
4513
4514         break;
4515
4516       case REF_SUBSTRING:
4517         break;
4518       }
4519
4520   if (as != NULL)
4521     gfc_internal_error ("find_array_spec(): unused as(2)");
4522 }
4523
4524
4525 /* Resolve an array reference.  */
4526
4527 static gfc_try
4528 resolve_array_ref (gfc_array_ref *ar)
4529 {
4530   int i, check_scalar;
4531   gfc_expr *e;
4532
4533   for (i = 0; i < ar->dimen + ar->codimen; i++)
4534     {
4535       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4536
4537       /* Do not force gfc_index_integer_kind for the start.  We can
4538          do fine with any integer kind.  This avoids temporary arrays
4539          created for indexing with a vector.  */
4540       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4541         return FAILURE;
4542       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4543         return FAILURE;
4544       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4545         return FAILURE;
4546
4547       e = ar->start[i];
4548
4549       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4550         switch (e->rank)
4551           {
4552           case 0:
4553             ar->dimen_type[i] = DIMEN_ELEMENT;
4554             break;
4555
4556           case 1:
4557             ar->dimen_type[i] = DIMEN_VECTOR;
4558             if (e->expr_type == EXPR_VARIABLE
4559                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4560               ar->start[i] = gfc_get_parentheses (e);
4561             break;
4562
4563           default:
4564             gfc_error ("Array index at %L is an array of rank %d",
4565                        &ar->c_where[i], e->rank);
4566             return FAILURE;
4567           }
4568
4569       /* Fill in the upper bound, which may be lower than the
4570          specified one for something like a(2:10:5), which is
4571          identical to a(2:7:5).  Only relevant for strides not equal
4572          to one.  Don't try a division by zero.  */
4573       if (ar->dimen_type[i] == DIMEN_RANGE
4574           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4575           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0
4576           && mpz_cmp_si (ar->stride[i]->value.integer, 0L) != 0)
4577         {
4578           mpz_t size, end;
4579
4580           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4581             {
4582               if (ar->end[i] == NULL)
4583                 {
4584                   ar->end[i] =
4585                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4586                                            &ar->where);
4587                   mpz_set (ar->end[i]->value.integer, end);
4588                 }
4589               else if (ar->end[i]->ts.type == BT_INTEGER
4590                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4591                 {
4592                   mpz_set (ar->end[i]->value.integer, end);
4593                 }
4594               else
4595                 gcc_unreachable ();
4596
4597               mpz_clear (size);
4598               mpz_clear (end);
4599             }
4600         }
4601     }
4602
4603   if (ar->type == AR_FULL && ar->as->rank == 0)
4604     ar->type = AR_ELEMENT;
4605
4606   /* If the reference type is unknown, figure out what kind it is.  */
4607
4608   if (ar->type == AR_UNKNOWN)
4609     {
4610       ar->type = AR_ELEMENT;
4611       for (i = 0; i < ar->dimen; i++)
4612         if (ar->dimen_type[i] == DIMEN_RANGE
4613             || ar->dimen_type[i] == DIMEN_VECTOR)
4614           {
4615             ar->type = AR_SECTION;
4616             break;
4617           }
4618     }
4619
4620   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4621     return FAILURE;
4622
4623   return SUCCESS;
4624 }
4625
4626
4627 static gfc_try
4628 resolve_substring (gfc_ref *ref)
4629 {
4630   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4631
4632   if (ref->u.ss.start != NULL)
4633     {
4634       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4635         return FAILURE;
4636
4637       if (ref->u.ss.start->ts.type != BT_INTEGER)
4638         {
4639           gfc_error ("Substring start index at %L must be of type INTEGER",
4640                      &ref->u.ss.start->where);
4641           return FAILURE;
4642         }
4643
4644       if (ref->u.ss.start->rank != 0)
4645         {
4646           gfc_error ("Substring start index at %L must be scalar",
4647                      &ref->u.ss.start->where);
4648           return FAILURE;
4649         }
4650
4651       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4652           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4653               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4654         {
4655           gfc_error ("Substring start index at %L is less than one",
4656                      &ref->u.ss.start->where);
4657           return FAILURE;
4658         }
4659     }
4660
4661   if (ref->u.ss.end != NULL)
4662     {
4663       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4664         return FAILURE;
4665
4666       if (ref->u.ss.end->ts.type != BT_INTEGER)
4667         {
4668           gfc_error ("Substring end index at %L must be of type INTEGER",
4669                      &ref->u.ss.end->where);
4670           return FAILURE;
4671         }
4672
4673       if (ref->u.ss.end->rank != 0)
4674         {
4675           gfc_error ("Substring end index at %L must be scalar",
4676                      &ref->u.ss.end->where);
4677           return FAILURE;
4678         }
4679
4680       if (ref->u.ss.length != NULL
4681           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4682           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4683               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4684         {
4685           gfc_error ("Substring end index at %L exceeds the string length",
4686                      &ref->u.ss.start->where);
4687           return FAILURE;
4688         }
4689
4690       if (compare_bound_mpz_t (ref->u.ss.end,
4691                                gfc_integer_kinds[k].huge) == CMP_GT
4692           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4693               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4694         {
4695           gfc_error ("Substring end index at %L is too large",
4696                      &ref->u.ss.end->where);
4697           return FAILURE;
4698         }
4699     }
4700
4701   return SUCCESS;
4702 }
4703
4704
4705 /* This function supplies missing substring charlens.  */
4706
4707 void
4708 gfc_resolve_substring_charlen (gfc_expr *e)
4709 {
4710   gfc_ref *char_ref;
4711   gfc_expr *start, *end;
4712
4713   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4714     if (char_ref->type == REF_SUBSTRING)
4715       break;
4716
4717   if (!char_ref)
4718     return;
4719
4720   gcc_assert (char_ref->next == NULL);
4721
4722   if (e->ts.u.cl)
4723     {
4724       if (e->ts.u.cl->length)
4725         gfc_free_expr (e->ts.u.cl->length);
4726       else if (e->expr_type == EXPR_VARIABLE
4727                  && e->symtree->n.sym->attr.dummy)
4728         return;
4729     }
4730
4731   e->ts.type = BT_CHARACTER;
4732   e->ts.kind = gfc_default_character_kind;
4733
4734   if (!e->ts.u.cl)
4735     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4736
4737   if (char_ref->u.ss.start)
4738     start = gfc_copy_expr (char_ref->u.ss.start);
4739   else
4740     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4741
4742   if (char_ref->u.ss.end)
4743     end = gfc_copy_expr (char_ref->u.ss.end);
4744   else if (e->expr_type == EXPR_VARIABLE)
4745     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4746   else
4747     end = NULL;
4748
4749   if (!start || !end)
4750     return;
4751
4752   /* Length = (end - start +1).  */
4753   e->ts.u.cl->length = gfc_subtract (end, start);
4754   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4755                                 gfc_get_int_expr (gfc_default_integer_kind,
4756                                                   NULL, 1));
4757
4758   e->ts.u.cl->length->ts.type = BT_INTEGER;
4759   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4760
4761   /* Make sure that the length is simplified.  */
4762   gfc_simplify_expr (e->ts.u.cl->length, 1);
4763   gfc_resolve_expr (e->ts.u.cl->length);
4764 }
4765
4766
4767 /* Resolve subtype references.  */
4768
4769 static gfc_try
4770 resolve_ref (gfc_expr *expr)
4771 {
4772   int current_part_dimension, n_components, seen_part_dimension;
4773   gfc_ref *ref;
4774
4775   for (ref = expr->ref; ref; ref = ref->next)
4776     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4777       {
4778         find_array_spec (expr);
4779         break;
4780       }
4781
4782   for (ref = expr->ref; ref; ref = ref->next)
4783     switch (ref->type)
4784       {
4785       case REF_ARRAY:
4786         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4787           return FAILURE;
4788         break;
4789
4790       case REF_COMPONENT:
4791         break;
4792
4793       case REF_SUBSTRING:
4794         resolve_substring (ref);
4795         break;
4796       }
4797
4798   /* Check constraints on part references.  */
4799
4800   current_part_dimension = 0;
4801   seen_part_dimension = 0;
4802   n_components = 0;
4803
4804   for (ref = expr->ref; ref; ref = ref->next)
4805     {
4806       switch (ref->type)
4807         {
4808         case REF_ARRAY:
4809           switch (ref->u.ar.type)
4810             {
4811             case AR_FULL:
4812               /* Coarray scalar.  */
4813               if (ref->u.ar.as->rank == 0)
4814                 {
4815                   current_part_dimension = 0;
4816                   break;
4817                 }
4818               /* Fall through.  */
4819             case AR_SECTION:
4820               current_part_dimension = 1;
4821               break;
4822
4823             case AR_ELEMENT:
4824               current_part_dimension = 0;
4825               break;
4826
4827             case AR_UNKNOWN:
4828               gfc_internal_error ("resolve_ref(): Bad array reference");
4829             }
4830
4831           break;
4832
4833         case REF_COMPONENT:
4834           if (current_part_dimension || seen_part_dimension)
4835             {
4836               /* F03:C614.  */
4837               if (ref->u.c.component->attr.pointer
4838                   || ref->u.c.component->attr.proc_pointer)
4839                 {
4840                   gfc_error ("Component to the right of a part reference "
4841                              "with nonzero rank must not have the POINTER "
4842                              "attribute at %L", &expr->where);
4843                   return FAILURE;
4844                 }
4845               else if (ref->u.c.component->attr.allocatable)
4846                 {
4847                   gfc_error ("Component to the right of a part reference "
4848                              "with nonzero rank must not have the ALLOCATABLE "
4849                              "attribute at %L", &expr->where);
4850                   return FAILURE;
4851                 }
4852             }
4853
4854           n_components++;
4855           break;
4856
4857         case REF_SUBSTRING:
4858           break;
4859         }
4860
4861       if (((ref->type == REF_COMPONENT && n_components > 1)
4862            || ref->next == NULL)
4863           && current_part_dimension
4864           && seen_part_dimension)
4865         {
4866           gfc_error ("Two or more part references with nonzero rank must "
4867                      "not be specified at %L", &expr->where);
4868           return FAILURE;
4869         }
4870
4871       if (ref->type == REF_COMPONENT)
4872         {
4873           if (current_part_dimension)
4874             seen_part_dimension = 1;
4875
4876           /* reset to make sure */
4877           current_part_dimension = 0;
4878         }
4879     }
4880
4881   return SUCCESS;
4882 }
4883
4884
4885 /* Given an expression, determine its shape.  This is easier than it sounds.
4886    Leaves the shape array NULL if it is not possible to determine the shape.  */
4887
4888 static void
4889 expression_shape (gfc_expr *e)
4890 {
4891   mpz_t array[GFC_MAX_DIMENSIONS];
4892   int i;
4893
4894   if (e->rank == 0 || e->shape != NULL)
4895     return;
4896
4897   for (i = 0; i < e->rank; i++)
4898     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4899       goto fail;
4900
4901   e->shape = gfc_get_shape (e->rank);
4902
4903   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4904
4905   return;
4906
4907 fail:
4908   for (i--; i >= 0; i--)
4909     mpz_clear (array[i]);
4910 }
4911
4912
4913 /* Given a variable expression node, compute the rank of the expression by
4914    examining the base symbol and any reference structures it may have.  */
4915
4916 static void
4917 expression_rank (gfc_expr *e)
4918 {
4919   gfc_ref *ref;
4920   int i, rank;
4921
4922   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4923      could lead to serious confusion...  */
4924   gcc_assert (e->expr_type != EXPR_COMPCALL);
4925
4926   if (e->ref == NULL)
4927     {
4928       if (e->expr_type == EXPR_ARRAY)
4929         goto done;
4930       /* Constructors can have a rank different from one via RESHAPE().  */
4931
4932       if (e->symtree == NULL)
4933         {
4934           e->rank = 0;
4935           goto done;
4936         }
4937
4938       e->rank = (e->symtree->n.sym->as == NULL)
4939                 ? 0 : e->symtree->n.sym->as->rank;
4940       goto done;
4941     }
4942
4943   rank = 0;
4944
4945   for (ref = e->ref; ref; ref = ref->next)
4946     {
4947       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
4948           && ref->u.c.component->attr.function && !ref->next)
4949         rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
4950
4951       if (ref->type != REF_ARRAY)
4952         continue;
4953
4954       if (ref->u.ar.type == AR_FULL)
4955         {
4956           rank = ref->u.ar.as->rank;
4957           break;
4958         }
4959
4960       if (ref->u.ar.type == AR_SECTION)
4961         {
4962           /* Figure out the rank of the section.  */
4963           if (rank != 0)
4964             gfc_internal_error ("expression_rank(): Two array specs");
4965
4966           for (i = 0; i < ref->u.ar.dimen; i++)
4967             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
4968                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
4969               rank++;
4970
4971           break;
4972         }
4973     }
4974
4975   e->rank = rank;
4976
4977 done:
4978   expression_shape (e);
4979 }
4980
4981
4982 /* Resolve a variable expression.  */
4983
4984 static gfc_try
4985 resolve_variable (gfc_expr *e)
4986 {
4987   gfc_symbol *sym;
4988   gfc_try t;
4989
4990   t = SUCCESS;
4991
4992   if (e->symtree == NULL)
4993     return FAILURE;
4994   sym = e->symtree->n.sym;
4995
4996   /* If this is an associate-name, it may be parsed with an array reference
4997      in error even though the target is scalar.  Fail directly in this case.  */
4998   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
4999     return FAILURE;
5000
5001   /* On the other hand, the parser may not have known this is an array;
5002      in this case, we have to add a FULL reference.  */
5003   if (sym->assoc && sym->attr.dimension && !e->ref)
5004     {
5005       e->ref = gfc_get_ref ();
5006       e->ref->type = REF_ARRAY;
5007       e->ref->u.ar.type = AR_FULL;
5008       e->ref->u.ar.dimen = 0;
5009     }
5010
5011   if (e->ref && resolve_ref (e) == FAILURE)
5012     return FAILURE;
5013
5014   if (sym->attr.flavor == FL_PROCEDURE
5015       && (!sym->attr.function
5016           || (sym->attr.function && sym->result
5017               && sym->result->attr.proc_pointer
5018               && !sym->result->attr.function)))
5019     {
5020       e->ts.type = BT_PROCEDURE;
5021       goto resolve_procedure;
5022     }
5023
5024   if (sym->ts.type != BT_UNKNOWN)
5025     gfc_variable_attr (e, &e->ts);
5026   else
5027     {
5028       /* Must be a simple variable reference.  */
5029       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
5030         return FAILURE;
5031       e->ts = sym->ts;
5032     }
5033
5034   if (check_assumed_size_reference (sym, e))
5035     return FAILURE;
5036
5037   /* Deal with forward references to entries during resolve_code, to
5038      satisfy, at least partially, 12.5.2.5.  */
5039   if (gfc_current_ns->entries
5040       && current_entry_id == sym->entry_id
5041       && cs_base
5042       && cs_base->current
5043       && cs_base->current->op != EXEC_ENTRY)
5044     {
5045       gfc_entry_list *entry;
5046       gfc_formal_arglist *formal;
5047       int n;
5048       bool seen;
5049
5050       /* If the symbol is a dummy...  */
5051       if (sym->attr.dummy && sym->ns == gfc_current_ns)
5052         {
5053           entry = gfc_current_ns->entries;
5054           seen = false;
5055
5056           /* ...test if the symbol is a parameter of previous entries.  */
5057           for (; entry && entry->id <= current_entry_id; entry = entry->next)
5058             for (formal = entry->sym->formal; formal; formal = formal->next)
5059               {
5060                 if (formal->sym && sym->name == formal->sym->name)
5061                   seen = true;
5062               }
5063
5064           /*  If it has not been seen as a dummy, this is an error.  */
5065           if (!seen)
5066             {
5067               if (specification_expr)
5068                 gfc_error ("Variable '%s', used in a specification expression"
5069                            ", is referenced at %L before the ENTRY statement "
5070                            "in which it is a parameter",
5071                            sym->name, &cs_base->current->loc);
5072               else
5073                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5074                            "statement in which it is a parameter",
5075                            sym->name, &cs_base->current->loc);
5076               t = FAILURE;
5077             }
5078         }
5079
5080       /* Now do the same check on the specification expressions.  */
5081       specification_expr = 1;
5082       if (sym->ts.type == BT_CHARACTER
5083           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5084         t = FAILURE;
5085
5086       if (sym->as)
5087         for (n = 0; n < sym->as->rank; n++)
5088           {
5089              specification_expr = 1;
5090              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5091                t = FAILURE;
5092              specification_expr = 1;
5093              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5094                t = FAILURE;
5095           }
5096       specification_expr = 0;
5097
5098       if (t == SUCCESS)
5099         /* Update the symbol's entry level.  */
5100         sym->entry_id = current_entry_id + 1;
5101     }
5102
5103   /* If a symbol has been host_associated mark it.  This is used latter,
5104      to identify if aliasing is possible via host association.  */
5105   if (sym->attr.flavor == FL_VARIABLE
5106         && gfc_current_ns->parent
5107         && (gfc_current_ns->parent == sym->ns
5108               || (gfc_current_ns->parent->parent
5109                     && gfc_current_ns->parent->parent == sym->ns)))
5110     sym->attr.host_assoc = 1;
5111
5112 resolve_procedure:
5113   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5114     t = FAILURE;
5115
5116   /* F2008, C617 and C1229.  */
5117   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5118       && gfc_is_coindexed (e))
5119     {
5120       gfc_ref *ref, *ref2 = NULL;
5121
5122       for (ref = e->ref; ref; ref = ref->next)
5123         {
5124           if (ref->type == REF_COMPONENT)
5125             ref2 = ref;
5126           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5127             break;
5128         }
5129
5130       for ( ; ref; ref = ref->next)
5131         if (ref->type == REF_COMPONENT)
5132           break;
5133
5134       /* Expression itself is not coindexed object.  */
5135       if (ref && e->ts.type == BT_CLASS)
5136         {
5137           gfc_error ("Polymorphic subobject of coindexed object at %L",
5138                      &e->where);
5139           t = FAILURE;
5140         }
5141
5142       /* Expression itself is coindexed object.  */
5143       if (ref == NULL)
5144         {
5145           gfc_component *c;
5146           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5147           for ( ; c; c = c->next)
5148             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5149               {
5150                 gfc_error ("Coindexed object with polymorphic allocatable "
5151                          "subcomponent at %L", &e->where);
5152                 t = FAILURE;
5153                 break;
5154               }
5155         }
5156     }
5157
5158   return t;
5159 }
5160
5161
5162 /* Checks to see that the correct symbol has been host associated.
5163    The only situation where this arises is that in which a twice
5164    contained function is parsed after the host association is made.
5165    Therefore, on detecting this, change the symbol in the expression
5166    and convert the array reference into an actual arglist if the old
5167    symbol is a variable.  */
5168 static bool
5169 check_host_association (gfc_expr *e)
5170 {
5171   gfc_symbol *sym, *old_sym;
5172   gfc_symtree *st;
5173   int n;
5174   gfc_ref *ref;
5175   gfc_actual_arglist *arg, *tail = NULL;
5176   bool retval = e->expr_type == EXPR_FUNCTION;
5177
5178   /*  If the expression is the result of substitution in
5179       interface.c(gfc_extend_expr) because there is no way in
5180       which the host association can be wrong.  */
5181   if (e->symtree == NULL
5182         || e->symtree->n.sym == NULL
5183         || e->user_operator)
5184     return retval;
5185
5186   old_sym = e->symtree->n.sym;
5187
5188   if (gfc_current_ns->parent
5189         && old_sym->ns != gfc_current_ns)
5190     {
5191       /* Use the 'USE' name so that renamed module symbols are
5192          correctly handled.  */
5193       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5194
5195       if (sym && old_sym != sym
5196               && sym->ts.type == old_sym->ts.type
5197               && sym->attr.flavor == FL_PROCEDURE
5198               && sym->attr.contained)
5199         {
5200           /* Clear the shape, since it might not be valid.  */
5201           if (e->shape != NULL)
5202             gfc_free_shape (&e->shape, e->rank);
5203
5204           /* Give the expression the right symtree!  */
5205           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5206           gcc_assert (st != NULL);
5207
5208           if (old_sym->attr.flavor == FL_PROCEDURE
5209                 || e->expr_type == EXPR_FUNCTION)
5210             {
5211               /* Original was function so point to the new symbol, since
5212                  the actual argument list is already attached to the
5213                  expression. */
5214               e->value.function.esym = NULL;
5215               e->symtree = st;
5216             }
5217           else
5218             {
5219               /* Original was variable so convert array references into
5220                  an actual arglist. This does not need any checking now
5221                  since resolve_function will take care of it.  */
5222               e->value.function.actual = NULL;
5223               e->expr_type = EXPR_FUNCTION;
5224               e->symtree = st;
5225
5226               /* Ambiguity will not arise if the array reference is not
5227                  the last reference.  */
5228               for (ref = e->ref; ref; ref = ref->next)
5229                 if (ref->type == REF_ARRAY && ref->next == NULL)
5230                   break;
5231
5232               gcc_assert (ref->type == REF_ARRAY);
5233
5234               /* Grab the start expressions from the array ref and
5235                  copy them into actual arguments.  */
5236               for (n = 0; n < ref->u.ar.dimen; n++)
5237                 {
5238                   arg = gfc_get_actual_arglist ();
5239                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5240                   if (e->value.function.actual == NULL)
5241                     tail = e->value.function.actual = arg;
5242                   else
5243                     {
5244                       tail->next = arg;
5245                       tail = arg;
5246                     }
5247                 }
5248
5249               /* Dump the reference list and set the rank.  */
5250               gfc_free_ref_list (e->ref);
5251               e->ref = NULL;
5252               e->rank = sym->as ? sym->as->rank : 0;
5253             }
5254
5255           gfc_resolve_expr (e);
5256           sym->refs++;
5257         }
5258     }
5259   /* This might have changed!  */
5260   return e->expr_type == EXPR_FUNCTION;
5261 }
5262
5263
5264 static void
5265 gfc_resolve_character_operator (gfc_expr *e)
5266 {
5267   gfc_expr *op1 = e->value.op.op1;
5268   gfc_expr *op2 = e->value.op.op2;
5269   gfc_expr *e1 = NULL;
5270   gfc_expr *e2 = NULL;
5271
5272   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5273
5274   if (op1->ts.u.cl && op1->ts.u.cl->length)
5275     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5276   else if (op1->expr_type == EXPR_CONSTANT)
5277     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5278                            op1->value.character.length);
5279
5280   if (op2->ts.u.cl && op2->ts.u.cl->length)
5281     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5282   else if (op2->expr_type == EXPR_CONSTANT)
5283     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5284                            op2->value.character.length);
5285
5286   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5287
5288   if (!e1 || !e2)
5289     return;
5290
5291   e->ts.u.cl->length = gfc_add (e1, e2);
5292   e->ts.u.cl->length->ts.type = BT_INTEGER;
5293   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5294   gfc_simplify_expr (e->ts.u.cl->length, 0);
5295   gfc_resolve_expr (e->ts.u.cl->length);
5296
5297   return;
5298 }
5299
5300
5301 /*  Ensure that an character expression has a charlen and, if possible, a
5302     length expression.  */
5303
5304 static void
5305 fixup_charlen (gfc_expr *e)
5306 {
5307   /* The cases fall through so that changes in expression type and the need
5308      for multiple fixes are picked up.  In all circumstances, a charlen should
5309      be available for the middle end to hang a backend_decl on.  */
5310   switch (e->expr_type)
5311     {
5312     case EXPR_OP:
5313       gfc_resolve_character_operator (e);
5314
5315     case EXPR_ARRAY:
5316       if (e->expr_type == EXPR_ARRAY)
5317         gfc_resolve_character_array_constructor (e);
5318
5319     case EXPR_SUBSTRING:
5320       if (!e->ts.u.cl && e->ref)
5321         gfc_resolve_substring_charlen (e);
5322
5323     default:
5324       if (!e->ts.u.cl)
5325         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5326
5327       break;
5328     }
5329 }
5330
5331
5332 /* Update an actual argument to include the passed-object for type-bound
5333    procedures at the right position.  */
5334
5335 static gfc_actual_arglist*
5336 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5337                      const char *name)
5338 {
5339   gcc_assert (argpos > 0);
5340
5341   if (argpos == 1)
5342     {
5343       gfc_actual_arglist* result;
5344
5345       result = gfc_get_actual_arglist ();
5346       result->expr = po;
5347       result->next = lst;
5348       if (name)
5349         result->name = name;
5350
5351       return result;
5352     }
5353
5354   if (lst)
5355     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5356   else
5357     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5358   return lst;
5359 }
5360
5361
5362 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5363
5364 static gfc_expr*
5365 extract_compcall_passed_object (gfc_expr* e)
5366 {
5367   gfc_expr* po;
5368
5369   gcc_assert (e->expr_type == EXPR_COMPCALL);
5370
5371   if (e->value.compcall.base_object)
5372     po = gfc_copy_expr (e->value.compcall.base_object);
5373   else
5374     {
5375       po = gfc_get_expr ();
5376       po->expr_type = EXPR_VARIABLE;
5377       po->symtree = e->symtree;
5378       po->ref = gfc_copy_ref (e->ref);
5379       po->where = e->where;
5380     }
5381
5382   if (gfc_resolve_expr (po) == FAILURE)
5383     return NULL;
5384
5385   return po;
5386 }
5387
5388
5389 /* Update the arglist of an EXPR_COMPCALL expression to include the
5390    passed-object.  */
5391
5392 static gfc_try
5393 update_compcall_arglist (gfc_expr* e)
5394 {
5395   gfc_expr* po;
5396   gfc_typebound_proc* tbp;
5397
5398   tbp = e->value.compcall.tbp;
5399
5400   if (tbp->error)
5401     return FAILURE;
5402
5403   po = extract_compcall_passed_object (e);
5404   if (!po)
5405     return FAILURE;
5406
5407   if (tbp->nopass || e->value.compcall.ignore_pass)
5408     {
5409       gfc_free_expr (po);
5410       return SUCCESS;
5411     }
5412
5413   gcc_assert (tbp->pass_arg_num > 0);
5414   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5415                                                   tbp->pass_arg_num,
5416                                                   tbp->pass_arg);
5417
5418   return SUCCESS;
5419 }
5420
5421
5422 /* Extract the passed object from a PPC call (a copy of it).  */
5423
5424 static gfc_expr*
5425 extract_ppc_passed_object (gfc_expr *e)
5426 {
5427   gfc_expr *po;
5428   gfc_ref **ref;
5429
5430   po = gfc_get_expr ();
5431   po->expr_type = EXPR_VARIABLE;
5432   po->symtree = e->symtree;
5433   po->ref = gfc_copy_ref (e->ref);
5434   po->where = e->where;
5435
5436   /* Remove PPC reference.  */
5437   ref = &po->ref;
5438   while ((*ref)->next)
5439     ref = &(*ref)->next;
5440   gfc_free_ref_list (*ref);
5441   *ref = NULL;
5442
5443   if (gfc_resolve_expr (po) == FAILURE)
5444     return NULL;
5445
5446   return po;
5447 }
5448
5449
5450 /* Update the actual arglist of a procedure pointer component to include the
5451    passed-object.  */
5452
5453 static gfc_try
5454 update_ppc_arglist (gfc_expr* e)
5455 {
5456   gfc_expr* po;
5457   gfc_component *ppc;
5458   gfc_typebound_proc* tb;
5459
5460   if (!gfc_is_proc_ptr_comp (e, &ppc))
5461     return FAILURE;
5462
5463   tb = ppc->tb;
5464
5465   if (tb->error)
5466     return FAILURE;
5467   else if (tb->nopass)
5468     return SUCCESS;
5469
5470   po = extract_ppc_passed_object (e);
5471   if (!po)
5472     return FAILURE;
5473
5474   /* F08:R739.  */
5475   if (po->rank > 0)
5476     {
5477       gfc_error ("Passed-object at %L must be scalar", &e->where);
5478       return FAILURE;
5479     }
5480
5481   /* F08:C611.  */
5482   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
5483     {
5484       gfc_error ("Base object for procedure-pointer component call at %L is of"
5485                  " ABSTRACT type '%s'", &e->where, po->ts.u.derived->name);
5486       return FAILURE;
5487     }
5488
5489   gcc_assert (tb->pass_arg_num > 0);
5490   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5491                                                   tb->pass_arg_num,
5492                                                   tb->pass_arg);
5493
5494   return SUCCESS;
5495 }
5496
5497
5498 /* Check that the object a TBP is called on is valid, i.e. it must not be
5499    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5500
5501 static gfc_try
5502 check_typebound_baseobject (gfc_expr* e)
5503 {
5504   gfc_expr* base;
5505   gfc_try return_value = FAILURE;
5506
5507   base = extract_compcall_passed_object (e);
5508   if (!base)
5509     return FAILURE;
5510
5511   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5512
5513   /* F08:C611.  */
5514   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5515     {
5516       gfc_error ("Base object for type-bound procedure call at %L is of"
5517                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5518       goto cleanup;
5519     }
5520
5521   /* F08:C1230. If the procedure called is NOPASS,
5522      the base object must be scalar.  */
5523   if (e->value.compcall.tbp->nopass && base->rank > 0)
5524     {
5525       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5526                  " be scalar", &e->where);
5527       goto cleanup;
5528     }
5529
5530   /* FIXME: Remove once PR 43214 is fixed (TBP with non-scalar PASS).  */
5531   if (base->rank > 0)
5532     {
5533       gfc_error ("Non-scalar base object at %L currently not implemented",
5534                  &e->where);
5535       goto cleanup;
5536     }
5537
5538   return_value = SUCCESS;
5539
5540 cleanup:
5541   gfc_free_expr (base);
5542   return return_value;
5543 }
5544
5545
5546 /* Resolve a call to a type-bound procedure, either function or subroutine,
5547    statically from the data in an EXPR_COMPCALL expression.  The adapted
5548    arglist and the target-procedure symtree are returned.  */
5549
5550 static gfc_try
5551 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5552                           gfc_actual_arglist** actual)
5553 {
5554   gcc_assert (e->expr_type == EXPR_COMPCALL);
5555   gcc_assert (!e->value.compcall.tbp->is_generic);
5556
5557   /* Update the actual arglist for PASS.  */
5558   if (update_compcall_arglist (e) == FAILURE)
5559     return FAILURE;
5560
5561   *actual = e->value.compcall.actual;
5562   *target = e->value.compcall.tbp->u.specific;
5563
5564   gfc_free_ref_list (e->ref);
5565   e->ref = NULL;
5566   e->value.compcall.actual = NULL;
5567
5568   return SUCCESS;
5569 }
5570
5571
5572 /* Get the ultimate declared type from an expression.  In addition,
5573    return the last class/derived type reference and the copy of the
5574    reference list.  */
5575 static gfc_symbol*
5576 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5577                         gfc_expr *e)
5578 {
5579   gfc_symbol *declared;
5580   gfc_ref *ref;
5581
5582   declared = NULL;
5583   if (class_ref)
5584     *class_ref = NULL;
5585   if (new_ref)
5586     *new_ref = gfc_copy_ref (e->ref);
5587
5588   for (ref = e->ref; ref; ref = ref->next)
5589     {
5590       if (ref->type != REF_COMPONENT)
5591         continue;
5592
5593       if (ref->u.c.component->ts.type == BT_CLASS
5594             || ref->u.c.component->ts.type == BT_DERIVED)
5595         {
5596           declared = ref->u.c.component->ts.u.derived;
5597           if (class_ref)
5598             *class_ref = ref;
5599         }
5600     }
5601
5602   if (declared == NULL)
5603     declared = e->symtree->n.sym->ts.u.derived;
5604
5605   return declared;
5606 }
5607
5608
5609 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5610    which of the specific bindings (if any) matches the arglist and transform
5611    the expression into a call of that binding.  */
5612
5613 static gfc_try
5614 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5615 {
5616   gfc_typebound_proc* genproc;
5617   const char* genname;
5618   gfc_symtree *st;
5619   gfc_symbol *derived;
5620
5621   gcc_assert (e->expr_type == EXPR_COMPCALL);
5622   genname = e->value.compcall.name;
5623   genproc = e->value.compcall.tbp;
5624
5625   if (!genproc->is_generic)
5626     return SUCCESS;
5627
5628   /* Try the bindings on this type and in the inheritance hierarchy.  */
5629   for (; genproc; genproc = genproc->overridden)
5630     {
5631       gfc_tbp_generic* g;
5632
5633       gcc_assert (genproc->is_generic);
5634       for (g = genproc->u.generic; g; g = g->next)
5635         {
5636           gfc_symbol* target;
5637           gfc_actual_arglist* args;
5638           bool matches;
5639
5640           gcc_assert (g->specific);
5641
5642           if (g->specific->error)
5643             continue;
5644
5645           target = g->specific->u.specific->n.sym;
5646
5647           /* Get the right arglist by handling PASS/NOPASS.  */
5648           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5649           if (!g->specific->nopass)
5650             {
5651               gfc_expr* po;
5652               po = extract_compcall_passed_object (e);
5653               if (!po)
5654                 return FAILURE;
5655
5656               gcc_assert (g->specific->pass_arg_num > 0);
5657               gcc_assert (!g->specific->error);
5658               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5659                                           g->specific->pass_arg);
5660             }
5661           resolve_actual_arglist (args, target->attr.proc,
5662                                   is_external_proc (target) && !target->formal);
5663
5664           /* Check if this arglist matches the formal.  */
5665           matches = gfc_arglist_matches_symbol (&args, target);
5666
5667           /* Clean up and break out of the loop if we've found it.  */
5668           gfc_free_actual_arglist (args);
5669           if (matches)
5670             {
5671               e->value.compcall.tbp = g->specific;
5672               genname = g->specific_st->name;
5673               /* Pass along the name for CLASS methods, where the vtab
5674                  procedure pointer component has to be referenced.  */
5675               if (name)
5676                 *name = genname;
5677               goto success;
5678             }
5679         }
5680     }
5681
5682   /* Nothing matching found!  */
5683   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5684              " '%s' at %L", genname, &e->where);
5685   return FAILURE;
5686
5687 success:
5688   /* Make sure that we have the right specific instance for the name.  */
5689   derived = get_declared_from_expr (NULL, NULL, e);
5690
5691   st = gfc_find_typebound_proc (derived, NULL, genname, true, &e->where);
5692   if (st)
5693     e->value.compcall.tbp = st->n.tb;
5694
5695   return SUCCESS;
5696 }
5697
5698
5699 /* Resolve a call to a type-bound subroutine.  */
5700
5701 static gfc_try
5702 resolve_typebound_call (gfc_code* c, const char **name)
5703 {
5704   gfc_actual_arglist* newactual;
5705   gfc_symtree* target;
5706
5707   /* Check that's really a SUBROUTINE.  */
5708   if (!c->expr1->value.compcall.tbp->subroutine)
5709     {
5710       gfc_error ("'%s' at %L should be a SUBROUTINE",
5711                  c->expr1->value.compcall.name, &c->loc);
5712       return FAILURE;
5713     }
5714
5715   if (check_typebound_baseobject (c->expr1) == FAILURE)
5716     return FAILURE;
5717
5718   /* Pass along the name for CLASS methods, where the vtab
5719      procedure pointer component has to be referenced.  */
5720   if (name)
5721     *name = c->expr1->value.compcall.name;
5722
5723   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5724     return FAILURE;
5725
5726   /* Transform into an ordinary EXEC_CALL for now.  */
5727
5728   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5729     return FAILURE;
5730
5731   c->ext.actual = newactual;
5732   c->symtree = target;
5733   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5734
5735   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5736
5737   gfc_free_expr (c->expr1);
5738   c->expr1 = gfc_get_expr ();
5739   c->expr1->expr_type = EXPR_FUNCTION;
5740   c->expr1->symtree = target;
5741   c->expr1->where = c->loc;
5742
5743   return resolve_call (c);
5744 }
5745
5746
5747 /* Resolve a component-call expression.  */
5748 static gfc_try
5749 resolve_compcall (gfc_expr* e, const char **name)
5750 {
5751   gfc_actual_arglist* newactual;
5752   gfc_symtree* target;
5753
5754   /* Check that's really a FUNCTION.  */
5755   if (!e->value.compcall.tbp->function)
5756     {
5757       gfc_error ("'%s' at %L should be a FUNCTION",
5758                  e->value.compcall.name, &e->where);
5759       return FAILURE;
5760     }
5761
5762   /* These must not be assign-calls!  */
5763   gcc_assert (!e->value.compcall.assign);
5764
5765   if (check_typebound_baseobject (e) == FAILURE)
5766     return FAILURE;
5767
5768   /* Pass along the name for CLASS methods, where the vtab
5769      procedure pointer component has to be referenced.  */
5770   if (name)
5771     *name = e->value.compcall.name;
5772
5773   if (resolve_typebound_generic_call (e, name) == FAILURE)
5774     return FAILURE;
5775   gcc_assert (!e->value.compcall.tbp->is_generic);
5776
5777   /* Take the rank from the function's symbol.  */
5778   if (e->value.compcall.tbp->u.specific->n.sym->as)
5779     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5780
5781   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5782      arglist to the TBP's binding target.  */
5783
5784   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5785     return FAILURE;
5786
5787   e->value.function.actual = newactual;
5788   e->value.function.name = NULL;
5789   e->value.function.esym = target->n.sym;
5790   e->value.function.isym = NULL;
5791   e->symtree = target;
5792   e->ts = target->n.sym->ts;
5793   e->expr_type = EXPR_FUNCTION;
5794
5795   /* Resolution is not necessary if this is a class subroutine; this
5796      function only has to identify the specific proc. Resolution of
5797      the call will be done next in resolve_typebound_call.  */
5798   return gfc_resolve_expr (e);
5799 }
5800
5801
5802
5803 /* Resolve a typebound function, or 'method'. First separate all
5804    the non-CLASS references by calling resolve_compcall directly.  */
5805
5806 static gfc_try
5807 resolve_typebound_function (gfc_expr* e)
5808 {
5809   gfc_symbol *declared;
5810   gfc_component *c;
5811   gfc_ref *new_ref;
5812   gfc_ref *class_ref;
5813   gfc_symtree *st;
5814   const char *name;
5815   gfc_typespec ts;
5816   gfc_expr *expr;
5817
5818   st = e->symtree;
5819
5820   /* Deal with typebound operators for CLASS objects.  */
5821   expr = e->value.compcall.base_object;
5822   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
5823     {
5824       /* Since the typebound operators are generic, we have to ensure
5825          that any delays in resolution are corrected and that the vtab
5826          is present.  */
5827       ts = expr->ts;
5828       declared = ts.u.derived;
5829       c = gfc_find_component (declared, "_vptr", true, true);
5830       if (c->ts.u.derived == NULL)
5831         c->ts.u.derived = gfc_find_derived_vtab (declared);
5832
5833       if (resolve_compcall (e, &name) == FAILURE)
5834         return FAILURE;
5835
5836       /* Use the generic name if it is there.  */
5837       name = name ? name : e->value.function.esym->name;
5838       e->symtree = expr->symtree;
5839       e->ref = gfc_copy_ref (expr->ref);
5840       gfc_add_vptr_component (e);
5841       gfc_add_component_ref (e, name);
5842       e->value.function.esym = NULL;
5843       return SUCCESS;
5844     }
5845
5846   if (st == NULL)
5847     return resolve_compcall (e, NULL);
5848
5849   if (resolve_ref (e) == FAILURE)
5850     return FAILURE;
5851
5852   /* Get the CLASS declared type.  */
5853   declared = get_declared_from_expr (&class_ref, &new_ref, e);
5854
5855   /* Weed out cases of the ultimate component being a derived type.  */
5856   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5857          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5858     {
5859       gfc_free_ref_list (new_ref);
5860       return resolve_compcall (e, NULL);
5861     }
5862
5863   c = gfc_find_component (declared, "_data", true, true);
5864   declared = c->ts.u.derived;
5865
5866   /* Treat the call as if it is a typebound procedure, in order to roll
5867      out the correct name for the specific function.  */
5868   if (resolve_compcall (e, &name) == FAILURE)
5869     return FAILURE;
5870   ts = e->ts;
5871
5872   /* Then convert the expression to a procedure pointer component call.  */
5873   e->value.function.esym = NULL;
5874   e->symtree = st;
5875
5876   if (new_ref)  
5877     e->ref = new_ref;
5878
5879   /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5880   gfc_add_vptr_component (e);
5881   gfc_add_component_ref (e, name);
5882
5883   /* Recover the typespec for the expression.  This is really only
5884      necessary for generic procedures, where the additional call
5885      to gfc_add_component_ref seems to throw the collection of the
5886      correct typespec.  */
5887   e->ts = ts;
5888   return SUCCESS;
5889 }
5890
5891 /* Resolve a typebound subroutine, or 'method'. First separate all
5892    the non-CLASS references by calling resolve_typebound_call
5893    directly.  */
5894
5895 static gfc_try
5896 resolve_typebound_subroutine (gfc_code *code)
5897 {
5898   gfc_symbol *declared;
5899   gfc_component *c;
5900   gfc_ref *new_ref;
5901   gfc_ref *class_ref;
5902   gfc_symtree *st;
5903   const char *name;
5904   gfc_typespec ts;
5905   gfc_expr *expr;
5906
5907   st = code->expr1->symtree;
5908
5909   /* Deal with typebound operators for CLASS objects.  */
5910   expr = code->expr1->value.compcall.base_object;
5911   if (expr && expr->ts.type == BT_CLASS && code->expr1->value.compcall.name)
5912     {
5913       /* Since the typebound operators are generic, we have to ensure
5914          that any delays in resolution are corrected and that the vtab
5915          is present.  */
5916       declared = expr->ts.u.derived;
5917       c = gfc_find_component (declared, "_vptr", true, true);
5918       if (c->ts.u.derived == NULL)
5919         c->ts.u.derived = gfc_find_derived_vtab (declared);
5920
5921       if (resolve_typebound_call (code, &name) == FAILURE)
5922         return FAILURE;
5923
5924       /* Use the generic name if it is there.  */
5925       name = name ? name : code->expr1->value.function.esym->name;
5926       code->expr1->symtree = expr->symtree;
5927       code->expr1->ref = gfc_copy_ref (expr->ref);
5928       gfc_add_vptr_component (code->expr1);
5929       gfc_add_component_ref (code->expr1, name);
5930       code->expr1->value.function.esym = NULL;
5931       return SUCCESS;
5932     }
5933
5934   if (st == NULL)
5935     return resolve_typebound_call (code, NULL);
5936
5937   if (resolve_ref (code->expr1) == FAILURE)
5938     return FAILURE;
5939
5940   /* Get the CLASS declared type.  */
5941   get_declared_from_expr (&class_ref, &new_ref, code->expr1);
5942
5943   /* Weed out cases of the ultimate component being a derived type.  */
5944   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5945          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5946     {
5947       gfc_free_ref_list (new_ref);
5948       return resolve_typebound_call (code, NULL);
5949     }
5950
5951   if (resolve_typebound_call (code, &name) == FAILURE)
5952     return FAILURE;
5953   ts = code->expr1->ts;
5954
5955   /* Then convert the expression to a procedure pointer component call.  */
5956   code->expr1->value.function.esym = NULL;
5957   code->expr1->symtree = st;
5958
5959   if (new_ref)
5960     code->expr1->ref = new_ref;
5961
5962   /* '_vptr' points to the vtab, which contains the procedure pointers.  */
5963   gfc_add_vptr_component (code->expr1);
5964   gfc_add_component_ref (code->expr1, name);
5965
5966   /* Recover the typespec for the expression.  This is really only
5967      necessary for generic procedures, where the additional call
5968      to gfc_add_component_ref seems to throw the collection of the
5969      correct typespec.  */
5970   code->expr1->ts = ts;
5971   return SUCCESS;
5972 }
5973
5974
5975 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
5976
5977 static gfc_try
5978 resolve_ppc_call (gfc_code* c)
5979 {
5980   gfc_component *comp;
5981   bool b;
5982
5983   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
5984   gcc_assert (b);
5985
5986   c->resolved_sym = c->expr1->symtree->n.sym;
5987   c->expr1->expr_type = EXPR_VARIABLE;
5988
5989   if (!comp->attr.subroutine)
5990     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
5991
5992   if (resolve_ref (c->expr1) == FAILURE)
5993     return FAILURE;
5994
5995   if (update_ppc_arglist (c->expr1) == FAILURE)
5996     return FAILURE;
5997
5998   c->ext.actual = c->expr1->value.compcall.actual;
5999
6000   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
6001                               comp->formal == NULL) == FAILURE)
6002     return FAILURE;
6003
6004   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
6005
6006   return SUCCESS;
6007 }
6008
6009
6010 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
6011
6012 static gfc_try
6013 resolve_expr_ppc (gfc_expr* e)
6014 {
6015   gfc_component *comp;
6016   bool b;
6017
6018   b = gfc_is_proc_ptr_comp (e, &comp);
6019   gcc_assert (b);
6020
6021   /* Convert to EXPR_FUNCTION.  */
6022   e->expr_type = EXPR_FUNCTION;
6023   e->value.function.isym = NULL;
6024   e->value.function.actual = e->value.compcall.actual;
6025   e->ts = comp->ts;
6026   if (comp->as != NULL)
6027     e->rank = comp->as->rank;
6028
6029   if (!comp->attr.function)
6030     gfc_add_function (&comp->attr, comp->name, &e->where);
6031
6032   if (resolve_ref (e) == FAILURE)
6033     return FAILURE;
6034
6035   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
6036                               comp->formal == NULL) == FAILURE)
6037     return FAILURE;
6038
6039   if (update_ppc_arglist (e) == FAILURE)
6040     return FAILURE;
6041
6042   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6043
6044   return SUCCESS;
6045 }
6046
6047
6048 static bool
6049 gfc_is_expandable_expr (gfc_expr *e)
6050 {
6051   gfc_constructor *con;
6052
6053   if (e->expr_type == EXPR_ARRAY)
6054     {
6055       /* Traverse the constructor looking for variables that are flavor
6056          parameter.  Parameters must be expanded since they are fully used at
6057          compile time.  */
6058       con = gfc_constructor_first (e->value.constructor);
6059       for (; con; con = gfc_constructor_next (con))
6060         {
6061           if (con->expr->expr_type == EXPR_VARIABLE
6062               && con->expr->symtree
6063               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6064               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6065             return true;
6066           if (con->expr->expr_type == EXPR_ARRAY
6067               && gfc_is_expandable_expr (con->expr))
6068             return true;
6069         }
6070     }
6071
6072   return false;
6073 }
6074
6075 /* Resolve an expression.  That is, make sure that types of operands agree
6076    with their operators, intrinsic operators are converted to function calls
6077    for overloaded types and unresolved function references are resolved.  */
6078
6079 gfc_try
6080 gfc_resolve_expr (gfc_expr *e)
6081 {
6082   gfc_try t;
6083   bool inquiry_save;
6084
6085   if (e == NULL)
6086     return SUCCESS;
6087
6088   /* inquiry_argument only applies to variables.  */
6089   inquiry_save = inquiry_argument;
6090   if (e->expr_type != EXPR_VARIABLE)
6091     inquiry_argument = false;
6092
6093   switch (e->expr_type)
6094     {
6095     case EXPR_OP:
6096       t = resolve_operator (e);
6097       break;
6098
6099     case EXPR_FUNCTION:
6100     case EXPR_VARIABLE:
6101
6102       if (check_host_association (e))
6103         t = resolve_function (e);
6104       else
6105         {
6106           t = resolve_variable (e);
6107           if (t == SUCCESS)
6108             expression_rank (e);
6109         }
6110
6111       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6112           && e->ref->type != REF_SUBSTRING)
6113         gfc_resolve_substring_charlen (e);
6114
6115       break;
6116
6117     case EXPR_COMPCALL:
6118       t = resolve_typebound_function (e);
6119       break;
6120
6121     case EXPR_SUBSTRING:
6122       t = resolve_ref (e);
6123       break;
6124
6125     case EXPR_CONSTANT:
6126     case EXPR_NULL:
6127       t = SUCCESS;
6128       break;
6129
6130     case EXPR_PPC:
6131       t = resolve_expr_ppc (e);
6132       break;
6133
6134     case EXPR_ARRAY:
6135       t = FAILURE;
6136       if (resolve_ref (e) == FAILURE)
6137         break;
6138
6139       t = gfc_resolve_array_constructor (e);
6140       /* Also try to expand a constructor.  */
6141       if (t == SUCCESS)
6142         {
6143           expression_rank (e);
6144           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6145             gfc_expand_constructor (e, false);
6146         }
6147
6148       /* This provides the opportunity for the length of constructors with
6149          character valued function elements to propagate the string length
6150          to the expression.  */
6151       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6152         {
6153           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6154              here rather then add a duplicate test for it above.  */ 
6155           gfc_expand_constructor (e, false);
6156           t = gfc_resolve_character_array_constructor (e);
6157         }
6158
6159       break;
6160
6161     case EXPR_STRUCTURE:
6162       t = resolve_ref (e);
6163       if (t == FAILURE)
6164         break;
6165
6166       t = resolve_structure_cons (e, 0);
6167       if (t == FAILURE)
6168         break;
6169
6170       t = gfc_simplify_expr (e, 0);
6171       break;
6172
6173     default:
6174       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6175     }
6176
6177   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6178     fixup_charlen (e);
6179
6180   inquiry_argument = inquiry_save;
6181
6182   return t;
6183 }
6184
6185
6186 /* Resolve an expression from an iterator.  They must be scalar and have
6187    INTEGER or (optionally) REAL type.  */
6188
6189 static gfc_try
6190 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6191                            const char *name_msgid)
6192 {
6193   if (gfc_resolve_expr (expr) == FAILURE)
6194     return FAILURE;
6195
6196   if (expr->rank != 0)
6197     {
6198       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6199       return FAILURE;
6200     }
6201
6202   if (expr->ts.type != BT_INTEGER)
6203     {
6204       if (expr->ts.type == BT_REAL)
6205         {
6206           if (real_ok)
6207             return gfc_notify_std (GFC_STD_F95_DEL,
6208                                    "Deleted feature: %s at %L must be integer",
6209                                    _(name_msgid), &expr->where);
6210           else
6211             {
6212               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6213                          &expr->where);
6214               return FAILURE;
6215             }
6216         }
6217       else
6218         {
6219           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6220           return FAILURE;
6221         }
6222     }
6223   return SUCCESS;
6224 }
6225
6226
6227 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6228    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6229
6230 gfc_try
6231 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6232 {
6233   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6234       == FAILURE)
6235     return FAILURE;
6236
6237   if (gfc_check_vardef_context (iter->var, false, false, _("iterator variable"))
6238       == FAILURE)
6239     return FAILURE;
6240
6241   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6242                                  "Start expression in DO loop") == FAILURE)
6243     return FAILURE;
6244
6245   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6246                                  "End expression in DO loop") == FAILURE)
6247     return FAILURE;
6248
6249   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6250                                  "Step expression in DO loop") == FAILURE)
6251     return FAILURE;
6252
6253   if (iter->step->expr_type == EXPR_CONSTANT)
6254     {
6255       if ((iter->step->ts.type == BT_INTEGER
6256            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6257           || (iter->step->ts.type == BT_REAL
6258               && mpfr_sgn (iter->step->value.real) == 0))
6259         {
6260           gfc_error ("Step expression in DO loop at %L cannot be zero",
6261                      &iter->step->where);
6262           return FAILURE;
6263         }
6264     }
6265
6266   /* Convert start, end, and step to the same type as var.  */
6267   if (iter->start->ts.kind != iter->var->ts.kind
6268       || iter->start->ts.type != iter->var->ts.type)
6269     gfc_convert_type (iter->start, &iter->var->ts, 2);
6270
6271   if (iter->end->ts.kind != iter->var->ts.kind
6272       || iter->end->ts.type != iter->var->ts.type)
6273     gfc_convert_type (iter->end, &iter->var->ts, 2);
6274
6275   if (iter->step->ts.kind != iter->var->ts.kind
6276       || iter->step->ts.type != iter->var->ts.type)
6277     gfc_convert_type (iter->step, &iter->var->ts, 2);
6278
6279   if (iter->start->expr_type == EXPR_CONSTANT
6280       && iter->end->expr_type == EXPR_CONSTANT
6281       && iter->step->expr_type == EXPR_CONSTANT)
6282     {
6283       int sgn, cmp;
6284       if (iter->start->ts.type == BT_INTEGER)
6285         {
6286           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6287           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6288         }
6289       else
6290         {
6291           sgn = mpfr_sgn (iter->step->value.real);
6292           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6293         }
6294       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6295         gfc_warning ("DO loop at %L will be executed zero times",
6296                      &iter->step->where);
6297     }
6298
6299   return SUCCESS;
6300 }
6301
6302
6303 /* Traversal function for find_forall_index.  f == 2 signals that
6304    that variable itself is not to be checked - only the references.  */
6305
6306 static bool
6307 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6308 {
6309   if (expr->expr_type != EXPR_VARIABLE)
6310     return false;
6311   
6312   /* A scalar assignment  */
6313   if (!expr->ref || *f == 1)
6314     {
6315       if (expr->symtree->n.sym == sym)
6316         return true;
6317       else
6318         return false;
6319     }
6320
6321   if (*f == 2)
6322     *f = 1;
6323   return false;
6324 }
6325
6326
6327 /* Check whether the FORALL index appears in the expression or not.
6328    Returns SUCCESS if SYM is found in EXPR.  */
6329
6330 gfc_try
6331 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6332 {
6333   if (gfc_traverse_expr (expr, sym, forall_index, f))
6334     return SUCCESS;
6335   else
6336     return FAILURE;
6337 }
6338
6339
6340 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6341    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6342    INTEGERs, and if stride is a constant it must be nonzero.
6343    Furthermore "A subscript or stride in a forall-triplet-spec shall
6344    not contain a reference to any index-name in the
6345    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6346
6347 static void
6348 resolve_forall_iterators (gfc_forall_iterator *it)
6349 {
6350   gfc_forall_iterator *iter, *iter2;
6351
6352   for (iter = it; iter; iter = iter->next)
6353     {
6354       if (gfc_resolve_expr (iter->var) == SUCCESS
6355           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6356         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6357                    &iter->var->where);
6358
6359       if (gfc_resolve_expr (iter->start) == SUCCESS
6360           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6361         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6362                    &iter->start->where);
6363       if (iter->var->ts.kind != iter->start->ts.kind)
6364         gfc_convert_type (iter->start, &iter->var->ts, 2);
6365
6366       if (gfc_resolve_expr (iter->end) == SUCCESS
6367           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6368         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6369                    &iter->end->where);
6370       if (iter->var->ts.kind != iter->end->ts.kind)
6371         gfc_convert_type (iter->end, &iter->var->ts, 2);
6372
6373       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6374         {
6375           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6376             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6377                        &iter->stride->where, "INTEGER");
6378
6379           if (iter->stride->expr_type == EXPR_CONSTANT
6380               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6381             gfc_error ("FORALL stride expression at %L cannot be zero",
6382                        &iter->stride->where);
6383         }
6384       if (iter->var->ts.kind != iter->stride->ts.kind)
6385         gfc_convert_type (iter->stride, &iter->var->ts, 2);
6386     }
6387
6388   for (iter = it; iter; iter = iter->next)
6389     for (iter2 = iter; iter2; iter2 = iter2->next)
6390       {
6391         if (find_forall_index (iter2->start,
6392                                iter->var->symtree->n.sym, 0) == SUCCESS
6393             || find_forall_index (iter2->end,
6394                                   iter->var->symtree->n.sym, 0) == SUCCESS
6395             || find_forall_index (iter2->stride,
6396                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6397           gfc_error ("FORALL index '%s' may not appear in triplet "
6398                      "specification at %L", iter->var->symtree->name,
6399                      &iter2->start->where);
6400       }
6401 }
6402
6403
6404 /* Given a pointer to a symbol that is a derived type, see if it's
6405    inaccessible, i.e. if it's defined in another module and the components are
6406    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6407    inaccessible components are found, nonzero otherwise.  */
6408
6409 static int
6410 derived_inaccessible (gfc_symbol *sym)
6411 {
6412   gfc_component *c;
6413
6414   if (sym->attr.use_assoc && sym->attr.private_comp)
6415     return 1;
6416
6417   for (c = sym->components; c; c = c->next)
6418     {
6419         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6420           return 1;
6421     }
6422
6423   return 0;
6424 }
6425
6426
6427 /* Resolve the argument of a deallocate expression.  The expression must be
6428    a pointer or a full array.  */
6429
6430 static gfc_try
6431 resolve_deallocate_expr (gfc_expr *e)
6432 {
6433   symbol_attribute attr;
6434   int allocatable, pointer;
6435   gfc_ref *ref;
6436   gfc_symbol *sym;
6437   gfc_component *c;
6438
6439   if (gfc_resolve_expr (e) == FAILURE)
6440     return FAILURE;
6441
6442   if (e->expr_type != EXPR_VARIABLE)
6443     goto bad;
6444
6445   sym = e->symtree->n.sym;
6446
6447   if (sym->ts.type == BT_CLASS)
6448     {
6449       allocatable = CLASS_DATA (sym)->attr.allocatable;
6450       pointer = CLASS_DATA (sym)->attr.class_pointer;
6451     }
6452   else
6453     {
6454       allocatable = sym->attr.allocatable;
6455       pointer = sym->attr.pointer;
6456     }
6457   for (ref = e->ref; ref; ref = ref->next)
6458     {
6459       switch (ref->type)
6460         {
6461         case REF_ARRAY:
6462           if (ref->u.ar.type != AR_FULL
6463               && !(ref->u.ar.type == AR_ELEMENT && ref->u.ar.as->rank == 0
6464                    && ref->u.ar.codimen && gfc_ref_this_image (ref)))
6465             allocatable = 0;
6466           break;
6467
6468         case REF_COMPONENT:
6469           c = ref->u.c.component;
6470           if (c->ts.type == BT_CLASS)
6471             {
6472               allocatable = CLASS_DATA (c)->attr.allocatable;
6473               pointer = CLASS_DATA (c)->attr.class_pointer;
6474             }
6475           else
6476             {
6477               allocatable = c->attr.allocatable;
6478               pointer = c->attr.pointer;
6479             }
6480           break;
6481
6482         case REF_SUBSTRING:
6483           allocatable = 0;
6484           break;
6485         }
6486     }
6487
6488   attr = gfc_expr_attr (e);
6489
6490   if (allocatable == 0 && attr.pointer == 0)
6491     {
6492     bad:
6493       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6494                  &e->where);
6495       return FAILURE;
6496     }
6497
6498   /* F2008, C644.  */
6499   if (gfc_is_coindexed (e))
6500     {
6501       gfc_error ("Coindexed allocatable object at %L", &e->where);
6502       return FAILURE;
6503     }
6504
6505   if (pointer
6506       && gfc_check_vardef_context (e, true, true, _("DEALLOCATE object"))
6507          == FAILURE)
6508     return FAILURE;
6509   if (gfc_check_vardef_context (e, false, true, _("DEALLOCATE object"))
6510       == FAILURE)
6511     return FAILURE;
6512
6513   return SUCCESS;
6514 }
6515
6516
6517 /* Returns true if the expression e contains a reference to the symbol sym.  */
6518 static bool
6519 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6520 {
6521   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6522     return true;
6523
6524   return false;
6525 }
6526
6527 bool
6528 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6529 {
6530   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6531 }
6532
6533
6534 /* Given the expression node e for an allocatable/pointer of derived type to be
6535    allocated, get the expression node to be initialized afterwards (needed for
6536    derived types with default initializers, and derived types with allocatable
6537    components that need nullification.)  */
6538
6539 gfc_expr *
6540 gfc_expr_to_initialize (gfc_expr *e)
6541 {
6542   gfc_expr *result;
6543   gfc_ref *ref;
6544   int i;
6545
6546   result = gfc_copy_expr (e);
6547
6548   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6549   for (ref = result->ref; ref; ref = ref->next)
6550     if (ref->type == REF_ARRAY && ref->next == NULL)
6551       {
6552         ref->u.ar.type = AR_FULL;
6553
6554         for (i = 0; i < ref->u.ar.dimen; i++)
6555           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6556
6557         break;
6558       }
6559
6560   gfc_free_shape (&result->shape, result->rank);
6561
6562   /* Recalculate rank, shape, etc.  */
6563   gfc_resolve_expr (result);
6564   return result;
6565 }
6566
6567
6568 /* If the last ref of an expression is an array ref, return a copy of the
6569    expression with that one removed.  Otherwise, a copy of the original
6570    expression.  This is used for allocate-expressions and pointer assignment
6571    LHS, where there may be an array specification that needs to be stripped
6572    off when using gfc_check_vardef_context.  */
6573
6574 static gfc_expr*
6575 remove_last_array_ref (gfc_expr* e)
6576 {
6577   gfc_expr* e2;
6578   gfc_ref** r;
6579
6580   e2 = gfc_copy_expr (e);
6581   for (r = &e2->ref; *r; r = &(*r)->next)
6582     if ((*r)->type == REF_ARRAY && !(*r)->next)
6583       {
6584         gfc_free_ref_list (*r);
6585         *r = NULL;
6586         break;
6587       }
6588
6589   return e2;
6590 }
6591
6592
6593 /* Used in resolve_allocate_expr to check that a allocation-object and
6594    a source-expr are conformable.  This does not catch all possible 
6595    cases; in particular a runtime checking is needed.  */
6596
6597 static gfc_try
6598 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6599 {
6600   gfc_ref *tail;
6601   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6602   
6603   /* First compare rank.  */
6604   if (tail && e1->rank != tail->u.ar.as->rank)
6605     {
6606       gfc_error ("Source-expr at %L must be scalar or have the "
6607                  "same rank as the allocate-object at %L",
6608                  &e1->where, &e2->where);
6609       return FAILURE;
6610     }
6611
6612   if (e1->shape)
6613     {
6614       int i;
6615       mpz_t s;
6616
6617       mpz_init (s);
6618
6619       for (i = 0; i < e1->rank; i++)
6620         {
6621           if (tail->u.ar.end[i])
6622             {
6623               mpz_set (s, tail->u.ar.end[i]->value.integer);
6624               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6625               mpz_add_ui (s, s, 1);
6626             }
6627           else
6628             {
6629               mpz_set (s, tail->u.ar.start[i]->value.integer);
6630             }
6631
6632           if (mpz_cmp (e1->shape[i], s) != 0)
6633             {
6634               gfc_error ("Source-expr at %L and allocate-object at %L must "
6635                          "have the same shape", &e1->where, &e2->where);
6636               mpz_clear (s);
6637               return FAILURE;
6638             }
6639         }
6640
6641       mpz_clear (s);
6642     }
6643
6644   return SUCCESS;
6645 }
6646
6647
6648 /* Resolve the expression in an ALLOCATE statement, doing the additional
6649    checks to see whether the expression is OK or not.  The expression must
6650    have a trailing array reference that gives the size of the array.  */
6651
6652 static gfc_try
6653 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6654 {
6655   int i, pointer, allocatable, dimension, is_abstract;
6656   int codimension;
6657   bool coindexed;
6658   symbol_attribute attr;
6659   gfc_ref *ref, *ref2;
6660   gfc_expr *e2;
6661   gfc_array_ref *ar;
6662   gfc_symbol *sym = NULL;
6663   gfc_alloc *a;
6664   gfc_component *c;
6665   gfc_try t;
6666
6667   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6668      checking of coarrays.  */
6669   for (ref = e->ref; ref; ref = ref->next)
6670     if (ref->next == NULL)
6671       break;
6672
6673   if (ref && ref->type == REF_ARRAY)
6674     ref->u.ar.in_allocate = true;
6675
6676   if (gfc_resolve_expr (e) == FAILURE)
6677     goto failure;
6678
6679   /* Make sure the expression is allocatable or a pointer.  If it is
6680      pointer, the next-to-last reference must be a pointer.  */
6681
6682   ref2 = NULL;
6683   if (e->symtree)
6684     sym = e->symtree->n.sym;
6685
6686   /* Check whether ultimate component is abstract and CLASS.  */
6687   is_abstract = 0;
6688
6689   if (e->expr_type != EXPR_VARIABLE)
6690     {
6691       allocatable = 0;
6692       attr = gfc_expr_attr (e);
6693       pointer = attr.pointer;
6694       dimension = attr.dimension;
6695       codimension = attr.codimension;
6696     }
6697   else
6698     {
6699       if (sym->ts.type == BT_CLASS)
6700         {
6701           allocatable = CLASS_DATA (sym)->attr.allocatable;
6702           pointer = CLASS_DATA (sym)->attr.class_pointer;
6703           dimension = CLASS_DATA (sym)->attr.dimension;
6704           codimension = CLASS_DATA (sym)->attr.codimension;
6705           is_abstract = CLASS_DATA (sym)->attr.abstract;
6706         }
6707       else
6708         {
6709           allocatable = sym->attr.allocatable;
6710           pointer = sym->attr.pointer;
6711           dimension = sym->attr.dimension;
6712           codimension = sym->attr.codimension;
6713         }
6714
6715       coindexed = false;
6716
6717       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6718         {
6719           switch (ref->type)
6720             {
6721               case REF_ARRAY:
6722                 if (ref->u.ar.codimen > 0)
6723                   {
6724                     int n;
6725                     for (n = ref->u.ar.dimen;
6726                          n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
6727                       if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
6728                         {
6729                           coindexed = true;
6730                           break;
6731                         }
6732                    }
6733
6734                 if (ref->next != NULL)
6735                   pointer = 0;
6736                 break;
6737
6738               case REF_COMPONENT:
6739                 /* F2008, C644.  */
6740                 if (coindexed)
6741                   {
6742                     gfc_error ("Coindexed allocatable object at %L",
6743                                &e->where);
6744                     goto failure;
6745                   }
6746
6747                 c = ref->u.c.component;
6748                 if (c->ts.type == BT_CLASS)
6749                   {
6750                     allocatable = CLASS_DATA (c)->attr.allocatable;
6751                     pointer = CLASS_DATA (c)->attr.class_pointer;
6752                     dimension = CLASS_DATA (c)->attr.dimension;
6753                     codimension = CLASS_DATA (c)->attr.codimension;
6754                     is_abstract = CLASS_DATA (c)->attr.abstract;
6755                   }
6756                 else
6757                   {
6758                     allocatable = c->attr.allocatable;
6759                     pointer = c->attr.pointer;
6760                     dimension = c->attr.dimension;
6761                     codimension = c->attr.codimension;
6762                     is_abstract = c->attr.abstract;
6763                   }
6764                 break;
6765
6766               case REF_SUBSTRING:
6767                 allocatable = 0;
6768                 pointer = 0;
6769                 break;
6770             }
6771         }
6772     }
6773
6774   if (allocatable == 0 && pointer == 0)
6775     {
6776       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6777                  &e->where);
6778       goto failure;
6779     }
6780
6781   /* Some checks for the SOURCE tag.  */
6782   if (code->expr3)
6783     {
6784       /* Check F03:C631.  */
6785       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6786         {
6787           gfc_error ("Type of entity at %L is type incompatible with "
6788                       "source-expr at %L", &e->where, &code->expr3->where);
6789           goto failure;
6790         }
6791
6792       /* Check F03:C632 and restriction following Note 6.18.  */
6793       if (code->expr3->rank > 0
6794           && conformable_arrays (code->expr3, e) == FAILURE)
6795         goto failure;
6796
6797       /* Check F03:C633.  */
6798       if (code->expr3->ts.kind != e->ts.kind)
6799         {
6800           gfc_error ("The allocate-object at %L and the source-expr at %L "
6801                       "shall have the same kind type parameter",
6802                       &e->where, &code->expr3->where);
6803           goto failure;
6804         }
6805
6806       /* Check F2008, C642.  */
6807       if (code->expr3->ts.type == BT_DERIVED
6808           && ((codimension && gfc_expr_attr (code->expr3).lock_comp)
6809               || (code->expr3->ts.u.derived->from_intmod
6810                      == INTMOD_ISO_FORTRAN_ENV
6811                   && code->expr3->ts.u.derived->intmod_sym_id
6812                      == ISOFORTRAN_LOCK_TYPE)))
6813         {
6814           gfc_error ("The source-expr at %L shall neither be of type "
6815                      "LOCK_TYPE nor have a LOCK_TYPE component if "
6816                       "allocate-object at %L is a coarray",
6817                       &code->expr3->where, &e->where);
6818           goto failure;
6819         }
6820     }
6821
6822   /* Check F08:C629.  */
6823   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6824       && !code->expr3)
6825     {
6826       gcc_assert (e->ts.type == BT_CLASS);
6827       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6828                  "type-spec or source-expr", sym->name, &e->where);
6829       goto failure;
6830     }
6831
6832   /* In the variable definition context checks, gfc_expr_attr is used
6833      on the expression.  This is fooled by the array specification
6834      present in e, thus we have to eliminate that one temporarily.  */
6835   e2 = remove_last_array_ref (e);
6836   t = SUCCESS;
6837   if (t == SUCCESS && pointer)
6838     t = gfc_check_vardef_context (e2, true, true, _("ALLOCATE object"));
6839   if (t == SUCCESS)
6840     t = gfc_check_vardef_context (e2, false, true, _("ALLOCATE object"));
6841   gfc_free_expr (e2);
6842   if (t == FAILURE)
6843     goto failure;
6844
6845   if (!code->expr3)
6846     {
6847       /* Set up default initializer if needed.  */
6848       gfc_typespec ts;
6849       gfc_expr *init_e;
6850
6851       if (code->ext.alloc.ts.type == BT_DERIVED)
6852         ts = code->ext.alloc.ts;
6853       else
6854         ts = e->ts;
6855
6856       if (ts.type == BT_CLASS)
6857         ts = ts.u.derived->components->ts;
6858
6859       if (ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&ts)))
6860         {
6861           gfc_code *init_st = gfc_get_code ();
6862           init_st->loc = code->loc;
6863           init_st->op = EXEC_INIT_ASSIGN;
6864           init_st->expr1 = gfc_expr_to_initialize (e);
6865           init_st->expr2 = init_e;
6866           init_st->next = code->next;
6867           code->next = init_st;
6868         }
6869     }
6870   else if (code->expr3->mold && code->expr3->ts.type == BT_DERIVED)
6871     {
6872       /* Default initialization via MOLD (non-polymorphic).  */
6873       gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
6874       gfc_resolve_expr (rhs);
6875       gfc_free_expr (code->expr3);
6876       code->expr3 = rhs;
6877     }
6878
6879   if (e->ts.type == BT_CLASS)
6880     {
6881       /* Make sure the vtab symbol is present when
6882          the module variables are generated.  */
6883       gfc_typespec ts = e->ts;
6884       if (code->expr3)
6885         ts = code->expr3->ts;
6886       else if (code->ext.alloc.ts.type == BT_DERIVED)
6887         ts = code->ext.alloc.ts;
6888       gfc_find_derived_vtab (ts.u.derived);
6889     }
6890
6891   if (dimension == 0 && codimension == 0)
6892     goto success;
6893
6894   /* Make sure the last reference node is an array specifiction.  */
6895
6896   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
6897       || (dimension && ref2->u.ar.dimen == 0))
6898     {
6899       gfc_error ("Array specification required in ALLOCATE statement "
6900                  "at %L", &e->where);
6901       goto failure;
6902     }
6903
6904   /* Make sure that the array section reference makes sense in the
6905     context of an ALLOCATE specification.  */
6906
6907   ar = &ref2->u.ar;
6908
6909   if (codimension)
6910     for (i = ar->dimen; i < ar->dimen + ar->codimen; i++)
6911       if (ar->dimen_type[i] == DIMEN_THIS_IMAGE)
6912         {
6913           gfc_error ("Coarray specification required in ALLOCATE statement "
6914                      "at %L", &e->where);
6915           goto failure;
6916         }
6917
6918   for (i = 0; i < ar->dimen; i++)
6919     {
6920       if (ref2->u.ar.type == AR_ELEMENT)
6921         goto check_symbols;
6922
6923       switch (ar->dimen_type[i])
6924         {
6925         case DIMEN_ELEMENT:
6926           break;
6927
6928         case DIMEN_RANGE:
6929           if (ar->start[i] != NULL
6930               && ar->end[i] != NULL
6931               && ar->stride[i] == NULL)
6932             break;
6933
6934           /* Fall Through...  */
6935
6936         case DIMEN_UNKNOWN:
6937         case DIMEN_VECTOR:
6938         case DIMEN_STAR:
6939         case DIMEN_THIS_IMAGE:
6940           gfc_error ("Bad array specification in ALLOCATE statement at %L",
6941                      &e->where);
6942           goto failure;
6943         }
6944
6945 check_symbols:
6946       for (a = code->ext.alloc.list; a; a = a->next)
6947         {
6948           sym = a->expr->symtree->n.sym;
6949
6950           /* TODO - check derived type components.  */
6951           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
6952             continue;
6953
6954           if ((ar->start[i] != NULL
6955                && gfc_find_sym_in_expr (sym, ar->start[i]))
6956               || (ar->end[i] != NULL
6957                   && gfc_find_sym_in_expr (sym, ar->end[i])))
6958             {
6959               gfc_error ("'%s' must not appear in the array specification at "
6960                          "%L in the same ALLOCATE statement where it is "
6961                          "itself allocated", sym->name, &ar->where);
6962               goto failure;
6963             }
6964         }
6965     }
6966
6967   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
6968     {
6969       if (ar->dimen_type[i] == DIMEN_ELEMENT
6970           || ar->dimen_type[i] == DIMEN_RANGE)
6971         {
6972           if (i == (ar->dimen + ar->codimen - 1))
6973             {
6974               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
6975                          "statement at %L", &e->where);
6976               goto failure;
6977             }
6978           break;
6979         }
6980
6981       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
6982           && ar->stride[i] == NULL)
6983         break;
6984
6985       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
6986                  &e->where);
6987       goto failure;
6988     }
6989
6990 success:
6991   return SUCCESS;
6992
6993 failure:
6994   return FAILURE;
6995 }
6996
6997 static void
6998 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
6999 {
7000   gfc_expr *stat, *errmsg, *pe, *qe;
7001   gfc_alloc *a, *p, *q;
7002
7003   stat = code->expr1;
7004   errmsg = code->expr2;
7005
7006   /* Check the stat variable.  */
7007   if (stat)
7008     {
7009       gfc_check_vardef_context (stat, false, false, _("STAT variable"));
7010
7011       if ((stat->ts.type != BT_INTEGER
7012            && !(stat->ref && (stat->ref->type == REF_ARRAY
7013                               || stat->ref->type == REF_COMPONENT)))
7014           || stat->rank > 0)
7015         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
7016                    "variable", &stat->where);
7017
7018       for (p = code->ext.alloc.list; p; p = p->next)
7019         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
7020           {
7021             gfc_ref *ref1, *ref2;
7022             bool found = true;
7023
7024             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
7025                  ref1 = ref1->next, ref2 = ref2->next)
7026               {
7027                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7028                   continue;
7029                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7030                   {
7031                     found = false;
7032                     break;
7033                   }
7034               }
7035
7036             if (found)
7037               {
7038                 gfc_error ("Stat-variable at %L shall not be %sd within "
7039                            "the same %s statement", &stat->where, fcn, fcn);
7040                 break;
7041               }
7042           }
7043     }
7044
7045   /* Check the errmsg variable.  */
7046   if (errmsg)
7047     {
7048       if (!stat)
7049         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
7050                      &errmsg->where);
7051
7052       gfc_check_vardef_context (errmsg, false, false, _("ERRMSG variable"));
7053
7054       if ((errmsg->ts.type != BT_CHARACTER
7055            && !(errmsg->ref
7056                 && (errmsg->ref->type == REF_ARRAY
7057                     || errmsg->ref->type == REF_COMPONENT)))
7058           || errmsg->rank > 0 )
7059         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
7060                    "variable", &errmsg->where);
7061
7062       for (p = code->ext.alloc.list; p; p = p->next)
7063         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
7064           {
7065             gfc_ref *ref1, *ref2;
7066             bool found = true;
7067
7068             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
7069                  ref1 = ref1->next, ref2 = ref2->next)
7070               {
7071                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7072                   continue;
7073                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7074                   {
7075                     found = false;
7076                     break;
7077                   }
7078               }
7079
7080             if (found)
7081               {
7082                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
7083                            "the same %s statement", &errmsg->where, fcn, fcn);
7084                 break;
7085               }
7086           }
7087     }
7088
7089   /* Check that an allocate-object appears only once in the statement.  
7090      FIXME: Checking derived types is disabled.  */
7091   for (p = code->ext.alloc.list; p; p = p->next)
7092     {
7093       pe = p->expr;
7094       for (q = p->next; q; q = q->next)
7095         {
7096           qe = q->expr;
7097           if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
7098             {
7099               /* This is a potential collision.  */
7100               gfc_ref *pr = pe->ref;
7101               gfc_ref *qr = qe->ref;
7102               
7103               /* Follow the references  until
7104                  a) They start to differ, in which case there is no error;
7105                  you can deallocate a%b and a%c in a single statement
7106                  b) Both of them stop, which is an error
7107                  c) One of them stops, which is also an error.  */
7108               while (1)
7109                 {
7110                   if (pr == NULL && qr == NULL)
7111                     {
7112                       gfc_error ("Allocate-object at %L also appears at %L",
7113                                  &pe->where, &qe->where);
7114                       break;
7115                     }
7116                   else if (pr != NULL && qr == NULL)
7117                     {
7118                       gfc_error ("Allocate-object at %L is subobject of"
7119                                  " object at %L", &pe->where, &qe->where);
7120                       break;
7121                     }
7122                   else if (pr == NULL && qr != NULL)
7123                     {
7124                       gfc_error ("Allocate-object at %L is subobject of"
7125                                  " object at %L", &qe->where, &pe->where);
7126                       break;
7127                     }
7128                   /* Here, pr != NULL && qr != NULL  */
7129                   gcc_assert(pr->type == qr->type);
7130                   if (pr->type == REF_ARRAY)
7131                     {
7132                       /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
7133                          which are legal.  */
7134                       gcc_assert (qr->type == REF_ARRAY);
7135
7136                       if (pr->next && qr->next)
7137                         {
7138                           gfc_array_ref *par = &(pr->u.ar);
7139                           gfc_array_ref *qar = &(qr->u.ar);
7140                           if (gfc_dep_compare_expr (par->start[0],
7141                                                     qar->start[0]) != 0)
7142                               break;
7143                         }
7144                     }
7145                   else
7146                     {
7147                       if (pr->u.c.component->name != qr->u.c.component->name)
7148                         break;
7149                     }
7150                   
7151                   pr = pr->next;
7152                   qr = qr->next;
7153                 }
7154             }
7155         }
7156     }
7157
7158   if (strcmp (fcn, "ALLOCATE") == 0)
7159     {
7160       for (a = code->ext.alloc.list; a; a = a->next)
7161         resolve_allocate_expr (a->expr, code);
7162     }
7163   else
7164     {
7165       for (a = code->ext.alloc.list; a; a = a->next)
7166         resolve_deallocate_expr (a->expr);
7167     }
7168 }
7169
7170
7171 /************ SELECT CASE resolution subroutines ************/
7172
7173 /* Callback function for our mergesort variant.  Determines interval
7174    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7175    op1 > op2.  Assumes we're not dealing with the default case.  
7176    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7177    There are nine situations to check.  */
7178
7179 static int
7180 compare_cases (const gfc_case *op1, const gfc_case *op2)
7181 {
7182   int retval;
7183
7184   if (op1->low == NULL) /* op1 = (:L)  */
7185     {
7186       /* op2 = (:N), so overlap.  */
7187       retval = 0;
7188       /* op2 = (M:) or (M:N),  L < M  */
7189       if (op2->low != NULL
7190           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7191         retval = -1;
7192     }
7193   else if (op1->high == NULL) /* op1 = (K:)  */
7194     {
7195       /* op2 = (M:), so overlap.  */
7196       retval = 0;
7197       /* op2 = (:N) or (M:N), K > N  */
7198       if (op2->high != NULL
7199           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7200         retval = 1;
7201     }
7202   else /* op1 = (K:L)  */
7203     {
7204       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7205         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7206                  ? 1 : 0;
7207       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7208         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7209                  ? -1 : 0;
7210       else                      /* op2 = (M:N)  */
7211         {
7212           retval =  0;
7213           /* L < M  */
7214           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7215             retval =  -1;
7216           /* K > N  */
7217           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7218             retval =  1;
7219         }
7220     }
7221
7222   return retval;
7223 }
7224
7225
7226 /* Merge-sort a double linked case list, detecting overlap in the
7227    process.  LIST is the head of the double linked case list before it
7228    is sorted.  Returns the head of the sorted list if we don't see any
7229    overlap, or NULL otherwise.  */
7230
7231 static gfc_case *
7232 check_case_overlap (gfc_case *list)
7233 {
7234   gfc_case *p, *q, *e, *tail;
7235   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7236
7237   /* If the passed list was empty, return immediately.  */
7238   if (!list)
7239     return NULL;
7240
7241   overlap_seen = 0;
7242   insize = 1;
7243
7244   /* Loop unconditionally.  The only exit from this loop is a return
7245      statement, when we've finished sorting the case list.  */
7246   for (;;)
7247     {
7248       p = list;
7249       list = NULL;
7250       tail = NULL;
7251
7252       /* Count the number of merges we do in this pass.  */
7253       nmerges = 0;
7254
7255       /* Loop while there exists a merge to be done.  */
7256       while (p)
7257         {
7258           int i;
7259
7260           /* Count this merge.  */
7261           nmerges++;
7262
7263           /* Cut the list in two pieces by stepping INSIZE places
7264              forward in the list, starting from P.  */
7265           psize = 0;
7266           q = p;
7267           for (i = 0; i < insize; i++)
7268             {
7269               psize++;
7270               q = q->right;
7271               if (!q)
7272                 break;
7273             }
7274           qsize = insize;
7275
7276           /* Now we have two lists.  Merge them!  */
7277           while (psize > 0 || (qsize > 0 && q != NULL))
7278             {
7279               /* See from which the next case to merge comes from.  */
7280               if (psize == 0)
7281                 {
7282                   /* P is empty so the next case must come from Q.  */
7283                   e = q;
7284                   q = q->right;
7285                   qsize--;
7286                 }
7287               else if (qsize == 0 || q == NULL)
7288                 {
7289                   /* Q is empty.  */
7290                   e = p;
7291                   p = p->right;
7292                   psize--;
7293                 }
7294               else
7295                 {
7296                   cmp = compare_cases (p, q);
7297                   if (cmp < 0)
7298                     {
7299                       /* The whole case range for P is less than the
7300                          one for Q.  */
7301                       e = p;
7302                       p = p->right;
7303                       psize--;
7304                     }
7305                   else if (cmp > 0)
7306                     {
7307                       /* The whole case range for Q is greater than
7308                          the case range for P.  */
7309                       e = q;
7310                       q = q->right;
7311                       qsize--;
7312                     }
7313                   else
7314                     {
7315                       /* The cases overlap, or they are the same
7316                          element in the list.  Either way, we must
7317                          issue an error and get the next case from P.  */
7318                       /* FIXME: Sort P and Q by line number.  */
7319                       gfc_error ("CASE label at %L overlaps with CASE "
7320                                  "label at %L", &p->where, &q->where);
7321                       overlap_seen = 1;
7322                       e = p;
7323                       p = p->right;
7324                       psize--;
7325                     }
7326                 }
7327
7328                 /* Add the next element to the merged list.  */
7329               if (tail)
7330                 tail->right = e;
7331               else
7332                 list = e;
7333               e->left = tail;
7334               tail = e;
7335             }
7336
7337           /* P has now stepped INSIZE places along, and so has Q.  So
7338              they're the same.  */
7339           p = q;
7340         }
7341       tail->right = NULL;
7342
7343       /* If we have done only one merge or none at all, we've
7344          finished sorting the cases.  */
7345       if (nmerges <= 1)
7346         {
7347           if (!overlap_seen)
7348             return list;
7349           else
7350             return NULL;
7351         }
7352
7353       /* Otherwise repeat, merging lists twice the size.  */
7354       insize *= 2;
7355     }
7356 }
7357
7358
7359 /* Check to see if an expression is suitable for use in a CASE statement.
7360    Makes sure that all case expressions are scalar constants of the same
7361    type.  Return FAILURE if anything is wrong.  */
7362
7363 static gfc_try
7364 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7365 {
7366   if (e == NULL) return SUCCESS;
7367
7368   if (e->ts.type != case_expr->ts.type)
7369     {
7370       gfc_error ("Expression in CASE statement at %L must be of type %s",
7371                  &e->where, gfc_basic_typename (case_expr->ts.type));
7372       return FAILURE;
7373     }
7374
7375   /* C805 (R808) For a given case-construct, each case-value shall be of
7376      the same type as case-expr.  For character type, length differences
7377      are allowed, but the kind type parameters shall be the same.  */
7378
7379   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7380     {
7381       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7382                  &e->where, case_expr->ts.kind);
7383       return FAILURE;
7384     }
7385
7386   /* Convert the case value kind to that of case expression kind,
7387      if needed */
7388
7389   if (e->ts.kind != case_expr->ts.kind)
7390     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7391
7392   if (e->rank != 0)
7393     {
7394       gfc_error ("Expression in CASE statement at %L must be scalar",
7395                  &e->where);
7396       return FAILURE;
7397     }
7398
7399   return SUCCESS;
7400 }
7401
7402
7403 /* Given a completely parsed select statement, we:
7404
7405      - Validate all expressions and code within the SELECT.
7406      - Make sure that the selection expression is not of the wrong type.
7407      - Make sure that no case ranges overlap.
7408      - Eliminate unreachable cases and unreachable code resulting from
7409        removing case labels.
7410
7411    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7412    they are a hassle for code generation, and to prevent that, we just
7413    cut them out here.  This is not necessary for overlapping cases
7414    because they are illegal and we never even try to generate code.
7415
7416    We have the additional caveat that a SELECT construct could have
7417    been a computed GOTO in the source code. Fortunately we can fairly
7418    easily work around that here: The case_expr for a "real" SELECT CASE
7419    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7420    we have to do is make sure that the case_expr is a scalar integer
7421    expression.  */
7422
7423 static void
7424 resolve_select (gfc_code *code)
7425 {
7426   gfc_code *body;
7427   gfc_expr *case_expr;
7428   gfc_case *cp, *default_case, *tail, *head;
7429   int seen_unreachable;
7430   int seen_logical;
7431   int ncases;
7432   bt type;
7433   gfc_try t;
7434
7435   if (code->expr1 == NULL)
7436     {
7437       /* This was actually a computed GOTO statement.  */
7438       case_expr = code->expr2;
7439       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7440         gfc_error ("Selection expression in computed GOTO statement "
7441                    "at %L must be a scalar integer expression",
7442                    &case_expr->where);
7443
7444       /* Further checking is not necessary because this SELECT was built
7445          by the compiler, so it should always be OK.  Just move the
7446          case_expr from expr2 to expr so that we can handle computed
7447          GOTOs as normal SELECTs from here on.  */
7448       code->expr1 = code->expr2;
7449       code->expr2 = NULL;
7450       return;
7451     }
7452
7453   case_expr = code->expr1;
7454
7455   type = case_expr->ts.type;
7456   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7457     {
7458       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7459                  &case_expr->where, gfc_typename (&case_expr->ts));
7460
7461       /* Punt. Going on here just produce more garbage error messages.  */
7462       return;
7463     }
7464
7465   if (case_expr->rank != 0)
7466     {
7467       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7468                  "expression", &case_expr->where);
7469
7470       /* Punt.  */
7471       return;
7472     }
7473
7474
7475   /* Raise a warning if an INTEGER case value exceeds the range of
7476      the case-expr. Later, all expressions will be promoted to the
7477      largest kind of all case-labels.  */
7478
7479   if (type == BT_INTEGER)
7480     for (body = code->block; body; body = body->block)
7481       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7482         {
7483           if (cp->low
7484               && gfc_check_integer_range (cp->low->value.integer,
7485                                           case_expr->ts.kind) != ARITH_OK)
7486             gfc_warning ("Expression in CASE statement at %L is "
7487                          "not in the range of %s", &cp->low->where,
7488                          gfc_typename (&case_expr->ts));
7489
7490           if (cp->high
7491               && cp->low != cp->high
7492               && gfc_check_integer_range (cp->high->value.integer,
7493                                           case_expr->ts.kind) != ARITH_OK)
7494             gfc_warning ("Expression in CASE statement at %L is "
7495                          "not in the range of %s", &cp->high->where,
7496                          gfc_typename (&case_expr->ts));
7497         }
7498
7499   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7500      of the SELECT CASE expression and its CASE values.  Walk the lists
7501      of case values, and if we find a mismatch, promote case_expr to
7502      the appropriate kind.  */
7503
7504   if (type == BT_LOGICAL || type == BT_INTEGER)
7505     {
7506       for (body = code->block; body; body = body->block)
7507         {
7508           /* Walk the case label list.  */
7509           for (cp = body->ext.block.case_list; cp; cp = cp->next)
7510             {
7511               /* Intercept the DEFAULT case.  It does not have a kind.  */
7512               if (cp->low == NULL && cp->high == NULL)
7513                 continue;
7514
7515               /* Unreachable case ranges are discarded, so ignore.  */
7516               if (cp->low != NULL && cp->high != NULL
7517                   && cp->low != cp->high
7518                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7519                 continue;
7520
7521               if (cp->low != NULL
7522                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7523                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7524
7525               if (cp->high != NULL
7526                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7527                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7528             }
7529          }
7530     }
7531
7532   /* Assume there is no DEFAULT case.  */
7533   default_case = NULL;
7534   head = tail = NULL;
7535   ncases = 0;
7536   seen_logical = 0;
7537
7538   for (body = code->block; body; body = body->block)
7539     {
7540       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7541       t = SUCCESS;
7542       seen_unreachable = 0;
7543
7544       /* Walk the case label list, making sure that all case labels
7545          are legal.  */
7546       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7547         {
7548           /* Count the number of cases in the whole construct.  */
7549           ncases++;
7550
7551           /* Intercept the DEFAULT case.  */
7552           if (cp->low == NULL && cp->high == NULL)
7553             {
7554               if (default_case != NULL)
7555                 {
7556                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7557                              "by a second DEFAULT CASE at %L",
7558                              &default_case->where, &cp->where);
7559                   t = FAILURE;
7560                   break;
7561                 }
7562               else
7563                 {
7564                   default_case = cp;
7565                   continue;
7566                 }
7567             }
7568
7569           /* Deal with single value cases and case ranges.  Errors are
7570              issued from the validation function.  */
7571           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7572               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7573             {
7574               t = FAILURE;
7575               break;
7576             }
7577
7578           if (type == BT_LOGICAL
7579               && ((cp->low == NULL || cp->high == NULL)
7580                   || cp->low != cp->high))
7581             {
7582               gfc_error ("Logical range in CASE statement at %L is not "
7583                          "allowed", &cp->low->where);
7584               t = FAILURE;
7585               break;
7586             }
7587
7588           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7589             {
7590               int value;
7591               value = cp->low->value.logical == 0 ? 2 : 1;
7592               if (value & seen_logical)
7593                 {
7594                   gfc_error ("Constant logical value in CASE statement "
7595                              "is repeated at %L",
7596                              &cp->low->where);
7597                   t = FAILURE;
7598                   break;
7599                 }
7600               seen_logical |= value;
7601             }
7602
7603           if (cp->low != NULL && cp->high != NULL
7604               && cp->low != cp->high
7605               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7606             {
7607               if (gfc_option.warn_surprising)
7608                 gfc_warning ("Range specification at %L can never "
7609                              "be matched", &cp->where);
7610
7611               cp->unreachable = 1;
7612               seen_unreachable = 1;
7613             }
7614           else
7615             {
7616               /* If the case range can be matched, it can also overlap with
7617                  other cases.  To make sure it does not, we put it in a
7618                  double linked list here.  We sort that with a merge sort
7619                  later on to detect any overlapping cases.  */
7620               if (!head)
7621                 {
7622                   head = tail = cp;
7623                   head->right = head->left = NULL;
7624                 }
7625               else
7626                 {
7627                   tail->right = cp;
7628                   tail->right->left = tail;
7629                   tail = tail->right;
7630                   tail->right = NULL;
7631                 }
7632             }
7633         }
7634
7635       /* It there was a failure in the previous case label, give up
7636          for this case label list.  Continue with the next block.  */
7637       if (t == FAILURE)
7638         continue;
7639
7640       /* See if any case labels that are unreachable have been seen.
7641          If so, we eliminate them.  This is a bit of a kludge because
7642          the case lists for a single case statement (label) is a
7643          single forward linked lists.  */
7644       if (seen_unreachable)
7645       {
7646         /* Advance until the first case in the list is reachable.  */
7647         while (body->ext.block.case_list != NULL
7648                && body->ext.block.case_list->unreachable)
7649           {
7650             gfc_case *n = body->ext.block.case_list;
7651             body->ext.block.case_list = body->ext.block.case_list->next;
7652             n->next = NULL;
7653             gfc_free_case_list (n);
7654           }
7655
7656         /* Strip all other unreachable cases.  */
7657         if (body->ext.block.case_list)
7658           {
7659             for (cp = body->ext.block.case_list; cp->next; cp = cp->next)
7660               {
7661                 if (cp->next->unreachable)
7662                   {
7663                     gfc_case *n = cp->next;
7664                     cp->next = cp->next->next;
7665                     n->next = NULL;
7666                     gfc_free_case_list (n);
7667                   }
7668               }
7669           }
7670       }
7671     }
7672
7673   /* See if there were overlapping cases.  If the check returns NULL,
7674      there was overlap.  In that case we don't do anything.  If head
7675      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7676      then used during code generation for SELECT CASE constructs with
7677      a case expression of a CHARACTER type.  */
7678   if (head)
7679     {
7680       head = check_case_overlap (head);
7681
7682       /* Prepend the default_case if it is there.  */
7683       if (head != NULL && default_case)
7684         {
7685           default_case->left = NULL;
7686           default_case->right = head;
7687           head->left = default_case;
7688         }
7689     }
7690
7691   /* Eliminate dead blocks that may be the result if we've seen
7692      unreachable case labels for a block.  */
7693   for (body = code; body && body->block; body = body->block)
7694     {
7695       if (body->block->ext.block.case_list == NULL)
7696         {
7697           /* Cut the unreachable block from the code chain.  */
7698           gfc_code *c = body->block;
7699           body->block = c->block;
7700
7701           /* Kill the dead block, but not the blocks below it.  */
7702           c->block = NULL;
7703           gfc_free_statements (c);
7704         }
7705     }
7706
7707   /* More than two cases is legal but insane for logical selects.
7708      Issue a warning for it.  */
7709   if (gfc_option.warn_surprising && type == BT_LOGICAL
7710       && ncases > 2)
7711     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7712                  &code->loc);
7713 }
7714
7715
7716 /* Check if a derived type is extensible.  */
7717
7718 bool
7719 gfc_type_is_extensible (gfc_symbol *sym)
7720 {
7721   return !(sym->attr.is_bind_c || sym->attr.sequence);
7722 }
7723
7724
7725 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7726    correct as well as possibly the array-spec.  */
7727
7728 static void
7729 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7730 {
7731   gfc_expr* target;
7732
7733   gcc_assert (sym->assoc);
7734   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7735
7736   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7737      case, return.  Resolution will be called later manually again when
7738      this is done.  */
7739   target = sym->assoc->target;
7740   if (!target)
7741     return;
7742   gcc_assert (!sym->assoc->dangling);
7743
7744   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7745     return;
7746
7747   /* For variable targets, we get some attributes from the target.  */
7748   if (target->expr_type == EXPR_VARIABLE)
7749     {
7750       gfc_symbol* tsym;
7751
7752       gcc_assert (target->symtree);
7753       tsym = target->symtree->n.sym;
7754
7755       sym->attr.asynchronous = tsym->attr.asynchronous;
7756       sym->attr.volatile_ = tsym->attr.volatile_;
7757
7758       sym->attr.target = (tsym->attr.target || tsym->attr.pointer);
7759     }
7760
7761   /* Get type if this was not already set.  Note that it can be
7762      some other type than the target in case this is a SELECT TYPE
7763      selector!  So we must not update when the type is already there.  */
7764   if (sym->ts.type == BT_UNKNOWN)
7765     sym->ts = target->ts;
7766   gcc_assert (sym->ts.type != BT_UNKNOWN);
7767
7768   /* See if this is a valid association-to-variable.  */
7769   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
7770                           && !gfc_has_vector_subscript (target));
7771
7772   /* Finally resolve if this is an array or not.  */
7773   if (sym->attr.dimension && target->rank == 0)
7774     {
7775       gfc_error ("Associate-name '%s' at %L is used as array",
7776                  sym->name, &sym->declared_at);
7777       sym->attr.dimension = 0;
7778       return;
7779     }
7780   if (target->rank > 0)
7781     sym->attr.dimension = 1;
7782
7783   if (sym->attr.dimension)
7784     {
7785       sym->as = gfc_get_array_spec ();
7786       sym->as->rank = target->rank;
7787       sym->as->type = AS_DEFERRED;
7788
7789       /* Target must not be coindexed, thus the associate-variable
7790          has no corank.  */
7791       sym->as->corank = 0;
7792     }
7793 }
7794
7795
7796 /* Resolve a SELECT TYPE statement.  */
7797
7798 static void
7799 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
7800 {
7801   gfc_symbol *selector_type;
7802   gfc_code *body, *new_st, *if_st, *tail;
7803   gfc_code *class_is = NULL, *default_case = NULL;
7804   gfc_case *c;
7805   gfc_symtree *st;
7806   char name[GFC_MAX_SYMBOL_LEN];
7807   gfc_namespace *ns;
7808   int error = 0;
7809
7810   ns = code->ext.block.ns;
7811   gfc_resolve (ns);
7812
7813   /* Check for F03:C813.  */
7814   if (code->expr1->ts.type != BT_CLASS
7815       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
7816     {
7817       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
7818                  "at %L", &code->loc);
7819       return;
7820     }
7821
7822   if (code->expr2)
7823     {
7824       if (code->expr1->symtree->n.sym->attr.untyped)
7825         code->expr1->symtree->n.sym->ts = code->expr2->ts;
7826       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
7827     }
7828   else
7829     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
7830
7831   /* Loop over TYPE IS / CLASS IS cases.  */
7832   for (body = code->block; body; body = body->block)
7833     {
7834       c = body->ext.block.case_list;
7835
7836       /* Check F03:C815.  */
7837       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7838           && !gfc_type_is_extensible (c->ts.u.derived))
7839         {
7840           gfc_error ("Derived type '%s' at %L must be extensible",
7841                      c->ts.u.derived->name, &c->where);
7842           error++;
7843           continue;
7844         }
7845
7846       /* Check F03:C816.  */
7847       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
7848           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
7849         {
7850           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
7851                      c->ts.u.derived->name, &c->where, selector_type->name);
7852           error++;
7853           continue;
7854         }
7855
7856       /* Intercept the DEFAULT case.  */
7857       if (c->ts.type == BT_UNKNOWN)
7858         {
7859           /* Check F03:C818.  */
7860           if (default_case)
7861             {
7862               gfc_error ("The DEFAULT CASE at %L cannot be followed "
7863                          "by a second DEFAULT CASE at %L",
7864                          &default_case->ext.block.case_list->where, &c->where);
7865               error++;
7866               continue;
7867             }
7868
7869           default_case = body;
7870         }
7871     }
7872     
7873   if (error > 0)
7874     return;
7875
7876   /* Transform SELECT TYPE statement to BLOCK and associate selector to
7877      target if present.  If there are any EXIT statements referring to the
7878      SELECT TYPE construct, this is no problem because the gfc_code
7879      reference stays the same and EXIT is equally possible from the BLOCK
7880      it is changed to.  */
7881   code->op = EXEC_BLOCK;
7882   if (code->expr2)
7883     {
7884       gfc_association_list* assoc;
7885
7886       assoc = gfc_get_association_list ();
7887       assoc->st = code->expr1->symtree;
7888       assoc->target = gfc_copy_expr (code->expr2);
7889       /* assoc->variable will be set by resolve_assoc_var.  */
7890       
7891       code->ext.block.assoc = assoc;
7892       code->expr1->symtree->n.sym->assoc = assoc;
7893
7894       resolve_assoc_var (code->expr1->symtree->n.sym, false);
7895     }
7896   else
7897     code->ext.block.assoc = NULL;
7898
7899   /* Add EXEC_SELECT to switch on type.  */
7900   new_st = gfc_get_code ();
7901   new_st->op = code->op;
7902   new_st->expr1 = code->expr1;
7903   new_st->expr2 = code->expr2;
7904   new_st->block = code->block;
7905   code->expr1 = code->expr2 =  NULL;
7906   code->block = NULL;
7907   if (!ns->code)
7908     ns->code = new_st;
7909   else
7910     ns->code->next = new_st;
7911   code = new_st;
7912   code->op = EXEC_SELECT;
7913   gfc_add_vptr_component (code->expr1);
7914   gfc_add_hash_component (code->expr1);
7915
7916   /* Loop over TYPE IS / CLASS IS cases.  */
7917   for (body = code->block; body; body = body->block)
7918     {
7919       c = body->ext.block.case_list;
7920
7921       if (c->ts.type == BT_DERIVED)
7922         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
7923                                              c->ts.u.derived->hash_value);
7924
7925       else if (c->ts.type == BT_UNKNOWN)
7926         continue;
7927
7928       /* Associate temporary to selector.  This should only be done
7929          when this case is actually true, so build a new ASSOCIATE
7930          that does precisely this here (instead of using the
7931          'global' one).  */
7932
7933       if (c->ts.type == BT_CLASS)
7934         sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
7935       else
7936         sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
7937       st = gfc_find_symtree (ns->sym_root, name);
7938       gcc_assert (st->n.sym->assoc);
7939       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
7940       if (c->ts.type == BT_DERIVED)
7941         gfc_add_data_component (st->n.sym->assoc->target);
7942
7943       new_st = gfc_get_code ();
7944       new_st->op = EXEC_BLOCK;
7945       new_st->ext.block.ns = gfc_build_block_ns (ns);
7946       new_st->ext.block.ns->code = body->next;
7947       body->next = new_st;
7948
7949       /* Chain in the new list only if it is marked as dangling.  Otherwise
7950          there is a CASE label overlap and this is already used.  Just ignore,
7951          the error is diagonsed elsewhere.  */
7952       if (st->n.sym->assoc->dangling)
7953         {
7954           new_st->ext.block.assoc = st->n.sym->assoc;
7955           st->n.sym->assoc->dangling = 0;
7956         }
7957
7958       resolve_assoc_var (st->n.sym, false);
7959     }
7960     
7961   /* Take out CLASS IS cases for separate treatment.  */
7962   body = code;
7963   while (body && body->block)
7964     {
7965       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
7966         {
7967           /* Add to class_is list.  */
7968           if (class_is == NULL)
7969             { 
7970               class_is = body->block;
7971               tail = class_is;
7972             }
7973           else
7974             {
7975               for (tail = class_is; tail->block; tail = tail->block) ;
7976               tail->block = body->block;
7977               tail = tail->block;
7978             }
7979           /* Remove from EXEC_SELECT list.  */
7980           body->block = body->block->block;
7981           tail->block = NULL;
7982         }
7983       else
7984         body = body->block;
7985     }
7986
7987   if (class_is)
7988     {
7989       gfc_symbol *vtab;
7990       
7991       if (!default_case)
7992         {
7993           /* Add a default case to hold the CLASS IS cases.  */
7994           for (tail = code; tail->block; tail = tail->block) ;
7995           tail->block = gfc_get_code ();
7996           tail = tail->block;
7997           tail->op = EXEC_SELECT_TYPE;
7998           tail->ext.block.case_list = gfc_get_case ();
7999           tail->ext.block.case_list->ts.type = BT_UNKNOWN;
8000           tail->next = NULL;
8001           default_case = tail;
8002         }
8003
8004       /* More than one CLASS IS block?  */
8005       if (class_is->block)
8006         {
8007           gfc_code **c1,*c2;
8008           bool swapped;
8009           /* Sort CLASS IS blocks by extension level.  */
8010           do
8011             {
8012               swapped = false;
8013               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
8014                 {
8015                   c2 = (*c1)->block;
8016                   /* F03:C817 (check for doubles).  */
8017                   if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
8018                       == c2->ext.block.case_list->ts.u.derived->hash_value)
8019                     {
8020                       gfc_error ("Double CLASS IS block in SELECT TYPE "
8021                                  "statement at %L",
8022                                  &c2->ext.block.case_list->where);
8023                       return;
8024                     }
8025                   if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
8026                       < c2->ext.block.case_list->ts.u.derived->attr.extension)
8027                     {
8028                       /* Swap.  */
8029                       (*c1)->block = c2->block;
8030                       c2->block = *c1;
8031                       *c1 = c2;
8032                       swapped = true;
8033                     }
8034                 }
8035             }
8036           while (swapped);
8037         }
8038         
8039       /* Generate IF chain.  */
8040       if_st = gfc_get_code ();
8041       if_st->op = EXEC_IF;
8042       new_st = if_st;
8043       for (body = class_is; body; body = body->block)
8044         {
8045           new_st->block = gfc_get_code ();
8046           new_st = new_st->block;
8047           new_st->op = EXEC_IF;
8048           /* Set up IF condition: Call _gfortran_is_extension_of.  */
8049           new_st->expr1 = gfc_get_expr ();
8050           new_st->expr1->expr_type = EXPR_FUNCTION;
8051           new_st->expr1->ts.type = BT_LOGICAL;
8052           new_st->expr1->ts.kind = 4;
8053           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
8054           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
8055           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
8056           /* Set up arguments.  */
8057           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
8058           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
8059           new_st->expr1->value.function.actual->expr->where = code->loc;
8060           gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
8061           vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
8062           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
8063           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
8064           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
8065           new_st->next = body->next;
8066         }
8067         if (default_case->next)
8068           {
8069             new_st->block = gfc_get_code ();
8070             new_st = new_st->block;
8071             new_st->op = EXEC_IF;
8072             new_st->next = default_case->next;
8073           }
8074           
8075         /* Replace CLASS DEFAULT code by the IF chain.  */
8076         default_case->next = if_st;
8077     }
8078
8079   /* Resolve the internal code.  This can not be done earlier because
8080      it requires that the sym->assoc of selectors is set already.  */
8081   gfc_current_ns = ns;
8082   gfc_resolve_blocks (code->block, gfc_current_ns);
8083   gfc_current_ns = old_ns;
8084
8085   resolve_select (code);
8086 }
8087
8088
8089 /* Resolve a transfer statement. This is making sure that:
8090    -- a derived type being transferred has only non-pointer components
8091    -- a derived type being transferred doesn't have private components, unless 
8092       it's being transferred from the module where the type was defined
8093    -- we're not trying to transfer a whole assumed size array.  */
8094
8095 static void
8096 resolve_transfer (gfc_code *code)
8097 {
8098   gfc_typespec *ts;
8099   gfc_symbol *sym;
8100   gfc_ref *ref;
8101   gfc_expr *exp;
8102
8103   exp = code->expr1;
8104
8105   while (exp != NULL && exp->expr_type == EXPR_OP
8106          && exp->value.op.op == INTRINSIC_PARENTHESES)
8107     exp = exp->value.op.op1;
8108
8109   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
8110                       && exp->expr_type != EXPR_FUNCTION))
8111     return;
8112
8113   /* If we are reading, the variable will be changed.  Note that
8114      code->ext.dt may be NULL if the TRANSFER is related to
8115      an INQUIRE statement -- but in this case, we are not reading, either.  */
8116   if (code->ext.dt && code->ext.dt->dt_io_kind->value.iokind == M_READ
8117       && gfc_check_vardef_context (exp, false, false, _("item in READ"))
8118          == FAILURE)
8119     return;
8120
8121   sym = exp->symtree->n.sym;
8122   ts = &sym->ts;
8123
8124   /* Go to actual component transferred.  */
8125   for (ref = exp->ref; ref; ref = ref->next)
8126     if (ref->type == REF_COMPONENT)
8127       ts = &ref->u.c.component->ts;
8128
8129   if (ts->type == BT_CLASS)
8130     {
8131       /* FIXME: Test for defined input/output.  */
8132       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
8133                 "it is processed by a defined input/output procedure",
8134                 &code->loc);
8135       return;
8136     }
8137
8138   if (ts->type == BT_DERIVED)
8139     {
8140       /* Check that transferred derived type doesn't contain POINTER
8141          components.  */
8142       if (ts->u.derived->attr.pointer_comp)
8143         {
8144           gfc_error ("Data transfer element at %L cannot have POINTER "
8145                      "components unless it is processed by a defined "
8146                      "input/output procedure", &code->loc);
8147           return;
8148         }
8149
8150       /* F08:C935.  */
8151       if (ts->u.derived->attr.proc_pointer_comp)
8152         {
8153           gfc_error ("Data transfer element at %L cannot have "
8154                      "procedure pointer components", &code->loc);
8155           return;
8156         }
8157
8158       if (ts->u.derived->attr.alloc_comp)
8159         {
8160           gfc_error ("Data transfer element at %L cannot have ALLOCATABLE "
8161                      "components unless it is processed by a defined "
8162                      "input/output procedure", &code->loc);
8163           return;
8164         }
8165
8166       if (derived_inaccessible (ts->u.derived))
8167         {
8168           gfc_error ("Data transfer element at %L cannot have "
8169                      "PRIVATE components",&code->loc);
8170           return;
8171         }
8172     }
8173
8174   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE
8175       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
8176     {
8177       gfc_error ("Data transfer element at %L cannot be a full reference to "
8178                  "an assumed-size array", &code->loc);
8179       return;
8180     }
8181 }
8182
8183
8184 /*********** Toplevel code resolution subroutines ***********/
8185
8186 /* Find the set of labels that are reachable from this block.  We also
8187    record the last statement in each block.  */
8188      
8189 static void
8190 find_reachable_labels (gfc_code *block)
8191 {
8192   gfc_code *c;
8193
8194   if (!block)
8195     return;
8196
8197   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8198
8199   /* Collect labels in this block.  We don't keep those corresponding
8200      to END {IF|SELECT}, these are checked in resolve_branch by going
8201      up through the code_stack.  */
8202   for (c = block; c; c = c->next)
8203     {
8204       if (c->here && c->op != EXEC_END_NESTED_BLOCK)
8205         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8206     }
8207
8208   /* Merge with labels from parent block.  */
8209   if (cs_base->prev)
8210     {
8211       gcc_assert (cs_base->prev->reachable_labels);
8212       bitmap_ior_into (cs_base->reachable_labels,
8213                        cs_base->prev->reachable_labels);
8214     }
8215 }
8216
8217
8218 static void
8219 resolve_lock_unlock (gfc_code *code)
8220 {
8221   if (code->expr1->ts.type != BT_DERIVED
8222       || code->expr1->expr_type != EXPR_VARIABLE
8223       || code->expr1->ts.u.derived->from_intmod != INTMOD_ISO_FORTRAN_ENV
8224       || code->expr1->ts.u.derived->intmod_sym_id != ISOFORTRAN_LOCK_TYPE
8225       || code->expr1->rank != 0
8226       || (!gfc_is_coarray (code->expr1) && !gfc_is_coindexed (code->expr1)))
8227     gfc_error ("Lock variable at %L must be a scalar of type LOCK_TYPE",
8228                &code->expr1->where);
8229
8230   /* Check STAT.  */
8231   if (code->expr2
8232       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8233           || code->expr2->expr_type != EXPR_VARIABLE))
8234     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8235                &code->expr2->where);
8236
8237   if (code->expr2
8238       && gfc_check_vardef_context (code->expr2, false, false,
8239                                    _("STAT variable")) == FAILURE)
8240     return;
8241
8242   /* Check ERRMSG.  */
8243   if (code->expr3
8244       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8245           || code->expr3->expr_type != EXPR_VARIABLE))
8246     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8247                &code->expr3->where);
8248
8249   if (code->expr3
8250       && gfc_check_vardef_context (code->expr3, false, false,
8251                                    _("ERRMSG variable")) == FAILURE)
8252     return;
8253
8254   /* Check ACQUIRED_LOCK.  */
8255   if (code->expr4
8256       && (code->expr4->ts.type != BT_LOGICAL || code->expr4->rank != 0
8257           || code->expr4->expr_type != EXPR_VARIABLE))
8258     gfc_error ("ACQUIRED_LOCK= argument at %L must be a scalar LOGICAL "
8259                "variable", &code->expr4->where);
8260
8261   if (code->expr4
8262       && gfc_check_vardef_context (code->expr4, false, false,
8263                                    _("ACQUIRED_LOCK variable")) == FAILURE)
8264     return;
8265 }
8266
8267
8268 static void
8269 resolve_sync (gfc_code *code)
8270 {
8271   /* Check imageset. The * case matches expr1 == NULL.  */
8272   if (code->expr1)
8273     {
8274       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8275         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8276                    "INTEGER expression", &code->expr1->where);
8277       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8278           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8279         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8280                    &code->expr1->where);
8281       else if (code->expr1->expr_type == EXPR_ARRAY
8282                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8283         {
8284            gfc_constructor *cons;
8285            cons = gfc_constructor_first (code->expr1->value.constructor);
8286            for (; cons; cons = gfc_constructor_next (cons))
8287              if (cons->expr->expr_type == EXPR_CONSTANT
8288                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8289                gfc_error ("Imageset argument at %L must between 1 and "
8290                           "num_images()", &cons->expr->where);
8291         }
8292     }
8293
8294   /* Check STAT.  */
8295   if (code->expr2
8296       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8297           || code->expr2->expr_type != EXPR_VARIABLE))
8298     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8299                &code->expr2->where);
8300
8301   /* Check ERRMSG.  */
8302   if (code->expr3
8303       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8304           || code->expr3->expr_type != EXPR_VARIABLE))
8305     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8306                &code->expr3->where);
8307 }
8308
8309
8310 /* Given a branch to a label, see if the branch is conforming.
8311    The code node describes where the branch is located.  */
8312
8313 static void
8314 resolve_branch (gfc_st_label *label, gfc_code *code)
8315 {
8316   code_stack *stack;
8317
8318   if (label == NULL)
8319     return;
8320
8321   /* Step one: is this a valid branching target?  */
8322
8323   if (label->defined == ST_LABEL_UNKNOWN)
8324     {
8325       gfc_error ("Label %d referenced at %L is never defined", label->value,
8326                  &label->where);
8327       return;
8328     }
8329
8330   if (label->defined != ST_LABEL_TARGET)
8331     {
8332       gfc_error ("Statement at %L is not a valid branch target statement "
8333                  "for the branch statement at %L", &label->where, &code->loc);
8334       return;
8335     }
8336
8337   /* Step two: make sure this branch is not a branch to itself ;-)  */
8338
8339   if (code->here == label)
8340     {
8341       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8342       return;
8343     }
8344
8345   /* Step three:  See if the label is in the same block as the
8346      branching statement.  The hard work has been done by setting up
8347      the bitmap reachable_labels.  */
8348
8349   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8350     {
8351       /* Check now whether there is a CRITICAL construct; if so, check
8352          whether the label is still visible outside of the CRITICAL block,
8353          which is invalid.  */
8354       for (stack = cs_base; stack; stack = stack->prev)
8355         if (stack->current->op == EXEC_CRITICAL
8356             && bitmap_bit_p (stack->reachable_labels, label->value))
8357           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8358                       " at %L", &code->loc, &label->where);
8359
8360       return;
8361     }
8362
8363   /* Step four:  If we haven't found the label in the bitmap, it may
8364     still be the label of the END of the enclosing block, in which
8365     case we find it by going up the code_stack.  */
8366
8367   for (stack = cs_base; stack; stack = stack->prev)
8368     {
8369       if (stack->current->next && stack->current->next->here == label)
8370         break;
8371       if (stack->current->op == EXEC_CRITICAL)
8372         {
8373           /* Note: A label at END CRITICAL does not leave the CRITICAL
8374              construct as END CRITICAL is still part of it.  */
8375           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8376                       " at %L", &code->loc, &label->where);
8377           return;
8378         }
8379     }
8380
8381   if (stack)
8382     {
8383       gcc_assert (stack->current->next->op == EXEC_END_NESTED_BLOCK);
8384       return;
8385     }
8386
8387   /* The label is not in an enclosing block, so illegal.  This was
8388      allowed in Fortran 66, so we allow it as extension.  No
8389      further checks are necessary in this case.  */
8390   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8391                   "as the GOTO statement at %L", &label->where,
8392                   &code->loc);
8393   return;
8394 }
8395
8396
8397 /* Check whether EXPR1 has the same shape as EXPR2.  */
8398
8399 static gfc_try
8400 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8401 {
8402   mpz_t shape[GFC_MAX_DIMENSIONS];
8403   mpz_t shape2[GFC_MAX_DIMENSIONS];
8404   gfc_try result = FAILURE;
8405   int i;
8406
8407   /* Compare the rank.  */
8408   if (expr1->rank != expr2->rank)
8409     return result;
8410
8411   /* Compare the size of each dimension.  */
8412   for (i=0; i<expr1->rank; i++)
8413     {
8414       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8415         goto ignore;
8416
8417       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8418         goto ignore;
8419
8420       if (mpz_cmp (shape[i], shape2[i]))
8421         goto over;
8422     }
8423
8424   /* When either of the two expression is an assumed size array, we
8425      ignore the comparison of dimension sizes.  */
8426 ignore:
8427   result = SUCCESS;
8428
8429 over:
8430   gfc_clear_shape (shape, i);
8431   gfc_clear_shape (shape2, i);
8432   return result;
8433 }
8434
8435
8436 /* Check whether a WHERE assignment target or a WHERE mask expression
8437    has the same shape as the outmost WHERE mask expression.  */
8438
8439 static void
8440 resolve_where (gfc_code *code, gfc_expr *mask)
8441 {
8442   gfc_code *cblock;
8443   gfc_code *cnext;
8444   gfc_expr *e = NULL;
8445
8446   cblock = code->block;
8447
8448   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8449      In case of nested WHERE, only the outmost one is stored.  */
8450   if (mask == NULL) /* outmost WHERE */
8451     e = cblock->expr1;
8452   else /* inner WHERE */
8453     e = mask;
8454
8455   while (cblock)
8456     {
8457       if (cblock->expr1)
8458         {
8459           /* Check if the mask-expr has a consistent shape with the
8460              outmost WHERE mask-expr.  */
8461           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8462             gfc_error ("WHERE mask at %L has inconsistent shape",
8463                        &cblock->expr1->where);
8464          }
8465
8466       /* the assignment statement of a WHERE statement, or the first
8467          statement in where-body-construct of a WHERE construct */
8468       cnext = cblock->next;
8469       while (cnext)
8470         {
8471           switch (cnext->op)
8472             {
8473             /* WHERE assignment statement */
8474             case EXEC_ASSIGN:
8475
8476               /* Check shape consistent for WHERE assignment target.  */
8477               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8478                gfc_error ("WHERE assignment target at %L has "
8479                           "inconsistent shape", &cnext->expr1->where);
8480               break;
8481
8482   
8483             case EXEC_ASSIGN_CALL:
8484               resolve_call (cnext);
8485               if (!cnext->resolved_sym->attr.elemental)
8486                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8487                           &cnext->ext.actual->expr->where);
8488               break;
8489
8490             /* WHERE or WHERE construct is part of a where-body-construct */
8491             case EXEC_WHERE:
8492               resolve_where (cnext, e);
8493               break;
8494
8495             default:
8496               gfc_error ("Unsupported statement inside WHERE at %L",
8497                          &cnext->loc);
8498             }
8499          /* the next statement within the same where-body-construct */
8500          cnext = cnext->next;
8501        }
8502     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8503     cblock = cblock->block;
8504   }
8505 }
8506
8507
8508 /* Resolve assignment in FORALL construct.
8509    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8510    FORALL index variables.  */
8511
8512 static void
8513 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8514 {
8515   int n;
8516
8517   for (n = 0; n < nvar; n++)
8518     {
8519       gfc_symbol *forall_index;
8520
8521       forall_index = var_expr[n]->symtree->n.sym;
8522
8523       /* Check whether the assignment target is one of the FORALL index
8524          variable.  */
8525       if ((code->expr1->expr_type == EXPR_VARIABLE)
8526           && (code->expr1->symtree->n.sym == forall_index))
8527         gfc_error ("Assignment to a FORALL index variable at %L",
8528                    &code->expr1->where);
8529       else
8530         {
8531           /* If one of the FORALL index variables doesn't appear in the
8532              assignment variable, then there could be a many-to-one
8533              assignment.  Emit a warning rather than an error because the
8534              mask could be resolving this problem.  */
8535           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8536             gfc_warning ("The FORALL with index '%s' is not used on the "
8537                          "left side of the assignment at %L and so might "
8538                          "cause multiple assignment to this object",
8539                          var_expr[n]->symtree->name, &code->expr1->where);
8540         }
8541     }
8542 }
8543
8544
8545 /* Resolve WHERE statement in FORALL construct.  */
8546
8547 static void
8548 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8549                                   gfc_expr **var_expr)
8550 {
8551   gfc_code *cblock;
8552   gfc_code *cnext;
8553
8554   cblock = code->block;
8555   while (cblock)
8556     {
8557       /* the assignment statement of a WHERE statement, or the first
8558          statement in where-body-construct of a WHERE construct */
8559       cnext = cblock->next;
8560       while (cnext)
8561         {
8562           switch (cnext->op)
8563             {
8564             /* WHERE assignment statement */
8565             case EXEC_ASSIGN:
8566               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8567               break;
8568   
8569             /* WHERE operator assignment statement */
8570             case EXEC_ASSIGN_CALL:
8571               resolve_call (cnext);
8572               if (!cnext->resolved_sym->attr.elemental)
8573                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8574                           &cnext->ext.actual->expr->where);
8575               break;
8576
8577             /* WHERE or WHERE construct is part of a where-body-construct */
8578             case EXEC_WHERE:
8579               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8580               break;
8581
8582             default:
8583               gfc_error ("Unsupported statement inside WHERE at %L",
8584                          &cnext->loc);
8585             }
8586           /* the next statement within the same where-body-construct */
8587           cnext = cnext->next;
8588         }
8589       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8590       cblock = cblock->block;
8591     }
8592 }
8593
8594
8595 /* Traverse the FORALL body to check whether the following errors exist:
8596    1. For assignment, check if a many-to-one assignment happens.
8597    2. For WHERE statement, check the WHERE body to see if there is any
8598       many-to-one assignment.  */
8599
8600 static void
8601 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8602 {
8603   gfc_code *c;
8604
8605   c = code->block->next;
8606   while (c)
8607     {
8608       switch (c->op)
8609         {
8610         case EXEC_ASSIGN:
8611         case EXEC_POINTER_ASSIGN:
8612           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8613           break;
8614
8615         case EXEC_ASSIGN_CALL:
8616           resolve_call (c);
8617           break;
8618
8619         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8620            there is no need to handle it here.  */
8621         case EXEC_FORALL:
8622           break;
8623         case EXEC_WHERE:
8624           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8625           break;
8626         default:
8627           break;
8628         }
8629       /* The next statement in the FORALL body.  */
8630       c = c->next;
8631     }
8632 }
8633
8634
8635 /* Counts the number of iterators needed inside a forall construct, including
8636    nested forall constructs. This is used to allocate the needed memory 
8637    in gfc_resolve_forall.  */
8638
8639 static int 
8640 gfc_count_forall_iterators (gfc_code *code)
8641 {
8642   int max_iters, sub_iters, current_iters;
8643   gfc_forall_iterator *fa;
8644
8645   gcc_assert(code->op == EXEC_FORALL);
8646   max_iters = 0;
8647   current_iters = 0;
8648
8649   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8650     current_iters ++;
8651   
8652   code = code->block->next;
8653
8654   while (code)
8655     {          
8656       if (code->op == EXEC_FORALL)
8657         {
8658           sub_iters = gfc_count_forall_iterators (code);
8659           if (sub_iters > max_iters)
8660             max_iters = sub_iters;
8661         }
8662       code = code->next;
8663     }
8664
8665   return current_iters + max_iters;
8666 }
8667
8668
8669 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8670    gfc_resolve_forall_body to resolve the FORALL body.  */
8671
8672 static void
8673 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8674 {
8675   static gfc_expr **var_expr;
8676   static int total_var = 0;
8677   static int nvar = 0;
8678   int old_nvar, tmp;
8679   gfc_forall_iterator *fa;
8680   int i;
8681
8682   old_nvar = nvar;
8683
8684   /* Start to resolve a FORALL construct   */
8685   if (forall_save == 0)
8686     {
8687       /* Count the total number of FORALL index in the nested FORALL
8688          construct in order to allocate the VAR_EXPR with proper size.  */
8689       total_var = gfc_count_forall_iterators (code);
8690
8691       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8692       var_expr = XCNEWVEC (gfc_expr *, total_var);
8693     }
8694
8695   /* The information about FORALL iterator, including FORALL index start, end
8696      and stride. The FORALL index can not appear in start, end or stride.  */
8697   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8698     {
8699       /* Check if any outer FORALL index name is the same as the current
8700          one.  */
8701       for (i = 0; i < nvar; i++)
8702         {
8703           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8704             {
8705               gfc_error ("An outer FORALL construct already has an index "
8706                          "with this name %L", &fa->var->where);
8707             }
8708         }
8709
8710       /* Record the current FORALL index.  */
8711       var_expr[nvar] = gfc_copy_expr (fa->var);
8712
8713       nvar++;
8714
8715       /* No memory leak.  */
8716       gcc_assert (nvar <= total_var);
8717     }
8718
8719   /* Resolve the FORALL body.  */
8720   gfc_resolve_forall_body (code, nvar, var_expr);
8721
8722   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8723   gfc_resolve_blocks (code->block, ns);
8724
8725   tmp = nvar;
8726   nvar = old_nvar;
8727   /* Free only the VAR_EXPRs allocated in this frame.  */
8728   for (i = nvar; i < tmp; i++)
8729      gfc_free_expr (var_expr[i]);
8730
8731   if (nvar == 0)
8732     {
8733       /* We are in the outermost FORALL construct.  */
8734       gcc_assert (forall_save == 0);
8735
8736       /* VAR_EXPR is not needed any more.  */
8737       free (var_expr);
8738       total_var = 0;
8739     }
8740 }
8741
8742
8743 /* Resolve a BLOCK construct statement.  */
8744
8745 static void
8746 resolve_block_construct (gfc_code* code)
8747 {
8748   /* Resolve the BLOCK's namespace.  */
8749   gfc_resolve (code->ext.block.ns);
8750
8751   /* For an ASSOCIATE block, the associations (and their targets) are already
8752      resolved during resolve_symbol.  */
8753 }
8754
8755
8756 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8757    DO code nodes.  */
8758
8759 static void resolve_code (gfc_code *, gfc_namespace *);
8760
8761 void
8762 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8763 {
8764   gfc_try t;
8765
8766   for (; b; b = b->block)
8767     {
8768       t = gfc_resolve_expr (b->expr1);
8769       if (gfc_resolve_expr (b->expr2) == FAILURE)
8770         t = FAILURE;
8771
8772       switch (b->op)
8773         {
8774         case EXEC_IF:
8775           if (t == SUCCESS && b->expr1 != NULL
8776               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
8777             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
8778                        &b->expr1->where);
8779           break;
8780
8781         case EXEC_WHERE:
8782           if (t == SUCCESS
8783               && b->expr1 != NULL
8784               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
8785             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
8786                        &b->expr1->where);
8787           break;
8788
8789         case EXEC_GOTO:
8790           resolve_branch (b->label1, b);
8791           break;
8792
8793         case EXEC_BLOCK:
8794           resolve_block_construct (b);
8795           break;
8796
8797         case EXEC_SELECT:
8798         case EXEC_SELECT_TYPE:
8799         case EXEC_FORALL:
8800         case EXEC_DO:
8801         case EXEC_DO_WHILE:
8802         case EXEC_CRITICAL:
8803         case EXEC_READ:
8804         case EXEC_WRITE:
8805         case EXEC_IOLENGTH:
8806         case EXEC_WAIT:
8807           break;
8808
8809         case EXEC_OMP_ATOMIC:
8810         case EXEC_OMP_CRITICAL:
8811         case EXEC_OMP_DO:
8812         case EXEC_OMP_MASTER:
8813         case EXEC_OMP_ORDERED:
8814         case EXEC_OMP_PARALLEL:
8815         case EXEC_OMP_PARALLEL_DO:
8816         case EXEC_OMP_PARALLEL_SECTIONS:
8817         case EXEC_OMP_PARALLEL_WORKSHARE:
8818         case EXEC_OMP_SECTIONS:
8819         case EXEC_OMP_SINGLE:
8820         case EXEC_OMP_TASK:
8821         case EXEC_OMP_TASKWAIT:
8822         case EXEC_OMP_TASKYIELD:
8823         case EXEC_OMP_WORKSHARE:
8824           break;
8825
8826         default:
8827           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
8828         }
8829
8830       resolve_code (b->next, ns);
8831     }
8832 }
8833
8834
8835 /* Does everything to resolve an ordinary assignment.  Returns true
8836    if this is an interface assignment.  */
8837 static bool
8838 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
8839 {
8840   bool rval = false;
8841   gfc_expr *lhs;
8842   gfc_expr *rhs;
8843   int llen = 0;
8844   int rlen = 0;
8845   int n;
8846   gfc_ref *ref;
8847
8848   if (gfc_extend_assign (code, ns) == SUCCESS)
8849     {
8850       gfc_expr** rhsptr;
8851
8852       if (code->op == EXEC_ASSIGN_CALL)
8853         {
8854           lhs = code->ext.actual->expr;
8855           rhsptr = &code->ext.actual->next->expr;
8856         }
8857       else
8858         {
8859           gfc_actual_arglist* args;
8860           gfc_typebound_proc* tbp;
8861
8862           gcc_assert (code->op == EXEC_COMPCALL);
8863
8864           args = code->expr1->value.compcall.actual;
8865           lhs = args->expr;
8866           rhsptr = &args->next->expr;
8867
8868           tbp = code->expr1->value.compcall.tbp;
8869           gcc_assert (!tbp->is_generic);
8870         }
8871
8872       /* Make a temporary rhs when there is a default initializer
8873          and rhs is the same symbol as the lhs.  */
8874       if ((*rhsptr)->expr_type == EXPR_VARIABLE
8875             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
8876             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
8877             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
8878         *rhsptr = gfc_get_parentheses (*rhsptr);
8879
8880       return true;
8881     }
8882
8883   lhs = code->expr1;
8884   rhs = code->expr2;
8885
8886   if (rhs->is_boz
8887       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
8888                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
8889                          &code->loc) == FAILURE)
8890     return false;
8891
8892   /* Handle the case of a BOZ literal on the RHS.  */
8893   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
8894     {
8895       int rc;
8896       if (gfc_option.warn_surprising)
8897         gfc_warning ("BOZ literal at %L is bitwise transferred "
8898                      "non-integer symbol '%s'", &code->loc,
8899                      lhs->symtree->n.sym->name);
8900
8901       if (!gfc_convert_boz (rhs, &lhs->ts))
8902         return false;
8903       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
8904         {
8905           if (rc == ARITH_UNDERFLOW)
8906             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
8907                        ". This check can be disabled with the option "
8908                        "-fno-range-check", &rhs->where);
8909           else if (rc == ARITH_OVERFLOW)
8910             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
8911                        ". This check can be disabled with the option "
8912                        "-fno-range-check", &rhs->where);
8913           else if (rc == ARITH_NAN)
8914             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
8915                        ". This check can be disabled with the option "
8916                        "-fno-range-check", &rhs->where);
8917           return false;
8918         }
8919     }
8920
8921   if (lhs->ts.type == BT_CHARACTER
8922         && gfc_option.warn_character_truncation)
8923     {
8924       if (lhs->ts.u.cl != NULL
8925             && lhs->ts.u.cl->length != NULL
8926             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8927         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
8928
8929       if (rhs->expr_type == EXPR_CONSTANT)
8930         rlen = rhs->value.character.length;
8931
8932       else if (rhs->ts.u.cl != NULL
8933                  && rhs->ts.u.cl->length != NULL
8934                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
8935         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
8936
8937       if (rlen && llen && rlen > llen)
8938         gfc_warning_now ("CHARACTER expression will be truncated "
8939                          "in assignment (%d/%d) at %L",
8940                          llen, rlen, &code->loc);
8941     }
8942
8943   /* Ensure that a vector index expression for the lvalue is evaluated
8944      to a temporary if the lvalue symbol is referenced in it.  */
8945   if (lhs->rank)
8946     {
8947       for (ref = lhs->ref; ref; ref= ref->next)
8948         if (ref->type == REF_ARRAY)
8949           {
8950             for (n = 0; n < ref->u.ar.dimen; n++)
8951               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
8952                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
8953                                            ref->u.ar.start[n]))
8954                 ref->u.ar.start[n]
8955                         = gfc_get_parentheses (ref->u.ar.start[n]);
8956           }
8957     }
8958
8959   if (gfc_pure (NULL))
8960     {
8961       if (lhs->ts.type == BT_DERIVED
8962             && lhs->expr_type == EXPR_VARIABLE
8963             && lhs->ts.u.derived->attr.pointer_comp
8964             && rhs->expr_type == EXPR_VARIABLE
8965             && (gfc_impure_variable (rhs->symtree->n.sym)
8966                 || gfc_is_coindexed (rhs)))
8967         {
8968           /* F2008, C1283.  */
8969           if (gfc_is_coindexed (rhs))
8970             gfc_error ("Coindexed expression at %L is assigned to "
8971                         "a derived type variable with a POINTER "
8972                         "component in a PURE procedure",
8973                         &rhs->where);
8974           else
8975             gfc_error ("The impure variable at %L is assigned to "
8976                         "a derived type variable with a POINTER "
8977                         "component in a PURE procedure (12.6)",
8978                         &rhs->where);
8979           return rval;
8980         }
8981
8982       /* Fortran 2008, C1283.  */
8983       if (gfc_is_coindexed (lhs))
8984         {
8985           gfc_error ("Assignment to coindexed variable at %L in a PURE "
8986                      "procedure", &rhs->where);
8987           return rval;
8988         }
8989     }
8990
8991   if (gfc_implicit_pure (NULL))
8992     {
8993       if (lhs->expr_type == EXPR_VARIABLE
8994             && lhs->symtree->n.sym != gfc_current_ns->proc_name
8995             && lhs->symtree->n.sym->ns != gfc_current_ns)
8996         gfc_current_ns->proc_name->attr.implicit_pure = 0;
8997
8998       if (lhs->ts.type == BT_DERIVED
8999             && lhs->expr_type == EXPR_VARIABLE
9000             && lhs->ts.u.derived->attr.pointer_comp
9001             && rhs->expr_type == EXPR_VARIABLE
9002             && (gfc_impure_variable (rhs->symtree->n.sym)
9003                 || gfc_is_coindexed (rhs)))
9004         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9005
9006       /* Fortran 2008, C1283.  */
9007       if (gfc_is_coindexed (lhs))
9008         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9009     }
9010
9011   /* F03:7.4.1.2.  */
9012   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
9013      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
9014   if (lhs->ts.type == BT_CLASS)
9015     {
9016       gfc_error ("Variable must not be polymorphic in assignment at %L",
9017                  &lhs->where);
9018       return false;
9019     }
9020
9021   /* F2008, Section 7.2.1.2.  */
9022   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
9023     {
9024       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
9025                  "component in assignment at %L", &lhs->where);
9026       return false;
9027     }
9028
9029   gfc_check_assign (lhs, rhs, 1);
9030   return false;
9031 }
9032
9033
9034 /* Given a block of code, recursively resolve everything pointed to by this
9035    code block.  */
9036
9037 static void
9038 resolve_code (gfc_code *code, gfc_namespace *ns)
9039 {
9040   int omp_workshare_save;
9041   int forall_save;
9042   code_stack frame;
9043   gfc_try t;
9044
9045   frame.prev = cs_base;
9046   frame.head = code;
9047   cs_base = &frame;
9048
9049   find_reachable_labels (code);
9050
9051   for (; code; code = code->next)
9052     {
9053       frame.current = code;
9054       forall_save = forall_flag;
9055
9056       if (code->op == EXEC_FORALL)
9057         {
9058           forall_flag = 1;
9059           gfc_resolve_forall (code, ns, forall_save);
9060           forall_flag = 2;
9061         }
9062       else if (code->block)
9063         {
9064           omp_workshare_save = -1;
9065           switch (code->op)
9066             {
9067             case EXEC_OMP_PARALLEL_WORKSHARE:
9068               omp_workshare_save = omp_workshare_flag;
9069               omp_workshare_flag = 1;
9070               gfc_resolve_omp_parallel_blocks (code, ns);
9071               break;
9072             case EXEC_OMP_PARALLEL:
9073             case EXEC_OMP_PARALLEL_DO:
9074             case EXEC_OMP_PARALLEL_SECTIONS:
9075             case EXEC_OMP_TASK:
9076               omp_workshare_save = omp_workshare_flag;
9077               omp_workshare_flag = 0;
9078               gfc_resolve_omp_parallel_blocks (code, ns);
9079               break;
9080             case EXEC_OMP_DO:
9081               gfc_resolve_omp_do_blocks (code, ns);
9082               break;
9083             case EXEC_SELECT_TYPE:
9084               /* Blocks are handled in resolve_select_type because we have
9085                  to transform the SELECT TYPE into ASSOCIATE first.  */
9086               break;
9087             case EXEC_OMP_WORKSHARE:
9088               omp_workshare_save = omp_workshare_flag;
9089               omp_workshare_flag = 1;
9090               /* FALLTHROUGH */
9091             default:
9092               gfc_resolve_blocks (code->block, ns);
9093               break;
9094             }
9095
9096           if (omp_workshare_save != -1)
9097             omp_workshare_flag = omp_workshare_save;
9098         }
9099
9100       t = SUCCESS;
9101       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
9102         t = gfc_resolve_expr (code->expr1);
9103       forall_flag = forall_save;
9104
9105       if (gfc_resolve_expr (code->expr2) == FAILURE)
9106         t = FAILURE;
9107
9108       if (code->op == EXEC_ALLOCATE
9109           && gfc_resolve_expr (code->expr3) == FAILURE)
9110         t = FAILURE;
9111
9112       switch (code->op)
9113         {
9114         case EXEC_NOP:
9115         case EXEC_END_BLOCK:
9116         case EXEC_END_NESTED_BLOCK:
9117         case EXEC_CYCLE:
9118         case EXEC_PAUSE:
9119         case EXEC_STOP:
9120         case EXEC_ERROR_STOP:
9121         case EXEC_EXIT:
9122         case EXEC_CONTINUE:
9123         case EXEC_DT_END:
9124         case EXEC_ASSIGN_CALL:
9125         case EXEC_CRITICAL:
9126           break;
9127
9128         case EXEC_SYNC_ALL:
9129         case EXEC_SYNC_IMAGES:
9130         case EXEC_SYNC_MEMORY:
9131           resolve_sync (code);
9132           break;
9133
9134         case EXEC_LOCK:
9135         case EXEC_UNLOCK:
9136           resolve_lock_unlock (code);
9137           break;
9138
9139         case EXEC_ENTRY:
9140           /* Keep track of which entry we are up to.  */
9141           current_entry_id = code->ext.entry->id;
9142           break;
9143
9144         case EXEC_WHERE:
9145           resolve_where (code, NULL);
9146           break;
9147
9148         case EXEC_GOTO:
9149           if (code->expr1 != NULL)
9150             {
9151               if (code->expr1->ts.type != BT_INTEGER)
9152                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
9153                            "INTEGER variable", &code->expr1->where);
9154               else if (code->expr1->symtree->n.sym->attr.assign != 1)
9155                 gfc_error ("Variable '%s' has not been assigned a target "
9156                            "label at %L", code->expr1->symtree->n.sym->name,
9157                            &code->expr1->where);
9158             }
9159           else
9160             resolve_branch (code->label1, code);
9161           break;
9162
9163         case EXEC_RETURN:
9164           if (code->expr1 != NULL
9165                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
9166             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
9167                        "INTEGER return specifier", &code->expr1->where);
9168           break;
9169
9170         case EXEC_INIT_ASSIGN:
9171         case EXEC_END_PROCEDURE:
9172           break;
9173
9174         case EXEC_ASSIGN:
9175           if (t == FAILURE)
9176             break;
9177
9178           if (gfc_check_vardef_context (code->expr1, false, false,
9179                                         _("assignment")) == FAILURE)
9180             break;
9181
9182           if (resolve_ordinary_assign (code, ns))
9183             {
9184               if (code->op == EXEC_COMPCALL)
9185                 goto compcall;
9186               else
9187                 goto call;
9188             }
9189           break;
9190
9191         case EXEC_LABEL_ASSIGN:
9192           if (code->label1->defined == ST_LABEL_UNKNOWN)
9193             gfc_error ("Label %d referenced at %L is never defined",
9194                        code->label1->value, &code->label1->where);
9195           if (t == SUCCESS
9196               && (code->expr1->expr_type != EXPR_VARIABLE
9197                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
9198                   || code->expr1->symtree->n.sym->ts.kind
9199                      != gfc_default_integer_kind
9200                   || code->expr1->symtree->n.sym->as != NULL))
9201             gfc_error ("ASSIGN statement at %L requires a scalar "
9202                        "default INTEGER variable", &code->expr1->where);
9203           break;
9204
9205         case EXEC_POINTER_ASSIGN:
9206           {
9207             gfc_expr* e;
9208
9209             if (t == FAILURE)
9210               break;
9211
9212             /* This is both a variable definition and pointer assignment
9213                context, so check both of them.  For rank remapping, a final
9214                array ref may be present on the LHS and fool gfc_expr_attr
9215                used in gfc_check_vardef_context.  Remove it.  */
9216             e = remove_last_array_ref (code->expr1);
9217             t = gfc_check_vardef_context (e, true, false,
9218                                           _("pointer assignment"));
9219             if (t == SUCCESS)
9220               t = gfc_check_vardef_context (e, false, false,
9221                                             _("pointer assignment"));
9222             gfc_free_expr (e);
9223             if (t == FAILURE)
9224               break;
9225
9226             gfc_check_pointer_assign (code->expr1, code->expr2);
9227             break;
9228           }
9229
9230         case EXEC_ARITHMETIC_IF:
9231           if (t == SUCCESS
9232               && code->expr1->ts.type != BT_INTEGER
9233               && code->expr1->ts.type != BT_REAL)
9234             gfc_error ("Arithmetic IF statement at %L requires a numeric "
9235                        "expression", &code->expr1->where);
9236
9237           resolve_branch (code->label1, code);
9238           resolve_branch (code->label2, code);
9239           resolve_branch (code->label3, code);
9240           break;
9241
9242         case EXEC_IF:
9243           if (t == SUCCESS && code->expr1 != NULL
9244               && (code->expr1->ts.type != BT_LOGICAL
9245                   || code->expr1->rank != 0))
9246             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9247                        &code->expr1->where);
9248           break;
9249
9250         case EXEC_CALL:
9251         call:
9252           resolve_call (code);
9253           break;
9254
9255         case EXEC_COMPCALL:
9256         compcall:
9257           resolve_typebound_subroutine (code);
9258           break;
9259
9260         case EXEC_CALL_PPC:
9261           resolve_ppc_call (code);
9262           break;
9263
9264         case EXEC_SELECT:
9265           /* Select is complicated. Also, a SELECT construct could be
9266              a transformed computed GOTO.  */
9267           resolve_select (code);
9268           break;
9269
9270         case EXEC_SELECT_TYPE:
9271           resolve_select_type (code, ns);
9272           break;
9273
9274         case EXEC_BLOCK:
9275           resolve_block_construct (code);
9276           break;
9277
9278         case EXEC_DO:
9279           if (code->ext.iterator != NULL)
9280             {
9281               gfc_iterator *iter = code->ext.iterator;
9282               if (gfc_resolve_iterator (iter, true) != FAILURE)
9283                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9284             }
9285           break;
9286
9287         case EXEC_DO_WHILE:
9288           if (code->expr1 == NULL)
9289             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9290           if (t == SUCCESS
9291               && (code->expr1->rank != 0
9292                   || code->expr1->ts.type != BT_LOGICAL))
9293             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9294                        "a scalar LOGICAL expression", &code->expr1->where);
9295           break;
9296
9297         case EXEC_ALLOCATE:
9298           if (t == SUCCESS)
9299             resolve_allocate_deallocate (code, "ALLOCATE");
9300
9301           break;
9302
9303         case EXEC_DEALLOCATE:
9304           if (t == SUCCESS)
9305             resolve_allocate_deallocate (code, "DEALLOCATE");
9306
9307           break;
9308
9309         case EXEC_OPEN:
9310           if (gfc_resolve_open (code->ext.open) == FAILURE)
9311             break;
9312
9313           resolve_branch (code->ext.open->err, code);
9314           break;
9315
9316         case EXEC_CLOSE:
9317           if (gfc_resolve_close (code->ext.close) == FAILURE)
9318             break;
9319
9320           resolve_branch (code->ext.close->err, code);
9321           break;
9322
9323         case EXEC_BACKSPACE:
9324         case EXEC_ENDFILE:
9325         case EXEC_REWIND:
9326         case EXEC_FLUSH:
9327           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9328             break;
9329
9330           resolve_branch (code->ext.filepos->err, code);
9331           break;
9332
9333         case EXEC_INQUIRE:
9334           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9335               break;
9336
9337           resolve_branch (code->ext.inquire->err, code);
9338           break;
9339
9340         case EXEC_IOLENGTH:
9341           gcc_assert (code->ext.inquire != NULL);
9342           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9343             break;
9344
9345           resolve_branch (code->ext.inquire->err, code);
9346           break;
9347
9348         case EXEC_WAIT:
9349           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9350             break;
9351
9352           resolve_branch (code->ext.wait->err, code);
9353           resolve_branch (code->ext.wait->end, code);
9354           resolve_branch (code->ext.wait->eor, code);
9355           break;
9356
9357         case EXEC_READ:
9358         case EXEC_WRITE:
9359           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9360             break;
9361
9362           resolve_branch (code->ext.dt->err, code);
9363           resolve_branch (code->ext.dt->end, code);
9364           resolve_branch (code->ext.dt->eor, code);
9365           break;
9366
9367         case EXEC_TRANSFER:
9368           resolve_transfer (code);
9369           break;
9370
9371         case EXEC_FORALL:
9372           resolve_forall_iterators (code->ext.forall_iterator);
9373
9374           if (code->expr1 != NULL
9375               && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
9376             gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
9377                        "expression", &code->expr1->where);
9378           break;
9379
9380         case EXEC_OMP_ATOMIC:
9381         case EXEC_OMP_BARRIER:
9382         case EXEC_OMP_CRITICAL:
9383         case EXEC_OMP_FLUSH:
9384         case EXEC_OMP_DO:
9385         case EXEC_OMP_MASTER:
9386         case EXEC_OMP_ORDERED:
9387         case EXEC_OMP_SECTIONS:
9388         case EXEC_OMP_SINGLE:
9389         case EXEC_OMP_TASKWAIT:
9390         case EXEC_OMP_TASKYIELD:
9391         case EXEC_OMP_WORKSHARE:
9392           gfc_resolve_omp_directive (code, ns);
9393           break;
9394
9395         case EXEC_OMP_PARALLEL:
9396         case EXEC_OMP_PARALLEL_DO:
9397         case EXEC_OMP_PARALLEL_SECTIONS:
9398         case EXEC_OMP_PARALLEL_WORKSHARE:
9399         case EXEC_OMP_TASK:
9400           omp_workshare_save = omp_workshare_flag;
9401           omp_workshare_flag = 0;
9402           gfc_resolve_omp_directive (code, ns);
9403           omp_workshare_flag = omp_workshare_save;
9404           break;
9405
9406         default:
9407           gfc_internal_error ("resolve_code(): Bad statement code");
9408         }
9409     }
9410
9411   cs_base = frame.prev;
9412 }
9413
9414
9415 /* Resolve initial values and make sure they are compatible with
9416    the variable.  */
9417
9418 static void
9419 resolve_values (gfc_symbol *sym)
9420 {
9421   gfc_try t;
9422
9423   if (sym->value == NULL)
9424     return;
9425
9426   if (sym->value->expr_type == EXPR_STRUCTURE)
9427     t= resolve_structure_cons (sym->value, 1);
9428   else 
9429     t = gfc_resolve_expr (sym->value);
9430
9431   if (t == FAILURE)
9432     return;
9433
9434   gfc_check_assign_symbol (sym, sym->value);
9435 }
9436
9437
9438 /* Verify the binding labels for common blocks that are BIND(C).  The label
9439    for a BIND(C) common block must be identical in all scoping units in which
9440    the common block is declared.  Further, the binding label can not collide
9441    with any other global entity in the program.  */
9442
9443 static void
9444 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9445 {
9446   if (comm_block_tree->n.common->is_bind_c == 1)
9447     {
9448       gfc_gsymbol *binding_label_gsym;
9449       gfc_gsymbol *comm_name_gsym;
9450
9451       /* See if a global symbol exists by the common block's name.  It may
9452          be NULL if the common block is use-associated.  */
9453       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9454                                          comm_block_tree->n.common->name);
9455       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9456         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9457                    "with the global entity '%s' at %L",
9458                    comm_block_tree->n.common->binding_label,
9459                    comm_block_tree->n.common->name,
9460                    &(comm_block_tree->n.common->where),
9461                    comm_name_gsym->name, &(comm_name_gsym->where));
9462       else if (comm_name_gsym != NULL
9463                && strcmp (comm_name_gsym->name,
9464                           comm_block_tree->n.common->name) == 0)
9465         {
9466           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9467              as expected.  */
9468           if (comm_name_gsym->binding_label == NULL)
9469             /* No binding label for common block stored yet; save this one.  */
9470             comm_name_gsym->binding_label =
9471               comm_block_tree->n.common->binding_label;
9472           else
9473             if (strcmp (comm_name_gsym->binding_label,
9474                         comm_block_tree->n.common->binding_label) != 0)
9475               {
9476                 /* Common block names match but binding labels do not.  */
9477                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9478                            "does not match the binding label '%s' for common "
9479                            "block '%s' at %L",
9480                            comm_block_tree->n.common->binding_label,
9481                            comm_block_tree->n.common->name,
9482                            &(comm_block_tree->n.common->where),
9483                            comm_name_gsym->binding_label,
9484                            comm_name_gsym->name,
9485                            &(comm_name_gsym->where));
9486                 return;
9487               }
9488         }
9489
9490       /* There is no binding label (NAME="") so we have nothing further to
9491          check and nothing to add as a global symbol for the label.  */
9492       if (comm_block_tree->n.common->binding_label[0] == '\0' )
9493         return;
9494       
9495       binding_label_gsym =
9496         gfc_find_gsymbol (gfc_gsym_root,
9497                           comm_block_tree->n.common->binding_label);
9498       if (binding_label_gsym == NULL)
9499         {
9500           /* Need to make a global symbol for the binding label to prevent
9501              it from colliding with another.  */
9502           binding_label_gsym =
9503             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9504           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9505           binding_label_gsym->type = GSYM_COMMON;
9506         }
9507       else
9508         {
9509           /* If comm_name_gsym is NULL, the name common block is use
9510              associated and the name could be colliding.  */
9511           if (binding_label_gsym->type != GSYM_COMMON)
9512             gfc_error ("Binding label '%s' for common block '%s' at %L "
9513                        "collides with the global entity '%s' at %L",
9514                        comm_block_tree->n.common->binding_label,
9515                        comm_block_tree->n.common->name,
9516                        &(comm_block_tree->n.common->where),
9517                        binding_label_gsym->name,
9518                        &(binding_label_gsym->where));
9519           else if (comm_name_gsym != NULL
9520                    && (strcmp (binding_label_gsym->name,
9521                                comm_name_gsym->binding_label) != 0)
9522                    && (strcmp (binding_label_gsym->sym_name,
9523                                comm_name_gsym->name) != 0))
9524             gfc_error ("Binding label '%s' for common block '%s' at %L "
9525                        "collides with global entity '%s' at %L",
9526                        binding_label_gsym->name, binding_label_gsym->sym_name,
9527                        &(comm_block_tree->n.common->where),
9528                        comm_name_gsym->name, &(comm_name_gsym->where));
9529         }
9530     }
9531   
9532   return;
9533 }
9534
9535
9536 /* Verify any BIND(C) derived types in the namespace so we can report errors
9537    for them once, rather than for each variable declared of that type.  */
9538
9539 static void
9540 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9541 {
9542   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9543       && derived_sym->attr.is_bind_c == 1)
9544     verify_bind_c_derived_type (derived_sym);
9545   
9546   return;
9547 }
9548
9549
9550 /* Verify that any binding labels used in a given namespace do not collide 
9551    with the names or binding labels of any global symbols.  */
9552
9553 static void
9554 gfc_verify_binding_labels (gfc_symbol *sym)
9555 {
9556   int has_error = 0;
9557   
9558   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0 
9559       && sym->attr.flavor != FL_DERIVED && sym->binding_label[0] != '\0')
9560     {
9561       gfc_gsymbol *bind_c_sym;
9562
9563       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9564       if (bind_c_sym != NULL 
9565           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9566         {
9567           if (sym->attr.if_source == IFSRC_DECL 
9568               && (bind_c_sym->type != GSYM_SUBROUTINE 
9569                   && bind_c_sym->type != GSYM_FUNCTION) 
9570               && ((sym->attr.contained == 1 
9571                    && strcmp (bind_c_sym->sym_name, sym->name) != 0) 
9572                   || (sym->attr.use_assoc == 1 
9573                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9574             {
9575               /* Make sure global procedures don't collide with anything.  */
9576               gfc_error ("Binding label '%s' at %L collides with the global "
9577                          "entity '%s' at %L", sym->binding_label,
9578                          &(sym->declared_at), bind_c_sym->name,
9579                          &(bind_c_sym->where));
9580               has_error = 1;
9581             }
9582           else if (sym->attr.contained == 0 
9583                    && (sym->attr.if_source == IFSRC_IFBODY 
9584                        && sym->attr.flavor == FL_PROCEDURE) 
9585                    && (bind_c_sym->sym_name != NULL 
9586                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9587             {
9588               /* Make sure procedures in interface bodies don't collide.  */
9589               gfc_error ("Binding label '%s' in interface body at %L collides "
9590                          "with the global entity '%s' at %L",
9591                          sym->binding_label,
9592                          &(sym->declared_at), bind_c_sym->name,
9593                          &(bind_c_sym->where));
9594               has_error = 1;
9595             }
9596           else if (sym->attr.contained == 0 
9597                    && sym->attr.if_source == IFSRC_UNKNOWN)
9598             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9599                  && strcmp (bind_c_sym->mod_name, sym->module) != 0) 
9600                 || sym->attr.use_assoc == 0)
9601               {
9602                 gfc_error ("Binding label '%s' at %L collides with global "
9603                            "entity '%s' at %L", sym->binding_label,
9604                            &(sym->declared_at), bind_c_sym->name,
9605                            &(bind_c_sym->where));
9606                 has_error = 1;
9607               }
9608
9609           if (has_error != 0)
9610             /* Clear the binding label to prevent checking multiple times.  */
9611             sym->binding_label[0] = '\0';
9612         }
9613       else if (bind_c_sym == NULL)
9614         {
9615           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9616           bind_c_sym->where = sym->declared_at;
9617           bind_c_sym->sym_name = sym->name;
9618
9619           if (sym->attr.use_assoc == 1)
9620             bind_c_sym->mod_name = sym->module;
9621           else
9622             if (sym->ns->proc_name != NULL)
9623               bind_c_sym->mod_name = sym->ns->proc_name->name;
9624
9625           if (sym->attr.contained == 0)
9626             {
9627               if (sym->attr.subroutine)
9628                 bind_c_sym->type = GSYM_SUBROUTINE;
9629               else if (sym->attr.function)
9630                 bind_c_sym->type = GSYM_FUNCTION;
9631             }
9632         }
9633     }
9634   return;
9635 }
9636
9637
9638 /* Resolve an index expression.  */
9639
9640 static gfc_try
9641 resolve_index_expr (gfc_expr *e)
9642 {
9643   if (gfc_resolve_expr (e) == FAILURE)
9644     return FAILURE;
9645
9646   if (gfc_simplify_expr (e, 0) == FAILURE)
9647     return FAILURE;
9648
9649   if (gfc_specification_expr (e) == FAILURE)
9650     return FAILURE;
9651
9652   return SUCCESS;
9653 }
9654
9655
9656 /* Resolve a charlen structure.  */
9657
9658 static gfc_try
9659 resolve_charlen (gfc_charlen *cl)
9660 {
9661   int i, k;
9662
9663   if (cl->resolved)
9664     return SUCCESS;
9665
9666   cl->resolved = 1;
9667
9668   specification_expr = 1;
9669
9670   if (resolve_index_expr (cl->length) == FAILURE)
9671     {
9672       specification_expr = 0;
9673       return FAILURE;
9674     }
9675
9676   /* "If the character length parameter value evaluates to a negative
9677      value, the length of character entities declared is zero."  */
9678   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9679     {
9680       if (gfc_option.warn_surprising)
9681         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9682                          " the length has been set to zero",
9683                          &cl->length->where, i);
9684       gfc_replace_expr (cl->length,
9685                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9686     }
9687
9688   /* Check that the character length is not too large.  */
9689   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9690   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9691       && cl->length->ts.type == BT_INTEGER
9692       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9693     {
9694       gfc_error ("String length at %L is too large", &cl->length->where);
9695       return FAILURE;
9696     }
9697
9698   return SUCCESS;
9699 }
9700
9701
9702 /* Test for non-constant shape arrays.  */
9703
9704 static bool
9705 is_non_constant_shape_array (gfc_symbol *sym)
9706 {
9707   gfc_expr *e;
9708   int i;
9709   bool not_constant;
9710
9711   not_constant = false;
9712   if (sym->as != NULL)
9713     {
9714       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9715          has not been simplified; parameter array references.  Do the
9716          simplification now.  */
9717       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9718         {
9719           e = sym->as->lower[i];
9720           if (e && (resolve_index_expr (e) == FAILURE
9721                     || !gfc_is_constant_expr (e)))
9722             not_constant = true;
9723           e = sym->as->upper[i];
9724           if (e && (resolve_index_expr (e) == FAILURE
9725                     || !gfc_is_constant_expr (e)))
9726             not_constant = true;
9727         }
9728     }
9729   return not_constant;
9730 }
9731
9732 /* Given a symbol and an initialization expression, add code to initialize
9733    the symbol to the function entry.  */
9734 static void
9735 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9736 {
9737   gfc_expr *lval;
9738   gfc_code *init_st;
9739   gfc_namespace *ns = sym->ns;
9740
9741   /* Search for the function namespace if this is a contained
9742      function without an explicit result.  */
9743   if (sym->attr.function && sym == sym->result
9744       && sym->name != sym->ns->proc_name->name)
9745     {
9746       ns = ns->contained;
9747       for (;ns; ns = ns->sibling)
9748         if (strcmp (ns->proc_name->name, sym->name) == 0)
9749           break;
9750     }
9751
9752   if (ns == NULL)
9753     {
9754       gfc_free_expr (init);
9755       return;
9756     }
9757
9758   /* Build an l-value expression for the result.  */
9759   lval = gfc_lval_expr_from_sym (sym);
9760
9761   /* Add the code at scope entry.  */
9762   init_st = gfc_get_code ();
9763   init_st->next = ns->code;
9764   ns->code = init_st;
9765
9766   /* Assign the default initializer to the l-value.  */
9767   init_st->loc = sym->declared_at;
9768   init_st->op = EXEC_INIT_ASSIGN;
9769   init_st->expr1 = lval;
9770   init_st->expr2 = init;
9771 }
9772
9773 /* Assign the default initializer to a derived type variable or result.  */
9774
9775 static void
9776 apply_default_init (gfc_symbol *sym)
9777 {
9778   gfc_expr *init = NULL;
9779
9780   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9781     return;
9782
9783   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
9784     init = gfc_default_initializer (&sym->ts);
9785
9786   if (init == NULL && sym->ts.type != BT_CLASS)
9787     return;
9788
9789   build_init_assign (sym, init);
9790   sym->attr.referenced = 1;
9791 }
9792
9793 /* Build an initializer for a local integer, real, complex, logical, or
9794    character variable, based on the command line flags finit-local-zero,
9795    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns 
9796    null if the symbol should not have a default initialization.  */
9797 static gfc_expr *
9798 build_default_init_expr (gfc_symbol *sym)
9799 {
9800   int char_len;
9801   gfc_expr *init_expr;
9802   int i;
9803
9804   /* These symbols should never have a default initialization.  */
9805   if ((sym->attr.dimension && !gfc_is_compile_time_shape (sym->as))
9806       || sym->attr.external
9807       || sym->attr.dummy
9808       || sym->attr.pointer
9809       || sym->attr.in_equivalence
9810       || sym->attr.in_common
9811       || sym->attr.data
9812       || sym->module
9813       || sym->attr.cray_pointee
9814       || sym->attr.cray_pointer)
9815     return NULL;
9816
9817   /* Now we'll try to build an initializer expression.  */
9818   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
9819                                      &sym->declared_at);
9820
9821   /* We will only initialize integers, reals, complex, logicals, and
9822      characters, and only if the corresponding command-line flags
9823      were set.  Otherwise, we free init_expr and return null.  */
9824   switch (sym->ts.type)
9825     {    
9826     case BT_INTEGER:
9827       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
9828         mpz_set_si (init_expr->value.integer, 
9829                          gfc_option.flag_init_integer_value);
9830       else
9831         {
9832           gfc_free_expr (init_expr);
9833           init_expr = NULL;
9834         }
9835       break;
9836
9837     case BT_REAL:
9838       switch (gfc_option.flag_init_real)
9839         {
9840         case GFC_INIT_REAL_SNAN:
9841           init_expr->is_snan = 1;
9842           /* Fall through.  */
9843         case GFC_INIT_REAL_NAN:
9844           mpfr_set_nan (init_expr->value.real);
9845           break;
9846
9847         case GFC_INIT_REAL_INF:
9848           mpfr_set_inf (init_expr->value.real, 1);
9849           break;
9850
9851         case GFC_INIT_REAL_NEG_INF:
9852           mpfr_set_inf (init_expr->value.real, -1);
9853           break;
9854
9855         case GFC_INIT_REAL_ZERO:
9856           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
9857           break;
9858
9859         default:
9860           gfc_free_expr (init_expr);
9861           init_expr = NULL;
9862           break;
9863         }
9864       break;
9865           
9866     case BT_COMPLEX:
9867       switch (gfc_option.flag_init_real)
9868         {
9869         case GFC_INIT_REAL_SNAN:
9870           init_expr->is_snan = 1;
9871           /* Fall through.  */
9872         case GFC_INIT_REAL_NAN:
9873           mpfr_set_nan (mpc_realref (init_expr->value.complex));
9874           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
9875           break;
9876
9877         case GFC_INIT_REAL_INF:
9878           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
9879           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
9880           break;
9881
9882         case GFC_INIT_REAL_NEG_INF:
9883           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
9884           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
9885           break;
9886
9887         case GFC_INIT_REAL_ZERO:
9888           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
9889           break;
9890
9891         default:
9892           gfc_free_expr (init_expr);
9893           init_expr = NULL;
9894           break;
9895         }
9896       break;
9897           
9898     case BT_LOGICAL:
9899       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
9900         init_expr->value.logical = 0;
9901       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
9902         init_expr->value.logical = 1;
9903       else
9904         {
9905           gfc_free_expr (init_expr);
9906           init_expr = NULL;
9907         }
9908       break;
9909           
9910     case BT_CHARACTER:
9911       /* For characters, the length must be constant in order to 
9912          create a default initializer.  */
9913       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
9914           && sym->ts.u.cl->length
9915           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9916         {
9917           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
9918           init_expr->value.character.length = char_len;
9919           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
9920           for (i = 0; i < char_len; i++)
9921             init_expr->value.character.string[i]
9922               = (unsigned char) gfc_option.flag_init_character_value;
9923         }
9924       else
9925         {
9926           gfc_free_expr (init_expr);
9927           init_expr = NULL;
9928         }
9929       break;
9930           
9931     default:
9932      gfc_free_expr (init_expr);
9933      init_expr = NULL;
9934     }
9935   return init_expr;
9936 }
9937
9938 /* Add an initialization expression to a local variable.  */
9939 static void
9940 apply_default_init_local (gfc_symbol *sym)
9941 {
9942   gfc_expr *init = NULL;
9943
9944   /* The symbol should be a variable or a function return value.  */
9945   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
9946       || (sym->attr.function && sym->result != sym))
9947     return;
9948
9949   /* Try to build the initializer expression.  If we can't initialize
9950      this symbol, then init will be NULL.  */
9951   init = build_default_init_expr (sym);
9952   if (init == NULL)
9953     return;
9954
9955   /* For saved variables, we don't want to add an initializer at 
9956      function entry, so we just add a static initializer.  */
9957   if (sym->attr.save || sym->ns->save_all 
9958       || gfc_option.flag_max_stack_var_size == 0)
9959     {
9960       /* Don't clobber an existing initializer!  */
9961       gcc_assert (sym->value == NULL);
9962       sym->value = init;
9963       return;
9964     }
9965
9966   build_init_assign (sym, init);
9967 }
9968
9969
9970 /* Resolution of common features of flavors variable and procedure.  */
9971
9972 static gfc_try
9973 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
9974 {
9975   /* Avoid double diagnostics for function result symbols.  */
9976   if ((sym->result || sym->attr.result) && !sym->attr.dummy
9977       && (sym->ns != gfc_current_ns))
9978     return SUCCESS;
9979
9980   /* Constraints on deferred shape variable.  */
9981   if (sym->as == NULL || sym->as->type != AS_DEFERRED)
9982     {
9983       if (sym->attr.allocatable)
9984         {
9985           if (sym->attr.dimension)
9986             {
9987               gfc_error ("Allocatable array '%s' at %L must have "
9988                          "a deferred shape", sym->name, &sym->declared_at);
9989               return FAILURE;
9990             }
9991           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
9992                                    "may not be ALLOCATABLE", sym->name,
9993                                    &sym->declared_at) == FAILURE)
9994             return FAILURE;
9995         }
9996
9997       if (sym->attr.pointer && sym->attr.dimension)
9998         {
9999           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
10000                      sym->name, &sym->declared_at);
10001           return FAILURE;
10002         }
10003     }
10004   else
10005     {
10006       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
10007           && sym->ts.type != BT_CLASS && !sym->assoc)
10008         {
10009           gfc_error ("Array '%s' at %L cannot have a deferred shape",
10010                      sym->name, &sym->declared_at);
10011           return FAILURE;
10012          }
10013     }
10014
10015   /* Constraints on polymorphic variables.  */
10016   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
10017     {
10018       /* F03:C502.  */
10019       if (sym->attr.class_ok
10020           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
10021         {
10022           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
10023                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
10024                      &sym->declared_at);
10025           return FAILURE;
10026         }
10027
10028       /* F03:C509.  */
10029       /* Assume that use associated symbols were checked in the module ns.
10030          Class-variables that are associate-names are also something special
10031          and excepted from the test.  */
10032       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
10033         {
10034           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
10035                      "or pointer", sym->name, &sym->declared_at);
10036           return FAILURE;
10037         }
10038     }
10039     
10040   return SUCCESS;
10041 }
10042
10043
10044 /* Additional checks for symbols with flavor variable and derived
10045    type.  To be called from resolve_fl_variable.  */
10046
10047 static gfc_try
10048 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
10049 {
10050   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
10051
10052   /* Check to see if a derived type is blocked from being host
10053      associated by the presence of another class I symbol in the same
10054      namespace.  14.6.1.3 of the standard and the discussion on
10055      comp.lang.fortran.  */
10056   if (sym->ns != sym->ts.u.derived->ns
10057       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
10058     {
10059       gfc_symbol *s;
10060       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
10061       if (s && s->attr.flavor != FL_DERIVED)
10062         {
10063           gfc_error ("The type '%s' cannot be host associated at %L "
10064                      "because it is blocked by an incompatible object "
10065                      "of the same name declared at %L",
10066                      sym->ts.u.derived->name, &sym->declared_at,
10067                      &s->declared_at);
10068           return FAILURE;
10069         }
10070     }
10071
10072   /* 4th constraint in section 11.3: "If an object of a type for which
10073      component-initialization is specified (R429) appears in the
10074      specification-part of a module and does not have the ALLOCATABLE
10075      or POINTER attribute, the object shall have the SAVE attribute."
10076
10077      The check for initializers is performed with
10078      gfc_has_default_initializer because gfc_default_initializer generates
10079      a hidden default for allocatable components.  */
10080   if (!(sym->value || no_init_flag) && sym->ns->proc_name
10081       && sym->ns->proc_name->attr.flavor == FL_MODULE
10082       && !sym->ns->save_all && !sym->attr.save
10083       && !sym->attr.pointer && !sym->attr.allocatable
10084       && gfc_has_default_initializer (sym->ts.u.derived)
10085       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
10086                          "module variable '%s' at %L, needed due to "
10087                          "the default initialization", sym->name,
10088                          &sym->declared_at) == FAILURE)
10089     return FAILURE;
10090
10091   /* Assign default initializer.  */
10092   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
10093       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
10094     {
10095       sym->value = gfc_default_initializer (&sym->ts);
10096     }
10097
10098   return SUCCESS;
10099 }
10100
10101
10102 /* Resolve symbols with flavor variable.  */
10103
10104 static gfc_try
10105 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
10106 {
10107   int no_init_flag, automatic_flag;
10108   gfc_expr *e;
10109   const char *auto_save_msg;
10110
10111   auto_save_msg = "Automatic object '%s' at %L cannot have the "
10112                   "SAVE attribute";
10113
10114   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10115     return FAILURE;
10116
10117   /* Set this flag to check that variables are parameters of all entries.
10118      This check is effected by the call to gfc_resolve_expr through
10119      is_non_constant_shape_array.  */
10120   specification_expr = 1;
10121
10122   if (sym->ns->proc_name
10123       && (sym->ns->proc_name->attr.flavor == FL_MODULE
10124           || sym->ns->proc_name->attr.is_main_program)
10125       && !sym->attr.use_assoc
10126       && !sym->attr.allocatable
10127       && !sym->attr.pointer
10128       && is_non_constant_shape_array (sym))
10129     {
10130       /* The shape of a main program or module array needs to be
10131          constant.  */
10132       gfc_error ("The module or main program array '%s' at %L must "
10133                  "have constant shape", sym->name, &sym->declared_at);
10134       specification_expr = 0;
10135       return FAILURE;
10136     }
10137
10138   /* Constraints on deferred type parameter.  */
10139   if (sym->ts.deferred && !(sym->attr.pointer || sym->attr.allocatable))
10140     {
10141       gfc_error ("Entity '%s' at %L has a deferred type parameter and "
10142                  "requires either the pointer or allocatable attribute",
10143                      sym->name, &sym->declared_at);
10144       return FAILURE;
10145     }
10146
10147   if (sym->ts.type == BT_CHARACTER)
10148     {
10149       /* Make sure that character string variables with assumed length are
10150          dummy arguments.  */
10151       e = sym->ts.u.cl->length;
10152       if (e == NULL && !sym->attr.dummy && !sym->attr.result
10153           && !sym->ts.deferred)
10154         {
10155           gfc_error ("Entity with assumed character length at %L must be a "
10156                      "dummy argument or a PARAMETER", &sym->declared_at);
10157           return FAILURE;
10158         }
10159
10160       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
10161         {
10162           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10163           return FAILURE;
10164         }
10165
10166       if (!gfc_is_constant_expr (e)
10167           && !(e->expr_type == EXPR_VARIABLE
10168                && e->symtree->n.sym->attr.flavor == FL_PARAMETER))
10169         {
10170           if (!sym->attr.use_assoc && sym->ns->proc_name
10171               && (sym->ns->proc_name->attr.flavor == FL_MODULE
10172                   || sym->ns->proc_name->attr.is_main_program))
10173             {
10174               gfc_error ("'%s' at %L must have constant character length "
10175                         "in this context", sym->name, &sym->declared_at);
10176               return FAILURE;
10177             }
10178           if (sym->attr.in_common)
10179             {
10180               gfc_error ("COMMON variable '%s' at %L must have constant "
10181                          "character length", sym->name, &sym->declared_at);
10182               return FAILURE;
10183             }
10184         }
10185     }
10186
10187   if (sym->value == NULL && sym->attr.referenced)
10188     apply_default_init_local (sym); /* Try to apply a default initialization.  */
10189
10190   /* Determine if the symbol may not have an initializer.  */
10191   no_init_flag = automatic_flag = 0;
10192   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
10193       || sym->attr.intrinsic || sym->attr.result)
10194     no_init_flag = 1;
10195   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
10196            && is_non_constant_shape_array (sym))
10197     {
10198       no_init_flag = automatic_flag = 1;
10199
10200       /* Also, they must not have the SAVE attribute.
10201          SAVE_IMPLICIT is checked below.  */
10202       if (sym->as && sym->attr.codimension)
10203         {
10204           int corank = sym->as->corank;
10205           sym->as->corank = 0;
10206           no_init_flag = automatic_flag = is_non_constant_shape_array (sym);
10207           sym->as->corank = corank;
10208         }
10209       if (automatic_flag && sym->attr.save == SAVE_EXPLICIT)
10210         {
10211           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10212           return FAILURE;
10213         }
10214     }
10215
10216   /* Ensure that any initializer is simplified.  */
10217   if (sym->value)
10218     gfc_simplify_expr (sym->value, 1);
10219
10220   /* Reject illegal initializers.  */
10221   if (!sym->mark && sym->value)
10222     {
10223       if (sym->attr.allocatable || (sym->ts.type == BT_CLASS
10224                                     && CLASS_DATA (sym)->attr.allocatable))
10225         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
10226                    sym->name, &sym->declared_at);
10227       else if (sym->attr.external)
10228         gfc_error ("External '%s' at %L cannot have an initializer",
10229                    sym->name, &sym->declared_at);
10230       else if (sym->attr.dummy
10231         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
10232         gfc_error ("Dummy '%s' at %L cannot have an initializer",
10233                    sym->name, &sym->declared_at);
10234       else if (sym->attr.intrinsic)
10235         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
10236                    sym->name, &sym->declared_at);
10237       else if (sym->attr.result)
10238         gfc_error ("Function result '%s' at %L cannot have an initializer",
10239                    sym->name, &sym->declared_at);
10240       else if (automatic_flag)
10241         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
10242                    sym->name, &sym->declared_at);
10243       else
10244         goto no_init_error;
10245       return FAILURE;
10246     }
10247
10248 no_init_error:
10249   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
10250     return resolve_fl_variable_derived (sym, no_init_flag);
10251
10252   return SUCCESS;
10253 }
10254
10255
10256 /* Resolve a procedure.  */
10257
10258 static gfc_try
10259 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
10260 {
10261   gfc_formal_arglist *arg;
10262
10263   if (sym->attr.function
10264       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10265     return FAILURE;
10266
10267   if (sym->ts.type == BT_CHARACTER)
10268     {
10269       gfc_charlen *cl = sym->ts.u.cl;
10270
10271       if (cl && cl->length && gfc_is_constant_expr (cl->length)
10272              && resolve_charlen (cl) == FAILURE)
10273         return FAILURE;
10274
10275       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10276           && sym->attr.proc == PROC_ST_FUNCTION)
10277         {
10278           gfc_error ("Character-valued statement function '%s' at %L must "
10279                      "have constant length", sym->name, &sym->declared_at);
10280           return FAILURE;
10281         }
10282     }
10283
10284   /* Ensure that derived type for are not of a private type.  Internal
10285      module procedures are excluded by 2.2.3.3 - i.e., they are not
10286      externally accessible and can access all the objects accessible in
10287      the host.  */
10288   if (!(sym->ns->parent
10289         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
10290       && gfc_check_symbol_access (sym))
10291     {
10292       gfc_interface *iface;
10293
10294       for (arg = sym->formal; arg; arg = arg->next)
10295         {
10296           if (arg->sym
10297               && arg->sym->ts.type == BT_DERIVED
10298               && !arg->sym->ts.u.derived->attr.use_assoc
10299               && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10300               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
10301                                  "PRIVATE type and cannot be a dummy argument"
10302                                  " of '%s', which is PUBLIC at %L",
10303                                  arg->sym->name, sym->name, &sym->declared_at)
10304                  == FAILURE)
10305             {
10306               /* Stop this message from recurring.  */
10307               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10308               return FAILURE;
10309             }
10310         }
10311
10312       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10313          PRIVATE to the containing module.  */
10314       for (iface = sym->generic; iface; iface = iface->next)
10315         {
10316           for (arg = iface->sym->formal; arg; arg = arg->next)
10317             {
10318               if (arg->sym
10319                   && arg->sym->ts.type == BT_DERIVED
10320                   && !arg->sym->ts.u.derived->attr.use_assoc
10321                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10322                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10323                                      "'%s' in PUBLIC interface '%s' at %L "
10324                                      "takes dummy arguments of '%s' which is "
10325                                      "PRIVATE", iface->sym->name, sym->name,
10326                                      &iface->sym->declared_at,
10327                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10328                 {
10329                   /* Stop this message from recurring.  */
10330                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10331                   return FAILURE;
10332                 }
10333              }
10334         }
10335
10336       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10337          PRIVATE to the containing module.  */
10338       for (iface = sym->generic; iface; iface = iface->next)
10339         {
10340           for (arg = iface->sym->formal; arg; arg = arg->next)
10341             {
10342               if (arg->sym
10343                   && arg->sym->ts.type == BT_DERIVED
10344                   && !arg->sym->ts.u.derived->attr.use_assoc
10345                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10346                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10347                                      "'%s' in PUBLIC interface '%s' at %L "
10348                                      "takes dummy arguments of '%s' which is "
10349                                      "PRIVATE", iface->sym->name, sym->name,
10350                                      &iface->sym->declared_at,
10351                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10352                 {
10353                   /* Stop this message from recurring.  */
10354                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10355                   return FAILURE;
10356                 }
10357              }
10358         }
10359     }
10360
10361   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10362       && !sym->attr.proc_pointer)
10363     {
10364       gfc_error ("Function '%s' at %L cannot have an initializer",
10365                  sym->name, &sym->declared_at);
10366       return FAILURE;
10367     }
10368
10369   /* An external symbol may not have an initializer because it is taken to be
10370      a procedure. Exception: Procedure Pointers.  */
10371   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10372     {
10373       gfc_error ("External object '%s' at %L may not have an initializer",
10374                  sym->name, &sym->declared_at);
10375       return FAILURE;
10376     }
10377
10378   /* An elemental function is required to return a scalar 12.7.1  */
10379   if (sym->attr.elemental && sym->attr.function && sym->as)
10380     {
10381       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10382                  "result", sym->name, &sym->declared_at);
10383       /* Reset so that the error only occurs once.  */
10384       sym->attr.elemental = 0;
10385       return FAILURE;
10386     }
10387
10388   if (sym->attr.proc == PROC_ST_FUNCTION
10389       && (sym->attr.allocatable || sym->attr.pointer))
10390     {
10391       gfc_error ("Statement function '%s' at %L may not have pointer or "
10392                  "allocatable attribute", sym->name, &sym->declared_at);
10393       return FAILURE;
10394     }
10395
10396   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10397      char-len-param shall not be array-valued, pointer-valued, recursive
10398      or pure.  ....snip... A character value of * may only be used in the
10399      following ways: (i) Dummy arg of procedure - dummy associates with
10400      actual length; (ii) To declare a named constant; or (iii) External
10401      function - but length must be declared in calling scoping unit.  */
10402   if (sym->attr.function
10403       && sym->ts.type == BT_CHARACTER
10404       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10405     {
10406       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10407           || (sym->attr.recursive) || (sym->attr.pure))
10408         {
10409           if (sym->as && sym->as->rank)
10410             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10411                        "array-valued", sym->name, &sym->declared_at);
10412
10413           if (sym->attr.pointer)
10414             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10415                        "pointer-valued", sym->name, &sym->declared_at);
10416
10417           if (sym->attr.pure)
10418             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10419                        "pure", sym->name, &sym->declared_at);
10420
10421           if (sym->attr.recursive)
10422             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10423                        "recursive", sym->name, &sym->declared_at);
10424
10425           return FAILURE;
10426         }
10427
10428       /* Appendix B.2 of the standard.  Contained functions give an
10429          error anyway.  Fixed-form is likely to be F77/legacy. Deferred
10430          character length is an F2003 feature.  */
10431       if (!sym->attr.contained
10432             && gfc_current_form != FORM_FIXED
10433             && !sym->ts.deferred)
10434         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10435                         "CHARACTER(*) function '%s' at %L",
10436                         sym->name, &sym->declared_at);
10437     }
10438
10439   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10440     {
10441       gfc_formal_arglist *curr_arg;
10442       int has_non_interop_arg = 0;
10443
10444       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10445                              sym->common_block) == FAILURE)
10446         {
10447           /* Clear these to prevent looking at them again if there was an
10448              error.  */
10449           sym->attr.is_bind_c = 0;
10450           sym->attr.is_c_interop = 0;
10451           sym->ts.is_c_interop = 0;
10452         }
10453       else
10454         {
10455           /* So far, no errors have been found.  */
10456           sym->attr.is_c_interop = 1;
10457           sym->ts.is_c_interop = 1;
10458         }
10459       
10460       curr_arg = sym->formal;
10461       while (curr_arg != NULL)
10462         {
10463           /* Skip implicitly typed dummy args here.  */
10464           if (curr_arg->sym->attr.implicit_type == 0)
10465             if (verify_c_interop_param (curr_arg->sym) == FAILURE)
10466               /* If something is found to fail, record the fact so we
10467                  can mark the symbol for the procedure as not being
10468                  BIND(C) to try and prevent multiple errors being
10469                  reported.  */
10470               has_non_interop_arg = 1;
10471           
10472           curr_arg = curr_arg->next;
10473         }
10474
10475       /* See if any of the arguments were not interoperable and if so, clear
10476          the procedure symbol to prevent duplicate error messages.  */
10477       if (has_non_interop_arg != 0)
10478         {
10479           sym->attr.is_c_interop = 0;
10480           sym->ts.is_c_interop = 0;
10481           sym->attr.is_bind_c = 0;
10482         }
10483     }
10484   
10485   if (!sym->attr.proc_pointer)
10486     {
10487       if (sym->attr.save == SAVE_EXPLICIT)
10488         {
10489           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10490                      "in '%s' at %L", sym->name, &sym->declared_at);
10491           return FAILURE;
10492         }
10493       if (sym->attr.intent)
10494         {
10495           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10496                      "in '%s' at %L", sym->name, &sym->declared_at);
10497           return FAILURE;
10498         }
10499       if (sym->attr.subroutine && sym->attr.result)
10500         {
10501           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10502                      "in '%s' at %L", sym->name, &sym->declared_at);
10503           return FAILURE;
10504         }
10505       if (sym->attr.external && sym->attr.function
10506           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10507               || sym->attr.contained))
10508         {
10509           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10510                      "in '%s' at %L", sym->name, &sym->declared_at);
10511           return FAILURE;
10512         }
10513       if (strcmp ("ppr@", sym->name) == 0)
10514         {
10515           gfc_error ("Procedure pointer result '%s' at %L "
10516                      "is missing the pointer attribute",
10517                      sym->ns->proc_name->name, &sym->declared_at);
10518           return FAILURE;
10519         }
10520     }
10521
10522   return SUCCESS;
10523 }
10524
10525
10526 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10527    been defined and we now know their defined arguments, check that they fulfill
10528    the requirements of the standard for procedures used as finalizers.  */
10529
10530 static gfc_try
10531 gfc_resolve_finalizers (gfc_symbol* derived)
10532 {
10533   gfc_finalizer* list;
10534   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10535   gfc_try result = SUCCESS;
10536   bool seen_scalar = false;
10537
10538   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10539     return SUCCESS;
10540
10541   /* Walk over the list of finalizer-procedures, check them, and if any one
10542      does not fit in with the standard's definition, print an error and remove
10543      it from the list.  */
10544   prev_link = &derived->f2k_derived->finalizers;
10545   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10546     {
10547       gfc_symbol* arg;
10548       gfc_finalizer* i;
10549       int my_rank;
10550
10551       /* Skip this finalizer if we already resolved it.  */
10552       if (list->proc_tree)
10553         {
10554           prev_link = &(list->next);
10555           continue;
10556         }
10557
10558       /* Check this exists and is a SUBROUTINE.  */
10559       if (!list->proc_sym->attr.subroutine)
10560         {
10561           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10562                      list->proc_sym->name, &list->where);
10563           goto error;
10564         }
10565
10566       /* We should have exactly one argument.  */
10567       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10568         {
10569           gfc_error ("FINAL procedure at %L must have exactly one argument",
10570                      &list->where);
10571           goto error;
10572         }
10573       arg = list->proc_sym->formal->sym;
10574
10575       /* This argument must be of our type.  */
10576       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10577         {
10578           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10579                      &arg->declared_at, derived->name);
10580           goto error;
10581         }
10582
10583       /* It must neither be a pointer nor allocatable nor optional.  */
10584       if (arg->attr.pointer)
10585         {
10586           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10587                      &arg->declared_at);
10588           goto error;
10589         }
10590       if (arg->attr.allocatable)
10591         {
10592           gfc_error ("Argument of FINAL procedure at %L must not be"
10593                      " ALLOCATABLE", &arg->declared_at);
10594           goto error;
10595         }
10596       if (arg->attr.optional)
10597         {
10598           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10599                      &arg->declared_at);
10600           goto error;
10601         }
10602
10603       /* It must not be INTENT(OUT).  */
10604       if (arg->attr.intent == INTENT_OUT)
10605         {
10606           gfc_error ("Argument of FINAL procedure at %L must not be"
10607                      " INTENT(OUT)", &arg->declared_at);
10608           goto error;
10609         }
10610
10611       /* Warn if the procedure is non-scalar and not assumed shape.  */
10612       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10613           && arg->as->type != AS_ASSUMED_SHAPE)
10614         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10615                      " shape argument", &arg->declared_at);
10616
10617       /* Check that it does not match in kind and rank with a FINAL procedure
10618          defined earlier.  To really loop over the *earlier* declarations,
10619          we need to walk the tail of the list as new ones were pushed at the
10620          front.  */
10621       /* TODO: Handle kind parameters once they are implemented.  */
10622       my_rank = (arg->as ? arg->as->rank : 0);
10623       for (i = list->next; i; i = i->next)
10624         {
10625           /* Argument list might be empty; that is an error signalled earlier,
10626              but we nevertheless continued resolving.  */
10627           if (i->proc_sym->formal)
10628             {
10629               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10630               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10631               if (i_rank == my_rank)
10632                 {
10633                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10634                              " rank (%d) as '%s'",
10635                              list->proc_sym->name, &list->where, my_rank, 
10636                              i->proc_sym->name);
10637                   goto error;
10638                 }
10639             }
10640         }
10641
10642         /* Is this the/a scalar finalizer procedure?  */
10643         if (!arg->as || arg->as->rank == 0)
10644           seen_scalar = true;
10645
10646         /* Find the symtree for this procedure.  */
10647         gcc_assert (!list->proc_tree);
10648         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10649
10650         prev_link = &list->next;
10651         continue;
10652
10653         /* Remove wrong nodes immediately from the list so we don't risk any
10654            troubles in the future when they might fail later expectations.  */
10655 error:
10656         result = FAILURE;
10657         i = list;
10658         *prev_link = list->next;
10659         gfc_free_finalizer (i);
10660     }
10661
10662   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10663      were nodes in the list, must have been for arrays.  It is surely a good
10664      idea to have a scalar version there if there's something to finalize.  */
10665   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10666     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10667                  " defined at %L, suggest also scalar one",
10668                  derived->name, &derived->declared_at);
10669
10670   /* TODO:  Remove this error when finalization is finished.  */
10671   gfc_error ("Finalization at %L is not yet implemented",
10672              &derived->declared_at);
10673
10674   return result;
10675 }
10676
10677
10678 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10679
10680 static gfc_try
10681 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10682                              const char* generic_name, locus where)
10683 {
10684   gfc_symbol* sym1;
10685   gfc_symbol* sym2;
10686
10687   gcc_assert (t1->specific && t2->specific);
10688   gcc_assert (!t1->specific->is_generic);
10689   gcc_assert (!t2->specific->is_generic);
10690
10691   sym1 = t1->specific->u.specific->n.sym;
10692   sym2 = t2->specific->u.specific->n.sym;
10693
10694   if (sym1 == sym2)
10695     return SUCCESS;
10696
10697   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10698   if (sym1->attr.subroutine != sym2->attr.subroutine
10699       || sym1->attr.function != sym2->attr.function)
10700     {
10701       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10702                  " GENERIC '%s' at %L",
10703                  sym1->name, sym2->name, generic_name, &where);
10704       return FAILURE;
10705     }
10706
10707   /* Compare the interfaces.  */
10708   if (gfc_compare_interfaces (sym1, sym2, sym2->name, 1, 0, NULL, 0))
10709     {
10710       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10711                  sym1->name, sym2->name, generic_name, &where);
10712       return FAILURE;
10713     }
10714
10715   return SUCCESS;
10716 }
10717
10718
10719 /* Worker function for resolving a generic procedure binding; this is used to
10720    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
10721
10722    The difference between those cases is finding possible inherited bindings
10723    that are overridden, as one has to look for them in tb_sym_root,
10724    tb_uop_root or tb_op, respectively.  Thus the caller must already find
10725    the super-type and set p->overridden correctly.  */
10726
10727 static gfc_try
10728 resolve_tb_generic_targets (gfc_symbol* super_type,
10729                             gfc_typebound_proc* p, const char* name)
10730 {
10731   gfc_tbp_generic* target;
10732   gfc_symtree* first_target;
10733   gfc_symtree* inherited;
10734
10735   gcc_assert (p && p->is_generic);
10736
10737   /* Try to find the specific bindings for the symtrees in our target-list.  */
10738   gcc_assert (p->u.generic);
10739   for (target = p->u.generic; target; target = target->next)
10740     if (!target->specific)
10741       {
10742         gfc_typebound_proc* overridden_tbp;
10743         gfc_tbp_generic* g;
10744         const char* target_name;
10745
10746         target_name = target->specific_st->name;
10747
10748         /* Defined for this type directly.  */
10749         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
10750           {
10751             target->specific = target->specific_st->n.tb;
10752             goto specific_found;
10753           }
10754
10755         /* Look for an inherited specific binding.  */
10756         if (super_type)
10757           {
10758             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
10759                                                  true, NULL);
10760
10761             if (inherited)
10762               {
10763                 gcc_assert (inherited->n.tb);
10764                 target->specific = inherited->n.tb;
10765                 goto specific_found;
10766               }
10767           }
10768
10769         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
10770                    " at %L", target_name, name, &p->where);
10771         return FAILURE;
10772
10773         /* Once we've found the specific binding, check it is not ambiguous with
10774            other specifics already found or inherited for the same GENERIC.  */
10775 specific_found:
10776         gcc_assert (target->specific);
10777
10778         /* This must really be a specific binding!  */
10779         if (target->specific->is_generic)
10780           {
10781             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
10782                        " '%s' is GENERIC, too", name, &p->where, target_name);
10783             return FAILURE;
10784           }
10785
10786         /* Check those already resolved on this type directly.  */
10787         for (g = p->u.generic; g; g = g->next)
10788           if (g != target && g->specific
10789               && check_generic_tbp_ambiguity (target, g, name, p->where)
10790                   == FAILURE)
10791             return FAILURE;
10792
10793         /* Check for ambiguity with inherited specific targets.  */
10794         for (overridden_tbp = p->overridden; overridden_tbp;
10795              overridden_tbp = overridden_tbp->overridden)
10796           if (overridden_tbp->is_generic)
10797             {
10798               for (g = overridden_tbp->u.generic; g; g = g->next)
10799                 {
10800                   gcc_assert (g->specific);
10801                   if (check_generic_tbp_ambiguity (target, g,
10802                                                    name, p->where) == FAILURE)
10803                     return FAILURE;
10804                 }
10805             }
10806       }
10807
10808   /* If we attempt to "overwrite" a specific binding, this is an error.  */
10809   if (p->overridden && !p->overridden->is_generic)
10810     {
10811       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
10812                  " the same name", name, &p->where);
10813       return FAILURE;
10814     }
10815
10816   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
10817      all must have the same attributes here.  */
10818   first_target = p->u.generic->specific->u.specific;
10819   gcc_assert (first_target);
10820   p->subroutine = first_target->n.sym->attr.subroutine;
10821   p->function = first_target->n.sym->attr.function;
10822
10823   return SUCCESS;
10824 }
10825
10826
10827 /* Resolve a GENERIC procedure binding for a derived type.  */
10828
10829 static gfc_try
10830 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
10831 {
10832   gfc_symbol* super_type;
10833
10834   /* Find the overridden binding if any.  */
10835   st->n.tb->overridden = NULL;
10836   super_type = gfc_get_derived_super_type (derived);
10837   if (super_type)
10838     {
10839       gfc_symtree* overridden;
10840       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
10841                                             true, NULL);
10842
10843       if (overridden && overridden->n.tb)
10844         st->n.tb->overridden = overridden->n.tb;
10845     }
10846
10847   /* Resolve using worker function.  */
10848   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
10849 }
10850
10851
10852 /* Retrieve the target-procedure of an operator binding and do some checks in
10853    common for intrinsic and user-defined type-bound operators.  */
10854
10855 static gfc_symbol*
10856 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
10857 {
10858   gfc_symbol* target_proc;
10859
10860   gcc_assert (target->specific && !target->specific->is_generic);
10861   target_proc = target->specific->u.specific->n.sym;
10862   gcc_assert (target_proc);
10863
10864   /* All operator bindings must have a passed-object dummy argument.  */
10865   if (target->specific->nopass)
10866     {
10867       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
10868       return NULL;
10869     }
10870
10871   return target_proc;
10872 }
10873
10874
10875 /* Resolve a type-bound intrinsic operator.  */
10876
10877 static gfc_try
10878 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
10879                                 gfc_typebound_proc* p)
10880 {
10881   gfc_symbol* super_type;
10882   gfc_tbp_generic* target;
10883   
10884   /* If there's already an error here, do nothing (but don't fail again).  */
10885   if (p->error)
10886     return SUCCESS;
10887
10888   /* Operators should always be GENERIC bindings.  */
10889   gcc_assert (p->is_generic);
10890
10891   /* Look for an overridden binding.  */
10892   super_type = gfc_get_derived_super_type (derived);
10893   if (super_type && super_type->f2k_derived)
10894     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
10895                                                      op, true, NULL);
10896   else
10897     p->overridden = NULL;
10898
10899   /* Resolve general GENERIC properties using worker function.  */
10900   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
10901     goto error;
10902
10903   /* Check the targets to be procedures of correct interface.  */
10904   for (target = p->u.generic; target; target = target->next)
10905     {
10906       gfc_symbol* target_proc;
10907
10908       target_proc = get_checked_tb_operator_target (target, p->where);
10909       if (!target_proc)
10910         goto error;
10911
10912       if (!gfc_check_operator_interface (target_proc, op, p->where))
10913         goto error;
10914     }
10915
10916   return SUCCESS;
10917
10918 error:
10919   p->error = 1;
10920   return FAILURE;
10921 }
10922
10923
10924 /* Resolve a type-bound user operator (tree-walker callback).  */
10925
10926 static gfc_symbol* resolve_bindings_derived;
10927 static gfc_try resolve_bindings_result;
10928
10929 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
10930
10931 static void
10932 resolve_typebound_user_op (gfc_symtree* stree)
10933 {
10934   gfc_symbol* super_type;
10935   gfc_tbp_generic* target;
10936
10937   gcc_assert (stree && stree->n.tb);
10938
10939   if (stree->n.tb->error)
10940     return;
10941
10942   /* Operators should always be GENERIC bindings.  */
10943   gcc_assert (stree->n.tb->is_generic);
10944
10945   /* Find overridden procedure, if any.  */
10946   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
10947   if (super_type && super_type->f2k_derived)
10948     {
10949       gfc_symtree* overridden;
10950       overridden = gfc_find_typebound_user_op (super_type, NULL,
10951                                                stree->name, true, NULL);
10952
10953       if (overridden && overridden->n.tb)
10954         stree->n.tb->overridden = overridden->n.tb;
10955     }
10956   else
10957     stree->n.tb->overridden = NULL;
10958
10959   /* Resolve basically using worker function.  */
10960   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
10961         == FAILURE)
10962     goto error;
10963
10964   /* Check the targets to be functions of correct interface.  */
10965   for (target = stree->n.tb->u.generic; target; target = target->next)
10966     {
10967       gfc_symbol* target_proc;
10968
10969       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
10970       if (!target_proc)
10971         goto error;
10972
10973       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
10974         goto error;
10975     }
10976
10977   return;
10978
10979 error:
10980   resolve_bindings_result = FAILURE;
10981   stree->n.tb->error = 1;
10982 }
10983
10984
10985 /* Resolve the type-bound procedures for a derived type.  */
10986
10987 static void
10988 resolve_typebound_procedure (gfc_symtree* stree)
10989 {
10990   gfc_symbol* proc;
10991   locus where;
10992   gfc_symbol* me_arg;
10993   gfc_symbol* super_type;
10994   gfc_component* comp;
10995
10996   gcc_assert (stree);
10997
10998   /* Undefined specific symbol from GENERIC target definition.  */
10999   if (!stree->n.tb)
11000     return;
11001
11002   if (stree->n.tb->error)
11003     return;
11004
11005   /* If this is a GENERIC binding, use that routine.  */
11006   if (stree->n.tb->is_generic)
11007     {
11008       if (resolve_typebound_generic (resolve_bindings_derived, stree)
11009             == FAILURE)
11010         goto error;
11011       return;
11012     }
11013
11014   /* Get the target-procedure to check it.  */
11015   gcc_assert (!stree->n.tb->is_generic);
11016   gcc_assert (stree->n.tb->u.specific);
11017   proc = stree->n.tb->u.specific->n.sym;
11018   where = stree->n.tb->where;
11019
11020   /* Default access should already be resolved from the parser.  */
11021   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
11022
11023   /* It should be a module procedure or an external procedure with explicit
11024      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
11025   if ((!proc->attr.subroutine && !proc->attr.function)
11026       || (proc->attr.proc != PROC_MODULE
11027           && proc->attr.if_source != IFSRC_IFBODY)
11028       || (proc->attr.abstract && !stree->n.tb->deferred))
11029     {
11030       gfc_error ("'%s' must be a module procedure or an external procedure with"
11031                  " an explicit interface at %L", proc->name, &where);
11032       goto error;
11033     }
11034   stree->n.tb->subroutine = proc->attr.subroutine;
11035   stree->n.tb->function = proc->attr.function;
11036
11037   /* Find the super-type of the current derived type.  We could do this once and
11038      store in a global if speed is needed, but as long as not I believe this is
11039      more readable and clearer.  */
11040   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11041
11042   /* If PASS, resolve and check arguments if not already resolved / loaded
11043      from a .mod file.  */
11044   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
11045     {
11046       if (stree->n.tb->pass_arg)
11047         {
11048           gfc_formal_arglist* i;
11049
11050           /* If an explicit passing argument name is given, walk the arg-list
11051              and look for it.  */
11052
11053           me_arg = NULL;
11054           stree->n.tb->pass_arg_num = 1;
11055           for (i = proc->formal; i; i = i->next)
11056             {
11057               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
11058                 {
11059                   me_arg = i->sym;
11060                   break;
11061                 }
11062               ++stree->n.tb->pass_arg_num;
11063             }
11064
11065           if (!me_arg)
11066             {
11067               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
11068                          " argument '%s'",
11069                          proc->name, stree->n.tb->pass_arg, &where,
11070                          stree->n.tb->pass_arg);
11071               goto error;
11072             }
11073         }
11074       else
11075         {
11076           /* Otherwise, take the first one; there should in fact be at least
11077              one.  */
11078           stree->n.tb->pass_arg_num = 1;
11079           if (!proc->formal)
11080             {
11081               gfc_error ("Procedure '%s' with PASS at %L must have at"
11082                          " least one argument", proc->name, &where);
11083               goto error;
11084             }
11085           me_arg = proc->formal->sym;
11086         }
11087
11088       /* Now check that the argument-type matches and the passed-object
11089          dummy argument is generally fine.  */
11090
11091       gcc_assert (me_arg);
11092
11093       if (me_arg->ts.type != BT_CLASS)
11094         {
11095           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11096                      " at %L", proc->name, &where);
11097           goto error;
11098         }
11099
11100       if (CLASS_DATA (me_arg)->ts.u.derived
11101           != resolve_bindings_derived)
11102         {
11103           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11104                      " the derived-type '%s'", me_arg->name, proc->name,
11105                      me_arg->name, &where, resolve_bindings_derived->name);
11106           goto error;
11107         }
11108   
11109       gcc_assert (me_arg->ts.type == BT_CLASS);
11110       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
11111         {
11112           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
11113                      " scalar", proc->name, &where);
11114           goto error;
11115         }
11116       if (CLASS_DATA (me_arg)->attr.allocatable)
11117         {
11118           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11119                      " be ALLOCATABLE", proc->name, &where);
11120           goto error;
11121         }
11122       if (CLASS_DATA (me_arg)->attr.class_pointer)
11123         {
11124           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11125                      " be POINTER", proc->name, &where);
11126           goto error;
11127         }
11128     }
11129
11130   /* If we are extending some type, check that we don't override a procedure
11131      flagged NON_OVERRIDABLE.  */
11132   stree->n.tb->overridden = NULL;
11133   if (super_type)
11134     {
11135       gfc_symtree* overridden;
11136       overridden = gfc_find_typebound_proc (super_type, NULL,
11137                                             stree->name, true, NULL);
11138
11139       if (overridden)
11140         {
11141           if (overridden->n.tb)
11142             stree->n.tb->overridden = overridden->n.tb;
11143
11144           if (gfc_check_typebound_override (stree, overridden) == FAILURE)
11145             goto error;
11146         }
11147     }
11148
11149   /* See if there's a name collision with a component directly in this type.  */
11150   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11151     if (!strcmp (comp->name, stree->name))
11152       {
11153         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11154                    " '%s'",
11155                    stree->name, &where, resolve_bindings_derived->name);
11156         goto error;
11157       }
11158
11159   /* Try to find a name collision with an inherited component.  */
11160   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11161     {
11162       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11163                  " component of '%s'",
11164                  stree->name, &where, resolve_bindings_derived->name);
11165       goto error;
11166     }
11167
11168   stree->n.tb->error = 0;
11169   return;
11170
11171 error:
11172   resolve_bindings_result = FAILURE;
11173   stree->n.tb->error = 1;
11174 }
11175
11176
11177 static gfc_try
11178 resolve_typebound_procedures (gfc_symbol* derived)
11179 {
11180   int op;
11181   gfc_symbol* super_type;
11182
11183   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11184     return SUCCESS;
11185   
11186   super_type = gfc_get_derived_super_type (derived);
11187   if (super_type)
11188     resolve_typebound_procedures (super_type);
11189
11190   resolve_bindings_derived = derived;
11191   resolve_bindings_result = SUCCESS;
11192
11193   /* Make sure the vtab has been generated.  */
11194   gfc_find_derived_vtab (derived);
11195
11196   if (derived->f2k_derived->tb_sym_root)
11197     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11198                           &resolve_typebound_procedure);
11199
11200   if (derived->f2k_derived->tb_uop_root)
11201     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11202                           &resolve_typebound_user_op);
11203
11204   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11205     {
11206       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11207       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11208                                                p) == FAILURE)
11209         resolve_bindings_result = FAILURE;
11210     }
11211
11212   return resolve_bindings_result;
11213 }
11214
11215
11216 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11217    to give all identical derived types the same backend_decl.  */
11218 static void
11219 add_dt_to_dt_list (gfc_symbol *derived)
11220 {
11221   gfc_dt_list *dt_list;
11222
11223   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11224     if (derived == dt_list->derived)
11225       return;
11226
11227   dt_list = gfc_get_dt_list ();
11228   dt_list->next = gfc_derived_types;
11229   dt_list->derived = derived;
11230   gfc_derived_types = dt_list;
11231 }
11232
11233
11234 /* Ensure that a derived-type is really not abstract, meaning that every
11235    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11236
11237 static gfc_try
11238 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11239 {
11240   if (!st)
11241     return SUCCESS;
11242
11243   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11244     return FAILURE;
11245   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11246     return FAILURE;
11247
11248   if (st->n.tb && st->n.tb->deferred)
11249     {
11250       gfc_symtree* overriding;
11251       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11252       if (!overriding)
11253         return FAILURE;
11254       gcc_assert (overriding->n.tb);
11255       if (overriding->n.tb->deferred)
11256         {
11257           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11258                      " '%s' is DEFERRED and not overridden",
11259                      sub->name, &sub->declared_at, st->name);
11260           return FAILURE;
11261         }
11262     }
11263
11264   return SUCCESS;
11265 }
11266
11267 static gfc_try
11268 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11269 {
11270   /* The algorithm used here is to recursively travel up the ancestry of sub
11271      and for each ancestor-type, check all bindings.  If any of them is
11272      DEFERRED, look it up starting from sub and see if the found (overriding)
11273      binding is not DEFERRED.
11274      This is not the most efficient way to do this, but it should be ok and is
11275      clearer than something sophisticated.  */
11276
11277   gcc_assert (ancestor && !sub->attr.abstract);
11278   
11279   if (!ancestor->attr.abstract)
11280     return SUCCESS;
11281
11282   /* Walk bindings of this ancestor.  */
11283   if (ancestor->f2k_derived)
11284     {
11285       gfc_try t;
11286       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11287       if (t == FAILURE)
11288         return FAILURE;
11289     }
11290
11291   /* Find next ancestor type and recurse on it.  */
11292   ancestor = gfc_get_derived_super_type (ancestor);
11293   if (ancestor)
11294     return ensure_not_abstract (sub, ancestor);
11295
11296   return SUCCESS;
11297 }
11298
11299
11300 /* Resolve the components of a derived type. This does not have to wait until
11301    resolution stage, but can be done as soon as the dt declaration has been
11302    parsed.  */
11303
11304 static gfc_try
11305 resolve_fl_derived0 (gfc_symbol *sym)
11306 {
11307   gfc_symbol* super_type;
11308   gfc_component *c;
11309
11310   super_type = gfc_get_derived_super_type (sym);
11311
11312   /* F2008, C432. */
11313   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11314     {
11315       gfc_error ("As extending type '%s' at %L has a coarray component, "
11316                  "parent type '%s' shall also have one", sym->name,
11317                  &sym->declared_at, super_type->name);
11318       return FAILURE;
11319     }
11320
11321   /* Ensure the extended type gets resolved before we do.  */
11322   if (super_type && resolve_fl_derived0 (super_type) == FAILURE)
11323     return FAILURE;
11324
11325   /* An ABSTRACT type must be extensible.  */
11326   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11327     {
11328       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11329                  sym->name, &sym->declared_at);
11330       return FAILURE;
11331     }
11332
11333   for (c = sym->components; c != NULL; c = c->next)
11334     {
11335       /* F2008, C442.  */
11336       if (c->attr.codimension /* FIXME: c->as check due to PR 43412.  */
11337           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11338         {
11339           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11340                      "deferred shape", c->name, &c->loc);
11341           return FAILURE;
11342         }
11343
11344       /* F2008, C443.  */
11345       if (c->attr.codimension && c->ts.type == BT_DERIVED
11346           && c->ts.u.derived->ts.is_iso_c)
11347         {
11348           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11349                      "shall not be a coarray", c->name, &c->loc);
11350           return FAILURE;
11351         }
11352
11353       /* F2008, C444.  */
11354       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11355           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11356               || c->attr.allocatable))
11357         {
11358           gfc_error ("Component '%s' at %L with coarray component "
11359                      "shall be a nonpointer, nonallocatable scalar",
11360                      c->name, &c->loc);
11361           return FAILURE;
11362         }
11363
11364       /* F2008, C448.  */
11365       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11366         {
11367           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11368                      "is not an array pointer", c->name, &c->loc);
11369           return FAILURE;
11370         }
11371
11372       if (c->attr.proc_pointer && c->ts.interface)
11373         {
11374           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11375             gfc_error ("Interface '%s', used by procedure pointer component "
11376                        "'%s' at %L, is declared in a later PROCEDURE statement",
11377                        c->ts.interface->name, c->name, &c->loc);
11378
11379           /* Get the attributes from the interface (now resolved).  */
11380           if (c->ts.interface->attr.if_source
11381               || c->ts.interface->attr.intrinsic)
11382             {
11383               gfc_symbol *ifc = c->ts.interface;
11384
11385               if (ifc->formal && !ifc->formal_ns)
11386                 resolve_symbol (ifc);
11387
11388               if (ifc->attr.intrinsic)
11389                 resolve_intrinsic (ifc, &ifc->declared_at);
11390
11391               if (ifc->result)
11392                 {
11393                   c->ts = ifc->result->ts;
11394                   c->attr.allocatable = ifc->result->attr.allocatable;
11395                   c->attr.pointer = ifc->result->attr.pointer;
11396                   c->attr.dimension = ifc->result->attr.dimension;
11397                   c->as = gfc_copy_array_spec (ifc->result->as);
11398                 }
11399               else
11400                 {   
11401                   c->ts = ifc->ts;
11402                   c->attr.allocatable = ifc->attr.allocatable;
11403                   c->attr.pointer = ifc->attr.pointer;
11404                   c->attr.dimension = ifc->attr.dimension;
11405                   c->as = gfc_copy_array_spec (ifc->as);
11406                 }
11407               c->ts.interface = ifc;
11408               c->attr.function = ifc->attr.function;
11409               c->attr.subroutine = ifc->attr.subroutine;
11410               gfc_copy_formal_args_ppc (c, ifc);
11411
11412               c->attr.pure = ifc->attr.pure;
11413               c->attr.elemental = ifc->attr.elemental;
11414               c->attr.recursive = ifc->attr.recursive;
11415               c->attr.always_explicit = ifc->attr.always_explicit;
11416               c->attr.ext_attr |= ifc->attr.ext_attr;
11417               /* Replace symbols in array spec.  */
11418               if (c->as)
11419                 {
11420                   int i;
11421                   for (i = 0; i < c->as->rank; i++)
11422                     {
11423                       gfc_expr_replace_comp (c->as->lower[i], c);
11424                       gfc_expr_replace_comp (c->as->upper[i], c);
11425                     }
11426                 }
11427               /* Copy char length.  */
11428               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11429                 {
11430                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11431                   gfc_expr_replace_comp (cl->length, c);
11432                   if (cl->length && !cl->resolved
11433                         && gfc_resolve_expr (cl->length) == FAILURE)
11434                     return FAILURE;
11435                   c->ts.u.cl = cl;
11436                 }
11437             }
11438           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11439             {
11440               gfc_error ("Interface '%s' of procedure pointer component "
11441                          "'%s' at %L must be explicit", c->ts.interface->name,
11442                          c->name, &c->loc);
11443               return FAILURE;
11444             }
11445         }
11446       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11447         {
11448           /* Since PPCs are not implicitly typed, a PPC without an explicit
11449              interface must be a subroutine.  */
11450           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11451         }
11452
11453       /* Procedure pointer components: Check PASS arg.  */
11454       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11455           && !sym->attr.vtype)
11456         {
11457           gfc_symbol* me_arg;
11458
11459           if (c->tb->pass_arg)
11460             {
11461               gfc_formal_arglist* i;
11462
11463               /* If an explicit passing argument name is given, walk the arg-list
11464                 and look for it.  */
11465
11466               me_arg = NULL;
11467               c->tb->pass_arg_num = 1;
11468               for (i = c->formal; i; i = i->next)
11469                 {
11470                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11471                     {
11472                       me_arg = i->sym;
11473                       break;
11474                     }
11475                   c->tb->pass_arg_num++;
11476                 }
11477
11478               if (!me_arg)
11479                 {
11480                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11481                              "at %L has no argument '%s'", c->name,
11482                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11483                   c->tb->error = 1;
11484                   return FAILURE;
11485                 }
11486             }
11487           else
11488             {
11489               /* Otherwise, take the first one; there should in fact be at least
11490                 one.  */
11491               c->tb->pass_arg_num = 1;
11492               if (!c->formal)
11493                 {
11494                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11495                              "must have at least one argument",
11496                              c->name, &c->loc);
11497                   c->tb->error = 1;
11498                   return FAILURE;
11499                 }
11500               me_arg = c->formal->sym;
11501             }
11502
11503           /* Now check that the argument-type matches.  */
11504           gcc_assert (me_arg);
11505           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11506               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11507               || (me_arg->ts.type == BT_CLASS
11508                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11509             {
11510               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11511                          " the derived type '%s'", me_arg->name, c->name,
11512                          me_arg->name, &c->loc, sym->name);
11513               c->tb->error = 1;
11514               return FAILURE;
11515             }
11516
11517           /* Check for C453.  */
11518           if (me_arg->attr.dimension)
11519             {
11520               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11521                          "must be scalar", me_arg->name, c->name, me_arg->name,
11522                          &c->loc);
11523               c->tb->error = 1;
11524               return FAILURE;
11525             }
11526
11527           if (me_arg->attr.pointer)
11528             {
11529               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11530                          "may not have the POINTER attribute", me_arg->name,
11531                          c->name, me_arg->name, &c->loc);
11532               c->tb->error = 1;
11533               return FAILURE;
11534             }
11535
11536           if (me_arg->attr.allocatable)
11537             {
11538               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11539                          "may not be ALLOCATABLE", me_arg->name, c->name,
11540                          me_arg->name, &c->loc);
11541               c->tb->error = 1;
11542               return FAILURE;
11543             }
11544
11545           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11546             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11547                        " at %L", c->name, &c->loc);
11548
11549         }
11550
11551       /* Check type-spec if this is not the parent-type component.  */
11552       if ((!sym->attr.extension || c != sym->components) && !sym->attr.vtype
11553           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11554         return FAILURE;
11555
11556       /* If this type is an extension, set the accessibility of the parent
11557          component.  */
11558       if (super_type && c == sym->components
11559           && strcmp (super_type->name, c->name) == 0)
11560         c->attr.access = super_type->attr.access;
11561       
11562       /* If this type is an extension, see if this component has the same name
11563          as an inherited type-bound procedure.  */
11564       if (super_type && !sym->attr.is_class
11565           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11566         {
11567           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11568                      " inherited type-bound procedure",
11569                      c->name, sym->name, &c->loc);
11570           return FAILURE;
11571         }
11572
11573       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
11574             && !c->ts.deferred)
11575         {
11576          if (c->ts.u.cl->length == NULL
11577              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11578              || !gfc_is_constant_expr (c->ts.u.cl->length))
11579            {
11580              gfc_error ("Character length of component '%s' needs to "
11581                         "be a constant specification expression at %L",
11582                         c->name,
11583                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11584              return FAILURE;
11585            }
11586         }
11587
11588       if (c->ts.type == BT_CHARACTER && c->ts.deferred
11589           && !c->attr.pointer && !c->attr.allocatable)
11590         {
11591           gfc_error ("Character component '%s' of '%s' at %L with deferred "
11592                      "length must be a POINTER or ALLOCATABLE",
11593                      c->name, sym->name, &c->loc);
11594           return FAILURE;
11595         }
11596
11597       if (c->ts.type == BT_DERIVED
11598           && sym->component_access != ACCESS_PRIVATE
11599           && gfc_check_symbol_access (sym)
11600           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11601           && !c->ts.u.derived->attr.use_assoc
11602           && !gfc_check_symbol_access (c->ts.u.derived)
11603           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11604                              "is a PRIVATE type and cannot be a component of "
11605                              "'%s', which is PUBLIC at %L", c->name,
11606                              sym->name, &sym->declared_at) == FAILURE)
11607         return FAILURE;
11608
11609       if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
11610         {
11611           gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
11612                      "type %s", c->name, &c->loc, sym->name);
11613           return FAILURE;
11614         }
11615
11616       if (sym->attr.sequence)
11617         {
11618           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11619             {
11620               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11621                          "not have the SEQUENCE attribute",
11622                          c->ts.u.derived->name, &sym->declared_at);
11623               return FAILURE;
11624             }
11625         }
11626
11627       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && !sym->attr.vtype
11628           && c->attr.pointer && c->ts.u.derived->components == NULL
11629           && !c->ts.u.derived->attr.zero_comp)
11630         {
11631           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11632                      "that has not been declared", c->name, sym->name,
11633                      &c->loc);
11634           return FAILURE;
11635         }
11636
11637       if (c->ts.type == BT_CLASS && c->attr.class_ok
11638           && CLASS_DATA (c)->attr.class_pointer
11639           && CLASS_DATA (c)->ts.u.derived->components == NULL
11640           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11641         {
11642           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11643                      "that has not been declared", c->name, sym->name,
11644                      &c->loc);
11645           return FAILURE;
11646         }
11647
11648       /* C437.  */
11649       if (c->ts.type == BT_CLASS && c->attr.flavor != FL_PROCEDURE
11650           && (!c->attr.class_ok
11651               || !(CLASS_DATA (c)->attr.class_pointer
11652                    || CLASS_DATA (c)->attr.allocatable)))
11653         {
11654           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11655                      "or pointer", c->name, &c->loc);
11656           return FAILURE;
11657         }
11658
11659       /* Ensure that all the derived type components are put on the
11660          derived type list; even in formal namespaces, where derived type
11661          pointer components might not have been declared.  */
11662       if (c->ts.type == BT_DERIVED
11663             && c->ts.u.derived
11664             && c->ts.u.derived->components
11665             && c->attr.pointer
11666             && sym != c->ts.u.derived)
11667         add_dt_to_dt_list (c->ts.u.derived);
11668
11669       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11670                                            || c->attr.proc_pointer
11671                                            || c->attr.allocatable)) == FAILURE)
11672         return FAILURE;
11673     }
11674
11675   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11676      all DEFERRED bindings are overridden.  */
11677   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11678       && !sym->attr.is_class
11679       && ensure_not_abstract (sym, super_type) == FAILURE)
11680     return FAILURE;
11681
11682   /* Add derived type to the derived type list.  */
11683   add_dt_to_dt_list (sym);
11684
11685   return SUCCESS;
11686 }
11687
11688
11689 /* The following procedure does the full resolution of a derived type,
11690    including resolution of all type-bound procedures (if present). In contrast
11691    to 'resolve_fl_derived0' this can only be done after the module has been
11692    parsed completely.  */
11693
11694 static gfc_try
11695 resolve_fl_derived (gfc_symbol *sym)
11696 {
11697   if (sym->attr.is_class && sym->ts.u.derived == NULL)
11698     {
11699       /* Fix up incomplete CLASS symbols.  */
11700       gfc_component *data = gfc_find_component (sym, "_data", true, true);
11701       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true);
11702       if (vptr->ts.u.derived == NULL)
11703         {
11704           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
11705           gcc_assert (vtab);
11706           vptr->ts.u.derived = vtab->ts.u.derived;
11707         }
11708     }
11709   
11710   if (resolve_fl_derived0 (sym) == FAILURE)
11711     return FAILURE;
11712   
11713   /* Resolve the type-bound procedures.  */
11714   if (resolve_typebound_procedures (sym) == FAILURE)
11715     return FAILURE;
11716
11717   /* Resolve the finalizer procedures.  */
11718   if (gfc_resolve_finalizers (sym) == FAILURE)
11719     return FAILURE;
11720   
11721   return SUCCESS;
11722 }
11723
11724
11725 static gfc_try
11726 resolve_fl_namelist (gfc_symbol *sym)
11727 {
11728   gfc_namelist *nl;
11729   gfc_symbol *nlsym;
11730
11731   for (nl = sym->namelist; nl; nl = nl->next)
11732     {
11733       /* Check again, the check in match only works if NAMELIST comes
11734          after the decl.  */
11735       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SIZE)
11736         {
11737           gfc_error ("Assumed size array '%s' in namelist '%s' at %L is not "
11738                      "allowed", nl->sym->name, sym->name, &sym->declared_at);
11739           return FAILURE;
11740         }
11741
11742       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
11743           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: NAMELIST array "
11744                              "object '%s' with assumed shape in namelist "
11745                              "'%s' at %L", nl->sym->name, sym->name,
11746                              &sym->declared_at) == FAILURE)
11747         return FAILURE;
11748
11749       if (is_non_constant_shape_array (nl->sym)
11750           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST array "
11751                              "object '%s' with nonconstant shape in namelist "
11752                              "'%s' at %L", nl->sym->name, sym->name,
11753                              &sym->declared_at) == FAILURE)
11754         return FAILURE;
11755
11756       if (nl->sym->ts.type == BT_CHARACTER
11757           && (nl->sym->ts.u.cl->length == NULL
11758               || !gfc_is_constant_expr (nl->sym->ts.u.cl->length))
11759           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
11760                              "'%s' with nonconstant character length in "
11761                              "namelist '%s' at %L", nl->sym->name, sym->name,
11762                              &sym->declared_at) == FAILURE)
11763         return FAILURE;
11764
11765       /* FIXME: Once UDDTIO is implemented, the following can be
11766          removed.  */
11767       if (nl->sym->ts.type == BT_CLASS)
11768         {
11769           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L is "
11770                      "polymorphic and requires a defined input/output "
11771                      "procedure", nl->sym->name, sym->name, &sym->declared_at);
11772           return FAILURE;
11773         }
11774
11775       if (nl->sym->ts.type == BT_DERIVED
11776           && (nl->sym->ts.u.derived->attr.alloc_comp
11777               || nl->sym->ts.u.derived->attr.pointer_comp))
11778         {
11779           if (gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
11780                               "'%s' in namelist '%s' at %L with ALLOCATABLE "
11781                               "or POINTER components", nl->sym->name,
11782                               sym->name, &sym->declared_at) == FAILURE)
11783             return FAILURE;
11784
11785          /* FIXME: Once UDDTIO is implemented, the following can be
11786             removed.  */
11787           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L has "
11788                      "ALLOCATABLE or POINTER components and thus requires "
11789                      "a defined input/output procedure", nl->sym->name,
11790                      sym->name, &sym->declared_at);
11791           return FAILURE;
11792         }
11793     }
11794
11795   /* Reject PRIVATE objects in a PUBLIC namelist.  */
11796   if (gfc_check_symbol_access (sym))
11797     {
11798       for (nl = sym->namelist; nl; nl = nl->next)
11799         {
11800           if (!nl->sym->attr.use_assoc
11801               && !is_sym_host_assoc (nl->sym, sym->ns)
11802               && !gfc_check_symbol_access (nl->sym))
11803             {
11804               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
11805                          "cannot be member of PUBLIC namelist '%s' at %L",
11806                          nl->sym->name, sym->name, &sym->declared_at);
11807               return FAILURE;
11808             }
11809
11810           /* Types with private components that came here by USE-association.  */
11811           if (nl->sym->ts.type == BT_DERIVED
11812               && derived_inaccessible (nl->sym->ts.u.derived))
11813             {
11814               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
11815                          "components and cannot be member of namelist '%s' at %L",
11816                          nl->sym->name, sym->name, &sym->declared_at);
11817               return FAILURE;
11818             }
11819
11820           /* Types with private components that are defined in the same module.  */
11821           if (nl->sym->ts.type == BT_DERIVED
11822               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
11823               && nl->sym->ts.u.derived->attr.private_comp)
11824             {
11825               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
11826                          "cannot be a member of PUBLIC namelist '%s' at %L",
11827                          nl->sym->name, sym->name, &sym->declared_at);
11828               return FAILURE;
11829             }
11830         }
11831     }
11832
11833
11834   /* 14.1.2 A module or internal procedure represent local entities
11835      of the same type as a namelist member and so are not allowed.  */
11836   for (nl = sym->namelist; nl; nl = nl->next)
11837     {
11838       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
11839         continue;
11840
11841       if (nl->sym->attr.function && nl->sym == nl->sym->result)
11842         if ((nl->sym == sym->ns->proc_name)
11843                ||
11844             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
11845           continue;
11846
11847       nlsym = NULL;
11848       if (nl->sym && nl->sym->name)
11849         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
11850       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
11851         {
11852           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
11853                      "attribute in '%s' at %L", nlsym->name,
11854                      &sym->declared_at);
11855           return FAILURE;
11856         }
11857     }
11858
11859   return SUCCESS;
11860 }
11861
11862
11863 static gfc_try
11864 resolve_fl_parameter (gfc_symbol *sym)
11865 {
11866   /* A parameter array's shape needs to be constant.  */
11867   if (sym->as != NULL 
11868       && (sym->as->type == AS_DEFERRED
11869           || is_non_constant_shape_array (sym)))
11870     {
11871       gfc_error ("Parameter array '%s' at %L cannot be automatic "
11872                  "or of deferred shape", sym->name, &sym->declared_at);
11873       return FAILURE;
11874     }
11875
11876   /* Make sure a parameter that has been implicitly typed still
11877      matches the implicit type, since PARAMETER statements can precede
11878      IMPLICIT statements.  */
11879   if (sym->attr.implicit_type
11880       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
11881                                                              sym->ns)))
11882     {
11883       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
11884                  "later IMPLICIT type", sym->name, &sym->declared_at);
11885       return FAILURE;
11886     }
11887
11888   /* Make sure the types of derived parameters are consistent.  This
11889      type checking is deferred until resolution because the type may
11890      refer to a derived type from the host.  */
11891   if (sym->ts.type == BT_DERIVED
11892       && !gfc_compare_types (&sym->ts, &sym->value->ts))
11893     {
11894       gfc_error ("Incompatible derived type in PARAMETER at %L",
11895                  &sym->value->where);
11896       return FAILURE;
11897     }
11898   return SUCCESS;
11899 }
11900
11901
11902 /* Do anything necessary to resolve a symbol.  Right now, we just
11903    assume that an otherwise unknown symbol is a variable.  This sort
11904    of thing commonly happens for symbols in module.  */
11905
11906 static void
11907 resolve_symbol (gfc_symbol *sym)
11908 {
11909   int check_constant, mp_flag;
11910   gfc_symtree *symtree;
11911   gfc_symtree *this_symtree;
11912   gfc_namespace *ns;
11913   gfc_component *c;
11914
11915   if (sym->attr.flavor == FL_UNKNOWN)
11916     {
11917
11918     /* If we find that a flavorless symbol is an interface in one of the
11919        parent namespaces, find its symtree in this namespace, free the
11920        symbol and set the symtree to point to the interface symbol.  */
11921       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
11922         {
11923           symtree = gfc_find_symtree (ns->sym_root, sym->name);
11924           if (symtree && (symtree->n.sym->generic ||
11925                           (symtree->n.sym->attr.flavor == FL_PROCEDURE
11926                            && sym->ns->construct_entities)))
11927             {
11928               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
11929                                                sym->name);
11930               gfc_release_symbol (sym);
11931               symtree->n.sym->refs++;
11932               this_symtree->n.sym = symtree->n.sym;
11933               return;
11934             }
11935         }
11936
11937       /* Otherwise give it a flavor according to such attributes as
11938          it has.  */
11939       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
11940         sym->attr.flavor = FL_VARIABLE;
11941       else
11942         {
11943           sym->attr.flavor = FL_PROCEDURE;
11944           if (sym->attr.dimension)
11945             sym->attr.function = 1;
11946         }
11947     }
11948
11949   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
11950     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
11951
11952   if (sym->attr.procedure && sym->ts.interface
11953       && sym->attr.if_source != IFSRC_DECL
11954       && resolve_procedure_interface (sym) == FAILURE)
11955     return;
11956
11957   if (sym->attr.is_protected && !sym->attr.proc_pointer
11958       && (sym->attr.procedure || sym->attr.external))
11959     {
11960       if (sym->attr.external)
11961         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
11962                    "at %L", &sym->declared_at);
11963       else
11964         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
11965                    "at %L", &sym->declared_at);
11966
11967       return;
11968     }
11969
11970
11971   /* F2008, C530. */
11972   if (sym->attr.contiguous
11973       && (!sym->attr.dimension || (sym->as->type != AS_ASSUMED_SHAPE
11974                                    && !sym->attr.pointer)))
11975     {
11976       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
11977                   "array pointer or an assumed-shape array", sym->name,
11978                   &sym->declared_at);
11979       return;
11980     }
11981
11982   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
11983     return;
11984
11985   /* Symbols that are module procedures with results (functions) have
11986      the types and array specification copied for type checking in
11987      procedures that call them, as well as for saving to a module
11988      file.  These symbols can't stand the scrutiny that their results
11989      can.  */
11990   mp_flag = (sym->result != NULL && sym->result != sym);
11991
11992   /* Make sure that the intrinsic is consistent with its internal 
11993      representation. This needs to be done before assigning a default 
11994      type to avoid spurious warnings.  */
11995   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
11996       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
11997     return;
11998
11999   /* Resolve associate names.  */
12000   if (sym->assoc)
12001     resolve_assoc_var (sym, true);
12002
12003   /* Assign default type to symbols that need one and don't have one.  */
12004   if (sym->ts.type == BT_UNKNOWN)
12005     {
12006       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
12007         gfc_set_default_type (sym, 1, NULL);
12008
12009       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
12010           && !sym->attr.function && !sym->attr.subroutine
12011           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
12012         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
12013
12014       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12015         {
12016           /* The specific case of an external procedure should emit an error
12017              in the case that there is no implicit type.  */
12018           if (!mp_flag)
12019             gfc_set_default_type (sym, sym->attr.external, NULL);
12020           else
12021             {
12022               /* Result may be in another namespace.  */
12023               resolve_symbol (sym->result);
12024
12025               if (!sym->result->attr.proc_pointer)
12026                 {
12027                   sym->ts = sym->result->ts;
12028                   sym->as = gfc_copy_array_spec (sym->result->as);
12029                   sym->attr.dimension = sym->result->attr.dimension;
12030                   sym->attr.pointer = sym->result->attr.pointer;
12031                   sym->attr.allocatable = sym->result->attr.allocatable;
12032                   sym->attr.contiguous = sym->result->attr.contiguous;
12033                 }
12034             }
12035         }
12036     }
12037   else if (mp_flag && sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12038     gfc_resolve_array_spec (sym->result->as, false);
12039
12040   /* Assumed size arrays and assumed shape arrays must be dummy
12041      arguments.  Array-spec's of implied-shape should have been resolved to
12042      AS_EXPLICIT already.  */
12043
12044   if (sym->as)
12045     {
12046       gcc_assert (sym->as->type != AS_IMPLIED_SHAPE);
12047       if (((sym->as->type == AS_ASSUMED_SIZE && !sym->as->cp_was_assumed)
12048            || sym->as->type == AS_ASSUMED_SHAPE)
12049           && sym->attr.dummy == 0)
12050         {
12051           if (sym->as->type == AS_ASSUMED_SIZE)
12052             gfc_error ("Assumed size array at %L must be a dummy argument",
12053                        &sym->declared_at);
12054           else
12055             gfc_error ("Assumed shape array at %L must be a dummy argument",
12056                        &sym->declared_at);
12057           return;
12058         }
12059     }
12060
12061   /* Make sure symbols with known intent or optional are really dummy
12062      variable.  Because of ENTRY statement, this has to be deferred
12063      until resolution time.  */
12064
12065   if (!sym->attr.dummy
12066       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
12067     {
12068       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
12069       return;
12070     }
12071
12072   if (sym->attr.value && !sym->attr.dummy)
12073     {
12074       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
12075                  "it is not a dummy argument", sym->name, &sym->declared_at);
12076       return;
12077     }
12078
12079   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
12080     {
12081       gfc_charlen *cl = sym->ts.u.cl;
12082       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12083         {
12084           gfc_error ("Character dummy variable '%s' at %L with VALUE "
12085                      "attribute must have constant length",
12086                      sym->name, &sym->declared_at);
12087           return;
12088         }
12089
12090       if (sym->ts.is_c_interop
12091           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
12092         {
12093           gfc_error ("C interoperable character dummy variable '%s' at %L "
12094                      "with VALUE attribute must have length one",
12095                      sym->name, &sym->declared_at);
12096           return;
12097         }
12098     }
12099
12100   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
12101      do this for something that was implicitly typed because that is handled
12102      in gfc_set_default_type.  Handle dummy arguments and procedure
12103      definitions separately.  Also, anything that is use associated is not
12104      handled here but instead is handled in the module it is declared in.
12105      Finally, derived type definitions are allowed to be BIND(C) since that
12106      only implies that they're interoperable, and they are checked fully for
12107      interoperability when a variable is declared of that type.  */
12108   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
12109       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
12110       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
12111     {
12112       gfc_try t = SUCCESS;
12113       
12114       /* First, make sure the variable is declared at the
12115          module-level scope (J3/04-007, Section 15.3).  */
12116       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
12117           sym->attr.in_common == 0)
12118         {
12119           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
12120                      "is neither a COMMON block nor declared at the "
12121                      "module level scope", sym->name, &(sym->declared_at));
12122           t = FAILURE;
12123         }
12124       else if (sym->common_head != NULL)
12125         {
12126           t = verify_com_block_vars_c_interop (sym->common_head);
12127         }
12128       else
12129         {
12130           /* If type() declaration, we need to verify that the components
12131              of the given type are all C interoperable, etc.  */
12132           if (sym->ts.type == BT_DERIVED &&
12133               sym->ts.u.derived->attr.is_c_interop != 1)
12134             {
12135               /* Make sure the user marked the derived type as BIND(C).  If
12136                  not, call the verify routine.  This could print an error
12137                  for the derived type more than once if multiple variables
12138                  of that type are declared.  */
12139               if (sym->ts.u.derived->attr.is_bind_c != 1)
12140                 verify_bind_c_derived_type (sym->ts.u.derived);
12141               t = FAILURE;
12142             }
12143           
12144           /* Verify the variable itself as C interoperable if it
12145              is BIND(C).  It is not possible for this to succeed if
12146              the verify_bind_c_derived_type failed, so don't have to handle
12147              any error returned by verify_bind_c_derived_type.  */
12148           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12149                                  sym->common_block);
12150         }
12151
12152       if (t == FAILURE)
12153         {
12154           /* clear the is_bind_c flag to prevent reporting errors more than
12155              once if something failed.  */
12156           sym->attr.is_bind_c = 0;
12157           return;
12158         }
12159     }
12160
12161   /* If a derived type symbol has reached this point, without its
12162      type being declared, we have an error.  Notice that most
12163      conditions that produce undefined derived types have already
12164      been dealt with.  However, the likes of:
12165      implicit type(t) (t) ..... call foo (t) will get us here if
12166      the type is not declared in the scope of the implicit
12167      statement. Change the type to BT_UNKNOWN, both because it is so
12168      and to prevent an ICE.  */
12169   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->components == NULL
12170       && !sym->ts.u.derived->attr.zero_comp)
12171     {
12172       gfc_error ("The derived type '%s' at %L is of type '%s', "
12173                  "which has not been defined", sym->name,
12174                   &sym->declared_at, sym->ts.u.derived->name);
12175       sym->ts.type = BT_UNKNOWN;
12176       return;
12177     }
12178
12179   /* Make sure that the derived type has been resolved and that the
12180      derived type is visible in the symbol's namespace, if it is a
12181      module function and is not PRIVATE.  */
12182   if (sym->ts.type == BT_DERIVED
12183         && sym->ts.u.derived->attr.use_assoc
12184         && sym->ns->proc_name
12185         && sym->ns->proc_name->attr.flavor == FL_MODULE)
12186     {
12187       gfc_symbol *ds;
12188
12189       if (resolve_fl_derived (sym->ts.u.derived) == FAILURE)
12190         return;
12191
12192       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 1, &ds);
12193       if (!ds && sym->attr.function && gfc_check_symbol_access (sym))
12194         {
12195           symtree = gfc_new_symtree (&sym->ns->sym_root,
12196                                      sym->ts.u.derived->name);
12197           symtree->n.sym = sym->ts.u.derived;
12198           sym->ts.u.derived->refs++;
12199         }
12200     }
12201
12202   /* Unless the derived-type declaration is use associated, Fortran 95
12203      does not allow public entries of private derived types.
12204      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12205      161 in 95-006r3.  */
12206   if (sym->ts.type == BT_DERIVED
12207       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12208       && !sym->ts.u.derived->attr.use_assoc
12209       && gfc_check_symbol_access (sym)
12210       && !gfc_check_symbol_access (sym->ts.u.derived)
12211       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12212                          "of PRIVATE derived type '%s'",
12213                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12214                          : "variable", sym->name, &sym->declared_at,
12215                          sym->ts.u.derived->name) == FAILURE)
12216     return;
12217
12218   /* F2008, C1302.  */
12219   if (sym->ts.type == BT_DERIVED
12220       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
12221            && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
12222           || sym->ts.u.derived->attr.lock_comp)
12223       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
12224     {
12225       gfc_error ("Variable %s at %L of type LOCK_TYPE or with subcomponent of "
12226                  "type LOCK_TYPE must be a coarray", sym->name,
12227                  &sym->declared_at);
12228       return;
12229     }
12230
12231   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12232      default initialization is defined (5.1.2.4.4).  */
12233   if (sym->ts.type == BT_DERIVED
12234       && sym->attr.dummy
12235       && sym->attr.intent == INTENT_OUT
12236       && sym->as
12237       && sym->as->type == AS_ASSUMED_SIZE)
12238     {
12239       for (c = sym->ts.u.derived->components; c; c = c->next)
12240         {
12241           if (c->initializer)
12242             {
12243               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12244                          "ASSUMED SIZE and so cannot have a default initializer",
12245                          sym->name, &sym->declared_at);
12246               return;
12247             }
12248         }
12249     }
12250
12251   /* F2008, C542.  */
12252   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
12253       && sym->attr.intent == INTENT_OUT && sym->attr.lock_comp)
12254     {
12255       gfc_error ("Dummy argument '%s' at %L of LOCK_TYPE shall not be "
12256                  "INTENT(OUT)", sym->name, &sym->declared_at);
12257       return;
12258     }
12259
12260   /* F2008, C525.  */
12261   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12262        || sym->attr.codimension)
12263       && (sym->attr.result || sym->result == sym))
12264     {
12265       gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12266                  "a coarray component", sym->name, &sym->declared_at);
12267       return;
12268     }
12269
12270   /* F2008, C524.  */
12271   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12272       && sym->ts.u.derived->ts.is_iso_c)
12273     {
12274       gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12275                  "shall not be a coarray", sym->name, &sym->declared_at);
12276       return;
12277     }
12278
12279   /* F2008, C525.  */
12280   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp
12281       && (sym->attr.codimension || sym->attr.pointer || sym->attr.dimension
12282           || sym->attr.allocatable))
12283     {
12284       gfc_error ("Variable '%s' at %L with coarray component "
12285                  "shall be a nonpointer, nonallocatable scalar",
12286                  sym->name, &sym->declared_at);
12287       return;
12288     }
12289
12290   /* F2008, C526.  The function-result case was handled above.  */
12291   if (sym->attr.codimension
12292       && !(sym->attr.allocatable || sym->attr.dummy || sym->attr.save
12293            || sym->ns->save_all
12294            || sym->ns->proc_name->attr.flavor == FL_MODULE
12295            || sym->ns->proc_name->attr.is_main_program
12296            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12297     {
12298       gfc_error ("Variable '%s' at %L is a coarray and is not ALLOCATABLE, SAVE "
12299                  "nor a dummy argument", sym->name, &sym->declared_at);
12300       return;
12301     }
12302   /* F2008, C528.  */  /* FIXME: sym->as check due to PR 43412.  */
12303   else if (sym->attr.codimension && !sym->attr.allocatable
12304       && sym->as && sym->as->cotype == AS_DEFERRED)
12305     {
12306       gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12307                  "deferred shape", sym->name, &sym->declared_at);
12308       return;
12309     }
12310   else if (sym->attr.codimension && sym->attr.allocatable
12311       && (sym->as->type != AS_DEFERRED || sym->as->cotype != AS_DEFERRED))
12312     {
12313       gfc_error ("Allocatable coarray variable '%s' at %L must have "
12314                  "deferred shape", sym->name, &sym->declared_at);
12315       return;
12316     }
12317
12318   /* F2008, C541.  */
12319   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12320        || (sym->attr.codimension && sym->attr.allocatable))
12321       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12322     {
12323       gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12324                  "allocatable coarray or have coarray components",
12325                  sym->name, &sym->declared_at);
12326       return;
12327     }
12328
12329   if (sym->attr.codimension && sym->attr.dummy
12330       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12331     {
12332       gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12333                  "procedure '%s'", sym->name, &sym->declared_at,
12334                  sym->ns->proc_name->name);
12335       return;
12336     }
12337
12338   switch (sym->attr.flavor)
12339     {
12340     case FL_VARIABLE:
12341       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12342         return;
12343       break;
12344
12345     case FL_PROCEDURE:
12346       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12347         return;
12348       break;
12349
12350     case FL_NAMELIST:
12351       if (resolve_fl_namelist (sym) == FAILURE)
12352         return;
12353       break;
12354
12355     case FL_PARAMETER:
12356       if (resolve_fl_parameter (sym) == FAILURE)
12357         return;
12358       break;
12359
12360     default:
12361       break;
12362     }
12363
12364   /* Resolve array specifier. Check as well some constraints
12365      on COMMON blocks.  */
12366
12367   check_constant = sym->attr.in_common && !sym->attr.pointer;
12368
12369   /* Set the formal_arg_flag so that check_conflict will not throw
12370      an error for host associated variables in the specification
12371      expression for an array_valued function.  */
12372   if (sym->attr.function && sym->as)
12373     formal_arg_flag = 1;
12374
12375   gfc_resolve_array_spec (sym->as, check_constant);
12376
12377   formal_arg_flag = 0;
12378
12379   /* Resolve formal namespaces.  */
12380   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12381       && !sym->attr.contained && !sym->attr.intrinsic)
12382     gfc_resolve (sym->formal_ns);
12383
12384   /* Make sure the formal namespace is present.  */
12385   if (sym->formal && !sym->formal_ns)
12386     {
12387       gfc_formal_arglist *formal = sym->formal;
12388       while (formal && !formal->sym)
12389         formal = formal->next;
12390
12391       if (formal)
12392         {
12393           sym->formal_ns = formal->sym->ns;
12394           sym->formal_ns->refs++;
12395         }
12396     }
12397
12398   /* Check threadprivate restrictions.  */
12399   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12400       && (!sym->attr.in_common
12401           && sym->module == NULL
12402           && (sym->ns->proc_name == NULL
12403               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12404     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12405
12406   /* If we have come this far we can apply default-initializers, as
12407      described in 14.7.5, to those variables that have not already
12408      been assigned one.  */
12409   if (sym->ts.type == BT_DERIVED
12410       && sym->ns == gfc_current_ns
12411       && !sym->value
12412       && !sym->attr.allocatable
12413       && !sym->attr.alloc_comp)
12414     {
12415       symbol_attribute *a = &sym->attr;
12416
12417       if ((!a->save && !a->dummy && !a->pointer
12418            && !a->in_common && !a->use_assoc
12419            && (a->referenced || a->result)
12420            && !(a->function && sym != sym->result))
12421           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12422         apply_default_init (sym);
12423     }
12424
12425   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
12426       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
12427       && !CLASS_DATA (sym)->attr.class_pointer
12428       && !CLASS_DATA (sym)->attr.allocatable)
12429     apply_default_init (sym);
12430
12431   /* If this symbol has a type-spec, check it.  */
12432   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12433       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12434     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12435           == FAILURE)
12436       return;
12437 }
12438
12439
12440 /************* Resolve DATA statements *************/
12441
12442 static struct
12443 {
12444   gfc_data_value *vnode;
12445   mpz_t left;
12446 }
12447 values;
12448
12449
12450 /* Advance the values structure to point to the next value in the data list.  */
12451
12452 static gfc_try
12453 next_data_value (void)
12454 {
12455   while (mpz_cmp_ui (values.left, 0) == 0)
12456     {
12457
12458       if (values.vnode->next == NULL)
12459         return FAILURE;
12460
12461       values.vnode = values.vnode->next;
12462       mpz_set (values.left, values.vnode->repeat);
12463     }
12464
12465   return SUCCESS;
12466 }
12467
12468
12469 static gfc_try
12470 check_data_variable (gfc_data_variable *var, locus *where)
12471 {
12472   gfc_expr *e;
12473   mpz_t size;
12474   mpz_t offset;
12475   gfc_try t;
12476   ar_type mark = AR_UNKNOWN;
12477   int i;
12478   mpz_t section_index[GFC_MAX_DIMENSIONS];
12479   gfc_ref *ref;
12480   gfc_array_ref *ar;
12481   gfc_symbol *sym;
12482   int has_pointer;
12483
12484   if (gfc_resolve_expr (var->expr) == FAILURE)
12485     return FAILURE;
12486
12487   ar = NULL;
12488   mpz_init_set_si (offset, 0);
12489   e = var->expr;
12490
12491   if (e->expr_type != EXPR_VARIABLE)
12492     gfc_internal_error ("check_data_variable(): Bad expression");
12493
12494   sym = e->symtree->n.sym;
12495
12496   if (sym->ns->is_block_data && !sym->attr.in_common)
12497     {
12498       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12499                  sym->name, &sym->declared_at);
12500     }
12501
12502   if (e->ref == NULL && sym->as)
12503     {
12504       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12505                  " declaration", sym->name, where);
12506       return FAILURE;
12507     }
12508
12509   has_pointer = sym->attr.pointer;
12510
12511   if (gfc_is_coindexed (e))
12512     {
12513       gfc_error ("DATA element '%s' at %L cannot have a coindex", sym->name,
12514                  where);
12515       return FAILURE;
12516     }
12517
12518   for (ref = e->ref; ref; ref = ref->next)
12519     {
12520       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12521         has_pointer = 1;
12522
12523       if (has_pointer
12524             && ref->type == REF_ARRAY
12525             && ref->u.ar.type != AR_FULL)
12526           {
12527             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12528                         "be a full array", sym->name, where);
12529             return FAILURE;
12530           }
12531     }
12532
12533   if (e->rank == 0 || has_pointer)
12534     {
12535       mpz_init_set_ui (size, 1);
12536       ref = NULL;
12537     }
12538   else
12539     {
12540       ref = e->ref;
12541
12542       /* Find the array section reference.  */
12543       for (ref = e->ref; ref; ref = ref->next)
12544         {
12545           if (ref->type != REF_ARRAY)
12546             continue;
12547           if (ref->u.ar.type == AR_ELEMENT)
12548             continue;
12549           break;
12550         }
12551       gcc_assert (ref);
12552
12553       /* Set marks according to the reference pattern.  */
12554       switch (ref->u.ar.type)
12555         {
12556         case AR_FULL:
12557           mark = AR_FULL;
12558           break;
12559
12560         case AR_SECTION:
12561           ar = &ref->u.ar;
12562           /* Get the start position of array section.  */
12563           gfc_get_section_index (ar, section_index, &offset);
12564           mark = AR_SECTION;
12565           break;
12566
12567         default:
12568           gcc_unreachable ();
12569         }
12570
12571       if (gfc_array_size (e, &size) == FAILURE)
12572         {
12573           gfc_error ("Nonconstant array section at %L in DATA statement",
12574                      &e->where);
12575           mpz_clear (offset);
12576           return FAILURE;
12577         }
12578     }
12579
12580   t = SUCCESS;
12581
12582   while (mpz_cmp_ui (size, 0) > 0)
12583     {
12584       if (next_data_value () == FAILURE)
12585         {
12586           gfc_error ("DATA statement at %L has more variables than values",
12587                      where);
12588           t = FAILURE;
12589           break;
12590         }
12591
12592       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12593       if (t == FAILURE)
12594         break;
12595
12596       /* If we have more than one element left in the repeat count,
12597          and we have more than one element left in the target variable,
12598          then create a range assignment.  */
12599       /* FIXME: Only done for full arrays for now, since array sections
12600          seem tricky.  */
12601       if (mark == AR_FULL && ref && ref->next == NULL
12602           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12603         {
12604           mpz_t range;
12605
12606           if (mpz_cmp (size, values.left) >= 0)
12607             {
12608               mpz_init_set (range, values.left);
12609               mpz_sub (size, size, values.left);
12610               mpz_set_ui (values.left, 0);
12611             }
12612           else
12613             {
12614               mpz_init_set (range, size);
12615               mpz_sub (values.left, values.left, size);
12616               mpz_set_ui (size, 0);
12617             }
12618
12619           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12620                                      offset, &range);
12621
12622           mpz_add (offset, offset, range);
12623           mpz_clear (range);
12624
12625           if (t == FAILURE)
12626             break;
12627         }
12628
12629       /* Assign initial value to symbol.  */
12630       else
12631         {
12632           mpz_sub_ui (values.left, values.left, 1);
12633           mpz_sub_ui (size, size, 1);
12634
12635           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12636                                      offset, NULL);
12637           if (t == FAILURE)
12638             break;
12639
12640           if (mark == AR_FULL)
12641             mpz_add_ui (offset, offset, 1);
12642
12643           /* Modify the array section indexes and recalculate the offset
12644              for next element.  */
12645           else if (mark == AR_SECTION)
12646             gfc_advance_section (section_index, ar, &offset);
12647         }
12648     }
12649
12650   if (mark == AR_SECTION)
12651     {
12652       for (i = 0; i < ar->dimen; i++)
12653         mpz_clear (section_index[i]);
12654     }
12655
12656   mpz_clear (size);
12657   mpz_clear (offset);
12658
12659   return t;
12660 }
12661
12662
12663 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
12664
12665 /* Iterate over a list of elements in a DATA statement.  */
12666
12667 static gfc_try
12668 traverse_data_list (gfc_data_variable *var, locus *where)
12669 {
12670   mpz_t trip;
12671   iterator_stack frame;
12672   gfc_expr *e, *start, *end, *step;
12673   gfc_try retval = SUCCESS;
12674
12675   mpz_init (frame.value);
12676   mpz_init (trip);
12677
12678   start = gfc_copy_expr (var->iter.start);
12679   end = gfc_copy_expr (var->iter.end);
12680   step = gfc_copy_expr (var->iter.step);
12681
12682   if (gfc_simplify_expr (start, 1) == FAILURE
12683       || start->expr_type != EXPR_CONSTANT)
12684     {
12685       gfc_error ("start of implied-do loop at %L could not be "
12686                  "simplified to a constant value", &start->where);
12687       retval = FAILURE;
12688       goto cleanup;
12689     }
12690   if (gfc_simplify_expr (end, 1) == FAILURE
12691       || end->expr_type != EXPR_CONSTANT)
12692     {
12693       gfc_error ("end of implied-do loop at %L could not be "
12694                  "simplified to a constant value", &start->where);
12695       retval = FAILURE;
12696       goto cleanup;
12697     }
12698   if (gfc_simplify_expr (step, 1) == FAILURE
12699       || step->expr_type != EXPR_CONSTANT)
12700     {
12701       gfc_error ("step of implied-do loop at %L could not be "
12702                  "simplified to a constant value", &start->where);
12703       retval = FAILURE;
12704       goto cleanup;
12705     }
12706
12707   mpz_set (trip, end->value.integer);
12708   mpz_sub (trip, trip, start->value.integer);
12709   mpz_add (trip, trip, step->value.integer);
12710
12711   mpz_div (trip, trip, step->value.integer);
12712
12713   mpz_set (frame.value, start->value.integer);
12714
12715   frame.prev = iter_stack;
12716   frame.variable = var->iter.var->symtree;
12717   iter_stack = &frame;
12718
12719   while (mpz_cmp_ui (trip, 0) > 0)
12720     {
12721       if (traverse_data_var (var->list, where) == FAILURE)
12722         {
12723           retval = FAILURE;
12724           goto cleanup;
12725         }
12726
12727       e = gfc_copy_expr (var->expr);
12728       if (gfc_simplify_expr (e, 1) == FAILURE)
12729         {
12730           gfc_free_expr (e);
12731           retval = FAILURE;
12732           goto cleanup;
12733         }
12734
12735       mpz_add (frame.value, frame.value, step->value.integer);
12736
12737       mpz_sub_ui (trip, trip, 1);
12738     }
12739
12740 cleanup:
12741   mpz_clear (frame.value);
12742   mpz_clear (trip);
12743
12744   gfc_free_expr (start);
12745   gfc_free_expr (end);
12746   gfc_free_expr (step);
12747
12748   iter_stack = frame.prev;
12749   return retval;
12750 }
12751
12752
12753 /* Type resolve variables in the variable list of a DATA statement.  */
12754
12755 static gfc_try
12756 traverse_data_var (gfc_data_variable *var, locus *where)
12757 {
12758   gfc_try t;
12759
12760   for (; var; var = var->next)
12761     {
12762       if (var->expr == NULL)
12763         t = traverse_data_list (var, where);
12764       else
12765         t = check_data_variable (var, where);
12766
12767       if (t == FAILURE)
12768         return FAILURE;
12769     }
12770
12771   return SUCCESS;
12772 }
12773
12774
12775 /* Resolve the expressions and iterators associated with a data statement.
12776    This is separate from the assignment checking because data lists should
12777    only be resolved once.  */
12778
12779 static gfc_try
12780 resolve_data_variables (gfc_data_variable *d)
12781 {
12782   for (; d; d = d->next)
12783     {
12784       if (d->list == NULL)
12785         {
12786           if (gfc_resolve_expr (d->expr) == FAILURE)
12787             return FAILURE;
12788         }
12789       else
12790         {
12791           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
12792             return FAILURE;
12793
12794           if (resolve_data_variables (d->list) == FAILURE)
12795             return FAILURE;
12796         }
12797     }
12798
12799   return SUCCESS;
12800 }
12801
12802
12803 /* Resolve a single DATA statement.  We implement this by storing a pointer to
12804    the value list into static variables, and then recursively traversing the
12805    variables list, expanding iterators and such.  */
12806
12807 static void
12808 resolve_data (gfc_data *d)
12809 {
12810
12811   if (resolve_data_variables (d->var) == FAILURE)
12812     return;
12813
12814   values.vnode = d->value;
12815   if (d->value == NULL)
12816     mpz_set_ui (values.left, 0);
12817   else
12818     mpz_set (values.left, d->value->repeat);
12819
12820   if (traverse_data_var (d->var, &d->where) == FAILURE)
12821     return;
12822
12823   /* At this point, we better not have any values left.  */
12824
12825   if (next_data_value () == SUCCESS)
12826     gfc_error ("DATA statement at %L has more values than variables",
12827                &d->where);
12828 }
12829
12830
12831 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
12832    accessed by host or use association, is a dummy argument to a pure function,
12833    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
12834    is storage associated with any such variable, shall not be used in the
12835    following contexts: (clients of this function).  */
12836
12837 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
12838    procedure.  Returns zero if assignment is OK, nonzero if there is a
12839    problem.  */
12840 int
12841 gfc_impure_variable (gfc_symbol *sym)
12842 {
12843   gfc_symbol *proc;
12844   gfc_namespace *ns;
12845
12846   if (sym->attr.use_assoc || sym->attr.in_common)
12847     return 1;
12848
12849   /* Check if the symbol's ns is inside the pure procedure.  */
12850   for (ns = gfc_current_ns; ns; ns = ns->parent)
12851     {
12852       if (ns == sym->ns)
12853         break;
12854       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
12855         return 1;
12856     }
12857
12858   proc = sym->ns->proc_name;
12859   if (sym->attr.dummy && gfc_pure (proc)
12860         && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
12861                 ||
12862              proc->attr.function))
12863     return 1;
12864
12865   /* TODO: Sort out what can be storage associated, if anything, and include
12866      it here.  In principle equivalences should be scanned but it does not
12867      seem to be possible to storage associate an impure variable this way.  */
12868   return 0;
12869 }
12870
12871
12872 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
12873    current namespace is inside a pure procedure.  */
12874
12875 int
12876 gfc_pure (gfc_symbol *sym)
12877 {
12878   symbol_attribute attr;
12879   gfc_namespace *ns;
12880
12881   if (sym == NULL)
12882     {
12883       /* Check if the current namespace or one of its parents
12884         belongs to a pure procedure.  */
12885       for (ns = gfc_current_ns; ns; ns = ns->parent)
12886         {
12887           sym = ns->proc_name;
12888           if (sym == NULL)
12889             return 0;
12890           attr = sym->attr;
12891           if (attr.flavor == FL_PROCEDURE && attr.pure)
12892             return 1;
12893         }
12894       return 0;
12895     }
12896
12897   attr = sym->attr;
12898
12899   return attr.flavor == FL_PROCEDURE && attr.pure;
12900 }
12901
12902
12903 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
12904    checks if the current namespace is implicitly pure.  Note that this
12905    function returns false for a PURE procedure.  */
12906
12907 int
12908 gfc_implicit_pure (gfc_symbol *sym)
12909 {
12910   symbol_attribute attr;
12911
12912   if (sym == NULL)
12913     {
12914       /* Check if the current namespace is implicit_pure.  */
12915       sym = gfc_current_ns->proc_name;
12916       if (sym == NULL)
12917         return 0;
12918       attr = sym->attr;
12919       if (attr.flavor == FL_PROCEDURE
12920             && attr.implicit_pure && !attr.pure)
12921         return 1;
12922       return 0;
12923     }
12924
12925   attr = sym->attr;
12926
12927   return attr.flavor == FL_PROCEDURE && attr.implicit_pure && !attr.pure;
12928 }
12929
12930
12931 /* Test whether the current procedure is elemental or not.  */
12932
12933 int
12934 gfc_elemental (gfc_symbol *sym)
12935 {
12936   symbol_attribute attr;
12937
12938   if (sym == NULL)
12939     sym = gfc_current_ns->proc_name;
12940   if (sym == NULL)
12941     return 0;
12942   attr = sym->attr;
12943
12944   return attr.flavor == FL_PROCEDURE && attr.elemental;
12945 }
12946
12947
12948 /* Warn about unused labels.  */
12949
12950 static void
12951 warn_unused_fortran_label (gfc_st_label *label)
12952 {
12953   if (label == NULL)
12954     return;
12955
12956   warn_unused_fortran_label (label->left);
12957
12958   if (label->defined == ST_LABEL_UNKNOWN)
12959     return;
12960
12961   switch (label->referenced)
12962     {
12963     case ST_LABEL_UNKNOWN:
12964       gfc_warning ("Label %d at %L defined but not used", label->value,
12965                    &label->where);
12966       break;
12967
12968     case ST_LABEL_BAD_TARGET:
12969       gfc_warning ("Label %d at %L defined but cannot be used",
12970                    label->value, &label->where);
12971       break;
12972
12973     default:
12974       break;
12975     }
12976
12977   warn_unused_fortran_label (label->right);
12978 }
12979
12980
12981 /* Returns the sequence type of a symbol or sequence.  */
12982
12983 static seq_type
12984 sequence_type (gfc_typespec ts)
12985 {
12986   seq_type result;
12987   gfc_component *c;
12988
12989   switch (ts.type)
12990   {
12991     case BT_DERIVED:
12992
12993       if (ts.u.derived->components == NULL)
12994         return SEQ_NONDEFAULT;
12995
12996       result = sequence_type (ts.u.derived->components->ts);
12997       for (c = ts.u.derived->components->next; c; c = c->next)
12998         if (sequence_type (c->ts) != result)
12999           return SEQ_MIXED;
13000
13001       return result;
13002
13003     case BT_CHARACTER:
13004       if (ts.kind != gfc_default_character_kind)
13005           return SEQ_NONDEFAULT;
13006
13007       return SEQ_CHARACTER;
13008
13009     case BT_INTEGER:
13010       if (ts.kind != gfc_default_integer_kind)
13011           return SEQ_NONDEFAULT;
13012
13013       return SEQ_NUMERIC;
13014
13015     case BT_REAL:
13016       if (!(ts.kind == gfc_default_real_kind
13017             || ts.kind == gfc_default_double_kind))
13018           return SEQ_NONDEFAULT;
13019
13020       return SEQ_NUMERIC;
13021
13022     case BT_COMPLEX:
13023       if (ts.kind != gfc_default_complex_kind)
13024           return SEQ_NONDEFAULT;
13025
13026       return SEQ_NUMERIC;
13027
13028     case BT_LOGICAL:
13029       if (ts.kind != gfc_default_logical_kind)
13030           return SEQ_NONDEFAULT;
13031
13032       return SEQ_NUMERIC;
13033
13034     default:
13035       return SEQ_NONDEFAULT;
13036   }
13037 }
13038
13039
13040 /* Resolve derived type EQUIVALENCE object.  */
13041
13042 static gfc_try
13043 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
13044 {
13045   gfc_component *c = derived->components;
13046
13047   if (!derived)
13048     return SUCCESS;
13049
13050   /* Shall not be an object of nonsequence derived type.  */
13051   if (!derived->attr.sequence)
13052     {
13053       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
13054                  "attribute to be an EQUIVALENCE object", sym->name,
13055                  &e->where);
13056       return FAILURE;
13057     }
13058
13059   /* Shall not have allocatable components.  */
13060   if (derived->attr.alloc_comp)
13061     {
13062       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
13063                  "components to be an EQUIVALENCE object",sym->name,
13064                  &e->where);
13065       return FAILURE;
13066     }
13067
13068   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
13069     {
13070       gfc_error ("Derived type variable '%s' at %L with default "
13071                  "initialization cannot be in EQUIVALENCE with a variable "
13072                  "in COMMON", sym->name, &e->where);
13073       return FAILURE;
13074     }
13075
13076   for (; c ; c = c->next)
13077     {
13078       if (c->ts.type == BT_DERIVED
13079           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
13080         return FAILURE;
13081
13082       /* Shall not be an object of sequence derived type containing a pointer
13083          in the structure.  */
13084       if (c->attr.pointer)
13085         {
13086           gfc_error ("Derived type variable '%s' at %L with pointer "
13087                      "component(s) cannot be an EQUIVALENCE object",
13088                      sym->name, &e->where);
13089           return FAILURE;
13090         }
13091     }
13092   return SUCCESS;
13093 }
13094
13095
13096 /* Resolve equivalence object. 
13097    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
13098    an allocatable array, an object of nonsequence derived type, an object of
13099    sequence derived type containing a pointer at any level of component
13100    selection, an automatic object, a function name, an entry name, a result
13101    name, a named constant, a structure component, or a subobject of any of
13102    the preceding objects.  A substring shall not have length zero.  A
13103    derived type shall not have components with default initialization nor
13104    shall two objects of an equivalence group be initialized.
13105    Either all or none of the objects shall have an protected attribute.
13106    The simple constraints are done in symbol.c(check_conflict) and the rest
13107    are implemented here.  */
13108
13109 static void
13110 resolve_equivalence (gfc_equiv *eq)
13111 {
13112   gfc_symbol *sym;
13113   gfc_symbol *first_sym;
13114   gfc_expr *e;
13115   gfc_ref *r;
13116   locus *last_where = NULL;
13117   seq_type eq_type, last_eq_type;
13118   gfc_typespec *last_ts;
13119   int object, cnt_protected;
13120   const char *msg;
13121
13122   last_ts = &eq->expr->symtree->n.sym->ts;
13123
13124   first_sym = eq->expr->symtree->n.sym;
13125
13126   cnt_protected = 0;
13127
13128   for (object = 1; eq; eq = eq->eq, object++)
13129     {
13130       e = eq->expr;
13131
13132       e->ts = e->symtree->n.sym->ts;
13133       /* match_varspec might not know yet if it is seeing
13134          array reference or substring reference, as it doesn't
13135          know the types.  */
13136       if (e->ref && e->ref->type == REF_ARRAY)
13137         {
13138           gfc_ref *ref = e->ref;
13139           sym = e->symtree->n.sym;
13140
13141           if (sym->attr.dimension)
13142             {
13143               ref->u.ar.as = sym->as;
13144               ref = ref->next;
13145             }
13146
13147           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
13148           if (e->ts.type == BT_CHARACTER
13149               && ref
13150               && ref->type == REF_ARRAY
13151               && ref->u.ar.dimen == 1
13152               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
13153               && ref->u.ar.stride[0] == NULL)
13154             {
13155               gfc_expr *start = ref->u.ar.start[0];
13156               gfc_expr *end = ref->u.ar.end[0];
13157               void *mem = NULL;
13158
13159               /* Optimize away the (:) reference.  */
13160               if (start == NULL && end == NULL)
13161                 {
13162                   if (e->ref == ref)
13163                     e->ref = ref->next;
13164                   else
13165                     e->ref->next = ref->next;
13166                   mem = ref;
13167                 }
13168               else
13169                 {
13170                   ref->type = REF_SUBSTRING;
13171                   if (start == NULL)
13172                     start = gfc_get_int_expr (gfc_default_integer_kind,
13173                                               NULL, 1);
13174                   ref->u.ss.start = start;
13175                   if (end == NULL && e->ts.u.cl)
13176                     end = gfc_copy_expr (e->ts.u.cl->length);
13177                   ref->u.ss.end = end;
13178                   ref->u.ss.length = e->ts.u.cl;
13179                   e->ts.u.cl = NULL;
13180                 }
13181               ref = ref->next;
13182               free (mem);
13183             }
13184
13185           /* Any further ref is an error.  */
13186           if (ref)
13187             {
13188               gcc_assert (ref->type == REF_ARRAY);
13189               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
13190                          &ref->u.ar.where);
13191               continue;
13192             }
13193         }
13194
13195       if (gfc_resolve_expr (e) == FAILURE)
13196         continue;
13197
13198       sym = e->symtree->n.sym;
13199
13200       if (sym->attr.is_protected)
13201         cnt_protected++;
13202       if (cnt_protected > 0 && cnt_protected != object)
13203         {
13204               gfc_error ("Either all or none of the objects in the "
13205                          "EQUIVALENCE set at %L shall have the "
13206                          "PROTECTED attribute",
13207                          &e->where);
13208               break;
13209         }
13210
13211       /* Shall not equivalence common block variables in a PURE procedure.  */
13212       if (sym->ns->proc_name
13213           && sym->ns->proc_name->attr.pure
13214           && sym->attr.in_common)
13215         {
13216           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
13217                      "object in the pure procedure '%s'",
13218                      sym->name, &e->where, sym->ns->proc_name->name);
13219           break;
13220         }
13221
13222       /* Shall not be a named constant.  */
13223       if (e->expr_type == EXPR_CONSTANT)
13224         {
13225           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
13226                      "object", sym->name, &e->where);
13227           continue;
13228         }
13229
13230       if (e->ts.type == BT_DERIVED
13231           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
13232         continue;
13233
13234       /* Check that the types correspond correctly:
13235          Note 5.28:
13236          A numeric sequence structure may be equivalenced to another sequence
13237          structure, an object of default integer type, default real type, double
13238          precision real type, default logical type such that components of the
13239          structure ultimately only become associated to objects of the same
13240          kind. A character sequence structure may be equivalenced to an object
13241          of default character kind or another character sequence structure.
13242          Other objects may be equivalenced only to objects of the same type and
13243          kind parameters.  */
13244
13245       /* Identical types are unconditionally OK.  */
13246       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
13247         goto identical_types;
13248
13249       last_eq_type = sequence_type (*last_ts);
13250       eq_type = sequence_type (sym->ts);
13251
13252       /* Since the pair of objects is not of the same type, mixed or
13253          non-default sequences can be rejected.  */
13254
13255       msg = "Sequence %s with mixed components in EQUIVALENCE "
13256             "statement at %L with different type objects";
13257       if ((object ==2
13258            && last_eq_type == SEQ_MIXED
13259            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
13260               == FAILURE)
13261           || (eq_type == SEQ_MIXED
13262               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13263                                  &e->where) == FAILURE))
13264         continue;
13265
13266       msg = "Non-default type object or sequence %s in EQUIVALENCE "
13267             "statement at %L with objects of different type";
13268       if ((object ==2
13269            && last_eq_type == SEQ_NONDEFAULT
13270            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
13271                               last_where) == FAILURE)
13272           || (eq_type == SEQ_NONDEFAULT
13273               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13274                                  &e->where) == FAILURE))
13275         continue;
13276
13277       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13278            "EQUIVALENCE statement at %L";
13279       if (last_eq_type == SEQ_CHARACTER
13280           && eq_type != SEQ_CHARACTER
13281           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13282                              &e->where) == FAILURE)
13283                 continue;
13284
13285       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13286            "EQUIVALENCE statement at %L";
13287       if (last_eq_type == SEQ_NUMERIC
13288           && eq_type != SEQ_NUMERIC
13289           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13290                              &e->where) == FAILURE)
13291                 continue;
13292
13293   identical_types:
13294       last_ts =&sym->ts;
13295       last_where = &e->where;
13296
13297       if (!e->ref)
13298         continue;
13299
13300       /* Shall not be an automatic array.  */
13301       if (e->ref->type == REF_ARRAY
13302           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13303         {
13304           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13305                      "an EQUIVALENCE object", sym->name, &e->where);
13306           continue;
13307         }
13308
13309       r = e->ref;
13310       while (r)
13311         {
13312           /* Shall not be a structure component.  */
13313           if (r->type == REF_COMPONENT)
13314             {
13315               gfc_error ("Structure component '%s' at %L cannot be an "
13316                          "EQUIVALENCE object",
13317                          r->u.c.component->name, &e->where);
13318               break;
13319             }
13320
13321           /* A substring shall not have length zero.  */
13322           if (r->type == REF_SUBSTRING)
13323             {
13324               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13325                 {
13326                   gfc_error ("Substring at %L has length zero",
13327                              &r->u.ss.start->where);
13328                   break;
13329                 }
13330             }
13331           r = r->next;
13332         }
13333     }
13334 }
13335
13336
13337 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13338
13339 static void
13340 resolve_fntype (gfc_namespace *ns)
13341 {
13342   gfc_entry_list *el;
13343   gfc_symbol *sym;
13344
13345   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13346     return;
13347
13348   /* If there are any entries, ns->proc_name is the entry master
13349      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13350   if (ns->entries)
13351     sym = ns->entries->sym;
13352   else
13353     sym = ns->proc_name;
13354   if (sym->result == sym
13355       && sym->ts.type == BT_UNKNOWN
13356       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13357       && !sym->attr.untyped)
13358     {
13359       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13360                  sym->name, &sym->declared_at);
13361       sym->attr.untyped = 1;
13362     }
13363
13364   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13365       && !sym->attr.contained
13366       && !gfc_check_symbol_access (sym->ts.u.derived)
13367       && gfc_check_symbol_access (sym))
13368     {
13369       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13370                       "%L of PRIVATE type '%s'", sym->name,
13371                       &sym->declared_at, sym->ts.u.derived->name);
13372     }
13373
13374     if (ns->entries)
13375     for (el = ns->entries->next; el; el = el->next)
13376       {
13377         if (el->sym->result == el->sym
13378             && el->sym->ts.type == BT_UNKNOWN
13379             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13380             && !el->sym->attr.untyped)
13381           {
13382             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13383                        el->sym->name, &el->sym->declared_at);
13384             el->sym->attr.untyped = 1;
13385           }
13386       }
13387 }
13388
13389
13390 /* 12.3.2.1.1 Defined operators.  */
13391
13392 static gfc_try
13393 check_uop_procedure (gfc_symbol *sym, locus where)
13394 {
13395   gfc_formal_arglist *formal;
13396
13397   if (!sym->attr.function)
13398     {
13399       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13400                  sym->name, &where);
13401       return FAILURE;
13402     }
13403
13404   if (sym->ts.type == BT_CHARACTER
13405       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13406       && !(sym->result && sym->result->ts.u.cl
13407            && sym->result->ts.u.cl->length))
13408     {
13409       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13410                  "character length", sym->name, &where);
13411       return FAILURE;
13412     }
13413
13414   formal = sym->formal;
13415   if (!formal || !formal->sym)
13416     {
13417       gfc_error ("User operator procedure '%s' at %L must have at least "
13418                  "one argument", sym->name, &where);
13419       return FAILURE;
13420     }
13421
13422   if (formal->sym->attr.intent != INTENT_IN)
13423     {
13424       gfc_error ("First argument of operator interface at %L must be "
13425                  "INTENT(IN)", &where);
13426       return FAILURE;
13427     }
13428
13429   if (formal->sym->attr.optional)
13430     {
13431       gfc_error ("First argument of operator interface at %L cannot be "
13432                  "optional", &where);
13433       return FAILURE;
13434     }
13435
13436   formal = formal->next;
13437   if (!formal || !formal->sym)
13438     return SUCCESS;
13439
13440   if (formal->sym->attr.intent != INTENT_IN)
13441     {
13442       gfc_error ("Second argument of operator interface at %L must be "
13443                  "INTENT(IN)", &where);
13444       return FAILURE;
13445     }
13446
13447   if (formal->sym->attr.optional)
13448     {
13449       gfc_error ("Second argument of operator interface at %L cannot be "
13450                  "optional", &where);
13451       return FAILURE;
13452     }
13453
13454   if (formal->next)
13455     {
13456       gfc_error ("Operator interface at %L must have, at most, two "
13457                  "arguments", &where);
13458       return FAILURE;
13459     }
13460
13461   return SUCCESS;
13462 }
13463
13464 static void
13465 gfc_resolve_uops (gfc_symtree *symtree)
13466 {
13467   gfc_interface *itr;
13468
13469   if (symtree == NULL)
13470     return;
13471
13472   gfc_resolve_uops (symtree->left);
13473   gfc_resolve_uops (symtree->right);
13474
13475   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13476     check_uop_procedure (itr->sym, itr->sym->declared_at);
13477 }
13478
13479
13480 /* Examine all of the expressions associated with a program unit,
13481    assign types to all intermediate expressions, make sure that all
13482    assignments are to compatible types and figure out which names
13483    refer to which functions or subroutines.  It doesn't check code
13484    block, which is handled by resolve_code.  */
13485
13486 static void
13487 resolve_types (gfc_namespace *ns)
13488 {
13489   gfc_namespace *n;
13490   gfc_charlen *cl;
13491   gfc_data *d;
13492   gfc_equiv *eq;
13493   gfc_namespace* old_ns = gfc_current_ns;
13494
13495   /* Check that all IMPLICIT types are ok.  */
13496   if (!ns->seen_implicit_none)
13497     {
13498       unsigned letter;
13499       for (letter = 0; letter != GFC_LETTERS; ++letter)
13500         if (ns->set_flag[letter]
13501             && resolve_typespec_used (&ns->default_type[letter],
13502                                       &ns->implicit_loc[letter],
13503                                       NULL) == FAILURE)
13504           return;
13505     }
13506
13507   gfc_current_ns = ns;
13508
13509   resolve_entries (ns);
13510
13511   resolve_common_vars (ns->blank_common.head, false);
13512   resolve_common_blocks (ns->common_root);
13513
13514   resolve_contained_functions (ns);
13515
13516   if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE
13517       && ns->proc_name->attr.if_source == IFSRC_IFBODY)
13518     resolve_formal_arglist (ns->proc_name);
13519
13520   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13521
13522   for (cl = ns->cl_list; cl; cl = cl->next)
13523     resolve_charlen (cl);
13524
13525   gfc_traverse_ns (ns, resolve_symbol);
13526
13527   resolve_fntype (ns);
13528
13529   for (n = ns->contained; n; n = n->sibling)
13530     {
13531       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13532         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13533                    "also be PURE", n->proc_name->name,
13534                    &n->proc_name->declared_at);
13535
13536       resolve_types (n);
13537     }
13538
13539   forall_flag = 0;
13540   gfc_check_interfaces (ns);
13541
13542   gfc_traverse_ns (ns, resolve_values);
13543
13544   if (ns->save_all)
13545     gfc_save_all (ns);
13546
13547   iter_stack = NULL;
13548   for (d = ns->data; d; d = d->next)
13549     resolve_data (d);
13550
13551   iter_stack = NULL;
13552   gfc_traverse_ns (ns, gfc_formalize_init_value);
13553
13554   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13555
13556   if (ns->common_root != NULL)
13557     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13558
13559   for (eq = ns->equiv; eq; eq = eq->next)
13560     resolve_equivalence (eq);
13561
13562   /* Warn about unused labels.  */
13563   if (warn_unused_label)
13564     warn_unused_fortran_label (ns->st_labels);
13565
13566   gfc_resolve_uops (ns->uop_root);
13567
13568   gfc_current_ns = old_ns;
13569 }
13570
13571
13572 /* Call resolve_code recursively.  */
13573
13574 static void
13575 resolve_codes (gfc_namespace *ns)
13576 {
13577   gfc_namespace *n;
13578   bitmap_obstack old_obstack;
13579
13580   if (ns->resolved == 1)
13581     return;
13582
13583   for (n = ns->contained; n; n = n->sibling)
13584     resolve_codes (n);
13585
13586   gfc_current_ns = ns;
13587
13588   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13589   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13590     cs_base = NULL;
13591
13592   /* Set to an out of range value.  */
13593   current_entry_id = -1;
13594
13595   old_obstack = labels_obstack;
13596   bitmap_obstack_initialize (&labels_obstack);
13597
13598   resolve_code (ns->code, ns);
13599
13600   bitmap_obstack_release (&labels_obstack);
13601   labels_obstack = old_obstack;
13602 }
13603
13604
13605 /* This function is called after a complete program unit has been compiled.
13606    Its purpose is to examine all of the expressions associated with a program
13607    unit, assign types to all intermediate expressions, make sure that all
13608    assignments are to compatible types and figure out which names refer to
13609    which functions or subroutines.  */
13610
13611 void
13612 gfc_resolve (gfc_namespace *ns)
13613 {
13614   gfc_namespace *old_ns;
13615   code_stack *old_cs_base;
13616
13617   if (ns->resolved)
13618     return;
13619
13620   ns->resolved = -1;
13621   old_ns = gfc_current_ns;
13622   old_cs_base = cs_base;
13623
13624   resolve_types (ns);
13625   resolve_codes (ns);
13626
13627   gfc_current_ns = old_ns;
13628   cs_base = old_cs_base;
13629   ns->resolved = 1;
13630
13631   gfc_run_passes (ns);
13632 }