OSDN Git Service

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