OSDN Git Service

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