OSDN Git Service

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