OSDN Git Service

2012-07-19 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / interface.c
1 /* Deal with interfaces.
2    Copyright (C) 2000, 2001, 2002, 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
24 /* Deal with interfaces.  An explicit interface is represented as a
25    singly linked list of formal argument structures attached to the
26    relevant symbols.  For an implicit interface, the arguments don't
27    point to symbols.  Explicit interfaces point to namespaces that
28    contain the symbols within that interface.
29
30    Implicit interfaces are linked together in a singly linked list
31    along the next_if member of symbol nodes.  Since a particular
32    symbol can only have a single explicit interface, the symbol cannot
33    be part of multiple lists and a single next-member suffices.
34
35    This is not the case for general classes, though.  An operator
36    definition is independent of just about all other uses and has it's
37    own head pointer.
38
39    Nameless interfaces:
40      Nameless interfaces create symbols with explicit interfaces within
41      the current namespace.  They are otherwise unlinked.
42
43    Generic interfaces:
44      The generic name points to a linked list of symbols.  Each symbol
45      has an explicit interface.  Each explicit interface has its own
46      namespace containing the arguments.  Module procedures are symbols in
47      which the interface is added later when the module procedure is parsed.
48
49    User operators:
50      User-defined operators are stored in a their own set of symtrees
51      separate from regular symbols.  The symtrees point to gfc_user_op
52      structures which in turn head up a list of relevant interfaces.
53
54    Extended intrinsics and assignment:
55      The head of these interface lists are stored in the containing namespace.
56
57    Implicit interfaces:
58      An implicit interface is represented as a singly linked list of
59      formal argument list structures that don't point to any symbol
60      nodes -- they just contain types.
61
62
63    When a subprogram is defined, the program unit's name points to an
64    interface as usual, but the link to the namespace is NULL and the
65    formal argument list points to symbols within the same namespace as
66    the program unit name.  */
67
68 #include "config.h"
69 #include "system.h"
70 #include "coretypes.h"
71 #include "gfortran.h"
72 #include "match.h"
73 #include "arith.h"
74
75 /* The current_interface structure holds information about the
76    interface currently being parsed.  This structure is saved and
77    restored during recursive interfaces.  */
78
79 gfc_interface_info current_interface;
80
81
82 /* Free a singly linked list of gfc_interface structures.  */
83
84 void
85 gfc_free_interface (gfc_interface *intr)
86 {
87   gfc_interface *next;
88
89   for (; intr; intr = next)
90     {
91       next = intr->next;
92       free (intr);
93     }
94 }
95
96
97 /* Change the operators unary plus and minus into binary plus and
98    minus respectively, leaving the rest unchanged.  */
99
100 static gfc_intrinsic_op
101 fold_unary_intrinsic (gfc_intrinsic_op op)
102 {
103   switch (op)
104     {
105     case INTRINSIC_UPLUS:
106       op = INTRINSIC_PLUS;
107       break;
108     case INTRINSIC_UMINUS:
109       op = INTRINSIC_MINUS;
110       break;
111     default:
112       break;
113     }
114
115   return op;
116 }
117
118
119 /* Match a generic specification.  Depending on which type of
120    interface is found, the 'name' or 'op' pointers may be set.
121    This subroutine doesn't return MATCH_NO.  */
122
123 match
124 gfc_match_generic_spec (interface_type *type,
125                         char *name,
126                         gfc_intrinsic_op *op)
127 {
128   char buffer[GFC_MAX_SYMBOL_LEN + 1];
129   match m;
130   gfc_intrinsic_op i;
131
132   if (gfc_match (" assignment ( = )") == MATCH_YES)
133     {
134       *type = INTERFACE_INTRINSIC_OP;
135       *op = INTRINSIC_ASSIGN;
136       return MATCH_YES;
137     }
138
139   if (gfc_match (" operator ( %o )", &i) == MATCH_YES)
140     {                           /* Operator i/f */
141       *type = INTERFACE_INTRINSIC_OP;
142       *op = fold_unary_intrinsic (i);
143       return MATCH_YES;
144     }
145
146   *op = INTRINSIC_NONE;
147   if (gfc_match (" operator ( ") == MATCH_YES)
148     {
149       m = gfc_match_defined_op_name (buffer, 1);
150       if (m == MATCH_NO)
151         goto syntax;
152       if (m != MATCH_YES)
153         return MATCH_ERROR;
154
155       m = gfc_match_char (')');
156       if (m == MATCH_NO)
157         goto syntax;
158       if (m != MATCH_YES)
159         return MATCH_ERROR;
160
161       strcpy (name, buffer);
162       *type = INTERFACE_USER_OP;
163       return MATCH_YES;
164     }
165
166   if (gfc_match_name (buffer) == MATCH_YES)
167     {
168       strcpy (name, buffer);
169       *type = INTERFACE_GENERIC;
170       return MATCH_YES;
171     }
172
173   *type = INTERFACE_NAMELESS;
174   return MATCH_YES;
175
176 syntax:
177   gfc_error ("Syntax error in generic specification at %C");
178   return MATCH_ERROR;
179 }
180
181
182 /* Match one of the five F95 forms of an interface statement.  The
183    matcher for the abstract interface follows.  */
184
185 match
186 gfc_match_interface (void)
187 {
188   char name[GFC_MAX_SYMBOL_LEN + 1];
189   interface_type type;
190   gfc_symbol *sym;
191   gfc_intrinsic_op op;
192   match m;
193
194   m = gfc_match_space ();
195
196   if (gfc_match_generic_spec (&type, name, &op) == MATCH_ERROR)
197     return MATCH_ERROR;
198
199   /* If we're not looking at the end of the statement now, or if this
200      is not a nameless interface but we did not see a space, punt.  */
201   if (gfc_match_eos () != MATCH_YES
202       || (type != INTERFACE_NAMELESS && m != MATCH_YES))
203     {
204       gfc_error ("Syntax error: Trailing garbage in INTERFACE statement "
205                  "at %C");
206       return MATCH_ERROR;
207     }
208
209   current_interface.type = type;
210
211   switch (type)
212     {
213     case INTERFACE_GENERIC:
214       if (gfc_get_symbol (name, NULL, &sym))
215         return MATCH_ERROR;
216
217       if (!sym->attr.generic 
218           && gfc_add_generic (&sym->attr, sym->name, NULL) == FAILURE)
219         return MATCH_ERROR;
220
221       if (sym->attr.dummy)
222         {
223           gfc_error ("Dummy procedure '%s' at %C cannot have a "
224                      "generic interface", sym->name);
225           return MATCH_ERROR;
226         }
227
228       current_interface.sym = gfc_new_block = sym;
229       break;
230
231     case INTERFACE_USER_OP:
232       current_interface.uop = gfc_get_uop (name);
233       break;
234
235     case INTERFACE_INTRINSIC_OP:
236       current_interface.op = op;
237       break;
238
239     case INTERFACE_NAMELESS:
240     case INTERFACE_ABSTRACT:
241       break;
242     }
243
244   return MATCH_YES;
245 }
246
247
248
249 /* Match a F2003 abstract interface.  */
250
251 match
252 gfc_match_abstract_interface (void)
253 {
254   match m;
255
256   if (gfc_notify_std (GFC_STD_F2003, "ABSTRACT INTERFACE at %C")
257                       == FAILURE)
258     return MATCH_ERROR;
259
260   m = gfc_match_eos ();
261
262   if (m != MATCH_YES)
263     {
264       gfc_error ("Syntax error in ABSTRACT INTERFACE statement at %C");
265       return MATCH_ERROR;
266     }
267
268   current_interface.type = INTERFACE_ABSTRACT;
269
270   return m;
271 }
272
273
274 /* Match the different sort of generic-specs that can be present after
275    the END INTERFACE itself.  */
276
277 match
278 gfc_match_end_interface (void)
279 {
280   char name[GFC_MAX_SYMBOL_LEN + 1];
281   interface_type type;
282   gfc_intrinsic_op op;
283   match m;
284
285   m = gfc_match_space ();
286
287   if (gfc_match_generic_spec (&type, name, &op) == MATCH_ERROR)
288     return MATCH_ERROR;
289
290   /* If we're not looking at the end of the statement now, or if this
291      is not a nameless interface but we did not see a space, punt.  */
292   if (gfc_match_eos () != MATCH_YES
293       || (type != INTERFACE_NAMELESS && m != MATCH_YES))
294     {
295       gfc_error ("Syntax error: Trailing garbage in END INTERFACE "
296                  "statement at %C");
297       return MATCH_ERROR;
298     }
299
300   m = MATCH_YES;
301
302   switch (current_interface.type)
303     {
304     case INTERFACE_NAMELESS:
305     case INTERFACE_ABSTRACT:
306       if (type != INTERFACE_NAMELESS)
307         {
308           gfc_error ("Expected a nameless interface at %C");
309           m = MATCH_ERROR;
310         }
311
312       break;
313
314     case INTERFACE_INTRINSIC_OP:
315       if (type != current_interface.type || op != current_interface.op)
316         {
317
318           if (current_interface.op == INTRINSIC_ASSIGN)
319             {
320               m = MATCH_ERROR;
321               gfc_error ("Expected 'END INTERFACE ASSIGNMENT (=)' at %C");
322             }
323           else
324             {
325               const char *s1, *s2;
326               s1 = gfc_op2string (current_interface.op);
327               s2 = gfc_op2string (op);
328
329               /* The following if-statements are used to enforce C1202
330                  from F2003.  */
331               if ((strcmp(s1, "==") == 0 && strcmp(s2, ".eq.") == 0)
332                   || (strcmp(s1, ".eq.") == 0 && strcmp(s2, "==") == 0))
333                 break;
334               if ((strcmp(s1, "/=") == 0 && strcmp(s2, ".ne.") == 0)
335                   || (strcmp(s1, ".ne.") == 0 && strcmp(s2, "/=") == 0))
336                 break;
337               if ((strcmp(s1, "<=") == 0 && strcmp(s2, ".le.") == 0)
338                   || (strcmp(s1, ".le.") == 0 && strcmp(s2, "<=") == 0))
339                 break;
340               if ((strcmp(s1, "<") == 0 && strcmp(s2, ".lt.") == 0)
341                   || (strcmp(s1, ".lt.") == 0 && strcmp(s2, "<") == 0))
342                 break;
343               if ((strcmp(s1, ">=") == 0 && strcmp(s2, ".ge.") == 0)
344                   || (strcmp(s1, ".ge.") == 0 && strcmp(s2, ">=") == 0))
345                 break;
346               if ((strcmp(s1, ">") == 0 && strcmp(s2, ".gt.") == 0)
347                   || (strcmp(s1, ".gt.") == 0 && strcmp(s2, ">") == 0))
348                 break;
349
350               m = MATCH_ERROR;
351               gfc_error ("Expecting 'END INTERFACE OPERATOR (%s)' at %C, "
352                          "but got %s", s1, s2);
353             }
354                 
355         }
356
357       break;
358
359     case INTERFACE_USER_OP:
360       /* Comparing the symbol node names is OK because only use-associated
361          symbols can be renamed.  */
362       if (type != current_interface.type
363           || strcmp (current_interface.uop->name, name) != 0)
364         {
365           gfc_error ("Expecting 'END INTERFACE OPERATOR (.%s.)' at %C",
366                      current_interface.uop->name);
367           m = MATCH_ERROR;
368         }
369
370       break;
371
372     case INTERFACE_GENERIC:
373       if (type != current_interface.type
374           || strcmp (current_interface.sym->name, name) != 0)
375         {
376           gfc_error ("Expecting 'END INTERFACE %s' at %C",
377                      current_interface.sym->name);
378           m = MATCH_ERROR;
379         }
380
381       break;
382     }
383
384   return m;
385 }
386
387
388 /* Compare two derived types using the criteria in 4.4.2 of the standard,
389    recursing through gfc_compare_types for the components.  */
390
391 int
392 gfc_compare_derived_types (gfc_symbol *derived1, gfc_symbol *derived2)
393 {
394   gfc_component *dt1, *dt2;
395
396   if (derived1 == derived2)
397     return 1;
398
399   /* Special case for comparing derived types across namespaces.  If the
400      true names and module names are the same and the module name is
401      nonnull, then they are equal.  */
402   if (derived1 != NULL && derived2 != NULL
403       && strcmp (derived1->name, derived2->name) == 0
404       && derived1->module != NULL && derived2->module != NULL
405       && strcmp (derived1->module, derived2->module) == 0)
406     return 1;
407
408   /* Compare type via the rules of the standard.  Both types must have
409      the SEQUENCE or BIND(C) attribute to be equal.  */
410
411   if (strcmp (derived1->name, derived2->name))
412     return 0;
413
414   if (derived1->component_access == ACCESS_PRIVATE
415       || derived2->component_access == ACCESS_PRIVATE)
416     return 0;
417
418   if (!(derived1->attr.sequence && derived2->attr.sequence)
419       && !(derived1->attr.is_bind_c && derived2->attr.is_bind_c))
420     return 0;
421
422   dt1 = derived1->components;
423   dt2 = derived2->components;
424
425   /* Since subtypes of SEQUENCE types must be SEQUENCE types as well, a
426      simple test can speed things up.  Otherwise, lots of things have to
427      match.  */
428   for (;;)
429     {
430       if (strcmp (dt1->name, dt2->name) != 0)
431         return 0;
432
433       if (dt1->attr.access != dt2->attr.access)
434         return 0;
435
436       if (dt1->attr.pointer != dt2->attr.pointer)
437         return 0;
438
439       if (dt1->attr.dimension != dt2->attr.dimension)
440         return 0;
441
442      if (dt1->attr.allocatable != dt2->attr.allocatable)
443         return 0;
444
445       if (dt1->attr.dimension && gfc_compare_array_spec (dt1->as, dt2->as) == 0)
446         return 0;
447
448       /* Make sure that link lists do not put this function into an 
449          endless recursive loop!  */
450       if (!(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
451             && !(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
452             && gfc_compare_types (&dt1->ts, &dt2->ts) == 0)
453         return 0;
454
455       else if ((dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
456                 && !(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived))
457         return 0;
458
459       else if (!(dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived)
460                 && (dt1->ts.type == BT_DERIVED && derived1 == dt1->ts.u.derived))
461         return 0;
462
463       dt1 = dt1->next;
464       dt2 = dt2->next;
465
466       if (dt1 == NULL && dt2 == NULL)
467         break;
468       if (dt1 == NULL || dt2 == NULL)
469         return 0;
470     }
471
472   return 1;
473 }
474
475
476 /* Compare two typespecs, recursively if necessary.  */
477
478 int
479 gfc_compare_types (gfc_typespec *ts1, gfc_typespec *ts2)
480 {
481   /* See if one of the typespecs is a BT_VOID, which is what is being used
482      to allow the funcs like c_f_pointer to accept any pointer type.
483      TODO: Possibly should narrow this to just the one typespec coming in
484      that is for the formal arg, but oh well.  */
485   if (ts1->type == BT_VOID || ts2->type == BT_VOID)
486     return 1;
487    
488   if (ts1->type != ts2->type
489       && ((ts1->type != BT_DERIVED && ts1->type != BT_CLASS)
490           || (ts2->type != BT_DERIVED && ts2->type != BT_CLASS)))
491     return 0;
492   if (ts1->type != BT_DERIVED && ts1->type != BT_CLASS)
493     return (ts1->kind == ts2->kind);
494
495   /* Compare derived types.  */
496   if (gfc_type_compatible (ts1, ts2))
497     return 1;
498
499   return gfc_compare_derived_types (ts1->u.derived ,ts2->u.derived);
500 }
501
502
503 /* Given two symbols that are formal arguments, compare their ranks
504    and types.  Returns nonzero if they have the same rank and type,
505    zero otherwise.  */
506
507 static int
508 compare_type_rank (gfc_symbol *s1, gfc_symbol *s2)
509 {
510   int r1, r2;
511
512   r1 = (s1->as != NULL) ? s1->as->rank : 0;
513   r2 = (s2->as != NULL) ? s2->as->rank : 0;
514
515   if (r1 != r2)
516     return 0;                   /* Ranks differ.  */
517
518   return gfc_compare_types (&s1->ts, &s2->ts)
519          || s1->ts.type == BT_ASSUMED || s2->ts.type == BT_ASSUMED; 
520 }
521
522
523 /* Given two symbols that are formal arguments, compare their types
524    and rank and their formal interfaces if they are both dummy
525    procedures.  Returns nonzero if the same, zero if different.  */
526
527 static int
528 compare_type_rank_if (gfc_symbol *s1, gfc_symbol *s2)
529 {
530   if (s1 == NULL || s2 == NULL)
531     return s1 == s2 ? 1 : 0;
532
533   if (s1 == s2)
534     return 1;
535
536   if (s1->attr.flavor != FL_PROCEDURE && s2->attr.flavor != FL_PROCEDURE)
537     return compare_type_rank (s1, s2);
538
539   if (s1->attr.flavor != FL_PROCEDURE || s2->attr.flavor != FL_PROCEDURE)
540     return 0;
541
542   /* At this point, both symbols are procedures.  It can happen that
543      external procedures are compared, where one is identified by usage
544      to be a function or subroutine but the other is not.  Check TKR
545      nonetheless for these cases.  */
546   if (s1->attr.function == 0 && s1->attr.subroutine == 0)
547     return s1->attr.external == 1 ? compare_type_rank (s1, s2) : 0;
548
549   if (s2->attr.function == 0 && s2->attr.subroutine == 0)
550     return s2->attr.external == 1 ? compare_type_rank (s1, s2) : 0;
551
552   /* Now the type of procedure has been identified.  */
553   if (s1->attr.function != s2->attr.function
554       || s1->attr.subroutine != s2->attr.subroutine)
555     return 0;
556
557   if (s1->attr.function && compare_type_rank (s1, s2) == 0)
558     return 0;
559
560   /* Originally, gfortran recursed here to check the interfaces of passed
561      procedures.  This is explicitly not required by the standard.  */
562   return 1;
563 }
564
565
566 /* Given a formal argument list and a keyword name, search the list
567    for that keyword.  Returns the correct symbol node if found, NULL
568    if not found.  */
569
570 static gfc_symbol *
571 find_keyword_arg (const char *name, gfc_formal_arglist *f)
572 {
573   for (; f; f = f->next)
574     if (strcmp (f->sym->name, name) == 0)
575       return f->sym;
576
577   return NULL;
578 }
579
580
581 /******** Interface checking subroutines **********/
582
583
584 /* Given an operator interface and the operator, make sure that all
585    interfaces for that operator are legal.  */
586
587 bool
588 gfc_check_operator_interface (gfc_symbol *sym, gfc_intrinsic_op op,
589                               locus opwhere)
590 {
591   gfc_formal_arglist *formal;
592   sym_intent i1, i2;
593   bt t1, t2;
594   int args, r1, r2, k1, k2;
595
596   gcc_assert (sym);
597
598   args = 0;
599   t1 = t2 = BT_UNKNOWN;
600   i1 = i2 = INTENT_UNKNOWN;
601   r1 = r2 = -1;
602   k1 = k2 = -1;
603
604   for (formal = sym->formal; formal; formal = formal->next)
605     {
606       gfc_symbol *fsym = formal->sym;
607       if (fsym == NULL)
608         {
609           gfc_error ("Alternate return cannot appear in operator "
610                      "interface at %L", &sym->declared_at);
611           return false;
612         }
613       if (args == 0)
614         {
615           t1 = fsym->ts.type;
616           i1 = fsym->attr.intent;
617           r1 = (fsym->as != NULL) ? fsym->as->rank : 0;
618           k1 = fsym->ts.kind;
619         }
620       if (args == 1)
621         {
622           t2 = fsym->ts.type;
623           i2 = fsym->attr.intent;
624           r2 = (fsym->as != NULL) ? fsym->as->rank : 0;
625           k2 = fsym->ts.kind;
626         }
627       args++;
628     }
629
630   /* Only +, - and .not. can be unary operators.
631      .not. cannot be a binary operator.  */
632   if (args == 0 || args > 2 || (args == 1 && op != INTRINSIC_PLUS
633                                 && op != INTRINSIC_MINUS
634                                 && op != INTRINSIC_NOT)
635       || (args == 2 && op == INTRINSIC_NOT))
636     {
637       gfc_error ("Operator interface at %L has the wrong number of arguments",
638                  &sym->declared_at);
639       return false;
640     }
641
642   /* Check that intrinsics are mapped to functions, except
643      INTRINSIC_ASSIGN which should map to a subroutine.  */
644   if (op == INTRINSIC_ASSIGN)
645     {
646       if (!sym->attr.subroutine)
647         {
648           gfc_error ("Assignment operator interface at %L must be "
649                      "a SUBROUTINE", &sym->declared_at);
650           return false;
651         }
652       if (args != 2)
653         {
654           gfc_error ("Assignment operator interface at %L must have "
655                      "two arguments", &sym->declared_at);
656           return false;
657         }
658
659       /* Allowed are (per F2003, 12.3.2.1.2 Defined assignments):
660          - First argument an array with different rank than second,
661          - First argument is a scalar and second an array,
662          - Types and kinds do not conform, or
663          - First argument is of derived type.  */
664       if (sym->formal->sym->ts.type != BT_DERIVED
665           && sym->formal->sym->ts.type != BT_CLASS
666           && (r2 == 0 || r1 == r2)
667           && (sym->formal->sym->ts.type == sym->formal->next->sym->ts.type
668               || (gfc_numeric_ts (&sym->formal->sym->ts)
669                   && gfc_numeric_ts (&sym->formal->next->sym->ts))))
670         {
671           gfc_error ("Assignment operator interface at %L must not redefine "
672                      "an INTRINSIC type assignment", &sym->declared_at);
673           return false;
674         }
675     }
676   else
677     {
678       if (!sym->attr.function)
679         {
680           gfc_error ("Intrinsic operator interface at %L must be a FUNCTION",
681                      &sym->declared_at);
682           return false;
683         }
684     }
685
686   /* Check intents on operator interfaces.  */
687   if (op == INTRINSIC_ASSIGN)
688     {
689       if (i1 != INTENT_OUT && i1 != INTENT_INOUT)
690         {
691           gfc_error ("First argument of defined assignment at %L must be "
692                      "INTENT(OUT) or INTENT(INOUT)", &sym->declared_at);
693           return false;
694         }
695
696       if (i2 != INTENT_IN)
697         {
698           gfc_error ("Second argument of defined assignment at %L must be "
699                      "INTENT(IN)", &sym->declared_at);
700           return false;
701         }
702     }
703   else
704     {
705       if (i1 != INTENT_IN)
706         {
707           gfc_error ("First argument of operator interface at %L must be "
708                      "INTENT(IN)", &sym->declared_at);
709           return false;
710         }
711
712       if (args == 2 && i2 != INTENT_IN)
713         {
714           gfc_error ("Second argument of operator interface at %L must be "
715                      "INTENT(IN)", &sym->declared_at);
716           return false;
717         }
718     }
719
720   /* From now on, all we have to do is check that the operator definition
721      doesn't conflict with an intrinsic operator. The rules for this
722      game are defined in 7.1.2 and 7.1.3 of both F95 and F2003 standards,
723      as well as 12.3.2.1.1 of Fortran 2003:
724
725      "If the operator is an intrinsic-operator (R310), the number of
726      function arguments shall be consistent with the intrinsic uses of
727      that operator, and the types, kind type parameters, or ranks of the
728      dummy arguments shall differ from those required for the intrinsic
729      operation (7.1.2)."  */
730
731 #define IS_NUMERIC_TYPE(t) \
732   ((t) == BT_INTEGER || (t) == BT_REAL || (t) == BT_COMPLEX)
733
734   /* Unary ops are easy, do them first.  */
735   if (op == INTRINSIC_NOT)
736     {
737       if (t1 == BT_LOGICAL)
738         goto bad_repl;
739       else
740         return true;
741     }
742
743   if (args == 1 && (op == INTRINSIC_PLUS || op == INTRINSIC_MINUS))
744     {
745       if (IS_NUMERIC_TYPE (t1))
746         goto bad_repl;
747       else
748         return true;
749     }
750
751   /* Character intrinsic operators have same character kind, thus
752      operator definitions with operands of different character kinds
753      are always safe.  */
754   if (t1 == BT_CHARACTER && t2 == BT_CHARACTER && k1 != k2)
755     return true;
756
757   /* Intrinsic operators always perform on arguments of same rank,
758      so different ranks is also always safe.  (rank == 0) is an exception
759      to that, because all intrinsic operators are elemental.  */
760   if (r1 != r2 && r1 != 0 && r2 != 0)
761     return true;
762
763   switch (op)
764   {
765     case INTRINSIC_EQ:
766     case INTRINSIC_EQ_OS:
767     case INTRINSIC_NE:
768     case INTRINSIC_NE_OS:
769       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
770         goto bad_repl;
771       /* Fall through.  */
772
773     case INTRINSIC_PLUS:
774     case INTRINSIC_MINUS:
775     case INTRINSIC_TIMES:
776     case INTRINSIC_DIVIDE:
777     case INTRINSIC_POWER:
778       if (IS_NUMERIC_TYPE (t1) && IS_NUMERIC_TYPE (t2))
779         goto bad_repl;
780       break;
781
782     case INTRINSIC_GT:
783     case INTRINSIC_GT_OS:
784     case INTRINSIC_GE:
785     case INTRINSIC_GE_OS:
786     case INTRINSIC_LT:
787     case INTRINSIC_LT_OS:
788     case INTRINSIC_LE:
789     case INTRINSIC_LE_OS:
790       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
791         goto bad_repl;
792       if ((t1 == BT_INTEGER || t1 == BT_REAL)
793           && (t2 == BT_INTEGER || t2 == BT_REAL))
794         goto bad_repl;
795       break;
796
797     case INTRINSIC_CONCAT:
798       if (t1 == BT_CHARACTER && t2 == BT_CHARACTER)
799         goto bad_repl;
800       break;
801
802     case INTRINSIC_AND:
803     case INTRINSIC_OR:
804     case INTRINSIC_EQV:
805     case INTRINSIC_NEQV:
806       if (t1 == BT_LOGICAL && t2 == BT_LOGICAL)
807         goto bad_repl;
808       break;
809
810     default:
811       break;
812   }
813
814   return true;
815
816 #undef IS_NUMERIC_TYPE
817
818 bad_repl:
819   gfc_error ("Operator interface at %L conflicts with intrinsic interface",
820              &opwhere);
821   return false;
822 }
823
824
825 /* Given a pair of formal argument lists, we see if the two lists can
826    be distinguished by counting the number of nonoptional arguments of
827    a given type/rank in f1 and seeing if there are less then that
828    number of those arguments in f2 (including optional arguments).
829    Since this test is asymmetric, it has to be called twice to make it
830    symmetric. Returns nonzero if the argument lists are incompatible
831    by this test. This subroutine implements rule 1 of section F03:16.2.3.
832    'p1' and 'p2' are the PASS arguments of both procedures (if applicable).  */
833
834 static int
835 count_types_test (gfc_formal_arglist *f1, gfc_formal_arglist *f2,
836                   const char *p1, const char *p2)
837 {
838   int rc, ac1, ac2, i, j, k, n1;
839   gfc_formal_arglist *f;
840
841   typedef struct
842   {
843     int flag;
844     gfc_symbol *sym;
845   }
846   arginfo;
847
848   arginfo *arg;
849
850   n1 = 0;
851
852   for (f = f1; f; f = f->next)
853     n1++;
854
855   /* Build an array of integers that gives the same integer to
856      arguments of the same type/rank.  */
857   arg = XCNEWVEC (arginfo, n1);
858
859   f = f1;
860   for (i = 0; i < n1; i++, f = f->next)
861     {
862       arg[i].flag = -1;
863       arg[i].sym = f->sym;
864     }
865
866   k = 0;
867
868   for (i = 0; i < n1; i++)
869     {
870       if (arg[i].flag != -1)
871         continue;
872
873       if (arg[i].sym && (arg[i].sym->attr.optional
874                          || (p1 && strcmp (arg[i].sym->name, p1) == 0)))
875         continue;               /* Skip OPTIONAL and PASS arguments.  */
876
877       arg[i].flag = k;
878
879       /* Find other non-optional, non-pass arguments of the same type/rank.  */
880       for (j = i + 1; j < n1; j++)
881         if ((arg[j].sym == NULL
882              || !(arg[j].sym->attr.optional
883                   || (p1 && strcmp (arg[j].sym->name, p1) == 0)))
884             && (compare_type_rank_if (arg[i].sym, arg[j].sym)
885                 || compare_type_rank_if (arg[j].sym, arg[i].sym)))
886           arg[j].flag = k;
887
888       k++;
889     }
890
891   /* Now loop over each distinct type found in f1.  */
892   k = 0;
893   rc = 0;
894
895   for (i = 0; i < n1; i++)
896     {
897       if (arg[i].flag != k)
898         continue;
899
900       ac1 = 1;
901       for (j = i + 1; j < n1; j++)
902         if (arg[j].flag == k)
903           ac1++;
904
905       /* Count the number of non-pass arguments in f2 with that type,
906          including those that are optional.  */
907       ac2 = 0;
908
909       for (f = f2; f; f = f->next)
910         if ((!p2 || strcmp (f->sym->name, p2) != 0)
911             && (compare_type_rank_if (arg[i].sym, f->sym)
912                 || compare_type_rank_if (f->sym, arg[i].sym)))
913           ac2++;
914
915       if (ac1 > ac2)
916         {
917           rc = 1;
918           break;
919         }
920
921       k++;
922     }
923
924   free (arg);
925
926   return rc;
927 }
928
929
930 /* Perform the correspondence test in rule 3 of section F03:16.2.3.
931    Returns zero if no argument is found that satisfies rule 3, nonzero
932    otherwise. 'p1' and 'p2' are the PASS arguments of both procedures
933    (if applicable).
934
935    This test is also not symmetric in f1 and f2 and must be called
936    twice.  This test finds problems caused by sorting the actual
937    argument list with keywords.  For example:
938
939    INTERFACE FOO
940        SUBROUTINE F1(A, B)
941            INTEGER :: A ; REAL :: B
942        END SUBROUTINE F1
943
944        SUBROUTINE F2(B, A)
945            INTEGER :: A ; REAL :: B
946        END SUBROUTINE F1
947    END INTERFACE FOO
948
949    At this point, 'CALL FOO(A=1, B=1.0)' is ambiguous.  */
950
951 static int
952 generic_correspondence (gfc_formal_arglist *f1, gfc_formal_arglist *f2,
953                         const char *p1, const char *p2)
954 {
955   gfc_formal_arglist *f2_save, *g;
956   gfc_symbol *sym;
957
958   f2_save = f2;
959
960   while (f1)
961     {
962       if (f1->sym->attr.optional)
963         goto next;
964
965       if (p1 && strcmp (f1->sym->name, p1) == 0)
966         f1 = f1->next;
967       if (f2 && p2 && strcmp (f2->sym->name, p2) == 0)
968         f2 = f2->next;
969
970       if (f2 != NULL && (compare_type_rank (f1->sym, f2->sym)
971                          || compare_type_rank (f2->sym, f1->sym)))
972         goto next;
973
974       /* Now search for a disambiguating keyword argument starting at
975          the current non-match.  */
976       for (g = f1; g; g = g->next)
977         {
978           if (g->sym->attr.optional || (p1 && strcmp (g->sym->name, p1) == 0))
979             continue;
980
981           sym = find_keyword_arg (g->sym->name, f2_save);
982           if (sym == NULL || !compare_type_rank (g->sym, sym))
983             return 1;
984         }
985
986     next:
987       if (f1 != NULL)
988         f1 = f1->next;
989       if (f2 != NULL)
990         f2 = f2->next;
991     }
992
993   return 0;
994 }
995
996
997 /* Check if the characteristics of two dummy arguments match,
998    cf. F08:12.3.2.  */
999
1000 static gfc_try
1001 check_dummy_characteristics (gfc_symbol *s1, gfc_symbol *s2,
1002                              bool type_must_agree, char *errmsg, int err_len)
1003 {
1004   /* Check type and rank.  */
1005   if (type_must_agree && !compare_type_rank (s2, s1))
1006     {
1007       if (errmsg != NULL)
1008         snprintf (errmsg, err_len, "Type/rank mismatch in argument '%s'",
1009                   s1->name);
1010       return FAILURE;
1011     }
1012
1013   /* Check INTENT.  */
1014   if (s1->attr.intent != s2->attr.intent)
1015     {
1016       snprintf (errmsg, err_len, "INTENT mismatch in argument '%s'",
1017                 s1->name);
1018       return FAILURE;
1019     }
1020
1021   /* Check OPTIONAL attribute.  */
1022   if (s1->attr.optional != s2->attr.optional)
1023     {
1024       snprintf (errmsg, err_len, "OPTIONAL mismatch in argument '%s'",
1025                 s1->name);
1026       return FAILURE;
1027     }
1028
1029   /* Check ALLOCATABLE attribute.  */
1030   if (s1->attr.allocatable != s2->attr.allocatable)
1031     {
1032       snprintf (errmsg, err_len, "ALLOCATABLE mismatch in argument '%s'",
1033                 s1->name);
1034       return FAILURE;
1035     }
1036
1037   /* Check POINTER attribute.  */
1038   if (s1->attr.pointer != s2->attr.pointer)
1039     {
1040       snprintf (errmsg, err_len, "POINTER mismatch in argument '%s'",
1041                 s1->name);
1042       return FAILURE;
1043     }
1044
1045   /* Check TARGET attribute.  */
1046   if (s1->attr.target != s2->attr.target)
1047     {
1048       snprintf (errmsg, err_len, "TARGET mismatch in argument '%s'",
1049                 s1->name);
1050       return FAILURE;
1051     }
1052
1053   /* FIXME: Do more comprehensive testing of attributes, like e.g.
1054             ASYNCHRONOUS, CONTIGUOUS, VALUE, VOLATILE, etc.  */
1055
1056   /* Check string length.  */
1057   if (s1->ts.type == BT_CHARACTER
1058       && s1->ts.u.cl && s1->ts.u.cl->length
1059       && s2->ts.u.cl && s2->ts.u.cl->length)
1060     {
1061       int compval = gfc_dep_compare_expr (s1->ts.u.cl->length,
1062                                           s2->ts.u.cl->length);
1063       switch (compval)
1064       {
1065         case -1:
1066         case  1:
1067         case -3:
1068           snprintf (errmsg, err_len, "Character length mismatch "
1069                     "in argument '%s'", s1->name);
1070           return FAILURE;
1071
1072         case -2:
1073           /* FIXME: Implement a warning for this case.
1074           gfc_warning ("Possible character length mismatch in argument '%s'",
1075                        s1->name);*/
1076           break;
1077
1078         case 0:
1079           break;
1080
1081         default:
1082           gfc_internal_error ("check_dummy_characteristics: Unexpected result "
1083                               "%i of gfc_dep_compare_expr", compval);
1084           break;
1085       }
1086     }
1087
1088   /* Check array shape.  */
1089   if (s1->as && s2->as)
1090     {
1091       int i, compval;
1092       gfc_expr *shape1, *shape2;
1093
1094       if (s1->as->type != s2->as->type)
1095         {
1096           snprintf (errmsg, err_len, "Shape mismatch in argument '%s'",
1097                     s1->name);
1098           return FAILURE;
1099         }
1100
1101       if (s1->as->type == AS_EXPLICIT)
1102         for (i = 0; i < s1->as->rank + s1->as->corank; i++)
1103           {
1104             shape1 = gfc_subtract (gfc_copy_expr (s1->as->upper[i]),
1105                                   gfc_copy_expr (s1->as->lower[i]));
1106             shape2 = gfc_subtract (gfc_copy_expr (s2->as->upper[i]),
1107                                   gfc_copy_expr (s2->as->lower[i]));
1108             compval = gfc_dep_compare_expr (shape1, shape2);
1109             gfc_free_expr (shape1);
1110             gfc_free_expr (shape2);
1111             switch (compval)
1112             {
1113               case -1:
1114               case  1:
1115               case -3:
1116                 snprintf (errmsg, err_len, "Shape mismatch in dimension %i of "
1117                           "argument '%s'", i + 1, s1->name);
1118                 return FAILURE;
1119
1120               case -2:
1121                 /* FIXME: Implement a warning for this case.
1122                 gfc_warning ("Possible shape mismatch in argument '%s'",
1123                             s1->name);*/
1124                 break;
1125
1126               case 0:
1127                 break;
1128
1129               default:
1130                 gfc_internal_error ("check_dummy_characteristics: Unexpected "
1131                                     "result %i of gfc_dep_compare_expr",
1132                                     compval);
1133                 break;
1134             }
1135           }
1136     }
1137     
1138   return SUCCESS;
1139 }
1140
1141
1142 /* 'Compare' two formal interfaces associated with a pair of symbols.
1143    We return nonzero if there exists an actual argument list that
1144    would be ambiguous between the two interfaces, zero otherwise.
1145    'strict_flag' specifies whether all the characteristics are
1146    required to match, which is not the case for ambiguity checks.
1147    'p1' and 'p2' are the PASS arguments of both procedures (if applicable).  */
1148
1149 int
1150 gfc_compare_interfaces (gfc_symbol *s1, gfc_symbol *s2, const char *name2,
1151                         int generic_flag, int strict_flag,
1152                         char *errmsg, int err_len,
1153                         const char *p1, const char *p2)
1154 {
1155   gfc_formal_arglist *f1, *f2;
1156
1157   gcc_assert (name2 != NULL);
1158
1159   if (s1->attr.function && (s2->attr.subroutine
1160       || (!s2->attr.function && s2->ts.type == BT_UNKNOWN
1161           && gfc_get_default_type (name2, s2->ns)->type == BT_UNKNOWN)))
1162     {
1163       if (errmsg != NULL)
1164         snprintf (errmsg, err_len, "'%s' is not a function", name2);
1165       return 0;
1166     }
1167
1168   if (s1->attr.subroutine && s2->attr.function)
1169     {
1170       if (errmsg != NULL)
1171         snprintf (errmsg, err_len, "'%s' is not a subroutine", name2);
1172       return 0;
1173     }
1174
1175   /* Do strict checks on all characteristics
1176      (for dummy procedures and procedure pointer assignments).  */
1177   if (!generic_flag && strict_flag)
1178     {
1179       if (s1->attr.function && s2->attr.function)
1180         {
1181           /* If both are functions, check result type.  */
1182           if (s1->ts.type == BT_UNKNOWN)
1183             return 1;
1184           if (!compare_type_rank (s1,s2))
1185             {
1186               if (errmsg != NULL)
1187                 snprintf (errmsg, err_len, "Type/rank mismatch in return value "
1188                           "of '%s'", name2);
1189               return 0;
1190             }
1191
1192           /* FIXME: Check array bounds and string length of result.  */
1193         }
1194
1195       if (s1->attr.pure && !s2->attr.pure)
1196         {
1197           snprintf (errmsg, err_len, "Mismatch in PURE attribute");
1198           return 0;
1199         }
1200       if (s1->attr.elemental && !s2->attr.elemental)
1201         {
1202           snprintf (errmsg, err_len, "Mismatch in ELEMENTAL attribute");
1203           return 0;
1204         }
1205     }
1206
1207   if (s1->attr.if_source == IFSRC_UNKNOWN
1208       || s2->attr.if_source == IFSRC_UNKNOWN)
1209     return 1;
1210
1211   f1 = s1->formal;
1212   f2 = s2->formal;
1213
1214   if (f1 == NULL && f2 == NULL)
1215     return 1;                   /* Special case: No arguments.  */
1216
1217   if (generic_flag)
1218     {
1219       if (count_types_test (f1, f2, p1, p2)
1220           || count_types_test (f2, f1, p2, p1))
1221         return 0;
1222       if (generic_correspondence (f1, f2, p1, p2)
1223           || generic_correspondence (f2, f1, p2, p1))
1224         return 0;
1225     }
1226   else
1227     /* Perform the abbreviated correspondence test for operators (the
1228        arguments cannot be optional and are always ordered correctly).
1229        This is also done when comparing interfaces for dummy procedures and in
1230        procedure pointer assignments.  */
1231
1232     for (;;)
1233       {
1234         /* Check existence.  */
1235         if (f1 == NULL && f2 == NULL)
1236           break;
1237         if (f1 == NULL || f2 == NULL)
1238           {
1239             if (errmsg != NULL)
1240               snprintf (errmsg, err_len, "'%s' has the wrong number of "
1241                         "arguments", name2);
1242             return 0;
1243           }
1244
1245         if (strict_flag)
1246           {
1247             /* Check all characteristics.  */
1248             if (check_dummy_characteristics (f1->sym, f2->sym,
1249                                              true, errmsg, err_len) == FAILURE)
1250               return 0;
1251           }
1252         else if (!compare_type_rank (f2->sym, f1->sym))
1253           {
1254             /* Only check type and rank.  */
1255             if (errmsg != NULL)
1256               snprintf (errmsg, err_len, "Type/rank mismatch in argument '%s'",
1257                         f1->sym->name);
1258             return 0;
1259           }
1260
1261         f1 = f1->next;
1262         f2 = f2->next;
1263       }
1264
1265   return 1;
1266 }
1267
1268
1269 /* Given a pointer to an interface pointer, remove duplicate
1270    interfaces and make sure that all symbols are either functions
1271    or subroutines, and all of the same kind.  Returns nonzero if
1272    something goes wrong.  */
1273
1274 static int
1275 check_interface0 (gfc_interface *p, const char *interface_name)
1276 {
1277   gfc_interface *psave, *q, *qlast;
1278
1279   psave = p;
1280   for (; p; p = p->next)
1281     {
1282       /* Make sure all symbols in the interface have been defined as
1283          functions or subroutines.  */
1284       if (((!p->sym->attr.function && !p->sym->attr.subroutine)
1285            || !p->sym->attr.if_source)
1286           && p->sym->attr.flavor != FL_DERIVED)
1287         {
1288           if (p->sym->attr.external)
1289             gfc_error ("Procedure '%s' in %s at %L has no explicit interface",
1290                        p->sym->name, interface_name, &p->sym->declared_at);
1291           else
1292             gfc_error ("Procedure '%s' in %s at %L is neither function nor "
1293                        "subroutine", p->sym->name, interface_name,
1294                       &p->sym->declared_at);
1295           return 1;
1296         }
1297
1298       /* Verify that procedures are either all SUBROUTINEs or all FUNCTIONs.  */
1299       if ((psave->sym->attr.function && !p->sym->attr.function
1300            && p->sym->attr.flavor != FL_DERIVED)
1301           || (psave->sym->attr.subroutine && !p->sym->attr.subroutine))
1302         {
1303           if (p->sym->attr.flavor != FL_DERIVED)
1304             gfc_error ("In %s at %L procedures must be either all SUBROUTINEs"
1305                        " or all FUNCTIONs", interface_name,
1306                        &p->sym->declared_at);
1307           else
1308             gfc_error ("In %s at %L procedures must be all FUNCTIONs as the "
1309                        "generic name is also the name of a derived type",
1310                        interface_name, &p->sym->declared_at);
1311           return 1;
1312         }
1313
1314       /* F2003, C1207. F2008, C1207.  */
1315       if (p->sym->attr.proc == PROC_INTERNAL
1316           && gfc_notify_std (GFC_STD_F2008, "Internal procedure "
1317                              "'%s' in %s at %L", p->sym->name, interface_name,
1318                              &p->sym->declared_at) == FAILURE)
1319         return 1;
1320     }
1321   p = psave;
1322
1323   /* Remove duplicate interfaces in this interface list.  */
1324   for (; p; p = p->next)
1325     {
1326       qlast = p;
1327
1328       for (q = p->next; q;)
1329         {
1330           if (p->sym != q->sym)
1331             {
1332               qlast = q;
1333               q = q->next;
1334             }
1335           else
1336             {
1337               /* Duplicate interface.  */
1338               qlast->next = q->next;
1339               free (q);
1340               q = qlast->next;
1341             }
1342         }
1343     }
1344
1345   return 0;
1346 }
1347
1348
1349 /* Check lists of interfaces to make sure that no two interfaces are
1350    ambiguous.  Duplicate interfaces (from the same symbol) are OK here.  */
1351
1352 static int
1353 check_interface1 (gfc_interface *p, gfc_interface *q0,
1354                   int generic_flag, const char *interface_name,
1355                   bool referenced)
1356 {
1357   gfc_interface *q;
1358   for (; p; p = p->next)
1359     for (q = q0; q; q = q->next)
1360       {
1361         if (p->sym == q->sym)
1362           continue;             /* Duplicates OK here.  */
1363
1364         if (p->sym->name == q->sym->name && p->sym->module == q->sym->module)
1365           continue;
1366
1367         if (p->sym->attr.flavor != FL_DERIVED
1368             && q->sym->attr.flavor != FL_DERIVED
1369             && gfc_compare_interfaces (p->sym, q->sym, q->sym->name,
1370                                        generic_flag, 0, NULL, 0, NULL, NULL))
1371           {
1372             if (referenced)
1373               gfc_error ("Ambiguous interfaces '%s' and '%s' in %s at %L",
1374                          p->sym->name, q->sym->name, interface_name,
1375                          &p->where);
1376             else if (!p->sym->attr.use_assoc && q->sym->attr.use_assoc)
1377               gfc_warning ("Ambiguous interfaces '%s' and '%s' in %s at %L",
1378                            p->sym->name, q->sym->name, interface_name,
1379                            &p->where);
1380             else
1381               gfc_warning ("Although not referenced, '%s' has ambiguous "
1382                            "interfaces at %L", interface_name, &p->where);
1383             return 1;
1384           }
1385       }
1386   return 0;
1387 }
1388
1389
1390 /* Check the generic and operator interfaces of symbols to make sure
1391    that none of the interfaces conflict.  The check has to be done
1392    after all of the symbols are actually loaded.  */
1393
1394 static void
1395 check_sym_interfaces (gfc_symbol *sym)
1396 {
1397   char interface_name[100];
1398   gfc_interface *p;
1399
1400   if (sym->ns != gfc_current_ns)
1401     return;
1402
1403   if (sym->generic != NULL)
1404     {
1405       sprintf (interface_name, "generic interface '%s'", sym->name);
1406       if (check_interface0 (sym->generic, interface_name))
1407         return;
1408
1409       for (p = sym->generic; p; p = p->next)
1410         {
1411           if (sym->attr.access != ACCESS_PRIVATE)
1412             p->sym->attr.public_used = 1;
1413
1414           if (p->sym->attr.mod_proc
1415               && (p->sym->attr.if_source != IFSRC_DECL
1416                   || p->sym->attr.procedure))
1417             {
1418               gfc_error ("'%s' at %L is not a module procedure",
1419                          p->sym->name, &p->where);
1420               return;
1421             }
1422         }
1423
1424       /* Originally, this test was applied to host interfaces too;
1425          this is incorrect since host associated symbols, from any
1426          source, cannot be ambiguous with local symbols.  */
1427       check_interface1 (sym->generic, sym->generic, 1, interface_name,
1428                         sym->attr.referenced || !sym->attr.use_assoc);
1429     }
1430 }
1431
1432
1433 static void
1434 check_uop_interfaces (gfc_user_op *uop)
1435 {
1436   char interface_name[100];
1437   gfc_user_op *uop2;
1438   gfc_namespace *ns;
1439   gfc_interface *p;
1440
1441   sprintf (interface_name, "operator interface '%s'", uop->name);
1442   if (check_interface0 (uop->op, interface_name))
1443     return;
1444
1445   if (uop->access != ACCESS_PRIVATE)
1446     for (p = uop->op; p; p = p->next)
1447       p->sym->attr.public_used = 1;
1448
1449   for (ns = gfc_current_ns; ns; ns = ns->parent)
1450     {
1451       uop2 = gfc_find_uop (uop->name, ns);
1452       if (uop2 == NULL)
1453         continue;
1454
1455       check_interface1 (uop->op, uop2->op, 0,
1456                         interface_name, true);
1457     }
1458 }
1459
1460 /* Given an intrinsic op, return an equivalent op if one exists,
1461    or INTRINSIC_NONE otherwise.  */
1462
1463 gfc_intrinsic_op
1464 gfc_equivalent_op (gfc_intrinsic_op op)
1465 {
1466   switch(op)
1467     {
1468     case INTRINSIC_EQ:
1469       return INTRINSIC_EQ_OS;
1470
1471     case INTRINSIC_EQ_OS:
1472       return INTRINSIC_EQ;
1473
1474     case INTRINSIC_NE:
1475       return INTRINSIC_NE_OS;
1476
1477     case INTRINSIC_NE_OS:
1478       return INTRINSIC_NE;
1479
1480     case INTRINSIC_GT:
1481       return INTRINSIC_GT_OS;
1482
1483     case INTRINSIC_GT_OS:
1484       return INTRINSIC_GT;
1485
1486     case INTRINSIC_GE:
1487       return INTRINSIC_GE_OS;
1488
1489     case INTRINSIC_GE_OS:
1490       return INTRINSIC_GE;
1491
1492     case INTRINSIC_LT:
1493       return INTRINSIC_LT_OS;
1494
1495     case INTRINSIC_LT_OS:
1496       return INTRINSIC_LT;
1497
1498     case INTRINSIC_LE:
1499       return INTRINSIC_LE_OS;
1500
1501     case INTRINSIC_LE_OS:
1502       return INTRINSIC_LE;
1503
1504     default:
1505       return INTRINSIC_NONE;
1506     }
1507 }
1508
1509 /* For the namespace, check generic, user operator and intrinsic
1510    operator interfaces for consistency and to remove duplicate
1511    interfaces.  We traverse the whole namespace, counting on the fact
1512    that most symbols will not have generic or operator interfaces.  */
1513
1514 void
1515 gfc_check_interfaces (gfc_namespace *ns)
1516 {
1517   gfc_namespace *old_ns, *ns2;
1518   gfc_interface *p;
1519   char interface_name[100];
1520   int i;
1521
1522   old_ns = gfc_current_ns;
1523   gfc_current_ns = ns;
1524
1525   gfc_traverse_ns (ns, check_sym_interfaces);
1526
1527   gfc_traverse_user_op (ns, check_uop_interfaces);
1528
1529   for (i = GFC_INTRINSIC_BEGIN; i != GFC_INTRINSIC_END; i++)
1530     {
1531       if (i == INTRINSIC_USER)
1532         continue;
1533
1534       if (i == INTRINSIC_ASSIGN)
1535         strcpy (interface_name, "intrinsic assignment operator");
1536       else
1537         sprintf (interface_name, "intrinsic '%s' operator",
1538                  gfc_op2string ((gfc_intrinsic_op) i));
1539
1540       if (check_interface0 (ns->op[i], interface_name))
1541         continue;
1542
1543       for (p = ns->op[i]; p; p = p->next)
1544         p->sym->attr.public_used = 1;
1545
1546
1547       if (ns->op[i])
1548         gfc_check_operator_interface (ns->op[i]->sym, (gfc_intrinsic_op) i,
1549                                       ns->op[i]->where);
1550
1551       for (ns2 = ns; ns2; ns2 = ns2->parent)
1552         {
1553           gfc_intrinsic_op other_op;
1554           
1555           if (check_interface1 (ns->op[i], ns2->op[i], 0,
1556                                 interface_name, true))
1557             goto done;
1558
1559           /* i should be gfc_intrinsic_op, but has to be int with this cast
1560              here for stupid C++ compatibility rules.  */
1561           other_op = gfc_equivalent_op ((gfc_intrinsic_op) i);
1562           if (other_op != INTRINSIC_NONE
1563             &&  check_interface1 (ns->op[i], ns2->op[other_op],
1564                                   0, interface_name, true))
1565             goto done;
1566         }
1567     }
1568
1569 done:
1570   gfc_current_ns = old_ns;
1571 }
1572
1573
1574 static int
1575 symbol_rank (gfc_symbol *sym)
1576 {
1577   if (sym->ts.type == BT_CLASS && CLASS_DATA (sym)->as)
1578     return CLASS_DATA (sym)->as->rank;
1579
1580   return (sym->as == NULL) ? 0 : sym->as->rank;
1581 }
1582
1583
1584 /* Given a symbol of a formal argument list and an expression, if the
1585    formal argument is allocatable, check that the actual argument is
1586    allocatable. Returns nonzero if compatible, zero if not compatible.  */
1587
1588 static int
1589 compare_allocatable (gfc_symbol *formal, gfc_expr *actual)
1590 {
1591   symbol_attribute attr;
1592
1593   if (formal->attr.allocatable
1594       || (formal->ts.type == BT_CLASS && CLASS_DATA (formal)->attr.allocatable))
1595     {
1596       attr = gfc_expr_attr (actual);
1597       if (!attr.allocatable)
1598         return 0;
1599     }
1600
1601   return 1;
1602 }
1603
1604
1605 /* Given a symbol of a formal argument list and an expression, if the
1606    formal argument is a pointer, see if the actual argument is a
1607    pointer. Returns nonzero if compatible, zero if not compatible.  */
1608
1609 static int
1610 compare_pointer (gfc_symbol *formal, gfc_expr *actual)
1611 {
1612   symbol_attribute attr;
1613
1614   if (formal->attr.pointer
1615       || (formal->ts.type == BT_CLASS && CLASS_DATA (formal)
1616           && CLASS_DATA (formal)->attr.class_pointer))
1617     {
1618       attr = gfc_expr_attr (actual);
1619
1620       /* Fortran 2008 allows non-pointer actual arguments.  */
1621       if (!attr.pointer && attr.target && formal->attr.intent == INTENT_IN)
1622         return 2;
1623
1624       if (!attr.pointer)
1625         return 0;
1626     }
1627
1628   return 1;
1629 }
1630
1631
1632 /* Emit clear error messages for rank mismatch.  */
1633
1634 static void
1635 argument_rank_mismatch (const char *name, locus *where,
1636                         int rank1, int rank2)
1637 {
1638   if (rank1 == 0)
1639     {
1640       gfc_error ("Rank mismatch in argument '%s' at %L "
1641                  "(scalar and rank-%d)", name, where, rank2);
1642     }
1643   else if (rank2 == 0)
1644     {
1645       gfc_error ("Rank mismatch in argument '%s' at %L "
1646                  "(rank-%d and scalar)", name, where, rank1);
1647     }
1648   else
1649     {    
1650       gfc_error ("Rank mismatch in argument '%s' at %L "
1651                  "(rank-%d and rank-%d)", name, where, rank1, rank2);
1652     }
1653 }
1654
1655
1656 /* Given a symbol of a formal argument list and an expression, see if
1657    the two are compatible as arguments.  Returns nonzero if
1658    compatible, zero if not compatible.  */
1659
1660 static int
1661 compare_parameter (gfc_symbol *formal, gfc_expr *actual,
1662                    int ranks_must_agree, int is_elemental, locus *where)
1663 {
1664   gfc_ref *ref;
1665   bool rank_check, is_pointer;
1666
1667   /* If the formal arg has type BT_VOID, it's to one of the iso_c_binding
1668      procs c_f_pointer or c_f_procpointer, and we need to accept most
1669      pointers the user could give us.  This should allow that.  */
1670   if (formal->ts.type == BT_VOID)
1671     return 1;
1672
1673   if (formal->ts.type == BT_DERIVED
1674       && formal->ts.u.derived && formal->ts.u.derived->ts.is_iso_c
1675       && actual->ts.type == BT_DERIVED
1676       && actual->ts.u.derived && actual->ts.u.derived->ts.is_iso_c)
1677     return 1;
1678
1679   if (formal->ts.type == BT_CLASS && actual->ts.type == BT_DERIVED)
1680     /* Make sure the vtab symbol is present when
1681        the module variables are generated.  */
1682     gfc_find_derived_vtab (actual->ts.u.derived);
1683
1684   if (actual->ts.type == BT_PROCEDURE)
1685     {
1686       char err[200];
1687       gfc_symbol *act_sym = actual->symtree->n.sym;
1688
1689       if (formal->attr.flavor != FL_PROCEDURE)
1690         {
1691           if (where)
1692             gfc_error ("Invalid procedure argument at %L", &actual->where);
1693           return 0;
1694         }
1695
1696       if (!gfc_compare_interfaces (formal, act_sym, act_sym->name, 0, 1, err,
1697                                    sizeof(err), NULL, NULL))
1698         {
1699           if (where)
1700             gfc_error ("Interface mismatch in dummy procedure '%s' at %L: %s",
1701                        formal->name, &actual->where, err);
1702           return 0;
1703         }
1704
1705       if (formal->attr.function && !act_sym->attr.function)
1706         {
1707           gfc_add_function (&act_sym->attr, act_sym->name,
1708           &act_sym->declared_at);
1709           if (act_sym->ts.type == BT_UNKNOWN
1710               && gfc_set_default_type (act_sym, 1, act_sym->ns) == FAILURE)
1711             return 0;
1712         }
1713       else if (formal->attr.subroutine && !act_sym->attr.subroutine)
1714         gfc_add_subroutine (&act_sym->attr, act_sym->name,
1715                             &act_sym->declared_at);
1716
1717       return 1;
1718     }
1719
1720   /* F2008, C1241.  */
1721   if (formal->attr.pointer && formal->attr.contiguous
1722       && !gfc_is_simply_contiguous (actual, true))
1723     {
1724       if (where)
1725         gfc_error ("Actual argument to contiguous pointer dummy '%s' at %L "
1726                    "must be simply contigous", formal->name, &actual->where);
1727       return 0;
1728     }
1729
1730   if ((actual->expr_type != EXPR_NULL || actual->ts.type != BT_UNKNOWN)
1731       && actual->ts.type != BT_HOLLERITH
1732       && formal->ts.type != BT_ASSUMED
1733       && !gfc_compare_types (&formal->ts, &actual->ts)
1734       && !(formal->ts.type == BT_DERIVED && actual->ts.type == BT_CLASS
1735            && gfc_compare_derived_types (formal->ts.u.derived, 
1736                                          CLASS_DATA (actual)->ts.u.derived)))
1737     {
1738       if (where)
1739         gfc_error ("Type mismatch in argument '%s' at %L; passed %s to %s",
1740                    formal->name, &actual->where, gfc_typename (&actual->ts),
1741                    gfc_typename (&formal->ts));
1742       return 0;
1743     }
1744
1745   /* F2008, 12.5.2.5; IR F08/0073.  */
1746   if (formal->ts.type == BT_CLASS && actual->expr_type != EXPR_NULL
1747       && ((CLASS_DATA (formal)->attr.class_pointer
1748            && !formal->attr.intent == INTENT_IN)
1749           || CLASS_DATA (formal)->attr.allocatable))
1750     {
1751       if (actual->ts.type != BT_CLASS)
1752         {
1753           if (where)
1754             gfc_error ("Actual argument to '%s' at %L must be polymorphic",
1755                         formal->name, &actual->where);
1756           return 0;
1757         }
1758       if (!gfc_compare_derived_types (CLASS_DATA (actual)->ts.u.derived,
1759                                       CLASS_DATA (formal)->ts.u.derived))
1760         {
1761           if (where)
1762             gfc_error ("Actual argument to '%s' at %L must have the same "
1763                        "declared type", formal->name, &actual->where);
1764           return 0;
1765         }
1766     }
1767
1768   if (formal->attr.codimension && !gfc_is_coarray (actual))
1769     {
1770       if (where)
1771         gfc_error ("Actual argument to '%s' at %L must be a coarray",
1772                        formal->name, &actual->where);
1773       return 0;
1774     }
1775
1776   if (formal->attr.codimension && formal->attr.allocatable)
1777     {
1778       gfc_ref *last = NULL;
1779
1780       for (ref = actual->ref; ref; ref = ref->next)
1781         if (ref->type == REF_COMPONENT)
1782           last = ref;
1783
1784       /* F2008, 12.5.2.6.  */
1785       if ((last && last->u.c.component->as->corank != formal->as->corank)
1786           || (!last
1787               && actual->symtree->n.sym->as->corank != formal->as->corank))
1788         {
1789           if (where)
1790             gfc_error ("Corank mismatch in argument '%s' at %L (%d and %d)",
1791                    formal->name, &actual->where, formal->as->corank,
1792                    last ? last->u.c.component->as->corank
1793                         : actual->symtree->n.sym->as->corank);
1794           return 0;
1795         }
1796     }
1797
1798   if (formal->attr.codimension)
1799     {
1800       /* F2008, 12.5.2.8.  */
1801       if (formal->attr.dimension
1802           && (formal->attr.contiguous || formal->as->type != AS_ASSUMED_SHAPE)
1803           && gfc_expr_attr (actual).dimension
1804           && !gfc_is_simply_contiguous (actual, true))
1805         {
1806           if (where)
1807             gfc_error ("Actual argument to '%s' at %L must be simply "
1808                        "contiguous", formal->name, &actual->where);
1809           return 0;
1810         }
1811
1812       /* F2008, C1303 and C1304.  */
1813       if (formal->attr.intent != INTENT_INOUT
1814           && (((formal->ts.type == BT_DERIVED || formal->ts.type == BT_CLASS)
1815                && formal->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
1816                && formal->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
1817               || formal->attr.lock_comp))
1818
1819         {
1820           if (where)
1821             gfc_error ("Actual argument to non-INTENT(INOUT) dummy '%s' at %L, "
1822                        "which is LOCK_TYPE or has a LOCK_TYPE component",
1823                        formal->name, &actual->where);
1824           return 0;
1825         }
1826     }
1827
1828   /* F2008, C1239/C1240.  */
1829   if (actual->expr_type == EXPR_VARIABLE
1830       && (actual->symtree->n.sym->attr.asynchronous
1831          || actual->symtree->n.sym->attr.volatile_)
1832       &&  (formal->attr.asynchronous || formal->attr.volatile_)
1833       && actual->rank && !gfc_is_simply_contiguous (actual, true)
1834       && ((formal->as->type != AS_ASSUMED_SHAPE && !formal->attr.pointer)
1835           || formal->attr.contiguous))
1836     {
1837       if (where)
1838         gfc_error ("Dummy argument '%s' has to be a pointer or assumed-shape "
1839                    "array without CONTIGUOUS attribute - as actual argument at"
1840                    " %L is not simply contiguous and both are ASYNCHRONOUS "
1841                    "or VOLATILE", formal->name, &actual->where);
1842       return 0;
1843     }
1844
1845   if (formal->attr.allocatable && !formal->attr.codimension
1846       && gfc_expr_attr (actual).codimension)
1847     {
1848       if (formal->attr.intent == INTENT_OUT)
1849         {
1850           if (where)
1851             gfc_error ("Passing coarray at %L to allocatable, noncoarray, "
1852                        "INTENT(OUT) dummy argument '%s'", &actual->where,
1853                        formal->name);
1854             return 0;
1855         }
1856       else if (gfc_option.warn_surprising && where
1857                && formal->attr.intent != INTENT_IN)
1858         gfc_warning ("Passing coarray at %L to allocatable, noncoarray dummy "
1859                      "argument '%s', which is invalid if the allocation status"
1860                      " is modified",  &actual->where, formal->name);
1861     }
1862
1863   if (symbol_rank (formal) == actual->rank)
1864     return 1;
1865
1866   if (actual->ts.type == BT_CLASS && CLASS_DATA (actual)->as
1867         && CLASS_DATA (actual)->as->rank == symbol_rank (formal))
1868     return 1;
1869
1870   rank_check = where != NULL && !is_elemental && formal->as
1871                && (formal->as->type == AS_ASSUMED_SHAPE
1872                    || formal->as->type == AS_DEFERRED)
1873                && actual->expr_type != EXPR_NULL;
1874
1875   /* Scalar & coindexed, see: F2008, Section 12.5.2.4.  */
1876   if (rank_check || ranks_must_agree
1877       || (formal->attr.pointer && actual->expr_type != EXPR_NULL)
1878       || (actual->rank != 0 && !(is_elemental || formal->attr.dimension))
1879       || (actual->rank == 0
1880           && ((formal->ts.type == BT_CLASS
1881                && CLASS_DATA (formal)->as->type == AS_ASSUMED_SHAPE)
1882               || (formal->ts.type != BT_CLASS
1883                    && formal->as->type == AS_ASSUMED_SHAPE))
1884           && actual->expr_type != EXPR_NULL)
1885       || (actual->rank == 0 && formal->attr.dimension
1886           && gfc_is_coindexed (actual)))
1887     {
1888       if (where)
1889         argument_rank_mismatch (formal->name, &actual->where,
1890                                 symbol_rank (formal), actual->rank);
1891       return 0;
1892     }
1893   else if (actual->rank != 0 && (is_elemental || formal->attr.dimension))
1894     return 1;
1895
1896   /* At this point, we are considering a scalar passed to an array.   This
1897      is valid (cf. F95 12.4.1.1, F2003 12.4.1.2, and F2008 12.5.2.4),
1898      - if the actual argument is (a substring of) an element of a
1899        non-assumed-shape/non-pointer/non-polymorphic array; or
1900      - (F2003) if the actual argument is of type character of default/c_char
1901        kind.  */
1902
1903   is_pointer = actual->expr_type == EXPR_VARIABLE
1904                ? actual->symtree->n.sym->attr.pointer : false;
1905
1906   for (ref = actual->ref; ref; ref = ref->next)
1907     {
1908       if (ref->type == REF_COMPONENT)
1909         is_pointer = ref->u.c.component->attr.pointer;
1910       else if (ref->type == REF_ARRAY && ref->u.ar.type == AR_ELEMENT
1911                && ref->u.ar.dimen > 0
1912                && (!ref->next 
1913                    || (ref->next->type == REF_SUBSTRING && !ref->next->next)))
1914         break;
1915     }
1916
1917   if (actual->ts.type == BT_CLASS && actual->expr_type != EXPR_NULL)
1918     {
1919       if (where)
1920         gfc_error ("Polymorphic scalar passed to array dummy argument '%s' "
1921                    "at %L", formal->name, &actual->where);
1922       return 0;
1923     }
1924
1925   if (actual->expr_type != EXPR_NULL && ref && actual->ts.type != BT_CHARACTER
1926       && (is_pointer || ref->u.ar.as->type == AS_ASSUMED_SHAPE))
1927     {
1928       if (where)
1929         gfc_error ("Element of assumed-shaped or pointer "
1930                    "array passed to array dummy argument '%s' at %L",
1931                    formal->name, &actual->where);
1932       return 0;
1933     }
1934
1935   if (actual->ts.type == BT_CHARACTER && actual->expr_type != EXPR_NULL
1936       && (!ref || is_pointer || ref->u.ar.as->type == AS_ASSUMED_SHAPE))
1937     {
1938       if (formal->ts.kind != 1 && (gfc_option.allow_std & GFC_STD_GNU) == 0)
1939         {
1940           if (where)
1941             gfc_error ("Extension: Scalar non-default-kind, non-C_CHAR-kind "
1942                        "CHARACTER actual argument with array dummy argument "
1943                        "'%s' at %L", formal->name, &actual->where);
1944           return 0;
1945         }
1946
1947       if (where && (gfc_option.allow_std & GFC_STD_F2003) == 0)
1948         {
1949           gfc_error ("Fortran 2003: Scalar CHARACTER actual argument with "
1950                      "array dummy argument '%s' at %L",
1951                      formal->name, &actual->where);
1952           return 0;
1953         }
1954       else if ((gfc_option.allow_std & GFC_STD_F2003) == 0)
1955         return 0;
1956       else
1957         return 1;
1958     }
1959
1960   if (ref == NULL && actual->expr_type != EXPR_NULL)
1961     {
1962       if (where)
1963         argument_rank_mismatch (formal->name, &actual->where,
1964                                 symbol_rank (formal), actual->rank);
1965       return 0;
1966     }
1967
1968   return 1;
1969 }
1970
1971
1972 /* Returns the storage size of a symbol (formal argument) or
1973    zero if it cannot be determined.  */
1974
1975 static unsigned long
1976 get_sym_storage_size (gfc_symbol *sym)
1977 {
1978   int i;
1979   unsigned long strlen, elements;
1980
1981   if (sym->ts.type == BT_CHARACTER)
1982     {
1983       if (sym->ts.u.cl && sym->ts.u.cl->length
1984           && sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
1985         strlen = mpz_get_ui (sym->ts.u.cl->length->value.integer);
1986       else
1987         return 0;
1988     }
1989   else
1990     strlen = 1; 
1991
1992   if (symbol_rank (sym) == 0)
1993     return strlen;
1994
1995   elements = 1;
1996   if (sym->as->type != AS_EXPLICIT)
1997     return 0;
1998   for (i = 0; i < sym->as->rank; i++)
1999     {
2000       if (!sym->as || sym->as->upper[i]->expr_type != EXPR_CONSTANT
2001           || sym->as->lower[i]->expr_type != EXPR_CONSTANT)
2002         return 0;
2003
2004       elements *= mpz_get_si (sym->as->upper[i]->value.integer)
2005                   - mpz_get_si (sym->as->lower[i]->value.integer) + 1L;
2006     }
2007
2008   return strlen*elements;
2009 }
2010
2011
2012 /* Returns the storage size of an expression (actual argument) or
2013    zero if it cannot be determined. For an array element, it returns
2014    the remaining size as the element sequence consists of all storage
2015    units of the actual argument up to the end of the array.  */
2016
2017 static unsigned long
2018 get_expr_storage_size (gfc_expr *e)
2019 {
2020   int i;
2021   long int strlen, elements;
2022   long int substrlen = 0;
2023   bool is_str_storage = false;
2024   gfc_ref *ref;
2025
2026   if (e == NULL)
2027     return 0;
2028   
2029   if (e->ts.type == BT_CHARACTER)
2030     {
2031       if (e->ts.u.cl && e->ts.u.cl->length
2032           && e->ts.u.cl->length->expr_type == EXPR_CONSTANT)
2033         strlen = mpz_get_si (e->ts.u.cl->length->value.integer);
2034       else if (e->expr_type == EXPR_CONSTANT
2035                && (e->ts.u.cl == NULL || e->ts.u.cl->length == NULL))
2036         strlen = e->value.character.length;
2037       else
2038         return 0;
2039     }
2040   else
2041     strlen = 1; /* Length per element.  */
2042
2043   if (e->rank == 0 && !e->ref)
2044     return strlen;
2045
2046   elements = 1;
2047   if (!e->ref)
2048     {
2049       if (!e->shape)
2050         return 0;
2051       for (i = 0; i < e->rank; i++)
2052         elements *= mpz_get_si (e->shape[i]);
2053       return elements*strlen;
2054     }
2055
2056   for (ref = e->ref; ref; ref = ref->next)
2057     {
2058       if (ref->type == REF_SUBSTRING && ref->u.ss.start
2059           && ref->u.ss.start->expr_type == EXPR_CONSTANT)
2060         {
2061           if (is_str_storage)
2062             {
2063               /* The string length is the substring length.
2064                  Set now to full string length.  */
2065               if (!ref->u.ss.length || !ref->u.ss.length->length
2066                   || ref->u.ss.length->length->expr_type != EXPR_CONSTANT)
2067                 return 0;
2068
2069               strlen = mpz_get_ui (ref->u.ss.length->length->value.integer);
2070             }
2071           substrlen = strlen - mpz_get_ui (ref->u.ss.start->value.integer) + 1;
2072           continue;
2073         }
2074
2075       if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION
2076           && ref->u.ar.start && ref->u.ar.end && ref->u.ar.stride
2077           && ref->u.ar.as->upper)
2078         for (i = 0; i < ref->u.ar.dimen; i++)
2079           {
2080             long int start, end, stride;
2081             stride = 1;
2082
2083             if (ref->u.ar.stride[i])
2084               {
2085                 if (ref->u.ar.stride[i]->expr_type == EXPR_CONSTANT)
2086                   stride = mpz_get_si (ref->u.ar.stride[i]->value.integer);
2087                 else
2088                   return 0;
2089               }
2090
2091             if (ref->u.ar.start[i])
2092               {
2093                 if (ref->u.ar.start[i]->expr_type == EXPR_CONSTANT)
2094                   start = mpz_get_si (ref->u.ar.start[i]->value.integer);
2095                 else
2096                   return 0;
2097               }
2098             else if (ref->u.ar.as->lower[i]
2099                      && ref->u.ar.as->lower[i]->expr_type == EXPR_CONSTANT)
2100               start = mpz_get_si (ref->u.ar.as->lower[i]->value.integer);
2101             else
2102               return 0;
2103
2104             if (ref->u.ar.end[i])
2105               {
2106                 if (ref->u.ar.end[i]->expr_type == EXPR_CONSTANT)
2107                   end = mpz_get_si (ref->u.ar.end[i]->value.integer);
2108                 else
2109                   return 0;
2110               }
2111             else if (ref->u.ar.as->upper[i]
2112                      && ref->u.ar.as->upper[i]->expr_type == EXPR_CONSTANT)
2113               end = mpz_get_si (ref->u.ar.as->upper[i]->value.integer);
2114             else
2115               return 0;
2116
2117             elements *= (end - start)/stride + 1L;
2118           }
2119       else if (ref->type == REF_ARRAY && ref->u.ar.type == AR_FULL
2120                && ref->u.ar.as->lower && ref->u.ar.as->upper)
2121         for (i = 0; i < ref->u.ar.as->rank; i++)
2122           {
2123             if (ref->u.ar.as->lower[i] && ref->u.ar.as->upper[i]
2124                 && ref->u.ar.as->lower[i]->expr_type == EXPR_CONSTANT
2125                 && ref->u.ar.as->upper[i]->expr_type == EXPR_CONSTANT)
2126               elements *= mpz_get_si (ref->u.ar.as->upper[i]->value.integer)
2127                           - mpz_get_si (ref->u.ar.as->lower[i]->value.integer)
2128                           + 1L;
2129             else
2130               return 0;
2131           }
2132       else if (ref->type == REF_ARRAY && ref->u.ar.type == AR_ELEMENT
2133                && e->expr_type == EXPR_VARIABLE)
2134         {
2135           if (ref->u.ar.as->type == AS_ASSUMED_SHAPE
2136               || e->symtree->n.sym->attr.pointer)
2137             {
2138               elements = 1;
2139               continue;
2140             }
2141
2142           /* Determine the number of remaining elements in the element
2143              sequence for array element designators.  */
2144           is_str_storage = true;
2145           for (i = ref->u.ar.dimen - 1; i >= 0; i--)
2146             {
2147               if (ref->u.ar.start[i] == NULL
2148                   || ref->u.ar.start[i]->expr_type != EXPR_CONSTANT
2149                   || ref->u.ar.as->upper[i] == NULL
2150                   || ref->u.ar.as->lower[i] == NULL
2151                   || ref->u.ar.as->upper[i]->expr_type != EXPR_CONSTANT
2152                   || ref->u.ar.as->lower[i]->expr_type != EXPR_CONSTANT)
2153                 return 0;
2154
2155               elements
2156                    = elements
2157                      * (mpz_get_si (ref->u.ar.as->upper[i]->value.integer)
2158                         - mpz_get_si (ref->u.ar.as->lower[i]->value.integer)
2159                         + 1L)
2160                      - (mpz_get_si (ref->u.ar.start[i]->value.integer)
2161                         - mpz_get_si (ref->u.ar.as->lower[i]->value.integer));
2162             }
2163         }
2164     }
2165
2166   if (substrlen)
2167     return (is_str_storage) ? substrlen + (elements-1)*strlen
2168                             : elements*strlen;
2169   else
2170     return elements*strlen;
2171 }
2172
2173
2174 /* Given an expression, check whether it is an array section
2175    which has a vector subscript. If it has, one is returned,
2176    otherwise zero.  */
2177
2178 int
2179 gfc_has_vector_subscript (gfc_expr *e)
2180 {
2181   int i;
2182   gfc_ref *ref;
2183
2184   if (e == NULL || e->rank == 0 || e->expr_type != EXPR_VARIABLE)
2185     return 0;
2186
2187   for (ref = e->ref; ref; ref = ref->next)
2188     if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION)
2189       for (i = 0; i < ref->u.ar.dimen; i++)
2190         if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
2191           return 1;
2192
2193   return 0;
2194 }
2195
2196
2197 /* Given formal and actual argument lists, see if they are compatible.
2198    If they are compatible, the actual argument list is sorted to
2199    correspond with the formal list, and elements for missing optional
2200    arguments are inserted. If WHERE pointer is nonnull, then we issue
2201    errors when things don't match instead of just returning the status
2202    code.  */
2203
2204 static int
2205 compare_actual_formal (gfc_actual_arglist **ap, gfc_formal_arglist *formal,
2206                        int ranks_must_agree, int is_elemental, locus *where)
2207 {
2208   gfc_actual_arglist **new_arg, *a, *actual, temp;
2209   gfc_formal_arglist *f;
2210   int i, n, na;
2211   unsigned long actual_size, formal_size;
2212   bool full_array = false;
2213
2214   actual = *ap;
2215
2216   if (actual == NULL && formal == NULL)
2217     return 1;
2218
2219   n = 0;
2220   for (f = formal; f; f = f->next)
2221     n++;
2222
2223   new_arg = XALLOCAVEC (gfc_actual_arglist *, n);
2224
2225   for (i = 0; i < n; i++)
2226     new_arg[i] = NULL;
2227
2228   na = 0;
2229   f = formal;
2230   i = 0;
2231
2232   for (a = actual; a; a = a->next, f = f->next)
2233     {
2234       /* Look for keywords but ignore g77 extensions like %VAL.  */
2235       if (a->name != NULL && a->name[0] != '%')
2236         {
2237           i = 0;
2238           for (f = formal; f; f = f->next, i++)
2239             {
2240               if (f->sym == NULL)
2241                 continue;
2242               if (strcmp (f->sym->name, a->name) == 0)
2243                 break;
2244             }
2245
2246           if (f == NULL)
2247             {
2248               if (where)
2249                 gfc_error ("Keyword argument '%s' at %L is not in "
2250                            "the procedure", a->name, &a->expr->where);
2251               return 0;
2252             }
2253
2254           if (new_arg[i] != NULL)
2255             {
2256               if (where)
2257                 gfc_error ("Keyword argument '%s' at %L is already associated "
2258                            "with another actual argument", a->name,
2259                            &a->expr->where);
2260               return 0;
2261             }
2262         }
2263
2264       if (f == NULL)
2265         {
2266           if (where)
2267             gfc_error ("More actual than formal arguments in procedure "
2268                        "call at %L", where);
2269
2270           return 0;
2271         }
2272
2273       if (f->sym == NULL && a->expr == NULL)
2274         goto match;
2275
2276       if (f->sym == NULL)
2277         {
2278           if (where)
2279             gfc_error ("Missing alternate return spec in subroutine call "
2280                        "at %L", where);
2281           return 0;
2282         }
2283
2284       if (a->expr == NULL)
2285         {
2286           if (where)
2287             gfc_error ("Unexpected alternate return spec in subroutine "
2288                        "call at %L", where);
2289           return 0;
2290         }
2291
2292       if (a->expr->expr_type == EXPR_NULL
2293           && ((f->sym->ts.type != BT_CLASS && !f->sym->attr.pointer
2294                && (f->sym->attr.allocatable || !f->sym->attr.optional
2295                    || (gfc_option.allow_std & GFC_STD_F2008) == 0))
2296               || (f->sym->ts.type == BT_CLASS
2297                   && !CLASS_DATA (f->sym)->attr.class_pointer
2298                   && (CLASS_DATA (f->sym)->attr.allocatable
2299                       || !f->sym->attr.optional
2300                       || (gfc_option.allow_std & GFC_STD_F2008) == 0))))
2301         {
2302           if (where
2303               && (!f->sym->attr.optional
2304                   || (f->sym->ts.type != BT_CLASS && f->sym->attr.allocatable)
2305                   || (f->sym->ts.type == BT_CLASS
2306                          && CLASS_DATA (f->sym)->attr.allocatable)))
2307             gfc_error ("Unexpected NULL() intrinsic at %L to dummy '%s'",
2308                        where, f->sym->name);
2309           else if (where)
2310             gfc_error ("Fortran 2008: Null pointer at %L to non-pointer "
2311                        "dummy '%s'", where, f->sym->name);
2312
2313           return 0;
2314         }
2315       
2316       if (!compare_parameter (f->sym, a->expr, ranks_must_agree,
2317                               is_elemental, where))
2318         return 0;
2319
2320       /* TS 29113, 6.3p2.  */
2321       if (f->sym->ts.type == BT_ASSUMED
2322           && (a->expr->ts.type == BT_DERIVED
2323               || (a->expr->ts.type == BT_CLASS && CLASS_DATA (a->expr))))
2324         {
2325           gfc_namespace *f2k_derived;
2326
2327           f2k_derived = a->expr->ts.type == BT_DERIVED
2328                         ? a->expr->ts.u.derived->f2k_derived
2329                         : CLASS_DATA (a->expr)->ts.u.derived->f2k_derived;
2330
2331           if (f2k_derived
2332               && (f2k_derived->finalizers || f2k_derived->tb_sym_root))
2333             {
2334               gfc_error ("Actual argument at %L to assumed-type dummy is of "
2335                          "derived type with type-bound or FINAL procedures",
2336                          &a->expr->where);
2337               return FAILURE;
2338             }
2339         }
2340
2341       /* Special case for character arguments.  For allocatable, pointer
2342          and assumed-shape dummies, the string length needs to match
2343          exactly.  */
2344       if (a->expr->ts.type == BT_CHARACTER
2345            && a->expr->ts.u.cl && a->expr->ts.u.cl->length
2346            && a->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT
2347            && f->sym->ts.u.cl && f->sym->ts.u.cl && f->sym->ts.u.cl->length
2348            && f->sym->ts.u.cl->length->expr_type == EXPR_CONSTANT
2349            && (f->sym->attr.pointer || f->sym->attr.allocatable
2350                || (f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2351            && (mpz_cmp (a->expr->ts.u.cl->length->value.integer,
2352                         f->sym->ts.u.cl->length->value.integer) != 0))
2353          {
2354            if (where && (f->sym->attr.pointer || f->sym->attr.allocatable))
2355              gfc_warning ("Character length mismatch (%ld/%ld) between actual "
2356                           "argument and pointer or allocatable dummy argument "
2357                           "'%s' at %L",
2358                           mpz_get_si (a->expr->ts.u.cl->length->value.integer),
2359                           mpz_get_si (f->sym->ts.u.cl->length->value.integer),
2360                           f->sym->name, &a->expr->where);
2361            else if (where)
2362              gfc_warning ("Character length mismatch (%ld/%ld) between actual "
2363                           "argument and assumed-shape dummy argument '%s' "
2364                           "at %L",
2365                           mpz_get_si (a->expr->ts.u.cl->length->value.integer),
2366                           mpz_get_si (f->sym->ts.u.cl->length->value.integer),
2367                           f->sym->name, &a->expr->where);
2368            return 0;
2369          }
2370
2371       if ((f->sym->attr.pointer || f->sym->attr.allocatable)
2372             && f->sym->ts.deferred != a->expr->ts.deferred
2373             && a->expr->ts.type == BT_CHARACTER)
2374         {
2375           if (where)
2376             gfc_error ("Actual argument at %L to allocatable or "
2377                        "pointer dummy argument '%s' must have a deferred "
2378                        "length type parameter if and only if the dummy has one",
2379                        &a->expr->where, f->sym->name);
2380           return 0;
2381         }
2382
2383       if (f->sym->ts.type == BT_CLASS)
2384         goto skip_size_check;
2385
2386       actual_size = get_expr_storage_size (a->expr);
2387       formal_size = get_sym_storage_size (f->sym);
2388       if (actual_size != 0 && actual_size < formal_size
2389           && a->expr->ts.type != BT_PROCEDURE
2390           && f->sym->attr.flavor != FL_PROCEDURE)
2391         {
2392           if (a->expr->ts.type == BT_CHARACTER && !f->sym->as && where)
2393             gfc_warning ("Character length of actual argument shorter "
2394                          "than of dummy argument '%s' (%lu/%lu) at %L",
2395                          f->sym->name, actual_size, formal_size,
2396                          &a->expr->where);
2397           else if (where)
2398             gfc_warning ("Actual argument contains too few "
2399                          "elements for dummy argument '%s' (%lu/%lu) at %L",
2400                          f->sym->name, actual_size, formal_size,
2401                          &a->expr->where);
2402           return  0;
2403         }
2404
2405      skip_size_check:
2406
2407       /* Satisfy 12.4.1.3 by ensuring that a procedure pointer actual argument
2408          is provided for a procedure pointer formal argument.  */
2409       if (f->sym->attr.proc_pointer
2410           && !((a->expr->expr_type == EXPR_VARIABLE
2411                 && a->expr->symtree->n.sym->attr.proc_pointer)
2412                || (a->expr->expr_type == EXPR_FUNCTION
2413                    && a->expr->symtree->n.sym->result->attr.proc_pointer)
2414                || gfc_is_proc_ptr_comp (a->expr, NULL)))
2415         {
2416           if (where)
2417             gfc_error ("Expected a procedure pointer for argument '%s' at %L",
2418                        f->sym->name, &a->expr->where);
2419           return 0;
2420         }
2421
2422       /* Satisfy 12.4.1.2 by ensuring that a procedure actual argument is
2423          provided for a procedure formal argument.  */
2424       if (a->expr->ts.type != BT_PROCEDURE && !gfc_is_proc_ptr_comp (a->expr, NULL)
2425           && a->expr->expr_type == EXPR_VARIABLE
2426           && f->sym->attr.flavor == FL_PROCEDURE)
2427         {
2428           if (where)
2429             gfc_error ("Expected a procedure for argument '%s' at %L",
2430                        f->sym->name, &a->expr->where);
2431           return 0;
2432         }
2433
2434       if (f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE
2435           && a->expr->expr_type == EXPR_VARIABLE
2436           && a->expr->symtree->n.sym->as
2437           && a->expr->symtree->n.sym->as->type == AS_ASSUMED_SIZE
2438           && (a->expr->ref == NULL
2439               || (a->expr->ref->type == REF_ARRAY
2440                   && a->expr->ref->u.ar.type == AR_FULL)))
2441         {
2442           if (where)
2443             gfc_error ("Actual argument for '%s' cannot be an assumed-size"
2444                        " array at %L", f->sym->name, where);
2445           return 0;
2446         }
2447
2448       if (a->expr->expr_type != EXPR_NULL
2449           && compare_pointer (f->sym, a->expr) == 0)
2450         {
2451           if (where)
2452             gfc_error ("Actual argument for '%s' must be a pointer at %L",
2453                        f->sym->name, &a->expr->where);
2454           return 0;
2455         }
2456
2457       if (a->expr->expr_type != EXPR_NULL
2458           && (gfc_option.allow_std & GFC_STD_F2008) == 0
2459           && compare_pointer (f->sym, a->expr) == 2)
2460         {
2461           if (where)
2462             gfc_error ("Fortran 2008: Non-pointer actual argument at %L to "
2463                        "pointer dummy '%s'", &a->expr->where,f->sym->name);
2464           return 0;
2465         }
2466         
2467
2468       /* Fortran 2008, C1242.  */
2469       if (f->sym->attr.pointer && gfc_is_coindexed (a->expr))
2470         {
2471           if (where)
2472             gfc_error ("Coindexed actual argument at %L to pointer "
2473                        "dummy '%s'",
2474                        &a->expr->where, f->sym->name);
2475           return 0;
2476         }
2477
2478       /* Fortran 2008, 12.5.2.5 (no constraint).  */
2479       if (a->expr->expr_type == EXPR_VARIABLE
2480           && f->sym->attr.intent != INTENT_IN
2481           && f->sym->attr.allocatable
2482           && gfc_is_coindexed (a->expr))
2483         {
2484           if (where)
2485             gfc_error ("Coindexed actual argument at %L to allocatable "
2486                        "dummy '%s' requires INTENT(IN)",
2487                        &a->expr->where, f->sym->name);
2488           return 0;
2489         }
2490
2491       /* Fortran 2008, C1237.  */
2492       if (a->expr->expr_type == EXPR_VARIABLE
2493           && (f->sym->attr.asynchronous || f->sym->attr.volatile_)
2494           && gfc_is_coindexed (a->expr)
2495           && (a->expr->symtree->n.sym->attr.volatile_
2496               || a->expr->symtree->n.sym->attr.asynchronous))
2497         {
2498           if (where)
2499             gfc_error ("Coindexed ASYNCHRONOUS or VOLATILE actual argument at "
2500                        "%L requires that dummy '%s' has neither "
2501                        "ASYNCHRONOUS nor VOLATILE", &a->expr->where,
2502                        f->sym->name);
2503           return 0;
2504         }
2505
2506       /* Fortran 2008, 12.5.2.4 (no constraint).  */
2507       if (a->expr->expr_type == EXPR_VARIABLE
2508           && f->sym->attr.intent != INTENT_IN && !f->sym->attr.value
2509           && gfc_is_coindexed (a->expr)
2510           && gfc_has_ultimate_allocatable (a->expr))
2511         {
2512           if (where)
2513             gfc_error ("Coindexed actual argument at %L with allocatable "
2514                        "ultimate component to dummy '%s' requires either VALUE "
2515                        "or INTENT(IN)", &a->expr->where, f->sym->name);
2516           return 0;
2517         }
2518
2519      if (f->sym->ts.type == BT_CLASS
2520            && CLASS_DATA (f->sym)->attr.allocatable
2521            && gfc_is_class_array_ref (a->expr, &full_array)
2522            && !full_array)
2523         {
2524           if (where)
2525             gfc_error ("Actual CLASS array argument for '%s' must be a full "
2526                        "array at %L", f->sym->name, &a->expr->where);
2527           return 0;
2528         }
2529
2530
2531       if (a->expr->expr_type != EXPR_NULL
2532           && compare_allocatable (f->sym, a->expr) == 0)
2533         {
2534           if (where)
2535             gfc_error ("Actual argument for '%s' must be ALLOCATABLE at %L",
2536                        f->sym->name, &a->expr->where);
2537           return 0;
2538         }
2539
2540       /* Check intent = OUT/INOUT for definable actual argument.  */
2541       if ((f->sym->attr.intent == INTENT_OUT
2542           || f->sym->attr.intent == INTENT_INOUT))
2543         {
2544           const char* context = (where
2545                                  ? _("actual argument to INTENT = OUT/INOUT")
2546                                  : NULL);
2547
2548           if (((f->sym->ts.type == BT_CLASS && f->sym->attr.class_ok
2549                 && CLASS_DATA (f->sym)->attr.class_pointer)
2550                || (f->sym->ts.type != BT_CLASS && f->sym->attr.pointer))
2551               && gfc_check_vardef_context (a->expr, true, false, context)
2552                    == FAILURE)
2553             return 0;
2554           if (gfc_check_vardef_context (a->expr, false, false, context)
2555                 == FAILURE)
2556             return 0;
2557         }
2558
2559       if ((f->sym->attr.intent == INTENT_OUT
2560            || f->sym->attr.intent == INTENT_INOUT
2561            || f->sym->attr.volatile_
2562            || f->sym->attr.asynchronous)
2563           && gfc_has_vector_subscript (a->expr))
2564         {
2565           if (where)
2566             gfc_error ("Array-section actual argument with vector "
2567                        "subscripts at %L is incompatible with INTENT(OUT), "
2568                        "INTENT(INOUT), VOLATILE or ASYNCHRONOUS attribute "
2569                        "of the dummy argument '%s'",
2570                        &a->expr->where, f->sym->name);
2571           return 0;
2572         }
2573
2574       /* C1232 (R1221) For an actual argument which is an array section or
2575          an assumed-shape array, the dummy argument shall be an assumed-
2576          shape array, if the dummy argument has the VOLATILE attribute.  */
2577
2578       if (f->sym->attr.volatile_
2579           && a->expr->symtree->n.sym->as
2580           && a->expr->symtree->n.sym->as->type == AS_ASSUMED_SHAPE
2581           && !(f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2582         {
2583           if (where)
2584             gfc_error ("Assumed-shape actual argument at %L is "
2585                        "incompatible with the non-assumed-shape "
2586                        "dummy argument '%s' due to VOLATILE attribute",
2587                        &a->expr->where,f->sym->name);
2588           return 0;
2589         }
2590
2591       if (f->sym->attr.volatile_
2592           && a->expr->ref && a->expr->ref->u.ar.type == AR_SECTION
2593           && !(f->sym->as && f->sym->as->type == AS_ASSUMED_SHAPE))
2594         {
2595           if (where)
2596             gfc_error ("Array-section actual argument at %L is "
2597                        "incompatible with the non-assumed-shape "
2598                        "dummy argument '%s' due to VOLATILE attribute",
2599                        &a->expr->where,f->sym->name);
2600           return 0;
2601         }
2602
2603       /* C1233 (R1221) For an actual argument which is a pointer array, the
2604          dummy argument shall be an assumed-shape or pointer array, if the
2605          dummy argument has the VOLATILE attribute.  */
2606
2607       if (f->sym->attr.volatile_
2608           && a->expr->symtree->n.sym->attr.pointer
2609           && a->expr->symtree->n.sym->as
2610           && !(f->sym->as
2611                && (f->sym->as->type == AS_ASSUMED_SHAPE
2612                    || f->sym->attr.pointer)))
2613         {
2614           if (where)
2615             gfc_error ("Pointer-array actual argument at %L requires "
2616                        "an assumed-shape or pointer-array dummy "
2617                        "argument '%s' due to VOLATILE attribute",
2618                        &a->expr->where,f->sym->name);
2619           return 0;
2620         }
2621
2622     match:
2623       if (a == actual)
2624         na = i;
2625
2626       new_arg[i++] = a;
2627     }
2628
2629   /* Make sure missing actual arguments are optional.  */
2630   i = 0;
2631   for (f = formal; f; f = f->next, i++)
2632     {
2633       if (new_arg[i] != NULL)
2634         continue;
2635       if (f->sym == NULL)
2636         {
2637           if (where)
2638             gfc_error ("Missing alternate return spec in subroutine call "
2639                        "at %L", where);
2640           return 0;
2641         }
2642       if (!f->sym->attr.optional)
2643         {
2644           if (where)
2645             gfc_error ("Missing actual argument for argument '%s' at %L",
2646                        f->sym->name, where);
2647           return 0;
2648         }
2649     }
2650
2651   /* The argument lists are compatible.  We now relink a new actual
2652      argument list with null arguments in the right places.  The head
2653      of the list remains the head.  */
2654   for (i = 0; i < n; i++)
2655     if (new_arg[i] == NULL)
2656       new_arg[i] = gfc_get_actual_arglist ();
2657
2658   if (na != 0)
2659     {
2660       temp = *new_arg[0];
2661       *new_arg[0] = *actual;
2662       *actual = temp;
2663
2664       a = new_arg[0];
2665       new_arg[0] = new_arg[na];
2666       new_arg[na] = a;
2667     }
2668
2669   for (i = 0; i < n - 1; i++)
2670     new_arg[i]->next = new_arg[i + 1];
2671
2672   new_arg[i]->next = NULL;
2673
2674   if (*ap == NULL && n > 0)
2675     *ap = new_arg[0];
2676
2677   /* Note the types of omitted optional arguments.  */
2678   for (a = *ap, f = formal; a; a = a->next, f = f->next)
2679     if (a->expr == NULL && a->label == NULL)
2680       a->missing_arg_type = f->sym->ts.type;
2681
2682   return 1;
2683 }
2684
2685
2686 typedef struct
2687 {
2688   gfc_formal_arglist *f;
2689   gfc_actual_arglist *a;
2690 }
2691 argpair;
2692
2693 /* qsort comparison function for argument pairs, with the following
2694    order:
2695     - p->a->expr == NULL
2696     - p->a->expr->expr_type != EXPR_VARIABLE
2697     - growing p->a->expr->symbol.  */
2698
2699 static int
2700 pair_cmp (const void *p1, const void *p2)
2701 {
2702   const gfc_actual_arglist *a1, *a2;
2703
2704   /* *p1 and *p2 are elements of the to-be-sorted array.  */
2705   a1 = ((const argpair *) p1)->a;
2706   a2 = ((const argpair *) p2)->a;
2707   if (!a1->expr)
2708     {
2709       if (!a2->expr)
2710         return 0;
2711       return -1;
2712     }
2713   if (!a2->expr)
2714     return 1;
2715   if (a1->expr->expr_type != EXPR_VARIABLE)
2716     {
2717       if (a2->expr->expr_type != EXPR_VARIABLE)
2718         return 0;
2719       return -1;
2720     }
2721   if (a2->expr->expr_type != EXPR_VARIABLE)
2722     return 1;
2723   return a1->expr->symtree->n.sym < a2->expr->symtree->n.sym;
2724 }
2725
2726
2727 /* Given two expressions from some actual arguments, test whether they
2728    refer to the same expression. The analysis is conservative.
2729    Returning FAILURE will produce no warning.  */
2730
2731 static gfc_try
2732 compare_actual_expr (gfc_expr *e1, gfc_expr *e2)
2733 {
2734   const gfc_ref *r1, *r2;
2735
2736   if (!e1 || !e2
2737       || e1->expr_type != EXPR_VARIABLE
2738       || e2->expr_type != EXPR_VARIABLE
2739       || e1->symtree->n.sym != e2->symtree->n.sym)
2740     return FAILURE;
2741
2742   /* TODO: improve comparison, see expr.c:show_ref().  */
2743   for (r1 = e1->ref, r2 = e2->ref; r1 && r2; r1 = r1->next, r2 = r2->next)
2744     {
2745       if (r1->type != r2->type)
2746         return FAILURE;
2747       switch (r1->type)
2748         {
2749         case REF_ARRAY:
2750           if (r1->u.ar.type != r2->u.ar.type)
2751             return FAILURE;
2752           /* TODO: At the moment, consider only full arrays;
2753              we could do better.  */
2754           if (r1->u.ar.type != AR_FULL || r2->u.ar.type != AR_FULL)
2755             return FAILURE;
2756           break;
2757
2758         case REF_COMPONENT:
2759           if (r1->u.c.component != r2->u.c.component)
2760             return FAILURE;
2761           break;
2762
2763         case REF_SUBSTRING:
2764           return FAILURE;
2765
2766         default:
2767           gfc_internal_error ("compare_actual_expr(): Bad component code");
2768         }
2769     }
2770   if (!r1 && !r2)
2771     return SUCCESS;
2772   return FAILURE;
2773 }
2774
2775
2776 /* Given formal and actual argument lists that correspond to one
2777    another, check that identical actual arguments aren't not
2778    associated with some incompatible INTENTs.  */
2779
2780 static gfc_try
2781 check_some_aliasing (gfc_formal_arglist *f, gfc_actual_arglist *a)
2782 {
2783   sym_intent f1_intent, f2_intent;
2784   gfc_formal_arglist *f1;
2785   gfc_actual_arglist *a1;
2786   size_t n, i, j;
2787   argpair *p;
2788   gfc_try t = SUCCESS;
2789
2790   n = 0;
2791   for (f1 = f, a1 = a;; f1 = f1->next, a1 = a1->next)
2792     {
2793       if (f1 == NULL && a1 == NULL)
2794         break;
2795       if (f1 == NULL || a1 == NULL)
2796         gfc_internal_error ("check_some_aliasing(): List mismatch");
2797       n++;
2798     }
2799   if (n == 0)
2800     return t;
2801   p = XALLOCAVEC (argpair, n);
2802
2803   for (i = 0, f1 = f, a1 = a; i < n; i++, f1 = f1->next, a1 = a1->next)
2804     {
2805       p[i].f = f1;
2806       p[i].a = a1;
2807     }
2808
2809   qsort (p, n, sizeof (argpair), pair_cmp);
2810
2811   for (i = 0; i < n; i++)
2812     {
2813       if (!p[i].a->expr
2814           || p[i].a->expr->expr_type != EXPR_VARIABLE
2815           || p[i].a->expr->ts.type == BT_PROCEDURE)
2816         continue;
2817       f1_intent = p[i].f->sym->attr.intent;
2818       for (j = i + 1; j < n; j++)
2819         {
2820           /* Expected order after the sort.  */
2821           if (!p[j].a->expr || p[j].a->expr->expr_type != EXPR_VARIABLE)
2822             gfc_internal_error ("check_some_aliasing(): corrupted data");
2823
2824           /* Are the expression the same?  */
2825           if (compare_actual_expr (p[i].a->expr, p[j].a->expr) == FAILURE)
2826             break;
2827           f2_intent = p[j].f->sym->attr.intent;
2828           if ((f1_intent == INTENT_IN && f2_intent == INTENT_OUT)
2829               || (f1_intent == INTENT_OUT && f2_intent == INTENT_IN))
2830             {
2831               gfc_warning ("Same actual argument associated with INTENT(%s) "
2832                            "argument '%s' and INTENT(%s) argument '%s' at %L",
2833                            gfc_intent_string (f1_intent), p[i].f->sym->name,
2834                            gfc_intent_string (f2_intent), p[j].f->sym->name,
2835                            &p[i].a->expr->where);
2836               t = FAILURE;
2837             }
2838         }
2839     }
2840
2841   return t;
2842 }
2843
2844
2845 /* Given formal and actual argument lists that correspond to one
2846    another, check that they are compatible in the sense that intents
2847    are not mismatched.  */
2848
2849 static gfc_try
2850 check_intents (gfc_formal_arglist *f, gfc_actual_arglist *a)
2851 {
2852   sym_intent f_intent;
2853
2854   for (;; f = f->next, a = a->next)
2855     {
2856       if (f == NULL && a == NULL)
2857         break;
2858       if (f == NULL || a == NULL)
2859         gfc_internal_error ("check_intents(): List mismatch");
2860
2861       if (a->expr == NULL || a->expr->expr_type != EXPR_VARIABLE)
2862         continue;
2863
2864       f_intent = f->sym->attr.intent;
2865
2866       if (gfc_pure (NULL) && gfc_impure_variable (a->expr->symtree->n.sym))
2867         {
2868           if ((f->sym->ts.type == BT_CLASS && f->sym->attr.class_ok
2869                && CLASS_DATA (f->sym)->attr.class_pointer)
2870               || (f->sym->ts.type != BT_CLASS && f->sym->attr.pointer))
2871             {
2872               gfc_error ("Procedure argument at %L is local to a PURE "
2873                          "procedure and has the POINTER attribute",
2874                          &a->expr->where);
2875               return FAILURE;
2876             }
2877         }
2878
2879        /* Fortran 2008, C1283.  */
2880        if (gfc_pure (NULL) && gfc_is_coindexed (a->expr))
2881         {
2882           if (f_intent == INTENT_INOUT || f_intent == INTENT_OUT)
2883             {
2884               gfc_error ("Coindexed actual argument at %L in PURE procedure "
2885                          "is passed to an INTENT(%s) argument",
2886                          &a->expr->where, gfc_intent_string (f_intent));
2887               return FAILURE;
2888             }
2889
2890           if ((f->sym->ts.type == BT_CLASS && f->sym->attr.class_ok
2891                && CLASS_DATA (f->sym)->attr.class_pointer)
2892               || (f->sym->ts.type != BT_CLASS && f->sym->attr.pointer))
2893             {
2894               gfc_error ("Coindexed actual argument at %L in PURE procedure "
2895                          "is passed to a POINTER dummy argument",
2896                          &a->expr->where);
2897               return FAILURE;
2898             }
2899         }
2900
2901        /* F2008, Section 12.5.2.4.  */
2902        if (a->expr->ts.type == BT_CLASS && f->sym->ts.type == BT_CLASS
2903            && gfc_is_coindexed (a->expr))
2904          {
2905            gfc_error ("Coindexed polymorphic actual argument at %L is passed "
2906                       "polymorphic dummy argument '%s'",
2907                          &a->expr->where, f->sym->name);
2908            return FAILURE;
2909          }
2910     }
2911
2912   return SUCCESS;
2913 }
2914
2915
2916 /* Check how a procedure is used against its interface.  If all goes
2917    well, the actual argument list will also end up being properly
2918    sorted.  */
2919
2920 void
2921 gfc_procedure_use (gfc_symbol *sym, gfc_actual_arglist **ap, locus *where)
2922 {
2923   /* Warn about calls with an implicit interface.  Special case
2924      for calling a ISO_C_BINDING becase c_loc and c_funloc
2925      are pseudo-unknown.  Additionally, warn about procedures not
2926      explicitly declared at all if requested.  */
2927   if (sym->attr.if_source == IFSRC_UNKNOWN && ! sym->attr.is_iso_c)
2928     {
2929       if (gfc_option.warn_implicit_interface)
2930         gfc_warning ("Procedure '%s' called with an implicit interface at %L",
2931                      sym->name, where);
2932       else if (gfc_option.warn_implicit_procedure
2933                && sym->attr.proc == PROC_UNKNOWN)
2934         gfc_warning ("Procedure '%s' called at %L is not explicitly declared",
2935                      sym->name, where);
2936     }
2937
2938   if (sym->attr.if_source == IFSRC_UNKNOWN)
2939     {
2940       gfc_actual_arglist *a;
2941
2942       if (sym->attr.pointer)
2943         {
2944           gfc_error("The pointer object '%s' at %L must have an explicit "
2945                     "function interface or be declared as array",
2946                     sym->name, where);
2947           return;
2948         }
2949
2950       if (sym->attr.allocatable && !sym->attr.external)
2951         {
2952           gfc_error("The allocatable object '%s' at %L must have an explicit "
2953                     "function interface or be declared as array",
2954                     sym->name, where);
2955           return;
2956         }
2957
2958       if (sym->attr.allocatable)
2959         {
2960           gfc_error("Allocatable function '%s' at %L must have an explicit "
2961                     "function interface", sym->name, where);
2962           return;
2963         }
2964
2965       for (a = *ap; a; a = a->next)
2966         {
2967           /* Skip g77 keyword extensions like %VAL, %REF, %LOC.  */
2968           if (a->name != NULL && a->name[0] != '%')
2969             {
2970               gfc_error("Keyword argument requires explicit interface "
2971                         "for procedure '%s' at %L", sym->name, &a->expr->where);
2972               break;
2973             }
2974
2975           /* TS 29113, 6.2.  */
2976           if (a->expr && a->expr->ts.type == BT_ASSUMED
2977               && sym->intmod_sym_id != ISOCBINDING_LOC)
2978             {
2979               gfc_error ("Assumed-type argument %s at %L requires an explicit "
2980                          "interface", a->expr->symtree->n.sym->name,
2981                          &a->expr->where);
2982               break;
2983             }
2984
2985           /* F2008, C1303 and C1304.  */
2986           if (a->expr
2987               && (a->expr->ts.type == BT_DERIVED || a->expr->ts.type == BT_CLASS)
2988               && ((a->expr->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
2989                    && a->expr->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)
2990                   || gfc_expr_attr (a->expr).lock_comp))
2991             {
2992               gfc_error("Actual argument of LOCK_TYPE or with LOCK_TYPE "
2993                         "component at %L requires an explicit interface for "
2994                         "procedure '%s'", &a->expr->where, sym->name);
2995               break;
2996             }
2997
2998           if (a->expr && a->expr->expr_type == EXPR_NULL
2999               && a->expr->ts.type == BT_UNKNOWN)
3000             {
3001               gfc_error ("MOLD argument to NULL required at %L", &a->expr->where);
3002               return;
3003             }
3004         }
3005
3006       return;
3007     }
3008
3009   if (!compare_actual_formal (ap, sym->formal, 0, sym->attr.elemental, where))
3010     return;
3011
3012   check_intents (sym->formal, *ap);
3013   if (gfc_option.warn_aliasing)
3014     check_some_aliasing (sym->formal, *ap);
3015 }
3016
3017
3018 /* Check how a procedure pointer component is used against its interface.
3019    If all goes well, the actual argument list will also end up being properly
3020    sorted. Completely analogous to gfc_procedure_use.  */
3021
3022 void
3023 gfc_ppc_use (gfc_component *comp, gfc_actual_arglist **ap, locus *where)
3024 {
3025
3026   /* Warn about calls with an implicit interface.  Special case
3027      for calling a ISO_C_BINDING becase c_loc and c_funloc
3028      are pseudo-unknown.  */
3029   if (gfc_option.warn_implicit_interface
3030       && comp->attr.if_source == IFSRC_UNKNOWN
3031       && !comp->attr.is_iso_c)
3032     gfc_warning ("Procedure pointer component '%s' called with an implicit "
3033                  "interface at %L", comp->name, where);
3034
3035   if (comp->attr.if_source == IFSRC_UNKNOWN)
3036     {
3037       gfc_actual_arglist *a;
3038       for (a = *ap; a; a = a->next)
3039         {
3040           /* Skip g77 keyword extensions like %VAL, %REF, %LOC.  */
3041           if (a->name != NULL && a->name[0] != '%')
3042             {
3043               gfc_error("Keyword argument requires explicit interface "
3044                         "for procedure pointer component '%s' at %L",
3045                         comp->name, &a->expr->where);
3046               break;
3047             }
3048         }
3049
3050       return;
3051     }
3052
3053   if (!compare_actual_formal (ap, comp->formal, 0, comp->attr.elemental, where))
3054     return;
3055
3056   check_intents (comp->formal, *ap);
3057   if (gfc_option.warn_aliasing)
3058     check_some_aliasing (comp->formal, *ap);
3059 }
3060
3061
3062 /* Try if an actual argument list matches the formal list of a symbol,
3063    respecting the symbol's attributes like ELEMENTAL.  This is used for
3064    GENERIC resolution.  */
3065
3066 bool
3067 gfc_arglist_matches_symbol (gfc_actual_arglist** args, gfc_symbol* sym)
3068 {
3069   bool r;
3070
3071   gcc_assert (sym->attr.flavor == FL_PROCEDURE);
3072
3073   r = !sym->attr.elemental;
3074   if (compare_actual_formal (args, sym->formal, r, !r, NULL))
3075     {
3076       check_intents (sym->formal, *args);
3077       if (gfc_option.warn_aliasing)
3078         check_some_aliasing (sym->formal, *args);
3079       return true;
3080     }
3081
3082   return false;
3083 }
3084
3085
3086 /* Given an interface pointer and an actual argument list, search for
3087    a formal argument list that matches the actual.  If found, returns
3088    a pointer to the symbol of the correct interface.  Returns NULL if
3089    not found.  */
3090
3091 gfc_symbol *
3092 gfc_search_interface (gfc_interface *intr, int sub_flag,
3093                       gfc_actual_arglist **ap)
3094 {
3095   gfc_symbol *elem_sym = NULL;
3096   gfc_symbol *null_sym = NULL;
3097   locus null_expr_loc;
3098   gfc_actual_arglist *a;
3099   bool has_null_arg = false;
3100
3101   for (a = *ap; a; a = a->next)
3102     if (a->expr && a->expr->expr_type == EXPR_NULL
3103         && a->expr->ts.type == BT_UNKNOWN)
3104       {
3105         has_null_arg = true;
3106         null_expr_loc = a->expr->where;
3107         break;
3108       } 
3109
3110   for (; intr; intr = intr->next)
3111     {
3112       if (intr->sym->attr.flavor == FL_DERIVED)
3113         continue;
3114       if (sub_flag && intr->sym->attr.function)
3115         continue;
3116       if (!sub_flag && intr->sym->attr.subroutine)
3117         continue;
3118
3119       if (gfc_arglist_matches_symbol (ap, intr->sym))
3120         {
3121           if (has_null_arg && null_sym)
3122             {
3123               gfc_error ("MOLD= required in NULL() argument at %L: Ambiguity "
3124                          "between specific functions %s and %s",
3125                          &null_expr_loc, null_sym->name, intr->sym->name);
3126               return NULL;
3127             }
3128           else if (has_null_arg)
3129             {
3130               null_sym = intr->sym;
3131               continue;
3132             }
3133
3134           /* Satisfy 12.4.4.1 such that an elemental match has lower
3135              weight than a non-elemental match.  */ 
3136           if (intr->sym->attr.elemental)
3137             {
3138               elem_sym = intr->sym;
3139               continue;
3140             }
3141           return intr->sym;
3142         }
3143     }
3144
3145   if (null_sym)
3146     return null_sym;
3147
3148   return elem_sym ? elem_sym : NULL;
3149 }
3150
3151
3152 /* Do a brute force recursive search for a symbol.  */
3153
3154 static gfc_symtree *
3155 find_symtree0 (gfc_symtree *root, gfc_symbol *sym)
3156 {
3157   gfc_symtree * st;
3158
3159   if (root->n.sym == sym)
3160     return root;
3161
3162   st = NULL;
3163   if (root->left)
3164     st = find_symtree0 (root->left, sym);
3165   if (root->right && ! st)
3166     st = find_symtree0 (root->right, sym);
3167   return st;
3168 }
3169
3170
3171 /* Find a symtree for a symbol.  */
3172
3173 gfc_symtree *
3174 gfc_find_sym_in_symtree (gfc_symbol *sym)
3175 {
3176   gfc_symtree *st;
3177   gfc_namespace *ns;
3178
3179   /* First try to find it by name.  */
3180   gfc_find_sym_tree (sym->name, gfc_current_ns, 1, &st);
3181   if (st && st->n.sym == sym)
3182     return st;
3183
3184   /* If it's been renamed, resort to a brute-force search.  */
3185   /* TODO: avoid having to do this search.  If the symbol doesn't exist
3186      in the symtree for the current namespace, it should probably be added.  */
3187   for (ns = gfc_current_ns; ns; ns = ns->parent)
3188     {
3189       st = find_symtree0 (ns->sym_root, sym);
3190       if (st)
3191         return st;
3192     }
3193   gfc_internal_error ("Unable to find symbol %s", sym->name);
3194   /* Not reached.  */
3195 }
3196
3197
3198 /* See if the arglist to an operator-call contains a derived-type argument
3199    with a matching type-bound operator.  If so, return the matching specific
3200    procedure defined as operator-target as well as the base-object to use
3201    (which is the found derived-type argument with operator).  The generic
3202    name, if any, is transmitted to the final expression via 'gname'.  */
3203
3204 static gfc_typebound_proc*
3205 matching_typebound_op (gfc_expr** tb_base,
3206                        gfc_actual_arglist* args,
3207                        gfc_intrinsic_op op, const char* uop,
3208                        const char ** gname)
3209 {
3210   gfc_actual_arglist* base;
3211
3212   for (base = args; base; base = base->next)
3213     if (base->expr->ts.type == BT_DERIVED || base->expr->ts.type == BT_CLASS)
3214       {
3215         gfc_typebound_proc* tb;
3216         gfc_symbol* derived;
3217         gfc_try result;
3218
3219         while (base->expr->expr_type == EXPR_OP
3220                && base->expr->value.op.op == INTRINSIC_PARENTHESES)
3221           base->expr = base->expr->value.op.op1;
3222
3223         if (base->expr->ts.type == BT_CLASS)
3224           {
3225             if (CLASS_DATA (base->expr) == NULL)
3226               continue;
3227             derived = CLASS_DATA (base->expr)->ts.u.derived;
3228           }
3229         else
3230           derived = base->expr->ts.u.derived;
3231
3232         if (op == INTRINSIC_USER)
3233           {
3234             gfc_symtree* tb_uop;
3235
3236             gcc_assert (uop);
3237             tb_uop = gfc_find_typebound_user_op (derived, &result, uop,
3238                                                  false, NULL);
3239
3240             if (tb_uop)
3241               tb = tb_uop->n.tb;
3242             else
3243               tb = NULL;
3244           }
3245         else
3246           tb = gfc_find_typebound_intrinsic_op (derived, &result, op,
3247                                                 false, NULL);
3248
3249         /* This means we hit a PRIVATE operator which is use-associated and
3250            should thus not be seen.  */
3251         if (result == FAILURE)
3252           tb = NULL;
3253
3254         /* Look through the super-type hierarchy for a matching specific
3255            binding.  */
3256         for (; tb; tb = tb->overridden)
3257           {
3258             gfc_tbp_generic* g;
3259
3260             gcc_assert (tb->is_generic);
3261             for (g = tb->u.generic; g; g = g->next)
3262               {
3263                 gfc_symbol* target;
3264                 gfc_actual_arglist* argcopy;
3265                 bool matches;
3266
3267                 gcc_assert (g->specific);
3268                 if (g->specific->error)
3269                   continue;
3270
3271                 target = g->specific->u.specific->n.sym;
3272
3273                 /* Check if this arglist matches the formal.  */
3274                 argcopy = gfc_copy_actual_arglist (args);
3275                 matches = gfc_arglist_matches_symbol (&argcopy, target);
3276                 gfc_free_actual_arglist (argcopy);
3277
3278                 /* Return if we found a match.  */
3279                 if (matches)
3280                   {
3281                     *tb_base = base->expr;
3282                     *gname = g->specific_st->name;
3283                     return g->specific;
3284                   }
3285               }
3286           }
3287       }
3288
3289   return NULL;
3290 }
3291
3292
3293 /* For the 'actual arglist' of an operator call and a specific typebound
3294    procedure that has been found the target of a type-bound operator, build the
3295    appropriate EXPR_COMPCALL and resolve it.  We take this indirection over
3296    type-bound procedures rather than resolving type-bound operators 'directly'
3297    so that we can reuse the existing logic.  */
3298
3299 static void
3300 build_compcall_for_operator (gfc_expr* e, gfc_actual_arglist* actual,
3301                              gfc_expr* base, gfc_typebound_proc* target,
3302                              const char *gname)
3303 {
3304   e->expr_type = EXPR_COMPCALL;
3305   e->value.compcall.tbp = target;
3306   e->value.compcall.name = gname ? gname : "$op";
3307   e->value.compcall.actual = actual;
3308   e->value.compcall.base_object = base;
3309   e->value.compcall.ignore_pass = 1;
3310   e->value.compcall.assign = 0;
3311   if (e->ts.type == BT_UNKNOWN
3312         && target->function)
3313     {
3314       if (target->is_generic)
3315         e->ts = target->u.generic->specific->u.specific->n.sym->ts;
3316       else
3317         e->ts = target->u.specific->n.sym->ts;
3318     }
3319 }
3320
3321
3322 /* This subroutine is called when an expression is being resolved.
3323    The expression node in question is either a user defined operator
3324    or an intrinsic operator with arguments that aren't compatible
3325    with the operator.  This subroutine builds an actual argument list
3326    corresponding to the operands, then searches for a compatible
3327    interface.  If one is found, the expression node is replaced with
3328    the appropriate function call. We use the 'match' enum to specify
3329    whether a replacement has been made or not, or if an error occurred.  */
3330
3331 match
3332 gfc_extend_expr (gfc_expr *e)
3333 {
3334   gfc_actual_arglist *actual;
3335   gfc_symbol *sym;
3336   gfc_namespace *ns;
3337   gfc_user_op *uop;
3338   gfc_intrinsic_op i;
3339   const char *gname;
3340
3341   sym = NULL;
3342
3343   actual = gfc_get_actual_arglist ();
3344   actual->expr = e->value.op.op1;
3345
3346   gname = NULL;
3347
3348   if (e->value.op.op2 != NULL)
3349     {
3350       actual->next = gfc_get_actual_arglist ();
3351       actual->next->expr = e->value.op.op2;
3352     }
3353
3354   i = fold_unary_intrinsic (e->value.op.op);
3355
3356   if (i == INTRINSIC_USER)
3357     {
3358       for (ns = gfc_current_ns; ns; ns = ns->parent)
3359         {
3360           uop = gfc_find_uop (e->value.op.uop->name, ns);
3361           if (uop == NULL)
3362             continue;
3363
3364           sym = gfc_search_interface (uop->op, 0, &actual);
3365           if (sym != NULL)
3366             break;
3367         }
3368     }
3369   else
3370     {
3371       for (ns = gfc_current_ns; ns; ns = ns->parent)
3372         {
3373           /* Due to the distinction between '==' and '.eq.' and friends, one has
3374              to check if either is defined.  */
3375           switch (i)
3376             {
3377 #define CHECK_OS_COMPARISON(comp) \
3378   case INTRINSIC_##comp: \
3379   case INTRINSIC_##comp##_OS: \
3380     sym = gfc_search_interface (ns->op[INTRINSIC_##comp], 0, &actual); \
3381     if (!sym) \
3382       sym = gfc_search_interface (ns->op[INTRINSIC_##comp##_OS], 0, &actual); \
3383     break;
3384               CHECK_OS_COMPARISON(EQ)
3385               CHECK_OS_COMPARISON(NE)
3386               CHECK_OS_COMPARISON(GT)
3387               CHECK_OS_COMPARISON(GE)
3388               CHECK_OS_COMPARISON(LT)
3389               CHECK_OS_COMPARISON(LE)
3390 #undef CHECK_OS_COMPARISON
3391
3392               default:
3393                 sym = gfc_search_interface (ns->op[i], 0, &actual);
3394             }
3395
3396           if (sym != NULL)
3397             break;
3398         }
3399     }
3400
3401   /* TODO: Do an ambiguity-check and error if multiple matching interfaces are
3402      found rather than just taking the first one and not checking further.  */
3403
3404   if (sym == NULL)
3405     {
3406       gfc_typebound_proc* tbo;
3407       gfc_expr* tb_base;
3408
3409       /* See if we find a matching type-bound operator.  */
3410       if (i == INTRINSIC_USER)
3411         tbo = matching_typebound_op (&tb_base, actual,
3412                                      i, e->value.op.uop->name, &gname);
3413       else
3414         switch (i)
3415           {
3416 #define CHECK_OS_COMPARISON(comp) \
3417   case INTRINSIC_##comp: \
3418   case INTRINSIC_##comp##_OS: \
3419     tbo = matching_typebound_op (&tb_base, actual, \
3420                                  INTRINSIC_##comp, NULL, &gname); \
3421     if (!tbo) \
3422       tbo = matching_typebound_op (&tb_base, actual, \
3423                                    INTRINSIC_##comp##_OS, NULL, &gname); \
3424     break;
3425             CHECK_OS_COMPARISON(EQ)
3426             CHECK_OS_COMPARISON(NE)
3427             CHECK_OS_COMPARISON(GT)
3428             CHECK_OS_COMPARISON(GE)
3429             CHECK_OS_COMPARISON(LT)
3430             CHECK_OS_COMPARISON(LE)
3431 #undef CHECK_OS_COMPARISON
3432
3433             default:
3434               tbo = matching_typebound_op (&tb_base, actual, i, NULL, &gname);
3435               break;
3436           }
3437               
3438       /* If there is a matching typebound-operator, replace the expression with
3439          a call to it and succeed.  */
3440       if (tbo)
3441         {
3442           gfc_try result;
3443
3444           gcc_assert (tb_base);
3445           build_compcall_for_operator (e, actual, tb_base, tbo, gname);
3446
3447           result = gfc_resolve_expr (e);
3448           if (result == FAILURE)
3449             return MATCH_ERROR;
3450
3451           return MATCH_YES;
3452         }
3453
3454       /* Don't use gfc_free_actual_arglist().  */
3455       free (actual->next);
3456       free (actual);
3457
3458       return MATCH_NO;
3459     }
3460
3461   /* Change the expression node to a function call.  */
3462   e->expr_type = EXPR_FUNCTION;
3463   e->symtree = gfc_find_sym_in_symtree (sym);
3464   e->value.function.actual = actual;
3465   e->value.function.esym = NULL;
3466   e->value.function.isym = NULL;
3467   e->value.function.name = NULL;
3468   e->user_operator = 1;
3469
3470   if (gfc_resolve_expr (e) == FAILURE)
3471     return MATCH_ERROR;
3472
3473   return MATCH_YES;
3474 }
3475
3476
3477 /* Tries to replace an assignment code node with a subroutine call to
3478    the subroutine associated with the assignment operator.  Return
3479    SUCCESS if the node was replaced.  On FAILURE, no error is
3480    generated.  */
3481
3482 gfc_try
3483 gfc_extend_assign (gfc_code *c, gfc_namespace *ns)
3484 {
3485   gfc_actual_arglist *actual;
3486   gfc_expr *lhs, *rhs;
3487   gfc_symbol *sym;
3488   const char *gname;
3489
3490   gname = NULL;
3491
3492   lhs = c->expr1;
3493   rhs = c->expr2;
3494
3495   /* Don't allow an intrinsic assignment to be replaced.  */
3496   if (lhs->ts.type != BT_DERIVED && lhs->ts.type != BT_CLASS
3497       && (rhs->rank == 0 || rhs->rank == lhs->rank)
3498       && (lhs->ts.type == rhs->ts.type
3499           || (gfc_numeric_ts (&lhs->ts) && gfc_numeric_ts (&rhs->ts))))
3500     return FAILURE;
3501
3502   actual = gfc_get_actual_arglist ();
3503   actual->expr = lhs;
3504
3505   actual->next = gfc_get_actual_arglist ();
3506   actual->next->expr = rhs;
3507
3508   sym = NULL;
3509
3510   for (; ns; ns = ns->parent)
3511     {
3512       sym = gfc_search_interface (ns->op[INTRINSIC_ASSIGN], 1, &actual);
3513       if (sym != NULL)
3514         break;
3515     }
3516
3517   /* TODO: Ambiguity-check, see above for gfc_extend_expr.  */
3518
3519   if (sym == NULL)
3520     {
3521       gfc_typebound_proc* tbo;
3522       gfc_expr* tb_base;
3523
3524       /* See if we find a matching type-bound assignment.  */
3525       tbo = matching_typebound_op (&tb_base, actual,
3526                                    INTRINSIC_ASSIGN, NULL, &gname);
3527               
3528       /* If there is one, replace the expression with a call to it and
3529          succeed.  */
3530       if (tbo)
3531         {
3532           gcc_assert (tb_base);
3533           c->expr1 = gfc_get_expr ();
3534           build_compcall_for_operator (c->expr1, actual, tb_base, tbo, gname);
3535           c->expr1->value.compcall.assign = 1;
3536           c->expr1->where = c->loc;
3537           c->expr2 = NULL;
3538           c->op = EXEC_COMPCALL;
3539
3540           /* c is resolved from the caller, so no need to do it here.  */
3541
3542           return SUCCESS;
3543         }
3544
3545       free (actual->next);
3546       free (actual);
3547       return FAILURE;
3548     }
3549
3550   /* Replace the assignment with the call.  */
3551   c->op = EXEC_ASSIGN_CALL;
3552   c->symtree = gfc_find_sym_in_symtree (sym);
3553   c->expr1 = NULL;
3554   c->expr2 = NULL;
3555   c->ext.actual = actual;
3556
3557   return SUCCESS;
3558 }
3559
3560
3561 /* Make sure that the interface just parsed is not already present in
3562    the given interface list.  Ambiguity isn't checked yet since module
3563    procedures can be present without interfaces.  */
3564
3565 gfc_try
3566 gfc_check_new_interface (gfc_interface *base, gfc_symbol *new_sym, locus loc)
3567 {
3568   gfc_interface *ip;
3569
3570   for (ip = base; ip; ip = ip->next)
3571     {
3572       if (ip->sym == new_sym)
3573         {
3574           gfc_error ("Entity '%s' at %L is already present in the interface",
3575                      new_sym->name, &loc);
3576           return FAILURE;
3577         }
3578     }
3579
3580   return SUCCESS;
3581 }
3582
3583
3584 /* Add a symbol to the current interface.  */
3585
3586 gfc_try
3587 gfc_add_interface (gfc_symbol *new_sym)
3588 {
3589   gfc_interface **head, *intr;
3590   gfc_namespace *ns;
3591   gfc_symbol *sym;
3592
3593   switch (current_interface.type)
3594     {
3595     case INTERFACE_NAMELESS:
3596     case INTERFACE_ABSTRACT:
3597       return SUCCESS;
3598
3599     case INTERFACE_INTRINSIC_OP:
3600       for (ns = current_interface.ns; ns; ns = ns->parent)
3601         switch (current_interface.op)
3602           {
3603             case INTRINSIC_EQ:
3604             case INTRINSIC_EQ_OS:
3605               if (gfc_check_new_interface (ns->op[INTRINSIC_EQ], new_sym,
3606                                            gfc_current_locus) == FAILURE
3607                   || gfc_check_new_interface (ns->op[INTRINSIC_EQ_OS], new_sym,
3608                                               gfc_current_locus) == FAILURE)
3609                 return FAILURE;
3610               break;
3611
3612             case INTRINSIC_NE:
3613             case INTRINSIC_NE_OS:
3614               if (gfc_check_new_interface (ns->op[INTRINSIC_NE], new_sym,
3615                                            gfc_current_locus) == FAILURE
3616                   || gfc_check_new_interface (ns->op[INTRINSIC_NE_OS], new_sym,
3617                                               gfc_current_locus) == FAILURE)
3618                 return FAILURE;
3619               break;
3620
3621             case INTRINSIC_GT:
3622             case INTRINSIC_GT_OS:
3623               if (gfc_check_new_interface (ns->op[INTRINSIC_GT], new_sym,
3624                                            gfc_current_locus) == FAILURE
3625                   || gfc_check_new_interface (ns->op[INTRINSIC_GT_OS], new_sym,
3626                                               gfc_current_locus) == FAILURE)
3627                 return FAILURE;
3628               break;
3629
3630             case INTRINSIC_GE:
3631             case INTRINSIC_GE_OS:
3632               if (gfc_check_new_interface (ns->op[INTRINSIC_GE], new_sym,
3633                                            gfc_current_locus) == FAILURE
3634                   || gfc_check_new_interface (ns->op[INTRINSIC_GE_OS], new_sym,
3635                                               gfc_current_locus) == FAILURE)
3636                 return FAILURE;
3637               break;
3638
3639             case INTRINSIC_LT:
3640             case INTRINSIC_LT_OS:
3641               if (gfc_check_new_interface (ns->op[INTRINSIC_LT], new_sym,
3642                                            gfc_current_locus) == FAILURE
3643                   || gfc_check_new_interface (ns->op[INTRINSIC_LT_OS], new_sym,
3644                                               gfc_current_locus) == FAILURE)
3645                 return FAILURE;
3646               break;
3647
3648             case INTRINSIC_LE:
3649             case INTRINSIC_LE_OS:
3650               if (gfc_check_new_interface (ns->op[INTRINSIC_LE], new_sym,
3651                                            gfc_current_locus) == FAILURE
3652                   || gfc_check_new_interface (ns->op[INTRINSIC_LE_OS], new_sym,
3653                                               gfc_current_locus) == FAILURE)
3654                 return FAILURE;
3655               break;
3656
3657             default:
3658               if (gfc_check_new_interface (ns->op[current_interface.op], new_sym,
3659                                            gfc_current_locus) == FAILURE)
3660                 return FAILURE;
3661           }
3662
3663       head = &current_interface.ns->op[current_interface.op];
3664       break;
3665
3666     case INTERFACE_GENERIC:
3667       for (ns = current_interface.ns; ns; ns = ns->parent)
3668         {
3669           gfc_find_symbol (current_interface.sym->name, ns, 0, &sym);
3670           if (sym == NULL)
3671             continue;
3672
3673           if (gfc_check_new_interface (sym->generic, new_sym, gfc_current_locus)
3674               == FAILURE)
3675             return FAILURE;
3676         }
3677
3678       head = &current_interface.sym->generic;
3679       break;
3680
3681     case INTERFACE_USER_OP:
3682       if (gfc_check_new_interface (current_interface.uop->op, new_sym,
3683                                    gfc_current_locus) == FAILURE)
3684         return FAILURE;
3685
3686       head = &current_interface.uop->op;
3687       break;
3688
3689     default:
3690       gfc_internal_error ("gfc_add_interface(): Bad interface type");
3691     }
3692
3693   intr = gfc_get_interface ();
3694   intr->sym = new_sym;
3695   intr->where = gfc_current_locus;
3696
3697   intr->next = *head;
3698   *head = intr;
3699
3700   return SUCCESS;
3701 }
3702
3703
3704 gfc_interface *
3705 gfc_current_interface_head (void)
3706 {
3707   switch (current_interface.type)
3708     {
3709       case INTERFACE_INTRINSIC_OP:
3710         return current_interface.ns->op[current_interface.op];
3711         break;
3712
3713       case INTERFACE_GENERIC:
3714         return current_interface.sym->generic;
3715         break;
3716
3717       case INTERFACE_USER_OP:
3718         return current_interface.uop->op;
3719         break;
3720
3721       default:
3722         gcc_unreachable ();
3723     }
3724 }
3725
3726
3727 void
3728 gfc_set_current_interface_head (gfc_interface *i)
3729 {
3730   switch (current_interface.type)
3731     {
3732       case INTERFACE_INTRINSIC_OP:
3733         current_interface.ns->op[current_interface.op] = i;
3734         break;
3735
3736       case INTERFACE_GENERIC:
3737         current_interface.sym->generic = i;
3738         break;
3739
3740       case INTERFACE_USER_OP:
3741         current_interface.uop->op = i;
3742         break;
3743
3744       default:
3745         gcc_unreachable ();
3746     }
3747 }
3748
3749
3750 /* Gets rid of a formal argument list.  We do not free symbols.
3751    Symbols are freed when a namespace is freed.  */
3752
3753 void
3754 gfc_free_formal_arglist (gfc_formal_arglist *p)
3755 {
3756   gfc_formal_arglist *q;
3757
3758   for (; p; p = q)
3759     {
3760       q = p->next;
3761       free (p);
3762     }
3763 }
3764
3765
3766 /* Check that it is ok for the type-bound procedure 'proc' to override the
3767    procedure 'old', cf. F08:4.5.7.3.  */
3768
3769 gfc_try
3770 gfc_check_typebound_override (gfc_symtree* proc, gfc_symtree* old)
3771 {
3772   locus where;
3773   const gfc_symbol *proc_target, *old_target;
3774   unsigned proc_pass_arg, old_pass_arg, argpos;
3775   gfc_formal_arglist *proc_formal, *old_formal;
3776   bool check_type;
3777   char err[200];
3778
3779   /* This procedure should only be called for non-GENERIC proc.  */
3780   gcc_assert (!proc->n.tb->is_generic);
3781
3782   /* If the overwritten procedure is GENERIC, this is an error.  */
3783   if (old->n.tb->is_generic)
3784     {
3785       gfc_error ("Can't overwrite GENERIC '%s' at %L",
3786                  old->name, &proc->n.tb->where);
3787       return FAILURE;
3788     }
3789
3790   where = proc->n.tb->where;
3791   proc_target = proc->n.tb->u.specific->n.sym;
3792   old_target = old->n.tb->u.specific->n.sym;
3793
3794   /* Check that overridden binding is not NON_OVERRIDABLE.  */
3795   if (old->n.tb->non_overridable)
3796     {
3797       gfc_error ("'%s' at %L overrides a procedure binding declared"
3798                  " NON_OVERRIDABLE", proc->name, &where);
3799       return FAILURE;
3800     }
3801
3802   /* It's an error to override a non-DEFERRED procedure with a DEFERRED one.  */
3803   if (!old->n.tb->deferred && proc->n.tb->deferred)
3804     {
3805       gfc_error ("'%s' at %L must not be DEFERRED as it overrides a"
3806                  " non-DEFERRED binding", proc->name, &where);
3807       return FAILURE;
3808     }
3809
3810   /* If the overridden binding is PURE, the overriding must be, too.  */
3811   if (old_target->attr.pure && !proc_target->attr.pure)
3812     {
3813       gfc_error ("'%s' at %L overrides a PURE procedure and must also be PURE",
3814                  proc->name, &where);
3815       return FAILURE;
3816     }
3817
3818   /* If the overridden binding is ELEMENTAL, the overriding must be, too.  If it
3819      is not, the overriding must not be either.  */
3820   if (old_target->attr.elemental && !proc_target->attr.elemental)
3821     {
3822       gfc_error ("'%s' at %L overrides an ELEMENTAL procedure and must also be"
3823                  " ELEMENTAL", proc->name, &where);
3824       return FAILURE;
3825     }
3826   if (!old_target->attr.elemental && proc_target->attr.elemental)
3827     {
3828       gfc_error ("'%s' at %L overrides a non-ELEMENTAL procedure and must not"
3829                  " be ELEMENTAL, either", proc->name, &where);
3830       return FAILURE;
3831     }
3832
3833   /* If the overridden binding is a SUBROUTINE, the overriding must also be a
3834      SUBROUTINE.  */
3835   if (old_target->attr.subroutine && !proc_target->attr.subroutine)
3836     {
3837       gfc_error ("'%s' at %L overrides a SUBROUTINE and must also be a"
3838                  " SUBROUTINE", proc->name, &where);
3839       return FAILURE;
3840     }
3841
3842   /* If the overridden binding is a FUNCTION, the overriding must also be a
3843      FUNCTION and have the same characteristics.  */
3844   if (old_target->attr.function)
3845     {
3846       if (!proc_target->attr.function)
3847         {
3848           gfc_error ("'%s' at %L overrides a FUNCTION and must also be a"
3849                      " FUNCTION", proc->name, &where);
3850           return FAILURE;
3851         }
3852
3853       /* FIXME:  Do more comprehensive checking (including, for instance, the
3854          array-shape).  */
3855       gcc_assert (proc_target->result && old_target->result);
3856       if (!compare_type_rank (proc_target->result, old_target->result))
3857         {
3858           gfc_error ("'%s' at %L and the overridden FUNCTION should have"
3859                      " matching result types and ranks", proc->name, &where);
3860           return FAILURE;
3861         }
3862         
3863       /* Check string length.  */
3864       if (proc_target->result->ts.type == BT_CHARACTER
3865           && proc_target->result->ts.u.cl && old_target->result->ts.u.cl)
3866         {
3867           int compval = gfc_dep_compare_expr (proc_target->result->ts.u.cl->length,
3868                                               old_target->result->ts.u.cl->length);
3869           switch (compval)
3870           {
3871             case -1:
3872             case  1:
3873             case -3:
3874               gfc_error ("Character length mismatch between '%s' at '%L' and "
3875                          "overridden FUNCTION", proc->name, &where);
3876               return FAILURE;
3877
3878             case -2:
3879               gfc_warning ("Possible character length mismatch between '%s' at"
3880                            " '%L' and overridden FUNCTION", proc->name, &where);
3881               break;
3882
3883             case 0:
3884               break;
3885
3886             default:
3887               gfc_internal_error ("gfc_check_typebound_override: Unexpected "
3888                                   "result %i of gfc_dep_compare_expr", compval);
3889               break;
3890           }
3891         }
3892     }
3893
3894   /* If the overridden binding is PUBLIC, the overriding one must not be
3895      PRIVATE.  */
3896   if (old->n.tb->access == ACCESS_PUBLIC
3897       && proc->n.tb->access == ACCESS_PRIVATE)
3898     {
3899       gfc_error ("'%s' at %L overrides a PUBLIC procedure and must not be"
3900                  " PRIVATE", proc->name, &where);
3901       return FAILURE;
3902     }
3903
3904   /* Compare the formal argument lists of both procedures.  This is also abused
3905      to find the position of the passed-object dummy arguments of both
3906      bindings as at least the overridden one might not yet be resolved and we
3907      need those positions in the check below.  */
3908   proc_pass_arg = old_pass_arg = 0;
3909   if (!proc->n.tb->nopass && !proc->n.tb->pass_arg)
3910     proc_pass_arg = 1;
3911   if (!old->n.tb->nopass && !old->n.tb->pass_arg)
3912     old_pass_arg = 1;
3913   argpos = 1;
3914   for (proc_formal = proc_target->formal, old_formal = old_target->formal;
3915        proc_formal && old_formal;
3916        proc_formal = proc_formal->next, old_formal = old_formal->next)
3917     {
3918       if (proc->n.tb->pass_arg
3919           && !strcmp (proc->n.tb->pass_arg, proc_formal->sym->name))
3920         proc_pass_arg = argpos;
3921       if (old->n.tb->pass_arg
3922           && !strcmp (old->n.tb->pass_arg, old_formal->sym->name))
3923         old_pass_arg = argpos;
3924
3925       /* Check that the names correspond.  */
3926       if (strcmp (proc_formal->sym->name, old_formal->sym->name))
3927         {
3928           gfc_error ("Dummy argument '%s' of '%s' at %L should be named '%s' as"
3929                      " to match the corresponding argument of the overridden"
3930                      " procedure", proc_formal->sym->name, proc->name, &where,
3931                      old_formal->sym->name);
3932           return FAILURE;
3933         }
3934
3935       check_type = proc_pass_arg != argpos && old_pass_arg != argpos;
3936       if (check_dummy_characteristics (proc_formal->sym, old_formal->sym,
3937                                        check_type, err, sizeof(err)) == FAILURE)
3938         {
3939           gfc_error ("Argument mismatch for the overriding procedure "
3940                      "'%s' at %L: %s", proc->name, &where, err);
3941           return FAILURE;
3942         }
3943
3944       ++argpos;
3945     }
3946   if (proc_formal || old_formal)
3947     {
3948       gfc_error ("'%s' at %L must have the same number of formal arguments as"
3949                  " the overridden procedure", proc->name, &where);
3950       return FAILURE;
3951     }
3952
3953   /* If the overridden binding is NOPASS, the overriding one must also be
3954      NOPASS.  */
3955   if (old->n.tb->nopass && !proc->n.tb->nopass)
3956     {
3957       gfc_error ("'%s' at %L overrides a NOPASS binding and must also be"
3958                  " NOPASS", proc->name, &where);
3959       return FAILURE;
3960     }
3961
3962   /* If the overridden binding is PASS(x), the overriding one must also be
3963      PASS and the passed-object dummy arguments must correspond.  */
3964   if (!old->n.tb->nopass)
3965     {
3966       if (proc->n.tb->nopass)
3967         {
3968           gfc_error ("'%s' at %L overrides a binding with PASS and must also be"
3969                      " PASS", proc->name, &where);
3970           return FAILURE;
3971         }
3972
3973       if (proc_pass_arg != old_pass_arg)
3974         {
3975           gfc_error ("Passed-object dummy argument of '%s' at %L must be at"
3976                      " the same position as the passed-object dummy argument of"
3977                      " the overridden procedure", proc->name, &where);
3978           return FAILURE;
3979         }
3980     }
3981
3982   return SUCCESS;
3983 }