OSDN Git Service

Daily bump.
[pf3gnuchains/gcc-fork.git] / gcc / fortran / resolve.c
1 /* Perform type resolution on the various structures.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
3    2010, 2011, 2012
4    Free Software Foundation, Inc.
5    Contributed by Andy Vaught
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "flags.h"
26 #include "gfortran.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "arith.h"  /* For gfc_compare_expr().  */
30 #include "dependency.h"
31 #include "data.h"
32 #include "target-memory.h" /* for gfc_simplify_transfer */
33 #include "constructor.h"
34
35 /* Types used in equivalence statements.  */
36
37 typedef enum seq_type
38 {
39   SEQ_NONDEFAULT, SEQ_NUMERIC, SEQ_CHARACTER, SEQ_MIXED
40 }
41 seq_type;
42
43 /* Stack to keep track of the nesting of blocks as we move through the
44    code.  See resolve_branch() and resolve_code().  */
45
46 typedef struct code_stack
47 {
48   struct gfc_code *head, *current;
49   struct code_stack *prev;
50
51   /* This bitmap keeps track of the targets valid for a branch from
52      inside this block except for END {IF|SELECT}s of enclosing
53      blocks.  */
54   bitmap reachable_labels;
55 }
56 code_stack;
57
58 static code_stack *cs_base = NULL;
59
60
61 /* Nonzero if we're inside a FORALL or DO CONCURRENT block.  */
62
63 static int forall_flag;
64 static int do_concurrent_flag;
65
66 /* Nonzero if we're inside a OpenMP WORKSHARE or PARALLEL WORKSHARE block.  */
67
68 static int omp_workshare_flag;
69
70 /* Nonzero if we are processing a formal arglist. The corresponding function
71    resets the flag each time that it is read.  */
72 static int formal_arg_flag = 0;
73
74 /* True if we are resolving a specification expression.  */
75 static int specification_expr = 0;
76
77 /* The id of the last entry seen.  */
78 static int current_entry_id;
79
80 /* We use bitmaps to determine if a branch target is valid.  */
81 static bitmap_obstack labels_obstack;
82
83 /* True when simplifying a EXPR_VARIABLE argument to an inquiry function.  */
84 static bool inquiry_argument = false;
85
86 int
87 gfc_is_formal_arg (void)
88 {
89   return formal_arg_flag;
90 }
91
92 /* Is the symbol host associated?  */
93 static bool
94 is_sym_host_assoc (gfc_symbol *sym, gfc_namespace *ns)
95 {
96   for (ns = ns->parent; ns; ns = ns->parent)
97     {
98       if (sym->ns == ns)
99         return true;
100     }
101
102   return false;
103 }
104
105 /* Ensure a typespec used is valid; for instance, TYPE(t) is invalid if t is
106    an ABSTRACT derived-type.  If where is not NULL, an error message with that
107    locus is printed, optionally using name.  */
108
109 static gfc_try
110 resolve_typespec_used (gfc_typespec* ts, locus* where, const char* name)
111 {
112   if (ts->type == BT_DERIVED && ts->u.derived->attr.abstract)
113     {
114       if (where)
115         {
116           if (name)
117             gfc_error ("'%s' at %L is of the ABSTRACT type '%s'",
118                        name, where, ts->u.derived->name);
119           else
120             gfc_error ("ABSTRACT type '%s' used at %L",
121                        ts->u.derived->name, where);
122         }
123
124       return FAILURE;
125     }
126
127   return SUCCESS;
128 }
129
130
131 static void resolve_symbol (gfc_symbol *sym);
132 static gfc_try resolve_intrinsic (gfc_symbol *sym, locus *loc);
133
134
135 /* Resolve the interface for a PROCEDURE declaration or procedure pointer.  */
136
137 static gfc_try
138 resolve_procedure_interface (gfc_symbol *sym)
139 {
140   if (sym->ts.interface == sym)
141     {
142       gfc_error ("PROCEDURE '%s' at %L may not be used as its own interface",
143                  sym->name, &sym->declared_at);
144       return FAILURE;
145     }
146   if (sym->ts.interface->attr.procedure)
147     {
148       gfc_error ("Interface '%s', used by procedure '%s' at %L, is declared "
149                  "in a later PROCEDURE statement", sym->ts.interface->name,
150                  sym->name, &sym->declared_at);
151       return FAILURE;
152     }
153
154   /* Get the attributes from the interface (now resolved).  */
155   if (sym->ts.interface->attr.if_source || sym->ts.interface->attr.intrinsic)
156     {
157       gfc_symbol *ifc = sym->ts.interface;
158       resolve_symbol (ifc);
159
160       if (ifc->attr.intrinsic)
161         resolve_intrinsic (ifc, &ifc->declared_at);
162
163       if (ifc->result)
164         {
165           sym->ts = ifc->result->ts;
166           sym->result = sym;
167         }
168       else
169         sym->ts = ifc->ts;
170       sym->ts.interface = ifc;
171       sym->attr.function = ifc->attr.function;
172       sym->attr.subroutine = ifc->attr.subroutine;
173       gfc_copy_formal_args (sym, ifc);
174
175       sym->attr.allocatable = ifc->attr.allocatable;
176       sym->attr.pointer = ifc->attr.pointer;
177       sym->attr.pure = ifc->attr.pure;
178       sym->attr.elemental = ifc->attr.elemental;
179       sym->attr.dimension = ifc->attr.dimension;
180       sym->attr.contiguous = ifc->attr.contiguous;
181       sym->attr.recursive = ifc->attr.recursive;
182       sym->attr.always_explicit = ifc->attr.always_explicit;
183       sym->attr.ext_attr |= ifc->attr.ext_attr;
184       sym->attr.is_bind_c = ifc->attr.is_bind_c;
185       /* Copy array spec.  */
186       sym->as = gfc_copy_array_spec (ifc->as);
187       if (sym->as)
188         {
189           int i;
190           for (i = 0; i < sym->as->rank; i++)
191             {
192               gfc_expr_replace_symbols (sym->as->lower[i], sym);
193               gfc_expr_replace_symbols (sym->as->upper[i], sym);
194             }
195         }
196       /* Copy char length.  */
197       if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
198         {
199           sym->ts.u.cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
200           gfc_expr_replace_symbols (sym->ts.u.cl->length, sym);
201           if (sym->ts.u.cl->length && !sym->ts.u.cl->resolved
202               && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
203             return FAILURE;
204         }
205     }
206   else if (sym->ts.interface->name[0] != '\0')
207     {
208       gfc_error ("Interface '%s' of procedure '%s' at %L must be explicit",
209                  sym->ts.interface->name, sym->name, &sym->declared_at);
210       return FAILURE;
211     }
212
213   return SUCCESS;
214 }
215
216
217 /* Resolve types of formal argument lists.  These have to be done early so that
218    the formal argument lists of module procedures can be copied to the
219    containing module before the individual procedures are resolved
220    individually.  We also resolve argument lists of procedures in interface
221    blocks because they are self-contained scoping units.
222
223    Since a dummy argument cannot be a non-dummy procedure, the only
224    resort left for untyped names are the IMPLICIT types.  */
225
226 static void
227 resolve_formal_arglist (gfc_symbol *proc)
228 {
229   gfc_formal_arglist *f;
230   gfc_symbol *sym;
231   int i;
232
233   if (proc->result != NULL)
234     sym = proc->result;
235   else
236     sym = proc;
237
238   if (gfc_elemental (proc)
239       || sym->attr.pointer || sym->attr.allocatable
240       || (sym->as && sym->as->rank > 0))
241     {
242       proc->attr.always_explicit = 1;
243       sym->attr.always_explicit = 1;
244     }
245
246   formal_arg_flag = 1;
247
248   for (f = proc->formal; f; f = f->next)
249     {
250       sym = f->sym;
251
252       if (sym == NULL)
253         {
254           /* Alternate return placeholder.  */
255           if (gfc_elemental (proc))
256             gfc_error ("Alternate return specifier in elemental subroutine "
257                        "'%s' at %L is not allowed", proc->name,
258                        &proc->declared_at);
259           if (proc->attr.function)
260             gfc_error ("Alternate return specifier in function "
261                        "'%s' at %L is not allowed", proc->name,
262                        &proc->declared_at);
263           continue;
264         }
265       else if (sym->attr.procedure && sym->ts.interface
266                && sym->attr.if_source != IFSRC_DECL)
267         resolve_procedure_interface (sym);
268
269       if (sym->attr.if_source != IFSRC_UNKNOWN)
270         resolve_formal_arglist (sym);
271
272       if (sym->attr.subroutine || sym->attr.external)
273         {
274           if (sym->attr.flavor == FL_UNKNOWN)
275             gfc_add_flavor (&sym->attr, FL_PROCEDURE, sym->name, &sym->declared_at);
276         }
277       else
278         {
279           if (sym->ts.type == BT_UNKNOWN && !proc->attr.intrinsic
280               && (!sym->attr.function || sym->result == sym))
281             gfc_set_default_type (sym, 1, sym->ns);
282         }
283
284       gfc_resolve_array_spec (sym->as, 0);
285
286       /* We can't tell if an array with dimension (:) is assumed or deferred
287          shape until we know if it has the pointer or allocatable attributes.
288       */
289       if (sym->as && sym->as->rank > 0 && sym->as->type == AS_DEFERRED
290           && !(sym->attr.pointer || sym->attr.allocatable)
291           && sym->attr.flavor != FL_PROCEDURE)
292         {
293           sym->as->type = AS_ASSUMED_SHAPE;
294           for (i = 0; i < sym->as->rank; i++)
295             sym->as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind,
296                                                   NULL, 1);
297         }
298
299       if ((sym->as && sym->as->rank > 0 && sym->as->type == AS_ASSUMED_SHAPE)
300           || sym->attr.pointer || sym->attr.allocatable || sym->attr.target
301           || sym->attr.optional)
302         {
303           proc->attr.always_explicit = 1;
304           if (proc->result)
305             proc->result->attr.always_explicit = 1;
306         }
307
308       /* If the flavor is unknown at this point, it has to be a variable.
309          A procedure specification would have already set the type.  */
310
311       if (sym->attr.flavor == FL_UNKNOWN)
312         gfc_add_flavor (&sym->attr, FL_VARIABLE, sym->name, &sym->declared_at);
313
314       if (gfc_pure (proc))
315         {
316           if (sym->attr.flavor == FL_PROCEDURE)
317             {
318               /* F08:C1279.  */
319               if (!gfc_pure (sym))
320                 {
321                   gfc_error ("Dummy procedure '%s' of PURE procedure at %L must "
322                             "also be PURE", sym->name, &sym->declared_at);
323                   continue;
324                 }
325             }
326           else if (!sym->attr.pointer)
327             {
328               if (proc->attr.function && sym->attr.intent != INTENT_IN)
329                 {
330                   if (sym->attr.value)
331                     gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s'"
332                                     " of pure function '%s' at %L with VALUE "
333                                     "attribute but without INTENT(IN)",
334                                     sym->name, proc->name, &sym->declared_at);
335                   else
336                     gfc_error ("Argument '%s' of pure function '%s' at %L must "
337                                "be INTENT(IN) or VALUE", sym->name, proc->name,
338                                &sym->declared_at);
339                 }
340
341               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN)
342                 {
343                   if (sym->attr.value)
344                     gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Argument '%s'"
345                                     " of pure subroutine '%s' at %L with VALUE "
346                                     "attribute but without INTENT", sym->name,
347                                     proc->name, &sym->declared_at);
348                   else
349                     gfc_error ("Argument '%s' of pure subroutine '%s' at %L "
350                                "must have its INTENT specified or have the "
351                                "VALUE attribute", sym->name, proc->name,
352                                &sym->declared_at);
353                 }
354             }
355         }
356
357       if (proc->attr.implicit_pure)
358         {
359           if (sym->attr.flavor == FL_PROCEDURE)
360             {
361               if (!gfc_pure(sym))
362                 proc->attr.implicit_pure = 0;
363             }
364           else if (!sym->attr.pointer)
365             {
366               if (proc->attr.function && sym->attr.intent != INTENT_IN
367                   && !sym->value)
368                 proc->attr.implicit_pure = 0;
369
370               if (proc->attr.subroutine && sym->attr.intent == INTENT_UNKNOWN
371                   && !sym->value)
372                 proc->attr.implicit_pure = 0;
373             }
374         }
375
376       if (gfc_elemental (proc))
377         {
378           /* F08:C1289.  */
379           if (sym->attr.codimension
380               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
381                   && CLASS_DATA (sym)->attr.codimension))
382             {
383               gfc_error ("Coarray dummy argument '%s' at %L to elemental "
384                          "procedure", sym->name, &sym->declared_at);
385               continue;
386             }
387
388           if (sym->as || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
389                           && CLASS_DATA (sym)->as))
390             {
391               gfc_error ("Argument '%s' of elemental procedure at %L must "
392                          "be scalar", sym->name, &sym->declared_at);
393               continue;
394             }
395
396           if (sym->attr.allocatable
397               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
398                   && CLASS_DATA (sym)->attr.allocatable))
399             {
400               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
401                          "have the ALLOCATABLE attribute", sym->name,
402                          &sym->declared_at);
403               continue;
404             }
405
406           if (sym->attr.pointer
407               || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
408                   && CLASS_DATA (sym)->attr.class_pointer))
409             {
410               gfc_error ("Argument '%s' of elemental procedure at %L cannot "
411                          "have the POINTER attribute", sym->name,
412                          &sym->declared_at);
413               continue;
414             }
415
416           if (sym->attr.flavor == FL_PROCEDURE)
417             {
418               gfc_error ("Dummy procedure '%s' not allowed in elemental "
419                          "procedure '%s' at %L", sym->name, proc->name,
420                          &sym->declared_at);
421               continue;
422             }
423
424           if (sym->attr.intent == INTENT_UNKNOWN)
425             {
426               gfc_error ("Argument '%s' of elemental procedure '%s' at %L must "
427                          "have its INTENT specified", sym->name, proc->name,
428                          &sym->declared_at);
429               continue;
430             }
431         }
432
433       /* Each dummy shall be specified to be scalar.  */
434       if (proc->attr.proc == PROC_ST_FUNCTION)
435         {
436           if (sym->as != NULL)
437             {
438               gfc_error ("Argument '%s' of statement function at %L must "
439                          "be scalar", sym->name, &sym->declared_at);
440               continue;
441             }
442
443           if (sym->ts.type == BT_CHARACTER)
444             {
445               gfc_charlen *cl = sym->ts.u.cl;
446               if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
447                 {
448                   gfc_error ("Character-valued argument '%s' of statement "
449                              "function at %L must have constant length",
450                              sym->name, &sym->declared_at);
451                   continue;
452                 }
453             }
454         }
455     }
456   formal_arg_flag = 0;
457 }
458
459
460 /* Work function called when searching for symbols that have argument lists
461    associated with them.  */
462
463 static void
464 find_arglists (gfc_symbol *sym)
465 {
466   if (sym->attr.if_source == IFSRC_UNKNOWN || sym->ns != gfc_current_ns
467       || sym->attr.flavor == FL_DERIVED)
468     return;
469
470   resolve_formal_arglist (sym);
471 }
472
473
474 /* Given a namespace, resolve all formal argument lists within the namespace.
475  */
476
477 static void
478 resolve_formal_arglists (gfc_namespace *ns)
479 {
480   if (ns == NULL)
481     return;
482
483   gfc_traverse_ns (ns, find_arglists);
484 }
485
486
487 static void
488 resolve_contained_fntype (gfc_symbol *sym, gfc_namespace *ns)
489 {
490   gfc_try t;
491
492   /* If this namespace is not a function or an entry master function,
493      ignore it.  */
494   if (! sym || !(sym->attr.function || sym->attr.flavor == FL_VARIABLE)
495       || sym->attr.entry_master)
496     return;
497
498   /* Try to find out of what the return type is.  */
499   if (sym->result->ts.type == BT_UNKNOWN && sym->result->ts.interface == NULL)
500     {
501       t = gfc_set_default_type (sym->result, 0, ns);
502
503       if (t == FAILURE && !sym->result->attr.untyped)
504         {
505           if (sym->result == sym)
506             gfc_error ("Contained function '%s' at %L has no IMPLICIT type",
507                        sym->name, &sym->declared_at);
508           else if (!sym->result->attr.proc_pointer)
509             gfc_error ("Result '%s' of contained function '%s' at %L has "
510                        "no IMPLICIT type", sym->result->name, sym->name,
511                        &sym->result->declared_at);
512           sym->result->attr.untyped = 1;
513         }
514     }
515
516   /* Fortran 95 Draft Standard, page 51, Section 5.1.1.5, on the Character
517      type, lists the only ways a character length value of * can be used:
518      dummy arguments of procedures, named constants, and function results
519      in external functions.  Internal function results and results of module
520      procedures are not on this list, ergo, not permitted.  */
521
522   if (sym->result->ts.type == BT_CHARACTER)
523     {
524       gfc_charlen *cl = sym->result->ts.u.cl;
525       if ((!cl || !cl->length) && !sym->result->ts.deferred)
526         {
527           /* See if this is a module-procedure and adapt error message
528              accordingly.  */
529           bool module_proc;
530           gcc_assert (ns->parent && ns->parent->proc_name);
531           module_proc = (ns->parent->proc_name->attr.flavor == FL_MODULE);
532
533           gfc_error ("Character-valued %s '%s' at %L must not be"
534                      " assumed length",
535                      module_proc ? _("module procedure")
536                                  : _("internal function"),
537                      sym->name, &sym->declared_at);
538         }
539     }
540 }
541
542
543 /* Add NEW_ARGS to the formal argument list of PROC, taking care not to
544    introduce duplicates.  */
545
546 static void
547 merge_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
548 {
549   gfc_formal_arglist *f, *new_arglist;
550   gfc_symbol *new_sym;
551
552   for (; new_args != NULL; new_args = new_args->next)
553     {
554       new_sym = new_args->sym;
555       /* See if this arg is already in the formal argument list.  */
556       for (f = proc->formal; f; f = f->next)
557         {
558           if (new_sym == f->sym)
559             break;
560         }
561
562       if (f)
563         continue;
564
565       /* Add a new argument.  Argument order is not important.  */
566       new_arglist = gfc_get_formal_arglist ();
567       new_arglist->sym = new_sym;
568       new_arglist->next = proc->formal;
569       proc->formal  = new_arglist;
570     }
571 }
572
573
574 /* Flag the arguments that are not present in all entries.  */
575
576 static void
577 check_argument_lists (gfc_symbol *proc, gfc_formal_arglist *new_args)
578 {
579   gfc_formal_arglist *f, *head;
580   head = new_args;
581
582   for (f = proc->formal; f; f = f->next)
583     {
584       if (f->sym == NULL)
585         continue;
586
587       for (new_args = head; new_args; new_args = new_args->next)
588         {
589           if (new_args->sym == f->sym)
590             break;
591         }
592
593       if (new_args)
594         continue;
595
596       f->sym->attr.not_always_present = 1;
597     }
598 }
599
600
601 /* Resolve alternate entry points.  If a symbol has multiple entry points we
602    create a new master symbol for the main routine, and turn the existing
603    symbol into an entry point.  */
604
605 static void
606 resolve_entries (gfc_namespace *ns)
607 {
608   gfc_namespace *old_ns;
609   gfc_code *c;
610   gfc_symbol *proc;
611   gfc_entry_list *el;
612   char name[GFC_MAX_SYMBOL_LEN + 1];
613   static int master_count = 0;
614
615   if (ns->proc_name == NULL)
616     return;
617
618   /* No need to do anything if this procedure doesn't have alternate entry
619      points.  */
620   if (!ns->entries)
621     return;
622
623   /* We may already have resolved alternate entry points.  */
624   if (ns->proc_name->attr.entry_master)
625     return;
626
627   /* If this isn't a procedure something has gone horribly wrong.  */
628   gcc_assert (ns->proc_name->attr.flavor == FL_PROCEDURE);
629
630   /* Remember the current namespace.  */
631   old_ns = gfc_current_ns;
632
633   gfc_current_ns = ns;
634
635   /* Add the main entry point to the list of entry points.  */
636   el = gfc_get_entry_list ();
637   el->sym = ns->proc_name;
638   el->id = 0;
639   el->next = ns->entries;
640   ns->entries = el;
641   ns->proc_name->attr.entry = 1;
642
643   /* If it is a module function, it needs to be in the right namespace
644      so that gfc_get_fake_result_decl can gather up the results. The
645      need for this arose in get_proc_name, where these beasts were
646      left in their own namespace, to keep prior references linked to
647      the entry declaration.*/
648   if (ns->proc_name->attr.function
649       && ns->parent && ns->parent->proc_name->attr.flavor == FL_MODULE)
650     el->sym->ns = ns;
651
652   /* Do the same for entries where the master is not a module
653      procedure.  These are retained in the module namespace because
654      of the module procedure declaration.  */
655   for (el = el->next; el; el = el->next)
656     if (el->sym->ns->proc_name->attr.flavor == FL_MODULE
657           && el->sym->attr.mod_proc)
658       el->sym->ns = ns;
659   el = ns->entries;
660
661   /* Add an entry statement for it.  */
662   c = gfc_get_code ();
663   c->op = EXEC_ENTRY;
664   c->ext.entry = el;
665   c->next = ns->code;
666   ns->code = c;
667
668   /* Create a new symbol for the master function.  */
669   /* Give the internal function a unique name (within this file).
670      Also include the function name so the user has some hope of figuring
671      out what is going on.  */
672   snprintf (name, GFC_MAX_SYMBOL_LEN, "master.%d.%s",
673             master_count++, ns->proc_name->name);
674   gfc_get_ha_symbol (name, &proc);
675   gcc_assert (proc != NULL);
676
677   gfc_add_procedure (&proc->attr, PROC_INTERNAL, proc->name, NULL);
678   if (ns->proc_name->attr.subroutine)
679     gfc_add_subroutine (&proc->attr, proc->name, NULL);
680   else
681     {
682       gfc_symbol *sym;
683       gfc_typespec *ts, *fts;
684       gfc_array_spec *as, *fas;
685       gfc_add_function (&proc->attr, proc->name, NULL);
686       proc->result = proc;
687       fas = ns->entries->sym->as;
688       fas = fas ? fas : ns->entries->sym->result->as;
689       fts = &ns->entries->sym->result->ts;
690       if (fts->type == BT_UNKNOWN)
691         fts = gfc_get_default_type (ns->entries->sym->result->name, NULL);
692       for (el = ns->entries->next; el; el = el->next)
693         {
694           ts = &el->sym->result->ts;
695           as = el->sym->as;
696           as = as ? as : el->sym->result->as;
697           if (ts->type == BT_UNKNOWN)
698             ts = gfc_get_default_type (el->sym->result->name, NULL);
699
700           if (! gfc_compare_types (ts, fts)
701               || (el->sym->result->attr.dimension
702                   != ns->entries->sym->result->attr.dimension)
703               || (el->sym->result->attr.pointer
704                   != ns->entries->sym->result->attr.pointer))
705             break;
706           else if (as && fas && ns->entries->sym->result != el->sym->result
707                       && gfc_compare_array_spec (as, fas) == 0)
708             gfc_error ("Function %s at %L has entries with mismatched "
709                        "array specifications", ns->entries->sym->name,
710                        &ns->entries->sym->declared_at);
711           /* The characteristics need to match and thus both need to have
712              the same string length, i.e. both len=*, or both len=4.
713              Having both len=<variable> is also possible, but difficult to
714              check at compile time.  */
715           else if (ts->type == BT_CHARACTER && ts->u.cl && fts->u.cl
716                    && (((ts->u.cl->length && !fts->u.cl->length)
717                         ||(!ts->u.cl->length && fts->u.cl->length))
718                        || (ts->u.cl->length
719                            && ts->u.cl->length->expr_type
720                               != fts->u.cl->length->expr_type)
721                        || (ts->u.cl->length
722                            && ts->u.cl->length->expr_type == EXPR_CONSTANT
723                            && mpz_cmp (ts->u.cl->length->value.integer,
724                                        fts->u.cl->length->value.integer) != 0)))
725             gfc_notify_std (GFC_STD_GNU, "Extension: Function %s at %L with "
726                             "entries returning variables of different "
727                             "string lengths", ns->entries->sym->name,
728                             &ns->entries->sym->declared_at);
729         }
730
731       if (el == NULL)
732         {
733           sym = ns->entries->sym->result;
734           /* All result types the same.  */
735           proc->ts = *fts;
736           if (sym->attr.dimension)
737             gfc_set_array_spec (proc, gfc_copy_array_spec (sym->as), NULL);
738           if (sym->attr.pointer)
739             gfc_add_pointer (&proc->attr, NULL);
740         }
741       else
742         {
743           /* Otherwise the result will be passed through a union by
744              reference.  */
745           proc->attr.mixed_entry_master = 1;
746           for (el = ns->entries; el; el = el->next)
747             {
748               sym = el->sym->result;
749               if (sym->attr.dimension)
750                 {
751                   if (el == ns->entries)
752                     gfc_error ("FUNCTION result %s can't be an array in "
753                                "FUNCTION %s at %L", sym->name,
754                                ns->entries->sym->name, &sym->declared_at);
755                   else
756                     gfc_error ("ENTRY result %s can't be an array in "
757                                "FUNCTION %s at %L", sym->name,
758                                ns->entries->sym->name, &sym->declared_at);
759                 }
760               else if (sym->attr.pointer)
761                 {
762                   if (el == ns->entries)
763                     gfc_error ("FUNCTION result %s can't be a POINTER in "
764                                "FUNCTION %s at %L", sym->name,
765                                ns->entries->sym->name, &sym->declared_at);
766                   else
767                     gfc_error ("ENTRY result %s can't be a POINTER in "
768                                "FUNCTION %s at %L", sym->name,
769                                ns->entries->sym->name, &sym->declared_at);
770                 }
771               else
772                 {
773                   ts = &sym->ts;
774                   if (ts->type == BT_UNKNOWN)
775                     ts = gfc_get_default_type (sym->name, NULL);
776                   switch (ts->type)
777                     {
778                     case BT_INTEGER:
779                       if (ts->kind == gfc_default_integer_kind)
780                         sym = NULL;
781                       break;
782                     case BT_REAL:
783                       if (ts->kind == gfc_default_real_kind
784                           || ts->kind == gfc_default_double_kind)
785                         sym = NULL;
786                       break;
787                     case BT_COMPLEX:
788                       if (ts->kind == gfc_default_complex_kind)
789                         sym = NULL;
790                       break;
791                     case BT_LOGICAL:
792                       if (ts->kind == gfc_default_logical_kind)
793                         sym = NULL;
794                       break;
795                     case BT_UNKNOWN:
796                       /* We will issue error elsewhere.  */
797                       sym = NULL;
798                       break;
799                     default:
800                       break;
801                     }
802                   if (sym)
803                     {
804                       if (el == ns->entries)
805                         gfc_error ("FUNCTION result %s can't be of type %s "
806                                    "in FUNCTION %s at %L", sym->name,
807                                    gfc_typename (ts), ns->entries->sym->name,
808                                    &sym->declared_at);
809                       else
810                         gfc_error ("ENTRY result %s can't be of type %s "
811                                    "in FUNCTION %s at %L", sym->name,
812                                    gfc_typename (ts), ns->entries->sym->name,
813                                    &sym->declared_at);
814                     }
815                 }
816             }
817         }
818     }
819   proc->attr.access = ACCESS_PRIVATE;
820   proc->attr.entry_master = 1;
821
822   /* Merge all the entry point arguments.  */
823   for (el = ns->entries; el; el = el->next)
824     merge_argument_lists (proc, el->sym->formal);
825
826   /* Check the master formal arguments for any that are not
827      present in all entry points.  */
828   for (el = ns->entries; el; el = el->next)
829     check_argument_lists (proc, el->sym->formal);
830
831   /* Use the master function for the function body.  */
832   ns->proc_name = proc;
833
834   /* Finalize the new symbols.  */
835   gfc_commit_symbols ();
836
837   /* Restore the original namespace.  */
838   gfc_current_ns = old_ns;
839 }
840
841
842 /* Resolve common variables.  */
843 static void
844 resolve_common_vars (gfc_symbol *sym, bool named_common)
845 {
846   gfc_symbol *csym = sym;
847
848   for (; csym; csym = csym->common_next)
849     {
850       if (csym->value || csym->attr.data)
851         {
852           if (!csym->ns->is_block_data)
853             gfc_notify_std (GFC_STD_GNU, "Variable '%s' at %L is in COMMON "
854                             "but only in BLOCK DATA initialization is "
855                             "allowed", csym->name, &csym->declared_at);
856           else if (!named_common)
857             gfc_notify_std (GFC_STD_GNU, "Initialized variable '%s' at %L is "
858                             "in a blank COMMON but initialization is only "
859                             "allowed in named common blocks", csym->name,
860                             &csym->declared_at);
861         }
862
863       if (csym->ts.type != BT_DERIVED)
864         continue;
865
866       if (!(csym->ts.u.derived->attr.sequence
867             || csym->ts.u.derived->attr.is_bind_c))
868         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
869                        "has neither the SEQUENCE nor the BIND(C) "
870                        "attribute", csym->name, &csym->declared_at);
871       if (csym->ts.u.derived->attr.alloc_comp)
872         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
873                        "has an ultimate component that is "
874                        "allocatable", csym->name, &csym->declared_at);
875       if (gfc_has_default_initializer (csym->ts.u.derived))
876         gfc_error_now ("Derived type variable '%s' in COMMON at %L "
877                        "may not have default initializer", csym->name,
878                        &csym->declared_at);
879
880       if (csym->attr.flavor == FL_UNKNOWN && !csym->attr.proc_pointer)
881         gfc_add_flavor (&csym->attr, FL_VARIABLE, csym->name, &csym->declared_at);
882     }
883 }
884
885 /* Resolve common blocks.  */
886 static void
887 resolve_common_blocks (gfc_symtree *common_root)
888 {
889   gfc_symbol *sym;
890
891   if (common_root == NULL)
892     return;
893
894   if (common_root->left)
895     resolve_common_blocks (common_root->left);
896   if (common_root->right)
897     resolve_common_blocks (common_root->right);
898
899   resolve_common_vars (common_root->n.common->head, true);
900
901   gfc_find_symbol (common_root->name, gfc_current_ns, 0, &sym);
902   if (sym == NULL)
903     return;
904
905   if (sym->attr.flavor == FL_PARAMETER)
906     gfc_error ("COMMON block '%s' at %L is used as PARAMETER at %L",
907                sym->name, &common_root->n.common->where, &sym->declared_at);
908
909   if (sym->attr.external)
910     gfc_error ("COMMON block '%s' at %L can not have the EXTERNAL attribute",
911                sym->name, &common_root->n.common->where);
912
913   if (sym->attr.intrinsic)
914     gfc_error ("COMMON block '%s' at %L is also an intrinsic procedure",
915                sym->name, &common_root->n.common->where);
916   else if (sym->attr.result
917            || gfc_is_function_return_value (sym, gfc_current_ns))
918     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
919                     "that is also a function result", sym->name,
920                     &common_root->n.common->where);
921   else if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_INTERNAL
922            && sym->attr.proc != PROC_ST_FUNCTION)
923     gfc_notify_std (GFC_STD_F2003, "Fortran 2003: COMMON block '%s' at %L "
924                     "that is also a global procedure", sym->name,
925                     &common_root->n.common->where);
926 }
927
928
929 /* Resolve contained function types.  Because contained functions can call one
930    another, they have to be worked out before any of the contained procedures
931    can be resolved.
932
933    The good news is that if a function doesn't already have a type, the only
934    way it can get one is through an IMPLICIT type or a RESULT variable, because
935    by definition contained functions are contained namespace they're contained
936    in, not in a sibling or parent namespace.  */
937
938 static void
939 resolve_contained_functions (gfc_namespace *ns)
940 {
941   gfc_namespace *child;
942   gfc_entry_list *el;
943
944   resolve_formal_arglists (ns);
945
946   for (child = ns->contained; child; child = child->sibling)
947     {
948       /* Resolve alternate entry points first.  */
949       resolve_entries (child);
950
951       /* Then check function return types.  */
952       resolve_contained_fntype (child->proc_name, child);
953       for (el = child->entries; el; el = el->next)
954         resolve_contained_fntype (el->sym, child);
955     }
956 }
957
958
959 static gfc_try resolve_fl_derived0 (gfc_symbol *sym);
960
961
962 /* Resolve all of the elements of a structure constructor and make sure that
963    the types are correct. The 'init' flag indicates that the given
964    constructor is an initializer.  */
965
966 static gfc_try
967 resolve_structure_cons (gfc_expr *expr, int init)
968 {
969   gfc_constructor *cons;
970   gfc_component *comp;
971   gfc_try t;
972   symbol_attribute a;
973
974   t = SUCCESS;
975
976   if (expr->ts.type == BT_DERIVED)
977     resolve_fl_derived0 (expr->ts.u.derived);
978
979   cons = gfc_constructor_first (expr->value.constructor);
980
981   /* See if the user is trying to invoke a structure constructor for one of
982      the iso_c_binding derived types.  */
983   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
984       && expr->ts.u.derived->ts.is_iso_c && cons
985       && (cons->expr == NULL || cons->expr->expr_type != EXPR_NULL))
986     {
987       gfc_error ("Components of structure constructor '%s' at %L are PRIVATE",
988                  expr->ts.u.derived->name, &(expr->where));
989       return FAILURE;
990     }
991
992   /* Return if structure constructor is c_null_(fun)prt.  */
993   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
994       && expr->ts.u.derived->ts.is_iso_c && cons
995       && cons->expr && cons->expr->expr_type == EXPR_NULL)
996     return SUCCESS;
997
998   /* A constructor may have references if it is the result of substituting a
999      parameter variable.  In this case we just pull out the component we
1000      want.  */
1001   if (expr->ref)
1002     comp = expr->ref->u.c.sym->components;
1003   else
1004     comp = expr->ts.u.derived->components;
1005
1006   for (; comp && cons; comp = comp->next, cons = gfc_constructor_next (cons))
1007     {
1008       int rank;
1009
1010       if (!cons->expr)
1011         continue;
1012
1013       if (gfc_resolve_expr (cons->expr) == FAILURE)
1014         {
1015           t = FAILURE;
1016           continue;
1017         }
1018
1019       rank = comp->as ? comp->as->rank : 0;
1020       if (cons->expr->expr_type != EXPR_NULL && rank != cons->expr->rank
1021           && (comp->attr.allocatable || cons->expr->rank))
1022         {
1023           gfc_error ("The rank of the element in the structure "
1024                      "constructor at %L does not match that of the "
1025                      "component (%d/%d)", &cons->expr->where,
1026                      cons->expr->rank, rank);
1027           t = FAILURE;
1028         }
1029
1030       /* If we don't have the right type, try to convert it.  */
1031
1032       if (!comp->attr.proc_pointer &&
1033           !gfc_compare_types (&cons->expr->ts, &comp->ts))
1034         {
1035           t = FAILURE;
1036           if (strcmp (comp->name, "_extends") == 0)
1037             {
1038               /* Can afford to be brutal with the _extends initializer.
1039                  The derived type can get lost because it is PRIVATE
1040                  but it is not usage constrained by the standard.  */
1041               cons->expr->ts = comp->ts;
1042               t = SUCCESS;
1043             }
1044           else if (comp->attr.pointer && cons->expr->ts.type != BT_UNKNOWN)
1045             gfc_error ("The element in the structure constructor at %L, "
1046                        "for pointer component '%s', is %s but should be %s",
1047                        &cons->expr->where, comp->name,
1048                        gfc_basic_typename (cons->expr->ts.type),
1049                        gfc_basic_typename (comp->ts.type));
1050           else
1051             t = gfc_convert_type (cons->expr, &comp->ts, 1);
1052         }
1053
1054       /* For strings, the length of the constructor should be the same as
1055          the one of the structure, ensure this if the lengths are known at
1056          compile time and when we are dealing with PARAMETER or structure
1057          constructors.  */
1058       if (cons->expr->ts.type == BT_CHARACTER && comp->ts.u.cl
1059           && comp->ts.u.cl->length
1060           && comp->ts.u.cl->length->expr_type == EXPR_CONSTANT
1061           && cons->expr->ts.u.cl && cons->expr->ts.u.cl->length
1062           && cons->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
1063           && cons->expr->rank != 0
1064           && mpz_cmp (cons->expr->ts.u.cl->length->value.integer,
1065                       comp->ts.u.cl->length->value.integer) != 0)
1066         {
1067           if (cons->expr->expr_type == EXPR_VARIABLE
1068               && cons->expr->symtree->n.sym->attr.flavor == FL_PARAMETER)
1069             {
1070               /* Wrap the parameter in an array constructor (EXPR_ARRAY)
1071                  to make use of the gfc_resolve_character_array_constructor
1072                  machinery.  The expression is later simplified away to
1073                  an array of string literals.  */
1074               gfc_expr *para = cons->expr;
1075               cons->expr = gfc_get_expr ();
1076               cons->expr->ts = para->ts;
1077               cons->expr->where = para->where;
1078               cons->expr->expr_type = EXPR_ARRAY;
1079               cons->expr->rank = para->rank;
1080               cons->expr->shape = gfc_copy_shape (para->shape, para->rank);
1081               gfc_constructor_append_expr (&cons->expr->value.constructor,
1082                                            para, &cons->expr->where);
1083             }
1084           if (cons->expr->expr_type == EXPR_ARRAY)
1085             {
1086               gfc_constructor *p;
1087               p = gfc_constructor_first (cons->expr->value.constructor);
1088               if (cons->expr->ts.u.cl != p->expr->ts.u.cl)
1089                 {
1090                   gfc_charlen *cl, *cl2;
1091
1092                   cl2 = NULL;
1093                   for (cl = gfc_current_ns->cl_list; cl; cl = cl->next)
1094                     {
1095                       if (cl == cons->expr->ts.u.cl)
1096                         break;
1097                       cl2 = cl;
1098                     }
1099
1100                   gcc_assert (cl);
1101
1102                   if (cl2)
1103                     cl2->next = cl->next;
1104
1105                   gfc_free_expr (cl->length);
1106                   free (cl);
1107                 }
1108
1109               cons->expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
1110               cons->expr->ts.u.cl->length_from_typespec = true;
1111               cons->expr->ts.u.cl->length = gfc_copy_expr (comp->ts.u.cl->length);
1112               gfc_resolve_character_array_constructor (cons->expr);
1113             }
1114         }
1115
1116       if (cons->expr->expr_type == EXPR_NULL
1117           && !(comp->attr.pointer || comp->attr.allocatable
1118                || comp->attr.proc_pointer
1119                || (comp->ts.type == BT_CLASS
1120                    && (CLASS_DATA (comp)->attr.class_pointer
1121                        || CLASS_DATA (comp)->attr.allocatable))))
1122         {
1123           t = FAILURE;
1124           gfc_error ("The NULL in the structure constructor at %L is "
1125                      "being applied to component '%s', which is neither "
1126                      "a POINTER nor ALLOCATABLE", &cons->expr->where,
1127                      comp->name);
1128         }
1129
1130       if (comp->attr.proc_pointer && comp->ts.interface)
1131         {
1132           /* Check procedure pointer interface.  */
1133           gfc_symbol *s2 = NULL;
1134           gfc_component *c2;
1135           const char *name;
1136           char err[200];
1137
1138           if (gfc_is_proc_ptr_comp (cons->expr, &c2))
1139             {
1140               s2 = c2->ts.interface;
1141               name = c2->name;
1142             }
1143           else if (cons->expr->expr_type == EXPR_FUNCTION)
1144             {
1145               s2 = cons->expr->symtree->n.sym->result;
1146               name = cons->expr->symtree->n.sym->result->name;
1147             }
1148           else if (cons->expr->expr_type != EXPR_NULL)
1149             {
1150               s2 = cons->expr->symtree->n.sym;
1151               name = cons->expr->symtree->n.sym->name;
1152             }
1153
1154           if (s2 && !gfc_compare_interfaces (comp->ts.interface, s2, name, 0, 1,
1155                                              err, sizeof (err)))
1156             {
1157               gfc_error ("Interface mismatch for procedure-pointer component "
1158                          "'%s' in structure constructor at %L: %s",
1159                          comp->name, &cons->expr->where, err);
1160               return FAILURE;
1161             }
1162         }
1163
1164       if (!comp->attr.pointer || comp->attr.proc_pointer
1165           || cons->expr->expr_type == EXPR_NULL)
1166         continue;
1167
1168       a = gfc_expr_attr (cons->expr);
1169
1170       if (!a.pointer && !a.target)
1171         {
1172           t = FAILURE;
1173           gfc_error ("The element in the structure constructor at %L, "
1174                      "for pointer component '%s' should be a POINTER or "
1175                      "a TARGET", &cons->expr->where, comp->name);
1176         }
1177
1178       if (init)
1179         {
1180           /* F08:C461. Additional checks for pointer initialization.  */
1181           if (a.allocatable)
1182             {
1183               t = FAILURE;
1184               gfc_error ("Pointer initialization target at %L "
1185                          "must not be ALLOCATABLE ", &cons->expr->where);
1186             }
1187           if (!a.save)
1188             {
1189               t = FAILURE;
1190               gfc_error ("Pointer initialization target at %L "
1191                          "must have the SAVE attribute", &cons->expr->where);
1192             }
1193         }
1194
1195       /* F2003, C1272 (3).  */
1196       if (gfc_pure (NULL) && cons->expr->expr_type == EXPR_VARIABLE
1197           && (gfc_impure_variable (cons->expr->symtree->n.sym)
1198               || gfc_is_coindexed (cons->expr)))
1199         {
1200           t = FAILURE;
1201           gfc_error ("Invalid expression in the structure constructor for "
1202                      "pointer component '%s' at %L in PURE procedure",
1203                      comp->name, &cons->expr->where);
1204         }
1205
1206       if (gfc_implicit_pure (NULL)
1207             && cons->expr->expr_type == EXPR_VARIABLE
1208             && (gfc_impure_variable (cons->expr->symtree->n.sym)
1209                 || gfc_is_coindexed (cons->expr)))
1210         gfc_current_ns->proc_name->attr.implicit_pure = 0;
1211
1212     }
1213
1214   return t;
1215 }
1216
1217
1218 /****************** Expression name resolution ******************/
1219
1220 /* Returns 0 if a symbol was not declared with a type or
1221    attribute declaration statement, nonzero otherwise.  */
1222
1223 static int
1224 was_declared (gfc_symbol *sym)
1225 {
1226   symbol_attribute a;
1227
1228   a = sym->attr;
1229
1230   if (!a.implicit_type && sym->ts.type != BT_UNKNOWN)
1231     return 1;
1232
1233   if (a.allocatable || a.dimension || a.dummy || a.external || a.intrinsic
1234       || a.optional || a.pointer || a.save || a.target || a.volatile_
1235       || a.value || a.access != ACCESS_UNKNOWN || a.intent != INTENT_UNKNOWN
1236       || a.asynchronous || a.codimension)
1237     return 1;
1238
1239   return 0;
1240 }
1241
1242
1243 /* Determine if a symbol is generic or not.  */
1244
1245 static int
1246 generic_sym (gfc_symbol *sym)
1247 {
1248   gfc_symbol *s;
1249
1250   if (sym->attr.generic ||
1251       (sym->attr.intrinsic && gfc_generic_intrinsic (sym->name)))
1252     return 1;
1253
1254   if (was_declared (sym) || sym->ns->parent == NULL)
1255     return 0;
1256
1257   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1258
1259   if (s != NULL)
1260     {
1261       if (s == sym)
1262         return 0;
1263       else
1264         return generic_sym (s);
1265     }
1266
1267   return 0;
1268 }
1269
1270
1271 /* Determine if a symbol is specific or not.  */
1272
1273 static int
1274 specific_sym (gfc_symbol *sym)
1275 {
1276   gfc_symbol *s;
1277
1278   if (sym->attr.if_source == IFSRC_IFBODY
1279       || sym->attr.proc == PROC_MODULE
1280       || sym->attr.proc == PROC_INTERNAL
1281       || sym->attr.proc == PROC_ST_FUNCTION
1282       || (sym->attr.intrinsic && gfc_specific_intrinsic (sym->name))
1283       || sym->attr.external)
1284     return 1;
1285
1286   if (was_declared (sym) || sym->ns->parent == NULL)
1287     return 0;
1288
1289   gfc_find_symbol (sym->name, sym->ns->parent, 1, &s);
1290
1291   return (s == NULL) ? 0 : specific_sym (s);
1292 }
1293
1294
1295 /* Figure out if the procedure is specific, generic or unknown.  */
1296
1297 typedef enum
1298 { PTYPE_GENERIC = 1, PTYPE_SPECIFIC, PTYPE_UNKNOWN }
1299 proc_type;
1300
1301 static proc_type
1302 procedure_kind (gfc_symbol *sym)
1303 {
1304   if (generic_sym (sym))
1305     return PTYPE_GENERIC;
1306
1307   if (specific_sym (sym))
1308     return PTYPE_SPECIFIC;
1309
1310   return PTYPE_UNKNOWN;
1311 }
1312
1313 /* Check references to assumed size arrays.  The flag need_full_assumed_size
1314    is nonzero when matching actual arguments.  */
1315
1316 static int need_full_assumed_size = 0;
1317
1318 static bool
1319 check_assumed_size_reference (gfc_symbol *sym, gfc_expr *e)
1320 {
1321   if (need_full_assumed_size || !(sym->as && sym->as->type == AS_ASSUMED_SIZE))
1322       return false;
1323
1324   /* FIXME: The comparison "e->ref->u.ar.type == AR_FULL" is wrong.
1325      What should it be?  */
1326   if ((e->ref->u.ar.end[e->ref->u.ar.as->rank - 1] == NULL)
1327           && (e->ref->u.ar.as->type == AS_ASSUMED_SIZE)
1328                && (e->ref->u.ar.type == AR_FULL))
1329     {
1330       gfc_error ("The upper bound in the last dimension must "
1331                  "appear in the reference to the assumed size "
1332                  "array '%s' at %L", sym->name, &e->where);
1333       return true;
1334     }
1335   return false;
1336 }
1337
1338
1339 /* Look for bad assumed size array references in argument expressions
1340   of elemental and array valued intrinsic procedures.  Since this is
1341   called from procedure resolution functions, it only recurses at
1342   operators.  */
1343
1344 static bool
1345 resolve_assumed_size_actual (gfc_expr *e)
1346 {
1347   if (e == NULL)
1348    return false;
1349
1350   switch (e->expr_type)
1351     {
1352     case EXPR_VARIABLE:
1353       if (e->symtree && check_assumed_size_reference (e->symtree->n.sym, e))
1354         return true;
1355       break;
1356
1357     case EXPR_OP:
1358       if (resolve_assumed_size_actual (e->value.op.op1)
1359           || resolve_assumed_size_actual (e->value.op.op2))
1360         return true;
1361       break;
1362
1363     default:
1364       break;
1365     }
1366   return false;
1367 }
1368
1369
1370 /* Check a generic procedure, passed as an actual argument, to see if
1371    there is a matching specific name.  If none, it is an error, and if
1372    more than one, the reference is ambiguous.  */
1373 static int
1374 count_specific_procs (gfc_expr *e)
1375 {
1376   int n;
1377   gfc_interface *p;
1378   gfc_symbol *sym;
1379
1380   n = 0;
1381   sym = e->symtree->n.sym;
1382
1383   for (p = sym->generic; p; p = p->next)
1384     if (strcmp (sym->name, p->sym->name) == 0)
1385       {
1386         e->symtree = gfc_find_symtree (p->sym->ns->sym_root,
1387                                        sym->name);
1388         n++;
1389       }
1390
1391   if (n > 1)
1392     gfc_error ("'%s' at %L is ambiguous", e->symtree->n.sym->name,
1393                &e->where);
1394
1395   if (n == 0)
1396     gfc_error ("GENERIC procedure '%s' is not allowed as an actual "
1397                "argument at %L", sym->name, &e->where);
1398
1399   return n;
1400 }
1401
1402
1403 /* See if a call to sym could possibly be a not allowed RECURSION because of
1404    a missing RECURIVE declaration.  This means that either sym is the current
1405    context itself, or sym is the parent of a contained procedure calling its
1406    non-RECURSIVE containing procedure.
1407    This also works if sym is an ENTRY.  */
1408
1409 static bool
1410 is_illegal_recursion (gfc_symbol* sym, gfc_namespace* context)
1411 {
1412   gfc_symbol* proc_sym;
1413   gfc_symbol* context_proc;
1414   gfc_namespace* real_context;
1415
1416   if (sym->attr.flavor == FL_PROGRAM
1417       || sym->attr.flavor == FL_DERIVED)
1418     return false;
1419
1420   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
1421
1422   /* If we've got an ENTRY, find real procedure.  */
1423   if (sym->attr.entry && sym->ns->entries)
1424     proc_sym = sym->ns->entries->sym;
1425   else
1426     proc_sym = sym;
1427
1428   /* If sym is RECURSIVE, all is well of course.  */
1429   if (proc_sym->attr.recursive || gfc_option.flag_recursive)
1430     return false;
1431
1432   /* Find the context procedure's "real" symbol if it has entries.
1433      We look for a procedure symbol, so recurse on the parents if we don't
1434      find one (like in case of a BLOCK construct).  */
1435   for (real_context = context; ; real_context = real_context->parent)
1436     {
1437       /* We should find something, eventually!  */
1438       gcc_assert (real_context);
1439
1440       context_proc = (real_context->entries ? real_context->entries->sym
1441                                             : real_context->proc_name);
1442
1443       /* In some special cases, there may not be a proc_name, like for this
1444          invalid code:
1445          real(bad_kind()) function foo () ...
1446          when checking the call to bad_kind ().
1447          In these cases, we simply return here and assume that the
1448          call is ok.  */
1449       if (!context_proc)
1450         return false;
1451
1452       if (context_proc->attr.flavor != FL_LABEL)
1453         break;
1454     }
1455
1456   /* A call from sym's body to itself is recursion, of course.  */
1457   if (context_proc == proc_sym)
1458     return true;
1459
1460   /* The same is true if context is a contained procedure and sym the
1461      containing one.  */
1462   if (context_proc->attr.contained)
1463     {
1464       gfc_symbol* parent_proc;
1465
1466       gcc_assert (context->parent);
1467       parent_proc = (context->parent->entries ? context->parent->entries->sym
1468                                               : context->parent->proc_name);
1469
1470       if (parent_proc == proc_sym)
1471         return true;
1472     }
1473
1474   return false;
1475 }
1476
1477
1478 /* Resolve an intrinsic procedure: Set its function/subroutine attribute,
1479    its typespec and formal argument list.  */
1480
1481 static gfc_try
1482 resolve_intrinsic (gfc_symbol *sym, locus *loc)
1483 {
1484   gfc_intrinsic_sym* isym = NULL;
1485   const char* symstd;
1486
1487   if (sym->formal)
1488     return SUCCESS;
1489
1490   /* Already resolved.  */
1491   if (sym->from_intmod && sym->ts.type != BT_UNKNOWN)
1492     return SUCCESS;
1493
1494   /* We already know this one is an intrinsic, so we don't call
1495      gfc_is_intrinsic for full checking but rather use gfc_find_function and
1496      gfc_find_subroutine directly to check whether it is a function or
1497      subroutine.  */
1498
1499   if (sym->intmod_sym_id)
1500     isym = gfc_intrinsic_function_by_id ((gfc_isym_id) sym->intmod_sym_id);
1501   else if (!sym->attr.subroutine)
1502     isym = gfc_find_function (sym->name);
1503
1504   if (isym)
1505     {
1506       if (sym->ts.type != BT_UNKNOWN && gfc_option.warn_surprising
1507           && !sym->attr.implicit_type)
1508         gfc_warning ("Type specified for intrinsic function '%s' at %L is"
1509                       " ignored", sym->name, &sym->declared_at);
1510
1511       if (!sym->attr.function &&
1512           gfc_add_function (&sym->attr, sym->name, loc) == FAILURE)
1513         return FAILURE;
1514
1515       sym->ts = isym->ts;
1516     }
1517   else if ((isym = gfc_find_subroutine (sym->name)))
1518     {
1519       if (sym->ts.type != BT_UNKNOWN && !sym->attr.implicit_type)
1520         {
1521           gfc_error ("Intrinsic subroutine '%s' at %L shall not have a type"
1522                       " specifier", sym->name, &sym->declared_at);
1523           return FAILURE;
1524         }
1525
1526       if (!sym->attr.subroutine &&
1527           gfc_add_subroutine (&sym->attr, sym->name, loc) == FAILURE)
1528         return FAILURE;
1529     }
1530   else
1531     {
1532       gfc_error ("'%s' declared INTRINSIC at %L does not exist", sym->name,
1533                  &sym->declared_at);
1534       return FAILURE;
1535     }
1536
1537   gfc_copy_formal_args_intr (sym, isym);
1538
1539   /* Check it is actually available in the standard settings.  */
1540   if (gfc_check_intrinsic_standard (isym, &symstd, false, sym->declared_at)
1541       == FAILURE)
1542     {
1543       gfc_error ("The intrinsic '%s' declared INTRINSIC at %L is not"
1544                  " available in the current standard settings but %s.  Use"
1545                  " an appropriate -std=* option or enable -fall-intrinsics"
1546                  " in order to use it.",
1547                  sym->name, &sym->declared_at, symstd);
1548       return FAILURE;
1549     }
1550
1551   return SUCCESS;
1552 }
1553
1554
1555 /* Resolve a procedure expression, like passing it to a called procedure or as
1556    RHS for a procedure pointer assignment.  */
1557
1558 static gfc_try
1559 resolve_procedure_expression (gfc_expr* expr)
1560 {
1561   gfc_symbol* sym;
1562
1563   if (expr->expr_type != EXPR_VARIABLE)
1564     return SUCCESS;
1565   gcc_assert (expr->symtree);
1566
1567   sym = expr->symtree->n.sym;
1568
1569   if (sym->attr.intrinsic)
1570     resolve_intrinsic (sym, &expr->where);
1571
1572   if (sym->attr.flavor != FL_PROCEDURE
1573       || (sym->attr.function && sym->result == sym))
1574     return SUCCESS;
1575
1576   /* A non-RECURSIVE procedure that is used as procedure expression within its
1577      own body is in danger of being called recursively.  */
1578   if (is_illegal_recursion (sym, gfc_current_ns))
1579     gfc_warning ("Non-RECURSIVE procedure '%s' at %L is possibly calling"
1580                  " itself recursively.  Declare it RECURSIVE or use"
1581                  " -frecursive", sym->name, &expr->where);
1582
1583   return SUCCESS;
1584 }
1585
1586
1587 /* Resolve an actual argument list.  Most of the time, this is just
1588    resolving the expressions in the list.
1589    The exception is that we sometimes have to decide whether arguments
1590    that look like procedure arguments are really simple variable
1591    references.  */
1592
1593 static gfc_try
1594 resolve_actual_arglist (gfc_actual_arglist *arg, procedure_type ptype,
1595                         bool no_formal_args)
1596 {
1597   gfc_symbol *sym;
1598   gfc_symtree *parent_st;
1599   gfc_expr *e;
1600   int save_need_full_assumed_size;
1601
1602   for (; arg; arg = arg->next)
1603     {
1604       e = arg->expr;
1605       if (e == NULL)
1606         {
1607           /* Check the label is a valid branching target.  */
1608           if (arg->label)
1609             {
1610               if (arg->label->defined == ST_LABEL_UNKNOWN)
1611                 {
1612                   gfc_error ("Label %d referenced at %L is never defined",
1613                              arg->label->value, &arg->label->where);
1614                   return FAILURE;
1615                 }
1616             }
1617           continue;
1618         }
1619
1620       if (e->expr_type == EXPR_VARIABLE
1621             && e->symtree->n.sym->attr.generic
1622             && no_formal_args
1623             && count_specific_procs (e) != 1)
1624         return FAILURE;
1625
1626       if (e->ts.type != BT_PROCEDURE)
1627         {
1628           save_need_full_assumed_size = need_full_assumed_size;
1629           if (e->expr_type != EXPR_VARIABLE)
1630             need_full_assumed_size = 0;
1631           if (gfc_resolve_expr (e) != SUCCESS)
1632             return FAILURE;
1633           need_full_assumed_size = save_need_full_assumed_size;
1634           goto argument_list;
1635         }
1636
1637       /* See if the expression node should really be a variable reference.  */
1638
1639       sym = e->symtree->n.sym;
1640
1641       if (sym->attr.flavor == FL_PROCEDURE
1642           || sym->attr.intrinsic
1643           || sym->attr.external)
1644         {
1645           int actual_ok;
1646
1647           /* If a procedure is not already determined to be something else
1648              check if it is intrinsic.  */
1649           if (!sym->attr.intrinsic
1650               && !(sym->attr.external || sym->attr.use_assoc
1651                    || sym->attr.if_source == IFSRC_IFBODY)
1652               && gfc_is_intrinsic (sym, sym->attr.subroutine, e->where))
1653             sym->attr.intrinsic = 1;
1654
1655           if (sym->attr.proc == PROC_ST_FUNCTION)
1656             {
1657               gfc_error ("Statement function '%s' at %L is not allowed as an "
1658                          "actual argument", sym->name, &e->where);
1659             }
1660
1661           actual_ok = gfc_intrinsic_actual_ok (sym->name,
1662                                                sym->attr.subroutine);
1663           if (sym->attr.intrinsic && actual_ok == 0)
1664             {
1665               gfc_error ("Intrinsic '%s' at %L is not allowed as an "
1666                          "actual argument", sym->name, &e->where);
1667             }
1668
1669           if (sym->attr.contained && !sym->attr.use_assoc
1670               && sym->ns->proc_name->attr.flavor != FL_MODULE)
1671             {
1672               if (gfc_notify_std (GFC_STD_F2008,
1673                                   "Fortran 2008: Internal procedure '%s' is"
1674                                   " used as actual argument at %L",
1675                                   sym->name, &e->where) == FAILURE)
1676                 return FAILURE;
1677             }
1678
1679           if (sym->attr.elemental && !sym->attr.intrinsic)
1680             {
1681               gfc_error ("ELEMENTAL non-INTRINSIC procedure '%s' is not "
1682                          "allowed as an actual argument at %L", sym->name,
1683                          &e->where);
1684             }
1685
1686           /* Check if a generic interface has a specific procedure
1687             with the same name before emitting an error.  */
1688           if (sym->attr.generic && count_specific_procs (e) != 1)
1689             return FAILURE;
1690
1691           /* Just in case a specific was found for the expression.  */
1692           sym = e->symtree->n.sym;
1693
1694           /* If the symbol is the function that names the current (or
1695              parent) scope, then we really have a variable reference.  */
1696
1697           if (gfc_is_function_return_value (sym, sym->ns))
1698             goto got_variable;
1699
1700           /* If all else fails, see if we have a specific intrinsic.  */
1701           if (sym->ts.type == BT_UNKNOWN && sym->attr.intrinsic)
1702             {
1703               gfc_intrinsic_sym *isym;
1704
1705               isym = gfc_find_function (sym->name);
1706               if (isym == NULL || !isym->specific)
1707                 {
1708                   gfc_error ("Unable to find a specific INTRINSIC procedure "
1709                              "for the reference '%s' at %L", sym->name,
1710                              &e->where);
1711                   return FAILURE;
1712                 }
1713               sym->ts = isym->ts;
1714               sym->attr.intrinsic = 1;
1715               sym->attr.function = 1;
1716             }
1717
1718           if (gfc_resolve_expr (e) == FAILURE)
1719             return FAILURE;
1720           goto argument_list;
1721         }
1722
1723       /* See if the name is a module procedure in a parent unit.  */
1724
1725       if (was_declared (sym) || sym->ns->parent == NULL)
1726         goto got_variable;
1727
1728       if (gfc_find_sym_tree (sym->name, sym->ns->parent, 1, &parent_st))
1729         {
1730           gfc_error ("Symbol '%s' at %L is ambiguous", sym->name, &e->where);
1731           return FAILURE;
1732         }
1733
1734       if (parent_st == NULL)
1735         goto got_variable;
1736
1737       sym = parent_st->n.sym;
1738       e->symtree = parent_st;           /* Point to the right thing.  */
1739
1740       if (sym->attr.flavor == FL_PROCEDURE
1741           || sym->attr.intrinsic
1742           || sym->attr.external)
1743         {
1744           if (gfc_resolve_expr (e) == FAILURE)
1745             return FAILURE;
1746           goto argument_list;
1747         }
1748
1749     got_variable:
1750       e->expr_type = EXPR_VARIABLE;
1751       e->ts = sym->ts;
1752       if ((sym->as != NULL && sym->ts.type != BT_CLASS)
1753           || (sym->ts.type == BT_CLASS && sym->attr.class_ok
1754               && CLASS_DATA (sym)->as))
1755         {
1756           e->rank = sym->ts.type == BT_CLASS
1757                     ? CLASS_DATA (sym)->as->rank : sym->as->rank;
1758           e->ref = gfc_get_ref ();
1759           e->ref->type = REF_ARRAY;
1760           e->ref->u.ar.type = AR_FULL;
1761           e->ref->u.ar.as = sym->ts.type == BT_CLASS
1762                             ? CLASS_DATA (sym)->as : sym->as;
1763         }
1764
1765       /* Expressions are assigned a default ts.type of BT_PROCEDURE in
1766          primary.c (match_actual_arg). If above code determines that it
1767          is a  variable instead, it needs to be resolved as it was not
1768          done at the beginning of this function.  */
1769       save_need_full_assumed_size = need_full_assumed_size;
1770       if (e->expr_type != EXPR_VARIABLE)
1771         need_full_assumed_size = 0;
1772       if (gfc_resolve_expr (e) != SUCCESS)
1773         return FAILURE;
1774       need_full_assumed_size = save_need_full_assumed_size;
1775
1776     argument_list:
1777       /* Check argument list functions %VAL, %LOC and %REF.  There is
1778          nothing to do for %REF.  */
1779       if (arg->name && arg->name[0] == '%')
1780         {
1781           if (strncmp ("%VAL", arg->name, 4) == 0)
1782             {
1783               if (e->ts.type == BT_CHARACTER || e->ts.type == BT_DERIVED)
1784                 {
1785                   gfc_error ("By-value argument at %L is not of numeric "
1786                              "type", &e->where);
1787                   return FAILURE;
1788                 }
1789
1790               if (e->rank)
1791                 {
1792                   gfc_error ("By-value argument at %L cannot be an array or "
1793                              "an array section", &e->where);
1794                 return FAILURE;
1795                 }
1796
1797               /* Intrinsics are still PROC_UNKNOWN here.  However,
1798                  since same file external procedures are not resolvable
1799                  in gfortran, it is a good deal easier to leave them to
1800                  intrinsic.c.  */
1801               if (ptype != PROC_UNKNOWN
1802                   && ptype != PROC_DUMMY
1803                   && ptype != PROC_EXTERNAL
1804                   && ptype != PROC_MODULE)
1805                 {
1806                   gfc_error ("By-value argument at %L is not allowed "
1807                              "in this context", &e->where);
1808                   return FAILURE;
1809                 }
1810             }
1811
1812           /* Statement functions have already been excluded above.  */
1813           else if (strncmp ("%LOC", arg->name, 4) == 0
1814                    && e->ts.type == BT_PROCEDURE)
1815             {
1816               if (e->symtree->n.sym->attr.proc == PROC_INTERNAL)
1817                 {
1818                   gfc_error ("Passing internal procedure at %L by location "
1819                              "not allowed", &e->where);
1820                   return FAILURE;
1821                 }
1822             }
1823         }
1824
1825       /* Fortran 2008, C1237.  */
1826       if (e->expr_type == EXPR_VARIABLE && gfc_is_coindexed (e)
1827           && gfc_has_ultimate_pointer (e))
1828         {
1829           gfc_error ("Coindexed actual argument at %L with ultimate pointer "
1830                      "component", &e->where);
1831           return FAILURE;
1832         }
1833     }
1834
1835   return SUCCESS;
1836 }
1837
1838
1839 /* Do the checks of the actual argument list that are specific to elemental
1840    procedures.  If called with c == NULL, we have a function, otherwise if
1841    expr == NULL, we have a subroutine.  */
1842
1843 static gfc_try
1844 resolve_elemental_actual (gfc_expr *expr, gfc_code *c)
1845 {
1846   gfc_actual_arglist *arg0;
1847   gfc_actual_arglist *arg;
1848   gfc_symbol *esym = NULL;
1849   gfc_intrinsic_sym *isym = NULL;
1850   gfc_expr *e = NULL;
1851   gfc_intrinsic_arg *iformal = NULL;
1852   gfc_formal_arglist *eformal = NULL;
1853   bool formal_optional = false;
1854   bool set_by_optional = false;
1855   int i;
1856   int rank = 0;
1857
1858   /* Is this an elemental procedure?  */
1859   if (expr && expr->value.function.actual != NULL)
1860     {
1861       if (expr->value.function.esym != NULL
1862           && expr->value.function.esym->attr.elemental)
1863         {
1864           arg0 = expr->value.function.actual;
1865           esym = expr->value.function.esym;
1866         }
1867       else if (expr->value.function.isym != NULL
1868                && expr->value.function.isym->elemental)
1869         {
1870           arg0 = expr->value.function.actual;
1871           isym = expr->value.function.isym;
1872         }
1873       else
1874         return SUCCESS;
1875     }
1876   else if (c && c->ext.actual != NULL)
1877     {
1878       arg0 = c->ext.actual;
1879
1880       if (c->resolved_sym)
1881         esym = c->resolved_sym;
1882       else
1883         esym = c->symtree->n.sym;
1884       gcc_assert (esym);
1885
1886       if (!esym->attr.elemental)
1887         return SUCCESS;
1888     }
1889   else
1890     return SUCCESS;
1891
1892   /* The rank of an elemental is the rank of its array argument(s).  */
1893   for (arg = arg0; arg; arg = arg->next)
1894     {
1895       if (arg->expr != NULL && arg->expr->rank > 0)
1896         {
1897           rank = arg->expr->rank;
1898           if (arg->expr->expr_type == EXPR_VARIABLE
1899               && arg->expr->symtree->n.sym->attr.optional)
1900             set_by_optional = true;
1901
1902           /* Function specific; set the result rank and shape.  */
1903           if (expr)
1904             {
1905               expr->rank = rank;
1906               if (!expr->shape && arg->expr->shape)
1907                 {
1908                   expr->shape = gfc_get_shape (rank);
1909                   for (i = 0; i < rank; i++)
1910                     mpz_init_set (expr->shape[i], arg->expr->shape[i]);
1911                 }
1912             }
1913           break;
1914         }
1915     }
1916
1917   /* If it is an array, it shall not be supplied as an actual argument
1918      to an elemental procedure unless an array of the same rank is supplied
1919      as an actual argument corresponding to a nonoptional dummy argument of
1920      that elemental procedure(12.4.1.5).  */
1921   formal_optional = false;
1922   if (isym)
1923     iformal = isym->formal;
1924   else
1925     eformal = esym->formal;
1926
1927   for (arg = arg0; arg; arg = arg->next)
1928     {
1929       if (eformal)
1930         {
1931           if (eformal->sym && eformal->sym->attr.optional)
1932             formal_optional = true;
1933           eformal = eformal->next;
1934         }
1935       else if (isym && iformal)
1936         {
1937           if (iformal->optional)
1938             formal_optional = true;
1939           iformal = iformal->next;
1940         }
1941       else if (isym)
1942         formal_optional = true;
1943
1944       if (pedantic && arg->expr != NULL
1945           && arg->expr->expr_type == EXPR_VARIABLE
1946           && arg->expr->symtree->n.sym->attr.optional
1947           && formal_optional
1948           && arg->expr->rank
1949           && (set_by_optional || arg->expr->rank != rank)
1950           && !(isym && isym->id == GFC_ISYM_CONVERSION))
1951         {
1952           gfc_warning ("'%s' at %L is an array and OPTIONAL; IF IT IS "
1953                        "MISSING, it cannot be the actual argument of an "
1954                        "ELEMENTAL procedure unless there is a non-optional "
1955                        "argument with the same rank (12.4.1.5)",
1956                        arg->expr->symtree->n.sym->name, &arg->expr->where);
1957           return FAILURE;
1958         }
1959     }
1960
1961   for (arg = arg0; arg; arg = arg->next)
1962     {
1963       if (arg->expr == NULL || arg->expr->rank == 0)
1964         continue;
1965
1966       /* Being elemental, the last upper bound of an assumed size array
1967          argument must be present.  */
1968       if (resolve_assumed_size_actual (arg->expr))
1969         return FAILURE;
1970
1971       /* Elemental procedure's array actual arguments must conform.  */
1972       if (e != NULL)
1973         {
1974           if (gfc_check_conformance (arg->expr, e,
1975                                      "elemental procedure") == FAILURE)
1976             return FAILURE;
1977         }
1978       else
1979         e = arg->expr;
1980     }
1981
1982   /* INTENT(OUT) is only allowed for subroutines; if any actual argument
1983      is an array, the intent inout/out variable needs to be also an array.  */
1984   if (rank > 0 && esym && expr == NULL)
1985     for (eformal = esym->formal, arg = arg0; arg && eformal;
1986          arg = arg->next, eformal = eformal->next)
1987       if ((eformal->sym->attr.intent == INTENT_OUT
1988            || eformal->sym->attr.intent == INTENT_INOUT)
1989           && arg->expr && arg->expr->rank == 0)
1990         {
1991           gfc_error ("Actual argument at %L for INTENT(%s) dummy '%s' of "
1992                      "ELEMENTAL subroutine '%s' is a scalar, but another "
1993                      "actual argument is an array", &arg->expr->where,
1994                      (eformal->sym->attr.intent == INTENT_OUT) ? "OUT"
1995                      : "INOUT", eformal->sym->name, esym->name);
1996           return FAILURE;
1997         }
1998   return SUCCESS;
1999 }
2000
2001
2002 /* This function does the checking of references to global procedures
2003    as defined in sections 18.1 and 14.1, respectively, of the Fortran
2004    77 and 95 standards.  It checks for a gsymbol for the name, making
2005    one if it does not already exist.  If it already exists, then the
2006    reference being resolved must correspond to the type of gsymbol.
2007    Otherwise, the new symbol is equipped with the attributes of the
2008    reference.  The corresponding code that is called in creating
2009    global entities is parse.c.
2010
2011    In addition, for all but -std=legacy, the gsymbols are used to
2012    check the interfaces of external procedures from the same file.
2013    The namespace of the gsymbol is resolved and then, once this is
2014    done the interface is checked.  */
2015
2016
2017 static bool
2018 not_in_recursive (gfc_symbol *sym, gfc_namespace *gsym_ns)
2019 {
2020   if (!gsym_ns->proc_name->attr.recursive)
2021     return true;
2022
2023   if (sym->ns == gsym_ns)
2024     return false;
2025
2026   if (sym->ns->parent && sym->ns->parent == gsym_ns)
2027     return false;
2028
2029   return true;
2030 }
2031
2032 static bool
2033 not_entry_self_reference  (gfc_symbol *sym, gfc_namespace *gsym_ns)
2034 {
2035   if (gsym_ns->entries)
2036     {
2037       gfc_entry_list *entry = gsym_ns->entries;
2038
2039       for (; entry; entry = entry->next)
2040         {
2041           if (strcmp (sym->name, entry->sym->name) == 0)
2042             {
2043               if (strcmp (gsym_ns->proc_name->name,
2044                           sym->ns->proc_name->name) == 0)
2045                 return false;
2046
2047               if (sym->ns->parent
2048                   && strcmp (gsym_ns->proc_name->name,
2049                              sym->ns->parent->proc_name->name) == 0)
2050                 return false;
2051             }
2052         }
2053     }
2054   return true;
2055 }
2056
2057 static void
2058 resolve_global_procedure (gfc_symbol *sym, locus *where,
2059                           gfc_actual_arglist **actual, int sub)
2060 {
2061   gfc_gsymbol * gsym;
2062   gfc_namespace *ns;
2063   enum gfc_symbol_type type;
2064
2065   type = sub ? GSYM_SUBROUTINE : GSYM_FUNCTION;
2066
2067   gsym = gfc_get_gsymbol (sym->name);
2068
2069   if ((gsym->type != GSYM_UNKNOWN && gsym->type != type))
2070     gfc_global_used (gsym, where);
2071
2072   if (gfc_option.flag_whole_file
2073         && (sym->attr.if_source == IFSRC_UNKNOWN
2074             || sym->attr.if_source == IFSRC_IFBODY)
2075         && gsym->type != GSYM_UNKNOWN
2076         && gsym->ns
2077         && gsym->ns->resolved != -1
2078         && gsym->ns->proc_name
2079         && not_in_recursive (sym, gsym->ns)
2080         && not_entry_self_reference (sym, gsym->ns))
2081     {
2082       gfc_symbol *def_sym;
2083
2084       /* Resolve the gsymbol namespace if needed.  */
2085       if (!gsym->ns->resolved)
2086         {
2087           gfc_dt_list *old_dt_list;
2088           struct gfc_omp_saved_state old_omp_state;
2089
2090           /* Stash away derived types so that the backend_decls do not
2091              get mixed up.  */
2092           old_dt_list = gfc_derived_types;
2093           gfc_derived_types = NULL;
2094           /* And stash away openmp state.  */
2095           gfc_omp_save_and_clear_state (&old_omp_state);
2096
2097           gfc_resolve (gsym->ns);
2098
2099           /* Store the new derived types with the global namespace.  */
2100           if (gfc_derived_types)
2101             gsym->ns->derived_types = gfc_derived_types;
2102
2103           /* Restore the derived types of this namespace.  */
2104           gfc_derived_types = old_dt_list;
2105           /* And openmp state.  */
2106           gfc_omp_restore_state (&old_omp_state);
2107         }
2108
2109       /* Make sure that translation for the gsymbol occurs before
2110          the procedure currently being resolved.  */
2111       ns = gfc_global_ns_list;
2112       for (; ns && ns != gsym->ns; ns = ns->sibling)
2113         {
2114           if (ns->sibling == gsym->ns)
2115             {
2116               ns->sibling = gsym->ns->sibling;
2117               gsym->ns->sibling = gfc_global_ns_list;
2118               gfc_global_ns_list = gsym->ns;
2119               break;
2120             }
2121         }
2122
2123       def_sym = gsym->ns->proc_name;
2124       if (def_sym->attr.entry_master)
2125         {
2126           gfc_entry_list *entry;
2127           for (entry = gsym->ns->entries; entry; entry = entry->next)
2128             if (strcmp (entry->sym->name, sym->name) == 0)
2129               {
2130                 def_sym = entry->sym;
2131                 break;
2132               }
2133         }
2134
2135       /* Differences in constant character lengths.  */
2136       if (sym->attr.function && sym->ts.type == BT_CHARACTER)
2137         {
2138           long int l1 = 0, l2 = 0;
2139           gfc_charlen *cl1 = sym->ts.u.cl;
2140           gfc_charlen *cl2 = def_sym->ts.u.cl;
2141
2142           if (cl1 != NULL
2143               && cl1->length != NULL
2144               && cl1->length->expr_type == EXPR_CONSTANT)
2145             l1 = mpz_get_si (cl1->length->value.integer);
2146
2147           if (cl2 != NULL
2148               && cl2->length != NULL
2149               && cl2->length->expr_type == EXPR_CONSTANT)
2150             l2 = mpz_get_si (cl2->length->value.integer);
2151
2152           if (l1 && l2 && l1 != l2)
2153             gfc_error ("Character length mismatch in return type of "
2154                        "function '%s' at %L (%ld/%ld)", sym->name,
2155                        &sym->declared_at, l1, l2);
2156         }
2157
2158      /* Type mismatch of function return type and expected type.  */
2159      if (sym->attr.function
2160          && !gfc_compare_types (&sym->ts, &def_sym->ts))
2161         gfc_error ("Return type mismatch of function '%s' at %L (%s/%s)",
2162                    sym->name, &sym->declared_at, gfc_typename (&sym->ts),
2163                    gfc_typename (&def_sym->ts));
2164
2165       if (def_sym->formal && sym->attr.if_source != IFSRC_IFBODY)
2166         {
2167           gfc_formal_arglist *arg = def_sym->formal;
2168           for ( ; arg; arg = arg->next)
2169             if (!arg->sym)
2170               continue;
2171             /* F2003, 12.3.1.1 (2a); F2008, 12.4.2.2 (2a)  */
2172             else if (arg->sym->attr.allocatable
2173                      || arg->sym->attr.asynchronous
2174                      || arg->sym->attr.optional
2175                      || arg->sym->attr.pointer
2176                      || arg->sym->attr.target
2177                      || arg->sym->attr.value
2178                      || arg->sym->attr.volatile_)
2179               {
2180                 gfc_error ("Dummy argument '%s' of procedure '%s' at %L "
2181                            "has an attribute that requires an explicit "
2182                            "interface for this procedure", arg->sym->name,
2183                            sym->name, &sym->declared_at);
2184                 break;
2185               }
2186             /* F2003, 12.3.1.1 (2b); F2008, 12.4.2.2 (2b)  */
2187             else if (arg->sym && arg->sym->as
2188                      && arg->sym->as->type == AS_ASSUMED_SHAPE)
2189               {
2190                 gfc_error ("Procedure '%s' at %L with assumed-shape dummy "
2191                            "argument '%s' must have an explicit interface",
2192                            sym->name, &sym->declared_at, arg->sym->name);
2193                 break;
2194               }
2195             /* F2008, 12.4.2.2 (2c)  */
2196             else if (arg->sym->attr.codimension)
2197               {
2198                 gfc_error ("Procedure '%s' at %L with coarray dummy argument "
2199                            "'%s' must have an explicit interface",
2200                            sym->name, &sym->declared_at, arg->sym->name);
2201                 break;
2202               }
2203             /* F2003, 12.3.1.1 (2c); F2008, 12.4.2.2 (2d)   */
2204             else if (false) /* TODO: is a parametrized derived type  */
2205               {
2206                 gfc_error ("Procedure '%s' at %L with parametrized derived "
2207                            "type argument '%s' must have an explicit "
2208                            "interface", sym->name, &sym->declared_at,
2209                            arg->sym->name);
2210                 break;
2211               }
2212             /* F2003, 12.3.1.1 (2d); F2008, 12.4.2.2 (2e)   */
2213             else if (arg->sym->ts.type == BT_CLASS)
2214               {
2215                 gfc_error ("Procedure '%s' at %L with polymorphic dummy "
2216                            "argument '%s' must have an explicit interface",
2217                            sym->name, &sym->declared_at, arg->sym->name);
2218                 break;
2219               }
2220         }
2221
2222       if (def_sym->attr.function)
2223         {
2224           /* F2003, 12.3.1.1 (3a); F2008, 12.4.2.2 (3a) */
2225           if (def_sym->as && def_sym->as->rank
2226               && (!sym->as || sym->as->rank != def_sym->as->rank))
2227             gfc_error ("The reference to function '%s' at %L either needs an "
2228                        "explicit INTERFACE or the rank is incorrect", sym->name,
2229                        where);
2230
2231           /* F2003, 12.3.1.1 (3b); F2008, 12.4.2.2 (3b) */
2232           if ((def_sym->result->attr.pointer
2233                || def_sym->result->attr.allocatable)
2234                && (sym->attr.if_source != IFSRC_IFBODY
2235                    || def_sym->result->attr.pointer
2236                         != sym->result->attr.pointer
2237                    || def_sym->result->attr.allocatable
2238                         != sym->result->attr.allocatable))
2239             gfc_error ("Function '%s' at %L with a POINTER or ALLOCATABLE "
2240                        "result must have an explicit interface", sym->name,
2241                        where);
2242
2243           /* F2003, 12.3.1.1 (3c); F2008, 12.4.2.2 (3c)  */
2244           if (sym->ts.type == BT_CHARACTER && sym->attr.if_source != IFSRC_IFBODY
2245               && def_sym->ts.type == BT_CHARACTER && def_sym->ts.u.cl->length != NULL)
2246             {
2247               gfc_charlen *cl = sym->ts.u.cl;
2248
2249               if (!sym->attr.entry_master && sym->attr.if_source == IFSRC_UNKNOWN
2250                   && cl && cl->length && cl->length->expr_type != EXPR_CONSTANT)
2251                 {
2252                   gfc_error ("Nonconstant character-length function '%s' at %L "
2253                              "must have an explicit interface", sym->name,
2254                              &sym->declared_at);
2255                 }
2256             }
2257         }
2258
2259       /* F2003, 12.3.1.1 (4); F2008, 12.4.2.2 (4) */
2260       if (def_sym->attr.elemental && !sym->attr.elemental)
2261         {
2262           gfc_error ("ELEMENTAL procedure '%s' at %L must have an explicit "
2263                      "interface", sym->name, &sym->declared_at);
2264         }
2265
2266       /* F2003, 12.3.1.1 (5); F2008, 12.4.2.2 (5) */
2267       if (def_sym->attr.is_bind_c && !sym->attr.is_bind_c)
2268         {
2269           gfc_error ("Procedure '%s' at %L with BIND(C) attribute must have "
2270                      "an explicit interface", sym->name, &sym->declared_at);
2271         }
2272
2273       if (gfc_option.flag_whole_file == 1
2274           || ((gfc_option.warn_std & GFC_STD_LEGACY)
2275               && !(gfc_option.warn_std & GFC_STD_GNU)))
2276         gfc_errors_to_warnings (1);
2277
2278       if (sym->attr.if_source != IFSRC_IFBODY)
2279         gfc_procedure_use (def_sym, actual, where);
2280
2281       gfc_errors_to_warnings (0);
2282     }
2283
2284   if (gsym->type == GSYM_UNKNOWN)
2285     {
2286       gsym->type = type;
2287       gsym->where = *where;
2288     }
2289
2290   gsym->used = 1;
2291 }
2292
2293
2294 /************* Function resolution *************/
2295
2296 /* Resolve a function call known to be generic.
2297    Section 14.1.2.4.1.  */
2298
2299 static match
2300 resolve_generic_f0 (gfc_expr *expr, gfc_symbol *sym)
2301 {
2302   gfc_symbol *s;
2303
2304   if (sym->attr.generic)
2305     {
2306       s = gfc_search_interface (sym->generic, 0, &expr->value.function.actual);
2307       if (s != NULL)
2308         {
2309           expr->value.function.name = s->name;
2310           expr->value.function.esym = s;
2311
2312           if (s->ts.type != BT_UNKNOWN)
2313             expr->ts = s->ts;
2314           else if (s->result != NULL && s->result->ts.type != BT_UNKNOWN)
2315             expr->ts = s->result->ts;
2316
2317           if (s->as != NULL)
2318             expr->rank = s->as->rank;
2319           else if (s->result != NULL && s->result->as != NULL)
2320             expr->rank = s->result->as->rank;
2321
2322           gfc_set_sym_referenced (expr->value.function.esym);
2323
2324           return MATCH_YES;
2325         }
2326
2327       /* TODO: Need to search for elemental references in generic
2328          interface.  */
2329     }
2330
2331   if (sym->attr.intrinsic)
2332     return gfc_intrinsic_func_interface (expr, 0);
2333
2334   return MATCH_NO;
2335 }
2336
2337
2338 static gfc_try
2339 resolve_generic_f (gfc_expr *expr)
2340 {
2341   gfc_symbol *sym;
2342   match m;
2343   gfc_interface *intr = NULL;
2344
2345   sym = expr->symtree->n.sym;
2346
2347   for (;;)
2348     {
2349       m = resolve_generic_f0 (expr, sym);
2350       if (m == MATCH_YES)
2351         return SUCCESS;
2352       else if (m == MATCH_ERROR)
2353         return FAILURE;
2354
2355 generic:
2356       if (!intr)
2357         for (intr = sym->generic; intr; intr = intr->next)
2358           if (intr->sym->attr.flavor == FL_DERIVED)
2359             break;
2360
2361       if (sym->ns->parent == NULL)
2362         break;
2363       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2364
2365       if (sym == NULL)
2366         break;
2367       if (!generic_sym (sym))
2368         goto generic;
2369     }
2370
2371   /* Last ditch attempt.  See if the reference is to an intrinsic
2372      that possesses a matching interface.  14.1.2.4  */
2373   if (sym  && !intr && !gfc_is_intrinsic (sym, 0, expr->where))
2374     {
2375       gfc_error ("There is no specific function for the generic '%s' "
2376                  "at %L", expr->symtree->n.sym->name, &expr->where);
2377       return FAILURE;
2378     }
2379
2380   if (intr)
2381     {
2382       if (gfc_convert_to_structure_constructor (expr, intr->sym, NULL, NULL,
2383                                                 false) != SUCCESS)
2384         return FAILURE;
2385       return resolve_structure_cons (expr, 0);
2386     }
2387
2388   m = gfc_intrinsic_func_interface (expr, 0);
2389   if (m == MATCH_YES)
2390     return SUCCESS;
2391
2392   if (m == MATCH_NO)
2393     gfc_error ("Generic function '%s' at %L is not consistent with a "
2394                "specific intrinsic interface", expr->symtree->n.sym->name,
2395                &expr->where);
2396
2397   return FAILURE;
2398 }
2399
2400
2401 /* Resolve a function call known to be specific.  */
2402
2403 static match
2404 resolve_specific_f0 (gfc_symbol *sym, gfc_expr *expr)
2405 {
2406   match m;
2407
2408   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
2409     {
2410       if (sym->attr.dummy)
2411         {
2412           sym->attr.proc = PROC_DUMMY;
2413           goto found;
2414         }
2415
2416       sym->attr.proc = PROC_EXTERNAL;
2417       goto found;
2418     }
2419
2420   if (sym->attr.proc == PROC_MODULE
2421       || sym->attr.proc == PROC_ST_FUNCTION
2422       || sym->attr.proc == PROC_INTERNAL)
2423     goto found;
2424
2425   if (sym->attr.intrinsic)
2426     {
2427       m = gfc_intrinsic_func_interface (expr, 1);
2428       if (m == MATCH_YES)
2429         return MATCH_YES;
2430       if (m == MATCH_NO)
2431         gfc_error ("Function '%s' at %L is INTRINSIC but is not compatible "
2432                    "with an intrinsic", sym->name, &expr->where);
2433
2434       return MATCH_ERROR;
2435     }
2436
2437   return MATCH_NO;
2438
2439 found:
2440   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2441
2442   if (sym->result)
2443     expr->ts = sym->result->ts;
2444   else
2445     expr->ts = sym->ts;
2446   expr->value.function.name = sym->name;
2447   expr->value.function.esym = sym;
2448   if (sym->as != NULL)
2449     expr->rank = sym->as->rank;
2450
2451   return MATCH_YES;
2452 }
2453
2454
2455 static gfc_try
2456 resolve_specific_f (gfc_expr *expr)
2457 {
2458   gfc_symbol *sym;
2459   match m;
2460
2461   sym = expr->symtree->n.sym;
2462
2463   for (;;)
2464     {
2465       m = resolve_specific_f0 (sym, expr);
2466       if (m == MATCH_YES)
2467         return SUCCESS;
2468       if (m == MATCH_ERROR)
2469         return FAILURE;
2470
2471       if (sym->ns->parent == NULL)
2472         break;
2473
2474       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
2475
2476       if (sym == NULL)
2477         break;
2478     }
2479
2480   gfc_error ("Unable to resolve the specific function '%s' at %L",
2481              expr->symtree->n.sym->name, &expr->where);
2482
2483   return SUCCESS;
2484 }
2485
2486
2487 /* Resolve a procedure call not known to be generic nor specific.  */
2488
2489 static gfc_try
2490 resolve_unknown_f (gfc_expr *expr)
2491 {
2492   gfc_symbol *sym;
2493   gfc_typespec *ts;
2494
2495   sym = expr->symtree->n.sym;
2496
2497   if (sym->attr.dummy)
2498     {
2499       sym->attr.proc = PROC_DUMMY;
2500       expr->value.function.name = sym->name;
2501       goto set_type;
2502     }
2503
2504   /* See if we have an intrinsic function reference.  */
2505
2506   if (gfc_is_intrinsic (sym, 0, expr->where))
2507     {
2508       if (gfc_intrinsic_func_interface (expr, 1) == MATCH_YES)
2509         return SUCCESS;
2510       return FAILURE;
2511     }
2512
2513   /* The reference is to an external name.  */
2514
2515   sym->attr.proc = PROC_EXTERNAL;
2516   expr->value.function.name = sym->name;
2517   expr->value.function.esym = expr->symtree->n.sym;
2518
2519   if (sym->as != NULL)
2520     expr->rank = sym->as->rank;
2521
2522   /* Type of the expression is either the type of the symbol or the
2523      default type of the symbol.  */
2524
2525 set_type:
2526   gfc_procedure_use (sym, &expr->value.function.actual, &expr->where);
2527
2528   if (sym->ts.type != BT_UNKNOWN)
2529     expr->ts = sym->ts;
2530   else
2531     {
2532       ts = gfc_get_default_type (sym->name, sym->ns);
2533
2534       if (ts->type == BT_UNKNOWN)
2535         {
2536           gfc_error ("Function '%s' at %L has no IMPLICIT type",
2537                      sym->name, &expr->where);
2538           return FAILURE;
2539         }
2540       else
2541         expr->ts = *ts;
2542     }
2543
2544   return SUCCESS;
2545 }
2546
2547
2548 /* Return true, if the symbol is an external procedure.  */
2549 static bool
2550 is_external_proc (gfc_symbol *sym)
2551 {
2552   if (!sym->attr.dummy && !sym->attr.contained
2553         && !(sym->attr.intrinsic
2554               || gfc_is_intrinsic (sym, sym->attr.subroutine, sym->declared_at))
2555         && sym->attr.proc != PROC_ST_FUNCTION
2556         && !sym->attr.proc_pointer
2557         && !sym->attr.use_assoc
2558         && sym->name)
2559     return true;
2560
2561   return false;
2562 }
2563
2564
2565 /* Figure out if a function reference is pure or not.  Also set the name
2566    of the function for a potential error message.  Return nonzero if the
2567    function is PURE, zero if not.  */
2568 static int
2569 pure_stmt_function (gfc_expr *, gfc_symbol *);
2570
2571 static int
2572 pure_function (gfc_expr *e, const char **name)
2573 {
2574   int pure;
2575
2576   *name = NULL;
2577
2578   if (e->symtree != NULL
2579         && e->symtree->n.sym != NULL
2580         && e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2581     return pure_stmt_function (e, e->symtree->n.sym);
2582
2583   if (e->value.function.esym)
2584     {
2585       pure = gfc_pure (e->value.function.esym);
2586       *name = e->value.function.esym->name;
2587     }
2588   else if (e->value.function.isym)
2589     {
2590       pure = e->value.function.isym->pure
2591              || e->value.function.isym->elemental;
2592       *name = e->value.function.isym->name;
2593     }
2594   else
2595     {
2596       /* Implicit functions are not pure.  */
2597       pure = 0;
2598       *name = e->value.function.name;
2599     }
2600
2601   return pure;
2602 }
2603
2604
2605 static bool
2606 impure_stmt_fcn (gfc_expr *e, gfc_symbol *sym,
2607                  int *f ATTRIBUTE_UNUSED)
2608 {
2609   const char *name;
2610
2611   /* Don't bother recursing into other statement functions
2612      since they will be checked individually for purity.  */
2613   if (e->expr_type != EXPR_FUNCTION
2614         || !e->symtree
2615         || e->symtree->n.sym == sym
2616         || e->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
2617     return false;
2618
2619   return pure_function (e, &name) ? false : true;
2620 }
2621
2622
2623 static int
2624 pure_stmt_function (gfc_expr *e, gfc_symbol *sym)
2625 {
2626   return gfc_traverse_expr (e, sym, impure_stmt_fcn, 0) ? 0 : 1;
2627 }
2628
2629
2630 static gfc_try
2631 is_scalar_expr_ptr (gfc_expr *expr)
2632 {
2633   gfc_try retval = SUCCESS;
2634   gfc_ref *ref;
2635   int start;
2636   int end;
2637
2638   /* See if we have a gfc_ref, which means we have a substring, array
2639      reference, or a component.  */
2640   if (expr->ref != NULL)
2641     {
2642       ref = expr->ref;
2643       while (ref->next != NULL)
2644         ref = ref->next;
2645
2646       switch (ref->type)
2647         {
2648         case REF_SUBSTRING:
2649           if (ref->u.ss.start == NULL || ref->u.ss.end == NULL
2650               || gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) != 0)
2651             retval = FAILURE;
2652           break;
2653
2654         case REF_ARRAY:
2655           if (ref->u.ar.type == AR_ELEMENT)
2656             retval = SUCCESS;
2657           else if (ref->u.ar.type == AR_FULL)
2658             {
2659               /* The user can give a full array if the array is of size 1.  */
2660               if (ref->u.ar.as != NULL
2661                   && ref->u.ar.as->rank == 1
2662                   && ref->u.ar.as->type == AS_EXPLICIT
2663                   && ref->u.ar.as->lower[0] != NULL
2664                   && ref->u.ar.as->lower[0]->expr_type == EXPR_CONSTANT
2665                   && ref->u.ar.as->upper[0] != NULL
2666                   && ref->u.ar.as->upper[0]->expr_type == EXPR_CONSTANT)
2667                 {
2668                   /* If we have a character string, we need to check if
2669                      its length is one.  */
2670                   if (expr->ts.type == BT_CHARACTER)
2671                     {
2672                       if (expr->ts.u.cl == NULL
2673                           || expr->ts.u.cl->length == NULL
2674                           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1)
2675                           != 0)
2676                         retval = FAILURE;
2677                     }
2678                   else
2679                     {
2680                       /* We have constant lower and upper bounds.  If the
2681                          difference between is 1, it can be considered a
2682                          scalar.
2683                          FIXME: Use gfc_dep_compare_expr instead.  */
2684                       start = (int) mpz_get_si
2685                                 (ref->u.ar.as->lower[0]->value.integer);
2686                       end = (int) mpz_get_si
2687                                 (ref->u.ar.as->upper[0]->value.integer);
2688                       if (end - start + 1 != 1)
2689                         retval = FAILURE;
2690                    }
2691                 }
2692               else
2693                 retval = FAILURE;
2694             }
2695           else
2696             retval = FAILURE;
2697           break;
2698         default:
2699           retval = SUCCESS;
2700           break;
2701         }
2702     }
2703   else if (expr->ts.type == BT_CHARACTER && expr->rank == 0)
2704     {
2705       /* Character string.  Make sure it's of length 1.  */
2706       if (expr->ts.u.cl == NULL
2707           || expr->ts.u.cl->length == NULL
2708           || mpz_cmp_si (expr->ts.u.cl->length->value.integer, 1) != 0)
2709         retval = FAILURE;
2710     }
2711   else if (expr->rank != 0)
2712     retval = FAILURE;
2713
2714   return retval;
2715 }
2716
2717
2718 /* Match one of the iso_c_binding functions (c_associated or c_loc)
2719    and, in the case of c_associated, set the binding label based on
2720    the arguments.  */
2721
2722 static gfc_try
2723 gfc_iso_c_func_interface (gfc_symbol *sym, gfc_actual_arglist *args,
2724                           gfc_symbol **new_sym)
2725 {
2726   char name[GFC_MAX_SYMBOL_LEN + 1];
2727   int optional_arg = 0;
2728   gfc_try retval = SUCCESS;
2729   gfc_symbol *args_sym;
2730   gfc_typespec *arg_ts;
2731   symbol_attribute arg_attr;
2732
2733   if (args->expr->expr_type == EXPR_CONSTANT
2734       || args->expr->expr_type == EXPR_OP
2735       || args->expr->expr_type == EXPR_NULL)
2736     {
2737       gfc_error ("Argument to '%s' at %L is not a variable",
2738                  sym->name, &(args->expr->where));
2739       return FAILURE;
2740     }
2741
2742   args_sym = args->expr->symtree->n.sym;
2743
2744   /* The typespec for the actual arg should be that stored in the expr
2745      and not necessarily that of the expr symbol (args_sym), because
2746      the actual expression could be a part-ref of the expr symbol.  */
2747   arg_ts = &(args->expr->ts);
2748   arg_attr = gfc_expr_attr (args->expr);
2749
2750   if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2751     {
2752       /* If the user gave two args then they are providing something for
2753          the optional arg (the second cptr).  Therefore, set the name and
2754          binding label to the c_associated for two cptrs.  Otherwise,
2755          set c_associated to expect one cptr.  */
2756       if (args->next)
2757         {
2758           /* two args.  */
2759           sprintf (name, "%s_2", sym->name);
2760           optional_arg = 1;
2761         }
2762       else
2763         {
2764           /* one arg.  */
2765           sprintf (name, "%s_1", sym->name);
2766           optional_arg = 0;
2767         }
2768
2769       /* Get a new symbol for the version of c_associated that
2770          will get called.  */
2771       *new_sym = get_iso_c_sym (sym, name, NULL, optional_arg);
2772     }
2773   else if (sym->intmod_sym_id == ISOCBINDING_LOC
2774            || sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2775     {
2776       sprintf (name, "%s", sym->name);
2777
2778       /* Error check the call.  */
2779       if (args->next != NULL)
2780         {
2781           gfc_error_now ("More actual than formal arguments in '%s' "
2782                          "call at %L", name, &(args->expr->where));
2783           retval = FAILURE;
2784         }
2785       else if (sym->intmod_sym_id == ISOCBINDING_LOC)
2786         {
2787           gfc_ref *ref;
2788           bool seen_section;
2789
2790           /* Make sure we have either the target or pointer attribute.  */
2791           if (!arg_attr.target && !arg_attr.pointer)
2792             {
2793               gfc_error_now ("Parameter '%s' to '%s' at %L must be either "
2794                              "a TARGET or an associated pointer",
2795                              args_sym->name,
2796                              sym->name, &(args->expr->where));
2797               retval = FAILURE;
2798             }
2799
2800           if (gfc_is_coindexed (args->expr))
2801             {
2802               gfc_error_now ("Coindexed argument not permitted"
2803                              " in '%s' call at %L", name,
2804                              &(args->expr->where));
2805               retval = FAILURE;
2806             }
2807
2808           /* Follow references to make sure there are no array
2809              sections.  */
2810           seen_section = false;
2811
2812           for (ref=args->expr->ref; ref; ref = ref->next)
2813             {
2814               if (ref->type == REF_ARRAY)
2815                 {
2816                   if (ref->u.ar.type == AR_SECTION)
2817                     seen_section = true;
2818
2819                   if (ref->u.ar.type != AR_ELEMENT)
2820                     {
2821                       gfc_ref *r;
2822                       for (r = ref->next; r; r=r->next)
2823                         if (r->type == REF_COMPONENT)
2824                           {
2825                             gfc_error_now ("Array section not permitted"
2826                                            " in '%s' call at %L", name,
2827                                            &(args->expr->where));
2828                             retval = FAILURE;
2829                             break;
2830                           }
2831                     }
2832                 }
2833             }
2834
2835           if (seen_section && retval == SUCCESS)
2836             gfc_warning ("Array section in '%s' call at %L", name,
2837                          &(args->expr->where));
2838
2839           /* See if we have interoperable type and type param.  */
2840           if (gfc_verify_c_interop (arg_ts) == SUCCESS
2841               || gfc_check_any_c_kind (arg_ts) == SUCCESS)
2842             {
2843               if (args_sym->attr.target == 1)
2844                 {
2845                   /* Case 1a, section 15.1.2.5, J3/04-007: variable that
2846                      has the target attribute and is interoperable.  */
2847                   /* Case 1b, section 15.1.2.5, J3/04-007: allocated
2848                      allocatable variable that has the TARGET attribute and
2849                      is not an array of zero size.  */
2850                   if (args_sym->attr.allocatable == 1)
2851                     {
2852                       if (args_sym->attr.dimension != 0
2853                           && (args_sym->as && args_sym->as->rank == 0))
2854                         {
2855                           gfc_error_now ("Allocatable variable '%s' used as a "
2856                                          "parameter to '%s' at %L must not be "
2857                                          "an array of zero size",
2858                                          args_sym->name, sym->name,
2859                                          &(args->expr->where));
2860                           retval = FAILURE;
2861                         }
2862                     }
2863                   else
2864                     {
2865                       /* A non-allocatable target variable with C
2866                          interoperable type and type parameters must be
2867                          interoperable.  */
2868                       if (args_sym && args_sym->attr.dimension)
2869                         {
2870                           if (args_sym->as->type == AS_ASSUMED_SHAPE)
2871                             {
2872                               gfc_error ("Assumed-shape array '%s' at %L "
2873                                          "cannot be an argument to the "
2874                                          "procedure '%s' because "
2875                                          "it is not C interoperable",
2876                                          args_sym->name,
2877                                          &(args->expr->where), sym->name);
2878                               retval = FAILURE;
2879                             }
2880                           else if (args_sym->as->type == AS_DEFERRED)
2881                             {
2882                               gfc_error ("Deferred-shape array '%s' at %L "
2883                                          "cannot be an argument to the "
2884                                          "procedure '%s' because "
2885                                          "it is not C interoperable",
2886                                          args_sym->name,
2887                                          &(args->expr->where), sym->name);
2888                               retval = FAILURE;
2889                             }
2890                         }
2891
2892                       /* Make sure it's not a character string.  Arrays of
2893                          any type should be ok if the variable is of a C
2894                          interoperable type.  */
2895                       if (arg_ts->type == BT_CHARACTER)
2896                         if (arg_ts->u.cl != NULL
2897                             && (arg_ts->u.cl->length == NULL
2898                                 || arg_ts->u.cl->length->expr_type
2899                                    != EXPR_CONSTANT
2900                                 || mpz_cmp_si
2901                                     (arg_ts->u.cl->length->value.integer, 1)
2902                                    != 0)
2903                             && is_scalar_expr_ptr (args->expr) != SUCCESS)
2904                           {
2905                             gfc_error_now ("CHARACTER argument '%s' to '%s' "
2906                                            "at %L must have a length of 1",
2907                                            args_sym->name, sym->name,
2908                                            &(args->expr->where));
2909                             retval = FAILURE;
2910                           }
2911                     }
2912                 }
2913               else if (arg_attr.pointer
2914                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2915                 {
2916                   /* Case 1c, section 15.1.2.5, J3/04-007: an associated
2917                      scalar pointer.  */
2918                   gfc_error_now ("Argument '%s' to '%s' at %L must be an "
2919                                  "associated scalar POINTER", args_sym->name,
2920                                  sym->name, &(args->expr->where));
2921                   retval = FAILURE;
2922                 }
2923             }
2924           else
2925             {
2926               /* The parameter is not required to be C interoperable.  If it
2927                  is not C interoperable, it must be a nonpolymorphic scalar
2928                  with no length type parameters.  It still must have either
2929                  the pointer or target attribute, and it can be
2930                  allocatable (but must be allocated when c_loc is called).  */
2931               if (args->expr->rank != 0
2932                   && is_scalar_expr_ptr (args->expr) != SUCCESS)
2933                 {
2934                   gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2935                                  "scalar", args_sym->name, sym->name,
2936                                  &(args->expr->where));
2937                   retval = FAILURE;
2938                 }
2939               else if (arg_ts->type == BT_CHARACTER
2940                        && is_scalar_expr_ptr (args->expr) != SUCCESS)
2941                 {
2942                   gfc_error_now ("CHARACTER argument '%s' to '%s' at "
2943                                  "%L must have a length of 1",
2944                                  args_sym->name, sym->name,
2945                                  &(args->expr->where));
2946                   retval = FAILURE;
2947                 }
2948               else if (arg_ts->type == BT_CLASS)
2949                 {
2950                   gfc_error_now ("Parameter '%s' to '%s' at %L must not be "
2951                                  "polymorphic", args_sym->name, sym->name,
2952                                  &(args->expr->where));
2953                   retval = FAILURE;
2954                 }
2955             }
2956         }
2957       else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2958         {
2959           if (args_sym->attr.flavor != FL_PROCEDURE)
2960             {
2961               /* TODO: Update this error message to allow for procedure
2962                  pointers once they are implemented.  */
2963               gfc_error_now ("Parameter '%s' to '%s' at %L must be a "
2964                              "procedure",
2965                              args_sym->name, sym->name,
2966                              &(args->expr->where));
2967               retval = FAILURE;
2968             }
2969           else if (args_sym->attr.is_bind_c != 1)
2970             {
2971               gfc_error_now ("Parameter '%s' to '%s' at %L must be "
2972                              "BIND(C)",
2973                              args_sym->name, sym->name,
2974                              &(args->expr->where));
2975               retval = FAILURE;
2976             }
2977         }
2978
2979       /* for c_loc/c_funloc, the new symbol is the same as the old one */
2980       *new_sym = sym;
2981     }
2982   else
2983     {
2984       gfc_internal_error ("gfc_iso_c_func_interface(): Unhandled "
2985                           "iso_c_binding function: '%s'!\n", sym->name);
2986     }
2987
2988   return retval;
2989 }
2990
2991
2992 /* Resolve a function call, which means resolving the arguments, then figuring
2993    out which entity the name refers to.  */
2994
2995 static gfc_try
2996 resolve_function (gfc_expr *expr)
2997 {
2998   gfc_actual_arglist *arg;
2999   gfc_symbol *sym;
3000   const char *name;
3001   gfc_try t;
3002   int temp;
3003   procedure_type p = PROC_INTRINSIC;
3004   bool no_formal_args;
3005
3006   sym = NULL;
3007   if (expr->symtree)
3008     sym = expr->symtree->n.sym;
3009
3010   /* If this is a procedure pointer component, it has already been resolved.  */
3011   if (gfc_is_proc_ptr_comp (expr, NULL))
3012     return SUCCESS;
3013
3014   if (sym && sym->attr.intrinsic
3015       && resolve_intrinsic (sym, &expr->where) == FAILURE)
3016     return FAILURE;
3017
3018   if (sym && (sym->attr.flavor == FL_VARIABLE || sym->attr.subroutine))
3019     {
3020       gfc_error ("'%s' at %L is not a function", sym->name, &expr->where);
3021       return FAILURE;
3022     }
3023
3024   /* If this ia a deferred TBP with an abstract interface (which may
3025      of course be referenced), expr->value.function.esym will be set.  */
3026   if (sym && sym->attr.abstract && !expr->value.function.esym)
3027     {
3028       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3029                  sym->name, &expr->where);
3030       return FAILURE;
3031     }
3032
3033   /* Switch off assumed size checking and do this again for certain kinds
3034      of procedure, once the procedure itself is resolved.  */
3035   need_full_assumed_size++;
3036
3037   if (expr->symtree && expr->symtree->n.sym)
3038     p = expr->symtree->n.sym->attr.proc;
3039
3040   if (expr->value.function.isym && expr->value.function.isym->inquiry)
3041     inquiry_argument = true;
3042   no_formal_args = sym && is_external_proc (sym) && sym->formal == NULL;
3043
3044   if (resolve_actual_arglist (expr->value.function.actual,
3045                               p, no_formal_args) == FAILURE)
3046     {
3047       inquiry_argument = false;
3048       return FAILURE;
3049     }
3050
3051   inquiry_argument = false;
3052
3053   /* Need to setup the call to the correct c_associated, depending on
3054      the number of cptrs to user gives to compare.  */
3055   if (sym && sym->attr.is_iso_c == 1)
3056     {
3057       if (gfc_iso_c_func_interface (sym, expr->value.function.actual, &sym)
3058           == FAILURE)
3059         return FAILURE;
3060
3061       /* Get the symtree for the new symbol (resolved func).
3062          the old one will be freed later, when it's no longer used.  */
3063       gfc_find_sym_tree (sym->name, sym->ns, 1, &(expr->symtree));
3064     }
3065
3066   /* Resume assumed_size checking.  */
3067   need_full_assumed_size--;
3068
3069   /* If the procedure is external, check for usage.  */
3070   if (sym && is_external_proc (sym))
3071     resolve_global_procedure (sym, &expr->where,
3072                               &expr->value.function.actual, 0);
3073
3074   if (sym && sym->ts.type == BT_CHARACTER
3075       && sym->ts.u.cl
3076       && sym->ts.u.cl->length == NULL
3077       && !sym->attr.dummy
3078       && !sym->ts.deferred
3079       && expr->value.function.esym == NULL
3080       && !sym->attr.contained)
3081     {
3082       /* Internal procedures are taken care of in resolve_contained_fntype.  */
3083       gfc_error ("Function '%s' is declared CHARACTER(*) and cannot "
3084                  "be used at %L since it is not a dummy argument",
3085                  sym->name, &expr->where);
3086       return FAILURE;
3087     }
3088
3089   /* See if function is already resolved.  */
3090
3091   if (expr->value.function.name != NULL)
3092     {
3093       if (expr->ts.type == BT_UNKNOWN)
3094         expr->ts = sym->ts;
3095       t = SUCCESS;
3096     }
3097   else
3098     {
3099       /* Apply the rules of section 14.1.2.  */
3100
3101       switch (procedure_kind (sym))
3102         {
3103         case PTYPE_GENERIC:
3104           t = resolve_generic_f (expr);
3105           break;
3106
3107         case PTYPE_SPECIFIC:
3108           t = resolve_specific_f (expr);
3109           break;
3110
3111         case PTYPE_UNKNOWN:
3112           t = resolve_unknown_f (expr);
3113           break;
3114
3115         default:
3116           gfc_internal_error ("resolve_function(): bad function type");
3117         }
3118     }
3119
3120   /* If the expression is still a function (it might have simplified),
3121      then we check to see if we are calling an elemental function.  */
3122
3123   if (expr->expr_type != EXPR_FUNCTION)
3124     return t;
3125
3126   temp = need_full_assumed_size;
3127   need_full_assumed_size = 0;
3128
3129   if (resolve_elemental_actual (expr, NULL) == FAILURE)
3130     return FAILURE;
3131
3132   if (omp_workshare_flag
3133       && expr->value.function.esym
3134       && ! gfc_elemental (expr->value.function.esym))
3135     {
3136       gfc_error ("User defined non-ELEMENTAL function '%s' at %L not allowed "
3137                  "in WORKSHARE construct", expr->value.function.esym->name,
3138                  &expr->where);
3139       t = FAILURE;
3140     }
3141
3142 #define GENERIC_ID expr->value.function.isym->id
3143   else if (expr->value.function.actual != NULL
3144            && expr->value.function.isym != NULL
3145            && GENERIC_ID != GFC_ISYM_LBOUND
3146            && GENERIC_ID != GFC_ISYM_LEN
3147            && GENERIC_ID != GFC_ISYM_LOC
3148            && GENERIC_ID != GFC_ISYM_PRESENT)
3149     {
3150       /* Array intrinsics must also have the last upper bound of an
3151          assumed size array argument.  UBOUND and SIZE have to be
3152          excluded from the check if the second argument is anything
3153          than a constant.  */
3154
3155       for (arg = expr->value.function.actual; arg; arg = arg->next)
3156         {
3157           if ((GENERIC_ID == GFC_ISYM_UBOUND || GENERIC_ID == GFC_ISYM_SIZE)
3158               && arg == expr->value.function.actual
3159               && arg->next != NULL && arg->next->expr)
3160             {
3161               if (arg->next->expr->expr_type != EXPR_CONSTANT)
3162                 break;
3163
3164               if (arg->next->name && strncmp(arg->next->name, "kind", 4) == 0)
3165                 break;
3166
3167               if ((int)mpz_get_si (arg->next->expr->value.integer)
3168                         < arg->expr->rank)
3169                 break;
3170             }
3171
3172           if (arg->expr != NULL
3173               && arg->expr->rank > 0
3174               && resolve_assumed_size_actual (arg->expr))
3175             return FAILURE;
3176         }
3177     }
3178 #undef GENERIC_ID
3179
3180   need_full_assumed_size = temp;
3181   name = NULL;
3182
3183   if (!pure_function (expr, &name) && name)
3184     {
3185       if (forall_flag)
3186         {
3187           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
3188                      "FORALL %s", name, &expr->where,
3189                      forall_flag == 2 ? "mask" : "block");
3190           t = FAILURE;
3191         }
3192       else if (do_concurrent_flag)
3193         {
3194           gfc_error ("Reference to non-PURE function '%s' at %L inside a "
3195                      "DO CONCURRENT %s", name, &expr->where,
3196                      do_concurrent_flag == 2 ? "mask" : "block");
3197           t = FAILURE;
3198         }
3199       else if (gfc_pure (NULL))
3200         {
3201           gfc_error ("Function reference to '%s' at %L is to a non-PURE "
3202                      "procedure within a PURE procedure", name, &expr->where);
3203           t = FAILURE;
3204         }
3205
3206       if (gfc_implicit_pure (NULL))
3207         gfc_current_ns->proc_name->attr.implicit_pure = 0;
3208     }
3209
3210   /* Functions without the RECURSIVE attribution are not allowed to
3211    * call themselves.  */
3212   if (expr->value.function.esym && !expr->value.function.esym->attr.recursive)
3213     {
3214       gfc_symbol *esym;
3215       esym = expr->value.function.esym;
3216
3217       if (is_illegal_recursion (esym, gfc_current_ns))
3218       {
3219         if (esym->attr.entry && esym->ns->entries)
3220           gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3221                      " function '%s' is not RECURSIVE",
3222                      esym->name, &expr->where, esym->ns->entries->sym->name);
3223         else
3224           gfc_error ("Function '%s' at %L cannot be called recursively, as it"
3225                      " is not RECURSIVE", esym->name, &expr->where);
3226
3227         t = FAILURE;
3228       }
3229     }
3230
3231   /* Character lengths of use associated functions may contains references to
3232      symbols not referenced from the current program unit otherwise.  Make sure
3233      those symbols are marked as referenced.  */
3234
3235   if (expr->ts.type == BT_CHARACTER && expr->value.function.esym
3236       && expr->value.function.esym->attr.use_assoc)
3237     {
3238       gfc_expr_set_symbols_referenced (expr->ts.u.cl->length);
3239     }
3240
3241   /* Make sure that the expression has a typespec that works.  */
3242   if (expr->ts.type == BT_UNKNOWN)
3243     {
3244       if (expr->symtree->n.sym->result
3245             && expr->symtree->n.sym->result->ts.type != BT_UNKNOWN
3246             && !expr->symtree->n.sym->result->attr.proc_pointer)
3247         expr->ts = expr->symtree->n.sym->result->ts;
3248     }
3249
3250   return t;
3251 }
3252
3253
3254 /************* Subroutine resolution *************/
3255
3256 static void
3257 pure_subroutine (gfc_code *c, gfc_symbol *sym)
3258 {
3259   if (gfc_pure (sym))
3260     return;
3261
3262   if (forall_flag)
3263     gfc_error ("Subroutine call to '%s' in FORALL block at %L is not PURE",
3264                sym->name, &c->loc);
3265   else if (do_concurrent_flag)
3266     gfc_error ("Subroutine call to '%s' in DO CONCURRENT block at %L is not "
3267                "PURE", sym->name, &c->loc);
3268   else if (gfc_pure (NULL))
3269     gfc_error ("Subroutine call to '%s' at %L is not PURE", sym->name,
3270                &c->loc);
3271
3272   if (gfc_implicit_pure (NULL))
3273     gfc_current_ns->proc_name->attr.implicit_pure = 0;
3274 }
3275
3276
3277 static match
3278 resolve_generic_s0 (gfc_code *c, gfc_symbol *sym)
3279 {
3280   gfc_symbol *s;
3281
3282   if (sym->attr.generic)
3283     {
3284       s = gfc_search_interface (sym->generic, 1, &c->ext.actual);
3285       if (s != NULL)
3286         {
3287           c->resolved_sym = s;
3288           pure_subroutine (c, s);
3289           return MATCH_YES;
3290         }
3291
3292       /* TODO: Need to search for elemental references in generic interface.  */
3293     }
3294
3295   if (sym->attr.intrinsic)
3296     return gfc_intrinsic_sub_interface (c, 0);
3297
3298   return MATCH_NO;
3299 }
3300
3301
3302 static gfc_try
3303 resolve_generic_s (gfc_code *c)
3304 {
3305   gfc_symbol *sym;
3306   match m;
3307
3308   sym = c->symtree->n.sym;
3309
3310   for (;;)
3311     {
3312       m = resolve_generic_s0 (c, sym);
3313       if (m == MATCH_YES)
3314         return SUCCESS;
3315       else if (m == MATCH_ERROR)
3316         return FAILURE;
3317
3318 generic:
3319       if (sym->ns->parent == NULL)
3320         break;
3321       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3322
3323       if (sym == NULL)
3324         break;
3325       if (!generic_sym (sym))
3326         goto generic;
3327     }
3328
3329   /* Last ditch attempt.  See if the reference is to an intrinsic
3330      that possesses a matching interface.  14.1.2.4  */
3331   sym = c->symtree->n.sym;
3332
3333   if (!gfc_is_intrinsic (sym, 1, c->loc))
3334     {
3335       gfc_error ("There is no specific subroutine for the generic '%s' at %L",
3336                  sym->name, &c->loc);
3337       return FAILURE;
3338     }
3339
3340   m = gfc_intrinsic_sub_interface (c, 0);
3341   if (m == MATCH_YES)
3342     return SUCCESS;
3343   if (m == MATCH_NO)
3344     gfc_error ("Generic subroutine '%s' at %L is not consistent with an "
3345                "intrinsic subroutine interface", sym->name, &c->loc);
3346
3347   return FAILURE;
3348 }
3349
3350
3351 /* Set the name and binding label of the subroutine symbol in the call
3352    expression represented by 'c' to include the type and kind of the
3353    second parameter.  This function is for resolving the appropriate
3354    version of c_f_pointer() and c_f_procpointer().  For example, a
3355    call to c_f_pointer() for a default integer pointer could have a
3356    name of c_f_pointer_i4.  If no second arg exists, which is an error
3357    for these two functions, it defaults to the generic symbol's name
3358    and binding label.  */
3359
3360 static void
3361 set_name_and_label (gfc_code *c, gfc_symbol *sym,
3362                     char *name, const char **binding_label)
3363 {
3364   gfc_expr *arg = NULL;
3365   char type;
3366   int kind;
3367
3368   /* The second arg of c_f_pointer and c_f_procpointer determines
3369      the type and kind for the procedure name.  */
3370   arg = c->ext.actual->next->expr;
3371
3372   if (arg != NULL)
3373     {
3374       /* Set up the name to have the given symbol's name,
3375          plus the type and kind.  */
3376       /* a derived type is marked with the type letter 'u' */
3377       if (arg->ts.type == BT_DERIVED)
3378         {
3379           type = 'd';
3380           kind = 0; /* set the kind as 0 for now */
3381         }
3382       else
3383         {
3384           type = gfc_type_letter (arg->ts.type);
3385           kind = arg->ts.kind;
3386         }
3387
3388       if (arg->ts.type == BT_CHARACTER)
3389         /* Kind info for character strings not needed.  */
3390         kind = 0;
3391
3392       sprintf (name, "%s_%c%d", sym->name, type, kind);
3393       /* Set up the binding label as the given symbol's label plus
3394          the type and kind.  */
3395       *binding_label = gfc_get_string ("%s_%c%d", sym->binding_label, type,
3396                                        kind);
3397     }
3398   else
3399     {
3400       /* If the second arg is missing, set the name and label as
3401          was, cause it should at least be found, and the missing
3402          arg error will be caught by compare_parameters().  */
3403       sprintf (name, "%s", sym->name);
3404       *binding_label = sym->binding_label;
3405     }
3406
3407   return;
3408 }
3409
3410
3411 /* Resolve a generic version of the iso_c_binding procedure given
3412    (sym) to the specific one based on the type and kind of the
3413    argument(s).  Currently, this function resolves c_f_pointer() and
3414    c_f_procpointer based on the type and kind of the second argument
3415    (FPTR).  Other iso_c_binding procedures aren't specially handled.
3416    Upon successfully exiting, c->resolved_sym will hold the resolved
3417    symbol.  Returns MATCH_ERROR if an error occurred; MATCH_YES
3418    otherwise.  */
3419
3420 match
3421 gfc_iso_c_sub_interface (gfc_code *c, gfc_symbol *sym)
3422 {
3423   gfc_symbol *new_sym;
3424   /* this is fine, since we know the names won't use the max */
3425   char name[GFC_MAX_SYMBOL_LEN + 1];
3426   const char* binding_label;
3427   /* default to success; will override if find error */
3428   match m = MATCH_YES;
3429
3430   /* Make sure the actual arguments are in the necessary order (based on the
3431      formal args) before resolving.  */
3432   gfc_procedure_use (sym, &c->ext.actual, &(c->loc));
3433
3434   if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER) ||
3435       (sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER))
3436     {
3437       set_name_and_label (c, sym, name, &binding_label);
3438
3439       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER)
3440         {
3441           if (c->ext.actual != NULL && c->ext.actual->next != NULL)
3442             {
3443               /* Make sure we got a third arg if the second arg has non-zero
3444                  rank.  We must also check that the type and rank are
3445                  correct since we short-circuit this check in
3446                  gfc_procedure_use() (called above to sort actual args).  */
3447               if (c->ext.actual->next->expr->rank != 0)
3448                 {
3449                   if(c->ext.actual->next->next == NULL
3450                      || c->ext.actual->next->next->expr == NULL)
3451                     {
3452                       m = MATCH_ERROR;
3453                       gfc_error ("Missing SHAPE parameter for call to %s "
3454                                  "at %L", sym->name, &(c->loc));
3455                     }
3456                   else if (c->ext.actual->next->next->expr->ts.type
3457                            != BT_INTEGER
3458                            || c->ext.actual->next->next->expr->rank != 1)
3459                     {
3460                       m = MATCH_ERROR;
3461                       gfc_error ("SHAPE parameter for call to %s at %L must "
3462                                  "be a rank 1 INTEGER array", sym->name,
3463                                  &(c->loc));
3464                     }
3465                 }
3466             }
3467         }
3468
3469       if (m != MATCH_ERROR)
3470         {
3471           /* the 1 means to add the optional arg to formal list */
3472           new_sym = get_iso_c_sym (sym, name, binding_label, 1);
3473
3474           /* for error reporting, say it's declared where the original was */
3475           new_sym->declared_at = sym->declared_at;
3476         }
3477     }
3478   else
3479     {
3480       /* no differences for c_loc or c_funloc */
3481       new_sym = sym;
3482     }
3483
3484   /* set the resolved symbol */
3485   if (m != MATCH_ERROR)
3486     c->resolved_sym = new_sym;
3487   else
3488     c->resolved_sym = sym;
3489
3490   return m;
3491 }
3492
3493
3494 /* Resolve a subroutine call known to be specific.  */
3495
3496 static match
3497 resolve_specific_s0 (gfc_code *c, gfc_symbol *sym)
3498 {
3499   match m;
3500
3501   if(sym->attr.is_iso_c)
3502     {
3503       m = gfc_iso_c_sub_interface (c,sym);
3504       return m;
3505     }
3506
3507   if (sym->attr.external || sym->attr.if_source == IFSRC_IFBODY)
3508     {
3509       if (sym->attr.dummy)
3510         {
3511           sym->attr.proc = PROC_DUMMY;
3512           goto found;
3513         }
3514
3515       sym->attr.proc = PROC_EXTERNAL;
3516       goto found;
3517     }
3518
3519   if (sym->attr.proc == PROC_MODULE || sym->attr.proc == PROC_INTERNAL)
3520     goto found;
3521
3522   if (sym->attr.intrinsic)
3523     {
3524       m = gfc_intrinsic_sub_interface (c, 1);
3525       if (m == MATCH_YES)
3526         return MATCH_YES;
3527       if (m == MATCH_NO)
3528         gfc_error ("Subroutine '%s' at %L is INTRINSIC but is not compatible "
3529                    "with an intrinsic", sym->name, &c->loc);
3530
3531       return MATCH_ERROR;
3532     }
3533
3534   return MATCH_NO;
3535
3536 found:
3537   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3538
3539   c->resolved_sym = sym;
3540   pure_subroutine (c, sym);
3541
3542   return MATCH_YES;
3543 }
3544
3545
3546 static gfc_try
3547 resolve_specific_s (gfc_code *c)
3548 {
3549   gfc_symbol *sym;
3550   match m;
3551
3552   sym = c->symtree->n.sym;
3553
3554   for (;;)
3555     {
3556       m = resolve_specific_s0 (c, sym);
3557       if (m == MATCH_YES)
3558         return SUCCESS;
3559       if (m == MATCH_ERROR)
3560         return FAILURE;
3561
3562       if (sym->ns->parent == NULL)
3563         break;
3564
3565       gfc_find_symbol (sym->name, sym->ns->parent, 1, &sym);
3566
3567       if (sym == NULL)
3568         break;
3569     }
3570
3571   sym = c->symtree->n.sym;
3572   gfc_error ("Unable to resolve the specific subroutine '%s' at %L",
3573              sym->name, &c->loc);
3574
3575   return FAILURE;
3576 }
3577
3578
3579 /* Resolve a subroutine call not known to be generic nor specific.  */
3580
3581 static gfc_try
3582 resolve_unknown_s (gfc_code *c)
3583 {
3584   gfc_symbol *sym;
3585
3586   sym = c->symtree->n.sym;
3587
3588   if (sym->attr.dummy)
3589     {
3590       sym->attr.proc = PROC_DUMMY;
3591       goto found;
3592     }
3593
3594   /* See if we have an intrinsic function reference.  */
3595
3596   if (gfc_is_intrinsic (sym, 1, c->loc))
3597     {
3598       if (gfc_intrinsic_sub_interface (c, 1) == MATCH_YES)
3599         return SUCCESS;
3600       return FAILURE;
3601     }
3602
3603   /* The reference is to an external name.  */
3604
3605 found:
3606   gfc_procedure_use (sym, &c->ext.actual, &c->loc);
3607
3608   c->resolved_sym = sym;
3609
3610   pure_subroutine (c, sym);
3611
3612   return SUCCESS;
3613 }
3614
3615
3616 /* Resolve a subroutine call.  Although it was tempting to use the same code
3617    for functions, subroutines and functions are stored differently and this
3618    makes things awkward.  */
3619
3620 static gfc_try
3621 resolve_call (gfc_code *c)
3622 {
3623   gfc_try t;
3624   procedure_type ptype = PROC_INTRINSIC;
3625   gfc_symbol *csym, *sym;
3626   bool no_formal_args;
3627
3628   csym = c->symtree ? c->symtree->n.sym : NULL;
3629
3630   if (csym && csym->ts.type != BT_UNKNOWN)
3631     {
3632       gfc_error ("'%s' at %L has a type, which is not consistent with "
3633                  "the CALL at %L", csym->name, &csym->declared_at, &c->loc);
3634       return FAILURE;
3635     }
3636
3637   if (csym && gfc_current_ns->parent && csym->ns != gfc_current_ns)
3638     {
3639       gfc_symtree *st;
3640       gfc_find_sym_tree (c->symtree->name, gfc_current_ns, 1, &st);
3641       sym = st ? st->n.sym : NULL;
3642       if (sym && csym != sym
3643               && sym->ns == gfc_current_ns
3644               && sym->attr.flavor == FL_PROCEDURE
3645               && sym->attr.contained)
3646         {
3647           sym->refs++;
3648           if (csym->attr.generic)
3649             c->symtree->n.sym = sym;
3650           else
3651             c->symtree = st;
3652           csym = c->symtree->n.sym;
3653         }
3654     }
3655
3656   /* If this ia a deferred TBP with an abstract interface
3657      (which may of course be referenced), c->expr1 will be set.  */
3658   if (csym && csym->attr.abstract && !c->expr1)
3659     {
3660       gfc_error ("ABSTRACT INTERFACE '%s' must not be referenced at %L",
3661                  csym->name, &c->loc);
3662       return FAILURE;
3663     }
3664
3665   /* Subroutines without the RECURSIVE attribution are not allowed to
3666    * call themselves.  */
3667   if (csym && is_illegal_recursion (csym, gfc_current_ns))
3668     {
3669       if (csym->attr.entry && csym->ns->entries)
3670         gfc_error ("ENTRY '%s' at %L cannot be called recursively, as"
3671                    " subroutine '%s' is not RECURSIVE",
3672                    csym->name, &c->loc, csym->ns->entries->sym->name);
3673       else
3674         gfc_error ("SUBROUTINE '%s' at %L cannot be called recursively, as it"
3675                    " is not RECURSIVE", csym->name, &c->loc);
3676
3677       t = FAILURE;
3678     }
3679
3680   /* Switch off assumed size checking and do this again for certain kinds
3681      of procedure, once the procedure itself is resolved.  */
3682   need_full_assumed_size++;
3683
3684   if (csym)
3685     ptype = csym->attr.proc;
3686
3687   no_formal_args = csym && is_external_proc (csym) && csym->formal == NULL;
3688   if (resolve_actual_arglist (c->ext.actual, ptype,
3689                               no_formal_args) == FAILURE)
3690     return FAILURE;
3691
3692   /* Resume assumed_size checking.  */
3693   need_full_assumed_size--;
3694
3695   /* If external, check for usage.  */
3696   if (csym && is_external_proc (csym))
3697     resolve_global_procedure (csym, &c->loc, &c->ext.actual, 1);
3698
3699   t = SUCCESS;
3700   if (c->resolved_sym == NULL)
3701     {
3702       c->resolved_isym = NULL;
3703       switch (procedure_kind (csym))
3704         {
3705         case PTYPE_GENERIC:
3706           t = resolve_generic_s (c);
3707           break;
3708
3709         case PTYPE_SPECIFIC:
3710           t = resolve_specific_s (c);
3711           break;
3712
3713         case PTYPE_UNKNOWN:
3714           t = resolve_unknown_s (c);
3715           break;
3716
3717         default:
3718           gfc_internal_error ("resolve_subroutine(): bad function type");
3719         }
3720     }
3721
3722   /* Some checks of elemental subroutine actual arguments.  */
3723   if (resolve_elemental_actual (NULL, c) == FAILURE)
3724     return FAILURE;
3725
3726   return t;
3727 }
3728
3729
3730 /* Compare the shapes of two arrays that have non-NULL shapes.  If both
3731    op1->shape and op2->shape are non-NULL return SUCCESS if their shapes
3732    match.  If both op1->shape and op2->shape are non-NULL return FAILURE
3733    if their shapes do not match.  If either op1->shape or op2->shape is
3734    NULL, return SUCCESS.  */
3735
3736 static gfc_try
3737 compare_shapes (gfc_expr *op1, gfc_expr *op2)
3738 {
3739   gfc_try t;
3740   int i;
3741
3742   t = SUCCESS;
3743
3744   if (op1->shape != NULL && op2->shape != NULL)
3745     {
3746       for (i = 0; i < op1->rank; i++)
3747         {
3748           if (mpz_cmp (op1->shape[i], op2->shape[i]) != 0)
3749            {
3750              gfc_error ("Shapes for operands at %L and %L are not conformable",
3751                          &op1->where, &op2->where);
3752              t = FAILURE;
3753              break;
3754            }
3755         }
3756     }
3757
3758   return t;
3759 }
3760
3761
3762 /* Resolve an operator expression node.  This can involve replacing the
3763    operation with a user defined function call.  */
3764
3765 static gfc_try
3766 resolve_operator (gfc_expr *e)
3767 {
3768   gfc_expr *op1, *op2;
3769   char msg[200];
3770   bool dual_locus_error;
3771   gfc_try t;
3772
3773   /* Resolve all subnodes-- give them types.  */
3774
3775   switch (e->value.op.op)
3776     {
3777     default:
3778       if (gfc_resolve_expr (e->value.op.op2) == FAILURE)
3779         return FAILURE;
3780
3781     /* Fall through...  */
3782
3783     case INTRINSIC_NOT:
3784     case INTRINSIC_UPLUS:
3785     case INTRINSIC_UMINUS:
3786     case INTRINSIC_PARENTHESES:
3787       if (gfc_resolve_expr (e->value.op.op1) == FAILURE)
3788         return FAILURE;
3789       break;
3790     }
3791
3792   /* Typecheck the new node.  */
3793
3794   op1 = e->value.op.op1;
3795   op2 = e->value.op.op2;
3796   dual_locus_error = false;
3797
3798   if ((op1 && op1->expr_type == EXPR_NULL)
3799       || (op2 && op2->expr_type == EXPR_NULL))
3800     {
3801       sprintf (msg, _("Invalid context for NULL() pointer at %%L"));
3802       goto bad_op;
3803     }
3804
3805   switch (e->value.op.op)
3806     {
3807     case INTRINSIC_UPLUS:
3808     case INTRINSIC_UMINUS:
3809       if (op1->ts.type == BT_INTEGER
3810           || op1->ts.type == BT_REAL
3811           || op1->ts.type == BT_COMPLEX)
3812         {
3813           e->ts = op1->ts;
3814           break;
3815         }
3816
3817       sprintf (msg, _("Operand of unary numeric operator '%s' at %%L is %s"),
3818                gfc_op2string (e->value.op.op), gfc_typename (&e->ts));
3819       goto bad_op;
3820
3821     case INTRINSIC_PLUS:
3822     case INTRINSIC_MINUS:
3823     case INTRINSIC_TIMES:
3824     case INTRINSIC_DIVIDE:
3825     case INTRINSIC_POWER:
3826       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3827         {
3828           gfc_type_convert_binary (e, 1);
3829           break;
3830         }
3831
3832       sprintf (msg,
3833                _("Operands of binary numeric operator '%s' at %%L are %s/%s"),
3834                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3835                gfc_typename (&op2->ts));
3836       goto bad_op;
3837
3838     case INTRINSIC_CONCAT:
3839       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3840           && op1->ts.kind == op2->ts.kind)
3841         {
3842           e->ts.type = BT_CHARACTER;
3843           e->ts.kind = op1->ts.kind;
3844           break;
3845         }
3846
3847       sprintf (msg,
3848                _("Operands of string concatenation operator at %%L are %s/%s"),
3849                gfc_typename (&op1->ts), gfc_typename (&op2->ts));
3850       goto bad_op;
3851
3852     case INTRINSIC_AND:
3853     case INTRINSIC_OR:
3854     case INTRINSIC_EQV:
3855     case INTRINSIC_NEQV:
3856       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3857         {
3858           e->ts.type = BT_LOGICAL;
3859           e->ts.kind = gfc_kind_max (op1, op2);
3860           if (op1->ts.kind < e->ts.kind)
3861             gfc_convert_type (op1, &e->ts, 2);
3862           else if (op2->ts.kind < e->ts.kind)
3863             gfc_convert_type (op2, &e->ts, 2);
3864           break;
3865         }
3866
3867       sprintf (msg, _("Operands of logical operator '%s' at %%L are %s/%s"),
3868                gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3869                gfc_typename (&op2->ts));
3870
3871       goto bad_op;
3872
3873     case INTRINSIC_NOT:
3874       if (op1->ts.type == BT_LOGICAL)
3875         {
3876           e->ts.type = BT_LOGICAL;
3877           e->ts.kind = op1->ts.kind;
3878           break;
3879         }
3880
3881       sprintf (msg, _("Operand of .not. operator at %%L is %s"),
3882                gfc_typename (&op1->ts));
3883       goto bad_op;
3884
3885     case INTRINSIC_GT:
3886     case INTRINSIC_GT_OS:
3887     case INTRINSIC_GE:
3888     case INTRINSIC_GE_OS:
3889     case INTRINSIC_LT:
3890     case INTRINSIC_LT_OS:
3891     case INTRINSIC_LE:
3892     case INTRINSIC_LE_OS:
3893       if (op1->ts.type == BT_COMPLEX || op2->ts.type == BT_COMPLEX)
3894         {
3895           strcpy (msg, _("COMPLEX quantities cannot be compared at %L"));
3896           goto bad_op;
3897         }
3898
3899       /* Fall through...  */
3900
3901     case INTRINSIC_EQ:
3902     case INTRINSIC_EQ_OS:
3903     case INTRINSIC_NE:
3904     case INTRINSIC_NE_OS:
3905       if (op1->ts.type == BT_CHARACTER && op2->ts.type == BT_CHARACTER
3906           && op1->ts.kind == op2->ts.kind)
3907         {
3908           e->ts.type = BT_LOGICAL;
3909           e->ts.kind = gfc_default_logical_kind;
3910           break;
3911         }
3912
3913       if (gfc_numeric_ts (&op1->ts) && gfc_numeric_ts (&op2->ts))
3914         {
3915           gfc_type_convert_binary (e, 1);
3916
3917           e->ts.type = BT_LOGICAL;
3918           e->ts.kind = gfc_default_logical_kind;
3919           break;
3920         }
3921
3922       if (op1->ts.type == BT_LOGICAL && op2->ts.type == BT_LOGICAL)
3923         sprintf (msg,
3924                  _("Logicals at %%L must be compared with %s instead of %s"),
3925                  (e->value.op.op == INTRINSIC_EQ
3926                   || e->value.op.op == INTRINSIC_EQ_OS)
3927                  ? ".eqv." : ".neqv.", gfc_op2string (e->value.op.op));
3928       else
3929         sprintf (msg,
3930                  _("Operands of comparison operator '%s' at %%L are %s/%s"),
3931                  gfc_op2string (e->value.op.op), gfc_typename (&op1->ts),
3932                  gfc_typename (&op2->ts));
3933
3934       goto bad_op;
3935
3936     case INTRINSIC_USER:
3937       if (e->value.op.uop->op == NULL)
3938         sprintf (msg, _("Unknown operator '%s' at %%L"), e->value.op.uop->name);
3939       else if (op2 == NULL)
3940         sprintf (msg, _("Operand of user operator '%s' at %%L is %s"),
3941                  e->value.op.uop->name, gfc_typename (&op1->ts));
3942       else
3943         {
3944           sprintf (msg, _("Operands of user operator '%s' at %%L are %s/%s"),
3945                    e->value.op.uop->name, gfc_typename (&op1->ts),
3946                    gfc_typename (&op2->ts));
3947           e->value.op.uop->op->sym->attr.referenced = 1;
3948         }
3949
3950       goto bad_op;
3951
3952     case INTRINSIC_PARENTHESES:
3953       e->ts = op1->ts;
3954       if (e->ts.type == BT_CHARACTER)
3955         e->ts.u.cl = op1->ts.u.cl;
3956       break;
3957
3958     default:
3959       gfc_internal_error ("resolve_operator(): Bad intrinsic");
3960     }
3961
3962   /* Deal with arrayness of an operand through an operator.  */
3963
3964   t = SUCCESS;
3965
3966   switch (e->value.op.op)
3967     {
3968     case INTRINSIC_PLUS:
3969     case INTRINSIC_MINUS:
3970     case INTRINSIC_TIMES:
3971     case INTRINSIC_DIVIDE:
3972     case INTRINSIC_POWER:
3973     case INTRINSIC_CONCAT:
3974     case INTRINSIC_AND:
3975     case INTRINSIC_OR:
3976     case INTRINSIC_EQV:
3977     case INTRINSIC_NEQV:
3978     case INTRINSIC_EQ:
3979     case INTRINSIC_EQ_OS:
3980     case INTRINSIC_NE:
3981     case INTRINSIC_NE_OS:
3982     case INTRINSIC_GT:
3983     case INTRINSIC_GT_OS:
3984     case INTRINSIC_GE:
3985     case INTRINSIC_GE_OS:
3986     case INTRINSIC_LT:
3987     case INTRINSIC_LT_OS:
3988     case INTRINSIC_LE:
3989     case INTRINSIC_LE_OS:
3990
3991       if (op1->rank == 0 && op2->rank == 0)
3992         e->rank = 0;
3993
3994       if (op1->rank == 0 && op2->rank != 0)
3995         {
3996           e->rank = op2->rank;
3997
3998           if (e->shape == NULL)
3999             e->shape = gfc_copy_shape (op2->shape, op2->rank);
4000         }
4001
4002       if (op1->rank != 0 && op2->rank == 0)
4003         {
4004           e->rank = op1->rank;
4005
4006           if (e->shape == NULL)
4007             e->shape = gfc_copy_shape (op1->shape, op1->rank);
4008         }
4009
4010       if (op1->rank != 0 && op2->rank != 0)
4011         {
4012           if (op1->rank == op2->rank)
4013             {
4014               e->rank = op1->rank;
4015               if (e->shape == NULL)
4016                 {
4017                   t = compare_shapes (op1, op2);
4018                   if (t == FAILURE)
4019                     e->shape = NULL;
4020                   else
4021                     e->shape = gfc_copy_shape (op1->shape, op1->rank);
4022                 }
4023             }
4024           else
4025             {
4026               /* Allow higher level expressions to work.  */
4027               e->rank = 0;
4028
4029               /* Try user-defined operators, and otherwise throw an error.  */
4030               dual_locus_error = true;
4031               sprintf (msg,
4032                        _("Inconsistent ranks for operator at %%L and %%L"));
4033               goto bad_op;
4034             }
4035         }
4036
4037       break;
4038
4039     case INTRINSIC_PARENTHESES:
4040     case INTRINSIC_NOT:
4041     case INTRINSIC_UPLUS:
4042     case INTRINSIC_UMINUS:
4043       /* Simply copy arrayness attribute */
4044       e->rank = op1->rank;
4045
4046       if (e->shape == NULL)
4047         e->shape = gfc_copy_shape (op1->shape, op1->rank);
4048
4049       break;
4050
4051     default:
4052       break;
4053     }
4054
4055   /* Attempt to simplify the expression.  */
4056   if (t == SUCCESS)
4057     {
4058       t = gfc_simplify_expr (e, 0);
4059       /* Some calls do not succeed in simplification and return FAILURE
4060          even though there is no error; e.g. variable references to
4061          PARAMETER arrays.  */
4062       if (!gfc_is_constant_expr (e))
4063         t = SUCCESS;
4064     }
4065   return t;
4066
4067 bad_op:
4068
4069   {
4070     match m = gfc_extend_expr (e);
4071     if (m == MATCH_YES)
4072       return SUCCESS;
4073     if (m == MATCH_ERROR)
4074       return FAILURE;
4075   }
4076
4077   if (dual_locus_error)
4078     gfc_error (msg, &op1->where, &op2->where);
4079   else
4080     gfc_error (msg, &e->where);
4081
4082   return FAILURE;
4083 }
4084
4085
4086 /************** Array resolution subroutines **************/
4087
4088 typedef enum
4089 { CMP_LT, CMP_EQ, CMP_GT, CMP_UNKNOWN }
4090 comparison;
4091
4092 /* Compare two integer expressions.  */
4093
4094 static comparison
4095 compare_bound (gfc_expr *a, gfc_expr *b)
4096 {
4097   int i;
4098
4099   if (a == NULL || a->expr_type != EXPR_CONSTANT
4100       || b == NULL || b->expr_type != EXPR_CONSTANT)
4101     return CMP_UNKNOWN;
4102
4103   /* If either of the types isn't INTEGER, we must have
4104      raised an error earlier.  */
4105
4106   if (a->ts.type != BT_INTEGER || b->ts.type != BT_INTEGER)
4107     return CMP_UNKNOWN;
4108
4109   i = mpz_cmp (a->value.integer, b->value.integer);
4110
4111   if (i < 0)
4112     return CMP_LT;
4113   if (i > 0)
4114     return CMP_GT;
4115   return CMP_EQ;
4116 }
4117
4118
4119 /* Compare an integer expression with an integer.  */
4120
4121 static comparison
4122 compare_bound_int (gfc_expr *a, int b)
4123 {
4124   int i;
4125
4126   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4127     return CMP_UNKNOWN;
4128
4129   if (a->ts.type != BT_INTEGER)
4130     gfc_internal_error ("compare_bound_int(): Bad expression");
4131
4132   i = mpz_cmp_si (a->value.integer, b);
4133
4134   if (i < 0)
4135     return CMP_LT;
4136   if (i > 0)
4137     return CMP_GT;
4138   return CMP_EQ;
4139 }
4140
4141
4142 /* Compare an integer expression with a mpz_t.  */
4143
4144 static comparison
4145 compare_bound_mpz_t (gfc_expr *a, mpz_t b)
4146 {
4147   int i;
4148
4149   if (a == NULL || a->expr_type != EXPR_CONSTANT)
4150     return CMP_UNKNOWN;
4151
4152   if (a->ts.type != BT_INTEGER)
4153     gfc_internal_error ("compare_bound_int(): Bad expression");
4154
4155   i = mpz_cmp (a->value.integer, b);
4156
4157   if (i < 0)
4158     return CMP_LT;
4159   if (i > 0)
4160     return CMP_GT;
4161   return CMP_EQ;
4162 }
4163
4164
4165 /* Compute the last value of a sequence given by a triplet.
4166    Return 0 if it wasn't able to compute the last value, or if the
4167    sequence if empty, and 1 otherwise.  */
4168
4169 static int
4170 compute_last_value_for_triplet (gfc_expr *start, gfc_expr *end,
4171                                 gfc_expr *stride, mpz_t last)
4172 {
4173   mpz_t rem;
4174
4175   if (start == NULL || start->expr_type != EXPR_CONSTANT
4176       || end == NULL || end->expr_type != EXPR_CONSTANT
4177       || (stride != NULL && stride->expr_type != EXPR_CONSTANT))
4178     return 0;
4179
4180   if (start->ts.type != BT_INTEGER || end->ts.type != BT_INTEGER
4181       || (stride != NULL && stride->ts.type != BT_INTEGER))
4182     return 0;
4183
4184   if (stride == NULL || compare_bound_int(stride, 1) == CMP_EQ)
4185     {
4186       if (compare_bound (start, end) == CMP_GT)
4187         return 0;
4188       mpz_set (last, end->value.integer);
4189       return 1;
4190     }
4191
4192   if (compare_bound_int (stride, 0) == CMP_GT)
4193     {
4194       /* Stride is positive */
4195       if (mpz_cmp (start->value.integer, end->value.integer) > 0)
4196         return 0;
4197     }
4198   else
4199     {
4200       /* Stride is negative */
4201       if (mpz_cmp (start->value.integer, end->value.integer) < 0)
4202         return 0;
4203     }
4204
4205   mpz_init (rem);
4206   mpz_sub (rem, end->value.integer, start->value.integer);
4207   mpz_tdiv_r (rem, rem, stride->value.integer);
4208   mpz_sub (last, end->value.integer, rem);
4209   mpz_clear (rem);
4210
4211   return 1;
4212 }
4213
4214
4215 /* Compare a single dimension of an array reference to the array
4216    specification.  */
4217
4218 static gfc_try
4219 check_dimension (int i, gfc_array_ref *ar, gfc_array_spec *as)
4220 {
4221   mpz_t last_value;
4222
4223   if (ar->dimen_type[i] == DIMEN_STAR)
4224     {
4225       gcc_assert (ar->stride[i] == NULL);
4226       /* This implies [*] as [*:] and [*:3] are not possible.  */
4227       if (ar->start[i] == NULL)
4228         {
4229           gcc_assert (ar->end[i] == NULL);
4230           return SUCCESS;
4231         }
4232     }
4233
4234 /* Given start, end and stride values, calculate the minimum and
4235    maximum referenced indexes.  */
4236
4237   switch (ar->dimen_type[i])
4238     {
4239     case DIMEN_VECTOR:
4240     case DIMEN_THIS_IMAGE:
4241       break;
4242
4243     case DIMEN_STAR:
4244     case DIMEN_ELEMENT:
4245       if (compare_bound (ar->start[i], as->lower[i]) == CMP_LT)
4246         {
4247           if (i < as->rank)
4248             gfc_warning ("Array reference at %L is out of bounds "
4249                          "(%ld < %ld) in dimension %d", &ar->c_where[i],
4250                          mpz_get_si (ar->start[i]->value.integer),
4251                          mpz_get_si (as->lower[i]->value.integer), i+1);
4252           else
4253             gfc_warning ("Array reference at %L is out of bounds "
4254                          "(%ld < %ld) in codimension %d", &ar->c_where[i],
4255                          mpz_get_si (ar->start[i]->value.integer),
4256                          mpz_get_si (as->lower[i]->value.integer),
4257                          i + 1 - as->rank);
4258           return SUCCESS;
4259         }
4260       if (compare_bound (ar->start[i], as->upper[i]) == CMP_GT)
4261         {
4262           if (i < as->rank)
4263             gfc_warning ("Array reference at %L is out of bounds "
4264                          "(%ld > %ld) in dimension %d", &ar->c_where[i],
4265                          mpz_get_si (ar->start[i]->value.integer),
4266                          mpz_get_si (as->upper[i]->value.integer), i+1);
4267           else
4268             gfc_warning ("Array reference at %L is out of bounds "
4269                          "(%ld > %ld) in codimension %d", &ar->c_where[i],
4270                          mpz_get_si (ar->start[i]->value.integer),
4271                          mpz_get_si (as->upper[i]->value.integer),
4272                          i + 1 - as->rank);
4273           return SUCCESS;
4274         }
4275
4276       break;
4277
4278     case DIMEN_RANGE:
4279       {
4280 #define AR_START (ar->start[i] ? ar->start[i] : as->lower[i])
4281 #define AR_END (ar->end[i] ? ar->end[i] : as->upper[i])
4282
4283         comparison comp_start_end = compare_bound (AR_START, AR_END);
4284
4285         /* Check for zero stride, which is not allowed.  */
4286         if (compare_bound_int (ar->stride[i], 0) == CMP_EQ)
4287           {
4288             gfc_error ("Illegal stride of zero at %L", &ar->c_where[i]);
4289             return FAILURE;
4290           }
4291
4292         /* if start == len || (stride > 0 && start < len)
4293                            || (stride < 0 && start > len),
4294            then the array section contains at least one element.  In this
4295            case, there is an out-of-bounds access if
4296            (start < lower || start > upper).  */
4297         if (compare_bound (AR_START, AR_END) == CMP_EQ
4298             || ((compare_bound_int (ar->stride[i], 0) == CMP_GT
4299                  || ar->stride[i] == NULL) && comp_start_end == CMP_LT)
4300             || (compare_bound_int (ar->stride[i], 0) == CMP_LT
4301                 && comp_start_end == CMP_GT))
4302           {
4303             if (compare_bound (AR_START, as->lower[i]) == CMP_LT)
4304               {
4305                 gfc_warning ("Lower array reference at %L is out of bounds "
4306                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4307                        mpz_get_si (AR_START->value.integer),
4308                        mpz_get_si (as->lower[i]->value.integer), i+1);
4309                 return SUCCESS;
4310               }
4311             if (compare_bound (AR_START, as->upper[i]) == CMP_GT)
4312               {
4313                 gfc_warning ("Lower array reference at %L is out of bounds "
4314                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4315                        mpz_get_si (AR_START->value.integer),
4316                        mpz_get_si (as->upper[i]->value.integer), i+1);
4317                 return SUCCESS;
4318               }
4319           }
4320
4321         /* If we can compute the highest index of the array section,
4322            then it also has to be between lower and upper.  */
4323         mpz_init (last_value);
4324         if (compute_last_value_for_triplet (AR_START, AR_END, ar->stride[i],
4325                                             last_value))
4326           {
4327             if (compare_bound_mpz_t (as->lower[i], last_value) == CMP_GT)
4328               {
4329                 gfc_warning ("Upper array reference at %L is out of bounds "
4330                        "(%ld < %ld) in dimension %d", &ar->c_where[i],
4331                        mpz_get_si (last_value),
4332                        mpz_get_si (as->lower[i]->value.integer), i+1);
4333                 mpz_clear (last_value);
4334                 return SUCCESS;
4335               }
4336             if (compare_bound_mpz_t (as->upper[i], last_value) == CMP_LT)
4337               {
4338                 gfc_warning ("Upper array reference at %L is out of bounds "
4339                        "(%ld > %ld) in dimension %d", &ar->c_where[i],
4340                        mpz_get_si (last_value),
4341                        mpz_get_si (as->upper[i]->value.integer), i+1);
4342                 mpz_clear (last_value);
4343                 return SUCCESS;
4344               }
4345           }
4346         mpz_clear (last_value);
4347
4348 #undef AR_START
4349 #undef AR_END
4350       }
4351       break;
4352
4353     default:
4354       gfc_internal_error ("check_dimension(): Bad array reference");
4355     }
4356
4357   return SUCCESS;
4358 }
4359
4360
4361 /* Compare an array reference with an array specification.  */
4362
4363 static gfc_try
4364 compare_spec_to_ref (gfc_array_ref *ar)
4365 {
4366   gfc_array_spec *as;
4367   int i;
4368
4369   as = ar->as;
4370   i = as->rank - 1;
4371   /* TODO: Full array sections are only allowed as actual parameters.  */
4372   if (as->type == AS_ASSUMED_SIZE
4373       && (/*ar->type == AR_FULL
4374           ||*/ (ar->type == AR_SECTION
4375               && ar->dimen_type[i] == DIMEN_RANGE && ar->end[i] == NULL)))
4376     {
4377       gfc_error ("Rightmost upper bound of assumed size array section "
4378                  "not specified at %L", &ar->where);
4379       return FAILURE;
4380     }
4381
4382   if (ar->type == AR_FULL)
4383     return SUCCESS;
4384
4385   if (as->rank != ar->dimen)
4386     {
4387       gfc_error ("Rank mismatch in array reference at %L (%d/%d)",
4388                  &ar->where, ar->dimen, as->rank);
4389       return FAILURE;
4390     }
4391
4392   /* ar->codimen == 0 is a local array.  */
4393   if (as->corank != ar->codimen && ar->codimen != 0)
4394     {
4395       gfc_error ("Coindex rank mismatch in array reference at %L (%d/%d)",
4396                  &ar->where, ar->codimen, as->corank);
4397       return FAILURE;
4398     }
4399
4400   for (i = 0; i < as->rank; i++)
4401     if (check_dimension (i, ar, as) == FAILURE)
4402       return FAILURE;
4403
4404   /* Local access has no coarray spec.  */
4405   if (ar->codimen != 0)
4406     for (i = as->rank; i < as->rank + as->corank; i++)
4407       {
4408         if (ar->dimen_type[i] != DIMEN_ELEMENT && !ar->in_allocate
4409             && ar->dimen_type[i] != DIMEN_THIS_IMAGE)
4410           {
4411             gfc_error ("Coindex of codimension %d must be a scalar at %L",
4412                        i + 1 - as->rank, &ar->where);
4413             return FAILURE;
4414           }
4415         if (check_dimension (i, ar, as) == FAILURE)
4416           return FAILURE;
4417       }
4418
4419   return SUCCESS;
4420 }
4421
4422
4423 /* Resolve one part of an array index.  */
4424
4425 static gfc_try
4426 gfc_resolve_index_1 (gfc_expr *index, int check_scalar,
4427                      int force_index_integer_kind)
4428 {
4429   gfc_typespec ts;
4430
4431   if (index == NULL)
4432     return SUCCESS;
4433
4434   if (gfc_resolve_expr (index) == FAILURE)
4435     return FAILURE;
4436
4437   if (check_scalar && index->rank != 0)
4438     {
4439       gfc_error ("Array index at %L must be scalar", &index->where);
4440       return FAILURE;
4441     }
4442
4443   if (index->ts.type != BT_INTEGER && index->ts.type != BT_REAL)
4444     {
4445       gfc_error ("Array index at %L must be of INTEGER type, found %s",
4446                  &index->where, gfc_basic_typename (index->ts.type));
4447       return FAILURE;
4448     }
4449
4450   if (index->ts.type == BT_REAL)
4451     if (gfc_notify_std (GFC_STD_LEGACY, "Extension: REAL array index at %L",
4452                         &index->where) == FAILURE)
4453       return FAILURE;
4454
4455   if ((index->ts.kind != gfc_index_integer_kind
4456        && force_index_integer_kind)
4457       || index->ts.type != BT_INTEGER)
4458     {
4459       gfc_clear_ts (&ts);
4460       ts.type = BT_INTEGER;
4461       ts.kind = gfc_index_integer_kind;
4462
4463       gfc_convert_type_warn (index, &ts, 2, 0);
4464     }
4465
4466   return SUCCESS;
4467 }
4468
4469 /* Resolve one part of an array index.  */
4470
4471 gfc_try
4472 gfc_resolve_index (gfc_expr *index, int check_scalar)
4473 {
4474   return gfc_resolve_index_1 (index, check_scalar, 1);
4475 }
4476
4477 /* Resolve a dim argument to an intrinsic function.  */
4478
4479 gfc_try
4480 gfc_resolve_dim_arg (gfc_expr *dim)
4481 {
4482   if (dim == NULL)
4483     return SUCCESS;
4484
4485   if (gfc_resolve_expr (dim) == FAILURE)
4486     return FAILURE;
4487
4488   if (dim->rank != 0)
4489     {
4490       gfc_error ("Argument dim at %L must be scalar", &dim->where);
4491       return FAILURE;
4492
4493     }
4494
4495   if (dim->ts.type != BT_INTEGER)
4496     {
4497       gfc_error ("Argument dim at %L must be of INTEGER type", &dim->where);
4498       return FAILURE;
4499     }
4500
4501   if (dim->ts.kind != gfc_index_integer_kind)
4502     {
4503       gfc_typespec ts;
4504
4505       gfc_clear_ts (&ts);
4506       ts.type = BT_INTEGER;
4507       ts.kind = gfc_index_integer_kind;
4508
4509       gfc_convert_type_warn (dim, &ts, 2, 0);
4510     }
4511
4512   return SUCCESS;
4513 }
4514
4515 /* Given an expression that contains array references, update those array
4516    references to point to the right array specifications.  While this is
4517    filled in during matching, this information is difficult to save and load
4518    in a module, so we take care of it here.
4519
4520    The idea here is that the original array reference comes from the
4521    base symbol.  We traverse the list of reference structures, setting
4522    the stored reference to references.  Component references can
4523    provide an additional array specification.  */
4524
4525 static void
4526 find_array_spec (gfc_expr *e)
4527 {
4528   gfc_array_spec *as;
4529   gfc_component *c;
4530   gfc_ref *ref;
4531
4532   if (e->symtree->n.sym->ts.type == BT_CLASS)
4533     as = CLASS_DATA (e->symtree->n.sym)->as;
4534   else
4535     as = e->symtree->n.sym->as;
4536
4537   for (ref = e->ref; ref; ref = ref->next)
4538     switch (ref->type)
4539       {
4540       case REF_ARRAY:
4541         if (as == NULL)
4542           gfc_internal_error ("find_array_spec(): Missing spec");
4543
4544         ref->u.ar.as = as;
4545         as = NULL;
4546         break;
4547
4548       case REF_COMPONENT:
4549         c = ref->u.c.component;
4550         if (c->attr.dimension)
4551           {
4552             if (as != NULL)
4553               gfc_internal_error ("find_array_spec(): unused as(1)");
4554             as = c->as;
4555           }
4556
4557         break;
4558
4559       case REF_SUBSTRING:
4560         break;
4561       }
4562
4563   if (as != NULL)
4564     gfc_internal_error ("find_array_spec(): unused as(2)");
4565 }
4566
4567
4568 /* Resolve an array reference.  */
4569
4570 static gfc_try
4571 resolve_array_ref (gfc_array_ref *ar)
4572 {
4573   int i, check_scalar;
4574   gfc_expr *e;
4575
4576   for (i = 0; i < ar->dimen + ar->codimen; i++)
4577     {
4578       check_scalar = ar->dimen_type[i] == DIMEN_RANGE;
4579
4580       /* Do not force gfc_index_integer_kind for the start.  We can
4581          do fine with any integer kind.  This avoids temporary arrays
4582          created for indexing with a vector.  */
4583       if (gfc_resolve_index_1 (ar->start[i], check_scalar, 0) == FAILURE)
4584         return FAILURE;
4585       if (gfc_resolve_index (ar->end[i], check_scalar) == FAILURE)
4586         return FAILURE;
4587       if (gfc_resolve_index (ar->stride[i], check_scalar) == FAILURE)
4588         return FAILURE;
4589
4590       e = ar->start[i];
4591
4592       if (ar->dimen_type[i] == DIMEN_UNKNOWN)
4593         switch (e->rank)
4594           {
4595           case 0:
4596             ar->dimen_type[i] = DIMEN_ELEMENT;
4597             break;
4598
4599           case 1:
4600             ar->dimen_type[i] = DIMEN_VECTOR;
4601             if (e->expr_type == EXPR_VARIABLE
4602                 && e->symtree->n.sym->ts.type == BT_DERIVED)
4603               ar->start[i] = gfc_get_parentheses (e);
4604             break;
4605
4606           default:
4607             gfc_error ("Array index at %L is an array of rank %d",
4608                        &ar->c_where[i], e->rank);
4609             return FAILURE;
4610           }
4611
4612       /* Fill in the upper bound, which may be lower than the
4613          specified one for something like a(2:10:5), which is
4614          identical to a(2:7:5).  Only relevant for strides not equal
4615          to one.  Don't try a division by zero.  */
4616       if (ar->dimen_type[i] == DIMEN_RANGE
4617           && ar->stride[i] != NULL && ar->stride[i]->expr_type == EXPR_CONSTANT
4618           && mpz_cmp_si (ar->stride[i]->value.integer, 1L) != 0
4619           && mpz_cmp_si (ar->stride[i]->value.integer, 0L) != 0)
4620         {
4621           mpz_t size, end;
4622
4623           if (gfc_ref_dimen_size (ar, i, &size, &end) == SUCCESS)
4624             {
4625               if (ar->end[i] == NULL)
4626                 {
4627                   ar->end[i] =
4628                     gfc_get_constant_expr (BT_INTEGER, gfc_index_integer_kind,
4629                                            &ar->where);
4630                   mpz_set (ar->end[i]->value.integer, end);
4631                 }
4632               else if (ar->end[i]->ts.type == BT_INTEGER
4633                        && ar->end[i]->expr_type == EXPR_CONSTANT)
4634                 {
4635                   mpz_set (ar->end[i]->value.integer, end);
4636                 }
4637               else
4638                 gcc_unreachable ();
4639
4640               mpz_clear (size);
4641               mpz_clear (end);
4642             }
4643         }
4644     }
4645
4646   if (ar->type == AR_FULL)
4647     {
4648       if (ar->as->rank == 0)
4649         ar->type = AR_ELEMENT;
4650
4651       /* Make sure array is the same as array(:,:), this way
4652          we don't need to special case all the time.  */
4653       ar->dimen = ar->as->rank;
4654       for (i = 0; i < ar->dimen; i++)
4655         {
4656           ar->dimen_type[i] = DIMEN_RANGE;
4657
4658           gcc_assert (ar->start[i] == NULL);
4659           gcc_assert (ar->end[i] == NULL);
4660           gcc_assert (ar->stride[i] == NULL);
4661         }
4662     }
4663
4664   /* If the reference type is unknown, figure out what kind it is.  */
4665
4666   if (ar->type == AR_UNKNOWN)
4667     {
4668       ar->type = AR_ELEMENT;
4669       for (i = 0; i < ar->dimen; i++)
4670         if (ar->dimen_type[i] == DIMEN_RANGE
4671             || ar->dimen_type[i] == DIMEN_VECTOR)
4672           {
4673             ar->type = AR_SECTION;
4674             break;
4675           }
4676     }
4677
4678   if (!ar->as->cray_pointee && compare_spec_to_ref (ar) == FAILURE)
4679     return FAILURE;
4680
4681   if (ar->as->corank && ar->codimen == 0)
4682     {
4683       int n;
4684       ar->codimen = ar->as->corank;
4685       for (n = ar->dimen; n < ar->dimen + ar->codimen; n++)
4686         ar->dimen_type[n] = DIMEN_THIS_IMAGE;
4687     }
4688
4689   return SUCCESS;
4690 }
4691
4692
4693 static gfc_try
4694 resolve_substring (gfc_ref *ref)
4695 {
4696   int k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
4697
4698   if (ref->u.ss.start != NULL)
4699     {
4700       if (gfc_resolve_expr (ref->u.ss.start) == FAILURE)
4701         return FAILURE;
4702
4703       if (ref->u.ss.start->ts.type != BT_INTEGER)
4704         {
4705           gfc_error ("Substring start index at %L must be of type INTEGER",
4706                      &ref->u.ss.start->where);
4707           return FAILURE;
4708         }
4709
4710       if (ref->u.ss.start->rank != 0)
4711         {
4712           gfc_error ("Substring start index at %L must be scalar",
4713                      &ref->u.ss.start->where);
4714           return FAILURE;
4715         }
4716
4717       if (compare_bound_int (ref->u.ss.start, 1) == CMP_LT
4718           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4719               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4720         {
4721           gfc_error ("Substring start index at %L is less than one",
4722                      &ref->u.ss.start->where);
4723           return FAILURE;
4724         }
4725     }
4726
4727   if (ref->u.ss.end != NULL)
4728     {
4729       if (gfc_resolve_expr (ref->u.ss.end) == FAILURE)
4730         return FAILURE;
4731
4732       if (ref->u.ss.end->ts.type != BT_INTEGER)
4733         {
4734           gfc_error ("Substring end index at %L must be of type INTEGER",
4735                      &ref->u.ss.end->where);
4736           return FAILURE;
4737         }
4738
4739       if (ref->u.ss.end->rank != 0)
4740         {
4741           gfc_error ("Substring end index at %L must be scalar",
4742                      &ref->u.ss.end->where);
4743           return FAILURE;
4744         }
4745
4746       if (ref->u.ss.length != NULL
4747           && compare_bound (ref->u.ss.end, ref->u.ss.length->length) == CMP_GT
4748           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4749               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4750         {
4751           gfc_error ("Substring end index at %L exceeds the string length",
4752                      &ref->u.ss.start->where);
4753           return FAILURE;
4754         }
4755
4756       if (compare_bound_mpz_t (ref->u.ss.end,
4757                                gfc_integer_kinds[k].huge) == CMP_GT
4758           && (compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_EQ
4759               || compare_bound (ref->u.ss.end, ref->u.ss.start) == CMP_GT))
4760         {
4761           gfc_error ("Substring end index at %L is too large",
4762                      &ref->u.ss.end->where);
4763           return FAILURE;
4764         }
4765     }
4766
4767   return SUCCESS;
4768 }
4769
4770
4771 /* This function supplies missing substring charlens.  */
4772
4773 void
4774 gfc_resolve_substring_charlen (gfc_expr *e)
4775 {
4776   gfc_ref *char_ref;
4777   gfc_expr *start, *end;
4778
4779   for (char_ref = e->ref; char_ref; char_ref = char_ref->next)
4780     if (char_ref->type == REF_SUBSTRING)
4781       break;
4782
4783   if (!char_ref)
4784     return;
4785
4786   gcc_assert (char_ref->next == NULL);
4787
4788   if (e->ts.u.cl)
4789     {
4790       if (e->ts.u.cl->length)
4791         gfc_free_expr (e->ts.u.cl->length);
4792       else if (e->expr_type == EXPR_VARIABLE
4793                  && e->symtree->n.sym->attr.dummy)
4794         return;
4795     }
4796
4797   e->ts.type = BT_CHARACTER;
4798   e->ts.kind = gfc_default_character_kind;
4799
4800   if (!e->ts.u.cl)
4801     e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
4802
4803   if (char_ref->u.ss.start)
4804     start = gfc_copy_expr (char_ref->u.ss.start);
4805   else
4806     start = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
4807
4808   if (char_ref->u.ss.end)
4809     end = gfc_copy_expr (char_ref->u.ss.end);
4810   else if (e->expr_type == EXPR_VARIABLE)
4811     end = gfc_copy_expr (e->symtree->n.sym->ts.u.cl->length);
4812   else
4813     end = NULL;
4814
4815   if (!start || !end)
4816     return;
4817
4818   /* Length = (end - start +1).  */
4819   e->ts.u.cl->length = gfc_subtract (end, start);
4820   e->ts.u.cl->length = gfc_add (e->ts.u.cl->length,
4821                                 gfc_get_int_expr (gfc_default_integer_kind,
4822                                                   NULL, 1));
4823
4824   e->ts.u.cl->length->ts.type = BT_INTEGER;
4825   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
4826
4827   /* Make sure that the length is simplified.  */
4828   gfc_simplify_expr (e->ts.u.cl->length, 1);
4829   gfc_resolve_expr (e->ts.u.cl->length);
4830 }
4831
4832
4833 /* Resolve subtype references.  */
4834
4835 static gfc_try
4836 resolve_ref (gfc_expr *expr)
4837 {
4838   int current_part_dimension, n_components, seen_part_dimension;
4839   gfc_ref *ref;
4840
4841   for (ref = expr->ref; ref; ref = ref->next)
4842     if (ref->type == REF_ARRAY && ref->u.ar.as == NULL)
4843       {
4844         find_array_spec (expr);
4845         break;
4846       }
4847
4848   for (ref = expr->ref; ref; ref = ref->next)
4849     switch (ref->type)
4850       {
4851       case REF_ARRAY:
4852         if (resolve_array_ref (&ref->u.ar) == FAILURE)
4853           return FAILURE;
4854         break;
4855
4856       case REF_COMPONENT:
4857         break;
4858
4859       case REF_SUBSTRING:
4860         if (resolve_substring (ref) == FAILURE)
4861           return FAILURE;
4862         break;
4863       }
4864
4865   /* Check constraints on part references.  */
4866
4867   current_part_dimension = 0;
4868   seen_part_dimension = 0;
4869   n_components = 0;
4870
4871   for (ref = expr->ref; ref; ref = ref->next)
4872     {
4873       switch (ref->type)
4874         {
4875         case REF_ARRAY:
4876           switch (ref->u.ar.type)
4877             {
4878             case AR_FULL:
4879               /* Coarray scalar.  */
4880               if (ref->u.ar.as->rank == 0)
4881                 {
4882                   current_part_dimension = 0;
4883                   break;
4884                 }
4885               /* Fall through.  */
4886             case AR_SECTION:
4887               current_part_dimension = 1;
4888               break;
4889
4890             case AR_ELEMENT:
4891               current_part_dimension = 0;
4892               break;
4893
4894             case AR_UNKNOWN:
4895               gfc_internal_error ("resolve_ref(): Bad array reference");
4896             }
4897
4898           break;
4899
4900         case REF_COMPONENT:
4901           if (current_part_dimension || seen_part_dimension)
4902             {
4903               /* F03:C614.  */
4904               if (ref->u.c.component->attr.pointer
4905                   || ref->u.c.component->attr.proc_pointer)
4906                 {
4907                   gfc_error ("Component to the right of a part reference "
4908                              "with nonzero rank must not have the POINTER "
4909                              "attribute at %L", &expr->where);
4910                   return FAILURE;
4911                 }
4912               else if (ref->u.c.component->attr.allocatable)
4913                 {
4914                   gfc_error ("Component to the right of a part reference "
4915                              "with nonzero rank must not have the ALLOCATABLE "
4916                              "attribute at %L", &expr->where);
4917                   return FAILURE;
4918                 }
4919             }
4920
4921           n_components++;
4922           break;
4923
4924         case REF_SUBSTRING:
4925           break;
4926         }
4927
4928       if (((ref->type == REF_COMPONENT && n_components > 1)
4929            || ref->next == NULL)
4930           && current_part_dimension
4931           && seen_part_dimension)
4932         {
4933           gfc_error ("Two or more part references with nonzero rank must "
4934                      "not be specified at %L", &expr->where);
4935           return FAILURE;
4936         }
4937
4938       if (ref->type == REF_COMPONENT)
4939         {
4940           if (current_part_dimension)
4941             seen_part_dimension = 1;
4942
4943           /* reset to make sure */
4944           current_part_dimension = 0;
4945         }
4946     }
4947
4948   return SUCCESS;
4949 }
4950
4951
4952 /* Given an expression, determine its shape.  This is easier than it sounds.
4953    Leaves the shape array NULL if it is not possible to determine the shape.  */
4954
4955 static void
4956 expression_shape (gfc_expr *e)
4957 {
4958   mpz_t array[GFC_MAX_DIMENSIONS];
4959   int i;
4960
4961   if (e->rank == 0 || e->shape != NULL)
4962     return;
4963
4964   for (i = 0; i < e->rank; i++)
4965     if (gfc_array_dimen_size (e, i, &array[i]) == FAILURE)
4966       goto fail;
4967
4968   e->shape = gfc_get_shape (e->rank);
4969
4970   memcpy (e->shape, array, e->rank * sizeof (mpz_t));
4971
4972   return;
4973
4974 fail:
4975   for (i--; i >= 0; i--)
4976     mpz_clear (array[i]);
4977 }
4978
4979
4980 /* Given a variable expression node, compute the rank of the expression by
4981    examining the base symbol and any reference structures it may have.  */
4982
4983 static void
4984 expression_rank (gfc_expr *e)
4985 {
4986   gfc_ref *ref;
4987   int i, rank;
4988
4989   /* Just to make sure, because EXPR_COMPCALL's also have an e->ref and that
4990      could lead to serious confusion...  */
4991   gcc_assert (e->expr_type != EXPR_COMPCALL);
4992
4993   if (e->ref == NULL)
4994     {
4995       if (e->expr_type == EXPR_ARRAY)
4996         goto done;
4997       /* Constructors can have a rank different from one via RESHAPE().  */
4998
4999       if (e->symtree == NULL)
5000         {
5001           e->rank = 0;
5002           goto done;
5003         }
5004
5005       e->rank = (e->symtree->n.sym->as == NULL)
5006                 ? 0 : e->symtree->n.sym->as->rank;
5007       goto done;
5008     }
5009
5010   rank = 0;
5011
5012   for (ref = e->ref; ref; ref = ref->next)
5013     {
5014       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.proc_pointer
5015           && ref->u.c.component->attr.function && !ref->next)
5016         rank = ref->u.c.component->as ? ref->u.c.component->as->rank : 0;
5017
5018       if (ref->type != REF_ARRAY)
5019         continue;
5020
5021       if (ref->u.ar.type == AR_FULL)
5022         {
5023           rank = ref->u.ar.as->rank;
5024           break;
5025         }
5026
5027       if (ref->u.ar.type == AR_SECTION)
5028         {
5029           /* Figure out the rank of the section.  */
5030           if (rank != 0)
5031             gfc_internal_error ("expression_rank(): Two array specs");
5032
5033           for (i = 0; i < ref->u.ar.dimen; i++)
5034             if (ref->u.ar.dimen_type[i] == DIMEN_RANGE
5035                 || ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
5036               rank++;
5037
5038           break;
5039         }
5040     }
5041
5042   e->rank = rank;
5043
5044 done:
5045   expression_shape (e);
5046 }
5047
5048
5049 /* Resolve a variable expression.  */
5050
5051 static gfc_try
5052 resolve_variable (gfc_expr *e)
5053 {
5054   gfc_symbol *sym;
5055   gfc_try t;
5056
5057   t = SUCCESS;
5058
5059   if (e->symtree == NULL)
5060     return FAILURE;
5061   sym = e->symtree->n.sym;
5062
5063   /* If this is an associate-name, it may be parsed with an array reference
5064      in error even though the target is scalar.  Fail directly in this case.  */
5065   if (sym->assoc && !sym->attr.dimension && e->ref && e->ref->type == REF_ARRAY)
5066     return FAILURE;
5067
5068   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.generic)
5069     sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
5070
5071   /* On the other hand, the parser may not have known this is an array;
5072      in this case, we have to add a FULL reference.  */
5073   if (sym->assoc && sym->attr.dimension && !e->ref)
5074     {
5075       e->ref = gfc_get_ref ();
5076       e->ref->type = REF_ARRAY;
5077       e->ref->u.ar.type = AR_FULL;
5078       e->ref->u.ar.dimen = 0;
5079     }
5080
5081   if (e->ref && resolve_ref (e) == FAILURE)
5082     return FAILURE;
5083
5084   if (sym->attr.flavor == FL_PROCEDURE
5085       && (!sym->attr.function
5086           || (sym->attr.function && sym->result
5087               && sym->result->attr.proc_pointer
5088               && !sym->result->attr.function)))
5089     {
5090       e->ts.type = BT_PROCEDURE;
5091       goto resolve_procedure;
5092     }
5093
5094   if (sym->ts.type != BT_UNKNOWN)
5095     gfc_variable_attr (e, &e->ts);
5096   else
5097     {
5098       /* Must be a simple variable reference.  */
5099       if (gfc_set_default_type (sym, 1, sym->ns) == FAILURE)
5100         return FAILURE;
5101       e->ts = sym->ts;
5102     }
5103
5104   if (check_assumed_size_reference (sym, e))
5105     return FAILURE;
5106
5107   /* Deal with forward references to entries during resolve_code, to
5108      satisfy, at least partially, 12.5.2.5.  */
5109   if (gfc_current_ns->entries
5110       && current_entry_id == sym->entry_id
5111       && cs_base
5112       && cs_base->current
5113       && cs_base->current->op != EXEC_ENTRY)
5114     {
5115       gfc_entry_list *entry;
5116       gfc_formal_arglist *formal;
5117       int n;
5118       bool seen;
5119
5120       /* If the symbol is a dummy...  */
5121       if (sym->attr.dummy && sym->ns == gfc_current_ns)
5122         {
5123           entry = gfc_current_ns->entries;
5124           seen = false;
5125
5126           /* ...test if the symbol is a parameter of previous entries.  */
5127           for (; entry && entry->id <= current_entry_id; entry = entry->next)
5128             for (formal = entry->sym->formal; formal; formal = formal->next)
5129               {
5130                 if (formal->sym && sym->name == formal->sym->name)
5131                   seen = true;
5132               }
5133
5134           /*  If it has not been seen as a dummy, this is an error.  */
5135           if (!seen)
5136             {
5137               if (specification_expr)
5138                 gfc_error ("Variable '%s', used in a specification expression"
5139                            ", is referenced at %L before the ENTRY statement "
5140                            "in which it is a parameter",
5141                            sym->name, &cs_base->current->loc);
5142               else
5143                 gfc_error ("Variable '%s' is used at %L before the ENTRY "
5144                            "statement in which it is a parameter",
5145                            sym->name, &cs_base->current->loc);
5146               t = FAILURE;
5147             }
5148         }
5149
5150       /* Now do the same check on the specification expressions.  */
5151       specification_expr = 1;
5152       if (sym->ts.type == BT_CHARACTER
5153           && gfc_resolve_expr (sym->ts.u.cl->length) == FAILURE)
5154         t = FAILURE;
5155
5156       if (sym->as)
5157         for (n = 0; n < sym->as->rank; n++)
5158           {
5159              specification_expr = 1;
5160              if (gfc_resolve_expr (sym->as->lower[n]) == FAILURE)
5161                t = FAILURE;
5162              specification_expr = 1;
5163              if (gfc_resolve_expr (sym->as->upper[n]) == FAILURE)
5164                t = FAILURE;
5165           }
5166       specification_expr = 0;
5167
5168       if (t == SUCCESS)
5169         /* Update the symbol's entry level.  */
5170         sym->entry_id = current_entry_id + 1;
5171     }
5172
5173   /* If a symbol has been host_associated mark it.  This is used latter,
5174      to identify if aliasing is possible via host association.  */
5175   if (sym->attr.flavor == FL_VARIABLE
5176         && gfc_current_ns->parent
5177         && (gfc_current_ns->parent == sym->ns
5178               || (gfc_current_ns->parent->parent
5179                     && gfc_current_ns->parent->parent == sym->ns)))
5180     sym->attr.host_assoc = 1;
5181
5182 resolve_procedure:
5183   if (t == SUCCESS && resolve_procedure_expression (e) == FAILURE)
5184     t = FAILURE;
5185
5186   /* F2008, C617 and C1229.  */
5187   if (!inquiry_argument && (e->ts.type == BT_CLASS || e->ts.type == BT_DERIVED)
5188       && gfc_is_coindexed (e))
5189     {
5190       gfc_ref *ref, *ref2 = NULL;
5191
5192       for (ref = e->ref; ref; ref = ref->next)
5193         {
5194           if (ref->type == REF_COMPONENT)
5195             ref2 = ref;
5196           if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5197             break;
5198         }
5199
5200       for ( ; ref; ref = ref->next)
5201         if (ref->type == REF_COMPONENT)
5202           break;
5203
5204       /* Expression itself is not coindexed object.  */
5205       if (ref && e->ts.type == BT_CLASS)
5206         {
5207           gfc_error ("Polymorphic subobject of coindexed object at %L",
5208                      &e->where);
5209           t = FAILURE;
5210         }
5211
5212       /* Expression itself is coindexed object.  */
5213       if (ref == NULL)
5214         {
5215           gfc_component *c;
5216           c = ref2 ? ref2->u.c.component : e->symtree->n.sym->components;
5217           for ( ; c; c = c->next)
5218             if (c->attr.allocatable && c->ts.type == BT_CLASS)
5219               {
5220                 gfc_error ("Coindexed object with polymorphic allocatable "
5221                          "subcomponent at %L", &e->where);
5222                 t = FAILURE;
5223                 break;
5224               }
5225         }
5226     }
5227
5228   return t;
5229 }
5230
5231
5232 /* Checks to see that the correct symbol has been host associated.
5233    The only situation where this arises is that in which a twice
5234    contained function is parsed after the host association is made.
5235    Therefore, on detecting this, change the symbol in the expression
5236    and convert the array reference into an actual arglist if the old
5237    symbol is a variable.  */
5238 static bool
5239 check_host_association (gfc_expr *e)
5240 {
5241   gfc_symbol *sym, *old_sym;
5242   gfc_symtree *st;
5243   int n;
5244   gfc_ref *ref;
5245   gfc_actual_arglist *arg, *tail = NULL;
5246   bool retval = e->expr_type == EXPR_FUNCTION;
5247
5248   /*  If the expression is the result of substitution in
5249       interface.c(gfc_extend_expr) because there is no way in
5250       which the host association can be wrong.  */
5251   if (e->symtree == NULL
5252         || e->symtree->n.sym == NULL
5253         || e->user_operator)
5254     return retval;
5255
5256   old_sym = e->symtree->n.sym;
5257
5258   if (gfc_current_ns->parent
5259         && old_sym->ns != gfc_current_ns)
5260     {
5261       /* Use the 'USE' name so that renamed module symbols are
5262          correctly handled.  */
5263       gfc_find_symbol (e->symtree->name, gfc_current_ns, 1, &sym);
5264
5265       if (sym && old_sym != sym
5266               && sym->ts.type == old_sym->ts.type
5267               && sym->attr.flavor == FL_PROCEDURE
5268               && sym->attr.contained)
5269         {
5270           /* Clear the shape, since it might not be valid.  */
5271           gfc_free_shape (&e->shape, e->rank);
5272
5273           /* Give the expression the right symtree!  */
5274           gfc_find_sym_tree (e->symtree->name, NULL, 1, &st);
5275           gcc_assert (st != NULL);
5276
5277           if (old_sym->attr.flavor == FL_PROCEDURE
5278                 || e->expr_type == EXPR_FUNCTION)
5279             {
5280               /* Original was function so point to the new symbol, since
5281                  the actual argument list is already attached to the
5282                  expression. */
5283               e->value.function.esym = NULL;
5284               e->symtree = st;
5285             }
5286           else
5287             {
5288               /* Original was variable so convert array references into
5289                  an actual arglist. This does not need any checking now
5290                  since resolve_function will take care of it.  */
5291               e->value.function.actual = NULL;
5292               e->expr_type = EXPR_FUNCTION;
5293               e->symtree = st;
5294
5295               /* Ambiguity will not arise if the array reference is not
5296                  the last reference.  */
5297               for (ref = e->ref; ref; ref = ref->next)
5298                 if (ref->type == REF_ARRAY && ref->next == NULL)
5299                   break;
5300
5301               gcc_assert (ref->type == REF_ARRAY);
5302
5303               /* Grab the start expressions from the array ref and
5304                  copy them into actual arguments.  */
5305               for (n = 0; n < ref->u.ar.dimen; n++)
5306                 {
5307                   arg = gfc_get_actual_arglist ();
5308                   arg->expr = gfc_copy_expr (ref->u.ar.start[n]);
5309                   if (e->value.function.actual == NULL)
5310                     tail = e->value.function.actual = arg;
5311                   else
5312                     {
5313                       tail->next = arg;
5314                       tail = arg;
5315                     }
5316                 }
5317
5318               /* Dump the reference list and set the rank.  */
5319               gfc_free_ref_list (e->ref);
5320               e->ref = NULL;
5321               e->rank = sym->as ? sym->as->rank : 0;
5322             }
5323
5324           gfc_resolve_expr (e);
5325           sym->refs++;
5326         }
5327     }
5328   /* This might have changed!  */
5329   return e->expr_type == EXPR_FUNCTION;
5330 }
5331
5332
5333 static void
5334 gfc_resolve_character_operator (gfc_expr *e)
5335 {
5336   gfc_expr *op1 = e->value.op.op1;
5337   gfc_expr *op2 = e->value.op.op2;
5338   gfc_expr *e1 = NULL;
5339   gfc_expr *e2 = NULL;
5340
5341   gcc_assert (e->value.op.op == INTRINSIC_CONCAT);
5342
5343   if (op1->ts.u.cl && op1->ts.u.cl->length)
5344     e1 = gfc_copy_expr (op1->ts.u.cl->length);
5345   else if (op1->expr_type == EXPR_CONSTANT)
5346     e1 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5347                            op1->value.character.length);
5348
5349   if (op2->ts.u.cl && op2->ts.u.cl->length)
5350     e2 = gfc_copy_expr (op2->ts.u.cl->length);
5351   else if (op2->expr_type == EXPR_CONSTANT)
5352     e2 = gfc_get_int_expr (gfc_default_integer_kind, NULL,
5353                            op2->value.character.length);
5354
5355   e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5356
5357   if (!e1 || !e2)
5358     return;
5359
5360   e->ts.u.cl->length = gfc_add (e1, e2);
5361   e->ts.u.cl->length->ts.type = BT_INTEGER;
5362   e->ts.u.cl->length->ts.kind = gfc_charlen_int_kind;
5363   gfc_simplify_expr (e->ts.u.cl->length, 0);
5364   gfc_resolve_expr (e->ts.u.cl->length);
5365
5366   return;
5367 }
5368
5369
5370 /*  Ensure that an character expression has a charlen and, if possible, a
5371     length expression.  */
5372
5373 static void
5374 fixup_charlen (gfc_expr *e)
5375 {
5376   /* The cases fall through so that changes in expression type and the need
5377      for multiple fixes are picked up.  In all circumstances, a charlen should
5378      be available for the middle end to hang a backend_decl on.  */
5379   switch (e->expr_type)
5380     {
5381     case EXPR_OP:
5382       gfc_resolve_character_operator (e);
5383
5384     case EXPR_ARRAY:
5385       if (e->expr_type == EXPR_ARRAY)
5386         gfc_resolve_character_array_constructor (e);
5387
5388     case EXPR_SUBSTRING:
5389       if (!e->ts.u.cl && e->ref)
5390         gfc_resolve_substring_charlen (e);
5391
5392     default:
5393       if (!e->ts.u.cl)
5394         e->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
5395
5396       break;
5397     }
5398 }
5399
5400
5401 /* Update an actual argument to include the passed-object for type-bound
5402    procedures at the right position.  */
5403
5404 static gfc_actual_arglist*
5405 update_arglist_pass (gfc_actual_arglist* lst, gfc_expr* po, unsigned argpos,
5406                      const char *name)
5407 {
5408   gcc_assert (argpos > 0);
5409
5410   if (argpos == 1)
5411     {
5412       gfc_actual_arglist* result;
5413
5414       result = gfc_get_actual_arglist ();
5415       result->expr = po;
5416       result->next = lst;
5417       if (name)
5418         result->name = name;
5419
5420       return result;
5421     }
5422
5423   if (lst)
5424     lst->next = update_arglist_pass (lst->next, po, argpos - 1, name);
5425   else
5426     lst = update_arglist_pass (NULL, po, argpos - 1, name);
5427   return lst;
5428 }
5429
5430
5431 /* Extract the passed-object from an EXPR_COMPCALL (a copy of it).  */
5432
5433 static gfc_expr*
5434 extract_compcall_passed_object (gfc_expr* e)
5435 {
5436   gfc_expr* po;
5437
5438   gcc_assert (e->expr_type == EXPR_COMPCALL);
5439
5440   if (e->value.compcall.base_object)
5441     po = gfc_copy_expr (e->value.compcall.base_object);
5442   else
5443     {
5444       po = gfc_get_expr ();
5445       po->expr_type = EXPR_VARIABLE;
5446       po->symtree = e->symtree;
5447       po->ref = gfc_copy_ref (e->ref);
5448       po->where = e->where;
5449     }
5450
5451   if (gfc_resolve_expr (po) == FAILURE)
5452     return NULL;
5453
5454   return po;
5455 }
5456
5457
5458 /* Update the arglist of an EXPR_COMPCALL expression to include the
5459    passed-object.  */
5460
5461 static gfc_try
5462 update_compcall_arglist (gfc_expr* e)
5463 {
5464   gfc_expr* po;
5465   gfc_typebound_proc* tbp;
5466
5467   tbp = e->value.compcall.tbp;
5468
5469   if (tbp->error)
5470     return FAILURE;
5471
5472   po = extract_compcall_passed_object (e);
5473   if (!po)
5474     return FAILURE;
5475
5476   if (tbp->nopass || e->value.compcall.ignore_pass)
5477     {
5478       gfc_free_expr (po);
5479       return SUCCESS;
5480     }
5481
5482   gcc_assert (tbp->pass_arg_num > 0);
5483   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5484                                                   tbp->pass_arg_num,
5485                                                   tbp->pass_arg);
5486
5487   return SUCCESS;
5488 }
5489
5490
5491 /* Extract the passed object from a PPC call (a copy of it).  */
5492
5493 static gfc_expr*
5494 extract_ppc_passed_object (gfc_expr *e)
5495 {
5496   gfc_expr *po;
5497   gfc_ref **ref;
5498
5499   po = gfc_get_expr ();
5500   po->expr_type = EXPR_VARIABLE;
5501   po->symtree = e->symtree;
5502   po->ref = gfc_copy_ref (e->ref);
5503   po->where = e->where;
5504
5505   /* Remove PPC reference.  */
5506   ref = &po->ref;
5507   while ((*ref)->next)
5508     ref = &(*ref)->next;
5509   gfc_free_ref_list (*ref);
5510   *ref = NULL;
5511
5512   if (gfc_resolve_expr (po) == FAILURE)
5513     return NULL;
5514
5515   return po;
5516 }
5517
5518
5519 /* Update the actual arglist of a procedure pointer component to include the
5520    passed-object.  */
5521
5522 static gfc_try
5523 update_ppc_arglist (gfc_expr* e)
5524 {
5525   gfc_expr* po;
5526   gfc_component *ppc;
5527   gfc_typebound_proc* tb;
5528
5529   if (!gfc_is_proc_ptr_comp (e, &ppc))
5530     return FAILURE;
5531
5532   tb = ppc->tb;
5533
5534   if (tb->error)
5535     return FAILURE;
5536   else if (tb->nopass)
5537     return SUCCESS;
5538
5539   po = extract_ppc_passed_object (e);
5540   if (!po)
5541     return FAILURE;
5542
5543   /* F08:R739.  */
5544   if (po->rank > 0)
5545     {
5546       gfc_error ("Passed-object at %L must be scalar", &e->where);
5547       return FAILURE;
5548     }
5549
5550   /* F08:C611.  */
5551   if (po->ts.type == BT_DERIVED && po->ts.u.derived->attr.abstract)
5552     {
5553       gfc_error ("Base object for procedure-pointer component call at %L is of"
5554                  " ABSTRACT type '%s'", &e->where, po->ts.u.derived->name);
5555       return FAILURE;
5556     }
5557
5558   gcc_assert (tb->pass_arg_num > 0);
5559   e->value.compcall.actual = update_arglist_pass (e->value.compcall.actual, po,
5560                                                   tb->pass_arg_num,
5561                                                   tb->pass_arg);
5562
5563   return SUCCESS;
5564 }
5565
5566
5567 /* Check that the object a TBP is called on is valid, i.e. it must not be
5568    of ABSTRACT type (as in subobject%abstract_parent%tbp()).  */
5569
5570 static gfc_try
5571 check_typebound_baseobject (gfc_expr* e)
5572 {
5573   gfc_expr* base;
5574   gfc_try return_value = FAILURE;
5575
5576   base = extract_compcall_passed_object (e);
5577   if (!base)
5578     return FAILURE;
5579
5580   gcc_assert (base->ts.type == BT_DERIVED || base->ts.type == BT_CLASS);
5581
5582   /* F08:C611.  */
5583   if (base->ts.type == BT_DERIVED && base->ts.u.derived->attr.abstract)
5584     {
5585       gfc_error ("Base object for type-bound procedure call at %L is of"
5586                  " ABSTRACT type '%s'", &e->where, base->ts.u.derived->name);
5587       goto cleanup;
5588     }
5589
5590   /* F08:C1230. If the procedure called is NOPASS,
5591      the base object must be scalar.  */
5592   if (e->value.compcall.tbp->nopass && base->rank > 0)
5593     {
5594       gfc_error ("Base object for NOPASS type-bound procedure call at %L must"
5595                  " be scalar", &e->where);
5596       goto cleanup;
5597     }
5598
5599   return_value = SUCCESS;
5600
5601 cleanup:
5602   gfc_free_expr (base);
5603   return return_value;
5604 }
5605
5606
5607 /* Resolve a call to a type-bound procedure, either function or subroutine,
5608    statically from the data in an EXPR_COMPCALL expression.  The adapted
5609    arglist and the target-procedure symtree are returned.  */
5610
5611 static gfc_try
5612 resolve_typebound_static (gfc_expr* e, gfc_symtree** target,
5613                           gfc_actual_arglist** actual)
5614 {
5615   gcc_assert (e->expr_type == EXPR_COMPCALL);
5616   gcc_assert (!e->value.compcall.tbp->is_generic);
5617
5618   /* Update the actual arglist for PASS.  */
5619   if (update_compcall_arglist (e) == FAILURE)
5620     return FAILURE;
5621
5622   *actual = e->value.compcall.actual;
5623   *target = e->value.compcall.tbp->u.specific;
5624
5625   gfc_free_ref_list (e->ref);
5626   e->ref = NULL;
5627   e->value.compcall.actual = NULL;
5628
5629   /* If we find a deferred typebound procedure, check for derived types
5630      that an overriding typebound procedure has not been missed.  */
5631   if (e->value.compcall.name
5632       && !e->value.compcall.tbp->non_overridable
5633       && e->value.compcall.base_object
5634       && e->value.compcall.base_object->ts.type == BT_DERIVED)
5635     {
5636       gfc_symtree *st;
5637       gfc_symbol *derived;
5638
5639       /* Use the derived type of the base_object.  */
5640       derived = e->value.compcall.base_object->ts.u.derived;
5641       st = NULL;
5642
5643       /* If necessary, go throught the inheritance chain.  */
5644       while (!st && derived)
5645         {
5646           /* Look for the typebound procedure 'name'.  */
5647           if (derived->f2k_derived && derived->f2k_derived->tb_sym_root)
5648             st = gfc_find_symtree (derived->f2k_derived->tb_sym_root,
5649                                    e->value.compcall.name);
5650           if (!st)
5651             derived = gfc_get_derived_super_type (derived);
5652         }
5653
5654       /* Now find the specific name in the derived type namespace.  */
5655       if (st && st->n.tb && st->n.tb->u.specific)
5656         gfc_find_sym_tree (st->n.tb->u.specific->name,
5657                            derived->ns, 1, &st);
5658       if (st)
5659         *target = st;
5660     }
5661   return SUCCESS;
5662 }
5663
5664
5665 /* Get the ultimate declared type from an expression.  In addition,
5666    return the last class/derived type reference and the copy of the
5667    reference list.  If check_types is set true, derived types are
5668    identified as well as class references.  */
5669 static gfc_symbol*
5670 get_declared_from_expr (gfc_ref **class_ref, gfc_ref **new_ref,
5671                         gfc_expr *e, bool check_types)
5672 {
5673   gfc_symbol *declared;
5674   gfc_ref *ref;
5675
5676   declared = NULL;
5677   if (class_ref)
5678     *class_ref = NULL;
5679   if (new_ref)
5680     *new_ref = gfc_copy_ref (e->ref);
5681
5682   for (ref = e->ref; ref; ref = ref->next)
5683     {
5684       if (ref->type != REF_COMPONENT)
5685         continue;
5686
5687       if ((ref->u.c.component->ts.type == BT_CLASS
5688              || (check_types && ref->u.c.component->ts.type == BT_DERIVED))
5689           && ref->u.c.component->attr.flavor != FL_PROCEDURE)
5690         {
5691           declared = ref->u.c.component->ts.u.derived;
5692           if (class_ref)
5693             *class_ref = ref;
5694         }
5695     }
5696
5697   if (declared == NULL)
5698     declared = e->symtree->n.sym->ts.u.derived;
5699
5700   return declared;
5701 }
5702
5703
5704 /* Given an EXPR_COMPCALL calling a GENERIC typebound procedure, figure out
5705    which of the specific bindings (if any) matches the arglist and transform
5706    the expression into a call of that binding.  */
5707
5708 static gfc_try
5709 resolve_typebound_generic_call (gfc_expr* e, const char **name)
5710 {
5711   gfc_typebound_proc* genproc;
5712   const char* genname;
5713   gfc_symtree *st;
5714   gfc_symbol *derived;
5715
5716   gcc_assert (e->expr_type == EXPR_COMPCALL);
5717   genname = e->value.compcall.name;
5718   genproc = e->value.compcall.tbp;
5719
5720   if (!genproc->is_generic)
5721     return SUCCESS;
5722
5723   /* Try the bindings on this type and in the inheritance hierarchy.  */
5724   for (; genproc; genproc = genproc->overridden)
5725     {
5726       gfc_tbp_generic* g;
5727
5728       gcc_assert (genproc->is_generic);
5729       for (g = genproc->u.generic; g; g = g->next)
5730         {
5731           gfc_symbol* target;
5732           gfc_actual_arglist* args;
5733           bool matches;
5734
5735           gcc_assert (g->specific);
5736
5737           if (g->specific->error)
5738             continue;
5739
5740           target = g->specific->u.specific->n.sym;
5741
5742           /* Get the right arglist by handling PASS/NOPASS.  */
5743           args = gfc_copy_actual_arglist (e->value.compcall.actual);
5744           if (!g->specific->nopass)
5745             {
5746               gfc_expr* po;
5747               po = extract_compcall_passed_object (e);
5748               if (!po)
5749                 return FAILURE;
5750
5751               gcc_assert (g->specific->pass_arg_num > 0);
5752               gcc_assert (!g->specific->error);
5753               args = update_arglist_pass (args, po, g->specific->pass_arg_num,
5754                                           g->specific->pass_arg);
5755             }
5756           resolve_actual_arglist (args, target->attr.proc,
5757                                   is_external_proc (target) && !target->formal);
5758
5759           /* Check if this arglist matches the formal.  */
5760           matches = gfc_arglist_matches_symbol (&args, target);
5761
5762           /* Clean up and break out of the loop if we've found it.  */
5763           gfc_free_actual_arglist (args);
5764           if (matches)
5765             {
5766               e->value.compcall.tbp = g->specific;
5767               genname = g->specific_st->name;
5768               /* Pass along the name for CLASS methods, where the vtab
5769                  procedure pointer component has to be referenced.  */
5770               if (name)
5771                 *name = genname;
5772               goto success;
5773             }
5774         }
5775     }
5776
5777   /* Nothing matching found!  */
5778   gfc_error ("Found no matching specific binding for the call to the GENERIC"
5779              " '%s' at %L", genname, &e->where);
5780   return FAILURE;
5781
5782 success:
5783   /* Make sure that we have the right specific instance for the name.  */
5784   derived = get_declared_from_expr (NULL, NULL, e, true);
5785
5786   st = gfc_find_typebound_proc (derived, NULL, genname, true, &e->where);
5787   if (st)
5788     e->value.compcall.tbp = st->n.tb;
5789
5790   return SUCCESS;
5791 }
5792
5793
5794 /* Resolve a call to a type-bound subroutine.  */
5795
5796 static gfc_try
5797 resolve_typebound_call (gfc_code* c, const char **name)
5798 {
5799   gfc_actual_arglist* newactual;
5800   gfc_symtree* target;
5801
5802   /* Check that's really a SUBROUTINE.  */
5803   if (!c->expr1->value.compcall.tbp->subroutine)
5804     {
5805       gfc_error ("'%s' at %L should be a SUBROUTINE",
5806                  c->expr1->value.compcall.name, &c->loc);
5807       return FAILURE;
5808     }
5809
5810   if (check_typebound_baseobject (c->expr1) == FAILURE)
5811     return FAILURE;
5812
5813   /* Pass along the name for CLASS methods, where the vtab
5814      procedure pointer component has to be referenced.  */
5815   if (name)
5816     *name = c->expr1->value.compcall.name;
5817
5818   if (resolve_typebound_generic_call (c->expr1, name) == FAILURE)
5819     return FAILURE;
5820
5821   /* Transform into an ordinary EXEC_CALL for now.  */
5822
5823   if (resolve_typebound_static (c->expr1, &target, &newactual) == FAILURE)
5824     return FAILURE;
5825
5826   c->ext.actual = newactual;
5827   c->symtree = target;
5828   c->op = (c->expr1->value.compcall.assign ? EXEC_ASSIGN_CALL : EXEC_CALL);
5829
5830   gcc_assert (!c->expr1->ref && !c->expr1->value.compcall.actual);
5831
5832   gfc_free_expr (c->expr1);
5833   c->expr1 = gfc_get_expr ();
5834   c->expr1->expr_type = EXPR_FUNCTION;
5835   c->expr1->symtree = target;
5836   c->expr1->where = c->loc;
5837
5838   return resolve_call (c);
5839 }
5840
5841
5842 /* Resolve a component-call expression.  */
5843 static gfc_try
5844 resolve_compcall (gfc_expr* e, const char **name)
5845 {
5846   gfc_actual_arglist* newactual;
5847   gfc_symtree* target;
5848
5849   /* Check that's really a FUNCTION.  */
5850   if (!e->value.compcall.tbp->function)
5851     {
5852       gfc_error ("'%s' at %L should be a FUNCTION",
5853                  e->value.compcall.name, &e->where);
5854       return FAILURE;
5855     }
5856
5857   /* These must not be assign-calls!  */
5858   gcc_assert (!e->value.compcall.assign);
5859
5860   if (check_typebound_baseobject (e) == FAILURE)
5861     return FAILURE;
5862
5863   /* Pass along the name for CLASS methods, where the vtab
5864      procedure pointer component has to be referenced.  */
5865   if (name)
5866     *name = e->value.compcall.name;
5867
5868   if (resolve_typebound_generic_call (e, name) == FAILURE)
5869     return FAILURE;
5870   gcc_assert (!e->value.compcall.tbp->is_generic);
5871
5872   /* Take the rank from the function's symbol.  */
5873   if (e->value.compcall.tbp->u.specific->n.sym->as)
5874     e->rank = e->value.compcall.tbp->u.specific->n.sym->as->rank;
5875
5876   /* For now, we simply transform it into an EXPR_FUNCTION call with the same
5877      arglist to the TBP's binding target.  */
5878
5879   if (resolve_typebound_static (e, &target, &newactual) == FAILURE)
5880     return FAILURE;
5881
5882   e->value.function.actual = newactual;
5883   e->value.function.name = NULL;
5884   e->value.function.esym = target->n.sym;
5885   e->value.function.isym = NULL;
5886   e->symtree = target;
5887   e->ts = target->n.sym->ts;
5888   e->expr_type = EXPR_FUNCTION;
5889
5890   /* Resolution is not necessary if this is a class subroutine; this
5891      function only has to identify the specific proc. Resolution of
5892      the call will be done next in resolve_typebound_call.  */
5893   return gfc_resolve_expr (e);
5894 }
5895
5896
5897
5898 /* Resolve a typebound function, or 'method'. First separate all
5899    the non-CLASS references by calling resolve_compcall directly.  */
5900
5901 static gfc_try
5902 resolve_typebound_function (gfc_expr* e)
5903 {
5904   gfc_symbol *declared;
5905   gfc_component *c;
5906   gfc_ref *new_ref;
5907   gfc_ref *class_ref;
5908   gfc_symtree *st;
5909   const char *name;
5910   gfc_typespec ts;
5911   gfc_expr *expr;
5912   bool overridable;
5913
5914   st = e->symtree;
5915
5916   /* Deal with typebound operators for CLASS objects.  */
5917   expr = e->value.compcall.base_object;
5918   overridable = !e->value.compcall.tbp->non_overridable;
5919   if (expr && expr->ts.type == BT_CLASS && e->value.compcall.name)
5920     {
5921       /* If the base_object is not a variable, the corresponding actual
5922          argument expression must be stored in e->base_expression so
5923          that the corresponding tree temporary can be used as the base
5924          object in gfc_conv_procedure_call.  */
5925       if (expr->expr_type != EXPR_VARIABLE)
5926         {
5927           gfc_actual_arglist *args;
5928
5929           for (args= e->value.function.actual; args; args = args->next)
5930             {
5931               if (expr == args->expr)
5932                 expr = args->expr;
5933             }
5934         }
5935
5936       /* Since the typebound operators are generic, we have to ensure
5937          that any delays in resolution are corrected and that the vtab
5938          is present.  */
5939       ts = expr->ts;
5940       declared = ts.u.derived;
5941       c = gfc_find_component (declared, "_vptr", true, true);
5942       if (c->ts.u.derived == NULL)
5943         c->ts.u.derived = gfc_find_derived_vtab (declared);
5944
5945       if (resolve_compcall (e, &name) == FAILURE)
5946         return FAILURE;
5947
5948       /* Use the generic name if it is there.  */
5949       name = name ? name : e->value.function.esym->name;
5950       e->symtree = expr->symtree;
5951       e->ref = gfc_copy_ref (expr->ref);
5952       get_declared_from_expr (&class_ref, NULL, e, false);
5953
5954       /* Trim away the extraneous references that emerge from nested
5955          use of interface.c (extend_expr).  */
5956       if (class_ref && class_ref->next)
5957         {
5958           gfc_free_ref_list (class_ref->next);
5959           class_ref->next = NULL;
5960         }
5961       else if (e->ref && !class_ref)
5962         {
5963           gfc_free_ref_list (e->ref);
5964           e->ref = NULL;
5965         }
5966
5967       gfc_add_vptr_component (e);
5968       gfc_add_component_ref (e, name);
5969       e->value.function.esym = NULL;
5970       if (expr->expr_type != EXPR_VARIABLE)
5971         e->base_expr = expr;
5972       return SUCCESS;
5973     }
5974
5975   if (st == NULL)
5976     return resolve_compcall (e, NULL);
5977
5978   if (resolve_ref (e) == FAILURE)
5979     return FAILURE;
5980
5981   /* Get the CLASS declared type.  */
5982   declared = get_declared_from_expr (&class_ref, &new_ref, e, true);
5983
5984   /* Weed out cases of the ultimate component being a derived type.  */
5985   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
5986          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
5987     {
5988       gfc_free_ref_list (new_ref);
5989       return resolve_compcall (e, NULL);
5990     }
5991
5992   c = gfc_find_component (declared, "_data", true, true);
5993   declared = c->ts.u.derived;
5994
5995   /* Treat the call as if it is a typebound procedure, in order to roll
5996      out the correct name for the specific function.  */
5997   if (resolve_compcall (e, &name) == FAILURE)
5998     return FAILURE;
5999   ts = e->ts;
6000
6001   if (overridable)
6002     {
6003       /* Convert the expression to a procedure pointer component call.  */
6004       e->value.function.esym = NULL;
6005       e->symtree = st;
6006
6007       if (new_ref)
6008         e->ref = new_ref;
6009
6010       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
6011       gfc_add_vptr_component (e);
6012       gfc_add_component_ref (e, name);
6013
6014       /* Recover the typespec for the expression.  This is really only
6015         necessary for generic procedures, where the additional call
6016         to gfc_add_component_ref seems to throw the collection of the
6017         correct typespec.  */
6018       e->ts = ts;
6019     }
6020
6021   return SUCCESS;
6022 }
6023
6024 /* Resolve a typebound subroutine, or 'method'. First separate all
6025    the non-CLASS references by calling resolve_typebound_call
6026    directly.  */
6027
6028 static gfc_try
6029 resolve_typebound_subroutine (gfc_code *code)
6030 {
6031   gfc_symbol *declared;
6032   gfc_component *c;
6033   gfc_ref *new_ref;
6034   gfc_ref *class_ref;
6035   gfc_symtree *st;
6036   const char *name;
6037   gfc_typespec ts;
6038   gfc_expr *expr;
6039   bool overridable;
6040
6041   st = code->expr1->symtree;
6042
6043   /* Deal with typebound operators for CLASS objects.  */
6044   expr = code->expr1->value.compcall.base_object;
6045   overridable = !code->expr1->value.compcall.tbp->non_overridable;
6046   if (expr && expr->ts.type == BT_CLASS && code->expr1->value.compcall.name)
6047     {
6048       /* If the base_object is not a variable, the corresponding actual
6049          argument expression must be stored in e->base_expression so
6050          that the corresponding tree temporary can be used as the base
6051          object in gfc_conv_procedure_call.  */
6052       if (expr->expr_type != EXPR_VARIABLE)
6053         {
6054           gfc_actual_arglist *args;
6055
6056           args= code->expr1->value.function.actual;
6057           for (; args; args = args->next)
6058             if (expr == args->expr)
6059               expr = args->expr;
6060         }
6061
6062       /* Since the typebound operators are generic, we have to ensure
6063          that any delays in resolution are corrected and that the vtab
6064          is present.  */
6065       declared = expr->ts.u.derived;
6066       c = gfc_find_component (declared, "_vptr", true, true);
6067       if (c->ts.u.derived == NULL)
6068         c->ts.u.derived = gfc_find_derived_vtab (declared);
6069
6070       if (resolve_typebound_call (code, &name) == FAILURE)
6071         return FAILURE;
6072
6073       /* Use the generic name if it is there.  */
6074       name = name ? name : code->expr1->value.function.esym->name;
6075       code->expr1->symtree = expr->symtree;
6076       code->expr1->ref = gfc_copy_ref (expr->ref);
6077
6078       /* Trim away the extraneous references that emerge from nested
6079          use of interface.c (extend_expr).  */
6080       get_declared_from_expr (&class_ref, NULL, code->expr1, false);
6081       if (class_ref && class_ref->next)
6082         {
6083           gfc_free_ref_list (class_ref->next);
6084           class_ref->next = NULL;
6085         }
6086       else if (code->expr1->ref && !class_ref)
6087         {
6088           gfc_free_ref_list (code->expr1->ref);
6089           code->expr1->ref = NULL;
6090         }
6091
6092       /* Now use the procedure in the vtable.  */
6093       gfc_add_vptr_component (code->expr1);
6094       gfc_add_component_ref (code->expr1, name);
6095       code->expr1->value.function.esym = NULL;
6096       if (expr->expr_type != EXPR_VARIABLE)
6097         code->expr1->base_expr = expr;
6098       return SUCCESS;
6099     }
6100
6101   if (st == NULL)
6102     return resolve_typebound_call (code, NULL);
6103
6104   if (resolve_ref (code->expr1) == FAILURE)
6105     return FAILURE;
6106
6107   /* Get the CLASS declared type.  */
6108   get_declared_from_expr (&class_ref, &new_ref, code->expr1, true);
6109
6110   /* Weed out cases of the ultimate component being a derived type.  */
6111   if ((class_ref && class_ref->u.c.component->ts.type == BT_DERIVED)
6112          || (!class_ref && st->n.sym->ts.type != BT_CLASS))
6113     {
6114       gfc_free_ref_list (new_ref);
6115       return resolve_typebound_call (code, NULL);
6116     }
6117
6118   if (resolve_typebound_call (code, &name) == FAILURE)
6119     return FAILURE;
6120   ts = code->expr1->ts;
6121
6122   if (overridable)
6123     {
6124       /* Convert the expression to a procedure pointer component call.  */
6125       code->expr1->value.function.esym = NULL;
6126       code->expr1->symtree = st;
6127
6128       if (new_ref)
6129         code->expr1->ref = new_ref;
6130
6131       /* '_vptr' points to the vtab, which contains the procedure pointers.  */
6132       gfc_add_vptr_component (code->expr1);
6133       gfc_add_component_ref (code->expr1, name);
6134
6135       /* Recover the typespec for the expression.  This is really only
6136         necessary for generic procedures, where the additional call
6137         to gfc_add_component_ref seems to throw the collection of the
6138         correct typespec.  */
6139       code->expr1->ts = ts;
6140     }
6141
6142   return SUCCESS;
6143 }
6144
6145
6146 /* Resolve a CALL to a Procedure Pointer Component (Subroutine).  */
6147
6148 static gfc_try
6149 resolve_ppc_call (gfc_code* c)
6150 {
6151   gfc_component *comp;
6152   bool b;
6153
6154   b = gfc_is_proc_ptr_comp (c->expr1, &comp);
6155   gcc_assert (b);
6156
6157   c->resolved_sym = c->expr1->symtree->n.sym;
6158   c->expr1->expr_type = EXPR_VARIABLE;
6159
6160   if (!comp->attr.subroutine)
6161     gfc_add_subroutine (&comp->attr, comp->name, &c->expr1->where);
6162
6163   if (resolve_ref (c->expr1) == FAILURE)
6164     return FAILURE;
6165
6166   if (update_ppc_arglist (c->expr1) == FAILURE)
6167     return FAILURE;
6168
6169   c->ext.actual = c->expr1->value.compcall.actual;
6170
6171   if (resolve_actual_arglist (c->ext.actual, comp->attr.proc,
6172                               comp->formal == NULL) == FAILURE)
6173     return FAILURE;
6174
6175   gfc_ppc_use (comp, &c->expr1->value.compcall.actual, &c->expr1->where);
6176
6177   return SUCCESS;
6178 }
6179
6180
6181 /* Resolve a Function Call to a Procedure Pointer Component (Function).  */
6182
6183 static gfc_try
6184 resolve_expr_ppc (gfc_expr* e)
6185 {
6186   gfc_component *comp;
6187   bool b;
6188
6189   b = gfc_is_proc_ptr_comp (e, &comp);
6190   gcc_assert (b);
6191
6192   /* Convert to EXPR_FUNCTION.  */
6193   e->expr_type = EXPR_FUNCTION;
6194   e->value.function.isym = NULL;
6195   e->value.function.actual = e->value.compcall.actual;
6196   e->ts = comp->ts;
6197   if (comp->as != NULL)
6198     e->rank = comp->as->rank;
6199
6200   if (!comp->attr.function)
6201     gfc_add_function (&comp->attr, comp->name, &e->where);
6202
6203   if (resolve_ref (e) == FAILURE)
6204     return FAILURE;
6205
6206   if (resolve_actual_arglist (e->value.function.actual, comp->attr.proc,
6207                               comp->formal == NULL) == FAILURE)
6208     return FAILURE;
6209
6210   if (update_ppc_arglist (e) == FAILURE)
6211     return FAILURE;
6212
6213   gfc_ppc_use (comp, &e->value.compcall.actual, &e->where);
6214
6215   return SUCCESS;
6216 }
6217
6218
6219 static bool
6220 gfc_is_expandable_expr (gfc_expr *e)
6221 {
6222   gfc_constructor *con;
6223
6224   if (e->expr_type == EXPR_ARRAY)
6225     {
6226       /* Traverse the constructor looking for variables that are flavor
6227          parameter.  Parameters must be expanded since they are fully used at
6228          compile time.  */
6229       con = gfc_constructor_first (e->value.constructor);
6230       for (; con; con = gfc_constructor_next (con))
6231         {
6232           if (con->expr->expr_type == EXPR_VARIABLE
6233               && con->expr->symtree
6234               && (con->expr->symtree->n.sym->attr.flavor == FL_PARAMETER
6235               || con->expr->symtree->n.sym->attr.flavor == FL_VARIABLE))
6236             return true;
6237           if (con->expr->expr_type == EXPR_ARRAY
6238               && gfc_is_expandable_expr (con->expr))
6239             return true;
6240         }
6241     }
6242
6243   return false;
6244 }
6245
6246 /* Resolve an expression.  That is, make sure that types of operands agree
6247    with their operators, intrinsic operators are converted to function calls
6248    for overloaded types and unresolved function references are resolved.  */
6249
6250 gfc_try
6251 gfc_resolve_expr (gfc_expr *e)
6252 {
6253   gfc_try t;
6254   bool inquiry_save;
6255
6256   if (e == NULL)
6257     return SUCCESS;
6258
6259   /* inquiry_argument only applies to variables.  */
6260   inquiry_save = inquiry_argument;
6261   if (e->expr_type != EXPR_VARIABLE)
6262     inquiry_argument = false;
6263
6264   switch (e->expr_type)
6265     {
6266     case EXPR_OP:
6267       t = resolve_operator (e);
6268       break;
6269
6270     case EXPR_FUNCTION:
6271     case EXPR_VARIABLE:
6272
6273       if (check_host_association (e))
6274         t = resolve_function (e);
6275       else
6276         {
6277           t = resolve_variable (e);
6278           if (t == SUCCESS)
6279             expression_rank (e);
6280         }
6281
6282       if (e->ts.type == BT_CHARACTER && e->ts.u.cl == NULL && e->ref
6283           && e->ref->type != REF_SUBSTRING)
6284         gfc_resolve_substring_charlen (e);
6285
6286       break;
6287
6288     case EXPR_COMPCALL:
6289       t = resolve_typebound_function (e);
6290       break;
6291
6292     case EXPR_SUBSTRING:
6293       t = resolve_ref (e);
6294       break;
6295
6296     case EXPR_CONSTANT:
6297     case EXPR_NULL:
6298       t = SUCCESS;
6299       break;
6300
6301     case EXPR_PPC:
6302       t = resolve_expr_ppc (e);
6303       break;
6304
6305     case EXPR_ARRAY:
6306       t = FAILURE;
6307       if (resolve_ref (e) == FAILURE)
6308         break;
6309
6310       t = gfc_resolve_array_constructor (e);
6311       /* Also try to expand a constructor.  */
6312       if (t == SUCCESS)
6313         {
6314           expression_rank (e);
6315           if (gfc_is_constant_expr (e) || gfc_is_expandable_expr (e))
6316             gfc_expand_constructor (e, false);
6317         }
6318
6319       /* This provides the opportunity for the length of constructors with
6320          character valued function elements to propagate the string length
6321          to the expression.  */
6322       if (t == SUCCESS && e->ts.type == BT_CHARACTER)
6323         {
6324           /* For efficiency, we call gfc_expand_constructor for BT_CHARACTER
6325              here rather then add a duplicate test for it above.  */
6326           gfc_expand_constructor (e, false);
6327           t = gfc_resolve_character_array_constructor (e);
6328         }
6329
6330       break;
6331
6332     case EXPR_STRUCTURE:
6333       t = resolve_ref (e);
6334       if (t == FAILURE)
6335         break;
6336
6337       t = resolve_structure_cons (e, 0);
6338       if (t == FAILURE)
6339         break;
6340
6341       t = gfc_simplify_expr (e, 0);
6342       break;
6343
6344     default:
6345       gfc_internal_error ("gfc_resolve_expr(): Bad expression type");
6346     }
6347
6348   if (e->ts.type == BT_CHARACTER && t == SUCCESS && !e->ts.u.cl)
6349     fixup_charlen (e);
6350
6351   inquiry_argument = inquiry_save;
6352
6353   return t;
6354 }
6355
6356
6357 /* Resolve an expression from an iterator.  They must be scalar and have
6358    INTEGER or (optionally) REAL type.  */
6359
6360 static gfc_try
6361 gfc_resolve_iterator_expr (gfc_expr *expr, bool real_ok,
6362                            const char *name_msgid)
6363 {
6364   if (gfc_resolve_expr (expr) == FAILURE)
6365     return FAILURE;
6366
6367   if (expr->rank != 0)
6368     {
6369       gfc_error ("%s at %L must be a scalar", _(name_msgid), &expr->where);
6370       return FAILURE;
6371     }
6372
6373   if (expr->ts.type != BT_INTEGER)
6374     {
6375       if (expr->ts.type == BT_REAL)
6376         {
6377           if (real_ok)
6378             return gfc_notify_std (GFC_STD_F95_DEL,
6379                                    "Deleted feature: %s at %L must be integer",
6380                                    _(name_msgid), &expr->where);
6381           else
6382             {
6383               gfc_error ("%s at %L must be INTEGER", _(name_msgid),
6384                          &expr->where);
6385               return FAILURE;
6386             }
6387         }
6388       else
6389         {
6390           gfc_error ("%s at %L must be INTEGER", _(name_msgid), &expr->where);
6391           return FAILURE;
6392         }
6393     }
6394   return SUCCESS;
6395 }
6396
6397
6398 /* Resolve the expressions in an iterator structure.  If REAL_OK is
6399    false allow only INTEGER type iterators, otherwise allow REAL types.  */
6400
6401 gfc_try
6402 gfc_resolve_iterator (gfc_iterator *iter, bool real_ok)
6403 {
6404   if (gfc_resolve_iterator_expr (iter->var, real_ok, "Loop variable")
6405       == FAILURE)
6406     return FAILURE;
6407
6408   if (gfc_check_vardef_context (iter->var, false, false, _("iterator variable"))
6409       == FAILURE)
6410     return FAILURE;
6411
6412   if (gfc_resolve_iterator_expr (iter->start, real_ok,
6413                                  "Start expression in DO loop") == FAILURE)
6414     return FAILURE;
6415
6416   if (gfc_resolve_iterator_expr (iter->end, real_ok,
6417                                  "End expression in DO loop") == FAILURE)
6418     return FAILURE;
6419
6420   if (gfc_resolve_iterator_expr (iter->step, real_ok,
6421                                  "Step expression in DO loop") == FAILURE)
6422     return FAILURE;
6423
6424   if (iter->step->expr_type == EXPR_CONSTANT)
6425     {
6426       if ((iter->step->ts.type == BT_INTEGER
6427            && mpz_cmp_ui (iter->step->value.integer, 0) == 0)
6428           || (iter->step->ts.type == BT_REAL
6429               && mpfr_sgn (iter->step->value.real) == 0))
6430         {
6431           gfc_error ("Step expression in DO loop at %L cannot be zero",
6432                      &iter->step->where);
6433           return FAILURE;
6434         }
6435     }
6436
6437   /* Convert start, end, and step to the same type as var.  */
6438   if (iter->start->ts.kind != iter->var->ts.kind
6439       || iter->start->ts.type != iter->var->ts.type)
6440     gfc_convert_type (iter->start, &iter->var->ts, 2);
6441
6442   if (iter->end->ts.kind != iter->var->ts.kind
6443       || iter->end->ts.type != iter->var->ts.type)
6444     gfc_convert_type (iter->end, &iter->var->ts, 2);
6445
6446   if (iter->step->ts.kind != iter->var->ts.kind
6447       || iter->step->ts.type != iter->var->ts.type)
6448     gfc_convert_type (iter->step, &iter->var->ts, 2);
6449
6450   if (iter->start->expr_type == EXPR_CONSTANT
6451       && iter->end->expr_type == EXPR_CONSTANT
6452       && iter->step->expr_type == EXPR_CONSTANT)
6453     {
6454       int sgn, cmp;
6455       if (iter->start->ts.type == BT_INTEGER)
6456         {
6457           sgn = mpz_cmp_ui (iter->step->value.integer, 0);
6458           cmp = mpz_cmp (iter->end->value.integer, iter->start->value.integer);
6459         }
6460       else
6461         {
6462           sgn = mpfr_sgn (iter->step->value.real);
6463           cmp = mpfr_cmp (iter->end->value.real, iter->start->value.real);
6464         }
6465       if ((sgn > 0 && cmp < 0) || (sgn < 0 && cmp > 0))
6466         gfc_warning ("DO loop at %L will be executed zero times",
6467                      &iter->step->where);
6468     }
6469
6470   return SUCCESS;
6471 }
6472
6473
6474 /* Traversal function for find_forall_index.  f == 2 signals that
6475    that variable itself is not to be checked - only the references.  */
6476
6477 static bool
6478 forall_index (gfc_expr *expr, gfc_symbol *sym, int *f)
6479 {
6480   if (expr->expr_type != EXPR_VARIABLE)
6481     return false;
6482
6483   /* A scalar assignment  */
6484   if (!expr->ref || *f == 1)
6485     {
6486       if (expr->symtree->n.sym == sym)
6487         return true;
6488       else
6489         return false;
6490     }
6491
6492   if (*f == 2)
6493     *f = 1;
6494   return false;
6495 }
6496
6497
6498 /* Check whether the FORALL index appears in the expression or not.
6499    Returns SUCCESS if SYM is found in EXPR.  */
6500
6501 gfc_try
6502 find_forall_index (gfc_expr *expr, gfc_symbol *sym, int f)
6503 {
6504   if (gfc_traverse_expr (expr, sym, forall_index, f))
6505     return SUCCESS;
6506   else
6507     return FAILURE;
6508 }
6509
6510
6511 /* Resolve a list of FORALL iterators.  The FORALL index-name is constrained
6512    to be a scalar INTEGER variable.  The subscripts and stride are scalar
6513    INTEGERs, and if stride is a constant it must be nonzero.
6514    Furthermore "A subscript or stride in a forall-triplet-spec shall
6515    not contain a reference to any index-name in the
6516    forall-triplet-spec-list in which it appears." (7.5.4.1)  */
6517
6518 static void
6519 resolve_forall_iterators (gfc_forall_iterator *it)
6520 {
6521   gfc_forall_iterator *iter, *iter2;
6522
6523   for (iter = it; iter; iter = iter->next)
6524     {
6525       if (gfc_resolve_expr (iter->var) == SUCCESS
6526           && (iter->var->ts.type != BT_INTEGER || iter->var->rank != 0))
6527         gfc_error ("FORALL index-name at %L must be a scalar INTEGER",
6528                    &iter->var->where);
6529
6530       if (gfc_resolve_expr (iter->start) == SUCCESS
6531           && (iter->start->ts.type != BT_INTEGER || iter->start->rank != 0))
6532         gfc_error ("FORALL start expression at %L must be a scalar INTEGER",
6533                    &iter->start->where);
6534       if (iter->var->ts.kind != iter->start->ts.kind)
6535         gfc_convert_type (iter->start, &iter->var->ts, 1);
6536
6537       if (gfc_resolve_expr (iter->end) == SUCCESS
6538           && (iter->end->ts.type != BT_INTEGER || iter->end->rank != 0))
6539         gfc_error ("FORALL end expression at %L must be a scalar INTEGER",
6540                    &iter->end->where);
6541       if (iter->var->ts.kind != iter->end->ts.kind)
6542         gfc_convert_type (iter->end, &iter->var->ts, 1);
6543
6544       if (gfc_resolve_expr (iter->stride) == SUCCESS)
6545         {
6546           if (iter->stride->ts.type != BT_INTEGER || iter->stride->rank != 0)
6547             gfc_error ("FORALL stride expression at %L must be a scalar %s",
6548                        &iter->stride->where, "INTEGER");
6549
6550           if (iter->stride->expr_type == EXPR_CONSTANT
6551               && mpz_cmp_ui(iter->stride->value.integer, 0) == 0)
6552             gfc_error ("FORALL stride expression at %L cannot be zero",
6553                        &iter->stride->where);
6554         }
6555       if (iter->var->ts.kind != iter->stride->ts.kind)
6556         gfc_convert_type (iter->stride, &iter->var->ts, 1);
6557     }
6558
6559   for (iter = it; iter; iter = iter->next)
6560     for (iter2 = iter; iter2; iter2 = iter2->next)
6561       {
6562         if (find_forall_index (iter2->start,
6563                                iter->var->symtree->n.sym, 0) == SUCCESS
6564             || find_forall_index (iter2->end,
6565                                   iter->var->symtree->n.sym, 0) == SUCCESS
6566             || find_forall_index (iter2->stride,
6567                                   iter->var->symtree->n.sym, 0) == SUCCESS)
6568           gfc_error ("FORALL index '%s' may not appear in triplet "
6569                      "specification at %L", iter->var->symtree->name,
6570                      &iter2->start->where);
6571       }
6572 }
6573
6574
6575 /* Given a pointer to a symbol that is a derived type, see if it's
6576    inaccessible, i.e. if it's defined in another module and the components are
6577    PRIVATE.  The search is recursive if necessary.  Returns zero if no
6578    inaccessible components are found, nonzero otherwise.  */
6579
6580 static int
6581 derived_inaccessible (gfc_symbol *sym)
6582 {
6583   gfc_component *c;
6584
6585   if (sym->attr.use_assoc && sym->attr.private_comp)
6586     return 1;
6587
6588   for (c = sym->components; c; c = c->next)
6589     {
6590         if (c->ts.type == BT_DERIVED && derived_inaccessible (c->ts.u.derived))
6591           return 1;
6592     }
6593
6594   return 0;
6595 }
6596
6597
6598 /* Resolve the argument of a deallocate expression.  The expression must be
6599    a pointer or a full array.  */
6600
6601 static gfc_try
6602 resolve_deallocate_expr (gfc_expr *e)
6603 {
6604   symbol_attribute attr;
6605   int allocatable, pointer;
6606   gfc_ref *ref;
6607   gfc_symbol *sym;
6608   gfc_component *c;
6609
6610   if (gfc_resolve_expr (e) == FAILURE)
6611     return FAILURE;
6612
6613   if (e->expr_type != EXPR_VARIABLE)
6614     goto bad;
6615
6616   sym = e->symtree->n.sym;
6617
6618   if (sym->ts.type == BT_CLASS)
6619     {
6620       allocatable = CLASS_DATA (sym)->attr.allocatable;
6621       pointer = CLASS_DATA (sym)->attr.class_pointer;
6622     }
6623   else
6624     {
6625       allocatable = sym->attr.allocatable;
6626       pointer = sym->attr.pointer;
6627     }
6628   for (ref = e->ref; ref; ref = ref->next)
6629     {
6630       switch (ref->type)
6631         {
6632         case REF_ARRAY:
6633           if (ref->u.ar.type != AR_FULL
6634               && !(ref->u.ar.type == AR_ELEMENT && ref->u.ar.as->rank == 0
6635                    && ref->u.ar.codimen && gfc_ref_this_image (ref)))
6636             allocatable = 0;
6637           break;
6638
6639         case REF_COMPONENT:
6640           c = ref->u.c.component;
6641           if (c->ts.type == BT_CLASS)
6642             {
6643               allocatable = CLASS_DATA (c)->attr.allocatable;
6644               pointer = CLASS_DATA (c)->attr.class_pointer;
6645             }
6646           else
6647             {
6648               allocatable = c->attr.allocatable;
6649               pointer = c->attr.pointer;
6650             }
6651           break;
6652
6653         case REF_SUBSTRING:
6654           allocatable = 0;
6655           break;
6656         }
6657     }
6658
6659   attr = gfc_expr_attr (e);
6660
6661   if (allocatable == 0 && attr.pointer == 0)
6662     {
6663     bad:
6664       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6665                  &e->where);
6666       return FAILURE;
6667     }
6668
6669   /* F2008, C644.  */
6670   if (gfc_is_coindexed (e))
6671     {
6672       gfc_error ("Coindexed allocatable object at %L", &e->where);
6673       return FAILURE;
6674     }
6675
6676   if (pointer
6677       && gfc_check_vardef_context (e, true, true, _("DEALLOCATE object"))
6678          == FAILURE)
6679     return FAILURE;
6680   if (gfc_check_vardef_context (e, false, true, _("DEALLOCATE object"))
6681       == FAILURE)
6682     return FAILURE;
6683
6684   return SUCCESS;
6685 }
6686
6687
6688 /* Returns true if the expression e contains a reference to the symbol sym.  */
6689 static bool
6690 sym_in_expr (gfc_expr *e, gfc_symbol *sym, int *f ATTRIBUTE_UNUSED)
6691 {
6692   if (e->expr_type == EXPR_VARIABLE && e->symtree->n.sym == sym)
6693     return true;
6694
6695   return false;
6696 }
6697
6698 bool
6699 gfc_find_sym_in_expr (gfc_symbol *sym, gfc_expr *e)
6700 {
6701   return gfc_traverse_expr (e, sym, sym_in_expr, 0);
6702 }
6703
6704
6705 /* Given the expression node e for an allocatable/pointer of derived type to be
6706    allocated, get the expression node to be initialized afterwards (needed for
6707    derived types with default initializers, and derived types with allocatable
6708    components that need nullification.)  */
6709
6710 gfc_expr *
6711 gfc_expr_to_initialize (gfc_expr *e)
6712 {
6713   gfc_expr *result;
6714   gfc_ref *ref;
6715   int i;
6716
6717   result = gfc_copy_expr (e);
6718
6719   /* Change the last array reference from AR_ELEMENT to AR_FULL.  */
6720   for (ref = result->ref; ref; ref = ref->next)
6721     if (ref->type == REF_ARRAY && ref->next == NULL)
6722       {
6723         ref->u.ar.type = AR_FULL;
6724
6725         for (i = 0; i < ref->u.ar.dimen; i++)
6726           ref->u.ar.start[i] = ref->u.ar.end[i] = ref->u.ar.stride[i] = NULL;
6727
6728         break;
6729       }
6730
6731   gfc_free_shape (&result->shape, result->rank);
6732
6733   /* Recalculate rank, shape, etc.  */
6734   gfc_resolve_expr (result);
6735   return result;
6736 }
6737
6738
6739 /* If the last ref of an expression is an array ref, return a copy of the
6740    expression with that one removed.  Otherwise, a copy of the original
6741    expression.  This is used for allocate-expressions and pointer assignment
6742    LHS, where there may be an array specification that needs to be stripped
6743    off when using gfc_check_vardef_context.  */
6744
6745 static gfc_expr*
6746 remove_last_array_ref (gfc_expr* e)
6747 {
6748   gfc_expr* e2;
6749   gfc_ref** r;
6750
6751   e2 = gfc_copy_expr (e);
6752   for (r = &e2->ref; *r; r = &(*r)->next)
6753     if ((*r)->type == REF_ARRAY && !(*r)->next)
6754       {
6755         gfc_free_ref_list (*r);
6756         *r = NULL;
6757         break;
6758       }
6759
6760   return e2;
6761 }
6762
6763
6764 /* Used in resolve_allocate_expr to check that a allocation-object and
6765    a source-expr are conformable.  This does not catch all possible
6766    cases; in particular a runtime checking is needed.  */
6767
6768 static gfc_try
6769 conformable_arrays (gfc_expr *e1, gfc_expr *e2)
6770 {
6771   gfc_ref *tail;
6772   for (tail = e2->ref; tail && tail->next; tail = tail->next);
6773
6774   /* First compare rank.  */
6775   if (tail && e1->rank != tail->u.ar.as->rank)
6776     {
6777       gfc_error ("Source-expr at %L must be scalar or have the "
6778                  "same rank as the allocate-object at %L",
6779                  &e1->where, &e2->where);
6780       return FAILURE;
6781     }
6782
6783   if (e1->shape)
6784     {
6785       int i;
6786       mpz_t s;
6787
6788       mpz_init (s);
6789
6790       for (i = 0; i < e1->rank; i++)
6791         {
6792           if (tail->u.ar.end[i])
6793             {
6794               mpz_set (s, tail->u.ar.end[i]->value.integer);
6795               mpz_sub (s, s, tail->u.ar.start[i]->value.integer);
6796               mpz_add_ui (s, s, 1);
6797             }
6798           else
6799             {
6800               mpz_set (s, tail->u.ar.start[i]->value.integer);
6801             }
6802
6803           if (mpz_cmp (e1->shape[i], s) != 0)
6804             {
6805               gfc_error ("Source-expr at %L and allocate-object at %L must "
6806                          "have the same shape", &e1->where, &e2->where);
6807               mpz_clear (s);
6808               return FAILURE;
6809             }
6810         }
6811
6812       mpz_clear (s);
6813     }
6814
6815   return SUCCESS;
6816 }
6817
6818
6819 /* Resolve the expression in an ALLOCATE statement, doing the additional
6820    checks to see whether the expression is OK or not.  The expression must
6821    have a trailing array reference that gives the size of the array.  */
6822
6823 static gfc_try
6824 resolve_allocate_expr (gfc_expr *e, gfc_code *code)
6825 {
6826   int i, pointer, allocatable, dimension, is_abstract;
6827   int codimension;
6828   bool coindexed;
6829   symbol_attribute attr;
6830   gfc_ref *ref, *ref2;
6831   gfc_expr *e2;
6832   gfc_array_ref *ar;
6833   gfc_symbol *sym = NULL;
6834   gfc_alloc *a;
6835   gfc_component *c;
6836   gfc_try t;
6837
6838   /* Mark the ultimost array component as being in allocate to allow DIMEN_STAR
6839      checking of coarrays.  */
6840   for (ref = e->ref; ref; ref = ref->next)
6841     if (ref->next == NULL)
6842       break;
6843
6844   if (ref && ref->type == REF_ARRAY)
6845     ref->u.ar.in_allocate = true;
6846
6847   if (gfc_resolve_expr (e) == FAILURE)
6848     goto failure;
6849
6850   /* Make sure the expression is allocatable or a pointer.  If it is
6851      pointer, the next-to-last reference must be a pointer.  */
6852
6853   ref2 = NULL;
6854   if (e->symtree)
6855     sym = e->symtree->n.sym;
6856
6857   /* Check whether ultimate component is abstract and CLASS.  */
6858   is_abstract = 0;
6859
6860   if (e->expr_type != EXPR_VARIABLE)
6861     {
6862       allocatable = 0;
6863       attr = gfc_expr_attr (e);
6864       pointer = attr.pointer;
6865       dimension = attr.dimension;
6866       codimension = attr.codimension;
6867     }
6868   else
6869     {
6870       if (sym->ts.type == BT_CLASS && CLASS_DATA (sym))
6871         {
6872           allocatable = CLASS_DATA (sym)->attr.allocatable;
6873           pointer = CLASS_DATA (sym)->attr.class_pointer;
6874           dimension = CLASS_DATA (sym)->attr.dimension;
6875           codimension = CLASS_DATA (sym)->attr.codimension;
6876           is_abstract = CLASS_DATA (sym)->attr.abstract;
6877         }
6878       else
6879         {
6880           allocatable = sym->attr.allocatable;
6881           pointer = sym->attr.pointer;
6882           dimension = sym->attr.dimension;
6883           codimension = sym->attr.codimension;
6884         }
6885
6886       coindexed = false;
6887
6888       for (ref = e->ref; ref; ref2 = ref, ref = ref->next)
6889         {
6890           switch (ref->type)
6891             {
6892               case REF_ARRAY:
6893                 if (ref->u.ar.codimen > 0)
6894                   {
6895                     int n;
6896                     for (n = ref->u.ar.dimen;
6897                          n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
6898                       if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
6899                         {
6900                           coindexed = true;
6901                           break;
6902                         }
6903                    }
6904
6905                 if (ref->next != NULL)
6906                   pointer = 0;
6907                 break;
6908
6909               case REF_COMPONENT:
6910                 /* F2008, C644.  */
6911                 if (coindexed)
6912                   {
6913                     gfc_error ("Coindexed allocatable object at %L",
6914                                &e->where);
6915                     goto failure;
6916                   }
6917
6918                 c = ref->u.c.component;
6919                 if (c->ts.type == BT_CLASS)
6920                   {
6921                     allocatable = CLASS_DATA (c)->attr.allocatable;
6922                     pointer = CLASS_DATA (c)->attr.class_pointer;
6923                     dimension = CLASS_DATA (c)->attr.dimension;
6924                     codimension = CLASS_DATA (c)->attr.codimension;
6925                     is_abstract = CLASS_DATA (c)->attr.abstract;
6926                   }
6927                 else
6928                   {
6929                     allocatable = c->attr.allocatable;
6930                     pointer = c->attr.pointer;
6931                     dimension = c->attr.dimension;
6932                     codimension = c->attr.codimension;
6933                     is_abstract = c->attr.abstract;
6934                   }
6935                 break;
6936
6937               case REF_SUBSTRING:
6938                 allocatable = 0;
6939                 pointer = 0;
6940                 break;
6941             }
6942         }
6943     }
6944
6945   if (allocatable == 0 && pointer == 0)
6946     {
6947       gfc_error ("Allocate-object at %L must be ALLOCATABLE or a POINTER",
6948                  &e->where);
6949       goto failure;
6950     }
6951
6952   /* Some checks for the SOURCE tag.  */
6953   if (code->expr3)
6954     {
6955       /* Check F03:C631.  */
6956       if (!gfc_type_compatible (&e->ts, &code->expr3->ts))
6957         {
6958           gfc_error ("Type of entity at %L is type incompatible with "
6959                       "source-expr at %L", &e->where, &code->expr3->where);
6960           goto failure;
6961         }
6962
6963       /* Check F03:C632 and restriction following Note 6.18.  */
6964       if (code->expr3->rank > 0
6965           && conformable_arrays (code->expr3, e) == FAILURE)
6966         goto failure;
6967
6968       /* Check F03:C633.  */
6969       if (code->expr3->ts.kind != e->ts.kind)
6970         {
6971           gfc_error ("The allocate-object at %L and the source-expr at %L "
6972                       "shall have the same kind type parameter",
6973                       &e->where, &code->expr3->where);
6974           goto failure;
6975         }
6976
6977       /* Check F2008, C642.  */
6978       if (code->expr3->ts.type == BT_DERIVED
6979           && ((codimension && gfc_expr_attr (code->expr3).lock_comp)
6980               || (code->expr3->ts.u.derived->from_intmod
6981                      == INTMOD_ISO_FORTRAN_ENV
6982                   && code->expr3->ts.u.derived->intmod_sym_id
6983                      == ISOFORTRAN_LOCK_TYPE)))
6984         {
6985           gfc_error ("The source-expr at %L shall neither be of type "
6986                      "LOCK_TYPE nor have a LOCK_TYPE component if "
6987                       "allocate-object at %L is a coarray",
6988                       &code->expr3->where, &e->where);
6989           goto failure;
6990         }
6991     }
6992
6993   /* Check F08:C629.  */
6994   if (is_abstract && code->ext.alloc.ts.type == BT_UNKNOWN
6995       && !code->expr3)
6996     {
6997       gcc_assert (e->ts.type == BT_CLASS);
6998       gfc_error ("Allocating %s of ABSTRACT base type at %L requires a "
6999                  "type-spec or source-expr", sym->name, &e->where);
7000       goto failure;
7001     }
7002
7003   if (code->ext.alloc.ts.type == BT_CHARACTER && !e->ts.deferred)
7004     {
7005       int cmp = gfc_dep_compare_expr (e->ts.u.cl->length,
7006                                       code->ext.alloc.ts.u.cl->length);
7007       if (cmp == 1 || cmp == -1 || cmp == -3)
7008         {
7009           gfc_error ("Allocating %s at %L with type-spec requires the same "
7010                      "character-length parameter as in the declaration",
7011                      sym->name, &e->where);
7012           goto failure;
7013         }
7014     }
7015
7016   /* In the variable definition context checks, gfc_expr_attr is used
7017      on the expression.  This is fooled by the array specification
7018      present in e, thus we have to eliminate that one temporarily.  */
7019   e2 = remove_last_array_ref (e);
7020   t = SUCCESS;
7021   if (t == SUCCESS && pointer)
7022     t = gfc_check_vardef_context (e2, true, true, _("ALLOCATE object"));
7023   if (t == SUCCESS)
7024     t = gfc_check_vardef_context (e2, false, true, _("ALLOCATE object"));
7025   gfc_free_expr (e2);
7026   if (t == FAILURE)
7027     goto failure;
7028
7029   if (e->ts.type == BT_CLASS && CLASS_DATA (e)->attr.dimension
7030         && !code->expr3 && code->ext.alloc.ts.type == BT_DERIVED)
7031     {
7032       /* For class arrays, the initialization with SOURCE is done
7033          using _copy and trans_call. It is convenient to exploit that
7034          when the allocated type is different from the declared type but
7035          no SOURCE exists by setting expr3.  */
7036       code->expr3 = gfc_default_initializer (&code->ext.alloc.ts);
7037     }
7038   else if (!code->expr3)
7039     {
7040       /* Set up default initializer if needed.  */
7041       gfc_typespec ts;
7042       gfc_expr *init_e;
7043
7044       if (code->ext.alloc.ts.type == BT_DERIVED)
7045         ts = code->ext.alloc.ts;
7046       else
7047         ts = e->ts;
7048
7049       if (ts.type == BT_CLASS)
7050         ts = ts.u.derived->components->ts;
7051
7052       if (ts.type == BT_DERIVED && (init_e = gfc_default_initializer (&ts)))
7053         {
7054           gfc_code *init_st = gfc_get_code ();
7055           init_st->loc = code->loc;
7056           init_st->op = EXEC_INIT_ASSIGN;
7057           init_st->expr1 = gfc_expr_to_initialize (e);
7058           init_st->expr2 = init_e;
7059           init_st->next = code->next;
7060           code->next = init_st;
7061         }
7062     }
7063   else if (code->expr3->mold && code->expr3->ts.type == BT_DERIVED)
7064     {
7065       /* Default initialization via MOLD (non-polymorphic).  */
7066       gfc_expr *rhs = gfc_default_initializer (&code->expr3->ts);
7067       gfc_resolve_expr (rhs);
7068       gfc_free_expr (code->expr3);
7069       code->expr3 = rhs;
7070     }
7071
7072   if (e->ts.type == BT_CLASS)
7073     {
7074       /* Make sure the vtab symbol is present when
7075          the module variables are generated.  */
7076       gfc_typespec ts = e->ts;
7077       if (code->expr3)
7078         ts = code->expr3->ts;
7079       else if (code->ext.alloc.ts.type == BT_DERIVED)
7080         ts = code->ext.alloc.ts;
7081       gfc_find_derived_vtab (ts.u.derived);
7082       if (dimension)
7083         e = gfc_expr_to_initialize (e);
7084     }
7085
7086   if (dimension == 0 && codimension == 0)
7087     goto success;
7088
7089   /* Make sure the last reference node is an array specifiction.  */
7090
7091   if (!ref2 || ref2->type != REF_ARRAY || ref2->u.ar.type == AR_FULL
7092       || (dimension && ref2->u.ar.dimen == 0))
7093     {
7094       gfc_error ("Array specification required in ALLOCATE statement "
7095                  "at %L", &e->where);
7096       goto failure;
7097     }
7098
7099   /* Make sure that the array section reference makes sense in the
7100     context of an ALLOCATE specification.  */
7101
7102   ar = &ref2->u.ar;
7103
7104   if (codimension)
7105     for (i = ar->dimen; i < ar->dimen + ar->codimen; i++)
7106       if (ar->dimen_type[i] == DIMEN_THIS_IMAGE)
7107         {
7108           gfc_error ("Coarray specification required in ALLOCATE statement "
7109                      "at %L", &e->where);
7110           goto failure;
7111         }
7112
7113   for (i = 0; i < ar->dimen; i++)
7114     {
7115       if (ref2->u.ar.type == AR_ELEMENT)
7116         goto check_symbols;
7117
7118       switch (ar->dimen_type[i])
7119         {
7120         case DIMEN_ELEMENT:
7121           break;
7122
7123         case DIMEN_RANGE:
7124           if (ar->start[i] != NULL
7125               && ar->end[i] != NULL
7126               && ar->stride[i] == NULL)
7127             break;
7128
7129           /* Fall Through...  */
7130
7131         case DIMEN_UNKNOWN:
7132         case DIMEN_VECTOR:
7133         case DIMEN_STAR:
7134         case DIMEN_THIS_IMAGE:
7135           gfc_error ("Bad array specification in ALLOCATE statement at %L",
7136                      &e->where);
7137           goto failure;
7138         }
7139
7140 check_symbols:
7141       for (a = code->ext.alloc.list; a; a = a->next)
7142         {
7143           sym = a->expr->symtree->n.sym;
7144
7145           /* TODO - check derived type components.  */
7146           if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
7147             continue;
7148
7149           if ((ar->start[i] != NULL
7150                && gfc_find_sym_in_expr (sym, ar->start[i]))
7151               || (ar->end[i] != NULL
7152                   && gfc_find_sym_in_expr (sym, ar->end[i])))
7153             {
7154               gfc_error ("'%s' must not appear in the array specification at "
7155                          "%L in the same ALLOCATE statement where it is "
7156                          "itself allocated", sym->name, &ar->where);
7157               goto failure;
7158             }
7159         }
7160     }
7161
7162   for (i = ar->dimen; i < ar->codimen + ar->dimen; i++)
7163     {
7164       if (ar->dimen_type[i] == DIMEN_ELEMENT
7165           || ar->dimen_type[i] == DIMEN_RANGE)
7166         {
7167           if (i == (ar->dimen + ar->codimen - 1))
7168             {
7169               gfc_error ("Expected '*' in coindex specification in ALLOCATE "
7170                          "statement at %L", &e->where);
7171               goto failure;
7172             }
7173           break;
7174         }
7175
7176       if (ar->dimen_type[i] == DIMEN_STAR && i == (ar->dimen + ar->codimen - 1)
7177           && ar->stride[i] == NULL)
7178         break;
7179
7180       gfc_error ("Bad coarray specification in ALLOCATE statement at %L",
7181                  &e->where);
7182       goto failure;
7183     }
7184
7185 success:
7186   return SUCCESS;
7187
7188 failure:
7189   return FAILURE;
7190 }
7191
7192 static void
7193 resolve_allocate_deallocate (gfc_code *code, const char *fcn)
7194 {
7195   gfc_expr *stat, *errmsg, *pe, *qe;
7196   gfc_alloc *a, *p, *q;
7197
7198   stat = code->expr1;
7199   errmsg = code->expr2;
7200
7201   /* Check the stat variable.  */
7202   if (stat)
7203     {
7204       gfc_check_vardef_context (stat, false, false, _("STAT variable"));
7205
7206       if ((stat->ts.type != BT_INTEGER
7207            && !(stat->ref && (stat->ref->type == REF_ARRAY
7208                               || stat->ref->type == REF_COMPONENT)))
7209           || stat->rank > 0)
7210         gfc_error ("Stat-variable at %L must be a scalar INTEGER "
7211                    "variable", &stat->where);
7212
7213       for (p = code->ext.alloc.list; p; p = p->next)
7214         if (p->expr->symtree->n.sym->name == stat->symtree->n.sym->name)
7215           {
7216             gfc_ref *ref1, *ref2;
7217             bool found = true;
7218
7219             for (ref1 = p->expr->ref, ref2 = stat->ref; ref1 && ref2;
7220                  ref1 = ref1->next, ref2 = ref2->next)
7221               {
7222                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7223                   continue;
7224                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7225                   {
7226                     found = false;
7227                     break;
7228                   }
7229               }
7230
7231             if (found)
7232               {
7233                 gfc_error ("Stat-variable at %L shall not be %sd within "
7234                            "the same %s statement", &stat->where, fcn, fcn);
7235                 break;
7236               }
7237           }
7238     }
7239
7240   /* Check the errmsg variable.  */
7241   if (errmsg)
7242     {
7243       if (!stat)
7244         gfc_warning ("ERRMSG at %L is useless without a STAT tag",
7245                      &errmsg->where);
7246
7247       gfc_check_vardef_context (errmsg, false, false, _("ERRMSG variable"));
7248
7249       if ((errmsg->ts.type != BT_CHARACTER
7250            && !(errmsg->ref
7251                 && (errmsg->ref->type == REF_ARRAY
7252                     || errmsg->ref->type == REF_COMPONENT)))
7253           || errmsg->rank > 0 )
7254         gfc_error ("Errmsg-variable at %L must be a scalar CHARACTER "
7255                    "variable", &errmsg->where);
7256
7257       for (p = code->ext.alloc.list; p; p = p->next)
7258         if (p->expr->symtree->n.sym->name == errmsg->symtree->n.sym->name)
7259           {
7260             gfc_ref *ref1, *ref2;
7261             bool found = true;
7262
7263             for (ref1 = p->expr->ref, ref2 = errmsg->ref; ref1 && ref2;
7264                  ref1 = ref1->next, ref2 = ref2->next)
7265               {
7266                 if (ref1->type != REF_COMPONENT || ref2->type != REF_COMPONENT)
7267                   continue;
7268                 if (ref1->u.c.component->name != ref2->u.c.component->name)
7269                   {
7270                     found = false;
7271                     break;
7272                   }
7273               }
7274
7275             if (found)
7276               {
7277                 gfc_error ("Errmsg-variable at %L shall not be %sd within "
7278                            "the same %s statement", &errmsg->where, fcn, fcn);
7279                 break;
7280               }
7281           }
7282     }
7283
7284   /* Check that an allocate-object appears only once in the statement.  */
7285
7286   for (p = code->ext.alloc.list; p; p = p->next)
7287     {
7288       pe = p->expr;
7289       for (q = p->next; q; q = q->next)
7290         {
7291           qe = q->expr;
7292           if (pe->symtree->n.sym->name == qe->symtree->n.sym->name)
7293             {
7294               /* This is a potential collision.  */
7295               gfc_ref *pr = pe->ref;
7296               gfc_ref *qr = qe->ref;
7297
7298               /* Follow the references  until
7299                  a) They start to differ, in which case there is no error;
7300                  you can deallocate a%b and a%c in a single statement
7301                  b) Both of them stop, which is an error
7302                  c) One of them stops, which is also an error.  */
7303               while (1)
7304                 {
7305                   if (pr == NULL && qr == NULL)
7306                     {
7307                       gfc_error ("Allocate-object at %L also appears at %L",
7308                                  &pe->where, &qe->where);
7309                       break;
7310                     }
7311                   else if (pr != NULL && qr == NULL)
7312                     {
7313                       gfc_error ("Allocate-object at %L is subobject of"
7314                                  " object at %L", &pe->where, &qe->where);
7315                       break;
7316                     }
7317                   else if (pr == NULL && qr != NULL)
7318                     {
7319                       gfc_error ("Allocate-object at %L is subobject of"
7320                                  " object at %L", &qe->where, &pe->where);
7321                       break;
7322                     }
7323                   /* Here, pr != NULL && qr != NULL  */
7324                   gcc_assert(pr->type == qr->type);
7325                   if (pr->type == REF_ARRAY)
7326                     {
7327                       /* Handle cases like allocate(v(3)%x(3), v(2)%x(3)),
7328                          which are legal.  */
7329                       gcc_assert (qr->type == REF_ARRAY);
7330
7331                       if (pr->next && qr->next)
7332                         {
7333                           int i;
7334                           gfc_array_ref *par = &(pr->u.ar);
7335                           gfc_array_ref *qar = &(qr->u.ar);
7336
7337                           for (i=0; i<par->dimen; i++)
7338                             {
7339                               if ((par->start[i] != NULL
7340                                    || qar->start[i] != NULL)
7341                                   && gfc_dep_compare_expr (par->start[i],
7342                                                            qar->start[i]) != 0)
7343                                 goto break_label;
7344                             }
7345                         }
7346                     }
7347                   else
7348                     {
7349                       if (pr->u.c.component->name != qr->u.c.component->name)
7350                         break;
7351                     }
7352
7353                   pr = pr->next;
7354                   qr = qr->next;
7355                 }
7356             break_label:
7357               ;
7358             }
7359         }
7360     }
7361
7362   if (strcmp (fcn, "ALLOCATE") == 0)
7363     {
7364       for (a = code->ext.alloc.list; a; a = a->next)
7365         resolve_allocate_expr (a->expr, code);
7366     }
7367   else
7368     {
7369       for (a = code->ext.alloc.list; a; a = a->next)
7370         resolve_deallocate_expr (a->expr);
7371     }
7372 }
7373
7374
7375 /************ SELECT CASE resolution subroutines ************/
7376
7377 /* Callback function for our mergesort variant.  Determines interval
7378    overlaps for CASEs. Return <0 if op1 < op2, 0 for overlap, >0 for
7379    op1 > op2.  Assumes we're not dealing with the default case.
7380    We have op1 = (:L), (K:L) or (K:) and op2 = (:N), (M:N) or (M:).
7381    There are nine situations to check.  */
7382
7383 static int
7384 compare_cases (const gfc_case *op1, const gfc_case *op2)
7385 {
7386   int retval;
7387
7388   if (op1->low == NULL) /* op1 = (:L)  */
7389     {
7390       /* op2 = (:N), so overlap.  */
7391       retval = 0;
7392       /* op2 = (M:) or (M:N),  L < M  */
7393       if (op2->low != NULL
7394           && gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7395         retval = -1;
7396     }
7397   else if (op1->high == NULL) /* op1 = (K:)  */
7398     {
7399       /* op2 = (M:), so overlap.  */
7400       retval = 0;
7401       /* op2 = (:N) or (M:N), K > N  */
7402       if (op2->high != NULL
7403           && gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7404         retval = 1;
7405     }
7406   else /* op1 = (K:L)  */
7407     {
7408       if (op2->low == NULL)       /* op2 = (:N), K > N  */
7409         retval = (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7410                  ? 1 : 0;
7411       else if (op2->high == NULL) /* op2 = (M:), L < M  */
7412         retval = (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7413                  ? -1 : 0;
7414       else                      /* op2 = (M:N)  */
7415         {
7416           retval =  0;
7417           /* L < M  */
7418           if (gfc_compare_expr (op1->high, op2->low, INTRINSIC_LT) < 0)
7419             retval =  -1;
7420           /* K > N  */
7421           else if (gfc_compare_expr (op1->low, op2->high, INTRINSIC_GT) > 0)
7422             retval =  1;
7423         }
7424     }
7425
7426   return retval;
7427 }
7428
7429
7430 /* Merge-sort a double linked case list, detecting overlap in the
7431    process.  LIST is the head of the double linked case list before it
7432    is sorted.  Returns the head of the sorted list if we don't see any
7433    overlap, or NULL otherwise.  */
7434
7435 static gfc_case *
7436 check_case_overlap (gfc_case *list)
7437 {
7438   gfc_case *p, *q, *e, *tail;
7439   int insize, nmerges, psize, qsize, cmp, overlap_seen;
7440
7441   /* If the passed list was empty, return immediately.  */
7442   if (!list)
7443     return NULL;
7444
7445   overlap_seen = 0;
7446   insize = 1;
7447
7448   /* Loop unconditionally.  The only exit from this loop is a return
7449      statement, when we've finished sorting the case list.  */
7450   for (;;)
7451     {
7452       p = list;
7453       list = NULL;
7454       tail = NULL;
7455
7456       /* Count the number of merges we do in this pass.  */
7457       nmerges = 0;
7458
7459       /* Loop while there exists a merge to be done.  */
7460       while (p)
7461         {
7462           int i;
7463
7464           /* Count this merge.  */
7465           nmerges++;
7466
7467           /* Cut the list in two pieces by stepping INSIZE places
7468              forward in the list, starting from P.  */
7469           psize = 0;
7470           q = p;
7471           for (i = 0; i < insize; i++)
7472             {
7473               psize++;
7474               q = q->right;
7475               if (!q)
7476                 break;
7477             }
7478           qsize = insize;
7479
7480           /* Now we have two lists.  Merge them!  */
7481           while (psize > 0 || (qsize > 0 && q != NULL))
7482             {
7483               /* See from which the next case to merge comes from.  */
7484               if (psize == 0)
7485                 {
7486                   /* P is empty so the next case must come from Q.  */
7487                   e = q;
7488                   q = q->right;
7489                   qsize--;
7490                 }
7491               else if (qsize == 0 || q == NULL)
7492                 {
7493                   /* Q is empty.  */
7494                   e = p;
7495                   p = p->right;
7496                   psize--;
7497                 }
7498               else
7499                 {
7500                   cmp = compare_cases (p, q);
7501                   if (cmp < 0)
7502                     {
7503                       /* The whole case range for P is less than the
7504                          one for Q.  */
7505                       e = p;
7506                       p = p->right;
7507                       psize--;
7508                     }
7509                   else if (cmp > 0)
7510                     {
7511                       /* The whole case range for Q is greater than
7512                          the case range for P.  */
7513                       e = q;
7514                       q = q->right;
7515                       qsize--;
7516                     }
7517                   else
7518                     {
7519                       /* The cases overlap, or they are the same
7520                          element in the list.  Either way, we must
7521                          issue an error and get the next case from P.  */
7522                       /* FIXME: Sort P and Q by line number.  */
7523                       gfc_error ("CASE label at %L overlaps with CASE "
7524                                  "label at %L", &p->where, &q->where);
7525                       overlap_seen = 1;
7526                       e = p;
7527                       p = p->right;
7528                       psize--;
7529                     }
7530                 }
7531
7532                 /* Add the next element to the merged list.  */
7533               if (tail)
7534                 tail->right = e;
7535               else
7536                 list = e;
7537               e->left = tail;
7538               tail = e;
7539             }
7540
7541           /* P has now stepped INSIZE places along, and so has Q.  So
7542              they're the same.  */
7543           p = q;
7544         }
7545       tail->right = NULL;
7546
7547       /* If we have done only one merge or none at all, we've
7548          finished sorting the cases.  */
7549       if (nmerges <= 1)
7550         {
7551           if (!overlap_seen)
7552             return list;
7553           else
7554             return NULL;
7555         }
7556
7557       /* Otherwise repeat, merging lists twice the size.  */
7558       insize *= 2;
7559     }
7560 }
7561
7562
7563 /* Check to see if an expression is suitable for use in a CASE statement.
7564    Makes sure that all case expressions are scalar constants of the same
7565    type.  Return FAILURE if anything is wrong.  */
7566
7567 static gfc_try
7568 validate_case_label_expr (gfc_expr *e, gfc_expr *case_expr)
7569 {
7570   if (e == NULL) return SUCCESS;
7571
7572   if (e->ts.type != case_expr->ts.type)
7573     {
7574       gfc_error ("Expression in CASE statement at %L must be of type %s",
7575                  &e->where, gfc_basic_typename (case_expr->ts.type));
7576       return FAILURE;
7577     }
7578
7579   /* C805 (R808) For a given case-construct, each case-value shall be of
7580      the same type as case-expr.  For character type, length differences
7581      are allowed, but the kind type parameters shall be the same.  */
7582
7583   if (case_expr->ts.type == BT_CHARACTER && e->ts.kind != case_expr->ts.kind)
7584     {
7585       gfc_error ("Expression in CASE statement at %L must be of kind %d",
7586                  &e->where, case_expr->ts.kind);
7587       return FAILURE;
7588     }
7589
7590   /* Convert the case value kind to that of case expression kind,
7591      if needed */
7592
7593   if (e->ts.kind != case_expr->ts.kind)
7594     gfc_convert_type_warn (e, &case_expr->ts, 2, 0);
7595
7596   if (e->rank != 0)
7597     {
7598       gfc_error ("Expression in CASE statement at %L must be scalar",
7599                  &e->where);
7600       return FAILURE;
7601     }
7602
7603   return SUCCESS;
7604 }
7605
7606
7607 /* Given a completely parsed select statement, we:
7608
7609      - Validate all expressions and code within the SELECT.
7610      - Make sure that the selection expression is not of the wrong type.
7611      - Make sure that no case ranges overlap.
7612      - Eliminate unreachable cases and unreachable code resulting from
7613        removing case labels.
7614
7615    The standard does allow unreachable cases, e.g. CASE (5:3).  But
7616    they are a hassle for code generation, and to prevent that, we just
7617    cut them out here.  This is not necessary for overlapping cases
7618    because they are illegal and we never even try to generate code.
7619
7620    We have the additional caveat that a SELECT construct could have
7621    been a computed GOTO in the source code. Fortunately we can fairly
7622    easily work around that here: The case_expr for a "real" SELECT CASE
7623    is in code->expr1, but for a computed GOTO it is in code->expr2. All
7624    we have to do is make sure that the case_expr is a scalar integer
7625    expression.  */
7626
7627 static void
7628 resolve_select (gfc_code *code, bool select_type)
7629 {
7630   gfc_code *body;
7631   gfc_expr *case_expr;
7632   gfc_case *cp, *default_case, *tail, *head;
7633   int seen_unreachable;
7634   int seen_logical;
7635   int ncases;
7636   bt type;
7637   gfc_try t;
7638
7639   if (code->expr1 == NULL)
7640     {
7641       /* This was actually a computed GOTO statement.  */
7642       case_expr = code->expr2;
7643       if (case_expr->ts.type != BT_INTEGER|| case_expr->rank != 0)
7644         gfc_error ("Selection expression in computed GOTO statement "
7645                    "at %L must be a scalar integer expression",
7646                    &case_expr->where);
7647
7648       /* Further checking is not necessary because this SELECT was built
7649          by the compiler, so it should always be OK.  Just move the
7650          case_expr from expr2 to expr so that we can handle computed
7651          GOTOs as normal SELECTs from here on.  */
7652       code->expr1 = code->expr2;
7653       code->expr2 = NULL;
7654       return;
7655     }
7656
7657   case_expr = code->expr1;
7658   type = case_expr->ts.type;
7659
7660   /* F08:C830.  */
7661   if (type != BT_LOGICAL && type != BT_INTEGER && type != BT_CHARACTER)
7662     {
7663       gfc_error ("Argument of SELECT statement at %L cannot be %s",
7664                  &case_expr->where, gfc_typename (&case_expr->ts));
7665
7666       /* Punt. Going on here just produce more garbage error messages.  */
7667       return;
7668     }
7669
7670   /* F08:R842.  */
7671   if (!select_type && case_expr->rank != 0)
7672     {
7673       gfc_error ("Argument of SELECT statement at %L must be a scalar "
7674                  "expression", &case_expr->where);
7675
7676       /* Punt.  */
7677       return;
7678     }
7679
7680   /* Raise a warning if an INTEGER case value exceeds the range of
7681      the case-expr. Later, all expressions will be promoted to the
7682      largest kind of all case-labels.  */
7683
7684   if (type == BT_INTEGER)
7685     for (body = code->block; body; body = body->block)
7686       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7687         {
7688           if (cp->low
7689               && gfc_check_integer_range (cp->low->value.integer,
7690                                           case_expr->ts.kind) != ARITH_OK)
7691             gfc_warning ("Expression in CASE statement at %L is "
7692                          "not in the range of %s", &cp->low->where,
7693                          gfc_typename (&case_expr->ts));
7694
7695           if (cp->high
7696               && cp->low != cp->high
7697               && gfc_check_integer_range (cp->high->value.integer,
7698                                           case_expr->ts.kind) != ARITH_OK)
7699             gfc_warning ("Expression in CASE statement at %L is "
7700                          "not in the range of %s", &cp->high->where,
7701                          gfc_typename (&case_expr->ts));
7702         }
7703
7704   /* PR 19168 has a long discussion concerning a mismatch of the kinds
7705      of the SELECT CASE expression and its CASE values.  Walk the lists
7706      of case values, and if we find a mismatch, promote case_expr to
7707      the appropriate kind.  */
7708
7709   if (type == BT_LOGICAL || type == BT_INTEGER)
7710     {
7711       for (body = code->block; body; body = body->block)
7712         {
7713           /* Walk the case label list.  */
7714           for (cp = body->ext.block.case_list; cp; cp = cp->next)
7715             {
7716               /* Intercept the DEFAULT case.  It does not have a kind.  */
7717               if (cp->low == NULL && cp->high == NULL)
7718                 continue;
7719
7720               /* Unreachable case ranges are discarded, so ignore.  */
7721               if (cp->low != NULL && cp->high != NULL
7722                   && cp->low != cp->high
7723                   && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7724                 continue;
7725
7726               if (cp->low != NULL
7727                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->low))
7728                 gfc_convert_type_warn (case_expr, &cp->low->ts, 2, 0);
7729
7730               if (cp->high != NULL
7731                   && case_expr->ts.kind != gfc_kind_max(case_expr, cp->high))
7732                 gfc_convert_type_warn (case_expr, &cp->high->ts, 2, 0);
7733             }
7734          }
7735     }
7736
7737   /* Assume there is no DEFAULT case.  */
7738   default_case = NULL;
7739   head = tail = NULL;
7740   ncases = 0;
7741   seen_logical = 0;
7742
7743   for (body = code->block; body; body = body->block)
7744     {
7745       /* Assume the CASE list is OK, and all CASE labels can be matched.  */
7746       t = SUCCESS;
7747       seen_unreachable = 0;
7748
7749       /* Walk the case label list, making sure that all case labels
7750          are legal.  */
7751       for (cp = body->ext.block.case_list; cp; cp = cp->next)
7752         {
7753           /* Count the number of cases in the whole construct.  */
7754           ncases++;
7755
7756           /* Intercept the DEFAULT case.  */
7757           if (cp->low == NULL && cp->high == NULL)
7758             {
7759               if (default_case != NULL)
7760                 {
7761                   gfc_error ("The DEFAULT CASE at %L cannot be followed "
7762                              "by a second DEFAULT CASE at %L",
7763                              &default_case->where, &cp->where);
7764                   t = FAILURE;
7765                   break;
7766                 }
7767               else
7768                 {
7769                   default_case = cp;
7770                   continue;
7771                 }
7772             }
7773
7774           /* Deal with single value cases and case ranges.  Errors are
7775              issued from the validation function.  */
7776           if (validate_case_label_expr (cp->low, case_expr) != SUCCESS
7777               || validate_case_label_expr (cp->high, case_expr) != SUCCESS)
7778             {
7779               t = FAILURE;
7780               break;
7781             }
7782
7783           if (type == BT_LOGICAL
7784               && ((cp->low == NULL || cp->high == NULL)
7785                   || cp->low != cp->high))
7786             {
7787               gfc_error ("Logical range in CASE statement at %L is not "
7788                          "allowed", &cp->low->where);
7789               t = FAILURE;
7790               break;
7791             }
7792
7793           if (type == BT_LOGICAL && cp->low->expr_type == EXPR_CONSTANT)
7794             {
7795               int value;
7796               value = cp->low->value.logical == 0 ? 2 : 1;
7797               if (value & seen_logical)
7798                 {
7799                   gfc_error ("Constant logical value in CASE statement "
7800                              "is repeated at %L",
7801                              &cp->low->where);
7802                   t = FAILURE;
7803                   break;
7804                 }
7805               seen_logical |= value;
7806             }
7807
7808           if (cp->low != NULL && cp->high != NULL
7809               && cp->low != cp->high
7810               && gfc_compare_expr (cp->low, cp->high, INTRINSIC_GT) > 0)
7811             {
7812               if (gfc_option.warn_surprising)
7813                 gfc_warning ("Range specification at %L can never "
7814                              "be matched", &cp->where);
7815
7816               cp->unreachable = 1;
7817               seen_unreachable = 1;
7818             }
7819           else
7820             {
7821               /* If the case range can be matched, it can also overlap with
7822                  other cases.  To make sure it does not, we put it in a
7823                  double linked list here.  We sort that with a merge sort
7824                  later on to detect any overlapping cases.  */
7825               if (!head)
7826                 {
7827                   head = tail = cp;
7828                   head->right = head->left = NULL;
7829                 }
7830               else
7831                 {
7832                   tail->right = cp;
7833                   tail->right->left = tail;
7834                   tail = tail->right;
7835                   tail->right = NULL;
7836                 }
7837             }
7838         }
7839
7840       /* It there was a failure in the previous case label, give up
7841          for this case label list.  Continue with the next block.  */
7842       if (t == FAILURE)
7843         continue;
7844
7845       /* See if any case labels that are unreachable have been seen.
7846          If so, we eliminate them.  This is a bit of a kludge because
7847          the case lists for a single case statement (label) is a
7848          single forward linked lists.  */
7849       if (seen_unreachable)
7850       {
7851         /* Advance until the first case in the list is reachable.  */
7852         while (body->ext.block.case_list != NULL
7853                && body->ext.block.case_list->unreachable)
7854           {
7855             gfc_case *n = body->ext.block.case_list;
7856             body->ext.block.case_list = body->ext.block.case_list->next;
7857             n->next = NULL;
7858             gfc_free_case_list (n);
7859           }
7860
7861         /* Strip all other unreachable cases.  */
7862         if (body->ext.block.case_list)
7863           {
7864             for (cp = body->ext.block.case_list; cp->next; cp = cp->next)
7865               {
7866                 if (cp->next->unreachable)
7867                   {
7868                     gfc_case *n = cp->next;
7869                     cp->next = cp->next->next;
7870                     n->next = NULL;
7871                     gfc_free_case_list (n);
7872                   }
7873               }
7874           }
7875       }
7876     }
7877
7878   /* See if there were overlapping cases.  If the check returns NULL,
7879      there was overlap.  In that case we don't do anything.  If head
7880      is non-NULL, we prepend the DEFAULT case.  The sorted list can
7881      then used during code generation for SELECT CASE constructs with
7882      a case expression of a CHARACTER type.  */
7883   if (head)
7884     {
7885       head = check_case_overlap (head);
7886
7887       /* Prepend the default_case if it is there.  */
7888       if (head != NULL && default_case)
7889         {
7890           default_case->left = NULL;
7891           default_case->right = head;
7892           head->left = default_case;
7893         }
7894     }
7895
7896   /* Eliminate dead blocks that may be the result if we've seen
7897      unreachable case labels for a block.  */
7898   for (body = code; body && body->block; body = body->block)
7899     {
7900       if (body->block->ext.block.case_list == NULL)
7901         {
7902           /* Cut the unreachable block from the code chain.  */
7903           gfc_code *c = body->block;
7904           body->block = c->block;
7905
7906           /* Kill the dead block, but not the blocks below it.  */
7907           c->block = NULL;
7908           gfc_free_statements (c);
7909         }
7910     }
7911
7912   /* More than two cases is legal but insane for logical selects.
7913      Issue a warning for it.  */
7914   if (gfc_option.warn_surprising && type == BT_LOGICAL
7915       && ncases > 2)
7916     gfc_warning ("Logical SELECT CASE block at %L has more that two cases",
7917                  &code->loc);
7918 }
7919
7920
7921 /* Check if a derived type is extensible.  */
7922
7923 bool
7924 gfc_type_is_extensible (gfc_symbol *sym)
7925 {
7926   return !(sym->attr.is_bind_c || sym->attr.sequence);
7927 }
7928
7929
7930 /* Resolve an associate name:  Resolve target and ensure the type-spec is
7931    correct as well as possibly the array-spec.  */
7932
7933 static void
7934 resolve_assoc_var (gfc_symbol* sym, bool resolve_target)
7935 {
7936   gfc_expr* target;
7937
7938   gcc_assert (sym->assoc);
7939   gcc_assert (sym->attr.flavor == FL_VARIABLE);
7940
7941   /* If this is for SELECT TYPE, the target may not yet be set.  In that
7942      case, return.  Resolution will be called later manually again when
7943      this is done.  */
7944   target = sym->assoc->target;
7945   if (!target)
7946     return;
7947   gcc_assert (!sym->assoc->dangling);
7948
7949   if (resolve_target && gfc_resolve_expr (target) != SUCCESS)
7950     return;
7951
7952   /* For variable targets, we get some attributes from the target.  */
7953   if (target->expr_type == EXPR_VARIABLE)
7954     {
7955       gfc_symbol* tsym;
7956
7957       gcc_assert (target->symtree);
7958       tsym = target->symtree->n.sym;
7959
7960       sym->attr.asynchronous = tsym->attr.asynchronous;
7961       sym->attr.volatile_ = tsym->attr.volatile_;
7962
7963       sym->attr.target = tsym->attr.target
7964                          || gfc_expr_attr (target).pointer;
7965     }
7966
7967   /* Get type if this was not already set.  Note that it can be
7968      some other type than the target in case this is a SELECT TYPE
7969      selector!  So we must not update when the type is already there.  */
7970   if (sym->ts.type == BT_UNKNOWN)
7971     sym->ts = target->ts;
7972   gcc_assert (sym->ts.type != BT_UNKNOWN);
7973
7974   /* See if this is a valid association-to-variable.  */
7975   sym->assoc->variable = (target->expr_type == EXPR_VARIABLE
7976                           && !gfc_has_vector_subscript (target));
7977
7978   /* Finally resolve if this is an array or not.  */
7979   if (sym->attr.dimension && target->rank == 0)
7980     {
7981       gfc_error ("Associate-name '%s' at %L is used as array",
7982                  sym->name, &sym->declared_at);
7983       sym->attr.dimension = 0;
7984       return;
7985     }
7986   if (target->rank > 0)
7987     sym->attr.dimension = 1;
7988
7989   if (sym->attr.dimension)
7990     {
7991       sym->as = gfc_get_array_spec ();
7992       sym->as->rank = target->rank;
7993       sym->as->type = AS_DEFERRED;
7994
7995       /* Target must not be coindexed, thus the associate-variable
7996          has no corank.  */
7997       sym->as->corank = 0;
7998     }
7999 }
8000
8001
8002 /* Resolve a SELECT TYPE statement.  */
8003
8004 static void
8005 resolve_select_type (gfc_code *code, gfc_namespace *old_ns)
8006 {
8007   gfc_symbol *selector_type;
8008   gfc_code *body, *new_st, *if_st, *tail;
8009   gfc_code *class_is = NULL, *default_case = NULL;
8010   gfc_case *c;
8011   gfc_symtree *st;
8012   char name[GFC_MAX_SYMBOL_LEN];
8013   gfc_namespace *ns;
8014   int error = 0;
8015
8016   ns = code->ext.block.ns;
8017   gfc_resolve (ns);
8018
8019   /* Check for F03:C813.  */
8020   if (code->expr1->ts.type != BT_CLASS
8021       && !(code->expr2 && code->expr2->ts.type == BT_CLASS))
8022     {
8023       gfc_error ("Selector shall be polymorphic in SELECT TYPE statement "
8024                  "at %L", &code->loc);
8025       return;
8026     }
8027
8028   if (!code->expr1->symtree->n.sym->attr.class_ok)
8029     return;
8030
8031   if (code->expr2)
8032     {
8033       if (code->expr1->symtree->n.sym->attr.untyped)
8034         code->expr1->symtree->n.sym->ts = code->expr2->ts;
8035       selector_type = CLASS_DATA (code->expr2)->ts.u.derived;
8036     }
8037   else
8038     selector_type = CLASS_DATA (code->expr1)->ts.u.derived;
8039
8040   /* Loop over TYPE IS / CLASS IS cases.  */
8041   for (body = code->block; body; body = body->block)
8042     {
8043       c = body->ext.block.case_list;
8044
8045       /* Check F03:C815.  */
8046       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
8047           && !gfc_type_is_extensible (c->ts.u.derived))
8048         {
8049           gfc_error ("Derived type '%s' at %L must be extensible",
8050                      c->ts.u.derived->name, &c->where);
8051           error++;
8052           continue;
8053         }
8054
8055       /* Check F03:C816.  */
8056       if ((c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
8057           && !gfc_type_is_extension_of (selector_type, c->ts.u.derived))
8058         {
8059           gfc_error ("Derived type '%s' at %L must be an extension of '%s'",
8060                      c->ts.u.derived->name, &c->where, selector_type->name);
8061           error++;
8062           continue;
8063         }
8064
8065       /* Intercept the DEFAULT case.  */
8066       if (c->ts.type == BT_UNKNOWN)
8067         {
8068           /* Check F03:C818.  */
8069           if (default_case)
8070             {
8071               gfc_error ("The DEFAULT CASE at %L cannot be followed "
8072                          "by a second DEFAULT CASE at %L",
8073                          &default_case->ext.block.case_list->where, &c->where);
8074               error++;
8075               continue;
8076             }
8077
8078           default_case = body;
8079         }
8080     }
8081
8082   if (error > 0)
8083     return;
8084
8085   /* Transform SELECT TYPE statement to BLOCK and associate selector to
8086      target if present.  If there are any EXIT statements referring to the
8087      SELECT TYPE construct, this is no problem because the gfc_code
8088      reference stays the same and EXIT is equally possible from the BLOCK
8089      it is changed to.  */
8090   code->op = EXEC_BLOCK;
8091   if (code->expr2)
8092     {
8093       gfc_association_list* assoc;
8094
8095       assoc = gfc_get_association_list ();
8096       assoc->st = code->expr1->symtree;
8097       assoc->target = gfc_copy_expr (code->expr2);
8098       assoc->target->where = code->expr2->where;
8099       /* assoc->variable will be set by resolve_assoc_var.  */
8100
8101       code->ext.block.assoc = assoc;
8102       code->expr1->symtree->n.sym->assoc = assoc;
8103
8104       resolve_assoc_var (code->expr1->symtree->n.sym, false);
8105     }
8106   else
8107     code->ext.block.assoc = NULL;
8108
8109   /* Add EXEC_SELECT to switch on type.  */
8110   new_st = gfc_get_code ();
8111   new_st->op = code->op;
8112   new_st->expr1 = code->expr1;
8113   new_st->expr2 = code->expr2;
8114   new_st->block = code->block;
8115   code->expr1 = code->expr2 =  NULL;
8116   code->block = NULL;
8117   if (!ns->code)
8118     ns->code = new_st;
8119   else
8120     ns->code->next = new_st;
8121   code = new_st;
8122   code->op = EXEC_SELECT;
8123   gfc_add_vptr_component (code->expr1);
8124   gfc_add_hash_component (code->expr1);
8125
8126   /* Loop over TYPE IS / CLASS IS cases.  */
8127   for (body = code->block; body; body = body->block)
8128     {
8129       c = body->ext.block.case_list;
8130
8131       if (c->ts.type == BT_DERIVED)
8132         c->low = c->high = gfc_get_int_expr (gfc_default_integer_kind, NULL,
8133                                              c->ts.u.derived->hash_value);
8134
8135       else if (c->ts.type == BT_UNKNOWN)
8136         continue;
8137
8138       /* Associate temporary to selector.  This should only be done
8139          when this case is actually true, so build a new ASSOCIATE
8140          that does precisely this here (instead of using the
8141          'global' one).  */
8142
8143       if (c->ts.type == BT_CLASS)
8144         sprintf (name, "__tmp_class_%s", c->ts.u.derived->name);
8145       else
8146         sprintf (name, "__tmp_type_%s", c->ts.u.derived->name);
8147       st = gfc_find_symtree (ns->sym_root, name);
8148       gcc_assert (st->n.sym->assoc);
8149       st->n.sym->assoc->target = gfc_get_variable_expr (code->expr1->symtree);
8150       st->n.sym->assoc->target->where = code->expr1->where;
8151       if (c->ts.type == BT_DERIVED)
8152         gfc_add_data_component (st->n.sym->assoc->target);
8153
8154       new_st = gfc_get_code ();
8155       new_st->op = EXEC_BLOCK;
8156       new_st->ext.block.ns = gfc_build_block_ns (ns);
8157       new_st->ext.block.ns->code = body->next;
8158       body->next = new_st;
8159
8160       /* Chain in the new list only if it is marked as dangling.  Otherwise
8161          there is a CASE label overlap and this is already used.  Just ignore,
8162          the error is diagonsed elsewhere.  */
8163       if (st->n.sym->assoc->dangling)
8164         {
8165           new_st->ext.block.assoc = st->n.sym->assoc;
8166           st->n.sym->assoc->dangling = 0;
8167         }
8168
8169       resolve_assoc_var (st->n.sym, false);
8170     }
8171
8172   /* Take out CLASS IS cases for separate treatment.  */
8173   body = code;
8174   while (body && body->block)
8175     {
8176       if (body->block->ext.block.case_list->ts.type == BT_CLASS)
8177         {
8178           /* Add to class_is list.  */
8179           if (class_is == NULL)
8180             {
8181               class_is = body->block;
8182               tail = class_is;
8183             }
8184           else
8185             {
8186               for (tail = class_is; tail->block; tail = tail->block) ;
8187               tail->block = body->block;
8188               tail = tail->block;
8189             }
8190           /* Remove from EXEC_SELECT list.  */
8191           body->block = body->block->block;
8192           tail->block = NULL;
8193         }
8194       else
8195         body = body->block;
8196     }
8197
8198   if (class_is)
8199     {
8200       gfc_symbol *vtab;
8201
8202       if (!default_case)
8203         {
8204           /* Add a default case to hold the CLASS IS cases.  */
8205           for (tail = code; tail->block; tail = tail->block) ;
8206           tail->block = gfc_get_code ();
8207           tail = tail->block;
8208           tail->op = EXEC_SELECT_TYPE;
8209           tail->ext.block.case_list = gfc_get_case ();
8210           tail->ext.block.case_list->ts.type = BT_UNKNOWN;
8211           tail->next = NULL;
8212           default_case = tail;
8213         }
8214
8215       /* More than one CLASS IS block?  */
8216       if (class_is->block)
8217         {
8218           gfc_code **c1,*c2;
8219           bool swapped;
8220           /* Sort CLASS IS blocks by extension level.  */
8221           do
8222             {
8223               swapped = false;
8224               for (c1 = &class_is; (*c1) && (*c1)->block; c1 = &((*c1)->block))
8225                 {
8226                   c2 = (*c1)->block;
8227                   /* F03:C817 (check for doubles).  */
8228                   if ((*c1)->ext.block.case_list->ts.u.derived->hash_value
8229                       == c2->ext.block.case_list->ts.u.derived->hash_value)
8230                     {
8231                       gfc_error ("Double CLASS IS block in SELECT TYPE "
8232                                  "statement at %L",
8233                                  &c2->ext.block.case_list->where);
8234                       return;
8235                     }
8236                   if ((*c1)->ext.block.case_list->ts.u.derived->attr.extension
8237                       < c2->ext.block.case_list->ts.u.derived->attr.extension)
8238                     {
8239                       /* Swap.  */
8240                       (*c1)->block = c2->block;
8241                       c2->block = *c1;
8242                       *c1 = c2;
8243                       swapped = true;
8244                     }
8245                 }
8246             }
8247           while (swapped);
8248         }
8249
8250       /* Generate IF chain.  */
8251       if_st = gfc_get_code ();
8252       if_st->op = EXEC_IF;
8253       new_st = if_st;
8254       for (body = class_is; body; body = body->block)
8255         {
8256           new_st->block = gfc_get_code ();
8257           new_st = new_st->block;
8258           new_st->op = EXEC_IF;
8259           /* Set up IF condition: Call _gfortran_is_extension_of.  */
8260           new_st->expr1 = gfc_get_expr ();
8261           new_st->expr1->expr_type = EXPR_FUNCTION;
8262           new_st->expr1->ts.type = BT_LOGICAL;
8263           new_st->expr1->ts.kind = 4;
8264           new_st->expr1->value.function.name = gfc_get_string (PREFIX ("is_extension_of"));
8265           new_st->expr1->value.function.isym = XCNEW (gfc_intrinsic_sym);
8266           new_st->expr1->value.function.isym->id = GFC_ISYM_EXTENDS_TYPE_OF;
8267           /* Set up arguments.  */
8268           new_st->expr1->value.function.actual = gfc_get_actual_arglist ();
8269           new_st->expr1->value.function.actual->expr = gfc_get_variable_expr (code->expr1->symtree);
8270           new_st->expr1->value.function.actual->expr->where = code->loc;
8271           gfc_add_vptr_component (new_st->expr1->value.function.actual->expr);
8272           vtab = gfc_find_derived_vtab (body->ext.block.case_list->ts.u.derived);
8273           st = gfc_find_symtree (vtab->ns->sym_root, vtab->name);
8274           new_st->expr1->value.function.actual->next = gfc_get_actual_arglist ();
8275           new_st->expr1->value.function.actual->next->expr = gfc_get_variable_expr (st);
8276           new_st->next = body->next;
8277         }
8278         if (default_case->next)
8279           {
8280             new_st->block = gfc_get_code ();
8281             new_st = new_st->block;
8282             new_st->op = EXEC_IF;
8283             new_st->next = default_case->next;
8284           }
8285
8286         /* Replace CLASS DEFAULT code by the IF chain.  */
8287         default_case->next = if_st;
8288     }
8289
8290   /* Resolve the internal code.  This can not be done earlier because
8291      it requires that the sym->assoc of selectors is set already.  */
8292   gfc_current_ns = ns;
8293   gfc_resolve_blocks (code->block, gfc_current_ns);
8294   gfc_current_ns = old_ns;
8295
8296   resolve_select (code, true);
8297 }
8298
8299
8300 /* Resolve a transfer statement. This is making sure that:
8301    -- a derived type being transferred has only non-pointer components
8302    -- a derived type being transferred doesn't have private components, unless
8303       it's being transferred from the module where the type was defined
8304    -- we're not trying to transfer a whole assumed size array.  */
8305
8306 static void
8307 resolve_transfer (gfc_code *code)
8308 {
8309   gfc_typespec *ts;
8310   gfc_symbol *sym;
8311   gfc_ref *ref;
8312   gfc_expr *exp;
8313
8314   exp = code->expr1;
8315
8316   while (exp != NULL && exp->expr_type == EXPR_OP
8317          && exp->value.op.op == INTRINSIC_PARENTHESES)
8318     exp = exp->value.op.op1;
8319
8320   if (exp && exp->expr_type == EXPR_NULL && exp->ts.type == BT_UNKNOWN)
8321     {
8322       gfc_error ("NULL intrinsic at %L in data transfer statement requires "
8323                  "MOLD=", &exp->where);
8324       return;
8325     }
8326
8327   if (exp == NULL || (exp->expr_type != EXPR_VARIABLE
8328                       && exp->expr_type != EXPR_FUNCTION))
8329     return;
8330
8331   /* If we are reading, the variable will be changed.  Note that
8332      code->ext.dt may be NULL if the TRANSFER is related to
8333      an INQUIRE statement -- but in this case, we are not reading, either.  */
8334   if (code->ext.dt && code->ext.dt->dt_io_kind->value.iokind == M_READ
8335       && gfc_check_vardef_context (exp, false, false, _("item in READ"))
8336          == FAILURE)
8337     return;
8338
8339   sym = exp->symtree->n.sym;
8340   ts = &sym->ts;
8341
8342   /* Go to actual component transferred.  */
8343   for (ref = exp->ref; ref; ref = ref->next)
8344     if (ref->type == REF_COMPONENT)
8345       ts = &ref->u.c.component->ts;
8346
8347   if (ts->type == BT_CLASS)
8348     {
8349       /* FIXME: Test for defined input/output.  */
8350       gfc_error ("Data transfer element at %L cannot be polymorphic unless "
8351                 "it is processed by a defined input/output procedure",
8352                 &code->loc);
8353       return;
8354     }
8355
8356   if (ts->type == BT_DERIVED)
8357     {
8358       /* Check that transferred derived type doesn't contain POINTER
8359          components.  */
8360       if (ts->u.derived->attr.pointer_comp)
8361         {
8362           gfc_error ("Data transfer element at %L cannot have POINTER "
8363                      "components unless it is processed by a defined "
8364                      "input/output procedure", &code->loc);
8365           return;
8366         }
8367
8368       /* F08:C935.  */
8369       if (ts->u.derived->attr.proc_pointer_comp)
8370         {
8371           gfc_error ("Data transfer element at %L cannot have "
8372                      "procedure pointer components", &code->loc);
8373           return;
8374         }
8375
8376       if (ts->u.derived->attr.alloc_comp)
8377         {
8378           gfc_error ("Data transfer element at %L cannot have ALLOCATABLE "
8379                      "components unless it is processed by a defined "
8380                      "input/output procedure", &code->loc);
8381           return;
8382         }
8383
8384       if (derived_inaccessible (ts->u.derived))
8385         {
8386           gfc_error ("Data transfer element at %L cannot have "
8387                      "PRIVATE components",&code->loc);
8388           return;
8389         }
8390     }
8391
8392   if (sym->as != NULL && sym->as->type == AS_ASSUMED_SIZE && exp->ref
8393       && exp->ref->type == REF_ARRAY && exp->ref->u.ar.type == AR_FULL)
8394     {
8395       gfc_error ("Data transfer element at %L cannot be a full reference to "
8396                  "an assumed-size array", &code->loc);
8397       return;
8398     }
8399 }
8400
8401
8402 /*********** Toplevel code resolution subroutines ***********/
8403
8404 /* Find the set of labels that are reachable from this block.  We also
8405    record the last statement in each block.  */
8406
8407 static void
8408 find_reachable_labels (gfc_code *block)
8409 {
8410   gfc_code *c;
8411
8412   if (!block)
8413     return;
8414
8415   cs_base->reachable_labels = bitmap_obstack_alloc (&labels_obstack);
8416
8417   /* Collect labels in this block.  We don't keep those corresponding
8418      to END {IF|SELECT}, these are checked in resolve_branch by going
8419      up through the code_stack.  */
8420   for (c = block; c; c = c->next)
8421     {
8422       if (c->here && c->op != EXEC_END_NESTED_BLOCK)
8423         bitmap_set_bit (cs_base->reachable_labels, c->here->value);
8424     }
8425
8426   /* Merge with labels from parent block.  */
8427   if (cs_base->prev)
8428     {
8429       gcc_assert (cs_base->prev->reachable_labels);
8430       bitmap_ior_into (cs_base->reachable_labels,
8431                        cs_base->prev->reachable_labels);
8432     }
8433 }
8434
8435
8436 static void
8437 resolve_lock_unlock (gfc_code *code)
8438 {
8439   if (code->expr1->ts.type != BT_DERIVED
8440       || code->expr1->expr_type != EXPR_VARIABLE
8441       || code->expr1->ts.u.derived->from_intmod != INTMOD_ISO_FORTRAN_ENV
8442       || code->expr1->ts.u.derived->intmod_sym_id != ISOFORTRAN_LOCK_TYPE
8443       || code->expr1->rank != 0
8444       || (!gfc_is_coarray (code->expr1) && !gfc_is_coindexed (code->expr1)))
8445     gfc_error ("Lock variable at %L must be a scalar of type LOCK_TYPE",
8446                &code->expr1->where);
8447
8448   /* Check STAT.  */
8449   if (code->expr2
8450       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8451           || code->expr2->expr_type != EXPR_VARIABLE))
8452     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8453                &code->expr2->where);
8454
8455   if (code->expr2
8456       && gfc_check_vardef_context (code->expr2, false, false,
8457                                    _("STAT variable")) == FAILURE)
8458     return;
8459
8460   /* Check ERRMSG.  */
8461   if (code->expr3
8462       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8463           || code->expr3->expr_type != EXPR_VARIABLE))
8464     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8465                &code->expr3->where);
8466
8467   if (code->expr3
8468       && gfc_check_vardef_context (code->expr3, false, false,
8469                                    _("ERRMSG variable")) == FAILURE)
8470     return;
8471
8472   /* Check ACQUIRED_LOCK.  */
8473   if (code->expr4
8474       && (code->expr4->ts.type != BT_LOGICAL || code->expr4->rank != 0
8475           || code->expr4->expr_type != EXPR_VARIABLE))
8476     gfc_error ("ACQUIRED_LOCK= argument at %L must be a scalar LOGICAL "
8477                "variable", &code->expr4->where);
8478
8479   if (code->expr4
8480       && gfc_check_vardef_context (code->expr4, false, false,
8481                                    _("ACQUIRED_LOCK variable")) == FAILURE)
8482     return;
8483 }
8484
8485
8486 static void
8487 resolve_sync (gfc_code *code)
8488 {
8489   /* Check imageset. The * case matches expr1 == NULL.  */
8490   if (code->expr1)
8491     {
8492       if (code->expr1->ts.type != BT_INTEGER || code->expr1->rank > 1)
8493         gfc_error ("Imageset argument at %L must be a scalar or rank-1 "
8494                    "INTEGER expression", &code->expr1->where);
8495       if (code->expr1->expr_type == EXPR_CONSTANT && code->expr1->rank == 0
8496           && mpz_cmp_si (code->expr1->value.integer, 1) < 0)
8497         gfc_error ("Imageset argument at %L must between 1 and num_images()",
8498                    &code->expr1->where);
8499       else if (code->expr1->expr_type == EXPR_ARRAY
8500                && gfc_simplify_expr (code->expr1, 0) == SUCCESS)
8501         {
8502            gfc_constructor *cons;
8503            cons = gfc_constructor_first (code->expr1->value.constructor);
8504            for (; cons; cons = gfc_constructor_next (cons))
8505              if (cons->expr->expr_type == EXPR_CONSTANT
8506                  &&  mpz_cmp_si (cons->expr->value.integer, 1) < 0)
8507                gfc_error ("Imageset argument at %L must between 1 and "
8508                           "num_images()", &cons->expr->where);
8509         }
8510     }
8511
8512   /* Check STAT.  */
8513   if (code->expr2
8514       && (code->expr2->ts.type != BT_INTEGER || code->expr2->rank != 0
8515           || code->expr2->expr_type != EXPR_VARIABLE))
8516     gfc_error ("STAT= argument at %L must be a scalar INTEGER variable",
8517                &code->expr2->where);
8518
8519   /* Check ERRMSG.  */
8520   if (code->expr3
8521       && (code->expr3->ts.type != BT_CHARACTER || code->expr3->rank != 0
8522           || code->expr3->expr_type != EXPR_VARIABLE))
8523     gfc_error ("ERRMSG= argument at %L must be a scalar CHARACTER variable",
8524                &code->expr3->where);
8525 }
8526
8527
8528 /* Given a branch to a label, see if the branch is conforming.
8529    The code node describes where the branch is located.  */
8530
8531 static void
8532 resolve_branch (gfc_st_label *label, gfc_code *code)
8533 {
8534   code_stack *stack;
8535
8536   if (label == NULL)
8537     return;
8538
8539   /* Step one: is this a valid branching target?  */
8540
8541   if (label->defined == ST_LABEL_UNKNOWN)
8542     {
8543       gfc_error ("Label %d referenced at %L is never defined", label->value,
8544                  &label->where);
8545       return;
8546     }
8547
8548   if (label->defined != ST_LABEL_TARGET)
8549     {
8550       gfc_error ("Statement at %L is not a valid branch target statement "
8551                  "for the branch statement at %L", &label->where, &code->loc);
8552       return;
8553     }
8554
8555   /* Step two: make sure this branch is not a branch to itself ;-)  */
8556
8557   if (code->here == label)
8558     {
8559       gfc_warning ("Branch at %L may result in an infinite loop", &code->loc);
8560       return;
8561     }
8562
8563   /* Step three:  See if the label is in the same block as the
8564      branching statement.  The hard work has been done by setting up
8565      the bitmap reachable_labels.  */
8566
8567   if (bitmap_bit_p (cs_base->reachable_labels, label->value))
8568     {
8569       /* Check now whether there is a CRITICAL construct; if so, check
8570          whether the label is still visible outside of the CRITICAL block,
8571          which is invalid.  */
8572       for (stack = cs_base; stack; stack = stack->prev)
8573         {
8574           if (stack->current->op == EXEC_CRITICAL
8575               && bitmap_bit_p (stack->reachable_labels, label->value))
8576             gfc_error ("GOTO statement at %L leaves CRITICAL construct for "
8577                       "label at %L", &code->loc, &label->where);
8578           else if (stack->current->op == EXEC_DO_CONCURRENT
8579                    && bitmap_bit_p (stack->reachable_labels, label->value))
8580             gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct "
8581                       "for label at %L", &code->loc, &label->where);
8582         }
8583
8584       return;
8585     }
8586
8587   /* Step four:  If we haven't found the label in the bitmap, it may
8588     still be the label of the END of the enclosing block, in which
8589     case we find it by going up the code_stack.  */
8590
8591   for (stack = cs_base; stack; stack = stack->prev)
8592     {
8593       if (stack->current->next && stack->current->next->here == label)
8594         break;
8595       if (stack->current->op == EXEC_CRITICAL)
8596         {
8597           /* Note: A label at END CRITICAL does not leave the CRITICAL
8598              construct as END CRITICAL is still part of it.  */
8599           gfc_error ("GOTO statement at %L leaves CRITICAL construct for label"
8600                       " at %L", &code->loc, &label->where);
8601           return;
8602         }
8603       else if (stack->current->op == EXEC_DO_CONCURRENT)
8604         {
8605           gfc_error ("GOTO statement at %L leaves DO CONCURRENT construct for "
8606                      "label at %L", &code->loc, &label->where);
8607           return;
8608         }
8609     }
8610
8611   if (stack)
8612     {
8613       gcc_assert (stack->current->next->op == EXEC_END_NESTED_BLOCK);
8614       return;
8615     }
8616
8617   /* The label is not in an enclosing block, so illegal.  This was
8618      allowed in Fortran 66, so we allow it as extension.  No
8619      further checks are necessary in this case.  */
8620   gfc_notify_std (GFC_STD_LEGACY, "Label at %L is not in the same block "
8621                   "as the GOTO statement at %L", &label->where,
8622                   &code->loc);
8623   return;
8624 }
8625
8626
8627 /* Check whether EXPR1 has the same shape as EXPR2.  */
8628
8629 static gfc_try
8630 resolve_where_shape (gfc_expr *expr1, gfc_expr *expr2)
8631 {
8632   mpz_t shape[GFC_MAX_DIMENSIONS];
8633   mpz_t shape2[GFC_MAX_DIMENSIONS];
8634   gfc_try result = FAILURE;
8635   int i;
8636
8637   /* Compare the rank.  */
8638   if (expr1->rank != expr2->rank)
8639     return result;
8640
8641   /* Compare the size of each dimension.  */
8642   for (i=0; i<expr1->rank; i++)
8643     {
8644       if (gfc_array_dimen_size (expr1, i, &shape[i]) == FAILURE)
8645         goto ignore;
8646
8647       if (gfc_array_dimen_size (expr2, i, &shape2[i]) == FAILURE)
8648         goto ignore;
8649
8650       if (mpz_cmp (shape[i], shape2[i]))
8651         goto over;
8652     }
8653
8654   /* When either of the two expression is an assumed size array, we
8655      ignore the comparison of dimension sizes.  */
8656 ignore:
8657   result = SUCCESS;
8658
8659 over:
8660   gfc_clear_shape (shape, i);
8661   gfc_clear_shape (shape2, i);
8662   return result;
8663 }
8664
8665
8666 /* Check whether a WHERE assignment target or a WHERE mask expression
8667    has the same shape as the outmost WHERE mask expression.  */
8668
8669 static void
8670 resolve_where (gfc_code *code, gfc_expr *mask)
8671 {
8672   gfc_code *cblock;
8673   gfc_code *cnext;
8674   gfc_expr *e = NULL;
8675
8676   cblock = code->block;
8677
8678   /* Store the first WHERE mask-expr of the WHERE statement or construct.
8679      In case of nested WHERE, only the outmost one is stored.  */
8680   if (mask == NULL) /* outmost WHERE */
8681     e = cblock->expr1;
8682   else /* inner WHERE */
8683     e = mask;
8684
8685   while (cblock)
8686     {
8687       if (cblock->expr1)
8688         {
8689           /* Check if the mask-expr has a consistent shape with the
8690              outmost WHERE mask-expr.  */
8691           if (resolve_where_shape (cblock->expr1, e) == FAILURE)
8692             gfc_error ("WHERE mask at %L has inconsistent shape",
8693                        &cblock->expr1->where);
8694          }
8695
8696       /* the assignment statement of a WHERE statement, or the first
8697          statement in where-body-construct of a WHERE construct */
8698       cnext = cblock->next;
8699       while (cnext)
8700         {
8701           switch (cnext->op)
8702             {
8703             /* WHERE assignment statement */
8704             case EXEC_ASSIGN:
8705
8706               /* Check shape consistent for WHERE assignment target.  */
8707               if (e && resolve_where_shape (cnext->expr1, e) == FAILURE)
8708                gfc_error ("WHERE assignment target at %L has "
8709                           "inconsistent shape", &cnext->expr1->where);
8710               break;
8711
8712
8713             case EXEC_ASSIGN_CALL:
8714               resolve_call (cnext);
8715               if (!cnext->resolved_sym->attr.elemental)
8716                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8717                           &cnext->ext.actual->expr->where);
8718               break;
8719
8720             /* WHERE or WHERE construct is part of a where-body-construct */
8721             case EXEC_WHERE:
8722               resolve_where (cnext, e);
8723               break;
8724
8725             default:
8726               gfc_error ("Unsupported statement inside WHERE at %L",
8727                          &cnext->loc);
8728             }
8729          /* the next statement within the same where-body-construct */
8730          cnext = cnext->next;
8731        }
8732     /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8733     cblock = cblock->block;
8734   }
8735 }
8736
8737
8738 /* Resolve assignment in FORALL construct.
8739    NVAR is the number of FORALL index variables, and VAR_EXPR records the
8740    FORALL index variables.  */
8741
8742 static void
8743 gfc_resolve_assign_in_forall (gfc_code *code, int nvar, gfc_expr **var_expr)
8744 {
8745   int n;
8746
8747   for (n = 0; n < nvar; n++)
8748     {
8749       gfc_symbol *forall_index;
8750
8751       forall_index = var_expr[n]->symtree->n.sym;
8752
8753       /* Check whether the assignment target is one of the FORALL index
8754          variable.  */
8755       if ((code->expr1->expr_type == EXPR_VARIABLE)
8756           && (code->expr1->symtree->n.sym == forall_index))
8757         gfc_error ("Assignment to a FORALL index variable at %L",
8758                    &code->expr1->where);
8759       else
8760         {
8761           /* If one of the FORALL index variables doesn't appear in the
8762              assignment variable, then there could be a many-to-one
8763              assignment.  Emit a warning rather than an error because the
8764              mask could be resolving this problem.  */
8765           if (find_forall_index (code->expr1, forall_index, 0) == FAILURE)
8766             gfc_warning ("The FORALL with index '%s' is not used on the "
8767                          "left side of the assignment at %L and so might "
8768                          "cause multiple assignment to this object",
8769                          var_expr[n]->symtree->name, &code->expr1->where);
8770         }
8771     }
8772 }
8773
8774
8775 /* Resolve WHERE statement in FORALL construct.  */
8776
8777 static void
8778 gfc_resolve_where_code_in_forall (gfc_code *code, int nvar,
8779                                   gfc_expr **var_expr)
8780 {
8781   gfc_code *cblock;
8782   gfc_code *cnext;
8783
8784   cblock = code->block;
8785   while (cblock)
8786     {
8787       /* the assignment statement of a WHERE statement, or the first
8788          statement in where-body-construct of a WHERE construct */
8789       cnext = cblock->next;
8790       while (cnext)
8791         {
8792           switch (cnext->op)
8793             {
8794             /* WHERE assignment statement */
8795             case EXEC_ASSIGN:
8796               gfc_resolve_assign_in_forall (cnext, nvar, var_expr);
8797               break;
8798
8799             /* WHERE operator assignment statement */
8800             case EXEC_ASSIGN_CALL:
8801               resolve_call (cnext);
8802               if (!cnext->resolved_sym->attr.elemental)
8803                 gfc_error("Non-ELEMENTAL user-defined assignment in WHERE at %L",
8804                           &cnext->ext.actual->expr->where);
8805               break;
8806
8807             /* WHERE or WHERE construct is part of a where-body-construct */
8808             case EXEC_WHERE:
8809               gfc_resolve_where_code_in_forall (cnext, nvar, var_expr);
8810               break;
8811
8812             default:
8813               gfc_error ("Unsupported statement inside WHERE at %L",
8814                          &cnext->loc);
8815             }
8816           /* the next statement within the same where-body-construct */
8817           cnext = cnext->next;
8818         }
8819       /* the next masked-elsewhere-stmt, elsewhere-stmt, or end-where-stmt */
8820       cblock = cblock->block;
8821     }
8822 }
8823
8824
8825 /* Traverse the FORALL body to check whether the following errors exist:
8826    1. For assignment, check if a many-to-one assignment happens.
8827    2. For WHERE statement, check the WHERE body to see if there is any
8828       many-to-one assignment.  */
8829
8830 static void
8831 gfc_resolve_forall_body (gfc_code *code, int nvar, gfc_expr **var_expr)
8832 {
8833   gfc_code *c;
8834
8835   c = code->block->next;
8836   while (c)
8837     {
8838       switch (c->op)
8839         {
8840         case EXEC_ASSIGN:
8841         case EXEC_POINTER_ASSIGN:
8842           gfc_resolve_assign_in_forall (c, nvar, var_expr);
8843           break;
8844
8845         case EXEC_ASSIGN_CALL:
8846           resolve_call (c);
8847           break;
8848
8849         /* Because the gfc_resolve_blocks() will handle the nested FORALL,
8850            there is no need to handle it here.  */
8851         case EXEC_FORALL:
8852           break;
8853         case EXEC_WHERE:
8854           gfc_resolve_where_code_in_forall(c, nvar, var_expr);
8855           break;
8856         default:
8857           break;
8858         }
8859       /* The next statement in the FORALL body.  */
8860       c = c->next;
8861     }
8862 }
8863
8864
8865 /* Counts the number of iterators needed inside a forall construct, including
8866    nested forall constructs. This is used to allocate the needed memory
8867    in gfc_resolve_forall.  */
8868
8869 static int
8870 gfc_count_forall_iterators (gfc_code *code)
8871 {
8872   int max_iters, sub_iters, current_iters;
8873   gfc_forall_iterator *fa;
8874
8875   gcc_assert(code->op == EXEC_FORALL);
8876   max_iters = 0;
8877   current_iters = 0;
8878
8879   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8880     current_iters ++;
8881
8882   code = code->block->next;
8883
8884   while (code)
8885     {
8886       if (code->op == EXEC_FORALL)
8887         {
8888           sub_iters = gfc_count_forall_iterators (code);
8889           if (sub_iters > max_iters)
8890             max_iters = sub_iters;
8891         }
8892       code = code->next;
8893     }
8894
8895   return current_iters + max_iters;
8896 }
8897
8898
8899 /* Given a FORALL construct, first resolve the FORALL iterator, then call
8900    gfc_resolve_forall_body to resolve the FORALL body.  */
8901
8902 static void
8903 gfc_resolve_forall (gfc_code *code, gfc_namespace *ns, int forall_save)
8904 {
8905   static gfc_expr **var_expr;
8906   static int total_var = 0;
8907   static int nvar = 0;
8908   int old_nvar, tmp;
8909   gfc_forall_iterator *fa;
8910   int i;
8911
8912   old_nvar = nvar;
8913
8914   /* Start to resolve a FORALL construct   */
8915   if (forall_save == 0)
8916     {
8917       /* Count the total number of FORALL index in the nested FORALL
8918          construct in order to allocate the VAR_EXPR with proper size.  */
8919       total_var = gfc_count_forall_iterators (code);
8920
8921       /* Allocate VAR_EXPR with NUMBER_OF_FORALL_INDEX elements.  */
8922       var_expr = XCNEWVEC (gfc_expr *, total_var);
8923     }
8924
8925   /* The information about FORALL iterator, including FORALL index start, end
8926      and stride. The FORALL index can not appear in start, end or stride.  */
8927   for (fa = code->ext.forall_iterator; fa; fa = fa->next)
8928     {
8929       /* Check if any outer FORALL index name is the same as the current
8930          one.  */
8931       for (i = 0; i < nvar; i++)
8932         {
8933           if (fa->var->symtree->n.sym == var_expr[i]->symtree->n.sym)
8934             {
8935               gfc_error ("An outer FORALL construct already has an index "
8936                          "with this name %L", &fa->var->where);
8937             }
8938         }
8939
8940       /* Record the current FORALL index.  */
8941       var_expr[nvar] = gfc_copy_expr (fa->var);
8942
8943       nvar++;
8944
8945       /* No memory leak.  */
8946       gcc_assert (nvar <= total_var);
8947     }
8948
8949   /* Resolve the FORALL body.  */
8950   gfc_resolve_forall_body (code, nvar, var_expr);
8951
8952   /* May call gfc_resolve_forall to resolve the inner FORALL loop.  */
8953   gfc_resolve_blocks (code->block, ns);
8954
8955   tmp = nvar;
8956   nvar = old_nvar;
8957   /* Free only the VAR_EXPRs allocated in this frame.  */
8958   for (i = nvar; i < tmp; i++)
8959      gfc_free_expr (var_expr[i]);
8960
8961   if (nvar == 0)
8962     {
8963       /* We are in the outermost FORALL construct.  */
8964       gcc_assert (forall_save == 0);
8965
8966       /* VAR_EXPR is not needed any more.  */
8967       free (var_expr);
8968       total_var = 0;
8969     }
8970 }
8971
8972
8973 /* Resolve a BLOCK construct statement.  */
8974
8975 static void
8976 resolve_block_construct (gfc_code* code)
8977 {
8978   /* Resolve the BLOCK's namespace.  */
8979   gfc_resolve (code->ext.block.ns);
8980
8981   /* For an ASSOCIATE block, the associations (and their targets) are already
8982      resolved during resolve_symbol.  */
8983 }
8984
8985
8986 /* Resolve lists of blocks found in IF, SELECT CASE, WHERE, FORALL, GOTO and
8987    DO code nodes.  */
8988
8989 static void resolve_code (gfc_code *, gfc_namespace *);
8990
8991 void
8992 gfc_resolve_blocks (gfc_code *b, gfc_namespace *ns)
8993 {
8994   gfc_try t;
8995
8996   for (; b; b = b->block)
8997     {
8998       t = gfc_resolve_expr (b->expr1);
8999       if (gfc_resolve_expr (b->expr2) == FAILURE)
9000         t = FAILURE;
9001
9002       switch (b->op)
9003         {
9004         case EXEC_IF:
9005           if (t == SUCCESS && b->expr1 != NULL
9006               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank != 0))
9007             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9008                        &b->expr1->where);
9009           break;
9010
9011         case EXEC_WHERE:
9012           if (t == SUCCESS
9013               && b->expr1 != NULL
9014               && (b->expr1->ts.type != BT_LOGICAL || b->expr1->rank == 0))
9015             gfc_error ("WHERE/ELSEWHERE clause at %L requires a LOGICAL array",
9016                        &b->expr1->where);
9017           break;
9018
9019         case EXEC_GOTO:
9020           resolve_branch (b->label1, b);
9021           break;
9022
9023         case EXEC_BLOCK:
9024           resolve_block_construct (b);
9025           break;
9026
9027         case EXEC_SELECT:
9028         case EXEC_SELECT_TYPE:
9029         case EXEC_FORALL:
9030         case EXEC_DO:
9031         case EXEC_DO_WHILE:
9032         case EXEC_DO_CONCURRENT:
9033         case EXEC_CRITICAL:
9034         case EXEC_READ:
9035         case EXEC_WRITE:
9036         case EXEC_IOLENGTH:
9037         case EXEC_WAIT:
9038           break;
9039
9040         case EXEC_OMP_ATOMIC:
9041         case EXEC_OMP_CRITICAL:
9042         case EXEC_OMP_DO:
9043         case EXEC_OMP_MASTER:
9044         case EXEC_OMP_ORDERED:
9045         case EXEC_OMP_PARALLEL:
9046         case EXEC_OMP_PARALLEL_DO:
9047         case EXEC_OMP_PARALLEL_SECTIONS:
9048         case EXEC_OMP_PARALLEL_WORKSHARE:
9049         case EXEC_OMP_SECTIONS:
9050         case EXEC_OMP_SINGLE:
9051         case EXEC_OMP_TASK:
9052         case EXEC_OMP_TASKWAIT:
9053         case EXEC_OMP_TASKYIELD:
9054         case EXEC_OMP_WORKSHARE:
9055           break;
9056
9057         default:
9058           gfc_internal_error ("gfc_resolve_blocks(): Bad block type");
9059         }
9060
9061       resolve_code (b->next, ns);
9062     }
9063 }
9064
9065
9066 /* Does everything to resolve an ordinary assignment.  Returns true
9067    if this is an interface assignment.  */
9068 static bool
9069 resolve_ordinary_assign (gfc_code *code, gfc_namespace *ns)
9070 {
9071   bool rval = false;
9072   gfc_expr *lhs;
9073   gfc_expr *rhs;
9074   int llen = 0;
9075   int rlen = 0;
9076   int n;
9077   gfc_ref *ref;
9078
9079   if (gfc_extend_assign (code, ns) == SUCCESS)
9080     {
9081       gfc_expr** rhsptr;
9082
9083       if (code->op == EXEC_ASSIGN_CALL)
9084         {
9085           lhs = code->ext.actual->expr;
9086           rhsptr = &code->ext.actual->next->expr;
9087         }
9088       else
9089         {
9090           gfc_actual_arglist* args;
9091           gfc_typebound_proc* tbp;
9092
9093           gcc_assert (code->op == EXEC_COMPCALL);
9094
9095           args = code->expr1->value.compcall.actual;
9096           lhs = args->expr;
9097           rhsptr = &args->next->expr;
9098
9099           tbp = code->expr1->value.compcall.tbp;
9100           gcc_assert (!tbp->is_generic);
9101         }
9102
9103       /* Make a temporary rhs when there is a default initializer
9104          and rhs is the same symbol as the lhs.  */
9105       if ((*rhsptr)->expr_type == EXPR_VARIABLE
9106             && (*rhsptr)->symtree->n.sym->ts.type == BT_DERIVED
9107             && gfc_has_default_initializer ((*rhsptr)->symtree->n.sym->ts.u.derived)
9108             && (lhs->symtree->n.sym == (*rhsptr)->symtree->n.sym))
9109         *rhsptr = gfc_get_parentheses (*rhsptr);
9110
9111       return true;
9112     }
9113
9114   lhs = code->expr1;
9115   rhs = code->expr2;
9116
9117   if (rhs->is_boz
9118       && gfc_notify_std (GFC_STD_GNU, "Extension: BOZ literal at %L outside "
9119                          "a DATA statement and outside INT/REAL/DBLE/CMPLX",
9120                          &code->loc) == FAILURE)
9121     return false;
9122
9123   /* Handle the case of a BOZ literal on the RHS.  */
9124   if (rhs->is_boz && lhs->ts.type != BT_INTEGER)
9125     {
9126       int rc;
9127       if (gfc_option.warn_surprising)
9128         gfc_warning ("BOZ literal at %L is bitwise transferred "
9129                      "non-integer symbol '%s'", &code->loc,
9130                      lhs->symtree->n.sym->name);
9131
9132       if (!gfc_convert_boz (rhs, &lhs->ts))
9133         return false;
9134       if ((rc = gfc_range_check (rhs)) != ARITH_OK)
9135         {
9136           if (rc == ARITH_UNDERFLOW)
9137             gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
9138                        ". This check can be disabled with the option "
9139                        "-fno-range-check", &rhs->where);
9140           else if (rc == ARITH_OVERFLOW)
9141             gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
9142                        ". This check can be disabled with the option "
9143                        "-fno-range-check", &rhs->where);
9144           else if (rc == ARITH_NAN)
9145             gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
9146                        ". This check can be disabled with the option "
9147                        "-fno-range-check", &rhs->where);
9148           return false;
9149         }
9150     }
9151
9152   if (lhs->ts.type == BT_CHARACTER
9153         && gfc_option.warn_character_truncation)
9154     {
9155       if (lhs->ts.u.cl != NULL
9156             && lhs->ts.u.cl->length != NULL
9157             && lhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9158         llen = mpz_get_si (lhs->ts.u.cl->length->value.integer);
9159
9160       if (rhs->expr_type == EXPR_CONSTANT)
9161         rlen = rhs->value.character.length;
9162
9163       else if (rhs->ts.u.cl != NULL
9164                  && rhs->ts.u.cl->length != NULL
9165                  && rhs->ts.u.cl->length->expr_type == EXPR_CONSTANT)
9166         rlen = mpz_get_si (rhs->ts.u.cl->length->value.integer);
9167
9168       if (rlen && llen && rlen > llen)
9169         gfc_warning_now ("CHARACTER expression will be truncated "
9170                          "in assignment (%d/%d) at %L",
9171                          llen, rlen, &code->loc);
9172     }
9173
9174   /* Ensure that a vector index expression for the lvalue is evaluated
9175      to a temporary if the lvalue symbol is referenced in it.  */
9176   if (lhs->rank)
9177     {
9178       for (ref = lhs->ref; ref; ref= ref->next)
9179         if (ref->type == REF_ARRAY)
9180           {
9181             for (n = 0; n < ref->u.ar.dimen; n++)
9182               if (ref->u.ar.dimen_type[n] == DIMEN_VECTOR
9183                   && gfc_find_sym_in_expr (lhs->symtree->n.sym,
9184                                            ref->u.ar.start[n]))
9185                 ref->u.ar.start[n]
9186                         = gfc_get_parentheses (ref->u.ar.start[n]);
9187           }
9188     }
9189
9190   if (gfc_pure (NULL))
9191     {
9192       if (lhs->ts.type == BT_DERIVED
9193             && lhs->expr_type == EXPR_VARIABLE
9194             && lhs->ts.u.derived->attr.pointer_comp
9195             && rhs->expr_type == EXPR_VARIABLE
9196             && (gfc_impure_variable (rhs->symtree->n.sym)
9197                 || gfc_is_coindexed (rhs)))
9198         {
9199           /* F2008, C1283.  */
9200           if (gfc_is_coindexed (rhs))
9201             gfc_error ("Coindexed expression at %L is assigned to "
9202                         "a derived type variable with a POINTER "
9203                         "component in a PURE procedure",
9204                         &rhs->where);
9205           else
9206             gfc_error ("The impure variable at %L is assigned to "
9207                         "a derived type variable with a POINTER "
9208                         "component in a PURE procedure (12.6)",
9209                         &rhs->where);
9210           return rval;
9211         }
9212
9213       /* Fortran 2008, C1283.  */
9214       if (gfc_is_coindexed (lhs))
9215         {
9216           gfc_error ("Assignment to coindexed variable at %L in a PURE "
9217                      "procedure", &rhs->where);
9218           return rval;
9219         }
9220     }
9221
9222   if (gfc_implicit_pure (NULL))
9223     {
9224       if (lhs->expr_type == EXPR_VARIABLE
9225             && lhs->symtree->n.sym != gfc_current_ns->proc_name
9226             && lhs->symtree->n.sym->ns != gfc_current_ns)
9227         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9228
9229       if (lhs->ts.type == BT_DERIVED
9230             && lhs->expr_type == EXPR_VARIABLE
9231             && lhs->ts.u.derived->attr.pointer_comp
9232             && rhs->expr_type == EXPR_VARIABLE
9233             && (gfc_impure_variable (rhs->symtree->n.sym)
9234                 || gfc_is_coindexed (rhs)))
9235         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9236
9237       /* Fortran 2008, C1283.  */
9238       if (gfc_is_coindexed (lhs))
9239         gfc_current_ns->proc_name->attr.implicit_pure = 0;
9240     }
9241
9242   /* F03:7.4.1.2.  */
9243   /* FIXME: Valid in Fortran 2008, unless the LHS is both polymorphic
9244      and coindexed; cf. F2008, 7.2.1.2 and PR 43366.  */
9245   if (lhs->ts.type == BT_CLASS)
9246     {
9247       gfc_error ("Variable must not be polymorphic in intrinsic assignment at "
9248                  "%L - check that there is a matching specific subroutine "
9249                  "for '=' operator", &lhs->where);
9250       return false;
9251     }
9252
9253   /* F2008, Section 7.2.1.2.  */
9254   if (gfc_is_coindexed (lhs) && gfc_has_ultimate_allocatable (lhs))
9255     {
9256       gfc_error ("Coindexed variable must not be have an allocatable ultimate "
9257                  "component in assignment at %L", &lhs->where);
9258       return false;
9259     }
9260
9261   gfc_check_assign (lhs, rhs, 1);
9262   return false;
9263 }
9264
9265
9266 /* Given a block of code, recursively resolve everything pointed to by this
9267    code block.  */
9268
9269 static void
9270 resolve_code (gfc_code *code, gfc_namespace *ns)
9271 {
9272   int omp_workshare_save;
9273   int forall_save, do_concurrent_save;
9274   code_stack frame;
9275   gfc_try t;
9276
9277   frame.prev = cs_base;
9278   frame.head = code;
9279   cs_base = &frame;
9280
9281   find_reachable_labels (code);
9282
9283   for (; code; code = code->next)
9284     {
9285       frame.current = code;
9286       forall_save = forall_flag;
9287       do_concurrent_save = do_concurrent_flag;
9288
9289       if (code->op == EXEC_FORALL)
9290         {
9291           forall_flag = 1;
9292           gfc_resolve_forall (code, ns, forall_save);
9293           forall_flag = 2;
9294         }
9295       else if (code->block)
9296         {
9297           omp_workshare_save = -1;
9298           switch (code->op)
9299             {
9300             case EXEC_OMP_PARALLEL_WORKSHARE:
9301               omp_workshare_save = omp_workshare_flag;
9302               omp_workshare_flag = 1;
9303               gfc_resolve_omp_parallel_blocks (code, ns);
9304               break;
9305             case EXEC_OMP_PARALLEL:
9306             case EXEC_OMP_PARALLEL_DO:
9307             case EXEC_OMP_PARALLEL_SECTIONS:
9308             case EXEC_OMP_TASK:
9309               omp_workshare_save = omp_workshare_flag;
9310               omp_workshare_flag = 0;
9311               gfc_resolve_omp_parallel_blocks (code, ns);
9312               break;
9313             case EXEC_OMP_DO:
9314               gfc_resolve_omp_do_blocks (code, ns);
9315               break;
9316             case EXEC_SELECT_TYPE:
9317               /* Blocks are handled in resolve_select_type because we have
9318                  to transform the SELECT TYPE into ASSOCIATE first.  */
9319               break;
9320             case EXEC_DO_CONCURRENT:
9321               do_concurrent_flag = 1;
9322               gfc_resolve_blocks (code->block, ns);
9323               do_concurrent_flag = 2;
9324               break;
9325             case EXEC_OMP_WORKSHARE:
9326               omp_workshare_save = omp_workshare_flag;
9327               omp_workshare_flag = 1;
9328               /* FALLTHROUGH */
9329             default:
9330               gfc_resolve_blocks (code->block, ns);
9331               break;
9332             }
9333
9334           if (omp_workshare_save != -1)
9335             omp_workshare_flag = omp_workshare_save;
9336         }
9337
9338       t = SUCCESS;
9339       if (code->op != EXEC_COMPCALL && code->op != EXEC_CALL_PPC)
9340         t = gfc_resolve_expr (code->expr1);
9341       forall_flag = forall_save;
9342       do_concurrent_flag = do_concurrent_save;
9343
9344       if (gfc_resolve_expr (code->expr2) == FAILURE)
9345         t = FAILURE;
9346
9347       if (code->op == EXEC_ALLOCATE
9348           && gfc_resolve_expr (code->expr3) == FAILURE)
9349         t = FAILURE;
9350
9351       switch (code->op)
9352         {
9353         case EXEC_NOP:
9354         case EXEC_END_BLOCK:
9355         case EXEC_END_NESTED_BLOCK:
9356         case EXEC_CYCLE:
9357         case EXEC_PAUSE:
9358         case EXEC_STOP:
9359         case EXEC_ERROR_STOP:
9360         case EXEC_EXIT:
9361         case EXEC_CONTINUE:
9362         case EXEC_DT_END:
9363         case EXEC_ASSIGN_CALL:
9364         case EXEC_CRITICAL:
9365           break;
9366
9367         case EXEC_SYNC_ALL:
9368         case EXEC_SYNC_IMAGES:
9369         case EXEC_SYNC_MEMORY:
9370           resolve_sync (code);
9371           break;
9372
9373         case EXEC_LOCK:
9374         case EXEC_UNLOCK:
9375           resolve_lock_unlock (code);
9376           break;
9377
9378         case EXEC_ENTRY:
9379           /* Keep track of which entry we are up to.  */
9380           current_entry_id = code->ext.entry->id;
9381           break;
9382
9383         case EXEC_WHERE:
9384           resolve_where (code, NULL);
9385           break;
9386
9387         case EXEC_GOTO:
9388           if (code->expr1 != NULL)
9389             {
9390               if (code->expr1->ts.type != BT_INTEGER)
9391                 gfc_error ("ASSIGNED GOTO statement at %L requires an "
9392                            "INTEGER variable", &code->expr1->where);
9393               else if (code->expr1->symtree->n.sym->attr.assign != 1)
9394                 gfc_error ("Variable '%s' has not been assigned a target "
9395                            "label at %L", code->expr1->symtree->n.sym->name,
9396                            &code->expr1->where);
9397             }
9398           else
9399             resolve_branch (code->label1, code);
9400           break;
9401
9402         case EXEC_RETURN:
9403           if (code->expr1 != NULL
9404                 && (code->expr1->ts.type != BT_INTEGER || code->expr1->rank))
9405             gfc_error ("Alternate RETURN statement at %L requires a SCALAR-"
9406                        "INTEGER return specifier", &code->expr1->where);
9407           break;
9408
9409         case EXEC_INIT_ASSIGN:
9410         case EXEC_END_PROCEDURE:
9411           break;
9412
9413         case EXEC_ASSIGN:
9414           if (t == FAILURE)
9415             break;
9416
9417           if (gfc_check_vardef_context (code->expr1, false, false,
9418                                         _("assignment")) == FAILURE)
9419             break;
9420
9421           if (resolve_ordinary_assign (code, ns))
9422             {
9423               if (code->op == EXEC_COMPCALL)
9424                 goto compcall;
9425               else
9426                 goto call;
9427             }
9428           break;
9429
9430         case EXEC_LABEL_ASSIGN:
9431           if (code->label1->defined == ST_LABEL_UNKNOWN)
9432             gfc_error ("Label %d referenced at %L is never defined",
9433                        code->label1->value, &code->label1->where);
9434           if (t == SUCCESS
9435               && (code->expr1->expr_type != EXPR_VARIABLE
9436                   || code->expr1->symtree->n.sym->ts.type != BT_INTEGER
9437                   || code->expr1->symtree->n.sym->ts.kind
9438                      != gfc_default_integer_kind
9439                   || code->expr1->symtree->n.sym->as != NULL))
9440             gfc_error ("ASSIGN statement at %L requires a scalar "
9441                        "default INTEGER variable", &code->expr1->where);
9442           break;
9443
9444         case EXEC_POINTER_ASSIGN:
9445           {
9446             gfc_expr* e;
9447
9448             if (t == FAILURE)
9449               break;
9450
9451             /* This is both a variable definition and pointer assignment
9452                context, so check both of them.  For rank remapping, a final
9453                array ref may be present on the LHS and fool gfc_expr_attr
9454                used in gfc_check_vardef_context.  Remove it.  */
9455             e = remove_last_array_ref (code->expr1);
9456             t = gfc_check_vardef_context (e, true, false,
9457                                           _("pointer assignment"));
9458             if (t == SUCCESS)
9459               t = gfc_check_vardef_context (e, false, false,
9460                                             _("pointer assignment"));
9461             gfc_free_expr (e);
9462             if (t == FAILURE)
9463               break;
9464
9465             gfc_check_pointer_assign (code->expr1, code->expr2);
9466             break;
9467           }
9468
9469         case EXEC_ARITHMETIC_IF:
9470           if (t == SUCCESS
9471               && code->expr1->ts.type != BT_INTEGER
9472               && code->expr1->ts.type != BT_REAL)
9473             gfc_error ("Arithmetic IF statement at %L requires a numeric "
9474                        "expression", &code->expr1->where);
9475
9476           resolve_branch (code->label1, code);
9477           resolve_branch (code->label2, code);
9478           resolve_branch (code->label3, code);
9479           break;
9480
9481         case EXEC_IF:
9482           if (t == SUCCESS && code->expr1 != NULL
9483               && (code->expr1->ts.type != BT_LOGICAL
9484                   || code->expr1->rank != 0))
9485             gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
9486                        &code->expr1->where);
9487           break;
9488
9489         case EXEC_CALL:
9490         call:
9491           resolve_call (code);
9492           break;
9493
9494         case EXEC_COMPCALL:
9495         compcall:
9496           resolve_typebound_subroutine (code);
9497           break;
9498
9499         case EXEC_CALL_PPC:
9500           resolve_ppc_call (code);
9501           break;
9502
9503         case EXEC_SELECT:
9504           /* Select is complicated. Also, a SELECT construct could be
9505              a transformed computed GOTO.  */
9506           resolve_select (code, false);
9507           break;
9508
9509         case EXEC_SELECT_TYPE:
9510           resolve_select_type (code, ns);
9511           break;
9512
9513         case EXEC_BLOCK:
9514           resolve_block_construct (code);
9515           break;
9516
9517         case EXEC_DO:
9518           if (code->ext.iterator != NULL)
9519             {
9520               gfc_iterator *iter = code->ext.iterator;
9521               if (gfc_resolve_iterator (iter, true) != FAILURE)
9522                 gfc_resolve_do_iterator (code, iter->var->symtree->n.sym);
9523             }
9524           break;
9525
9526         case EXEC_DO_WHILE:
9527           if (code->expr1 == NULL)
9528             gfc_internal_error ("resolve_code(): No expression on DO WHILE");
9529           if (t == SUCCESS
9530               && (code->expr1->rank != 0
9531                   || code->expr1->ts.type != BT_LOGICAL))
9532             gfc_error ("Exit condition of DO WHILE loop at %L must be "
9533                        "a scalar LOGICAL expression", &code->expr1->where);
9534           break;
9535
9536         case EXEC_ALLOCATE:
9537           if (t == SUCCESS)
9538             resolve_allocate_deallocate (code, "ALLOCATE");
9539
9540           break;
9541
9542         case EXEC_DEALLOCATE:
9543           if (t == SUCCESS)
9544             resolve_allocate_deallocate (code, "DEALLOCATE");
9545
9546           break;
9547
9548         case EXEC_OPEN:
9549           if (gfc_resolve_open (code->ext.open) == FAILURE)
9550             break;
9551
9552           resolve_branch (code->ext.open->err, code);
9553           break;
9554
9555         case EXEC_CLOSE:
9556           if (gfc_resolve_close (code->ext.close) == FAILURE)
9557             break;
9558
9559           resolve_branch (code->ext.close->err, code);
9560           break;
9561
9562         case EXEC_BACKSPACE:
9563         case EXEC_ENDFILE:
9564         case EXEC_REWIND:
9565         case EXEC_FLUSH:
9566           if (gfc_resolve_filepos (code->ext.filepos) == FAILURE)
9567             break;
9568
9569           resolve_branch (code->ext.filepos->err, code);
9570           break;
9571
9572         case EXEC_INQUIRE:
9573           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9574               break;
9575
9576           resolve_branch (code->ext.inquire->err, code);
9577           break;
9578
9579         case EXEC_IOLENGTH:
9580           gcc_assert (code->ext.inquire != NULL);
9581           if (gfc_resolve_inquire (code->ext.inquire) == FAILURE)
9582             break;
9583
9584           resolve_branch (code->ext.inquire->err, code);
9585           break;
9586
9587         case EXEC_WAIT:
9588           if (gfc_resolve_wait (code->ext.wait) == FAILURE)
9589             break;
9590
9591           resolve_branch (code->ext.wait->err, code);
9592           resolve_branch (code->ext.wait->end, code);
9593           resolve_branch (code->ext.wait->eor, code);
9594           break;
9595
9596         case EXEC_READ:
9597         case EXEC_WRITE:
9598           if (gfc_resolve_dt (code->ext.dt, &code->loc) == FAILURE)
9599             break;
9600
9601           resolve_branch (code->ext.dt->err, code);
9602           resolve_branch (code->ext.dt->end, code);
9603           resolve_branch (code->ext.dt->eor, code);
9604           break;
9605
9606         case EXEC_TRANSFER:
9607           resolve_transfer (code);
9608           break;
9609
9610         case EXEC_DO_CONCURRENT:
9611         case EXEC_FORALL:
9612           resolve_forall_iterators (code->ext.forall_iterator);
9613
9614           if (code->expr1 != NULL
9615               && (code->expr1->ts.type != BT_LOGICAL || code->expr1->rank))
9616             gfc_error ("FORALL mask clause at %L requires a scalar LOGICAL "
9617                        "expression", &code->expr1->where);
9618           break;
9619
9620         case EXEC_OMP_ATOMIC:
9621         case EXEC_OMP_BARRIER:
9622         case EXEC_OMP_CRITICAL:
9623         case EXEC_OMP_FLUSH:
9624         case EXEC_OMP_DO:
9625         case EXEC_OMP_MASTER:
9626         case EXEC_OMP_ORDERED:
9627         case EXEC_OMP_SECTIONS:
9628         case EXEC_OMP_SINGLE:
9629         case EXEC_OMP_TASKWAIT:
9630         case EXEC_OMP_TASKYIELD:
9631         case EXEC_OMP_WORKSHARE:
9632           gfc_resolve_omp_directive (code, ns);
9633           break;
9634
9635         case EXEC_OMP_PARALLEL:
9636         case EXEC_OMP_PARALLEL_DO:
9637         case EXEC_OMP_PARALLEL_SECTIONS:
9638         case EXEC_OMP_PARALLEL_WORKSHARE:
9639         case EXEC_OMP_TASK:
9640           omp_workshare_save = omp_workshare_flag;
9641           omp_workshare_flag = 0;
9642           gfc_resolve_omp_directive (code, ns);
9643           omp_workshare_flag = omp_workshare_save;
9644           break;
9645
9646         default:
9647           gfc_internal_error ("resolve_code(): Bad statement code");
9648         }
9649     }
9650
9651   cs_base = frame.prev;
9652 }
9653
9654
9655 /* Resolve initial values and make sure they are compatible with
9656    the variable.  */
9657
9658 static void
9659 resolve_values (gfc_symbol *sym)
9660 {
9661   gfc_try t;
9662
9663   if (sym->value == NULL)
9664     return;
9665
9666   if (sym->value->expr_type == EXPR_STRUCTURE)
9667     t= resolve_structure_cons (sym->value, 1);
9668   else
9669     t = gfc_resolve_expr (sym->value);
9670
9671   if (t == FAILURE)
9672     return;
9673
9674   gfc_check_assign_symbol (sym, sym->value);
9675 }
9676
9677
9678 /* Verify the binding labels for common blocks that are BIND(C).  The label
9679    for a BIND(C) common block must be identical in all scoping units in which
9680    the common block is declared.  Further, the binding label can not collide
9681    with any other global entity in the program.  */
9682
9683 static void
9684 resolve_bind_c_comms (gfc_symtree *comm_block_tree)
9685 {
9686   if (comm_block_tree->n.common->is_bind_c == 1)
9687     {
9688       gfc_gsymbol *binding_label_gsym;
9689       gfc_gsymbol *comm_name_gsym;
9690       const char * bind_label = comm_block_tree->n.common->binding_label
9691         ? comm_block_tree->n.common->binding_label : "";
9692
9693       /* See if a global symbol exists by the common block's name.  It may
9694          be NULL if the common block is use-associated.  */
9695       comm_name_gsym = gfc_find_gsymbol (gfc_gsym_root,
9696                                          comm_block_tree->n.common->name);
9697       if (comm_name_gsym != NULL && comm_name_gsym->type != GSYM_COMMON)
9698         gfc_error ("Binding label '%s' for common block '%s' at %L collides "
9699                    "with the global entity '%s' at %L",
9700                    bind_label,
9701                    comm_block_tree->n.common->name,
9702                    &(comm_block_tree->n.common->where),
9703                    comm_name_gsym->name, &(comm_name_gsym->where));
9704       else if (comm_name_gsym != NULL
9705                && strcmp (comm_name_gsym->name,
9706                           comm_block_tree->n.common->name) == 0)
9707         {
9708           /* TODO: Need to make sure the fields of gfc_gsymbol are initialized
9709              as expected.  */
9710           if (comm_name_gsym->binding_label == NULL)
9711             /* No binding label for common block stored yet; save this one.  */
9712             comm_name_gsym->binding_label = bind_label;
9713           else if (strcmp (comm_name_gsym->binding_label, bind_label) != 0)
9714               {
9715                 /* Common block names match but binding labels do not.  */
9716                 gfc_error ("Binding label '%s' for common block '%s' at %L "
9717                            "does not match the binding label '%s' for common "
9718                            "block '%s' at %L",
9719                            bind_label,
9720                            comm_block_tree->n.common->name,
9721                            &(comm_block_tree->n.common->where),
9722                            comm_name_gsym->binding_label,
9723                            comm_name_gsym->name,
9724                            &(comm_name_gsym->where));
9725                 return;
9726               }
9727         }
9728
9729       /* There is no binding label (NAME="") so we have nothing further to
9730          check and nothing to add as a global symbol for the label.  */
9731       if (!comm_block_tree->n.common->binding_label)
9732         return;
9733
9734       binding_label_gsym =
9735         gfc_find_gsymbol (gfc_gsym_root,
9736                           comm_block_tree->n.common->binding_label);
9737       if (binding_label_gsym == NULL)
9738         {
9739           /* Need to make a global symbol for the binding label to prevent
9740              it from colliding with another.  */
9741           binding_label_gsym =
9742             gfc_get_gsymbol (comm_block_tree->n.common->binding_label);
9743           binding_label_gsym->sym_name = comm_block_tree->n.common->name;
9744           binding_label_gsym->type = GSYM_COMMON;
9745         }
9746       else
9747         {
9748           /* If comm_name_gsym is NULL, the name common block is use
9749              associated and the name could be colliding.  */
9750           if (binding_label_gsym->type != GSYM_COMMON)
9751             gfc_error ("Binding label '%s' for common block '%s' at %L "
9752                        "collides with the global entity '%s' at %L",
9753                        comm_block_tree->n.common->binding_label,
9754                        comm_block_tree->n.common->name,
9755                        &(comm_block_tree->n.common->where),
9756                        binding_label_gsym->name,
9757                        &(binding_label_gsym->where));
9758           else if (comm_name_gsym != NULL
9759                    && (strcmp (binding_label_gsym->name,
9760                                comm_name_gsym->binding_label) != 0)
9761                    && (strcmp (binding_label_gsym->sym_name,
9762                                comm_name_gsym->name) != 0))
9763             gfc_error ("Binding label '%s' for common block '%s' at %L "
9764                        "collides with global entity '%s' at %L",
9765                        binding_label_gsym->name, binding_label_gsym->sym_name,
9766                        &(comm_block_tree->n.common->where),
9767                        comm_name_gsym->name, &(comm_name_gsym->where));
9768         }
9769     }
9770
9771   return;
9772 }
9773
9774
9775 /* Verify any BIND(C) derived types in the namespace so we can report errors
9776    for them once, rather than for each variable declared of that type.  */
9777
9778 static void
9779 resolve_bind_c_derived_types (gfc_symbol *derived_sym)
9780 {
9781   if (derived_sym != NULL && derived_sym->attr.flavor == FL_DERIVED
9782       && derived_sym->attr.is_bind_c == 1)
9783     verify_bind_c_derived_type (derived_sym);
9784
9785   return;
9786 }
9787
9788
9789 /* Verify that any binding labels used in a given namespace do not collide
9790    with the names or binding labels of any global symbols.  */
9791
9792 static void
9793 gfc_verify_binding_labels (gfc_symbol *sym)
9794 {
9795   int has_error = 0;
9796
9797   if (sym != NULL && sym->attr.is_bind_c && sym->attr.is_iso_c == 0
9798       && sym->attr.flavor != FL_DERIVED && sym->binding_label)
9799     {
9800       gfc_gsymbol *bind_c_sym;
9801
9802       bind_c_sym = gfc_find_gsymbol (gfc_gsym_root, sym->binding_label);
9803       if (bind_c_sym != NULL
9804           && strcmp (bind_c_sym->name, sym->binding_label) == 0)
9805         {
9806           if (sym->attr.if_source == IFSRC_DECL
9807               && (bind_c_sym->type != GSYM_SUBROUTINE
9808                   && bind_c_sym->type != GSYM_FUNCTION)
9809               && ((sym->attr.contained == 1
9810                    && strcmp (bind_c_sym->sym_name, sym->name) != 0)
9811                   || (sym->attr.use_assoc == 1
9812                       && (strcmp (bind_c_sym->mod_name, sym->module) != 0))))
9813             {
9814               /* Make sure global procedures don't collide with anything.  */
9815               gfc_error ("Binding label '%s' at %L collides with the global "
9816                          "entity '%s' at %L", sym->binding_label,
9817                          &(sym->declared_at), bind_c_sym->name,
9818                          &(bind_c_sym->where));
9819               has_error = 1;
9820             }
9821           else if (sym->attr.contained == 0
9822                    && (sym->attr.if_source == IFSRC_IFBODY
9823                        && sym->attr.flavor == FL_PROCEDURE)
9824                    && (bind_c_sym->sym_name != NULL
9825                        && strcmp (bind_c_sym->sym_name, sym->name) != 0))
9826             {
9827               /* Make sure procedures in interface bodies don't collide.  */
9828               gfc_error ("Binding label '%s' in interface body at %L collides "
9829                          "with the global entity '%s' at %L",
9830                          sym->binding_label,
9831                          &(sym->declared_at), bind_c_sym->name,
9832                          &(bind_c_sym->where));
9833               has_error = 1;
9834             }
9835           else if (sym->attr.contained == 0
9836                    && sym->attr.if_source == IFSRC_UNKNOWN)
9837             if ((sym->attr.use_assoc && bind_c_sym->mod_name
9838                  && strcmp (bind_c_sym->mod_name, sym->module) != 0)
9839                 || sym->attr.use_assoc == 0)
9840               {
9841                 gfc_error ("Binding label '%s' at %L collides with global "
9842                            "entity '%s' at %L", sym->binding_label,
9843                            &(sym->declared_at), bind_c_sym->name,
9844                            &(bind_c_sym->where));
9845                 has_error = 1;
9846               }
9847
9848           if (has_error != 0)
9849             /* Clear the binding label to prevent checking multiple times.  */
9850             sym->binding_label = NULL;
9851         }
9852       else if (bind_c_sym == NULL)
9853         {
9854           bind_c_sym = gfc_get_gsymbol (sym->binding_label);
9855           bind_c_sym->where = sym->declared_at;
9856           bind_c_sym->sym_name = sym->name;
9857
9858           if (sym->attr.use_assoc == 1)
9859             bind_c_sym->mod_name = sym->module;
9860           else
9861             if (sym->ns->proc_name != NULL)
9862               bind_c_sym->mod_name = sym->ns->proc_name->name;
9863
9864           if (sym->attr.contained == 0)
9865             {
9866               if (sym->attr.subroutine)
9867                 bind_c_sym->type = GSYM_SUBROUTINE;
9868               else if (sym->attr.function)
9869                 bind_c_sym->type = GSYM_FUNCTION;
9870             }
9871         }
9872     }
9873   return;
9874 }
9875
9876
9877 /* Resolve an index expression.  */
9878
9879 static gfc_try
9880 resolve_index_expr (gfc_expr *e)
9881 {
9882   if (gfc_resolve_expr (e) == FAILURE)
9883     return FAILURE;
9884
9885   if (gfc_simplify_expr (e, 0) == FAILURE)
9886     return FAILURE;
9887
9888   if (gfc_specification_expr (e) == FAILURE)
9889     return FAILURE;
9890
9891   return SUCCESS;
9892 }
9893
9894
9895 /* Resolve a charlen structure.  */
9896
9897 static gfc_try
9898 resolve_charlen (gfc_charlen *cl)
9899 {
9900   int i, k;
9901
9902   if (cl->resolved)
9903     return SUCCESS;
9904
9905   cl->resolved = 1;
9906
9907   specification_expr = 1;
9908
9909   if (resolve_index_expr (cl->length) == FAILURE)
9910     {
9911       specification_expr = 0;
9912       return FAILURE;
9913     }
9914
9915   /* "If the character length parameter value evaluates to a negative
9916      value, the length of character entities declared is zero."  */
9917   if (cl->length && !gfc_extract_int (cl->length, &i) && i < 0)
9918     {
9919       if (gfc_option.warn_surprising)
9920         gfc_warning_now ("CHARACTER variable at %L has negative length %d,"
9921                          " the length has been set to zero",
9922                          &cl->length->where, i);
9923       gfc_replace_expr (cl->length,
9924                         gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
9925     }
9926
9927   /* Check that the character length is not too large.  */
9928   k = gfc_validate_kind (BT_INTEGER, gfc_charlen_int_kind, false);
9929   if (cl->length && cl->length->expr_type == EXPR_CONSTANT
9930       && cl->length->ts.type == BT_INTEGER
9931       && mpz_cmp (cl->length->value.integer, gfc_integer_kinds[k].huge) > 0)
9932     {
9933       gfc_error ("String length at %L is too large", &cl->length->where);
9934       return FAILURE;
9935     }
9936
9937   return SUCCESS;
9938 }
9939
9940
9941 /* Test for non-constant shape arrays.  */
9942
9943 static bool
9944 is_non_constant_shape_array (gfc_symbol *sym)
9945 {
9946   gfc_expr *e;
9947   int i;
9948   bool not_constant;
9949
9950   not_constant = false;
9951   if (sym->as != NULL)
9952     {
9953       /* Unfortunately, !gfc_is_compile_time_shape hits a legal case that
9954          has not been simplified; parameter array references.  Do the
9955          simplification now.  */
9956       for (i = 0; i < sym->as->rank + sym->as->corank; i++)
9957         {
9958           e = sym->as->lower[i];
9959           if (e && (resolve_index_expr (e) == FAILURE
9960                     || !gfc_is_constant_expr (e)))
9961             not_constant = true;
9962           e = sym->as->upper[i];
9963           if (e && (resolve_index_expr (e) == FAILURE
9964                     || !gfc_is_constant_expr (e)))
9965             not_constant = true;
9966         }
9967     }
9968   return not_constant;
9969 }
9970
9971 /* Given a symbol and an initialization expression, add code to initialize
9972    the symbol to the function entry.  */
9973 static void
9974 build_init_assign (gfc_symbol *sym, gfc_expr *init)
9975 {
9976   gfc_expr *lval;
9977   gfc_code *init_st;
9978   gfc_namespace *ns = sym->ns;
9979
9980   /* Search for the function namespace if this is a contained
9981      function without an explicit result.  */
9982   if (sym->attr.function && sym == sym->result
9983       && sym->name != sym->ns->proc_name->name)
9984     {
9985       ns = ns->contained;
9986       for (;ns; ns = ns->sibling)
9987         if (strcmp (ns->proc_name->name, sym->name) == 0)
9988           break;
9989     }
9990
9991   if (ns == NULL)
9992     {
9993       gfc_free_expr (init);
9994       return;
9995     }
9996
9997   /* Build an l-value expression for the result.  */
9998   lval = gfc_lval_expr_from_sym (sym);
9999
10000   /* Add the code at scope entry.  */
10001   init_st = gfc_get_code ();
10002   init_st->next = ns->code;
10003   ns->code = init_st;
10004
10005   /* Assign the default initializer to the l-value.  */
10006   init_st->loc = sym->declared_at;
10007   init_st->op = EXEC_INIT_ASSIGN;
10008   init_st->expr1 = lval;
10009   init_st->expr2 = init;
10010 }
10011
10012 /* Assign the default initializer to a derived type variable or result.  */
10013
10014 static void
10015 apply_default_init (gfc_symbol *sym)
10016 {
10017   gfc_expr *init = NULL;
10018
10019   if (sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
10020     return;
10021
10022   if (sym->ts.type == BT_DERIVED && sym->ts.u.derived)
10023     init = gfc_default_initializer (&sym->ts);
10024
10025   if (init == NULL && sym->ts.type != BT_CLASS)
10026     return;
10027
10028   build_init_assign (sym, init);
10029   sym->attr.referenced = 1;
10030 }
10031
10032 /* Build an initializer for a local integer, real, complex, logical, or
10033    character variable, based on the command line flags finit-local-zero,
10034    finit-integer=, finit-real=, finit-logical=, and finit-runtime.  Returns
10035    null if the symbol should not have a default initialization.  */
10036 static gfc_expr *
10037 build_default_init_expr (gfc_symbol *sym)
10038 {
10039   int char_len;
10040   gfc_expr *init_expr;
10041   int i;
10042
10043   /* These symbols should never have a default initialization.  */
10044   if (sym->attr.allocatable
10045       || sym->attr.external
10046       || sym->attr.dummy
10047       || sym->attr.pointer
10048       || sym->attr.in_equivalence
10049       || sym->attr.in_common
10050       || sym->attr.data
10051       || sym->module
10052       || sym->attr.cray_pointee
10053       || sym->attr.cray_pointer
10054       || sym->assoc)
10055     return NULL;
10056
10057   /* Now we'll try to build an initializer expression.  */
10058   init_expr = gfc_get_constant_expr (sym->ts.type, sym->ts.kind,
10059                                      &sym->declared_at);
10060
10061   /* We will only initialize integers, reals, complex, logicals, and
10062      characters, and only if the corresponding command-line flags
10063      were set.  Otherwise, we free init_expr and return null.  */
10064   switch (sym->ts.type)
10065     {
10066     case BT_INTEGER:
10067       if (gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
10068         mpz_set_si (init_expr->value.integer,
10069                          gfc_option.flag_init_integer_value);
10070       else
10071         {
10072           gfc_free_expr (init_expr);
10073           init_expr = NULL;
10074         }
10075       break;
10076
10077     case BT_REAL:
10078       switch (gfc_option.flag_init_real)
10079         {
10080         case GFC_INIT_REAL_SNAN:
10081           init_expr->is_snan = 1;
10082           /* Fall through.  */
10083         case GFC_INIT_REAL_NAN:
10084           mpfr_set_nan (init_expr->value.real);
10085           break;
10086
10087         case GFC_INIT_REAL_INF:
10088           mpfr_set_inf (init_expr->value.real, 1);
10089           break;
10090
10091         case GFC_INIT_REAL_NEG_INF:
10092           mpfr_set_inf (init_expr->value.real, -1);
10093           break;
10094
10095         case GFC_INIT_REAL_ZERO:
10096           mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
10097           break;
10098
10099         default:
10100           gfc_free_expr (init_expr);
10101           init_expr = NULL;
10102           break;
10103         }
10104       break;
10105
10106     case BT_COMPLEX:
10107       switch (gfc_option.flag_init_real)
10108         {
10109         case GFC_INIT_REAL_SNAN:
10110           init_expr->is_snan = 1;
10111           /* Fall through.  */
10112         case GFC_INIT_REAL_NAN:
10113           mpfr_set_nan (mpc_realref (init_expr->value.complex));
10114           mpfr_set_nan (mpc_imagref (init_expr->value.complex));
10115           break;
10116
10117         case GFC_INIT_REAL_INF:
10118           mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
10119           mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
10120           break;
10121
10122         case GFC_INIT_REAL_NEG_INF:
10123           mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
10124           mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
10125           break;
10126
10127         case GFC_INIT_REAL_ZERO:
10128           mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
10129           break;
10130
10131         default:
10132           gfc_free_expr (init_expr);
10133           init_expr = NULL;
10134           break;
10135         }
10136       break;
10137
10138     case BT_LOGICAL:
10139       if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_FALSE)
10140         init_expr->value.logical = 0;
10141       else if (gfc_option.flag_init_logical == GFC_INIT_LOGICAL_TRUE)
10142         init_expr->value.logical = 1;
10143       else
10144         {
10145           gfc_free_expr (init_expr);
10146           init_expr = NULL;
10147         }
10148       break;
10149
10150     case BT_CHARACTER:
10151       /* For characters, the length must be constant in order to
10152          create a default initializer.  */
10153       if (gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
10154           && sym->ts.u.cl->length
10155           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
10156         {
10157           char_len = mpz_get_si (sym->ts.u.cl->length->value.integer);
10158           init_expr->value.character.length = char_len;
10159           init_expr->value.character.string = gfc_get_wide_string (char_len+1);
10160           for (i = 0; i < char_len; i++)
10161             init_expr->value.character.string[i]
10162               = (unsigned char) gfc_option.flag_init_character_value;
10163         }
10164       else
10165         {
10166           gfc_free_expr (init_expr);
10167           init_expr = NULL;
10168         }
10169       if (!init_expr && gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON
10170           && sym->ts.u.cl->length)
10171         {
10172           gfc_actual_arglist *arg;
10173           init_expr = gfc_get_expr ();
10174           init_expr->where = sym->declared_at;
10175           init_expr->ts = sym->ts;
10176           init_expr->expr_type = EXPR_FUNCTION;
10177           init_expr->value.function.isym =
10178                 gfc_intrinsic_function_by_id (GFC_ISYM_REPEAT);
10179           init_expr->value.function.name = "repeat";
10180           arg = gfc_get_actual_arglist ();
10181           arg->expr = gfc_get_character_expr (sym->ts.kind, &sym->declared_at,
10182                                               NULL, 1);
10183           arg->expr->value.character.string[0]
10184                 = gfc_option.flag_init_character_value;
10185           arg->next = gfc_get_actual_arglist ();
10186           arg->next->expr = gfc_copy_expr (sym->ts.u.cl->length);
10187           init_expr->value.function.actual = arg;
10188         }
10189       break;
10190
10191     default:
10192      gfc_free_expr (init_expr);
10193      init_expr = NULL;
10194     }
10195   return init_expr;
10196 }
10197
10198 /* Add an initialization expression to a local variable.  */
10199 static void
10200 apply_default_init_local (gfc_symbol *sym)
10201 {
10202   gfc_expr *init = NULL;
10203
10204   /* The symbol should be a variable or a function return value.  */
10205   if ((sym->attr.flavor != FL_VARIABLE && !sym->attr.function)
10206       || (sym->attr.function && sym->result != sym))
10207     return;
10208
10209   /* Try to build the initializer expression.  If we can't initialize
10210      this symbol, then init will be NULL.  */
10211   init = build_default_init_expr (sym);
10212   if (init == NULL)
10213     return;
10214
10215   /* For saved variables, we don't want to add an initializer at function
10216      entry, so we just add a static initializer. Note that automatic variables
10217      are stack allocated even with -fno-automatic.  */
10218   if (sym->attr.save || sym->ns->save_all
10219       || (gfc_option.flag_max_stack_var_size == 0
10220           && (!sym->attr.dimension || !is_non_constant_shape_array (sym))))
10221     {
10222       /* Don't clobber an existing initializer!  */
10223       gcc_assert (sym->value == NULL);
10224       sym->value = init;
10225       return;
10226     }
10227
10228   build_init_assign (sym, init);
10229 }
10230
10231
10232 /* Resolution of common features of flavors variable and procedure.  */
10233
10234 static gfc_try
10235 resolve_fl_var_and_proc (gfc_symbol *sym, int mp_flag)
10236 {
10237   gfc_array_spec *as;
10238
10239   /* Avoid double diagnostics for function result symbols.  */
10240   if ((sym->result || sym->attr.result) && !sym->attr.dummy
10241       && (sym->ns != gfc_current_ns))
10242     return SUCCESS;
10243
10244   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
10245     as = CLASS_DATA (sym)->as;
10246   else
10247     as = sym->as;
10248
10249   /* Constraints on deferred shape variable.  */
10250   if (as == NULL || as->type != AS_DEFERRED)
10251     {
10252       bool pointer, allocatable, dimension;
10253
10254       if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
10255         {
10256           pointer = CLASS_DATA (sym)->attr.class_pointer;
10257           allocatable = CLASS_DATA (sym)->attr.allocatable;
10258           dimension = CLASS_DATA (sym)->attr.dimension;
10259         }
10260       else
10261         {
10262           pointer = sym->attr.pointer;
10263           allocatable = sym->attr.allocatable;
10264           dimension = sym->attr.dimension;
10265         }
10266
10267       if (allocatable)
10268         {
10269           if (dimension)
10270             {
10271               gfc_error ("Allocatable array '%s' at %L must have "
10272                          "a deferred shape", sym->name, &sym->declared_at);
10273               return FAILURE;
10274             }
10275           else if (gfc_notify_std (GFC_STD_F2003, "Scalar object '%s' at %L "
10276                                    "may not be ALLOCATABLE", sym->name,
10277                                    &sym->declared_at) == FAILURE)
10278             return FAILURE;
10279         }
10280
10281       if (pointer && dimension)
10282         {
10283           gfc_error ("Array pointer '%s' at %L must have a deferred shape",
10284                      sym->name, &sym->declared_at);
10285           return FAILURE;
10286         }
10287     }
10288   else
10289     {
10290       if (!mp_flag && !sym->attr.allocatable && !sym->attr.pointer
10291           && sym->ts.type != BT_CLASS && !sym->assoc)
10292         {
10293           gfc_error ("Array '%s' at %L cannot have a deferred shape",
10294                      sym->name, &sym->declared_at);
10295           return FAILURE;
10296          }
10297     }
10298
10299   /* Constraints on polymorphic variables.  */
10300   if (sym->ts.type == BT_CLASS && !(sym->result && sym->result != sym))
10301     {
10302       /* F03:C502.  */
10303       if (sym->attr.class_ok
10304           && !gfc_type_is_extensible (CLASS_DATA (sym)->ts.u.derived))
10305         {
10306           gfc_error ("Type '%s' of CLASS variable '%s' at %L is not extensible",
10307                      CLASS_DATA (sym)->ts.u.derived->name, sym->name,
10308                      &sym->declared_at);
10309           return FAILURE;
10310         }
10311
10312       /* F03:C509.  */
10313       /* Assume that use associated symbols were checked in the module ns.
10314          Class-variables that are associate-names are also something special
10315          and excepted from the test.  */
10316       if (!sym->attr.class_ok && !sym->attr.use_assoc && !sym->assoc)
10317         {
10318           gfc_error ("CLASS variable '%s' at %L must be dummy, allocatable "
10319                      "or pointer", sym->name, &sym->declared_at);
10320           return FAILURE;
10321         }
10322     }
10323
10324   return SUCCESS;
10325 }
10326
10327
10328 /* Additional checks for symbols with flavor variable and derived
10329    type.  To be called from resolve_fl_variable.  */
10330
10331 static gfc_try
10332 resolve_fl_variable_derived (gfc_symbol *sym, int no_init_flag)
10333 {
10334   gcc_assert (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS);
10335
10336   /* Check to see if a derived type is blocked from being host
10337      associated by the presence of another class I symbol in the same
10338      namespace.  14.6.1.3 of the standard and the discussion on
10339      comp.lang.fortran.  */
10340   if (sym->ns != sym->ts.u.derived->ns
10341       && sym->ns->proc_name->attr.if_source != IFSRC_IFBODY)
10342     {
10343       gfc_symbol *s;
10344       gfc_find_symbol (sym->ts.u.derived->name, sym->ns, 0, &s);
10345       if (s && s->attr.generic)
10346         s = gfc_find_dt_in_generic (s);
10347       if (s && s->attr.flavor != FL_DERIVED)
10348         {
10349           gfc_error ("The type '%s' cannot be host associated at %L "
10350                      "because it is blocked by an incompatible object "
10351                      "of the same name declared at %L",
10352                      sym->ts.u.derived->name, &sym->declared_at,
10353                      &s->declared_at);
10354           return FAILURE;
10355         }
10356     }
10357
10358   /* 4th constraint in section 11.3: "If an object of a type for which
10359      component-initialization is specified (R429) appears in the
10360      specification-part of a module and does not have the ALLOCATABLE
10361      or POINTER attribute, the object shall have the SAVE attribute."
10362
10363      The check for initializers is performed with
10364      gfc_has_default_initializer because gfc_default_initializer generates
10365      a hidden default for allocatable components.  */
10366   if (!(sym->value || no_init_flag) && sym->ns->proc_name
10367       && sym->ns->proc_name->attr.flavor == FL_MODULE
10368       && !sym->ns->save_all && !sym->attr.save
10369       && !sym->attr.pointer && !sym->attr.allocatable
10370       && gfc_has_default_initializer (sym->ts.u.derived)
10371       && gfc_notify_std (GFC_STD_F2008, "Fortran 2008: Implied SAVE for "
10372                          "module variable '%s' at %L, needed due to "
10373                          "the default initialization", sym->name,
10374                          &sym->declared_at) == FAILURE)
10375     return FAILURE;
10376
10377   /* Assign default initializer.  */
10378   if (!(sym->value || sym->attr.pointer || sym->attr.allocatable)
10379       && (!no_init_flag || sym->attr.intent == INTENT_OUT))
10380     {
10381       sym->value = gfc_default_initializer (&sym->ts);
10382     }
10383
10384   return SUCCESS;
10385 }
10386
10387
10388 /* Resolve symbols with flavor variable.  */
10389
10390 static gfc_try
10391 resolve_fl_variable (gfc_symbol *sym, int mp_flag)
10392 {
10393   int no_init_flag, automatic_flag;
10394   gfc_expr *e;
10395   const char *auto_save_msg;
10396
10397   auto_save_msg = "Automatic object '%s' at %L cannot have the "
10398                   "SAVE attribute";
10399
10400   if (resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10401     return FAILURE;
10402
10403   /* Set this flag to check that variables are parameters of all entries.
10404      This check is effected by the call to gfc_resolve_expr through
10405      is_non_constant_shape_array.  */
10406   specification_expr = 1;
10407
10408   if (sym->ns->proc_name
10409       && (sym->ns->proc_name->attr.flavor == FL_MODULE
10410           || sym->ns->proc_name->attr.is_main_program)
10411       && !sym->attr.use_assoc
10412       && !sym->attr.allocatable
10413       && !sym->attr.pointer
10414       && is_non_constant_shape_array (sym))
10415     {
10416       /* The shape of a main program or module array needs to be
10417          constant.  */
10418       gfc_error ("The module or main program array '%s' at %L must "
10419                  "have constant shape", sym->name, &sym->declared_at);
10420       specification_expr = 0;
10421       return FAILURE;
10422     }
10423
10424   /* Constraints on deferred type parameter.  */
10425   if (sym->ts.deferred && !(sym->attr.pointer || sym->attr.allocatable))
10426     {
10427       gfc_error ("Entity '%s' at %L has a deferred type parameter and "
10428                  "requires either the pointer or allocatable attribute",
10429                      sym->name, &sym->declared_at);
10430       return FAILURE;
10431     }
10432
10433   if (sym->ts.type == BT_CHARACTER)
10434     {
10435       /* Make sure that character string variables with assumed length are
10436          dummy arguments.  */
10437       e = sym->ts.u.cl->length;
10438       if (e == NULL && !sym->attr.dummy && !sym->attr.result
10439           && !sym->ts.deferred)
10440         {
10441           gfc_error ("Entity with assumed character length at %L must be a "
10442                      "dummy argument or a PARAMETER", &sym->declared_at);
10443           return FAILURE;
10444         }
10445
10446       if (e && sym->attr.save == SAVE_EXPLICIT && !gfc_is_constant_expr (e))
10447         {
10448           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10449           return FAILURE;
10450         }
10451
10452       if (!gfc_is_constant_expr (e)
10453           && !(e->expr_type == EXPR_VARIABLE
10454                && e->symtree->n.sym->attr.flavor == FL_PARAMETER))
10455         {
10456           if (!sym->attr.use_assoc && sym->ns->proc_name
10457               && (sym->ns->proc_name->attr.flavor == FL_MODULE
10458                   || sym->ns->proc_name->attr.is_main_program))
10459             {
10460               gfc_error ("'%s' at %L must have constant character length "
10461                         "in this context", sym->name, &sym->declared_at);
10462               return FAILURE;
10463             }
10464           if (sym->attr.in_common)
10465             {
10466               gfc_error ("COMMON variable '%s' at %L must have constant "
10467                          "character length", sym->name, &sym->declared_at);
10468               return FAILURE;
10469             }
10470         }
10471     }
10472
10473   if (sym->value == NULL && sym->attr.referenced)
10474     apply_default_init_local (sym); /* Try to apply a default initialization.  */
10475
10476   /* Determine if the symbol may not have an initializer.  */
10477   no_init_flag = automatic_flag = 0;
10478   if (sym->attr.allocatable || sym->attr.external || sym->attr.dummy
10479       || sym->attr.intrinsic || sym->attr.result)
10480     no_init_flag = 1;
10481   else if ((sym->attr.dimension || sym->attr.codimension) && !sym->attr.pointer
10482            && is_non_constant_shape_array (sym))
10483     {
10484       no_init_flag = automatic_flag = 1;
10485
10486       /* Also, they must not have the SAVE attribute.
10487          SAVE_IMPLICIT is checked below.  */
10488       if (sym->as && sym->attr.codimension)
10489         {
10490           int corank = sym->as->corank;
10491           sym->as->corank = 0;
10492           no_init_flag = automatic_flag = is_non_constant_shape_array (sym);
10493           sym->as->corank = corank;
10494         }
10495       if (automatic_flag && sym->attr.save == SAVE_EXPLICIT)
10496         {
10497           gfc_error (auto_save_msg, sym->name, &sym->declared_at);
10498           return FAILURE;
10499         }
10500     }
10501
10502   /* Ensure that any initializer is simplified.  */
10503   if (sym->value)
10504     gfc_simplify_expr (sym->value, 1);
10505
10506   /* Reject illegal initializers.  */
10507   if (!sym->mark && sym->value)
10508     {
10509       if (sym->attr.allocatable || (sym->ts.type == BT_CLASS
10510                                     && CLASS_DATA (sym)->attr.allocatable))
10511         gfc_error ("Allocatable '%s' at %L cannot have an initializer",
10512                    sym->name, &sym->declared_at);
10513       else if (sym->attr.external)
10514         gfc_error ("External '%s' at %L cannot have an initializer",
10515                    sym->name, &sym->declared_at);
10516       else if (sym->attr.dummy
10517         && !(sym->ts.type == BT_DERIVED && sym->attr.intent == INTENT_OUT))
10518         gfc_error ("Dummy '%s' at %L cannot have an initializer",
10519                    sym->name, &sym->declared_at);
10520       else if (sym->attr.intrinsic)
10521         gfc_error ("Intrinsic '%s' at %L cannot have an initializer",
10522                    sym->name, &sym->declared_at);
10523       else if (sym->attr.result)
10524         gfc_error ("Function result '%s' at %L cannot have an initializer",
10525                    sym->name, &sym->declared_at);
10526       else if (automatic_flag)
10527         gfc_error ("Automatic array '%s' at %L cannot have an initializer",
10528                    sym->name, &sym->declared_at);
10529       else
10530         goto no_init_error;
10531       return FAILURE;
10532     }
10533
10534 no_init_error:
10535   if (sym->ts.type == BT_DERIVED || sym->ts.type == BT_CLASS)
10536     return resolve_fl_variable_derived (sym, no_init_flag);
10537
10538   return SUCCESS;
10539 }
10540
10541
10542 /* Resolve a procedure.  */
10543
10544 static gfc_try
10545 resolve_fl_procedure (gfc_symbol *sym, int mp_flag)
10546 {
10547   gfc_formal_arglist *arg;
10548
10549   if (sym->attr.function
10550       && resolve_fl_var_and_proc (sym, mp_flag) == FAILURE)
10551     return FAILURE;
10552
10553   if (sym->ts.type == BT_CHARACTER)
10554     {
10555       gfc_charlen *cl = sym->ts.u.cl;
10556
10557       if (cl && cl->length && gfc_is_constant_expr (cl->length)
10558              && resolve_charlen (cl) == FAILURE)
10559         return FAILURE;
10560
10561       if ((!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
10562           && sym->attr.proc == PROC_ST_FUNCTION)
10563         {
10564           gfc_error ("Character-valued statement function '%s' at %L must "
10565                      "have constant length", sym->name, &sym->declared_at);
10566           return FAILURE;
10567         }
10568     }
10569
10570   /* Ensure that derived type for are not of a private type.  Internal
10571      module procedures are excluded by 2.2.3.3 - i.e., they are not
10572      externally accessible and can access all the objects accessible in
10573      the host.  */
10574   if (!(sym->ns->parent
10575         && sym->ns->parent->proc_name->attr.flavor == FL_MODULE)
10576       && gfc_check_symbol_access (sym))
10577     {
10578       gfc_interface *iface;
10579
10580       for (arg = sym->formal; arg; arg = arg->next)
10581         {
10582           if (arg->sym
10583               && arg->sym->ts.type == BT_DERIVED
10584               && !arg->sym->ts.u.derived->attr.use_assoc
10585               && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10586               && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: '%s' is of a "
10587                                  "PRIVATE type and cannot be a dummy argument"
10588                                  " of '%s', which is PUBLIC at %L",
10589                                  arg->sym->name, sym->name, &sym->declared_at)
10590                  == FAILURE)
10591             {
10592               /* Stop this message from recurring.  */
10593               arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10594               return FAILURE;
10595             }
10596         }
10597
10598       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10599          PRIVATE to the containing module.  */
10600       for (iface = sym->generic; iface; iface = iface->next)
10601         {
10602           for (arg = iface->sym->formal; arg; arg = arg->next)
10603             {
10604               if (arg->sym
10605                   && arg->sym->ts.type == BT_DERIVED
10606                   && !arg->sym->ts.u.derived->attr.use_assoc
10607                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10608                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10609                                      "'%s' in PUBLIC interface '%s' at %L "
10610                                      "takes dummy arguments of '%s' which is "
10611                                      "PRIVATE", iface->sym->name, sym->name,
10612                                      &iface->sym->declared_at,
10613                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10614                 {
10615                   /* Stop this message from recurring.  */
10616                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10617                   return FAILURE;
10618                 }
10619              }
10620         }
10621
10622       /* PUBLIC interfaces may expose PRIVATE procedures that take types
10623          PRIVATE to the containing module.  */
10624       for (iface = sym->generic; iface; iface = iface->next)
10625         {
10626           for (arg = iface->sym->formal; arg; arg = arg->next)
10627             {
10628               if (arg->sym
10629                   && arg->sym->ts.type == BT_DERIVED
10630                   && !arg->sym->ts.u.derived->attr.use_assoc
10631                   && !gfc_check_symbol_access (arg->sym->ts.u.derived)
10632                   && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Procedure "
10633                                      "'%s' in PUBLIC interface '%s' at %L "
10634                                      "takes dummy arguments of '%s' which is "
10635                                      "PRIVATE", iface->sym->name, sym->name,
10636                                      &iface->sym->declared_at,
10637                                      gfc_typename (&arg->sym->ts)) == FAILURE)
10638                 {
10639                   /* Stop this message from recurring.  */
10640                   arg->sym->ts.u.derived->attr.access = ACCESS_PUBLIC;
10641                   return FAILURE;
10642                 }
10643              }
10644         }
10645     }
10646
10647   if (sym->attr.function && sym->value && sym->attr.proc != PROC_ST_FUNCTION
10648       && !sym->attr.proc_pointer)
10649     {
10650       gfc_error ("Function '%s' at %L cannot have an initializer",
10651                  sym->name, &sym->declared_at);
10652       return FAILURE;
10653     }
10654
10655   /* An external symbol may not have an initializer because it is taken to be
10656      a procedure. Exception: Procedure Pointers.  */
10657   if (sym->attr.external && sym->value && !sym->attr.proc_pointer)
10658     {
10659       gfc_error ("External object '%s' at %L may not have an initializer",
10660                  sym->name, &sym->declared_at);
10661       return FAILURE;
10662     }
10663
10664   /* An elemental function is required to return a scalar 12.7.1  */
10665   if (sym->attr.elemental && sym->attr.function && sym->as)
10666     {
10667       gfc_error ("ELEMENTAL function '%s' at %L must have a scalar "
10668                  "result", sym->name, &sym->declared_at);
10669       /* Reset so that the error only occurs once.  */
10670       sym->attr.elemental = 0;
10671       return FAILURE;
10672     }
10673
10674   if (sym->attr.proc == PROC_ST_FUNCTION
10675       && (sym->attr.allocatable || sym->attr.pointer))
10676     {
10677       gfc_error ("Statement function '%s' at %L may not have pointer or "
10678                  "allocatable attribute", sym->name, &sym->declared_at);
10679       return FAILURE;
10680     }
10681
10682   /* 5.1.1.5 of the Standard: A function name declared with an asterisk
10683      char-len-param shall not be array-valued, pointer-valued, recursive
10684      or pure.  ....snip... A character value of * may only be used in the
10685      following ways: (i) Dummy arg of procedure - dummy associates with
10686      actual length; (ii) To declare a named constant; or (iii) External
10687      function - but length must be declared in calling scoping unit.  */
10688   if (sym->attr.function
10689       && sym->ts.type == BT_CHARACTER
10690       && sym->ts.u.cl && sym->ts.u.cl->length == NULL)
10691     {
10692       if ((sym->as && sym->as->rank) || (sym->attr.pointer)
10693           || (sym->attr.recursive) || (sym->attr.pure))
10694         {
10695           if (sym->as && sym->as->rank)
10696             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10697                        "array-valued", sym->name, &sym->declared_at);
10698
10699           if (sym->attr.pointer)
10700             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10701                        "pointer-valued", sym->name, &sym->declared_at);
10702
10703           if (sym->attr.pure)
10704             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10705                        "pure", sym->name, &sym->declared_at);
10706
10707           if (sym->attr.recursive)
10708             gfc_error ("CHARACTER(*) function '%s' at %L cannot be "
10709                        "recursive", sym->name, &sym->declared_at);
10710
10711           return FAILURE;
10712         }
10713
10714       /* Appendix B.2 of the standard.  Contained functions give an
10715          error anyway.  Fixed-form is likely to be F77/legacy. Deferred
10716          character length is an F2003 feature.  */
10717       if (!sym->attr.contained
10718             && gfc_current_form != FORM_FIXED
10719             && !sym->ts.deferred)
10720         gfc_notify_std (GFC_STD_F95_OBS, "Obsolescent feature: "
10721                         "CHARACTER(*) function '%s' at %L",
10722                         sym->name, &sym->declared_at);
10723     }
10724
10725   if (sym->attr.is_bind_c && sym->attr.is_c_interop != 1)
10726     {
10727       gfc_formal_arglist *curr_arg;
10728       int has_non_interop_arg = 0;
10729
10730       if (verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
10731                              sym->common_block) == FAILURE)
10732         {
10733           /* Clear these to prevent looking at them again if there was an
10734              error.  */
10735           sym->attr.is_bind_c = 0;
10736           sym->attr.is_c_interop = 0;
10737           sym->ts.is_c_interop = 0;
10738         }
10739       else
10740         {
10741           /* So far, no errors have been found.  */
10742           sym->attr.is_c_interop = 1;
10743           sym->ts.is_c_interop = 1;
10744         }
10745
10746       curr_arg = sym->formal;
10747       while (curr_arg != NULL)
10748         {
10749           /* Skip implicitly typed dummy args here.  */
10750           if (curr_arg->sym->attr.implicit_type == 0)
10751             if (gfc_verify_c_interop_param (curr_arg->sym) == FAILURE)
10752               /* If something is found to fail, record the fact so we
10753                  can mark the symbol for the procedure as not being
10754                  BIND(C) to try and prevent multiple errors being
10755                  reported.  */
10756               has_non_interop_arg = 1;
10757
10758           curr_arg = curr_arg->next;
10759         }
10760
10761       /* See if any of the arguments were not interoperable and if so, clear
10762          the procedure symbol to prevent duplicate error messages.  */
10763       if (has_non_interop_arg != 0)
10764         {
10765           sym->attr.is_c_interop = 0;
10766           sym->ts.is_c_interop = 0;
10767           sym->attr.is_bind_c = 0;
10768         }
10769     }
10770
10771   if (!sym->attr.proc_pointer)
10772     {
10773       if (sym->attr.save == SAVE_EXPLICIT)
10774         {
10775           gfc_error ("PROCEDURE attribute conflicts with SAVE attribute "
10776                      "in '%s' at %L", sym->name, &sym->declared_at);
10777           return FAILURE;
10778         }
10779       if (sym->attr.intent)
10780         {
10781           gfc_error ("PROCEDURE attribute conflicts with INTENT attribute "
10782                      "in '%s' at %L", sym->name, &sym->declared_at);
10783           return FAILURE;
10784         }
10785       if (sym->attr.subroutine && sym->attr.result)
10786         {
10787           gfc_error ("PROCEDURE attribute conflicts with RESULT attribute "
10788                      "in '%s' at %L", sym->name, &sym->declared_at);
10789           return FAILURE;
10790         }
10791       if (sym->attr.external && sym->attr.function
10792           && ((sym->attr.if_source == IFSRC_DECL && !sym->attr.procedure)
10793               || sym->attr.contained))
10794         {
10795           gfc_error ("EXTERNAL attribute conflicts with FUNCTION attribute "
10796                      "in '%s' at %L", sym->name, &sym->declared_at);
10797           return FAILURE;
10798         }
10799       if (strcmp ("ppr@", sym->name) == 0)
10800         {
10801           gfc_error ("Procedure pointer result '%s' at %L "
10802                      "is missing the pointer attribute",
10803                      sym->ns->proc_name->name, &sym->declared_at);
10804           return FAILURE;
10805         }
10806     }
10807
10808   return SUCCESS;
10809 }
10810
10811
10812 /* Resolve a list of finalizer procedures.  That is, after they have hopefully
10813    been defined and we now know their defined arguments, check that they fulfill
10814    the requirements of the standard for procedures used as finalizers.  */
10815
10816 static gfc_try
10817 gfc_resolve_finalizers (gfc_symbol* derived)
10818 {
10819   gfc_finalizer* list;
10820   gfc_finalizer** prev_link; /* For removing wrong entries from the list.  */
10821   gfc_try result = SUCCESS;
10822   bool seen_scalar = false;
10823
10824   if (!derived->f2k_derived || !derived->f2k_derived->finalizers)
10825     return SUCCESS;
10826
10827   /* Walk over the list of finalizer-procedures, check them, and if any one
10828      does not fit in with the standard's definition, print an error and remove
10829      it from the list.  */
10830   prev_link = &derived->f2k_derived->finalizers;
10831   for (list = derived->f2k_derived->finalizers; list; list = *prev_link)
10832     {
10833       gfc_symbol* arg;
10834       gfc_finalizer* i;
10835       int my_rank;
10836
10837       /* Skip this finalizer if we already resolved it.  */
10838       if (list->proc_tree)
10839         {
10840           prev_link = &(list->next);
10841           continue;
10842         }
10843
10844       /* Check this exists and is a SUBROUTINE.  */
10845       if (!list->proc_sym->attr.subroutine)
10846         {
10847           gfc_error ("FINAL procedure '%s' at %L is not a SUBROUTINE",
10848                      list->proc_sym->name, &list->where);
10849           goto error;
10850         }
10851
10852       /* We should have exactly one argument.  */
10853       if (!list->proc_sym->formal || list->proc_sym->formal->next)
10854         {
10855           gfc_error ("FINAL procedure at %L must have exactly one argument",
10856                      &list->where);
10857           goto error;
10858         }
10859       arg = list->proc_sym->formal->sym;
10860
10861       /* This argument must be of our type.  */
10862       if (arg->ts.type != BT_DERIVED || arg->ts.u.derived != derived)
10863         {
10864           gfc_error ("Argument of FINAL procedure at %L must be of type '%s'",
10865                      &arg->declared_at, derived->name);
10866           goto error;
10867         }
10868
10869       /* It must neither be a pointer nor allocatable nor optional.  */
10870       if (arg->attr.pointer)
10871         {
10872           gfc_error ("Argument of FINAL procedure at %L must not be a POINTER",
10873                      &arg->declared_at);
10874           goto error;
10875         }
10876       if (arg->attr.allocatable)
10877         {
10878           gfc_error ("Argument of FINAL procedure at %L must not be"
10879                      " ALLOCATABLE", &arg->declared_at);
10880           goto error;
10881         }
10882       if (arg->attr.optional)
10883         {
10884           gfc_error ("Argument of FINAL procedure at %L must not be OPTIONAL",
10885                      &arg->declared_at);
10886           goto error;
10887         }
10888
10889       /* It must not be INTENT(OUT).  */
10890       if (arg->attr.intent == INTENT_OUT)
10891         {
10892           gfc_error ("Argument of FINAL procedure at %L must not be"
10893                      " INTENT(OUT)", &arg->declared_at);
10894           goto error;
10895         }
10896
10897       /* Warn if the procedure is non-scalar and not assumed shape.  */
10898       if (gfc_option.warn_surprising && arg->as && arg->as->rank > 0
10899           && arg->as->type != AS_ASSUMED_SHAPE)
10900         gfc_warning ("Non-scalar FINAL procedure at %L should have assumed"
10901                      " shape argument", &arg->declared_at);
10902
10903       /* Check that it does not match in kind and rank with a FINAL procedure
10904          defined earlier.  To really loop over the *earlier* declarations,
10905          we need to walk the tail of the list as new ones were pushed at the
10906          front.  */
10907       /* TODO: Handle kind parameters once they are implemented.  */
10908       my_rank = (arg->as ? arg->as->rank : 0);
10909       for (i = list->next; i; i = i->next)
10910         {
10911           /* Argument list might be empty; that is an error signalled earlier,
10912              but we nevertheless continued resolving.  */
10913           if (i->proc_sym->formal)
10914             {
10915               gfc_symbol* i_arg = i->proc_sym->formal->sym;
10916               const int i_rank = (i_arg->as ? i_arg->as->rank : 0);
10917               if (i_rank == my_rank)
10918                 {
10919                   gfc_error ("FINAL procedure '%s' declared at %L has the same"
10920                              " rank (%d) as '%s'",
10921                              list->proc_sym->name, &list->where, my_rank,
10922                              i->proc_sym->name);
10923                   goto error;
10924                 }
10925             }
10926         }
10927
10928         /* Is this the/a scalar finalizer procedure?  */
10929         if (!arg->as || arg->as->rank == 0)
10930           seen_scalar = true;
10931
10932         /* Find the symtree for this procedure.  */
10933         gcc_assert (!list->proc_tree);
10934         list->proc_tree = gfc_find_sym_in_symtree (list->proc_sym);
10935
10936         prev_link = &list->next;
10937         continue;
10938
10939         /* Remove wrong nodes immediately from the list so we don't risk any
10940            troubles in the future when they might fail later expectations.  */
10941 error:
10942         result = FAILURE;
10943         i = list;
10944         *prev_link = list->next;
10945         gfc_free_finalizer (i);
10946     }
10947
10948   /* Warn if we haven't seen a scalar finalizer procedure (but we know there
10949      were nodes in the list, must have been for arrays.  It is surely a good
10950      idea to have a scalar version there if there's something to finalize.  */
10951   if (gfc_option.warn_surprising && result == SUCCESS && !seen_scalar)
10952     gfc_warning ("Only array FINAL procedures declared for derived type '%s'"
10953                  " defined at %L, suggest also scalar one",
10954                  derived->name, &derived->declared_at);
10955
10956   /* TODO:  Remove this error when finalization is finished.  */
10957   gfc_error ("Finalization at %L is not yet implemented",
10958              &derived->declared_at);
10959
10960   return result;
10961 }
10962
10963
10964 /* Check if two GENERIC targets are ambiguous and emit an error is they are.  */
10965
10966 static gfc_try
10967 check_generic_tbp_ambiguity (gfc_tbp_generic* t1, gfc_tbp_generic* t2,
10968                              const char* generic_name, locus where)
10969 {
10970   gfc_symbol* sym1;
10971   gfc_symbol* sym2;
10972
10973   gcc_assert (t1->specific && t2->specific);
10974   gcc_assert (!t1->specific->is_generic);
10975   gcc_assert (!t2->specific->is_generic);
10976   gcc_assert (t1->is_operator == t2->is_operator);
10977
10978   sym1 = t1->specific->u.specific->n.sym;
10979   sym2 = t2->specific->u.specific->n.sym;
10980
10981   if (sym1 == sym2)
10982     return SUCCESS;
10983
10984   /* Both must be SUBROUTINEs or both must be FUNCTIONs.  */
10985   if (sym1->attr.subroutine != sym2->attr.subroutine
10986       || sym1->attr.function != sym2->attr.function)
10987     {
10988       gfc_error ("'%s' and '%s' can't be mixed FUNCTION/SUBROUTINE for"
10989                  " GENERIC '%s' at %L",
10990                  sym1->name, sym2->name, generic_name, &where);
10991       return FAILURE;
10992     }
10993
10994   /* Compare the interfaces.  */
10995   if (gfc_compare_interfaces (sym1, sym2, sym2->name, !t1->is_operator, 0,
10996                               NULL, 0))
10997     {
10998       gfc_error ("'%s' and '%s' for GENERIC '%s' at %L are ambiguous",
10999                  sym1->name, sym2->name, generic_name, &where);
11000       return FAILURE;
11001     }
11002
11003   return SUCCESS;
11004 }
11005
11006
11007 /* Worker function for resolving a generic procedure binding; this is used to
11008    resolve GENERIC as well as user and intrinsic OPERATOR typebound procedures.
11009
11010    The difference between those cases is finding possible inherited bindings
11011    that are overridden, as one has to look for them in tb_sym_root,
11012    tb_uop_root or tb_op, respectively.  Thus the caller must already find
11013    the super-type and set p->overridden correctly.  */
11014
11015 static gfc_try
11016 resolve_tb_generic_targets (gfc_symbol* super_type,
11017                             gfc_typebound_proc* p, const char* name)
11018 {
11019   gfc_tbp_generic* target;
11020   gfc_symtree* first_target;
11021   gfc_symtree* inherited;
11022
11023   gcc_assert (p && p->is_generic);
11024
11025   /* Try to find the specific bindings for the symtrees in our target-list.  */
11026   gcc_assert (p->u.generic);
11027   for (target = p->u.generic; target; target = target->next)
11028     if (!target->specific)
11029       {
11030         gfc_typebound_proc* overridden_tbp;
11031         gfc_tbp_generic* g;
11032         const char* target_name;
11033
11034         target_name = target->specific_st->name;
11035
11036         /* Defined for this type directly.  */
11037         if (target->specific_st->n.tb && !target->specific_st->n.tb->error)
11038           {
11039             target->specific = target->specific_st->n.tb;
11040             goto specific_found;
11041           }
11042
11043         /* Look for an inherited specific binding.  */
11044         if (super_type)
11045           {
11046             inherited = gfc_find_typebound_proc (super_type, NULL, target_name,
11047                                                  true, NULL);
11048
11049             if (inherited)
11050               {
11051                 gcc_assert (inherited->n.tb);
11052                 target->specific = inherited->n.tb;
11053                 goto specific_found;
11054               }
11055           }
11056
11057         gfc_error ("Undefined specific binding '%s' as target of GENERIC '%s'"
11058                    " at %L", target_name, name, &p->where);
11059         return FAILURE;
11060
11061         /* Once we've found the specific binding, check it is not ambiguous with
11062            other specifics already found or inherited for the same GENERIC.  */
11063 specific_found:
11064         gcc_assert (target->specific);
11065
11066         /* This must really be a specific binding!  */
11067         if (target->specific->is_generic)
11068           {
11069             gfc_error ("GENERIC '%s' at %L must target a specific binding,"
11070                        " '%s' is GENERIC, too", name, &p->where, target_name);
11071             return FAILURE;
11072           }
11073
11074         /* Check those already resolved on this type directly.  */
11075         for (g = p->u.generic; g; g = g->next)
11076           if (g != target && g->specific
11077               && check_generic_tbp_ambiguity (target, g, name, p->where)
11078                   == FAILURE)
11079             return FAILURE;
11080
11081         /* Check for ambiguity with inherited specific targets.  */
11082         for (overridden_tbp = p->overridden; overridden_tbp;
11083              overridden_tbp = overridden_tbp->overridden)
11084           if (overridden_tbp->is_generic)
11085             {
11086               for (g = overridden_tbp->u.generic; g; g = g->next)
11087                 {
11088                   gcc_assert (g->specific);
11089                   if (check_generic_tbp_ambiguity (target, g,
11090                                                    name, p->where) == FAILURE)
11091                     return FAILURE;
11092                 }
11093             }
11094       }
11095
11096   /* If we attempt to "overwrite" a specific binding, this is an error.  */
11097   if (p->overridden && !p->overridden->is_generic)
11098     {
11099       gfc_error ("GENERIC '%s' at %L can't overwrite specific binding with"
11100                  " the same name", name, &p->where);
11101       return FAILURE;
11102     }
11103
11104   /* Take the SUBROUTINE/FUNCTION attributes of the first specific target, as
11105      all must have the same attributes here.  */
11106   first_target = p->u.generic->specific->u.specific;
11107   gcc_assert (first_target);
11108   p->subroutine = first_target->n.sym->attr.subroutine;
11109   p->function = first_target->n.sym->attr.function;
11110
11111   return SUCCESS;
11112 }
11113
11114
11115 /* Resolve a GENERIC procedure binding for a derived type.  */
11116
11117 static gfc_try
11118 resolve_typebound_generic (gfc_symbol* derived, gfc_symtree* st)
11119 {
11120   gfc_symbol* super_type;
11121
11122   /* Find the overridden binding if any.  */
11123   st->n.tb->overridden = NULL;
11124   super_type = gfc_get_derived_super_type (derived);
11125   if (super_type)
11126     {
11127       gfc_symtree* overridden;
11128       overridden = gfc_find_typebound_proc (super_type, NULL, st->name,
11129                                             true, NULL);
11130
11131       if (overridden && overridden->n.tb)
11132         st->n.tb->overridden = overridden->n.tb;
11133     }
11134
11135   /* Resolve using worker function.  */
11136   return resolve_tb_generic_targets (super_type, st->n.tb, st->name);
11137 }
11138
11139
11140 /* Retrieve the target-procedure of an operator binding and do some checks in
11141    common for intrinsic and user-defined type-bound operators.  */
11142
11143 static gfc_symbol*
11144 get_checked_tb_operator_target (gfc_tbp_generic* target, locus where)
11145 {
11146   gfc_symbol* target_proc;
11147
11148   gcc_assert (target->specific && !target->specific->is_generic);
11149   target_proc = target->specific->u.specific->n.sym;
11150   gcc_assert (target_proc);
11151
11152   /* All operator bindings must have a passed-object dummy argument.  */
11153   if (target->specific->nopass)
11154     {
11155       gfc_error ("Type-bound operator at %L can't be NOPASS", &where);
11156       return NULL;
11157     }
11158
11159   return target_proc;
11160 }
11161
11162
11163 /* Resolve a type-bound intrinsic operator.  */
11164
11165 static gfc_try
11166 resolve_typebound_intrinsic_op (gfc_symbol* derived, gfc_intrinsic_op op,
11167                                 gfc_typebound_proc* p)
11168 {
11169   gfc_symbol* super_type;
11170   gfc_tbp_generic* target;
11171
11172   /* If there's already an error here, do nothing (but don't fail again).  */
11173   if (p->error)
11174     return SUCCESS;
11175
11176   /* Operators should always be GENERIC bindings.  */
11177   gcc_assert (p->is_generic);
11178
11179   /* Look for an overridden binding.  */
11180   super_type = gfc_get_derived_super_type (derived);
11181   if (super_type && super_type->f2k_derived)
11182     p->overridden = gfc_find_typebound_intrinsic_op (super_type, NULL,
11183                                                      op, true, NULL);
11184   else
11185     p->overridden = NULL;
11186
11187   /* Resolve general GENERIC properties using worker function.  */
11188   if (resolve_tb_generic_targets (super_type, p, gfc_op2string (op)) == FAILURE)
11189     goto error;
11190
11191   /* Check the targets to be procedures of correct interface.  */
11192   for (target = p->u.generic; target; target = target->next)
11193     {
11194       gfc_symbol* target_proc;
11195
11196       target_proc = get_checked_tb_operator_target (target, p->where);
11197       if (!target_proc)
11198         goto error;
11199
11200       if (!gfc_check_operator_interface (target_proc, op, p->where))
11201         goto error;
11202     }
11203
11204   return SUCCESS;
11205
11206 error:
11207   p->error = 1;
11208   return FAILURE;
11209 }
11210
11211
11212 /* Resolve a type-bound user operator (tree-walker callback).  */
11213
11214 static gfc_symbol* resolve_bindings_derived;
11215 static gfc_try resolve_bindings_result;
11216
11217 static gfc_try check_uop_procedure (gfc_symbol* sym, locus where);
11218
11219 static void
11220 resolve_typebound_user_op (gfc_symtree* stree)
11221 {
11222   gfc_symbol* super_type;
11223   gfc_tbp_generic* target;
11224
11225   gcc_assert (stree && stree->n.tb);
11226
11227   if (stree->n.tb->error)
11228     return;
11229
11230   /* Operators should always be GENERIC bindings.  */
11231   gcc_assert (stree->n.tb->is_generic);
11232
11233   /* Find overridden procedure, if any.  */
11234   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11235   if (super_type && super_type->f2k_derived)
11236     {
11237       gfc_symtree* overridden;
11238       overridden = gfc_find_typebound_user_op (super_type, NULL,
11239                                                stree->name, true, NULL);
11240
11241       if (overridden && overridden->n.tb)
11242         stree->n.tb->overridden = overridden->n.tb;
11243     }
11244   else
11245     stree->n.tb->overridden = NULL;
11246
11247   /* Resolve basically using worker function.  */
11248   if (resolve_tb_generic_targets (super_type, stree->n.tb, stree->name)
11249         == FAILURE)
11250     goto error;
11251
11252   /* Check the targets to be functions of correct interface.  */
11253   for (target = stree->n.tb->u.generic; target; target = target->next)
11254     {
11255       gfc_symbol* target_proc;
11256
11257       target_proc = get_checked_tb_operator_target (target, stree->n.tb->where);
11258       if (!target_proc)
11259         goto error;
11260
11261       if (check_uop_procedure (target_proc, stree->n.tb->where) == FAILURE)
11262         goto error;
11263     }
11264
11265   return;
11266
11267 error:
11268   resolve_bindings_result = FAILURE;
11269   stree->n.tb->error = 1;
11270 }
11271
11272
11273 /* Resolve the type-bound procedures for a derived type.  */
11274
11275 static void
11276 resolve_typebound_procedure (gfc_symtree* stree)
11277 {
11278   gfc_symbol* proc;
11279   locus where;
11280   gfc_symbol* me_arg;
11281   gfc_symbol* super_type;
11282   gfc_component* comp;
11283
11284   gcc_assert (stree);
11285
11286   /* Undefined specific symbol from GENERIC target definition.  */
11287   if (!stree->n.tb)
11288     return;
11289
11290   if (stree->n.tb->error)
11291     return;
11292
11293   /* If this is a GENERIC binding, use that routine.  */
11294   if (stree->n.tb->is_generic)
11295     {
11296       if (resolve_typebound_generic (resolve_bindings_derived, stree)
11297             == FAILURE)
11298         goto error;
11299       return;
11300     }
11301
11302   /* Get the target-procedure to check it.  */
11303   gcc_assert (!stree->n.tb->is_generic);
11304   gcc_assert (stree->n.tb->u.specific);
11305   proc = stree->n.tb->u.specific->n.sym;
11306   where = stree->n.tb->where;
11307
11308   /* Default access should already be resolved from the parser.  */
11309   gcc_assert (stree->n.tb->access != ACCESS_UNKNOWN);
11310
11311   /* It should be a module procedure or an external procedure with explicit
11312      interface.  For DEFERRED bindings, abstract interfaces are ok as well.  */
11313   if ((!proc->attr.subroutine && !proc->attr.function)
11314       || (proc->attr.proc != PROC_MODULE
11315           && proc->attr.if_source != IFSRC_IFBODY)
11316       || (proc->attr.abstract && !stree->n.tb->deferred))
11317     {
11318       gfc_error ("'%s' must be a module procedure or an external procedure with"
11319                  " an explicit interface at %L", proc->name, &where);
11320       goto error;
11321     }
11322   stree->n.tb->subroutine = proc->attr.subroutine;
11323   stree->n.tb->function = proc->attr.function;
11324
11325   /* Find the super-type of the current derived type.  We could do this once and
11326      store in a global if speed is needed, but as long as not I believe this is
11327      more readable and clearer.  */
11328   super_type = gfc_get_derived_super_type (resolve_bindings_derived);
11329
11330   /* If PASS, resolve and check arguments if not already resolved / loaded
11331      from a .mod file.  */
11332   if (!stree->n.tb->nopass && stree->n.tb->pass_arg_num == 0)
11333     {
11334       if (stree->n.tb->pass_arg)
11335         {
11336           gfc_formal_arglist* i;
11337
11338           /* If an explicit passing argument name is given, walk the arg-list
11339              and look for it.  */
11340
11341           me_arg = NULL;
11342           stree->n.tb->pass_arg_num = 1;
11343           for (i = proc->formal; i; i = i->next)
11344             {
11345               if (!strcmp (i->sym->name, stree->n.tb->pass_arg))
11346                 {
11347                   me_arg = i->sym;
11348                   break;
11349                 }
11350               ++stree->n.tb->pass_arg_num;
11351             }
11352
11353           if (!me_arg)
11354             {
11355               gfc_error ("Procedure '%s' with PASS(%s) at %L has no"
11356                          " argument '%s'",
11357                          proc->name, stree->n.tb->pass_arg, &where,
11358                          stree->n.tb->pass_arg);
11359               goto error;
11360             }
11361         }
11362       else
11363         {
11364           /* Otherwise, take the first one; there should in fact be at least
11365              one.  */
11366           stree->n.tb->pass_arg_num = 1;
11367           if (!proc->formal)
11368             {
11369               gfc_error ("Procedure '%s' with PASS at %L must have at"
11370                          " least one argument", proc->name, &where);
11371               goto error;
11372             }
11373           me_arg = proc->formal->sym;
11374         }
11375
11376       /* Now check that the argument-type matches and the passed-object
11377          dummy argument is generally fine.  */
11378
11379       gcc_assert (me_arg);
11380
11381       if (me_arg->ts.type != BT_CLASS)
11382         {
11383           gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11384                      " at %L", proc->name, &where);
11385           goto error;
11386         }
11387
11388       if (CLASS_DATA (me_arg)->ts.u.derived
11389           != resolve_bindings_derived)
11390         {
11391           gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11392                      " the derived-type '%s'", me_arg->name, proc->name,
11393                      me_arg->name, &where, resolve_bindings_derived->name);
11394           goto error;
11395         }
11396
11397       gcc_assert (me_arg->ts.type == BT_CLASS);
11398       if (CLASS_DATA (me_arg)->as && CLASS_DATA (me_arg)->as->rank > 0)
11399         {
11400           gfc_error ("Passed-object dummy argument of '%s' at %L must be"
11401                      " scalar", proc->name, &where);
11402           goto error;
11403         }
11404       if (CLASS_DATA (me_arg)->attr.allocatable)
11405         {
11406           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11407                      " be ALLOCATABLE", proc->name, &where);
11408           goto error;
11409         }
11410       if (CLASS_DATA (me_arg)->attr.class_pointer)
11411         {
11412           gfc_error ("Passed-object dummy argument of '%s' at %L must not"
11413                      " be POINTER", proc->name, &where);
11414           goto error;
11415         }
11416     }
11417
11418   /* If we are extending some type, check that we don't override a procedure
11419      flagged NON_OVERRIDABLE.  */
11420   stree->n.tb->overridden = NULL;
11421   if (super_type)
11422     {
11423       gfc_symtree* overridden;
11424       overridden = gfc_find_typebound_proc (super_type, NULL,
11425                                             stree->name, true, NULL);
11426
11427       if (overridden)
11428         {
11429           if (overridden->n.tb)
11430             stree->n.tb->overridden = overridden->n.tb;
11431
11432           if (gfc_check_typebound_override (stree, overridden) == FAILURE)
11433             goto error;
11434         }
11435     }
11436
11437   /* See if there's a name collision with a component directly in this type.  */
11438   for (comp = resolve_bindings_derived->components; comp; comp = comp->next)
11439     if (!strcmp (comp->name, stree->name))
11440       {
11441         gfc_error ("Procedure '%s' at %L has the same name as a component of"
11442                    " '%s'",
11443                    stree->name, &where, resolve_bindings_derived->name);
11444         goto error;
11445       }
11446
11447   /* Try to find a name collision with an inherited component.  */
11448   if (super_type && gfc_find_component (super_type, stree->name, true, true))
11449     {
11450       gfc_error ("Procedure '%s' at %L has the same name as an inherited"
11451                  " component of '%s'",
11452                  stree->name, &where, resolve_bindings_derived->name);
11453       goto error;
11454     }
11455
11456   stree->n.tb->error = 0;
11457   return;
11458
11459 error:
11460   resolve_bindings_result = FAILURE;
11461   stree->n.tb->error = 1;
11462 }
11463
11464
11465 static gfc_try
11466 resolve_typebound_procedures (gfc_symbol* derived)
11467 {
11468   int op;
11469   gfc_symbol* super_type;
11470
11471   if (!derived->f2k_derived || !derived->f2k_derived->tb_sym_root)
11472     return SUCCESS;
11473
11474   super_type = gfc_get_derived_super_type (derived);
11475   if (super_type)
11476     resolve_typebound_procedures (super_type);
11477
11478   resolve_bindings_derived = derived;
11479   resolve_bindings_result = SUCCESS;
11480
11481   /* Make sure the vtab has been generated.  */
11482   gfc_find_derived_vtab (derived);
11483
11484   if (derived->f2k_derived->tb_sym_root)
11485     gfc_traverse_symtree (derived->f2k_derived->tb_sym_root,
11486                           &resolve_typebound_procedure);
11487
11488   if (derived->f2k_derived->tb_uop_root)
11489     gfc_traverse_symtree (derived->f2k_derived->tb_uop_root,
11490                           &resolve_typebound_user_op);
11491
11492   for (op = 0; op != GFC_INTRINSIC_OPS; ++op)
11493     {
11494       gfc_typebound_proc* p = derived->f2k_derived->tb_op[op];
11495       if (p && resolve_typebound_intrinsic_op (derived, (gfc_intrinsic_op) op,
11496                                                p) == FAILURE)
11497         resolve_bindings_result = FAILURE;
11498     }
11499
11500   return resolve_bindings_result;
11501 }
11502
11503
11504 /* Add a derived type to the dt_list.  The dt_list is used in trans-types.c
11505    to give all identical derived types the same backend_decl.  */
11506 static void
11507 add_dt_to_dt_list (gfc_symbol *derived)
11508 {
11509   gfc_dt_list *dt_list;
11510
11511   for (dt_list = gfc_derived_types; dt_list; dt_list = dt_list->next)
11512     if (derived == dt_list->derived)
11513       return;
11514
11515   dt_list = gfc_get_dt_list ();
11516   dt_list->next = gfc_derived_types;
11517   dt_list->derived = derived;
11518   gfc_derived_types = dt_list;
11519 }
11520
11521
11522 /* Ensure that a derived-type is really not abstract, meaning that every
11523    inherited DEFERRED binding is overridden by a non-DEFERRED one.  */
11524
11525 static gfc_try
11526 ensure_not_abstract_walker (gfc_symbol* sub, gfc_symtree* st)
11527 {
11528   if (!st)
11529     return SUCCESS;
11530
11531   if (ensure_not_abstract_walker (sub, st->left) == FAILURE)
11532     return FAILURE;
11533   if (ensure_not_abstract_walker (sub, st->right) == FAILURE)
11534     return FAILURE;
11535
11536   if (st->n.tb && st->n.tb->deferred)
11537     {
11538       gfc_symtree* overriding;
11539       overriding = gfc_find_typebound_proc (sub, NULL, st->name, true, NULL);
11540       if (!overriding)
11541         return FAILURE;
11542       gcc_assert (overriding->n.tb);
11543       if (overriding->n.tb->deferred)
11544         {
11545           gfc_error ("Derived-type '%s' declared at %L must be ABSTRACT because"
11546                      " '%s' is DEFERRED and not overridden",
11547                      sub->name, &sub->declared_at, st->name);
11548           return FAILURE;
11549         }
11550     }
11551
11552   return SUCCESS;
11553 }
11554
11555 static gfc_try
11556 ensure_not_abstract (gfc_symbol* sub, gfc_symbol* ancestor)
11557 {
11558   /* The algorithm used here is to recursively travel up the ancestry of sub
11559      and for each ancestor-type, check all bindings.  If any of them is
11560      DEFERRED, look it up starting from sub and see if the found (overriding)
11561      binding is not DEFERRED.
11562      This is not the most efficient way to do this, but it should be ok and is
11563      clearer than something sophisticated.  */
11564
11565   gcc_assert (ancestor && !sub->attr.abstract);
11566
11567   if (!ancestor->attr.abstract)
11568     return SUCCESS;
11569
11570   /* Walk bindings of this ancestor.  */
11571   if (ancestor->f2k_derived)
11572     {
11573       gfc_try t;
11574       t = ensure_not_abstract_walker (sub, ancestor->f2k_derived->tb_sym_root);
11575       if (t == FAILURE)
11576         return FAILURE;
11577     }
11578
11579   /* Find next ancestor type and recurse on it.  */
11580   ancestor = gfc_get_derived_super_type (ancestor);
11581   if (ancestor)
11582     return ensure_not_abstract (sub, ancestor);
11583
11584   return SUCCESS;
11585 }
11586
11587
11588 /* Resolve the components of a derived type. This does not have to wait until
11589    resolution stage, but can be done as soon as the dt declaration has been
11590    parsed.  */
11591
11592 static gfc_try
11593 resolve_fl_derived0 (gfc_symbol *sym)
11594 {
11595   gfc_symbol* super_type;
11596   gfc_component *c;
11597
11598   super_type = gfc_get_derived_super_type (sym);
11599
11600   /* F2008, C432. */
11601   if (super_type && sym->attr.coarray_comp && !super_type->attr.coarray_comp)
11602     {
11603       gfc_error ("As extending type '%s' at %L has a coarray component, "
11604                  "parent type '%s' shall also have one", sym->name,
11605                  &sym->declared_at, super_type->name);
11606       return FAILURE;
11607     }
11608
11609   /* Ensure the extended type gets resolved before we do.  */
11610   if (super_type && resolve_fl_derived0 (super_type) == FAILURE)
11611     return FAILURE;
11612
11613   /* An ABSTRACT type must be extensible.  */
11614   if (sym->attr.abstract && !gfc_type_is_extensible (sym))
11615     {
11616       gfc_error ("Non-extensible derived-type '%s' at %L must not be ABSTRACT",
11617                  sym->name, &sym->declared_at);
11618       return FAILURE;
11619     }
11620
11621   c = (sym->attr.is_class) ? sym->components->ts.u.derived->components
11622                            : sym->components;
11623
11624   for ( ; c != NULL; c = c->next)
11625     {
11626       /* See PRs 51550, 47545, 48654, 49050, 51075 - and 45170.  */
11627       if (c->ts.type == BT_CHARACTER && c->ts.deferred)
11628         {
11629           gfc_error ("Deferred-length character component '%s' at %L is not "
11630                      "yet supported", c->name, &c->loc);
11631           return FAILURE;
11632         }
11633
11634       /* F2008, C442.  */
11635       if ((!sym->attr.is_class || c != sym->components)
11636           && c->attr.codimension
11637           && (!c->attr.allocatable || (c->as && c->as->type != AS_DEFERRED)))
11638         {
11639           gfc_error ("Coarray component '%s' at %L must be allocatable with "
11640                      "deferred shape", c->name, &c->loc);
11641           return FAILURE;
11642         }
11643
11644       /* F2008, C443.  */
11645       if (c->attr.codimension && c->ts.type == BT_DERIVED
11646           && c->ts.u.derived->ts.is_iso_c)
11647         {
11648           gfc_error ("Component '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
11649                      "shall not be a coarray", c->name, &c->loc);
11650           return FAILURE;
11651         }
11652
11653       /* F2008, C444.  */
11654       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.coarray_comp
11655           && (c->attr.codimension || c->attr.pointer || c->attr.dimension
11656               || c->attr.allocatable))
11657         {
11658           gfc_error ("Component '%s' at %L with coarray component "
11659                      "shall be a nonpointer, nonallocatable scalar",
11660                      c->name, &c->loc);
11661           return FAILURE;
11662         }
11663
11664       /* F2008, C448.  */
11665       if (c->attr.contiguous && (!c->attr.dimension || !c->attr.pointer))
11666         {
11667           gfc_error ("Component '%s' at %L has the CONTIGUOUS attribute but "
11668                      "is not an array pointer", c->name, &c->loc);
11669           return FAILURE;
11670         }
11671
11672       if (c->attr.proc_pointer && c->ts.interface)
11673         {
11674           if (c->ts.interface->attr.procedure && !sym->attr.vtype)
11675             gfc_error ("Interface '%s', used by procedure pointer component "
11676                        "'%s' at %L, is declared in a later PROCEDURE statement",
11677                        c->ts.interface->name, c->name, &c->loc);
11678
11679           /* Get the attributes from the interface (now resolved).  */
11680           if (c->ts.interface->attr.if_source
11681               || c->ts.interface->attr.intrinsic)
11682             {
11683               gfc_symbol *ifc = c->ts.interface;
11684
11685               if (ifc->formal && !ifc->formal_ns)
11686                 resolve_symbol (ifc);
11687
11688               if (ifc->attr.intrinsic)
11689                 resolve_intrinsic (ifc, &ifc->declared_at);
11690
11691               if (ifc->result)
11692                 {
11693                   c->ts = ifc->result->ts;
11694                   c->attr.allocatable = ifc->result->attr.allocatable;
11695                   c->attr.pointer = ifc->result->attr.pointer;
11696                   c->attr.dimension = ifc->result->attr.dimension;
11697                   c->as = gfc_copy_array_spec (ifc->result->as);
11698                 }
11699               else
11700                 {
11701                   c->ts = ifc->ts;
11702                   c->attr.allocatable = ifc->attr.allocatable;
11703                   c->attr.pointer = ifc->attr.pointer;
11704                   c->attr.dimension = ifc->attr.dimension;
11705                   c->as = gfc_copy_array_spec (ifc->as);
11706                 }
11707               c->ts.interface = ifc;
11708               c->attr.function = ifc->attr.function;
11709               c->attr.subroutine = ifc->attr.subroutine;
11710               gfc_copy_formal_args_ppc (c, ifc);
11711
11712               c->attr.pure = ifc->attr.pure;
11713               c->attr.elemental = ifc->attr.elemental;
11714               c->attr.recursive = ifc->attr.recursive;
11715               c->attr.always_explicit = ifc->attr.always_explicit;
11716               c->attr.ext_attr |= ifc->attr.ext_attr;
11717               /* Replace symbols in array spec.  */
11718               if (c->as)
11719                 {
11720                   int i;
11721                   for (i = 0; i < c->as->rank; i++)
11722                     {
11723                       gfc_expr_replace_comp (c->as->lower[i], c);
11724                       gfc_expr_replace_comp (c->as->upper[i], c);
11725                     }
11726                 }
11727               /* Copy char length.  */
11728               if (ifc->ts.type == BT_CHARACTER && ifc->ts.u.cl)
11729                 {
11730                   gfc_charlen *cl = gfc_new_charlen (sym->ns, ifc->ts.u.cl);
11731                   gfc_expr_replace_comp (cl->length, c);
11732                   if (cl->length && !cl->resolved
11733                         && gfc_resolve_expr (cl->length) == FAILURE)
11734                     return FAILURE;
11735                   c->ts.u.cl = cl;
11736                 }
11737             }
11738           else if (!sym->attr.vtype && c->ts.interface->name[0] != '\0')
11739             {
11740               gfc_error ("Interface '%s' of procedure pointer component "
11741                          "'%s' at %L must be explicit", c->ts.interface->name,
11742                          c->name, &c->loc);
11743               return FAILURE;
11744             }
11745         }
11746       else if (c->attr.proc_pointer && c->ts.type == BT_UNKNOWN)
11747         {
11748           /* Since PPCs are not implicitly typed, a PPC without an explicit
11749              interface must be a subroutine.  */
11750           gfc_add_subroutine (&c->attr, c->name, &c->loc);
11751         }
11752
11753       /* Procedure pointer components: Check PASS arg.  */
11754       if (c->attr.proc_pointer && !c->tb->nopass && c->tb->pass_arg_num == 0
11755           && !sym->attr.vtype)
11756         {
11757           gfc_symbol* me_arg;
11758
11759           if (c->tb->pass_arg)
11760             {
11761               gfc_formal_arglist* i;
11762
11763               /* If an explicit passing argument name is given, walk the arg-list
11764                 and look for it.  */
11765
11766               me_arg = NULL;
11767               c->tb->pass_arg_num = 1;
11768               for (i = c->formal; i; i = i->next)
11769                 {
11770                   if (!strcmp (i->sym->name, c->tb->pass_arg))
11771                     {
11772                       me_arg = i->sym;
11773                       break;
11774                     }
11775                   c->tb->pass_arg_num++;
11776                 }
11777
11778               if (!me_arg)
11779                 {
11780                   gfc_error ("Procedure pointer component '%s' with PASS(%s) "
11781                              "at %L has no argument '%s'", c->name,
11782                              c->tb->pass_arg, &c->loc, c->tb->pass_arg);
11783                   c->tb->error = 1;
11784                   return FAILURE;
11785                 }
11786             }
11787           else
11788             {
11789               /* Otherwise, take the first one; there should in fact be at least
11790                 one.  */
11791               c->tb->pass_arg_num = 1;
11792               if (!c->formal)
11793                 {
11794                   gfc_error ("Procedure pointer component '%s' with PASS at %L "
11795                              "must have at least one argument",
11796                              c->name, &c->loc);
11797                   c->tb->error = 1;
11798                   return FAILURE;
11799                 }
11800               me_arg = c->formal->sym;
11801             }
11802
11803           /* Now check that the argument-type matches.  */
11804           gcc_assert (me_arg);
11805           if ((me_arg->ts.type != BT_DERIVED && me_arg->ts.type != BT_CLASS)
11806               || (me_arg->ts.type == BT_DERIVED && me_arg->ts.u.derived != sym)
11807               || (me_arg->ts.type == BT_CLASS
11808                   && CLASS_DATA (me_arg)->ts.u.derived != sym))
11809             {
11810               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L must be of"
11811                          " the derived type '%s'", me_arg->name, c->name,
11812                          me_arg->name, &c->loc, sym->name);
11813               c->tb->error = 1;
11814               return FAILURE;
11815             }
11816
11817           /* Check for C453.  */
11818           if (me_arg->attr.dimension)
11819             {
11820               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11821                          "must be scalar", me_arg->name, c->name, me_arg->name,
11822                          &c->loc);
11823               c->tb->error = 1;
11824               return FAILURE;
11825             }
11826
11827           if (me_arg->attr.pointer)
11828             {
11829               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11830                          "may not have the POINTER attribute", me_arg->name,
11831                          c->name, me_arg->name, &c->loc);
11832               c->tb->error = 1;
11833               return FAILURE;
11834             }
11835
11836           if (me_arg->attr.allocatable)
11837             {
11838               gfc_error ("Argument '%s' of '%s' with PASS(%s) at %L "
11839                          "may not be ALLOCATABLE", me_arg->name, c->name,
11840                          me_arg->name, &c->loc);
11841               c->tb->error = 1;
11842               return FAILURE;
11843             }
11844
11845           if (gfc_type_is_extensible (sym) && me_arg->ts.type != BT_CLASS)
11846             gfc_error ("Non-polymorphic passed-object dummy argument of '%s'"
11847                        " at %L", c->name, &c->loc);
11848
11849         }
11850
11851       /* Check type-spec if this is not the parent-type component.  */
11852       if (((sym->attr.is_class
11853             && (!sym->components->ts.u.derived->attr.extension
11854                 || c != sym->components->ts.u.derived->components))
11855            || (!sym->attr.is_class
11856                && (!sym->attr.extension || c != sym->components)))
11857           && !sym->attr.vtype
11858           && resolve_typespec_used (&c->ts, &c->loc, c->name) == FAILURE)
11859         return FAILURE;
11860
11861       /* If this type is an extension, set the accessibility of the parent
11862          component.  */
11863       if (super_type
11864           && ((sym->attr.is_class
11865                && c == sym->components->ts.u.derived->components)
11866               || (!sym->attr.is_class && c == sym->components))
11867           && strcmp (super_type->name, c->name) == 0)
11868         c->attr.access = super_type->attr.access;
11869
11870       /* If this type is an extension, see if this component has the same name
11871          as an inherited type-bound procedure.  */
11872       if (super_type && !sym->attr.is_class
11873           && gfc_find_typebound_proc (super_type, NULL, c->name, true, NULL))
11874         {
11875           gfc_error ("Component '%s' of '%s' at %L has the same name as an"
11876                      " inherited type-bound procedure",
11877                      c->name, sym->name, &c->loc);
11878           return FAILURE;
11879         }
11880
11881       if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
11882             && !c->ts.deferred)
11883         {
11884          if (c->ts.u.cl->length == NULL
11885              || (resolve_charlen (c->ts.u.cl) == FAILURE)
11886              || !gfc_is_constant_expr (c->ts.u.cl->length))
11887            {
11888              gfc_error ("Character length of component '%s' needs to "
11889                         "be a constant specification expression at %L",
11890                         c->name,
11891                         c->ts.u.cl->length ? &c->ts.u.cl->length->where : &c->loc);
11892              return FAILURE;
11893            }
11894         }
11895
11896       if (c->ts.type == BT_CHARACTER && c->ts.deferred
11897           && !c->attr.pointer && !c->attr.allocatable)
11898         {
11899           gfc_error ("Character component '%s' of '%s' at %L with deferred "
11900                      "length must be a POINTER or ALLOCATABLE",
11901                      c->name, sym->name, &c->loc);
11902           return FAILURE;
11903         }
11904
11905       if (c->ts.type == BT_DERIVED
11906           && sym->component_access != ACCESS_PRIVATE
11907           && gfc_check_symbol_access (sym)
11908           && !is_sym_host_assoc (c->ts.u.derived, sym->ns)
11909           && !c->ts.u.derived->attr.use_assoc
11910           && !gfc_check_symbol_access (c->ts.u.derived)
11911           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: the component '%s' "
11912                              "is a PRIVATE type and cannot be a component of "
11913                              "'%s', which is PUBLIC at %L", c->name,
11914                              sym->name, &sym->declared_at) == FAILURE)
11915         return FAILURE;
11916
11917       if ((sym->attr.sequence || sym->attr.is_bind_c) && c->ts.type == BT_CLASS)
11918         {
11919           gfc_error ("Polymorphic component %s at %L in SEQUENCE or BIND(C) "
11920                      "type %s", c->name, &c->loc, sym->name);
11921           return FAILURE;
11922         }
11923
11924       if (sym->attr.sequence)
11925         {
11926           if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.sequence == 0)
11927             {
11928               gfc_error ("Component %s of SEQUENCE type declared at %L does "
11929                          "not have the SEQUENCE attribute",
11930                          c->ts.u.derived->name, &sym->declared_at);
11931               return FAILURE;
11932             }
11933         }
11934
11935       if (c->ts.type == BT_DERIVED && c->ts.u.derived->attr.generic)
11936         c->ts.u.derived = gfc_find_dt_in_generic (c->ts.u.derived);
11937       else if (c->ts.type == BT_CLASS && c->attr.class_ok
11938                && CLASS_DATA (c)->ts.u.derived->attr.generic)
11939         CLASS_DATA (c)->ts.u.derived
11940                         = gfc_find_dt_in_generic (CLASS_DATA (c)->ts.u.derived);
11941
11942       if (!sym->attr.is_class && c->ts.type == BT_DERIVED && !sym->attr.vtype
11943           && c->attr.pointer && c->ts.u.derived->components == NULL
11944           && !c->ts.u.derived->attr.zero_comp)
11945         {
11946           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11947                      "that has not been declared", c->name, sym->name,
11948                      &c->loc);
11949           return FAILURE;
11950         }
11951
11952       if (c->ts.type == BT_CLASS && c->attr.class_ok
11953           && CLASS_DATA (c)->attr.class_pointer
11954           && CLASS_DATA (c)->ts.u.derived->components == NULL
11955           && !CLASS_DATA (c)->ts.u.derived->attr.zero_comp)
11956         {
11957           gfc_error ("The pointer component '%s' of '%s' at %L is a type "
11958                      "that has not been declared", c->name, sym->name,
11959                      &c->loc);
11960           return FAILURE;
11961         }
11962
11963       /* C437.  */
11964       if (c->ts.type == BT_CLASS && c->attr.flavor != FL_PROCEDURE
11965           && (!c->attr.class_ok
11966               || !(CLASS_DATA (c)->attr.class_pointer
11967                    || CLASS_DATA (c)->attr.allocatable)))
11968         {
11969           gfc_error ("Component '%s' with CLASS at %L must be allocatable "
11970                      "or pointer", c->name, &c->loc);
11971           /* Prevent a recurrence of the error.  */
11972           c->ts.type = BT_UNKNOWN;
11973           return FAILURE;
11974         }
11975
11976       /* Ensure that all the derived type components are put on the
11977          derived type list; even in formal namespaces, where derived type
11978          pointer components might not have been declared.  */
11979       if (c->ts.type == BT_DERIVED
11980             && c->ts.u.derived
11981             && c->ts.u.derived->components
11982             && c->attr.pointer
11983             && sym != c->ts.u.derived)
11984         add_dt_to_dt_list (c->ts.u.derived);
11985
11986       if (gfc_resolve_array_spec (c->as, !(c->attr.pointer
11987                                            || c->attr.proc_pointer
11988                                            || c->attr.allocatable)) == FAILURE)
11989         return FAILURE;
11990     }
11991
11992   /* If this is a non-ABSTRACT type extending an ABSTRACT one, ensure that
11993      all DEFERRED bindings are overridden.  */
11994   if (super_type && super_type->attr.abstract && !sym->attr.abstract
11995       && !sym->attr.is_class
11996       && ensure_not_abstract (sym, super_type) == FAILURE)
11997     return FAILURE;
11998
11999   /* Add derived type to the derived type list.  */
12000   add_dt_to_dt_list (sym);
12001
12002   return SUCCESS;
12003 }
12004
12005
12006 /* The following procedure does the full resolution of a derived type,
12007    including resolution of all type-bound procedures (if present). In contrast
12008    to 'resolve_fl_derived0' this can only be done after the module has been
12009    parsed completely.  */
12010
12011 static gfc_try
12012 resolve_fl_derived (gfc_symbol *sym)
12013 {
12014   gfc_symbol *gen_dt = NULL;
12015
12016   if (!sym->attr.is_class)
12017     gfc_find_symbol (sym->name, sym->ns, 0, &gen_dt);
12018   if (gen_dt && gen_dt->generic && gen_dt->generic->next
12019       && (!gen_dt->generic->sym->attr.use_assoc
12020           || gen_dt->generic->sym->module != gen_dt->generic->next->sym->module)
12021       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: Generic name '%s' of "
12022                          "function '%s' at %L being the same name as derived "
12023                          "type at %L", sym->name,
12024                          gen_dt->generic->sym == sym
12025                            ? gen_dt->generic->next->sym->name
12026                            : gen_dt->generic->sym->name,
12027                          gen_dt->generic->sym == sym
12028                            ? &gen_dt->generic->next->sym->declared_at
12029                            : &gen_dt->generic->sym->declared_at,
12030                          &sym->declared_at) == FAILURE)
12031     return FAILURE;
12032
12033   if (sym->attr.is_class && sym->ts.u.derived == NULL)
12034     {
12035       /* Fix up incomplete CLASS symbols.  */
12036       gfc_component *data = gfc_find_component (sym, "_data", true, true);
12037       gfc_component *vptr = gfc_find_component (sym, "_vptr", true, true);
12038       if (vptr->ts.u.derived == NULL)
12039         {
12040           gfc_symbol *vtab = gfc_find_derived_vtab (data->ts.u.derived);
12041           gcc_assert (vtab);
12042           vptr->ts.u.derived = vtab->ts.u.derived;
12043         }
12044     }
12045
12046   if (resolve_fl_derived0 (sym) == FAILURE)
12047     return FAILURE;
12048
12049   /* Resolve the type-bound procedures.  */
12050   if (resolve_typebound_procedures (sym) == FAILURE)
12051     return FAILURE;
12052
12053   /* Resolve the finalizer procedures.  */
12054   if (gfc_resolve_finalizers (sym) == FAILURE)
12055     return FAILURE;
12056
12057   return SUCCESS;
12058 }
12059
12060
12061 static gfc_try
12062 resolve_fl_namelist (gfc_symbol *sym)
12063 {
12064   gfc_namelist *nl;
12065   gfc_symbol *nlsym;
12066
12067   for (nl = sym->namelist; nl; nl = nl->next)
12068     {
12069       /* Check again, the check in match only works if NAMELIST comes
12070          after the decl.  */
12071       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SIZE)
12072         {
12073           gfc_error ("Assumed size array '%s' in namelist '%s' at %L is not "
12074                      "allowed", nl->sym->name, sym->name, &sym->declared_at);
12075           return FAILURE;
12076         }
12077
12078       if (nl->sym->as && nl->sym->as->type == AS_ASSUMED_SHAPE
12079           && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: NAMELIST array "
12080                              "object '%s' with assumed shape in namelist "
12081                              "'%s' at %L", nl->sym->name, sym->name,
12082                              &sym->declared_at) == FAILURE)
12083         return FAILURE;
12084
12085       if (is_non_constant_shape_array (nl->sym)
12086           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST array "
12087                              "object '%s' with nonconstant shape in namelist "
12088                              "'%s' at %L", nl->sym->name, sym->name,
12089                              &sym->declared_at) == FAILURE)
12090         return FAILURE;
12091
12092       if (nl->sym->ts.type == BT_CHARACTER
12093           && (nl->sym->ts.u.cl->length == NULL
12094               || !gfc_is_constant_expr (nl->sym->ts.u.cl->length))
12095           && gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
12096                              "'%s' with nonconstant character length in "
12097                              "namelist '%s' at %L", nl->sym->name, sym->name,
12098                              &sym->declared_at) == FAILURE)
12099         return FAILURE;
12100
12101       /* FIXME: Once UDDTIO is implemented, the following can be
12102          removed.  */
12103       if (nl->sym->ts.type == BT_CLASS)
12104         {
12105           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L is "
12106                      "polymorphic and requires a defined input/output "
12107                      "procedure", nl->sym->name, sym->name, &sym->declared_at);
12108           return FAILURE;
12109         }
12110
12111       if (nl->sym->ts.type == BT_DERIVED
12112           && (nl->sym->ts.u.derived->attr.alloc_comp
12113               || nl->sym->ts.u.derived->attr.pointer_comp))
12114         {
12115           if (gfc_notify_std (GFC_STD_F2003,  "Fortran 2003: NAMELIST object "
12116                               "'%s' in namelist '%s' at %L with ALLOCATABLE "
12117                               "or POINTER components", nl->sym->name,
12118                               sym->name, &sym->declared_at) == FAILURE)
12119             return FAILURE;
12120
12121          /* FIXME: Once UDDTIO is implemented, the following can be
12122             removed.  */
12123           gfc_error ("NAMELIST object '%s' in namelist '%s' at %L has "
12124                      "ALLOCATABLE or POINTER components and thus requires "
12125                      "a defined input/output procedure", nl->sym->name,
12126                      sym->name, &sym->declared_at);
12127           return FAILURE;
12128         }
12129     }
12130
12131   /* Reject PRIVATE objects in a PUBLIC namelist.  */
12132   if (gfc_check_symbol_access (sym))
12133     {
12134       for (nl = sym->namelist; nl; nl = nl->next)
12135         {
12136           if (!nl->sym->attr.use_assoc
12137               && !is_sym_host_assoc (nl->sym, sym->ns)
12138               && !gfc_check_symbol_access (nl->sym))
12139             {
12140               gfc_error ("NAMELIST object '%s' was declared PRIVATE and "
12141                          "cannot be member of PUBLIC namelist '%s' at %L",
12142                          nl->sym->name, sym->name, &sym->declared_at);
12143               return FAILURE;
12144             }
12145
12146           /* Types with private components that came here by USE-association.  */
12147           if (nl->sym->ts.type == BT_DERIVED
12148               && derived_inaccessible (nl->sym->ts.u.derived))
12149             {
12150               gfc_error ("NAMELIST object '%s' has use-associated PRIVATE "
12151                          "components and cannot be member of namelist '%s' at %L",
12152                          nl->sym->name, sym->name, &sym->declared_at);
12153               return FAILURE;
12154             }
12155
12156           /* Types with private components that are defined in the same module.  */
12157           if (nl->sym->ts.type == BT_DERIVED
12158               && !is_sym_host_assoc (nl->sym->ts.u.derived, sym->ns)
12159               && nl->sym->ts.u.derived->attr.private_comp)
12160             {
12161               gfc_error ("NAMELIST object '%s' has PRIVATE components and "
12162                          "cannot be a member of PUBLIC namelist '%s' at %L",
12163                          nl->sym->name, sym->name, &sym->declared_at);
12164               return FAILURE;
12165             }
12166         }
12167     }
12168
12169
12170   /* 14.1.2 A module or internal procedure represent local entities
12171      of the same type as a namelist member and so are not allowed.  */
12172   for (nl = sym->namelist; nl; nl = nl->next)
12173     {
12174       if (nl->sym->ts.kind != 0 && nl->sym->attr.flavor == FL_VARIABLE)
12175         continue;
12176
12177       if (nl->sym->attr.function && nl->sym == nl->sym->result)
12178         if ((nl->sym == sym->ns->proc_name)
12179                ||
12180             (sym->ns->parent && nl->sym == sym->ns->parent->proc_name))
12181           continue;
12182
12183       nlsym = NULL;
12184       if (nl->sym && nl->sym->name)
12185         gfc_find_symbol (nl->sym->name, sym->ns, 1, &nlsym);
12186       if (nlsym && nlsym->attr.flavor == FL_PROCEDURE)
12187         {
12188           gfc_error ("PROCEDURE attribute conflicts with NAMELIST "
12189                      "attribute in '%s' at %L", nlsym->name,
12190                      &sym->declared_at);
12191           return FAILURE;
12192         }
12193     }
12194
12195   return SUCCESS;
12196 }
12197
12198
12199 static gfc_try
12200 resolve_fl_parameter (gfc_symbol *sym)
12201 {
12202   /* A parameter array's shape needs to be constant.  */
12203   if (sym->as != NULL
12204       && (sym->as->type == AS_DEFERRED
12205           || is_non_constant_shape_array (sym)))
12206     {
12207       gfc_error ("Parameter array '%s' at %L cannot be automatic "
12208                  "or of deferred shape", sym->name, &sym->declared_at);
12209       return FAILURE;
12210     }
12211
12212   /* Make sure a parameter that has been implicitly typed still
12213      matches the implicit type, since PARAMETER statements can precede
12214      IMPLICIT statements.  */
12215   if (sym->attr.implicit_type
12216       && !gfc_compare_types (&sym->ts, gfc_get_default_type (sym->name,
12217                                                              sym->ns)))
12218     {
12219       gfc_error ("Implicitly typed PARAMETER '%s' at %L doesn't match a "
12220                  "later IMPLICIT type", sym->name, &sym->declared_at);
12221       return FAILURE;
12222     }
12223
12224   /* Make sure the types of derived parameters are consistent.  This
12225      type checking is deferred until resolution because the type may
12226      refer to a derived type from the host.  */
12227   if (sym->ts.type == BT_DERIVED
12228       && !gfc_compare_types (&sym->ts, &sym->value->ts))
12229     {
12230       gfc_error ("Incompatible derived type in PARAMETER at %L",
12231                  &sym->value->where);
12232       return FAILURE;
12233     }
12234   return SUCCESS;
12235 }
12236
12237
12238 /* Do anything necessary to resolve a symbol.  Right now, we just
12239    assume that an otherwise unknown symbol is a variable.  This sort
12240    of thing commonly happens for symbols in module.  */
12241
12242 static void
12243 resolve_symbol (gfc_symbol *sym)
12244 {
12245   int check_constant, mp_flag;
12246   gfc_symtree *symtree;
12247   gfc_symtree *this_symtree;
12248   gfc_namespace *ns;
12249   gfc_component *c;
12250   symbol_attribute class_attr;
12251   gfc_array_spec *as;
12252
12253   if (sym->attr.flavor == FL_UNKNOWN)
12254     {
12255
12256     /* If we find that a flavorless symbol is an interface in one of the
12257        parent namespaces, find its symtree in this namespace, free the
12258        symbol and set the symtree to point to the interface symbol.  */
12259       for (ns = gfc_current_ns->parent; ns; ns = ns->parent)
12260         {
12261           symtree = gfc_find_symtree (ns->sym_root, sym->name);
12262           if (symtree && (symtree->n.sym->generic ||
12263                           (symtree->n.sym->attr.flavor == FL_PROCEDURE
12264                            && sym->ns->construct_entities)))
12265             {
12266               this_symtree = gfc_find_symtree (gfc_current_ns->sym_root,
12267                                                sym->name);
12268               gfc_release_symbol (sym);
12269               symtree->n.sym->refs++;
12270               this_symtree->n.sym = symtree->n.sym;
12271               return;
12272             }
12273         }
12274
12275       /* Otherwise give it a flavor according to such attributes as
12276          it has.  */
12277       if (sym->attr.external == 0 && sym->attr.intrinsic == 0)
12278         sym->attr.flavor = FL_VARIABLE;
12279       else
12280         {
12281           sym->attr.flavor = FL_PROCEDURE;
12282           if (sym->attr.dimension)
12283             sym->attr.function = 1;
12284         }
12285     }
12286
12287   if (sym->attr.external && sym->ts.type != BT_UNKNOWN && !sym->attr.function)
12288     gfc_add_function (&sym->attr, sym->name, &sym->declared_at);
12289
12290   if (sym->attr.procedure && sym->ts.interface
12291       && sym->attr.if_source != IFSRC_DECL
12292       && resolve_procedure_interface (sym) == FAILURE)
12293     return;
12294
12295   if (sym->attr.is_protected && !sym->attr.proc_pointer
12296       && (sym->attr.procedure || sym->attr.external))
12297     {
12298       if (sym->attr.external)
12299         gfc_error ("PROTECTED attribute conflicts with EXTERNAL attribute "
12300                    "at %L", &sym->declared_at);
12301       else
12302         gfc_error ("PROCEDURE attribute conflicts with PROTECTED attribute "
12303                    "at %L", &sym->declared_at);
12304
12305       return;
12306     }
12307
12308   if (sym->attr.flavor == FL_DERIVED && resolve_fl_derived (sym) == FAILURE)
12309     return;
12310
12311   /* Symbols that are module procedures with results (functions) have
12312      the types and array specification copied for type checking in
12313      procedures that call them, as well as for saving to a module
12314      file.  These symbols can't stand the scrutiny that their results
12315      can.  */
12316   mp_flag = (sym->result != NULL && sym->result != sym);
12317
12318   /* Make sure that the intrinsic is consistent with its internal
12319      representation. This needs to be done before assigning a default
12320      type to avoid spurious warnings.  */
12321   if (sym->attr.flavor != FL_MODULE && sym->attr.intrinsic
12322       && resolve_intrinsic (sym, &sym->declared_at) == FAILURE)
12323     return;
12324
12325   /* Resolve associate names.  */
12326   if (sym->assoc)
12327     resolve_assoc_var (sym, true);
12328
12329   /* Assign default type to symbols that need one and don't have one.  */
12330   if (sym->ts.type == BT_UNKNOWN)
12331     {
12332       if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER)
12333         {
12334           gfc_set_default_type (sym, 1, NULL);
12335         }
12336
12337       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
12338           && !sym->attr.function && !sym->attr.subroutine
12339           && gfc_get_default_type (sym->name, sym->ns)->type == BT_UNKNOWN)
12340         gfc_add_subroutine (&sym->attr, sym->name, &sym->declared_at);
12341
12342       if (sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12343         {
12344           /* The specific case of an external procedure should emit an error
12345              in the case that there is no implicit type.  */
12346           if (!mp_flag)
12347             gfc_set_default_type (sym, sym->attr.external, NULL);
12348           else
12349             {
12350               /* Result may be in another namespace.  */
12351               resolve_symbol (sym->result);
12352
12353               if (!sym->result->attr.proc_pointer)
12354                 {
12355                   sym->ts = sym->result->ts;
12356                   sym->as = gfc_copy_array_spec (sym->result->as);
12357                   sym->attr.dimension = sym->result->attr.dimension;
12358                   sym->attr.pointer = sym->result->attr.pointer;
12359                   sym->attr.allocatable = sym->result->attr.allocatable;
12360                   sym->attr.contiguous = sym->result->attr.contiguous;
12361                 }
12362             }
12363         }
12364     }
12365   else if (mp_flag && sym->attr.flavor == FL_PROCEDURE && sym->attr.function)
12366     gfc_resolve_array_spec (sym->result->as, false);
12367
12368   if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
12369     {
12370       as = CLASS_DATA (sym)->as;
12371       class_attr = CLASS_DATA (sym)->attr;
12372       class_attr.pointer = class_attr.class_pointer;
12373     }
12374   else
12375     {
12376       class_attr = sym->attr;
12377       as = sym->as;
12378     }
12379
12380   /* F2008, C530. */
12381   if (sym->attr.contiguous
12382       && (!class_attr.dimension
12383           || (as->type != AS_ASSUMED_SHAPE && !class_attr.pointer)))
12384     {
12385       gfc_error ("'%s' at %L has the CONTIGUOUS attribute but is not an "
12386                   "array pointer or an assumed-shape array", sym->name,
12387                   &sym->declared_at);
12388       return;
12389     }
12390
12391   /* Assumed size arrays and assumed shape arrays must be dummy
12392      arguments.  Array-spec's of implied-shape should have been resolved to
12393      AS_EXPLICIT already.  */
12394
12395   if (as)
12396     {
12397       gcc_assert (as->type != AS_IMPLIED_SHAPE);
12398       if (((as->type == AS_ASSUMED_SIZE && !as->cp_was_assumed)
12399            || as->type == AS_ASSUMED_SHAPE)
12400           && sym->attr.dummy == 0)
12401         {
12402           if (as->type == AS_ASSUMED_SIZE)
12403             gfc_error ("Assumed size array at %L must be a dummy argument",
12404                        &sym->declared_at);
12405           else
12406             gfc_error ("Assumed shape array at %L must be a dummy argument",
12407                        &sym->declared_at);
12408           return;
12409         }
12410     }
12411
12412   /* Make sure symbols with known intent or optional are really dummy
12413      variable.  Because of ENTRY statement, this has to be deferred
12414      until resolution time.  */
12415
12416   if (!sym->attr.dummy
12417       && (sym->attr.optional || sym->attr.intent != INTENT_UNKNOWN))
12418     {
12419       gfc_error ("Symbol at %L is not a DUMMY variable", &sym->declared_at);
12420       return;
12421     }
12422
12423   if (sym->attr.value && !sym->attr.dummy)
12424     {
12425       gfc_error ("'%s' at %L cannot have the VALUE attribute because "
12426                  "it is not a dummy argument", sym->name, &sym->declared_at);
12427       return;
12428     }
12429
12430   if (sym->attr.value && sym->ts.type == BT_CHARACTER)
12431     {
12432       gfc_charlen *cl = sym->ts.u.cl;
12433       if (!cl || !cl->length || cl->length->expr_type != EXPR_CONSTANT)
12434         {
12435           gfc_error ("Character dummy variable '%s' at %L with VALUE "
12436                      "attribute must have constant length",
12437                      sym->name, &sym->declared_at);
12438           return;
12439         }
12440
12441       if (sym->ts.is_c_interop
12442           && mpz_cmp_si (cl->length->value.integer, 1) != 0)
12443         {
12444           gfc_error ("C interoperable character dummy variable '%s' at %L "
12445                      "with VALUE attribute must have length one",
12446                      sym->name, &sym->declared_at);
12447           return;
12448         }
12449     }
12450
12451   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
12452       && sym->ts.u.derived->attr.generic)
12453     {
12454       sym->ts.u.derived = gfc_find_dt_in_generic (sym->ts.u.derived);
12455       if (!sym->ts.u.derived)
12456         {
12457           gfc_error ("The derived type '%s' at %L is of type '%s', "
12458                      "which has not been defined", sym->name,
12459                      &sym->declared_at, sym->ts.u.derived->name);
12460           sym->ts.type = BT_UNKNOWN;
12461           return;
12462         }
12463     }
12464
12465   /* If the symbol is marked as bind(c), verify it's type and kind.  Do not
12466      do this for something that was implicitly typed because that is handled
12467      in gfc_set_default_type.  Handle dummy arguments and procedure
12468      definitions separately.  Also, anything that is use associated is not
12469      handled here but instead is handled in the module it is declared in.
12470      Finally, derived type definitions are allowed to be BIND(C) since that
12471      only implies that they're interoperable, and they are checked fully for
12472      interoperability when a variable is declared of that type.  */
12473   if (sym->attr.is_bind_c && sym->attr.implicit_type == 0 &&
12474       sym->attr.use_assoc == 0 && sym->attr.dummy == 0 &&
12475       sym->attr.flavor != FL_PROCEDURE && sym->attr.flavor != FL_DERIVED)
12476     {
12477       gfc_try t = SUCCESS;
12478
12479       /* First, make sure the variable is declared at the
12480          module-level scope (J3/04-007, Section 15.3).  */
12481       if (sym->ns->proc_name->attr.flavor != FL_MODULE &&
12482           sym->attr.in_common == 0)
12483         {
12484           gfc_error ("Variable '%s' at %L cannot be BIND(C) because it "
12485                      "is neither a COMMON block nor declared at the "
12486                      "module level scope", sym->name, &(sym->declared_at));
12487           t = FAILURE;
12488         }
12489       else if (sym->common_head != NULL)
12490         {
12491           t = verify_com_block_vars_c_interop (sym->common_head);
12492         }
12493       else
12494         {
12495           /* If type() declaration, we need to verify that the components
12496              of the given type are all C interoperable, etc.  */
12497           if (sym->ts.type == BT_DERIVED &&
12498               sym->ts.u.derived->attr.is_c_interop != 1)
12499             {
12500               /* Make sure the user marked the derived type as BIND(C).  If
12501                  not, call the verify routine.  This could print an error
12502                  for the derived type more than once if multiple variables
12503                  of that type are declared.  */
12504               if (sym->ts.u.derived->attr.is_bind_c != 1)
12505                 verify_bind_c_derived_type (sym->ts.u.derived);
12506               t = FAILURE;
12507             }
12508
12509           /* Verify the variable itself as C interoperable if it
12510              is BIND(C).  It is not possible for this to succeed if
12511              the verify_bind_c_derived_type failed, so don't have to handle
12512              any error returned by verify_bind_c_derived_type.  */
12513           t = verify_bind_c_sym (sym, &(sym->ts), sym->attr.in_common,
12514                                  sym->common_block);
12515         }
12516
12517       if (t == FAILURE)
12518         {
12519           /* clear the is_bind_c flag to prevent reporting errors more than
12520              once if something failed.  */
12521           sym->attr.is_bind_c = 0;
12522           return;
12523         }
12524     }
12525
12526   /* If a derived type symbol has reached this point, without its
12527      type being declared, we have an error.  Notice that most
12528      conditions that produce undefined derived types have already
12529      been dealt with.  However, the likes of:
12530      implicit type(t) (t) ..... call foo (t) will get us here if
12531      the type is not declared in the scope of the implicit
12532      statement. Change the type to BT_UNKNOWN, both because it is so
12533      and to prevent an ICE.  */
12534   if (sym->ts.type == BT_DERIVED && !sym->attr.is_iso_c
12535       && sym->ts.u.derived->components == NULL
12536       && !sym->ts.u.derived->attr.zero_comp)
12537     {
12538       gfc_error ("The derived type '%s' at %L is of type '%s', "
12539                  "which has not been defined", sym->name,
12540                   &sym->declared_at, sym->ts.u.derived->name);
12541       sym->ts.type = BT_UNKNOWN;
12542       return;
12543     }
12544
12545   /* Make sure that the derived type has been resolved and that the
12546      derived type is visible in the symbol's namespace, if it is a
12547      module function and is not PRIVATE.  */
12548   if (sym->ts.type == BT_DERIVED
12549         && sym->ts.u.derived->attr.use_assoc
12550         && sym->ns->proc_name
12551         && sym->ns->proc_name->attr.flavor == FL_MODULE
12552         && resolve_fl_derived (sym->ts.u.derived) == FAILURE)
12553     return;
12554
12555   /* Unless the derived-type declaration is use associated, Fortran 95
12556      does not allow public entries of private derived types.
12557      See 4.4.1 (F95) and 4.5.1.1 (F2003); and related interpretation
12558      161 in 95-006r3.  */
12559   if (sym->ts.type == BT_DERIVED
12560       && sym->ns->proc_name && sym->ns->proc_name->attr.flavor == FL_MODULE
12561       && !sym->ts.u.derived->attr.use_assoc
12562       && gfc_check_symbol_access (sym)
12563       && !gfc_check_symbol_access (sym->ts.u.derived)
12564       && gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC %s '%s' at %L "
12565                          "of PRIVATE derived type '%s'",
12566                          (sym->attr.flavor == FL_PARAMETER) ? "parameter"
12567                          : "variable", sym->name, &sym->declared_at,
12568                          sym->ts.u.derived->name) == FAILURE)
12569     return;
12570
12571   /* F2008, C1302.  */
12572   if (sym->ts.type == BT_DERIVED
12573       && ((sym->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
12574            && sym->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
12575           || sym->ts.u.derived->attr.lock_comp)
12576       && !sym->attr.codimension && !sym->ts.u.derived->attr.coarray_comp)
12577     {
12578       gfc_error ("Variable %s at %L of type LOCK_TYPE or with subcomponent of "
12579                  "type LOCK_TYPE must be a coarray", sym->name,
12580                  &sym->declared_at);
12581       return;
12582     }
12583
12584   /* An assumed-size array with INTENT(OUT) shall not be of a type for which
12585      default initialization is defined (5.1.2.4.4).  */
12586   if (sym->ts.type == BT_DERIVED
12587       && sym->attr.dummy
12588       && sym->attr.intent == INTENT_OUT
12589       && sym->as
12590       && sym->as->type == AS_ASSUMED_SIZE)
12591     {
12592       for (c = sym->ts.u.derived->components; c; c = c->next)
12593         {
12594           if (c->initializer)
12595             {
12596               gfc_error ("The INTENT(OUT) dummy argument '%s' at %L is "
12597                          "ASSUMED SIZE and so cannot have a default initializer",
12598                          sym->name, &sym->declared_at);
12599               return;
12600             }
12601         }
12602     }
12603
12604   /* F2008, C542.  */
12605   if (sym->ts.type == BT_DERIVED && sym->attr.dummy
12606       && sym->attr.intent == INTENT_OUT && sym->attr.lock_comp)
12607     {
12608       gfc_error ("Dummy argument '%s' at %L of LOCK_TYPE shall not be "
12609                  "INTENT(OUT)", sym->name, &sym->declared_at);
12610       return;
12611     }
12612
12613   /* F2008, C525.  */
12614   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12615          || (sym->ts.type == BT_CLASS && sym->attr.class_ok
12616              && CLASS_DATA (sym)->attr.coarray_comp))
12617        || class_attr.codimension)
12618       && (sym->attr.result || sym->result == sym))
12619     {
12620       gfc_error ("Function result '%s' at %L shall not be a coarray or have "
12621                  "a coarray component", sym->name, &sym->declared_at);
12622       return;
12623     }
12624
12625   /* F2008, C524.  */
12626   if (sym->attr.codimension && sym->ts.type == BT_DERIVED
12627       && sym->ts.u.derived->ts.is_iso_c)
12628     {
12629       gfc_error ("Variable '%s' at %L of TYPE(C_PTR) or TYPE(C_FUNPTR) "
12630                  "shall not be a coarray", sym->name, &sym->declared_at);
12631       return;
12632     }
12633
12634   /* F2008, C525.  */
12635   if (((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12636         || (sym->ts.type == BT_CLASS && sym->attr.class_ok
12637             && CLASS_DATA (sym)->attr.coarray_comp))
12638       && (class_attr.codimension || class_attr.pointer || class_attr.dimension
12639           || class_attr.allocatable))
12640     {
12641       gfc_error ("Variable '%s' at %L with coarray component "
12642                  "shall be a nonpointer, nonallocatable scalar",
12643                  sym->name, &sym->declared_at);
12644       return;
12645     }
12646
12647   /* F2008, C526.  The function-result case was handled above.  */
12648   if (class_attr.codimension
12649       && !(class_attr.allocatable || sym->attr.dummy || sym->attr.save
12650            || sym->attr.select_type_temporary
12651            || sym->ns->save_all
12652            || sym->ns->proc_name->attr.flavor == FL_MODULE
12653            || sym->ns->proc_name->attr.is_main_program
12654            || sym->attr.function || sym->attr.result || sym->attr.use_assoc))
12655     {
12656       gfc_error ("Variable '%s' at %L is a coarray and is not ALLOCATABLE, SAVE "
12657                  "nor a dummy argument", sym->name, &sym->declared_at);
12658       return;
12659     }
12660   /* F2008, C528.  */
12661   else if (class_attr.codimension && !sym->attr.select_type_temporary
12662            && !class_attr.allocatable && as && as->cotype == AS_DEFERRED)
12663     {
12664       gfc_error ("Coarray variable '%s' at %L shall not have codimensions with "
12665                  "deferred shape", sym->name, &sym->declared_at);
12666       return;
12667     }
12668   else if (class_attr.codimension && class_attr.allocatable && as
12669            && (as->cotype != AS_DEFERRED || as->type != AS_DEFERRED))
12670     {
12671       gfc_error ("Allocatable coarray variable '%s' at %L must have "
12672                  "deferred shape", sym->name, &sym->declared_at);
12673       return;
12674     }
12675
12676   /* F2008, C541.  */
12677   if ((((sym->ts.type == BT_DERIVED && sym->ts.u.derived->attr.coarray_comp)
12678         || (sym->ts.type == BT_CLASS && sym->attr.class_ok
12679             && CLASS_DATA (sym)->attr.coarray_comp))
12680        || (class_attr.codimension && class_attr.allocatable))
12681       && sym->attr.dummy && sym->attr.intent == INTENT_OUT)
12682     {
12683       gfc_error ("Variable '%s' at %L is INTENT(OUT) and can thus not be an "
12684                  "allocatable coarray or have coarray components",
12685                  sym->name, &sym->declared_at);
12686       return;
12687     }
12688
12689   if (class_attr.codimension && sym->attr.dummy
12690       && sym->ns->proc_name && sym->ns->proc_name->attr.is_bind_c)
12691     {
12692       gfc_error ("Coarray dummy variable '%s' at %L not allowed in BIND(C) "
12693                  "procedure '%s'", sym->name, &sym->declared_at,
12694                  sym->ns->proc_name->name);
12695       return;
12696     }
12697
12698   switch (sym->attr.flavor)
12699     {
12700     case FL_VARIABLE:
12701       if (resolve_fl_variable (sym, mp_flag) == FAILURE)
12702         return;
12703       break;
12704
12705     case FL_PROCEDURE:
12706       if (resolve_fl_procedure (sym, mp_flag) == FAILURE)
12707         return;
12708       break;
12709
12710     case FL_NAMELIST:
12711       if (resolve_fl_namelist (sym) == FAILURE)
12712         return;
12713       break;
12714
12715     case FL_PARAMETER:
12716       if (resolve_fl_parameter (sym) == FAILURE)
12717         return;
12718       break;
12719
12720     default:
12721       break;
12722     }
12723
12724   /* Resolve array specifier. Check as well some constraints
12725      on COMMON blocks.  */
12726
12727   check_constant = sym->attr.in_common && !sym->attr.pointer;
12728
12729   /* Set the formal_arg_flag so that check_conflict will not throw
12730      an error for host associated variables in the specification
12731      expression for an array_valued function.  */
12732   if (sym->attr.function && sym->as)
12733     formal_arg_flag = 1;
12734
12735   gfc_resolve_array_spec (sym->as, check_constant);
12736
12737   formal_arg_flag = 0;
12738
12739   /* Resolve formal namespaces.  */
12740   if (sym->formal_ns && sym->formal_ns != gfc_current_ns
12741       && !sym->attr.contained && !sym->attr.intrinsic)
12742     gfc_resolve (sym->formal_ns);
12743
12744   /* Make sure the formal namespace is present.  */
12745   if (sym->formal && !sym->formal_ns)
12746     {
12747       gfc_formal_arglist *formal = sym->formal;
12748       while (formal && !formal->sym)
12749         formal = formal->next;
12750
12751       if (formal)
12752         {
12753           sym->formal_ns = formal->sym->ns;
12754           sym->formal_ns->refs++;
12755         }
12756     }
12757
12758   /* Check threadprivate restrictions.  */
12759   if (sym->attr.threadprivate && !sym->attr.save && !sym->ns->save_all
12760       && (!sym->attr.in_common
12761           && sym->module == NULL
12762           && (sym->ns->proc_name == NULL
12763               || sym->ns->proc_name->attr.flavor != FL_MODULE)))
12764     gfc_error ("Threadprivate at %L isn't SAVEd", &sym->declared_at);
12765
12766   /* If we have come this far we can apply default-initializers, as
12767      described in 14.7.5, to those variables that have not already
12768      been assigned one.  */
12769   if (sym->ts.type == BT_DERIVED
12770       && sym->ns == gfc_current_ns
12771       && !sym->value
12772       && !sym->attr.allocatable
12773       && !sym->attr.alloc_comp)
12774     {
12775       symbol_attribute *a = &sym->attr;
12776
12777       if ((!a->save && !a->dummy && !a->pointer
12778            && !a->in_common && !a->use_assoc
12779            && (a->referenced || a->result)
12780            && !(a->function && sym != sym->result))
12781           || (a->dummy && a->intent == INTENT_OUT && !a->pointer))
12782         apply_default_init (sym);
12783     }
12784
12785   if (sym->ts.type == BT_CLASS && sym->ns == gfc_current_ns
12786       && sym->attr.dummy && sym->attr.intent == INTENT_OUT
12787       && !CLASS_DATA (sym)->attr.class_pointer
12788       && !CLASS_DATA (sym)->attr.allocatable)
12789     apply_default_init (sym);
12790
12791   /* If this symbol has a type-spec, check it.  */
12792   if (sym->attr.flavor == FL_VARIABLE || sym->attr.flavor == FL_PARAMETER
12793       || (sym->attr.flavor == FL_PROCEDURE && sym->attr.function))
12794     if (resolve_typespec_used (&sym->ts, &sym->declared_at, sym->name)
12795           == FAILURE)
12796       return;
12797 }
12798
12799
12800 /************* Resolve DATA statements *************/
12801
12802 static struct
12803 {
12804   gfc_data_value *vnode;
12805   mpz_t left;
12806 }
12807 values;
12808
12809
12810 /* Advance the values structure to point to the next value in the data list.  */
12811
12812 static gfc_try
12813 next_data_value (void)
12814 {
12815   while (mpz_cmp_ui (values.left, 0) == 0)
12816     {
12817
12818       if (values.vnode->next == NULL)
12819         return FAILURE;
12820
12821       values.vnode = values.vnode->next;
12822       mpz_set (values.left, values.vnode->repeat);
12823     }
12824
12825   return SUCCESS;
12826 }
12827
12828
12829 static gfc_try
12830 check_data_variable (gfc_data_variable *var, locus *where)
12831 {
12832   gfc_expr *e;
12833   mpz_t size;
12834   mpz_t offset;
12835   gfc_try t;
12836   ar_type mark = AR_UNKNOWN;
12837   int i;
12838   mpz_t section_index[GFC_MAX_DIMENSIONS];
12839   gfc_ref *ref;
12840   gfc_array_ref *ar;
12841   gfc_symbol *sym;
12842   int has_pointer;
12843
12844   if (gfc_resolve_expr (var->expr) == FAILURE)
12845     return FAILURE;
12846
12847   ar = NULL;
12848   mpz_init_set_si (offset, 0);
12849   e = var->expr;
12850
12851   if (e->expr_type != EXPR_VARIABLE)
12852     gfc_internal_error ("check_data_variable(): Bad expression");
12853
12854   sym = e->symtree->n.sym;
12855
12856   if (sym->ns->is_block_data && !sym->attr.in_common)
12857     {
12858       gfc_error ("BLOCK DATA element '%s' at %L must be in COMMON",
12859                  sym->name, &sym->declared_at);
12860     }
12861
12862   if (e->ref == NULL && sym->as)
12863     {
12864       gfc_error ("DATA array '%s' at %L must be specified in a previous"
12865                  " declaration", sym->name, where);
12866       return FAILURE;
12867     }
12868
12869   has_pointer = sym->attr.pointer;
12870
12871   if (gfc_is_coindexed (e))
12872     {
12873       gfc_error ("DATA element '%s' at %L cannot have a coindex", sym->name,
12874                  where);
12875       return FAILURE;
12876     }
12877
12878   for (ref = e->ref; ref; ref = ref->next)
12879     {
12880       if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
12881         has_pointer = 1;
12882
12883       if (has_pointer
12884             && ref->type == REF_ARRAY
12885             && ref->u.ar.type != AR_FULL)
12886           {
12887             gfc_error ("DATA element '%s' at %L is a pointer and so must "
12888                         "be a full array", sym->name, where);
12889             return FAILURE;
12890           }
12891     }
12892
12893   if (e->rank == 0 || has_pointer)
12894     {
12895       mpz_init_set_ui (size, 1);
12896       ref = NULL;
12897     }
12898   else
12899     {
12900       ref = e->ref;
12901
12902       /* Find the array section reference.  */
12903       for (ref = e->ref; ref; ref = ref->next)
12904         {
12905           if (ref->type != REF_ARRAY)
12906             continue;
12907           if (ref->u.ar.type == AR_ELEMENT)
12908             continue;
12909           break;
12910         }
12911       gcc_assert (ref);
12912
12913       /* Set marks according to the reference pattern.  */
12914       switch (ref->u.ar.type)
12915         {
12916         case AR_FULL:
12917           mark = AR_FULL;
12918           break;
12919
12920         case AR_SECTION:
12921           ar = &ref->u.ar;
12922           /* Get the start position of array section.  */
12923           gfc_get_section_index (ar, section_index, &offset);
12924           mark = AR_SECTION;
12925           break;
12926
12927         default:
12928           gcc_unreachable ();
12929         }
12930
12931       if (gfc_array_size (e, &size) == FAILURE)
12932         {
12933           gfc_error ("Nonconstant array section at %L in DATA statement",
12934                      &e->where);
12935           mpz_clear (offset);
12936           return FAILURE;
12937         }
12938     }
12939
12940   t = SUCCESS;
12941
12942   while (mpz_cmp_ui (size, 0) > 0)
12943     {
12944       if (next_data_value () == FAILURE)
12945         {
12946           gfc_error ("DATA statement at %L has more variables than values",
12947                      where);
12948           t = FAILURE;
12949           break;
12950         }
12951
12952       t = gfc_check_assign (var->expr, values.vnode->expr, 0);
12953       if (t == FAILURE)
12954         break;
12955
12956       /* If we have more than one element left in the repeat count,
12957          and we have more than one element left in the target variable,
12958          then create a range assignment.  */
12959       /* FIXME: Only done for full arrays for now, since array sections
12960          seem tricky.  */
12961       if (mark == AR_FULL && ref && ref->next == NULL
12962           && mpz_cmp_ui (values.left, 1) > 0 && mpz_cmp_ui (size, 1) > 0)
12963         {
12964           mpz_t range;
12965
12966           if (mpz_cmp (size, values.left) >= 0)
12967             {
12968               mpz_init_set (range, values.left);
12969               mpz_sub (size, size, values.left);
12970               mpz_set_ui (values.left, 0);
12971             }
12972           else
12973             {
12974               mpz_init_set (range, size);
12975               mpz_sub (values.left, values.left, size);
12976               mpz_set_ui (size, 0);
12977             }
12978
12979           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12980                                      offset, &range);
12981
12982           mpz_add (offset, offset, range);
12983           mpz_clear (range);
12984
12985           if (t == FAILURE)
12986             break;
12987         }
12988
12989       /* Assign initial value to symbol.  */
12990       else
12991         {
12992           mpz_sub_ui (values.left, values.left, 1);
12993           mpz_sub_ui (size, size, 1);
12994
12995           t = gfc_assign_data_value (var->expr, values.vnode->expr,
12996                                      offset, NULL);
12997           if (t == FAILURE)
12998             break;
12999
13000           if (mark == AR_FULL)
13001             mpz_add_ui (offset, offset, 1);
13002
13003           /* Modify the array section indexes and recalculate the offset
13004              for next element.  */
13005           else if (mark == AR_SECTION)
13006             gfc_advance_section (section_index, ar, &offset);
13007         }
13008     }
13009
13010   if (mark == AR_SECTION)
13011     {
13012       for (i = 0; i < ar->dimen; i++)
13013         mpz_clear (section_index[i]);
13014     }
13015
13016   mpz_clear (size);
13017   mpz_clear (offset);
13018
13019   return t;
13020 }
13021
13022
13023 static gfc_try traverse_data_var (gfc_data_variable *, locus *);
13024
13025 /* Iterate over a list of elements in a DATA statement.  */
13026
13027 static gfc_try
13028 traverse_data_list (gfc_data_variable *var, locus *where)
13029 {
13030   mpz_t trip;
13031   iterator_stack frame;
13032   gfc_expr *e, *start, *end, *step;
13033   gfc_try retval = SUCCESS;
13034
13035   mpz_init (frame.value);
13036   mpz_init (trip);
13037
13038   start = gfc_copy_expr (var->iter.start);
13039   end = gfc_copy_expr (var->iter.end);
13040   step = gfc_copy_expr (var->iter.step);
13041
13042   if (gfc_simplify_expr (start, 1) == FAILURE
13043       || start->expr_type != EXPR_CONSTANT)
13044     {
13045       gfc_error ("start of implied-do loop at %L could not be "
13046                  "simplified to a constant value", &start->where);
13047       retval = FAILURE;
13048       goto cleanup;
13049     }
13050   if (gfc_simplify_expr (end, 1) == FAILURE
13051       || end->expr_type != EXPR_CONSTANT)
13052     {
13053       gfc_error ("end of implied-do loop at %L could not be "
13054                  "simplified to a constant value", &start->where);
13055       retval = FAILURE;
13056       goto cleanup;
13057     }
13058   if (gfc_simplify_expr (step, 1) == FAILURE
13059       || step->expr_type != EXPR_CONSTANT)
13060     {
13061       gfc_error ("step of implied-do loop at %L could not be "
13062                  "simplified to a constant value", &start->where);
13063       retval = FAILURE;
13064       goto cleanup;
13065     }
13066
13067   mpz_set (trip, end->value.integer);
13068   mpz_sub (trip, trip, start->value.integer);
13069   mpz_add (trip, trip, step->value.integer);
13070
13071   mpz_div (trip, trip, step->value.integer);
13072
13073   mpz_set (frame.value, start->value.integer);
13074
13075   frame.prev = iter_stack;
13076   frame.variable = var->iter.var->symtree;
13077   iter_stack = &frame;
13078
13079   while (mpz_cmp_ui (trip, 0) > 0)
13080     {
13081       if (traverse_data_var (var->list, where) == FAILURE)
13082         {
13083           retval = FAILURE;
13084           goto cleanup;
13085         }
13086
13087       e = gfc_copy_expr (var->expr);
13088       if (gfc_simplify_expr (e, 1) == FAILURE)
13089         {
13090           gfc_free_expr (e);
13091           retval = FAILURE;
13092           goto cleanup;
13093         }
13094
13095       mpz_add (frame.value, frame.value, step->value.integer);
13096
13097       mpz_sub_ui (trip, trip, 1);
13098     }
13099
13100 cleanup:
13101   mpz_clear (frame.value);
13102   mpz_clear (trip);
13103
13104   gfc_free_expr (start);
13105   gfc_free_expr (end);
13106   gfc_free_expr (step);
13107
13108   iter_stack = frame.prev;
13109   return retval;
13110 }
13111
13112
13113 /* Type resolve variables in the variable list of a DATA statement.  */
13114
13115 static gfc_try
13116 traverse_data_var (gfc_data_variable *var, locus *where)
13117 {
13118   gfc_try t;
13119
13120   for (; var; var = var->next)
13121     {
13122       if (var->expr == NULL)
13123         t = traverse_data_list (var, where);
13124       else
13125         t = check_data_variable (var, where);
13126
13127       if (t == FAILURE)
13128         return FAILURE;
13129     }
13130
13131   return SUCCESS;
13132 }
13133
13134
13135 /* Resolve the expressions and iterators associated with a data statement.
13136    This is separate from the assignment checking because data lists should
13137    only be resolved once.  */
13138
13139 static gfc_try
13140 resolve_data_variables (gfc_data_variable *d)
13141 {
13142   for (; d; d = d->next)
13143     {
13144       if (d->list == NULL)
13145         {
13146           if (gfc_resolve_expr (d->expr) == FAILURE)
13147             return FAILURE;
13148         }
13149       else
13150         {
13151           if (gfc_resolve_iterator (&d->iter, false) == FAILURE)
13152             return FAILURE;
13153
13154           if (resolve_data_variables (d->list) == FAILURE)
13155             return FAILURE;
13156         }
13157     }
13158
13159   return SUCCESS;
13160 }
13161
13162
13163 /* Resolve a single DATA statement.  We implement this by storing a pointer to
13164    the value list into static variables, and then recursively traversing the
13165    variables list, expanding iterators and such.  */
13166
13167 static void
13168 resolve_data (gfc_data *d)
13169 {
13170
13171   if (resolve_data_variables (d->var) == FAILURE)
13172     return;
13173
13174   values.vnode = d->value;
13175   if (d->value == NULL)
13176     mpz_set_ui (values.left, 0);
13177   else
13178     mpz_set (values.left, d->value->repeat);
13179
13180   if (traverse_data_var (d->var, &d->where) == FAILURE)
13181     return;
13182
13183   /* At this point, we better not have any values left.  */
13184
13185   if (next_data_value () == SUCCESS)
13186     gfc_error ("DATA statement at %L has more values than variables",
13187                &d->where);
13188 }
13189
13190
13191 /* 12.6 Constraint: In a pure subprogram any variable which is in common or
13192    accessed by host or use association, is a dummy argument to a pure function,
13193    is a dummy argument with INTENT (IN) to a pure subroutine, or an object that
13194    is storage associated with any such variable, shall not be used in the
13195    following contexts: (clients of this function).  */
13196
13197 /* Determines if a variable is not 'pure', i.e., not assignable within a pure
13198    procedure.  Returns zero if assignment is OK, nonzero if there is a
13199    problem.  */
13200 int
13201 gfc_impure_variable (gfc_symbol *sym)
13202 {
13203   gfc_symbol *proc;
13204   gfc_namespace *ns;
13205
13206   if (sym->attr.use_assoc || sym->attr.in_common)
13207     return 1;
13208
13209   /* Check if the symbol's ns is inside the pure procedure.  */
13210   for (ns = gfc_current_ns; ns; ns = ns->parent)
13211     {
13212       if (ns == sym->ns)
13213         break;
13214       if (ns->proc_name->attr.flavor == FL_PROCEDURE && !sym->attr.function)
13215         return 1;
13216     }
13217
13218   proc = sym->ns->proc_name;
13219   if (sym->attr.dummy
13220       && ((proc->attr.subroutine && sym->attr.intent == INTENT_IN)
13221           || proc->attr.function))
13222     return 1;
13223
13224   /* TODO: Sort out what can be storage associated, if anything, and include
13225      it here.  In principle equivalences should be scanned but it does not
13226      seem to be possible to storage associate an impure variable this way.  */
13227   return 0;
13228 }
13229
13230
13231 /* Test whether a symbol is pure or not.  For a NULL pointer, checks if the
13232    current namespace is inside a pure procedure.  */
13233
13234 int
13235 gfc_pure (gfc_symbol *sym)
13236 {
13237   symbol_attribute attr;
13238   gfc_namespace *ns;
13239
13240   if (sym == NULL)
13241     {
13242       /* Check if the current namespace or one of its parents
13243         belongs to a pure procedure.  */
13244       for (ns = gfc_current_ns; ns; ns = ns->parent)
13245         {
13246           sym = ns->proc_name;
13247           if (sym == NULL)
13248             return 0;
13249           attr = sym->attr;
13250           if (attr.flavor == FL_PROCEDURE && attr.pure)
13251             return 1;
13252         }
13253       return 0;
13254     }
13255
13256   attr = sym->attr;
13257
13258   return attr.flavor == FL_PROCEDURE && attr.pure;
13259 }
13260
13261
13262 /* Test whether a symbol is implicitly pure or not.  For a NULL pointer,
13263    checks if the current namespace is implicitly pure.  Note that this
13264    function returns false for a PURE procedure.  */
13265
13266 int
13267 gfc_implicit_pure (gfc_symbol *sym)
13268 {
13269   gfc_namespace *ns;
13270
13271   if (sym == NULL)
13272     {
13273       /* Check if the current procedure is implicit_pure.  Walk up
13274          the procedure list until we find a procedure.  */
13275       for (ns = gfc_current_ns; ns; ns = ns->parent)
13276         {
13277           sym = ns->proc_name;
13278           if (sym == NULL)
13279             return 0;
13280
13281           if (sym->attr.flavor == FL_PROCEDURE)
13282             break;
13283         }
13284     }
13285
13286   return sym->attr.flavor == FL_PROCEDURE && sym->attr.implicit_pure
13287     && !sym->attr.pure;
13288 }
13289
13290
13291 /* Test whether the current procedure is elemental or not.  */
13292
13293 int
13294 gfc_elemental (gfc_symbol *sym)
13295 {
13296   symbol_attribute attr;
13297
13298   if (sym == NULL)
13299     sym = gfc_current_ns->proc_name;
13300   if (sym == NULL)
13301     return 0;
13302   attr = sym->attr;
13303
13304   return attr.flavor == FL_PROCEDURE && attr.elemental;
13305 }
13306
13307
13308 /* Warn about unused labels.  */
13309
13310 static void
13311 warn_unused_fortran_label (gfc_st_label *label)
13312 {
13313   if (label == NULL)
13314     return;
13315
13316   warn_unused_fortran_label (label->left);
13317
13318   if (label->defined == ST_LABEL_UNKNOWN)
13319     return;
13320
13321   switch (label->referenced)
13322     {
13323     case ST_LABEL_UNKNOWN:
13324       gfc_warning ("Label %d at %L defined but not used", label->value,
13325                    &label->where);
13326       break;
13327
13328     case ST_LABEL_BAD_TARGET:
13329       gfc_warning ("Label %d at %L defined but cannot be used",
13330                    label->value, &label->where);
13331       break;
13332
13333     default:
13334       break;
13335     }
13336
13337   warn_unused_fortran_label (label->right);
13338 }
13339
13340
13341 /* Returns the sequence type of a symbol or sequence.  */
13342
13343 static seq_type
13344 sequence_type (gfc_typespec ts)
13345 {
13346   seq_type result;
13347   gfc_component *c;
13348
13349   switch (ts.type)
13350   {
13351     case BT_DERIVED:
13352
13353       if (ts.u.derived->components == NULL)
13354         return SEQ_NONDEFAULT;
13355
13356       result = sequence_type (ts.u.derived->components->ts);
13357       for (c = ts.u.derived->components->next; c; c = c->next)
13358         if (sequence_type (c->ts) != result)
13359           return SEQ_MIXED;
13360
13361       return result;
13362
13363     case BT_CHARACTER:
13364       if (ts.kind != gfc_default_character_kind)
13365           return SEQ_NONDEFAULT;
13366
13367       return SEQ_CHARACTER;
13368
13369     case BT_INTEGER:
13370       if (ts.kind != gfc_default_integer_kind)
13371           return SEQ_NONDEFAULT;
13372
13373       return SEQ_NUMERIC;
13374
13375     case BT_REAL:
13376       if (!(ts.kind == gfc_default_real_kind
13377             || ts.kind == gfc_default_double_kind))
13378           return SEQ_NONDEFAULT;
13379
13380       return SEQ_NUMERIC;
13381
13382     case BT_COMPLEX:
13383       if (ts.kind != gfc_default_complex_kind)
13384           return SEQ_NONDEFAULT;
13385
13386       return SEQ_NUMERIC;
13387
13388     case BT_LOGICAL:
13389       if (ts.kind != gfc_default_logical_kind)
13390           return SEQ_NONDEFAULT;
13391
13392       return SEQ_NUMERIC;
13393
13394     default:
13395       return SEQ_NONDEFAULT;
13396   }
13397 }
13398
13399
13400 /* Resolve derived type EQUIVALENCE object.  */
13401
13402 static gfc_try
13403 resolve_equivalence_derived (gfc_symbol *derived, gfc_symbol *sym, gfc_expr *e)
13404 {
13405   gfc_component *c = derived->components;
13406
13407   if (!derived)
13408     return SUCCESS;
13409
13410   /* Shall not be an object of nonsequence derived type.  */
13411   if (!derived->attr.sequence)
13412     {
13413       gfc_error ("Derived type variable '%s' at %L must have SEQUENCE "
13414                  "attribute to be an EQUIVALENCE object", sym->name,
13415                  &e->where);
13416       return FAILURE;
13417     }
13418
13419   /* Shall not have allocatable components.  */
13420   if (derived->attr.alloc_comp)
13421     {
13422       gfc_error ("Derived type variable '%s' at %L cannot have ALLOCATABLE "
13423                  "components to be an EQUIVALENCE object",sym->name,
13424                  &e->where);
13425       return FAILURE;
13426     }
13427
13428   if (sym->attr.in_common && gfc_has_default_initializer (sym->ts.u.derived))
13429     {
13430       gfc_error ("Derived type variable '%s' at %L with default "
13431                  "initialization cannot be in EQUIVALENCE with a variable "
13432                  "in COMMON", sym->name, &e->where);
13433       return FAILURE;
13434     }
13435
13436   for (; c ; c = c->next)
13437     {
13438       if (c->ts.type == BT_DERIVED
13439           && (resolve_equivalence_derived (c->ts.u.derived, sym, e) == FAILURE))
13440         return FAILURE;
13441
13442       /* Shall not be an object of sequence derived type containing a pointer
13443          in the structure.  */
13444       if (c->attr.pointer)
13445         {
13446           gfc_error ("Derived type variable '%s' at %L with pointer "
13447                      "component(s) cannot be an EQUIVALENCE object",
13448                      sym->name, &e->where);
13449           return FAILURE;
13450         }
13451     }
13452   return SUCCESS;
13453 }
13454
13455
13456 /* Resolve equivalence object.
13457    An EQUIVALENCE object shall not be a dummy argument, a pointer, a target,
13458    an allocatable array, an object of nonsequence derived type, an object of
13459    sequence derived type containing a pointer at any level of component
13460    selection, an automatic object, a function name, an entry name, a result
13461    name, a named constant, a structure component, or a subobject of any of
13462    the preceding objects.  A substring shall not have length zero.  A
13463    derived type shall not have components with default initialization nor
13464    shall two objects of an equivalence group be initialized.
13465    Either all or none of the objects shall have an protected attribute.
13466    The simple constraints are done in symbol.c(check_conflict) and the rest
13467    are implemented here.  */
13468
13469 static void
13470 resolve_equivalence (gfc_equiv *eq)
13471 {
13472   gfc_symbol *sym;
13473   gfc_symbol *first_sym;
13474   gfc_expr *e;
13475   gfc_ref *r;
13476   locus *last_where = NULL;
13477   seq_type eq_type, last_eq_type;
13478   gfc_typespec *last_ts;
13479   int object, cnt_protected;
13480   const char *msg;
13481
13482   last_ts = &eq->expr->symtree->n.sym->ts;
13483
13484   first_sym = eq->expr->symtree->n.sym;
13485
13486   cnt_protected = 0;
13487
13488   for (object = 1; eq; eq = eq->eq, object++)
13489     {
13490       e = eq->expr;
13491
13492       e->ts = e->symtree->n.sym->ts;
13493       /* match_varspec might not know yet if it is seeing
13494          array reference or substring reference, as it doesn't
13495          know the types.  */
13496       if (e->ref && e->ref->type == REF_ARRAY)
13497         {
13498           gfc_ref *ref = e->ref;
13499           sym = e->symtree->n.sym;
13500
13501           if (sym->attr.dimension)
13502             {
13503               ref->u.ar.as = sym->as;
13504               ref = ref->next;
13505             }
13506
13507           /* For substrings, convert REF_ARRAY into REF_SUBSTRING.  */
13508           if (e->ts.type == BT_CHARACTER
13509               && ref
13510               && ref->type == REF_ARRAY
13511               && ref->u.ar.dimen == 1
13512               && ref->u.ar.dimen_type[0] == DIMEN_RANGE
13513               && ref->u.ar.stride[0] == NULL)
13514             {
13515               gfc_expr *start = ref->u.ar.start[0];
13516               gfc_expr *end = ref->u.ar.end[0];
13517               void *mem = NULL;
13518
13519               /* Optimize away the (:) reference.  */
13520               if (start == NULL && end == NULL)
13521                 {
13522                   if (e->ref == ref)
13523                     e->ref = ref->next;
13524                   else
13525                     e->ref->next = ref->next;
13526                   mem = ref;
13527                 }
13528               else
13529                 {
13530                   ref->type = REF_SUBSTRING;
13531                   if (start == NULL)
13532                     start = gfc_get_int_expr (gfc_default_integer_kind,
13533                                               NULL, 1);
13534                   ref->u.ss.start = start;
13535                   if (end == NULL && e->ts.u.cl)
13536                     end = gfc_copy_expr (e->ts.u.cl->length);
13537                   ref->u.ss.end = end;
13538                   ref->u.ss.length = e->ts.u.cl;
13539                   e->ts.u.cl = NULL;
13540                 }
13541               ref = ref->next;
13542               free (mem);
13543             }
13544
13545           /* Any further ref is an error.  */
13546           if (ref)
13547             {
13548               gcc_assert (ref->type == REF_ARRAY);
13549               gfc_error ("Syntax error in EQUIVALENCE statement at %L",
13550                          &ref->u.ar.where);
13551               continue;
13552             }
13553         }
13554
13555       if (gfc_resolve_expr (e) == FAILURE)
13556         continue;
13557
13558       sym = e->symtree->n.sym;
13559
13560       if (sym->attr.is_protected)
13561         cnt_protected++;
13562       if (cnt_protected > 0 && cnt_protected != object)
13563         {
13564               gfc_error ("Either all or none of the objects in the "
13565                          "EQUIVALENCE set at %L shall have the "
13566                          "PROTECTED attribute",
13567                          &e->where);
13568               break;
13569         }
13570
13571       /* Shall not equivalence common block variables in a PURE procedure.  */
13572       if (sym->ns->proc_name
13573           && sym->ns->proc_name->attr.pure
13574           && sym->attr.in_common)
13575         {
13576           gfc_error ("Common block member '%s' at %L cannot be an EQUIVALENCE "
13577                      "object in the pure procedure '%s'",
13578                      sym->name, &e->where, sym->ns->proc_name->name);
13579           break;
13580         }
13581
13582       /* Shall not be a named constant.  */
13583       if (e->expr_type == EXPR_CONSTANT)
13584         {
13585           gfc_error ("Named constant '%s' at %L cannot be an EQUIVALENCE "
13586                      "object", sym->name, &e->where);
13587           continue;
13588         }
13589
13590       if (e->ts.type == BT_DERIVED
13591           && resolve_equivalence_derived (e->ts.u.derived, sym, e) == FAILURE)
13592         continue;
13593
13594       /* Check that the types correspond correctly:
13595          Note 5.28:
13596          A numeric sequence structure may be equivalenced to another sequence
13597          structure, an object of default integer type, default real type, double
13598          precision real type, default logical type such that components of the
13599          structure ultimately only become associated to objects of the same
13600          kind. A character sequence structure may be equivalenced to an object
13601          of default character kind or another character sequence structure.
13602          Other objects may be equivalenced only to objects of the same type and
13603          kind parameters.  */
13604
13605       /* Identical types are unconditionally OK.  */
13606       if (object == 1 || gfc_compare_types (last_ts, &sym->ts))
13607         goto identical_types;
13608
13609       last_eq_type = sequence_type (*last_ts);
13610       eq_type = sequence_type (sym->ts);
13611
13612       /* Since the pair of objects is not of the same type, mixed or
13613          non-default sequences can be rejected.  */
13614
13615       msg = "Sequence %s with mixed components in EQUIVALENCE "
13616             "statement at %L with different type objects";
13617       if ((object ==2
13618            && last_eq_type == SEQ_MIXED
13619            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name, last_where)
13620               == FAILURE)
13621           || (eq_type == SEQ_MIXED
13622               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13623                                  &e->where) == FAILURE))
13624         continue;
13625
13626       msg = "Non-default type object or sequence %s in EQUIVALENCE "
13627             "statement at %L with objects of different type";
13628       if ((object ==2
13629            && last_eq_type == SEQ_NONDEFAULT
13630            && gfc_notify_std (GFC_STD_GNU, msg, first_sym->name,
13631                               last_where) == FAILURE)
13632           || (eq_type == SEQ_NONDEFAULT
13633               && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13634                                  &e->where) == FAILURE))
13635         continue;
13636
13637       msg ="Non-CHARACTER object '%s' in default CHARACTER "
13638            "EQUIVALENCE statement at %L";
13639       if (last_eq_type == SEQ_CHARACTER
13640           && eq_type != SEQ_CHARACTER
13641           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13642                              &e->where) == FAILURE)
13643                 continue;
13644
13645       msg ="Non-NUMERIC object '%s' in default NUMERIC "
13646            "EQUIVALENCE statement at %L";
13647       if (last_eq_type == SEQ_NUMERIC
13648           && eq_type != SEQ_NUMERIC
13649           && gfc_notify_std (GFC_STD_GNU, msg, sym->name,
13650                              &e->where) == FAILURE)
13651                 continue;
13652
13653   identical_types:
13654       last_ts =&sym->ts;
13655       last_where = &e->where;
13656
13657       if (!e->ref)
13658         continue;
13659
13660       /* Shall not be an automatic array.  */
13661       if (e->ref->type == REF_ARRAY
13662           && gfc_resolve_array_spec (e->ref->u.ar.as, 1) == FAILURE)
13663         {
13664           gfc_error ("Array '%s' at %L with non-constant bounds cannot be "
13665                      "an EQUIVALENCE object", sym->name, &e->where);
13666           continue;
13667         }
13668
13669       r = e->ref;
13670       while (r)
13671         {
13672           /* Shall not be a structure component.  */
13673           if (r->type == REF_COMPONENT)
13674             {
13675               gfc_error ("Structure component '%s' at %L cannot be an "
13676                          "EQUIVALENCE object",
13677                          r->u.c.component->name, &e->where);
13678               break;
13679             }
13680
13681           /* A substring shall not have length zero.  */
13682           if (r->type == REF_SUBSTRING)
13683             {
13684               if (compare_bound (r->u.ss.start, r->u.ss.end) == CMP_GT)
13685                 {
13686                   gfc_error ("Substring at %L has length zero",
13687                              &r->u.ss.start->where);
13688                   break;
13689                 }
13690             }
13691           r = r->next;
13692         }
13693     }
13694 }
13695
13696
13697 /* Resolve function and ENTRY types, issue diagnostics if needed.  */
13698
13699 static void
13700 resolve_fntype (gfc_namespace *ns)
13701 {
13702   gfc_entry_list *el;
13703   gfc_symbol *sym;
13704
13705   if (ns->proc_name == NULL || !ns->proc_name->attr.function)
13706     return;
13707
13708   /* If there are any entries, ns->proc_name is the entry master
13709      synthetic symbol and ns->entries->sym actual FUNCTION symbol.  */
13710   if (ns->entries)
13711     sym = ns->entries->sym;
13712   else
13713     sym = ns->proc_name;
13714   if (sym->result == sym
13715       && sym->ts.type == BT_UNKNOWN
13716       && gfc_set_default_type (sym, 0, NULL) == FAILURE
13717       && !sym->attr.untyped)
13718     {
13719       gfc_error ("Function '%s' at %L has no IMPLICIT type",
13720                  sym->name, &sym->declared_at);
13721       sym->attr.untyped = 1;
13722     }
13723
13724   if (sym->ts.type == BT_DERIVED && !sym->ts.u.derived->attr.use_assoc
13725       && !sym->attr.contained
13726       && !gfc_check_symbol_access (sym->ts.u.derived)
13727       && gfc_check_symbol_access (sym))
13728     {
13729       gfc_notify_std (GFC_STD_F2003, "Fortran 2003: PUBLIC function '%s' at "
13730                       "%L of PRIVATE type '%s'", sym->name,
13731                       &sym->declared_at, sym->ts.u.derived->name);
13732     }
13733
13734     if (ns->entries)
13735     for (el = ns->entries->next; el; el = el->next)
13736       {
13737         if (el->sym->result == el->sym
13738             && el->sym->ts.type == BT_UNKNOWN
13739             && gfc_set_default_type (el->sym, 0, NULL) == FAILURE
13740             && !el->sym->attr.untyped)
13741           {
13742             gfc_error ("ENTRY '%s' at %L has no IMPLICIT type",
13743                        el->sym->name, &el->sym->declared_at);
13744             el->sym->attr.untyped = 1;
13745           }
13746       }
13747 }
13748
13749
13750 /* 12.3.2.1.1 Defined operators.  */
13751
13752 static gfc_try
13753 check_uop_procedure (gfc_symbol *sym, locus where)
13754 {
13755   gfc_formal_arglist *formal;
13756
13757   if (!sym->attr.function)
13758     {
13759       gfc_error ("User operator procedure '%s' at %L must be a FUNCTION",
13760                  sym->name, &where);
13761       return FAILURE;
13762     }
13763
13764   if (sym->ts.type == BT_CHARACTER
13765       && !(sym->ts.u.cl && sym->ts.u.cl->length)
13766       && !(sym->result && sym->result->ts.u.cl
13767            && sym->result->ts.u.cl->length))
13768     {
13769       gfc_error ("User operator procedure '%s' at %L cannot be assumed "
13770                  "character length", sym->name, &where);
13771       return FAILURE;
13772     }
13773
13774   formal = sym->formal;
13775   if (!formal || !formal->sym)
13776     {
13777       gfc_error ("User operator procedure '%s' at %L must have at least "
13778                  "one argument", sym->name, &where);
13779       return FAILURE;
13780     }
13781
13782   if (formal->sym->attr.intent != INTENT_IN)
13783     {
13784       gfc_error ("First argument of operator interface at %L must be "
13785                  "INTENT(IN)", &where);
13786       return FAILURE;
13787     }
13788
13789   if (formal->sym->attr.optional)
13790     {
13791       gfc_error ("First argument of operator interface at %L cannot be "
13792                  "optional", &where);
13793       return FAILURE;
13794     }
13795
13796   formal = formal->next;
13797   if (!formal || !formal->sym)
13798     return SUCCESS;
13799
13800   if (formal->sym->attr.intent != INTENT_IN)
13801     {
13802       gfc_error ("Second argument of operator interface at %L must be "
13803                  "INTENT(IN)", &where);
13804       return FAILURE;
13805     }
13806
13807   if (formal->sym->attr.optional)
13808     {
13809       gfc_error ("Second argument of operator interface at %L cannot be "
13810                  "optional", &where);
13811       return FAILURE;
13812     }
13813
13814   if (formal->next)
13815     {
13816       gfc_error ("Operator interface at %L must have, at most, two "
13817                  "arguments", &where);
13818       return FAILURE;
13819     }
13820
13821   return SUCCESS;
13822 }
13823
13824 static void
13825 gfc_resolve_uops (gfc_symtree *symtree)
13826 {
13827   gfc_interface *itr;
13828
13829   if (symtree == NULL)
13830     return;
13831
13832   gfc_resolve_uops (symtree->left);
13833   gfc_resolve_uops (symtree->right);
13834
13835   for (itr = symtree->n.uop->op; itr; itr = itr->next)
13836     check_uop_procedure (itr->sym, itr->sym->declared_at);
13837 }
13838
13839
13840 /* Examine all of the expressions associated with a program unit,
13841    assign types to all intermediate expressions, make sure that all
13842    assignments are to compatible types and figure out which names
13843    refer to which functions or subroutines.  It doesn't check code
13844    block, which is handled by resolve_code.  */
13845
13846 static void
13847 resolve_types (gfc_namespace *ns)
13848 {
13849   gfc_namespace *n;
13850   gfc_charlen *cl;
13851   gfc_data *d;
13852   gfc_equiv *eq;
13853   gfc_namespace* old_ns = gfc_current_ns;
13854
13855   /* Check that all IMPLICIT types are ok.  */
13856   if (!ns->seen_implicit_none)
13857     {
13858       unsigned letter;
13859       for (letter = 0; letter != GFC_LETTERS; ++letter)
13860         if (ns->set_flag[letter]
13861             && resolve_typespec_used (&ns->default_type[letter],
13862                                       &ns->implicit_loc[letter],
13863                                       NULL) == FAILURE)
13864           return;
13865     }
13866
13867   gfc_current_ns = ns;
13868
13869   resolve_entries (ns);
13870
13871   resolve_common_vars (ns->blank_common.head, false);
13872   resolve_common_blocks (ns->common_root);
13873
13874   resolve_contained_functions (ns);
13875
13876   if (ns->proc_name && ns->proc_name->attr.flavor == FL_PROCEDURE
13877       && ns->proc_name->attr.if_source == IFSRC_IFBODY)
13878     resolve_formal_arglist (ns->proc_name);
13879
13880   gfc_traverse_ns (ns, resolve_bind_c_derived_types);
13881
13882   for (cl = ns->cl_list; cl; cl = cl->next)
13883     resolve_charlen (cl);
13884
13885   gfc_traverse_ns (ns, resolve_symbol);
13886
13887   resolve_fntype (ns);
13888
13889   for (n = ns->contained; n; n = n->sibling)
13890     {
13891       if (gfc_pure (ns->proc_name) && !gfc_pure (n->proc_name))
13892         gfc_error ("Contained procedure '%s' at %L of a PURE procedure must "
13893                    "also be PURE", n->proc_name->name,
13894                    &n->proc_name->declared_at);
13895
13896       resolve_types (n);
13897     }
13898
13899   forall_flag = 0;
13900   do_concurrent_flag = 0;
13901   gfc_check_interfaces (ns);
13902
13903   gfc_traverse_ns (ns, resolve_values);
13904
13905   if (ns->save_all)
13906     gfc_save_all (ns);
13907
13908   iter_stack = NULL;
13909   for (d = ns->data; d; d = d->next)
13910     resolve_data (d);
13911
13912   iter_stack = NULL;
13913   gfc_traverse_ns (ns, gfc_formalize_init_value);
13914
13915   gfc_traverse_ns (ns, gfc_verify_binding_labels);
13916
13917   if (ns->common_root != NULL)
13918     gfc_traverse_symtree (ns->common_root, resolve_bind_c_comms);
13919
13920   for (eq = ns->equiv; eq; eq = eq->next)
13921     resolve_equivalence (eq);
13922
13923   /* Warn about unused labels.  */
13924   if (warn_unused_label)
13925     warn_unused_fortran_label (ns->st_labels);
13926
13927   gfc_resolve_uops (ns->uop_root);
13928
13929   gfc_current_ns = old_ns;
13930 }
13931
13932
13933 /* Call resolve_code recursively.  */
13934
13935 static void
13936 resolve_codes (gfc_namespace *ns)
13937 {
13938   gfc_namespace *n;
13939   bitmap_obstack old_obstack;
13940
13941   if (ns->resolved == 1)
13942     return;
13943
13944   for (n = ns->contained; n; n = n->sibling)
13945     resolve_codes (n);
13946
13947   gfc_current_ns = ns;
13948
13949   /* Don't clear 'cs_base' if this is the namespace of a BLOCK construct.  */
13950   if (!(ns->proc_name && ns->proc_name->attr.flavor == FL_LABEL))
13951     cs_base = NULL;
13952
13953   /* Set to an out of range value.  */
13954   current_entry_id = -1;
13955
13956   old_obstack = labels_obstack;
13957   bitmap_obstack_initialize (&labels_obstack);
13958
13959   resolve_code (ns->code, ns);
13960
13961   bitmap_obstack_release (&labels_obstack);
13962   labels_obstack = old_obstack;
13963 }
13964
13965
13966 /* This function is called after a complete program unit has been compiled.
13967    Its purpose is to examine all of the expressions associated with a program
13968    unit, assign types to all intermediate expressions, make sure that all
13969    assignments are to compatible types and figure out which names refer to
13970    which functions or subroutines.  */
13971
13972 void
13973 gfc_resolve (gfc_namespace *ns)
13974 {
13975   gfc_namespace *old_ns;
13976   code_stack *old_cs_base;
13977
13978   if (ns->resolved)
13979     return;
13980
13981   ns->resolved = -1;
13982   old_ns = gfc_current_ns;
13983   old_cs_base = cs_base;
13984
13985   resolve_types (ns);
13986   resolve_codes (ns);
13987
13988   gfc_current_ns = old_ns;
13989   cs_base = old_cs_base;
13990   ns->resolved = 1;
13991
13992   gfc_run_passes (ns);
13993 }