OSDN Git Service

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