OSDN Git Service

2010-09-20 Janus Weil <janus@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-expr.c
1 /* Expression translation
2    Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Paul Brook <paul@nowt.org>
5    and Steven Bosscher <s.bosscher@student.tudelft.nl>
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 /* trans-expr.c-- generate GENERIC trees for gfc_expr.  */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tree.h"
29 #include "diagnostic-core.h"    /* For fatal_error.  */
30 #include "langhooks.h"
31 #include "flags.h"
32 #include "gfortran.h"
33 #include "arith.h"
34 #include "constructor.h"
35 #include "trans.h"
36 #include "trans-const.h"
37 #include "trans-types.h"
38 #include "trans-array.h"
39 /* Only for gfc_trans_assign and gfc_trans_pointer_assign.  */
40 #include "trans-stmt.h"
41 #include "dependency.h"
42
43 static tree gfc_trans_structure_assign (tree dest, gfc_expr * expr);
44 static void gfc_apply_interface_mapping_to_expr (gfc_interface_mapping *,
45                                                  gfc_expr *);
46
47 /* Copy the scalarization loop variables.  */
48
49 static void
50 gfc_copy_se_loopvars (gfc_se * dest, gfc_se * src)
51 {
52   dest->ss = src->ss;
53   dest->loop = src->loop;
54 }
55
56
57 /* Initialize a simple expression holder.
58
59    Care must be taken when multiple se are created with the same parent.
60    The child se must be kept in sync.  The easiest way is to delay creation
61    of a child se until after after the previous se has been translated.  */
62
63 void
64 gfc_init_se (gfc_se * se, gfc_se * parent)
65 {
66   memset (se, 0, sizeof (gfc_se));
67   gfc_init_block (&se->pre);
68   gfc_init_block (&se->post);
69
70   se->parent = parent;
71
72   if (parent)
73     gfc_copy_se_loopvars (se, parent);
74 }
75
76
77 /* Advances to the next SS in the chain.  Use this rather than setting
78    se->ss = se->ss->next because all the parents needs to be kept in sync.
79    See gfc_init_se.  */
80
81 void
82 gfc_advance_se_ss_chain (gfc_se * se)
83 {
84   gfc_se *p;
85
86   gcc_assert (se != NULL && se->ss != NULL && se->ss != gfc_ss_terminator);
87
88   p = se;
89   /* Walk down the parent chain.  */
90   while (p != NULL)
91     {
92       /* Simple consistency check.  */
93       gcc_assert (p->parent == NULL || p->parent->ss == p->ss);
94
95       p->ss = p->ss->next;
96
97       p = p->parent;
98     }
99 }
100
101
102 /* Ensures the result of the expression as either a temporary variable
103    or a constant so that it can be used repeatedly.  */
104
105 void
106 gfc_make_safe_expr (gfc_se * se)
107 {
108   tree var;
109
110   if (CONSTANT_CLASS_P (se->expr))
111     return;
112
113   /* We need a temporary for this result.  */
114   var = gfc_create_var (TREE_TYPE (se->expr), NULL);
115   gfc_add_modify (&se->pre, var, se->expr);
116   se->expr = var;
117 }
118
119
120 /* Return an expression which determines if a dummy parameter is present.
121    Also used for arguments to procedures with multiple entry points.  */
122
123 tree
124 gfc_conv_expr_present (gfc_symbol * sym)
125 {
126   tree decl, cond;
127
128   gcc_assert (sym->attr.dummy);
129
130   decl = gfc_get_symbol_decl (sym);
131   if (TREE_CODE (decl) != PARM_DECL)
132     {
133       /* Array parameters use a temporary descriptor, we want the real
134          parameter.  */
135       gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl))
136              || GFC_ARRAY_TYPE_P (TREE_TYPE (decl)));
137       decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
138     }
139
140   cond = fold_build2_loc (input_location, NE_EXPR, boolean_type_node, decl,
141                           fold_convert (TREE_TYPE (decl), null_pointer_node));
142
143   /* Fortran 2008 allows to pass null pointers and non-associated pointers
144      as actual argument to denote absent dummies. For array descriptors,
145      we thus also need to check the array descriptor.  */
146   if (!sym->attr.pointer && !sym->attr.allocatable
147       && sym->as && sym->as->type == AS_ASSUMED_SHAPE
148       && (gfc_option.allow_std & GFC_STD_F2008) != 0)
149     {
150       tree tmp;
151       tmp = build_fold_indirect_ref_loc (input_location, decl);
152       tmp = gfc_conv_array_data (tmp);
153       tmp = fold_build2_loc (input_location, NE_EXPR, boolean_type_node, tmp,
154                              fold_convert (TREE_TYPE (tmp), null_pointer_node));
155       cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
156                               boolean_type_node, cond, tmp);
157     }
158
159   return cond;
160 }
161
162
163 /* Converts a missing, dummy argument into a null or zero.  */
164
165 void
166 gfc_conv_missing_dummy (gfc_se * se, gfc_expr * arg, gfc_typespec ts, int kind)
167 {
168   tree present;
169   tree tmp;
170
171   present = gfc_conv_expr_present (arg->symtree->n.sym);
172
173   if (kind > 0)
174     {
175       /* Create a temporary and convert it to the correct type.  */
176       tmp = gfc_get_int_type (kind);
177       tmp = fold_convert (tmp, build_fold_indirect_ref_loc (input_location,
178                                                         se->expr));
179     
180       /* Test for a NULL value.  */
181       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), present,
182                         tmp, fold_convert (TREE_TYPE (tmp), integer_one_node));
183       tmp = gfc_evaluate_now (tmp, &se->pre);
184       se->expr = gfc_build_addr_expr (NULL_TREE, tmp);
185     }
186   else
187     {
188       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se->expr),
189                         present, se->expr,
190                         fold_convert (TREE_TYPE (se->expr), integer_zero_node));
191       tmp = gfc_evaluate_now (tmp, &se->pre);
192       se->expr = tmp;
193     }
194
195   if (ts.type == BT_CHARACTER)
196     {
197       tmp = build_int_cst (gfc_charlen_type_node, 0);
198       tmp = fold_build3_loc (input_location, COND_EXPR, gfc_charlen_type_node,
199                              present, se->string_length, tmp);
200       tmp = gfc_evaluate_now (tmp, &se->pre);
201       se->string_length = tmp;
202     }
203   return;
204 }
205
206
207 /* Get the character length of an expression, looking through gfc_refs
208    if necessary.  */
209
210 tree
211 gfc_get_expr_charlen (gfc_expr *e)
212 {
213   gfc_ref *r;
214   tree length;
215
216   gcc_assert (e->expr_type == EXPR_VARIABLE 
217               && e->ts.type == BT_CHARACTER);
218   
219   length = NULL; /* To silence compiler warning.  */
220
221   if (is_subref_array (e) && e->ts.u.cl->length)
222     {
223       gfc_se tmpse;
224       gfc_init_se (&tmpse, NULL);
225       gfc_conv_expr_type (&tmpse, e->ts.u.cl->length, gfc_charlen_type_node);
226       e->ts.u.cl->backend_decl = tmpse.expr;
227       return tmpse.expr;
228     }
229
230   /* First candidate: if the variable is of type CHARACTER, the
231      expression's length could be the length of the character
232      variable.  */
233   if (e->symtree->n.sym->ts.type == BT_CHARACTER)
234     length = e->symtree->n.sym->ts.u.cl->backend_decl;
235
236   /* Look through the reference chain for component references.  */
237   for (r = e->ref; r; r = r->next)
238     {
239       switch (r->type)
240         {
241         case REF_COMPONENT:
242           if (r->u.c.component->ts.type == BT_CHARACTER)
243             length = r->u.c.component->ts.u.cl->backend_decl;
244           break;
245
246         case REF_ARRAY:
247           /* Do nothing.  */
248           break;
249
250         default:
251           /* We should never got substring references here.  These will be
252              broken down by the scalarizer.  */
253           gcc_unreachable ();
254           break;
255         }
256     }
257
258   gcc_assert (length != NULL);
259   return length;
260 }
261
262
263 /* For each character array constructor subexpression without a ts.u.cl->length,
264    replace it by its first element (if there aren't any elements, the length
265    should already be set to zero).  */
266
267 static void
268 flatten_array_ctors_without_strlen (gfc_expr* e)
269 {
270   gfc_actual_arglist* arg;
271   gfc_constructor* c;
272
273   if (!e)
274     return;
275
276   switch (e->expr_type)
277     {
278
279     case EXPR_OP:
280       flatten_array_ctors_without_strlen (e->value.op.op1); 
281       flatten_array_ctors_without_strlen (e->value.op.op2); 
282       break;
283
284     case EXPR_COMPCALL:
285       /* TODO: Implement as with EXPR_FUNCTION when needed.  */
286       gcc_unreachable ();
287
288     case EXPR_FUNCTION:
289       for (arg = e->value.function.actual; arg; arg = arg->next)
290         flatten_array_ctors_without_strlen (arg->expr);
291       break;
292
293     case EXPR_ARRAY:
294
295       /* We've found what we're looking for.  */
296       if (e->ts.type == BT_CHARACTER && !e->ts.u.cl->length)
297         {
298           gfc_constructor *c;
299           gfc_expr* new_expr;
300
301           gcc_assert (e->value.constructor);
302
303           c = gfc_constructor_first (e->value.constructor);
304           new_expr = c->expr;
305           c->expr = NULL;
306
307           flatten_array_ctors_without_strlen (new_expr);
308           gfc_replace_expr (e, new_expr);
309           break;
310         }
311
312       /* Otherwise, fall through to handle constructor elements.  */
313     case EXPR_STRUCTURE:
314       for (c = gfc_constructor_first (e->value.constructor);
315            c; c = gfc_constructor_next (c))
316         flatten_array_ctors_without_strlen (c->expr);
317       break;
318
319     default:
320       break;
321
322     }
323 }
324
325
326 /* Generate code to initialize a string length variable. Returns the
327    value.  For array constructors, cl->length might be NULL and in this case,
328    the first element of the constructor is needed.  expr is the original
329    expression so we can access it but can be NULL if this is not needed.  */
330
331 void
332 gfc_conv_string_length (gfc_charlen * cl, gfc_expr * expr, stmtblock_t * pblock)
333 {
334   gfc_se se;
335
336   gfc_init_se (&se, NULL);
337
338   /* If cl->length is NULL, use gfc_conv_expr to obtain the string length but
339      "flatten" array constructors by taking their first element; all elements
340      should be the same length or a cl->length should be present.  */
341   if (!cl->length)
342     {
343       gfc_expr* expr_flat;
344       gcc_assert (expr);
345
346       expr_flat = gfc_copy_expr (expr);
347       flatten_array_ctors_without_strlen (expr_flat);
348       gfc_resolve_expr (expr_flat);
349
350       gfc_conv_expr (&se, expr_flat);
351       gfc_add_block_to_block (pblock, &se.pre);
352       cl->backend_decl = convert (gfc_charlen_type_node, se.string_length);
353
354       gfc_free_expr (expr_flat);
355       return;
356     }
357
358   /* Convert cl->length.  */
359
360   gcc_assert (cl->length);
361
362   gfc_conv_expr_type (&se, cl->length, gfc_charlen_type_node);
363   se.expr = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
364                              se.expr, build_int_cst (gfc_charlen_type_node, 0));
365   gfc_add_block_to_block (pblock, &se.pre);
366
367   if (cl->backend_decl)
368     gfc_add_modify (pblock, cl->backend_decl, se.expr);
369   else
370     cl->backend_decl = gfc_evaluate_now (se.expr, pblock);
371 }
372
373
374 static void
375 gfc_conv_substring (gfc_se * se, gfc_ref * ref, int kind,
376                     const char *name, locus *where)
377 {
378   tree tmp;
379   tree type;
380   tree fault;
381   gfc_se start;
382   gfc_se end;
383   char *msg;
384
385   type = gfc_get_character_type (kind, ref->u.ss.length);
386   type = build_pointer_type (type);
387
388   gfc_init_se (&start, se);
389   gfc_conv_expr_type (&start, ref->u.ss.start, gfc_charlen_type_node);
390   gfc_add_block_to_block (&se->pre, &start.pre);
391
392   if (integer_onep (start.expr))
393     gfc_conv_string_parameter (se);
394   else
395     {
396       tmp = start.expr;
397       STRIP_NOPS (tmp);
398       /* Avoid multiple evaluation of substring start.  */
399       if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
400         start.expr = gfc_evaluate_now (start.expr, &se->pre);
401
402       /* Change the start of the string.  */
403       if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
404         tmp = se->expr;
405       else
406         tmp = build_fold_indirect_ref_loc (input_location,
407                                        se->expr);
408       tmp = gfc_build_array_ref (tmp, start.expr, NULL);
409       se->expr = gfc_build_addr_expr (type, tmp);
410     }
411
412   /* Length = end + 1 - start.  */
413   gfc_init_se (&end, se);
414   if (ref->u.ss.end == NULL)
415     end.expr = se->string_length;
416   else
417     {
418       gfc_conv_expr_type (&end, ref->u.ss.end, gfc_charlen_type_node);
419       gfc_add_block_to_block (&se->pre, &end.pre);
420     }
421   tmp = end.expr;
422   STRIP_NOPS (tmp);
423   if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
424     end.expr = gfc_evaluate_now (end.expr, &se->pre);
425
426   if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
427     {
428       tree nonempty = fold_build2_loc (input_location, LE_EXPR,
429                                        boolean_type_node, start.expr,
430                                        end.expr);
431
432       /* Check lower bound.  */
433       fault = fold_build2_loc (input_location, LT_EXPR, boolean_type_node,
434                                start.expr,
435                                build_int_cst (gfc_charlen_type_node, 1));
436       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
437                                boolean_type_node, nonempty, fault);
438       if (name)
439         asprintf (&msg, "Substring out of bounds: lower bound (%%ld) of '%s' "
440                   "is less than one", name);
441       else
442         asprintf (&msg, "Substring out of bounds: lower bound (%%ld)"
443                   "is less than one");
444       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
445                                fold_convert (long_integer_type_node,
446                                              start.expr));
447       gfc_free (msg);
448
449       /* Check upper bound.  */
450       fault = fold_build2_loc (input_location, GT_EXPR, boolean_type_node,
451                                end.expr, se->string_length);
452       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
453                                boolean_type_node, nonempty, fault);
454       if (name)
455         asprintf (&msg, "Substring out of bounds: upper bound (%%ld) of '%s' "
456                   "exceeds string length (%%ld)", name);
457       else
458         asprintf (&msg, "Substring out of bounds: upper bound (%%ld) "
459                   "exceeds string length (%%ld)");
460       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
461                                fold_convert (long_integer_type_node, end.expr),
462                                fold_convert (long_integer_type_node,
463                                              se->string_length));
464       gfc_free (msg);
465     }
466
467   /* If the start and end expressions are equal, the length is one.  */
468   if (ref->u.ss.end
469       && gfc_dep_compare_expr (ref->u.ss.start, ref->u.ss.end) == 0)
470     tmp = build_int_cst (gfc_charlen_type_node, 1);
471   else
472     {
473       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_charlen_type_node,
474                              end.expr, start.expr);
475       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_charlen_type_node,
476                              build_int_cst (gfc_charlen_type_node, 1), tmp);
477       tmp = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
478                              tmp, build_int_cst (gfc_charlen_type_node, 0));
479     }
480
481   se->string_length = tmp;
482 }
483
484
485 /* Convert a derived type component reference.  */
486
487 static void
488 gfc_conv_component_ref (gfc_se * se, gfc_ref * ref)
489 {
490   gfc_component *c;
491   tree tmp;
492   tree decl;
493   tree field;
494
495   c = ref->u.c.component;
496
497   gcc_assert (c->backend_decl);
498
499   field = c->backend_decl;
500   gcc_assert (TREE_CODE (field) == FIELD_DECL);
501   decl = se->expr;
502   tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
503                          decl, field, NULL_TREE);
504
505   se->expr = tmp;
506
507   if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer)
508     {
509       tmp = c->ts.u.cl->backend_decl;
510       /* Components must always be constant length.  */
511       gcc_assert (tmp && INTEGER_CST_P (tmp));
512       se->string_length = tmp;
513     }
514
515   if (((c->attr.pointer || c->attr.allocatable) && c->attr.dimension == 0
516        && c->ts.type != BT_CHARACTER)
517       || c->attr.proc_pointer)
518     se->expr = build_fold_indirect_ref_loc (input_location,
519                                         se->expr);
520 }
521
522
523 /* This function deals with component references to components of the
524    parent type for derived type extensons.  */
525 static void
526 conv_parent_component_references (gfc_se * se, gfc_ref * ref)
527 {
528   gfc_component *c;
529   gfc_component *cmp;
530   gfc_symbol *dt;
531   gfc_ref parent;
532
533   dt = ref->u.c.sym;
534   c = ref->u.c.component;
535
536   /* Build a gfc_ref to recursively call gfc_conv_component_ref.  */
537   parent.type = REF_COMPONENT;
538   parent.next = NULL;
539   parent.u.c.sym = dt;
540   parent.u.c.component = dt->components;
541
542   if (dt->backend_decl == NULL)
543     gfc_get_derived_type (dt);
544
545   if (dt->attr.extension && dt->components)
546     {
547       if (dt->attr.is_class)
548         cmp = dt->components;
549       else
550         cmp = dt->components->next;
551       /* Return if the component is not in the parent type.  */
552       for (; cmp; cmp = cmp->next)
553         if (strcmp (c->name, cmp->name) == 0)
554           return;
555         
556       /* Otherwise build the reference and call self.  */
557       gfc_conv_component_ref (se, &parent);
558       parent.u.c.sym = dt->components->ts.u.derived;
559       parent.u.c.component = c;
560       conv_parent_component_references (se, &parent);
561     }
562 }
563
564 /* Return the contents of a variable. Also handles reference/pointer
565    variables (all Fortran pointer references are implicit).  */
566
567 static void
568 gfc_conv_variable (gfc_se * se, gfc_expr * expr)
569 {
570   gfc_ref *ref;
571   gfc_symbol *sym;
572   tree parent_decl = NULL_TREE;
573   int parent_flag;
574   bool return_value;
575   bool alternate_entry;
576   bool entry_master;
577
578   sym = expr->symtree->n.sym;
579   if (se->ss != NULL)
580     {
581       /* Check that something hasn't gone horribly wrong.  */
582       gcc_assert (se->ss != gfc_ss_terminator);
583       gcc_assert (se->ss->expr == expr);
584
585       /* A scalarized term.  We already know the descriptor.  */
586       se->expr = se->ss->data.info.descriptor;
587       se->string_length = se->ss->string_length;
588       for (ref = se->ss->data.info.ref; ref; ref = ref->next)
589         if (ref->type == REF_ARRAY && ref->u.ar.type != AR_ELEMENT)
590           break;
591     }
592   else
593     {
594       tree se_expr = NULL_TREE;
595
596       se->expr = gfc_get_symbol_decl (sym);
597
598       /* Deal with references to a parent results or entries by storing
599          the current_function_decl and moving to the parent_decl.  */
600       return_value = sym->attr.function && sym->result == sym;
601       alternate_entry = sym->attr.function && sym->attr.entry
602                         && sym->result == sym;
603       entry_master = sym->attr.result
604                      && sym->ns->proc_name->attr.entry_master
605                      && !gfc_return_by_reference (sym->ns->proc_name);
606       if (current_function_decl)
607         parent_decl = DECL_CONTEXT (current_function_decl);
608
609       if ((se->expr == parent_decl && return_value)
610            || (sym->ns && sym->ns->proc_name
611                && parent_decl
612                && sym->ns->proc_name->backend_decl == parent_decl
613                && (alternate_entry || entry_master)))
614         parent_flag = 1;
615       else
616         parent_flag = 0;
617
618       /* Special case for assigning the return value of a function.
619          Self recursive functions must have an explicit return value.  */
620       if (return_value && (se->expr == current_function_decl || parent_flag))
621         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
622
623       /* Similarly for alternate entry points.  */
624       else if (alternate_entry 
625                && (sym->ns->proc_name->backend_decl == current_function_decl
626                    || parent_flag))
627         {
628           gfc_entry_list *el = NULL;
629
630           for (el = sym->ns->entries; el; el = el->next)
631             if (sym == el->sym)
632               {
633                 se_expr = gfc_get_fake_result_decl (sym, parent_flag);
634                 break;
635               }
636         }
637
638       else if (entry_master
639                && (sym->ns->proc_name->backend_decl == current_function_decl
640                    || parent_flag))
641         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
642
643       if (se_expr)
644         se->expr = se_expr;
645
646       /* Procedure actual arguments.  */
647       else if (sym->attr.flavor == FL_PROCEDURE
648                && se->expr != current_function_decl)
649         {
650           if (!sym->attr.dummy && !sym->attr.proc_pointer)
651             {
652               gcc_assert (TREE_CODE (se->expr) == FUNCTION_DECL);
653               se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
654             }
655           return;
656         }
657
658
659       /* Dereference the expression, where needed. Since characters
660          are entirely different from other types, they are treated 
661          separately.  */
662       if (sym->ts.type == BT_CHARACTER)
663         {
664           /* Dereference character pointer dummy arguments
665              or results.  */
666           if ((sym->attr.pointer || sym->attr.allocatable)
667               && (sym->attr.dummy
668                   || sym->attr.function
669                   || sym->attr.result))
670             se->expr = build_fold_indirect_ref_loc (input_location,
671                                                 se->expr);
672
673         }
674       else if (!sym->attr.value)
675         {
676           /* Dereference non-character scalar dummy arguments.  */
677           if (sym->attr.dummy && !sym->attr.dimension)
678             se->expr = build_fold_indirect_ref_loc (input_location,
679                                                 se->expr);
680
681           /* Dereference scalar hidden result.  */
682           if (gfc_option.flag_f2c && sym->ts.type == BT_COMPLEX
683               && (sym->attr.function || sym->attr.result)
684               && !sym->attr.dimension && !sym->attr.pointer
685               && !sym->attr.always_explicit)
686             se->expr = build_fold_indirect_ref_loc (input_location,
687                                                 se->expr);
688
689           /* Dereference non-character pointer variables. 
690              These must be dummies, results, or scalars.  */
691           if ((sym->attr.pointer || sym->attr.allocatable
692                || gfc_is_associate_pointer (sym))
693               && (sym->attr.dummy
694                   || sym->attr.function
695                   || sym->attr.result
696                   || !sym->attr.dimension))
697             se->expr = build_fold_indirect_ref_loc (input_location,
698                                                 se->expr);
699         }
700
701       ref = expr->ref;
702     }
703
704   /* For character variables, also get the length.  */
705   if (sym->ts.type == BT_CHARACTER)
706     {
707       /* If the character length of an entry isn't set, get the length from
708          the master function instead.  */
709       if (sym->attr.entry && !sym->ts.u.cl->backend_decl)
710         se->string_length = sym->ns->proc_name->ts.u.cl->backend_decl;
711       else
712         se->string_length = sym->ts.u.cl->backend_decl;
713       gcc_assert (se->string_length);
714     }
715
716   while (ref)
717     {
718       switch (ref->type)
719         {
720         case REF_ARRAY:
721           /* Return the descriptor if that's what we want and this is an array
722              section reference.  */
723           if (se->descriptor_only && ref->u.ar.type != AR_ELEMENT)
724             return;
725 /* TODO: Pointers to single elements of array sections, eg elemental subs.  */
726           /* Return the descriptor for array pointers and allocations.  */
727           if (se->want_pointer
728               && ref->next == NULL && (se->descriptor_only))
729             return;
730
731           gfc_conv_array_ref (se, &ref->u.ar, sym, &expr->where);
732           /* Return a pointer to an element.  */
733           break;
734
735         case REF_COMPONENT:
736           if (ref->u.c.sym->attr.extension)
737             conv_parent_component_references (se, ref);
738
739           gfc_conv_component_ref (se, ref);
740           break;
741
742         case REF_SUBSTRING:
743           gfc_conv_substring (se, ref, expr->ts.kind,
744                               expr->symtree->name, &expr->where);
745           break;
746
747         default:
748           gcc_unreachable ();
749           break;
750         }
751       ref = ref->next;
752     }
753   /* Pointer assignment, allocation or pass by reference.  Arrays are handled
754      separately.  */
755   if (se->want_pointer)
756     {
757       if (expr->ts.type == BT_CHARACTER && !gfc_is_proc_ptr_comp (expr, NULL))
758         gfc_conv_string_parameter (se);
759       else 
760         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
761     }
762 }
763
764
765 /* Unary ops are easy... Or they would be if ! was a valid op.  */
766
767 static void
768 gfc_conv_unary_op (enum tree_code code, gfc_se * se, gfc_expr * expr)
769 {
770   gfc_se operand;
771   tree type;
772
773   gcc_assert (expr->ts.type != BT_CHARACTER);
774   /* Initialize the operand.  */
775   gfc_init_se (&operand, se);
776   gfc_conv_expr_val (&operand, expr->value.op.op1);
777   gfc_add_block_to_block (&se->pre, &operand.pre);
778
779   type = gfc_typenode_for_spec (&expr->ts);
780
781   /* TRUTH_NOT_EXPR is not a "true" unary operator in GCC.
782      We must convert it to a compare to 0 (e.g. EQ_EXPR (op1, 0)).
783      All other unary operators have an equivalent GIMPLE unary operator.  */
784   if (code == TRUTH_NOT_EXPR)
785     se->expr = fold_build2_loc (input_location, EQ_EXPR, type, operand.expr,
786                                 build_int_cst (type, 0));
787   else
788     se->expr = fold_build1_loc (input_location, code, type, operand.expr);
789
790 }
791
792 /* Expand power operator to optimal multiplications when a value is raised
793    to a constant integer n. See section 4.6.3, "Evaluation of Powers" of
794    Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer
795    Programming", 3rd Edition, 1998.  */
796
797 /* This code is mostly duplicated from expand_powi in the backend.
798    We establish the "optimal power tree" lookup table with the defined size.
799    The items in the table are the exponents used to calculate the index
800    exponents. Any integer n less than the value can get an "addition chain",
801    with the first node being one.  */
802 #define POWI_TABLE_SIZE 256
803
804 /* The table is from builtins.c.  */
805 static const unsigned char powi_table[POWI_TABLE_SIZE] =
806   {
807       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
808       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
809       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
810      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
811      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
812      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
813      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
814      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
815      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
816      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
817      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
818      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
819      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
820      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
821      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
822      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
823      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
824      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
825      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
826      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
827      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
828      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
829      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
830      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
831      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
832     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
833     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
834     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
835     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
836     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
837     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
838     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
839   };
840
841 /* If n is larger than lookup table's max index, we use the "window 
842    method".  */
843 #define POWI_WINDOW_SIZE 3
844
845 /* Recursive function to expand the power operator. The temporary 
846    values are put in tmpvar. The function returns tmpvar[1] ** n.  */
847 static tree
848 gfc_conv_powi (gfc_se * se, unsigned HOST_WIDE_INT n, tree * tmpvar)
849 {
850   tree op0;
851   tree op1;
852   tree tmp;
853   int digit;
854
855   if (n < POWI_TABLE_SIZE)
856     {
857       if (tmpvar[n])
858         return tmpvar[n];
859
860       op0 = gfc_conv_powi (se, n - powi_table[n], tmpvar);
861       op1 = gfc_conv_powi (se, powi_table[n], tmpvar);
862     }
863   else if (n & 1)
864     {
865       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
866       op0 = gfc_conv_powi (se, n - digit, tmpvar);
867       op1 = gfc_conv_powi (se, digit, tmpvar);
868     }
869   else
870     {
871       op0 = gfc_conv_powi (se, n >> 1, tmpvar);
872       op1 = op0;
873     }
874
875   tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (op0), op0, op1);
876   tmp = gfc_evaluate_now (tmp, &se->pre);
877
878   if (n < POWI_TABLE_SIZE)
879     tmpvar[n] = tmp;
880
881   return tmp;
882 }
883
884
885 /* Expand lhs ** rhs. rhs is a constant integer. If it expands successfully,
886    return 1. Else return 0 and a call to runtime library functions
887    will have to be built.  */
888 static int
889 gfc_conv_cst_int_power (gfc_se * se, tree lhs, tree rhs)
890 {
891   tree cond;
892   tree tmp;
893   tree type;
894   tree vartmp[POWI_TABLE_SIZE];
895   HOST_WIDE_INT m;
896   unsigned HOST_WIDE_INT n;
897   int sgn;
898
899   /* If exponent is too large, we won't expand it anyway, so don't bother
900      with large integer values.  */
901   if (!double_int_fits_in_shwi_p (TREE_INT_CST (rhs)))
902     return 0;
903
904   m = double_int_to_shwi (TREE_INT_CST (rhs));
905   /* There's no ABS for HOST_WIDE_INT, so here we go. It also takes care
906      of the asymmetric range of the integer type.  */
907   n = (unsigned HOST_WIDE_INT) (m < 0 ? -m : m);
908   
909   type = TREE_TYPE (lhs);
910   sgn = tree_int_cst_sgn (rhs);
911
912   if (((FLOAT_TYPE_P (type) && !flag_unsafe_math_optimizations)
913        || optimize_size) && (m > 2 || m < -1))
914     return 0;
915
916   /* rhs == 0  */
917   if (sgn == 0)
918     {
919       se->expr = gfc_build_const (type, integer_one_node);
920       return 1;
921     }
922
923   /* If rhs < 0 and lhs is an integer, the result is -1, 0 or 1.  */
924   if ((sgn == -1) && (TREE_CODE (type) == INTEGER_TYPE))
925     {
926       tmp = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
927                              lhs, build_int_cst (TREE_TYPE (lhs), -1));
928       cond = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
929                               lhs, build_int_cst (TREE_TYPE (lhs), 1));
930
931       /* If rhs is even,
932          result = (lhs == 1 || lhs == -1) ? 1 : 0.  */
933       if ((n & 1) == 0)
934         {
935           tmp = fold_build2_loc (input_location, TRUTH_OR_EXPR,
936                                  boolean_type_node, tmp, cond);
937           se->expr = fold_build3_loc (input_location, COND_EXPR, type,
938                                       tmp, build_int_cst (type, 1),
939                                       build_int_cst (type, 0));
940           return 1;
941         }
942       /* If rhs is odd,
943          result = (lhs == 1) ? 1 : (lhs == -1) ? -1 : 0.  */
944       tmp = fold_build3_loc (input_location, COND_EXPR, type, tmp,
945                              build_int_cst (type, -1),
946                              build_int_cst (type, 0));
947       se->expr = fold_build3_loc (input_location, COND_EXPR, type,
948                                   cond, build_int_cst (type, 1), tmp);
949       return 1;
950     }
951
952   memset (vartmp, 0, sizeof (vartmp));
953   vartmp[1] = lhs;
954   if (sgn == -1)
955     {
956       tmp = gfc_build_const (type, integer_one_node);
957       vartmp[1] = fold_build2_loc (input_location, RDIV_EXPR, type, tmp,
958                                    vartmp[1]);
959     }
960
961   se->expr = gfc_conv_powi (se, n, vartmp);
962
963   return 1;
964 }
965
966
967 /* Power op (**).  Constant integer exponent has special handling.  */
968
969 static void
970 gfc_conv_power_op (gfc_se * se, gfc_expr * expr)
971 {
972   tree gfc_int4_type_node;
973   int kind;
974   int ikind;
975   gfc_se lse;
976   gfc_se rse;
977   tree fndecl = NULL;
978
979   gfc_init_se (&lse, se);
980   gfc_conv_expr_val (&lse, expr->value.op.op1);
981   lse.expr = gfc_evaluate_now (lse.expr, &lse.pre);
982   gfc_add_block_to_block (&se->pre, &lse.pre);
983
984   gfc_init_se (&rse, se);
985   gfc_conv_expr_val (&rse, expr->value.op.op2);
986   gfc_add_block_to_block (&se->pre, &rse.pre);
987
988   if (expr->value.op.op2->ts.type == BT_INTEGER
989       && expr->value.op.op2->expr_type == EXPR_CONSTANT)
990     if (gfc_conv_cst_int_power (se, lse.expr, rse.expr))
991       return;
992
993   gfc_int4_type_node = gfc_get_int_type (4);
994
995   kind = expr->value.op.op1->ts.kind;
996   switch (expr->value.op.op2->ts.type)
997     {
998     case BT_INTEGER:
999       ikind = expr->value.op.op2->ts.kind;
1000       switch (ikind)
1001         {
1002         case 1:
1003         case 2:
1004           rse.expr = convert (gfc_int4_type_node, rse.expr);
1005           /* Fall through.  */
1006
1007         case 4:
1008           ikind = 0;
1009           break;
1010           
1011         case 8:
1012           ikind = 1;
1013           break;
1014
1015         case 16:
1016           ikind = 2;
1017           break;
1018
1019         default:
1020           gcc_unreachable ();
1021         }
1022       switch (kind)
1023         {
1024         case 1:
1025         case 2:
1026           if (expr->value.op.op1->ts.type == BT_INTEGER)
1027             lse.expr = convert (gfc_int4_type_node, lse.expr);
1028           else
1029             gcc_unreachable ();
1030           /* Fall through.  */
1031
1032         case 4:
1033           kind = 0;
1034           break;
1035           
1036         case 8:
1037           kind = 1;
1038           break;
1039
1040         case 10:
1041           kind = 2;
1042           break;
1043
1044         case 16:
1045           kind = 3;
1046           break;
1047
1048         default:
1049           gcc_unreachable ();
1050         }
1051       
1052       switch (expr->value.op.op1->ts.type)
1053         {
1054         case BT_INTEGER:
1055           if (kind == 3) /* Case 16 was not handled properly above.  */
1056             kind = 2;
1057           fndecl = gfor_fndecl_math_powi[kind][ikind].integer;
1058           break;
1059
1060         case BT_REAL:
1061           /* Use builtins for real ** int4.  */
1062           if (ikind == 0)
1063             {
1064               switch (kind)
1065                 {
1066                 case 0:
1067                   fndecl = built_in_decls[BUILT_IN_POWIF];
1068                   break;
1069                 
1070                 case 1:
1071                   fndecl = built_in_decls[BUILT_IN_POWI];
1072                   break;
1073
1074                 case 2:
1075                   fndecl = built_in_decls[BUILT_IN_POWIL];
1076                   break;
1077
1078                 case 3:
1079                   /* Use the __builtin_powil() only if real(kind=16) is 
1080                      actually the C long double type.  */
1081                   if (!gfc_real16_is_float128)
1082                     fndecl = built_in_decls[BUILT_IN_POWIL];
1083                   break;
1084
1085                 default:
1086                   gcc_unreachable ();
1087                 }
1088             }
1089
1090           /* If we don't have a good builtin for this, go for the 
1091              library function.  */
1092           if (!fndecl)
1093             fndecl = gfor_fndecl_math_powi[kind][ikind].real;
1094           break;
1095
1096         case BT_COMPLEX:
1097           fndecl = gfor_fndecl_math_powi[kind][ikind].cmplx;
1098           break;
1099
1100         default:
1101           gcc_unreachable ();
1102         }
1103       break;
1104
1105     case BT_REAL:
1106       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_POW, kind);
1107       break;
1108
1109     case BT_COMPLEX:
1110       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_CPOW, kind);
1111       break;
1112
1113     default:
1114       gcc_unreachable ();
1115       break;
1116     }
1117
1118   se->expr = build_call_expr_loc (input_location,
1119                               fndecl, 2, lse.expr, rse.expr);
1120 }
1121
1122
1123 /* Generate code to allocate a string temporary.  */
1124
1125 tree
1126 gfc_conv_string_tmp (gfc_se * se, tree type, tree len)
1127 {
1128   tree var;
1129   tree tmp;
1130
1131   if (gfc_can_put_var_on_stack (len))
1132     {
1133       /* Create a temporary variable to hold the result.  */
1134       tmp = fold_build2_loc (input_location, MINUS_EXPR,
1135                              gfc_charlen_type_node, len,
1136                              build_int_cst (gfc_charlen_type_node, 1));
1137       tmp = build_range_type (gfc_array_index_type, gfc_index_zero_node, tmp);
1138
1139       if (TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
1140         tmp = build_array_type (TREE_TYPE (TREE_TYPE (type)), tmp);
1141       else
1142         tmp = build_array_type (TREE_TYPE (type), tmp);
1143
1144       var = gfc_create_var (tmp, "str");
1145       var = gfc_build_addr_expr (type, var);
1146     }
1147   else
1148     {
1149       /* Allocate a temporary to hold the result.  */
1150       var = gfc_create_var (type, "pstr");
1151       tmp = gfc_call_malloc (&se->pre, type,
1152                              fold_build2_loc (input_location, MULT_EXPR,
1153                                               TREE_TYPE (len), len,
1154                                               fold_convert (TREE_TYPE (len),
1155                                                             TYPE_SIZE (type))));
1156       gfc_add_modify (&se->pre, var, tmp);
1157
1158       /* Free the temporary afterwards.  */
1159       tmp = gfc_call_free (convert (pvoid_type_node, var));
1160       gfc_add_expr_to_block (&se->post, tmp);
1161     }
1162
1163   return var;
1164 }
1165
1166
1167 /* Handle a string concatenation operation.  A temporary will be allocated to
1168    hold the result.  */
1169
1170 static void
1171 gfc_conv_concat_op (gfc_se * se, gfc_expr * expr)
1172 {
1173   gfc_se lse, rse;
1174   tree len, type, var, tmp, fndecl;
1175
1176   gcc_assert (expr->value.op.op1->ts.type == BT_CHARACTER
1177               && expr->value.op.op2->ts.type == BT_CHARACTER);
1178   gcc_assert (expr->value.op.op1->ts.kind == expr->value.op.op2->ts.kind);
1179
1180   gfc_init_se (&lse, se);
1181   gfc_conv_expr (&lse, expr->value.op.op1);
1182   gfc_conv_string_parameter (&lse);
1183   gfc_init_se (&rse, se);
1184   gfc_conv_expr (&rse, expr->value.op.op2);
1185   gfc_conv_string_parameter (&rse);
1186
1187   gfc_add_block_to_block (&se->pre, &lse.pre);
1188   gfc_add_block_to_block (&se->pre, &rse.pre);
1189
1190   type = gfc_get_character_type (expr->ts.kind, expr->ts.u.cl);
1191   len = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1192   if (len == NULL_TREE)
1193     {
1194       len = fold_build2_loc (input_location, PLUS_EXPR,
1195                              TREE_TYPE (lse.string_length),
1196                              lse.string_length, rse.string_length);
1197     }
1198
1199   type = build_pointer_type (type);
1200
1201   var = gfc_conv_string_tmp (se, type, len);
1202
1203   /* Do the actual concatenation.  */
1204   if (expr->ts.kind == 1)
1205     fndecl = gfor_fndecl_concat_string;
1206   else if (expr->ts.kind == 4)
1207     fndecl = gfor_fndecl_concat_string_char4;
1208   else
1209     gcc_unreachable ();
1210
1211   tmp = build_call_expr_loc (input_location,
1212                          fndecl, 6, len, var, lse.string_length, lse.expr,
1213                          rse.string_length, rse.expr);
1214   gfc_add_expr_to_block (&se->pre, tmp);
1215
1216   /* Add the cleanup for the operands.  */
1217   gfc_add_block_to_block (&se->pre, &rse.post);
1218   gfc_add_block_to_block (&se->pre, &lse.post);
1219
1220   se->expr = var;
1221   se->string_length = len;
1222 }
1223
1224 /* Translates an op expression. Common (binary) cases are handled by this
1225    function, others are passed on. Recursion is used in either case.
1226    We use the fact that (op1.ts == op2.ts) (except for the power
1227    operator **).
1228    Operators need no special handling for scalarized expressions as long as
1229    they call gfc_conv_simple_val to get their operands.
1230    Character strings get special handling.  */
1231
1232 static void
1233 gfc_conv_expr_op (gfc_se * se, gfc_expr * expr)
1234 {
1235   enum tree_code code;
1236   gfc_se lse;
1237   gfc_se rse;
1238   tree tmp, type;
1239   int lop;
1240   int checkstring;
1241
1242   checkstring = 0;
1243   lop = 0;
1244   switch (expr->value.op.op)
1245     {
1246     case INTRINSIC_PARENTHESES:
1247       if ((expr->ts.type == BT_REAL
1248            || expr->ts.type == BT_COMPLEX)
1249           && gfc_option.flag_protect_parens)
1250         {
1251           gfc_conv_unary_op (PAREN_EXPR, se, expr);
1252           gcc_assert (FLOAT_TYPE_P (TREE_TYPE (se->expr)));
1253           return;
1254         }
1255
1256       /* Fallthrough.  */
1257     case INTRINSIC_UPLUS:
1258       gfc_conv_expr (se, expr->value.op.op1);
1259       return;
1260
1261     case INTRINSIC_UMINUS:
1262       gfc_conv_unary_op (NEGATE_EXPR, se, expr);
1263       return;
1264
1265     case INTRINSIC_NOT:
1266       gfc_conv_unary_op (TRUTH_NOT_EXPR, se, expr);
1267       return;
1268
1269     case INTRINSIC_PLUS:
1270       code = PLUS_EXPR;
1271       break;
1272
1273     case INTRINSIC_MINUS:
1274       code = MINUS_EXPR;
1275       break;
1276
1277     case INTRINSIC_TIMES:
1278       code = MULT_EXPR;
1279       break;
1280
1281     case INTRINSIC_DIVIDE:
1282       /* If expr is a real or complex expr, use an RDIV_EXPR. If op1 is
1283          an integer, we must round towards zero, so we use a
1284          TRUNC_DIV_EXPR.  */
1285       if (expr->ts.type == BT_INTEGER)
1286         code = TRUNC_DIV_EXPR;
1287       else
1288         code = RDIV_EXPR;
1289       break;
1290
1291     case INTRINSIC_POWER:
1292       gfc_conv_power_op (se, expr);
1293       return;
1294
1295     case INTRINSIC_CONCAT:
1296       gfc_conv_concat_op (se, expr);
1297       return;
1298
1299     case INTRINSIC_AND:
1300       code = TRUTH_ANDIF_EXPR;
1301       lop = 1;
1302       break;
1303
1304     case INTRINSIC_OR:
1305       code = TRUTH_ORIF_EXPR;
1306       lop = 1;
1307       break;
1308
1309       /* EQV and NEQV only work on logicals, but since we represent them
1310          as integers, we can use EQ_EXPR and NE_EXPR for them in GIMPLE.  */
1311     case INTRINSIC_EQ:
1312     case INTRINSIC_EQ_OS:
1313     case INTRINSIC_EQV:
1314       code = EQ_EXPR;
1315       checkstring = 1;
1316       lop = 1;
1317       break;
1318
1319     case INTRINSIC_NE:
1320     case INTRINSIC_NE_OS:
1321     case INTRINSIC_NEQV:
1322       code = NE_EXPR;
1323       checkstring = 1;
1324       lop = 1;
1325       break;
1326
1327     case INTRINSIC_GT:
1328     case INTRINSIC_GT_OS:
1329       code = GT_EXPR;
1330       checkstring = 1;
1331       lop = 1;
1332       break;
1333
1334     case INTRINSIC_GE:
1335     case INTRINSIC_GE_OS:
1336       code = GE_EXPR;
1337       checkstring = 1;
1338       lop = 1;
1339       break;
1340
1341     case INTRINSIC_LT:
1342     case INTRINSIC_LT_OS:
1343       code = LT_EXPR;
1344       checkstring = 1;
1345       lop = 1;
1346       break;
1347
1348     case INTRINSIC_LE:
1349     case INTRINSIC_LE_OS:
1350       code = LE_EXPR;
1351       checkstring = 1;
1352       lop = 1;
1353       break;
1354
1355     case INTRINSIC_USER:
1356     case INTRINSIC_ASSIGN:
1357       /* These should be converted into function calls by the frontend.  */
1358       gcc_unreachable ();
1359
1360     default:
1361       fatal_error ("Unknown intrinsic op");
1362       return;
1363     }
1364
1365   /* The only exception to this is **, which is handled separately anyway.  */
1366   gcc_assert (expr->value.op.op1->ts.type == expr->value.op.op2->ts.type);
1367
1368   if (checkstring && expr->value.op.op1->ts.type != BT_CHARACTER)
1369     checkstring = 0;
1370
1371   /* lhs */
1372   gfc_init_se (&lse, se);
1373   gfc_conv_expr (&lse, expr->value.op.op1);
1374   gfc_add_block_to_block (&se->pre, &lse.pre);
1375
1376   /* rhs */
1377   gfc_init_se (&rse, se);
1378   gfc_conv_expr (&rse, expr->value.op.op2);
1379   gfc_add_block_to_block (&se->pre, &rse.pre);
1380
1381   if (checkstring)
1382     {
1383       gfc_conv_string_parameter (&lse);
1384       gfc_conv_string_parameter (&rse);
1385
1386       lse.expr = gfc_build_compare_string (lse.string_length, lse.expr,
1387                                            rse.string_length, rse.expr,
1388                                            expr->value.op.op1->ts.kind,
1389                                            code);
1390       rse.expr = build_int_cst (TREE_TYPE (lse.expr), 0);
1391       gfc_add_block_to_block (&lse.post, &rse.post);
1392     }
1393
1394   type = gfc_typenode_for_spec (&expr->ts);
1395
1396   if (lop)
1397     {
1398       /* The result of logical ops is always boolean_type_node.  */
1399       tmp = fold_build2_loc (input_location, code, boolean_type_node,
1400                              lse.expr, rse.expr);
1401       se->expr = convert (type, tmp);
1402     }
1403   else
1404     se->expr = fold_build2_loc (input_location, code, type, lse.expr, rse.expr);
1405
1406   /* Add the post blocks.  */
1407   gfc_add_block_to_block (&se->post, &rse.post);
1408   gfc_add_block_to_block (&se->post, &lse.post);
1409 }
1410
1411 /* If a string's length is one, we convert it to a single character.  */
1412
1413 tree
1414 gfc_string_to_single_character (tree len, tree str, int kind)
1415 {
1416   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str)));
1417
1418   if (!INTEGER_CST_P (len) || TREE_INT_CST_HIGH (len) != 0)
1419     return NULL_TREE;
1420
1421   if (TREE_INT_CST_LOW (len) == 1)
1422     {
1423       str = fold_convert (gfc_get_pchar_type (kind), str);
1424       return build_fold_indirect_ref_loc (input_location, str);
1425     }
1426
1427   if (kind == 1
1428       && TREE_CODE (str) == ADDR_EXPR
1429       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
1430       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
1431       && array_ref_low_bound (TREE_OPERAND (str, 0))
1432          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
1433       && TREE_INT_CST_LOW (len) > 1
1434       && TREE_INT_CST_LOW (len)
1435          == (unsigned HOST_WIDE_INT)
1436             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
1437     {
1438       tree ret = fold_convert (gfc_get_pchar_type (kind), str);
1439       ret = build_fold_indirect_ref_loc (input_location, ret);
1440       if (TREE_CODE (ret) == INTEGER_CST)
1441         {
1442           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
1443           int i, length = TREE_STRING_LENGTH (string_cst);
1444           const char *ptr = TREE_STRING_POINTER (string_cst);
1445
1446           for (i = 1; i < length; i++)
1447             if (ptr[i] != ' ')
1448               return NULL_TREE;
1449
1450           return ret;
1451         }
1452     }
1453
1454   return NULL_TREE;
1455 }
1456
1457
1458 void
1459 gfc_conv_scalar_char_value (gfc_symbol *sym, gfc_se *se, gfc_expr **expr)
1460 {
1461
1462   if (sym->backend_decl)
1463     {
1464       /* This becomes the nominal_type in
1465          function.c:assign_parm_find_data_types.  */
1466       TREE_TYPE (sym->backend_decl) = unsigned_char_type_node;
1467       /* This becomes the passed_type in
1468          function.c:assign_parm_find_data_types.  C promotes char to
1469          integer for argument passing.  */
1470       DECL_ARG_TYPE (sym->backend_decl) = unsigned_type_node;
1471
1472       DECL_BY_REFERENCE (sym->backend_decl) = 0;
1473     }
1474
1475   if (expr != NULL)
1476     {
1477       /* If we have a constant character expression, make it into an
1478          integer.  */
1479       if ((*expr)->expr_type == EXPR_CONSTANT)
1480         {
1481           gfc_typespec ts;
1482           gfc_clear_ts (&ts);
1483
1484           *expr = gfc_get_int_expr (gfc_default_integer_kind, NULL,
1485                                     (int)(*expr)->value.character.string[0]);
1486           if ((*expr)->ts.kind != gfc_c_int_kind)
1487             {
1488               /* The expr needs to be compatible with a C int.  If the 
1489                  conversion fails, then the 2 causes an ICE.  */
1490               ts.type = BT_INTEGER;
1491               ts.kind = gfc_c_int_kind;
1492               gfc_convert_type (*expr, &ts, 2);
1493             }
1494         }
1495       else if (se != NULL && (*expr)->expr_type == EXPR_VARIABLE)
1496         {
1497           if ((*expr)->ref == NULL)
1498             {
1499               se->expr = gfc_string_to_single_character
1500                 (build_int_cst (integer_type_node, 1),
1501                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
1502                                       gfc_get_symbol_decl
1503                                       ((*expr)->symtree->n.sym)),
1504                  (*expr)->ts.kind);
1505             }
1506           else
1507             {
1508               gfc_conv_variable (se, *expr);
1509               se->expr = gfc_string_to_single_character
1510                 (build_int_cst (integer_type_node, 1),
1511                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
1512                                       se->expr),
1513                  (*expr)->ts.kind);
1514             }
1515         }
1516     }
1517 }
1518
1519 /* Helper function for gfc_build_compare_string.  Return LEN_TRIM value
1520    if STR is a string literal, otherwise return -1.  */
1521
1522 static int
1523 gfc_optimize_len_trim (tree len, tree str, int kind)
1524 {
1525   if (kind == 1
1526       && TREE_CODE (str) == ADDR_EXPR
1527       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
1528       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
1529       && array_ref_low_bound (TREE_OPERAND (str, 0))
1530          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
1531       && TREE_INT_CST_LOW (len) >= 1
1532       && TREE_INT_CST_LOW (len)
1533          == (unsigned HOST_WIDE_INT)
1534             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
1535     {
1536       tree folded = fold_convert (gfc_get_pchar_type (kind), str);
1537       folded = build_fold_indirect_ref_loc (input_location, folded);
1538       if (TREE_CODE (folded) == INTEGER_CST)
1539         {
1540           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
1541           int length = TREE_STRING_LENGTH (string_cst);
1542           const char *ptr = TREE_STRING_POINTER (string_cst);
1543
1544           for (; length > 0; length--)
1545             if (ptr[length - 1] != ' ')
1546               break;
1547
1548           return length;
1549         }
1550     }
1551   return -1;
1552 }
1553
1554 /* Compare two strings. If they are all single characters, the result is the
1555    subtraction of them. Otherwise, we build a library call.  */
1556
1557 tree
1558 gfc_build_compare_string (tree len1, tree str1, tree len2, tree str2, int kind,
1559                           enum tree_code code)
1560 {
1561   tree sc1;
1562   tree sc2;
1563   tree fndecl;
1564
1565   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str1)));
1566   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str2)));
1567
1568   sc1 = gfc_string_to_single_character (len1, str1, kind);
1569   sc2 = gfc_string_to_single_character (len2, str2, kind);
1570
1571   if (sc1 != NULL_TREE && sc2 != NULL_TREE)
1572     {
1573       /* Deal with single character specially.  */
1574       sc1 = fold_convert (integer_type_node, sc1);
1575       sc2 = fold_convert (integer_type_node, sc2);
1576       return fold_build2_loc (input_location, MINUS_EXPR, integer_type_node,
1577                               sc1, sc2);
1578     }
1579
1580   if ((code == EQ_EXPR || code == NE_EXPR)
1581       && optimize
1582       && INTEGER_CST_P (len1) && INTEGER_CST_P (len2))
1583     {
1584       /* If one string is a string literal with LEN_TRIM longer
1585          than the length of the second string, the strings
1586          compare unequal.  */
1587       int len = gfc_optimize_len_trim (len1, str1, kind);
1588       if (len > 0 && compare_tree_int (len2, len) < 0)
1589         return integer_one_node;
1590       len = gfc_optimize_len_trim (len2, str2, kind);
1591       if (len > 0 && compare_tree_int (len1, len) < 0)
1592         return integer_one_node;
1593     }
1594
1595   /* Build a call for the comparison.  */
1596   if (kind == 1)
1597     fndecl = gfor_fndecl_compare_string;
1598   else if (kind == 4)
1599     fndecl = gfor_fndecl_compare_string_char4;
1600   else
1601     gcc_unreachable ();
1602
1603   return build_call_expr_loc (input_location, fndecl, 4,
1604                               len1, str1, len2, str2);
1605 }
1606
1607
1608 /* Return the backend_decl for a procedure pointer component.  */
1609
1610 static tree
1611 get_proc_ptr_comp (gfc_expr *e)
1612 {
1613   gfc_se comp_se;
1614   gfc_expr *e2;
1615   gfc_init_se (&comp_se, NULL);
1616   e2 = gfc_copy_expr (e);
1617   e2->expr_type = EXPR_VARIABLE;
1618   gfc_conv_expr (&comp_se, e2);
1619   gfc_free_expr (e2);
1620   return build_fold_addr_expr_loc (input_location, comp_se.expr);
1621 }
1622
1623
1624 static void
1625 conv_function_val (gfc_se * se, gfc_symbol * sym, gfc_expr * expr)
1626 {
1627   tree tmp;
1628
1629   if (gfc_is_proc_ptr_comp (expr, NULL))
1630     tmp = get_proc_ptr_comp (expr);
1631   else if (sym->attr.dummy)
1632     {
1633       tmp = gfc_get_symbol_decl (sym);
1634       if (sym->attr.proc_pointer)
1635         tmp = build_fold_indirect_ref_loc (input_location,
1636                                        tmp);
1637       gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == POINTER_TYPE
1638               && TREE_CODE (TREE_TYPE (TREE_TYPE (tmp))) == FUNCTION_TYPE);
1639     }
1640   else
1641     {
1642       if (!sym->backend_decl)
1643         sym->backend_decl = gfc_get_extern_function_decl (sym);
1644
1645       tmp = sym->backend_decl;
1646
1647       if (sym->attr.cray_pointee)
1648         {
1649           /* TODO - make the cray pointee a pointer to a procedure,
1650              assign the pointer to it and use it for the call.  This
1651              will do for now!  */
1652           tmp = convert (build_pointer_type (TREE_TYPE (tmp)),
1653                          gfc_get_symbol_decl (sym->cp_pointer));
1654           tmp = gfc_evaluate_now (tmp, &se->pre);
1655         }
1656
1657       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
1658         {
1659           gcc_assert (TREE_CODE (tmp) == FUNCTION_DECL);
1660           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
1661         }
1662     }
1663   se->expr = tmp;
1664 }
1665
1666
1667 /* Initialize MAPPING.  */
1668
1669 void
1670 gfc_init_interface_mapping (gfc_interface_mapping * mapping)
1671 {
1672   mapping->syms = NULL;
1673   mapping->charlens = NULL;
1674 }
1675
1676
1677 /* Free all memory held by MAPPING (but not MAPPING itself).  */
1678
1679 void
1680 gfc_free_interface_mapping (gfc_interface_mapping * mapping)
1681 {
1682   gfc_interface_sym_mapping *sym;
1683   gfc_interface_sym_mapping *nextsym;
1684   gfc_charlen *cl;
1685   gfc_charlen *nextcl;
1686
1687   for (sym = mapping->syms; sym; sym = nextsym)
1688     {
1689       nextsym = sym->next;
1690       sym->new_sym->n.sym->formal = NULL;
1691       gfc_free_symbol (sym->new_sym->n.sym);
1692       gfc_free_expr (sym->expr);
1693       gfc_free (sym->new_sym);
1694       gfc_free (sym);
1695     }
1696   for (cl = mapping->charlens; cl; cl = nextcl)
1697     {
1698       nextcl = cl->next;
1699       gfc_free_expr (cl->length);
1700       gfc_free (cl);
1701     }
1702 }
1703
1704
1705 /* Return a copy of gfc_charlen CL.  Add the returned structure to
1706    MAPPING so that it will be freed by gfc_free_interface_mapping.  */
1707
1708 static gfc_charlen *
1709 gfc_get_interface_mapping_charlen (gfc_interface_mapping * mapping,
1710                                    gfc_charlen * cl)
1711 {
1712   gfc_charlen *new_charlen;
1713
1714   new_charlen = gfc_get_charlen ();
1715   new_charlen->next = mapping->charlens;
1716   new_charlen->length = gfc_copy_expr (cl->length);
1717
1718   mapping->charlens = new_charlen;
1719   return new_charlen;
1720 }
1721
1722
1723 /* A subroutine of gfc_add_interface_mapping.  Return a descriptorless
1724    array variable that can be used as the actual argument for dummy
1725    argument SYM.  Add any initialization code to BLOCK.  PACKED is as
1726    for gfc_get_nodesc_array_type and DATA points to the first element
1727    in the passed array.  */
1728
1729 static tree
1730 gfc_get_interface_mapping_array (stmtblock_t * block, gfc_symbol * sym,
1731                                  gfc_packed packed, tree data)
1732 {
1733   tree type;
1734   tree var;
1735
1736   type = gfc_typenode_for_spec (&sym->ts);
1737   type = gfc_get_nodesc_array_type (type, sym->as, packed,
1738                                     !sym->attr.target && !sym->attr.pointer
1739                                     && !sym->attr.proc_pointer);
1740
1741   var = gfc_create_var (type, "ifm");
1742   gfc_add_modify (block, var, fold_convert (type, data));
1743
1744   return var;
1745 }
1746
1747
1748 /* A subroutine of gfc_add_interface_mapping.  Set the stride, upper bounds
1749    and offset of descriptorless array type TYPE given that it has the same
1750    size as DESC.  Add any set-up code to BLOCK.  */
1751
1752 static void
1753 gfc_set_interface_mapping_bounds (stmtblock_t * block, tree type, tree desc)
1754 {
1755   int n;
1756   tree dim;
1757   tree offset;
1758   tree tmp;
1759
1760   offset = gfc_index_zero_node;
1761   for (n = 0; n < GFC_TYPE_ARRAY_RANK (type); n++)
1762     {
1763       dim = gfc_rank_cst[n];
1764       GFC_TYPE_ARRAY_STRIDE (type, n) = gfc_conv_array_stride (desc, n);
1765       if (GFC_TYPE_ARRAY_LBOUND (type, n) == NULL_TREE)
1766         {
1767           GFC_TYPE_ARRAY_LBOUND (type, n)
1768                 = gfc_conv_descriptor_lbound_get (desc, dim);
1769           GFC_TYPE_ARRAY_UBOUND (type, n)
1770                 = gfc_conv_descriptor_ubound_get (desc, dim);
1771         }
1772       else if (GFC_TYPE_ARRAY_UBOUND (type, n) == NULL_TREE)
1773         {
1774           tmp = fold_build2_loc (input_location, MINUS_EXPR,
1775                                  gfc_array_index_type,
1776                                  gfc_conv_descriptor_ubound_get (desc, dim),
1777                                  gfc_conv_descriptor_lbound_get (desc, dim));
1778           tmp = fold_build2_loc (input_location, PLUS_EXPR,
1779                                  gfc_array_index_type,
1780                                  GFC_TYPE_ARRAY_LBOUND (type, n), tmp);
1781           tmp = gfc_evaluate_now (tmp, block);
1782           GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
1783         }
1784       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
1785                              GFC_TYPE_ARRAY_LBOUND (type, n),
1786                              GFC_TYPE_ARRAY_STRIDE (type, n));
1787       offset = fold_build2_loc (input_location, MINUS_EXPR,
1788                                 gfc_array_index_type, offset, tmp);
1789     }
1790   offset = gfc_evaluate_now (offset, block);
1791   GFC_TYPE_ARRAY_OFFSET (type) = offset;
1792 }
1793
1794
1795 /* Extend MAPPING so that it maps dummy argument SYM to the value stored
1796    in SE.  The caller may still use se->expr and se->string_length after
1797    calling this function.  */
1798
1799 void
1800 gfc_add_interface_mapping (gfc_interface_mapping * mapping,
1801                            gfc_symbol * sym, gfc_se * se,
1802                            gfc_expr *expr)
1803 {
1804   gfc_interface_sym_mapping *sm;
1805   tree desc;
1806   tree tmp;
1807   tree value;
1808   gfc_symbol *new_sym;
1809   gfc_symtree *root;
1810   gfc_symtree *new_symtree;
1811
1812   /* Create a new symbol to represent the actual argument.  */
1813   new_sym = gfc_new_symbol (sym->name, NULL);
1814   new_sym->ts = sym->ts;
1815   new_sym->as = gfc_copy_array_spec (sym->as);
1816   new_sym->attr.referenced = 1;
1817   new_sym->attr.dimension = sym->attr.dimension;
1818   new_sym->attr.contiguous = sym->attr.contiguous;
1819   new_sym->attr.codimension = sym->attr.codimension;
1820   new_sym->attr.pointer = sym->attr.pointer;
1821   new_sym->attr.allocatable = sym->attr.allocatable;
1822   new_sym->attr.flavor = sym->attr.flavor;
1823   new_sym->attr.function = sym->attr.function;
1824
1825   /* Ensure that the interface is available and that
1826      descriptors are passed for array actual arguments.  */
1827   if (sym->attr.flavor == FL_PROCEDURE)
1828     {
1829       new_sym->formal = expr->symtree->n.sym->formal;
1830       new_sym->attr.always_explicit
1831             = expr->symtree->n.sym->attr.always_explicit;
1832     }
1833
1834   /* Create a fake symtree for it.  */
1835   root = NULL;
1836   new_symtree = gfc_new_symtree (&root, sym->name);
1837   new_symtree->n.sym = new_sym;
1838   gcc_assert (new_symtree == root);
1839
1840   /* Create a dummy->actual mapping.  */
1841   sm = XCNEW (gfc_interface_sym_mapping);
1842   sm->next = mapping->syms;
1843   sm->old = sym;
1844   sm->new_sym = new_symtree;
1845   sm->expr = gfc_copy_expr (expr);
1846   mapping->syms = sm;
1847
1848   /* Stabilize the argument's value.  */
1849   if (!sym->attr.function && se)
1850     se->expr = gfc_evaluate_now (se->expr, &se->pre);
1851
1852   if (sym->ts.type == BT_CHARACTER)
1853     {
1854       /* Create a copy of the dummy argument's length.  */
1855       new_sym->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, sym->ts.u.cl);
1856       sm->expr->ts.u.cl = new_sym->ts.u.cl;
1857
1858       /* If the length is specified as "*", record the length that
1859          the caller is passing.  We should use the callee's length
1860          in all other cases.  */
1861       if (!new_sym->ts.u.cl->length && se)
1862         {
1863           se->string_length = gfc_evaluate_now (se->string_length, &se->pre);
1864           new_sym->ts.u.cl->backend_decl = se->string_length;
1865         }
1866     }
1867
1868   if (!se)
1869     return;
1870
1871   /* Use the passed value as-is if the argument is a function.  */
1872   if (sym->attr.flavor == FL_PROCEDURE)
1873     value = se->expr;
1874
1875   /* If the argument is either a string or a pointer to a string,
1876      convert it to a boundless character type.  */
1877   else if (!sym->attr.dimension && sym->ts.type == BT_CHARACTER)
1878     {
1879       tmp = gfc_get_character_type_len (sym->ts.kind, NULL);
1880       tmp = build_pointer_type (tmp);
1881       if (sym->attr.pointer)
1882         value = build_fold_indirect_ref_loc (input_location,
1883                                          se->expr);
1884       else
1885         value = se->expr;
1886       value = fold_convert (tmp, value);
1887     }
1888
1889   /* If the argument is a scalar, a pointer to an array or an allocatable,
1890      dereference it.  */
1891   else if (!sym->attr.dimension || sym->attr.pointer || sym->attr.allocatable)
1892     value = build_fold_indirect_ref_loc (input_location,
1893                                      se->expr);
1894   
1895   /* For character(*), use the actual argument's descriptor.  */  
1896   else if (sym->ts.type == BT_CHARACTER && !new_sym->ts.u.cl->length)
1897     value = build_fold_indirect_ref_loc (input_location,
1898                                      se->expr);
1899
1900   /* If the argument is an array descriptor, use it to determine
1901      information about the actual argument's shape.  */
1902   else if (POINTER_TYPE_P (TREE_TYPE (se->expr))
1903            && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se->expr))))
1904     {
1905       /* Get the actual argument's descriptor.  */
1906       desc = build_fold_indirect_ref_loc (input_location,
1907                                       se->expr);
1908
1909       /* Create the replacement variable.  */
1910       tmp = gfc_conv_descriptor_data_get (desc);
1911       value = gfc_get_interface_mapping_array (&se->pre, sym,
1912                                                PACKED_NO, tmp);
1913
1914       /* Use DESC to work out the upper bounds, strides and offset.  */
1915       gfc_set_interface_mapping_bounds (&se->pre, TREE_TYPE (value), desc);
1916     }
1917   else
1918     /* Otherwise we have a packed array.  */
1919     value = gfc_get_interface_mapping_array (&se->pre, sym,
1920                                              PACKED_FULL, se->expr);
1921
1922   new_sym->backend_decl = value;
1923 }
1924
1925
1926 /* Called once all dummy argument mappings have been added to MAPPING,
1927    but before the mapping is used to evaluate expressions.  Pre-evaluate
1928    the length of each argument, adding any initialization code to PRE and
1929    any finalization code to POST.  */
1930
1931 void
1932 gfc_finish_interface_mapping (gfc_interface_mapping * mapping,
1933                               stmtblock_t * pre, stmtblock_t * post)
1934 {
1935   gfc_interface_sym_mapping *sym;
1936   gfc_expr *expr;
1937   gfc_se se;
1938
1939   for (sym = mapping->syms; sym; sym = sym->next)
1940     if (sym->new_sym->n.sym->ts.type == BT_CHARACTER
1941         && !sym->new_sym->n.sym->ts.u.cl->backend_decl)
1942       {
1943         expr = sym->new_sym->n.sym->ts.u.cl->length;
1944         gfc_apply_interface_mapping_to_expr (mapping, expr);
1945         gfc_init_se (&se, NULL);
1946         gfc_conv_expr (&se, expr);
1947         se.expr = fold_convert (gfc_charlen_type_node, se.expr);
1948         se.expr = gfc_evaluate_now (se.expr, &se.pre);
1949         gfc_add_block_to_block (pre, &se.pre);
1950         gfc_add_block_to_block (post, &se.post);
1951
1952         sym->new_sym->n.sym->ts.u.cl->backend_decl = se.expr;
1953       }
1954 }
1955
1956
1957 /* Like gfc_apply_interface_mapping_to_expr, but applied to
1958    constructor C.  */
1959
1960 static void
1961 gfc_apply_interface_mapping_to_cons (gfc_interface_mapping * mapping,
1962                                      gfc_constructor_base base)
1963 {
1964   gfc_constructor *c;
1965   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1966     {
1967       gfc_apply_interface_mapping_to_expr (mapping, c->expr);
1968       if (c->iterator)
1969         {
1970           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->start);
1971           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->end);
1972           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->step);
1973         }
1974     }
1975 }
1976
1977
1978 /* Like gfc_apply_interface_mapping_to_expr, but applied to
1979    reference REF.  */
1980
1981 static void
1982 gfc_apply_interface_mapping_to_ref (gfc_interface_mapping * mapping,
1983                                     gfc_ref * ref)
1984 {
1985   int n;
1986
1987   for (; ref; ref = ref->next)
1988     switch (ref->type)
1989       {
1990       case REF_ARRAY:
1991         for (n = 0; n < ref->u.ar.dimen; n++)
1992           {
1993             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.start[n]);
1994             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.end[n]);
1995             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.stride[n]);
1996           }
1997         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.offset);
1998         break;
1999
2000       case REF_COMPONENT:
2001         break;
2002
2003       case REF_SUBSTRING:
2004         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.start);
2005         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.end);
2006         break;
2007       }
2008 }
2009
2010
2011 /* Convert intrinsic function calls into result expressions.  */
2012
2013 static bool
2014 gfc_map_intrinsic_function (gfc_expr *expr, gfc_interface_mapping *mapping)
2015 {
2016   gfc_symbol *sym;
2017   gfc_expr *new_expr;
2018   gfc_expr *arg1;
2019   gfc_expr *arg2;
2020   int d, dup;
2021
2022   arg1 = expr->value.function.actual->expr;
2023   if (expr->value.function.actual->next)
2024     arg2 = expr->value.function.actual->next->expr;
2025   else
2026     arg2 = NULL;
2027
2028   sym = arg1->symtree->n.sym;
2029
2030   if (sym->attr.dummy)
2031     return false;
2032
2033   new_expr = NULL;
2034
2035   switch (expr->value.function.isym->id)
2036     {
2037     case GFC_ISYM_LEN:
2038       /* TODO figure out why this condition is necessary.  */
2039       if (sym->attr.function
2040           && (arg1->ts.u.cl->length == NULL
2041               || (arg1->ts.u.cl->length->expr_type != EXPR_CONSTANT
2042                   && arg1->ts.u.cl->length->expr_type != EXPR_VARIABLE)))
2043         return false;
2044
2045       new_expr = gfc_copy_expr (arg1->ts.u.cl->length);
2046       break;
2047
2048     case GFC_ISYM_SIZE:
2049       if (!sym->as || sym->as->rank == 0)
2050         return false;
2051
2052       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
2053         {
2054           dup = mpz_get_si (arg2->value.integer);
2055           d = dup - 1;
2056         }
2057       else
2058         {
2059           dup = sym->as->rank;
2060           d = 0;
2061         }
2062
2063       for (; d < dup; d++)
2064         {
2065           gfc_expr *tmp;
2066
2067           if (!sym->as->upper[d] || !sym->as->lower[d])
2068             {
2069               gfc_free_expr (new_expr);
2070               return false;
2071             }
2072
2073           tmp = gfc_add (gfc_copy_expr (sym->as->upper[d]),
2074                                         gfc_get_int_expr (gfc_default_integer_kind,
2075                                                           NULL, 1));
2076           tmp = gfc_subtract (tmp, gfc_copy_expr (sym->as->lower[d]));
2077           if (new_expr)
2078             new_expr = gfc_multiply (new_expr, tmp);
2079           else
2080             new_expr = tmp;
2081         }
2082       break;
2083
2084     case GFC_ISYM_LBOUND:
2085     case GFC_ISYM_UBOUND:
2086         /* TODO These implementations of lbound and ubound do not limit if
2087            the size < 0, according to F95's 13.14.53 and 13.14.113.  */
2088
2089       if (!sym->as || sym->as->rank == 0)
2090         return false;
2091
2092       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
2093         d = mpz_get_si (arg2->value.integer) - 1;
2094       else
2095         /* TODO: If the need arises, this could produce an array of
2096            ubound/lbounds.  */
2097         gcc_unreachable ();
2098
2099       if (expr->value.function.isym->id == GFC_ISYM_LBOUND)
2100         {
2101           if (sym->as->lower[d])
2102             new_expr = gfc_copy_expr (sym->as->lower[d]);
2103         }
2104       else
2105         {
2106           if (sym->as->upper[d])
2107             new_expr = gfc_copy_expr (sym->as->upper[d]);
2108         }
2109       break;
2110
2111     default:
2112       break;
2113     }
2114
2115   gfc_apply_interface_mapping_to_expr (mapping, new_expr);
2116   if (!new_expr)
2117     return false;
2118
2119   gfc_replace_expr (expr, new_expr);
2120   return true;
2121 }
2122
2123
2124 static void
2125 gfc_map_fcn_formal_to_actual (gfc_expr *expr, gfc_expr *map_expr,
2126                               gfc_interface_mapping * mapping)
2127 {
2128   gfc_formal_arglist *f;
2129   gfc_actual_arglist *actual;
2130
2131   actual = expr->value.function.actual;
2132   f = map_expr->symtree->n.sym->formal;
2133
2134   for (; f && actual; f = f->next, actual = actual->next)
2135     {
2136       if (!actual->expr)
2137         continue;
2138
2139       gfc_add_interface_mapping (mapping, f->sym, NULL, actual->expr);
2140     }
2141
2142   if (map_expr->symtree->n.sym->attr.dimension)
2143     {
2144       int d;
2145       gfc_array_spec *as;
2146
2147       as = gfc_copy_array_spec (map_expr->symtree->n.sym->as);
2148
2149       for (d = 0; d < as->rank; d++)
2150         {
2151           gfc_apply_interface_mapping_to_expr (mapping, as->lower[d]);
2152           gfc_apply_interface_mapping_to_expr (mapping, as->upper[d]);
2153         }
2154
2155       expr->value.function.esym->as = as;
2156     }
2157
2158   if (map_expr->symtree->n.sym->ts.type == BT_CHARACTER)
2159     {
2160       expr->value.function.esym->ts.u.cl->length
2161         = gfc_copy_expr (map_expr->symtree->n.sym->ts.u.cl->length);
2162
2163       gfc_apply_interface_mapping_to_expr (mapping,
2164                         expr->value.function.esym->ts.u.cl->length);
2165     }
2166 }
2167
2168
2169 /* EXPR is a copy of an expression that appeared in the interface
2170    associated with MAPPING.  Walk it recursively looking for references to
2171    dummy arguments that MAPPING maps to actual arguments.  Replace each such
2172    reference with a reference to the associated actual argument.  */
2173
2174 static void
2175 gfc_apply_interface_mapping_to_expr (gfc_interface_mapping * mapping,
2176                                      gfc_expr * expr)
2177 {
2178   gfc_interface_sym_mapping *sym;
2179   gfc_actual_arglist *actual;
2180
2181   if (!expr)
2182     return;
2183
2184   /* Copying an expression does not copy its length, so do that here.  */
2185   if (expr->ts.type == BT_CHARACTER && expr->ts.u.cl)
2186     {
2187       expr->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, expr->ts.u.cl);
2188       gfc_apply_interface_mapping_to_expr (mapping, expr->ts.u.cl->length);
2189     }
2190
2191   /* Apply the mapping to any references.  */
2192   gfc_apply_interface_mapping_to_ref (mapping, expr->ref);
2193
2194   /* ...and to the expression's symbol, if it has one.  */
2195   /* TODO Find out why the condition on expr->symtree had to be moved into
2196      the loop rather than being outside it, as originally.  */
2197   for (sym = mapping->syms; sym; sym = sym->next)
2198     if (expr->symtree && sym->old == expr->symtree->n.sym)
2199       {
2200         if (sym->new_sym->n.sym->backend_decl)
2201           expr->symtree = sym->new_sym;
2202         else if (sym->expr)
2203           gfc_replace_expr (expr, gfc_copy_expr (sym->expr));
2204       }
2205
2206       /* ...and to subexpressions in expr->value.  */
2207   switch (expr->expr_type)
2208     {
2209     case EXPR_VARIABLE:
2210     case EXPR_CONSTANT:
2211     case EXPR_NULL:
2212     case EXPR_SUBSTRING:
2213       break;
2214
2215     case EXPR_OP:
2216       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op1);
2217       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op2);
2218       break;
2219
2220     case EXPR_FUNCTION:
2221       for (actual = expr->value.function.actual; actual; actual = actual->next)
2222         gfc_apply_interface_mapping_to_expr (mapping, actual->expr);
2223
2224       if (expr->value.function.esym == NULL
2225             && expr->value.function.isym != NULL
2226             && expr->value.function.actual->expr->symtree
2227             && gfc_map_intrinsic_function (expr, mapping))
2228         break;
2229
2230       for (sym = mapping->syms; sym; sym = sym->next)
2231         if (sym->old == expr->value.function.esym)
2232           {
2233             expr->value.function.esym = sym->new_sym->n.sym;
2234             gfc_map_fcn_formal_to_actual (expr, sym->expr, mapping);
2235             expr->value.function.esym->result = sym->new_sym->n.sym;
2236           }
2237       break;
2238
2239     case EXPR_ARRAY:
2240     case EXPR_STRUCTURE:
2241       gfc_apply_interface_mapping_to_cons (mapping, expr->value.constructor);
2242       break;
2243
2244     case EXPR_COMPCALL:
2245     case EXPR_PPC:
2246       gcc_unreachable ();
2247       break;
2248     }
2249
2250   return;
2251 }
2252
2253
2254 /* Evaluate interface expression EXPR using MAPPING.  Store the result
2255    in SE.  */
2256
2257 void
2258 gfc_apply_interface_mapping (gfc_interface_mapping * mapping,
2259                              gfc_se * se, gfc_expr * expr)
2260 {
2261   expr = gfc_copy_expr (expr);
2262   gfc_apply_interface_mapping_to_expr (mapping, expr);
2263   gfc_conv_expr (se, expr);
2264   se->expr = gfc_evaluate_now (se->expr, &se->pre);
2265   gfc_free_expr (expr);
2266 }
2267
2268
2269 /* Returns a reference to a temporary array into which a component of
2270    an actual argument derived type array is copied and then returned
2271    after the function call.  */
2272 void
2273 gfc_conv_subref_array_arg (gfc_se * parmse, gfc_expr * expr, int g77,
2274                            sym_intent intent, bool formal_ptr)
2275 {
2276   gfc_se lse;
2277   gfc_se rse;
2278   gfc_ss *lss;
2279   gfc_ss *rss;
2280   gfc_loopinfo loop;
2281   gfc_loopinfo loop2;
2282   gfc_ss_info *info;
2283   tree offset;
2284   tree tmp_index;
2285   tree tmp;
2286   tree base_type;
2287   tree size;
2288   stmtblock_t body;
2289   int n;
2290   int dimen;
2291
2292   gcc_assert (expr->expr_type == EXPR_VARIABLE);
2293
2294   gfc_init_se (&lse, NULL);
2295   gfc_init_se (&rse, NULL);
2296
2297   /* Walk the argument expression.  */
2298   rss = gfc_walk_expr (expr);
2299
2300   gcc_assert (rss != gfc_ss_terminator);
2301  
2302   /* Initialize the scalarizer.  */
2303   gfc_init_loopinfo (&loop);
2304   gfc_add_ss_to_loop (&loop, rss);
2305
2306   /* Calculate the bounds of the scalarization.  */
2307   gfc_conv_ss_startstride (&loop);
2308
2309   /* Build an ss for the temporary.  */
2310   if (expr->ts.type == BT_CHARACTER && !expr->ts.u.cl->backend_decl)
2311     gfc_conv_string_length (expr->ts.u.cl, expr, &parmse->pre);
2312
2313   base_type = gfc_typenode_for_spec (&expr->ts);
2314   if (GFC_ARRAY_TYPE_P (base_type)
2315                 || GFC_DESCRIPTOR_TYPE_P (base_type))
2316     base_type = gfc_get_element_type (base_type);
2317
2318   loop.temp_ss = gfc_get_ss ();;
2319   loop.temp_ss->type = GFC_SS_TEMP;
2320   loop.temp_ss->data.temp.type = base_type;
2321
2322   if (expr->ts.type == BT_CHARACTER)
2323     loop.temp_ss->string_length = expr->ts.u.cl->backend_decl;
2324   else
2325     loop.temp_ss->string_length = NULL;
2326
2327   parmse->string_length = loop.temp_ss->string_length;
2328   loop.temp_ss->data.temp.dimen = loop.dimen;
2329   loop.temp_ss->next = gfc_ss_terminator;
2330
2331   /* Associate the SS with the loop.  */
2332   gfc_add_ss_to_loop (&loop, loop.temp_ss);
2333
2334   /* Setup the scalarizing loops.  */
2335   gfc_conv_loop_setup (&loop, &expr->where);
2336
2337   /* Pass the temporary descriptor back to the caller.  */
2338   info = &loop.temp_ss->data.info;
2339   parmse->expr = info->descriptor;
2340
2341   /* Setup the gfc_se structures.  */
2342   gfc_copy_loopinfo_to_se (&lse, &loop);
2343   gfc_copy_loopinfo_to_se (&rse, &loop);
2344
2345   rse.ss = rss;
2346   lse.ss = loop.temp_ss;
2347   gfc_mark_ss_chain_used (rss, 1);
2348   gfc_mark_ss_chain_used (loop.temp_ss, 1);
2349
2350   /* Start the scalarized loop body.  */
2351   gfc_start_scalarized_body (&loop, &body);
2352
2353   /* Translate the expression.  */
2354   gfc_conv_expr (&rse, expr);
2355
2356   gfc_conv_tmp_array_ref (&lse);
2357   gfc_advance_se_ss_chain (&lse);
2358
2359   if (intent != INTENT_OUT)
2360     {
2361       tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, true, false, true);
2362       gfc_add_expr_to_block (&body, tmp);
2363       gcc_assert (rse.ss == gfc_ss_terminator);
2364       gfc_trans_scalarizing_loops (&loop, &body);
2365     }
2366   else
2367     {
2368       /* Make sure that the temporary declaration survives by merging
2369        all the loop declarations into the current context.  */
2370       for (n = 0; n < loop.dimen; n++)
2371         {
2372           gfc_merge_block_scope (&body);
2373           body = loop.code[loop.order[n]];
2374         }
2375       gfc_merge_block_scope (&body);
2376     }
2377
2378   /* Add the post block after the second loop, so that any
2379      freeing of allocated memory is done at the right time.  */
2380   gfc_add_block_to_block (&parmse->pre, &loop.pre);
2381
2382   /**********Copy the temporary back again.*********/
2383
2384   gfc_init_se (&lse, NULL);
2385   gfc_init_se (&rse, NULL);
2386
2387   /* Walk the argument expression.  */
2388   lss = gfc_walk_expr (expr);
2389   rse.ss = loop.temp_ss;
2390   lse.ss = lss;
2391
2392   /* Initialize the scalarizer.  */
2393   gfc_init_loopinfo (&loop2);
2394   gfc_add_ss_to_loop (&loop2, lss);
2395
2396   /* Calculate the bounds of the scalarization.  */
2397   gfc_conv_ss_startstride (&loop2);
2398
2399   /* Setup the scalarizing loops.  */
2400   gfc_conv_loop_setup (&loop2, &expr->where);
2401
2402   gfc_copy_loopinfo_to_se (&lse, &loop2);
2403   gfc_copy_loopinfo_to_se (&rse, &loop2);
2404
2405   gfc_mark_ss_chain_used (lss, 1);
2406   gfc_mark_ss_chain_used (loop.temp_ss, 1);
2407
2408   /* Declare the variable to hold the temporary offset and start the
2409      scalarized loop body.  */
2410   offset = gfc_create_var (gfc_array_index_type, NULL);
2411   gfc_start_scalarized_body (&loop2, &body);
2412
2413   /* Build the offsets for the temporary from the loop variables.  The
2414      temporary array has lbounds of zero and strides of one in all
2415      dimensions, so this is very simple.  The offset is only computed
2416      outside the innermost loop, so the overall transfer could be
2417      optimized further.  */
2418   info = &rse.ss->data.info;
2419   dimen = info->dimen;
2420
2421   tmp_index = gfc_index_zero_node;
2422   for (n = dimen - 1; n > 0; n--)
2423     {
2424       tree tmp_str;
2425       tmp = rse.loop->loopvar[n];
2426       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
2427                              tmp, rse.loop->from[n]);
2428       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
2429                              tmp, tmp_index);
2430
2431       tmp_str = fold_build2_loc (input_location, MINUS_EXPR,
2432                                  gfc_array_index_type,
2433                                  rse.loop->to[n-1], rse.loop->from[n-1]);
2434       tmp_str = fold_build2_loc (input_location, PLUS_EXPR,
2435                                  gfc_array_index_type,
2436                                  tmp_str, gfc_index_one_node);
2437
2438       tmp_index = fold_build2_loc (input_location, MULT_EXPR,
2439                                    gfc_array_index_type, tmp, tmp_str);
2440     }
2441
2442   tmp_index = fold_build2_loc (input_location, MINUS_EXPR,
2443                                gfc_array_index_type,
2444                                tmp_index, rse.loop->from[0]);
2445   gfc_add_modify (&rse.loop->code[0], offset, tmp_index);
2446
2447   tmp_index = fold_build2_loc (input_location, PLUS_EXPR,
2448                                gfc_array_index_type,
2449                                rse.loop->loopvar[0], offset);
2450
2451   /* Now use the offset for the reference.  */
2452   tmp = build_fold_indirect_ref_loc (input_location,
2453                                  info->data);
2454   rse.expr = gfc_build_array_ref (tmp, tmp_index, NULL);
2455
2456   if (expr->ts.type == BT_CHARACTER)
2457     rse.string_length = expr->ts.u.cl->backend_decl;
2458
2459   gfc_conv_expr (&lse, expr);
2460
2461   gcc_assert (lse.ss == gfc_ss_terminator);
2462
2463   tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, false, true);
2464   gfc_add_expr_to_block (&body, tmp);
2465   
2466   /* Generate the copying loops.  */
2467   gfc_trans_scalarizing_loops (&loop2, &body);
2468
2469   /* Wrap the whole thing up by adding the second loop to the post-block
2470      and following it by the post-block of the first loop.  In this way,
2471      if the temporary needs freeing, it is done after use!  */
2472   if (intent != INTENT_IN)
2473     {
2474       gfc_add_block_to_block (&parmse->post, &loop2.pre);
2475       gfc_add_block_to_block (&parmse->post, &loop2.post);
2476     }
2477
2478   gfc_add_block_to_block (&parmse->post, &loop.post);
2479
2480   gfc_cleanup_loop (&loop);
2481   gfc_cleanup_loop (&loop2);
2482
2483   /* Pass the string length to the argument expression.  */
2484   if (expr->ts.type == BT_CHARACTER)
2485     parmse->string_length = expr->ts.u.cl->backend_decl;
2486
2487   /* Determine the offset for pointer formal arguments and set the
2488      lbounds to one.  */
2489   if (formal_ptr)
2490     {
2491       size = gfc_index_one_node;
2492       offset = gfc_index_zero_node;  
2493       for (n = 0; n < dimen; n++)
2494         {
2495           tmp = gfc_conv_descriptor_ubound_get (parmse->expr,
2496                                                 gfc_rank_cst[n]);
2497           tmp = fold_build2_loc (input_location, PLUS_EXPR,
2498                                  gfc_array_index_type, tmp,
2499                                  gfc_index_one_node);
2500           gfc_conv_descriptor_ubound_set (&parmse->pre,
2501                                           parmse->expr,
2502                                           gfc_rank_cst[n],
2503                                           tmp);
2504           gfc_conv_descriptor_lbound_set (&parmse->pre,
2505                                           parmse->expr,
2506                                           gfc_rank_cst[n],
2507                                           gfc_index_one_node);
2508           size = gfc_evaluate_now (size, &parmse->pre);
2509           offset = fold_build2_loc (input_location, MINUS_EXPR,
2510                                     gfc_array_index_type,
2511                                     offset, size);
2512           offset = gfc_evaluate_now (offset, &parmse->pre);
2513           tmp = fold_build2_loc (input_location, MINUS_EXPR,
2514                                  gfc_array_index_type,
2515                                  rse.loop->to[n], rse.loop->from[n]);
2516           tmp = fold_build2_loc (input_location, PLUS_EXPR,
2517                                  gfc_array_index_type,
2518                                  tmp, gfc_index_one_node);
2519           size = fold_build2_loc (input_location, MULT_EXPR,
2520                                   gfc_array_index_type, size, tmp);
2521         }
2522
2523       gfc_conv_descriptor_offset_set (&parmse->pre, parmse->expr,
2524                                       offset);
2525     }
2526
2527   /* We want either the address for the data or the address of the descriptor,
2528      depending on the mode of passing array arguments.  */
2529   if (g77)
2530     parmse->expr = gfc_conv_descriptor_data_get (parmse->expr);
2531   else
2532     parmse->expr = gfc_build_addr_expr (NULL_TREE, parmse->expr);
2533
2534   return;
2535 }
2536
2537
2538 /* Generate the code for argument list functions.  */
2539
2540 static void
2541 conv_arglist_function (gfc_se *se, gfc_expr *expr, const char *name)
2542 {
2543   /* Pass by value for g77 %VAL(arg), pass the address
2544      indirectly for %LOC, else by reference.  Thus %REF
2545      is a "do-nothing" and %LOC is the same as an F95
2546      pointer.  */
2547   if (strncmp (name, "%VAL", 4) == 0)
2548     gfc_conv_expr (se, expr);
2549   else if (strncmp (name, "%LOC", 4) == 0)
2550     {
2551       gfc_conv_expr_reference (se, expr);
2552       se->expr = gfc_build_addr_expr (NULL, se->expr);
2553     }
2554   else if (strncmp (name, "%REF", 4) == 0)
2555     gfc_conv_expr_reference (se, expr);
2556   else
2557     gfc_error ("Unknown argument list function at %L", &expr->where);
2558 }
2559
2560
2561 /* Takes a derived type expression and returns the address of a temporary
2562    class object of the 'declared' type.  */ 
2563 static void
2564 gfc_conv_derived_to_class (gfc_se *parmse, gfc_expr *e,
2565                            gfc_typespec class_ts)
2566 {
2567   gfc_component *cmp;
2568   gfc_symbol *vtab;
2569   gfc_symbol *declared = class_ts.u.derived;
2570   gfc_ss *ss;
2571   tree ctree;
2572   tree var;
2573   tree tmp;
2574
2575   /* The derived type needs to be converted to a temporary
2576      CLASS object.  */
2577   tmp = gfc_typenode_for_spec (&class_ts);
2578   var = gfc_create_var (tmp, "class");
2579
2580   /* Set the vptr.  */
2581   cmp = gfc_find_component (declared, "$vptr", true, true);
2582   ctree = fold_build3_loc (input_location, COMPONENT_REF,
2583                            TREE_TYPE (cmp->backend_decl),
2584                            var, cmp->backend_decl, NULL_TREE);
2585
2586   /* Remember the vtab corresponds to the derived type
2587      not to the class declared type.  */
2588   vtab = gfc_find_derived_vtab (e->ts.u.derived);
2589   gcc_assert (vtab);
2590   tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
2591   gfc_add_modify (&parmse->pre, ctree,
2592                   fold_convert (TREE_TYPE (ctree), tmp));
2593
2594   /* Now set the data field.  */
2595   cmp = gfc_find_component (declared, "$data", true, true);
2596   ctree = fold_build3_loc (input_location, COMPONENT_REF,
2597                            TREE_TYPE (cmp->backend_decl),
2598                            var, cmp->backend_decl, NULL_TREE);
2599   ss = gfc_walk_expr (e);
2600   if (ss == gfc_ss_terminator)
2601     {
2602       parmse->ss = NULL;
2603       gfc_conv_expr_reference (parmse, e);
2604       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
2605       gfc_add_modify (&parmse->pre, ctree, tmp);
2606     }
2607   else
2608     {
2609       parmse->ss = ss;
2610       gfc_conv_expr (parmse, e);
2611       gfc_add_modify (&parmse->pre, ctree, parmse->expr);
2612     }
2613
2614   /* Pass the address of the class object.  */
2615   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
2616 }
2617
2618
2619 /* The following routine generates code for the intrinsic
2620    procedures from the ISO_C_BINDING module:
2621     * C_LOC           (function)
2622     * C_FUNLOC        (function)
2623     * C_F_POINTER     (subroutine)
2624     * C_F_PROCPOINTER (subroutine)
2625     * C_ASSOCIATED    (function)
2626    One exception which is not handled here is C_F_POINTER with non-scalar
2627    arguments. Returns 1 if the call was replaced by inline code (else: 0).  */
2628
2629 static int
2630 conv_isocbinding_procedure (gfc_se * se, gfc_symbol * sym,
2631                             gfc_actual_arglist * arg)
2632 {
2633   gfc_symbol *fsym;
2634   gfc_ss *argss;
2635     
2636   if (sym->intmod_sym_id == ISOCBINDING_LOC)
2637     {
2638       if (arg->expr->rank == 0)
2639         gfc_conv_expr_reference (se, arg->expr);
2640       else
2641         {
2642           int f;
2643           /* This is really the actual arg because no formal arglist is
2644              created for C_LOC.  */
2645           fsym = arg->expr->symtree->n.sym;
2646
2647           /* We should want it to do g77 calling convention.  */
2648           f = (fsym != NULL)
2649             && !(fsym->attr.pointer || fsym->attr.allocatable)
2650             && fsym->as->type != AS_ASSUMED_SHAPE;
2651           f = f || !sym->attr.always_explicit;
2652       
2653           argss = gfc_walk_expr (arg->expr);
2654           gfc_conv_array_parameter (se, arg->expr, argss, f,
2655                                     NULL, NULL, NULL);
2656         }
2657
2658       /* TODO -- the following two lines shouldn't be necessary, but if
2659          they're removed, a bug is exposed later in the code path.
2660          This workaround was thus introduced, but will have to be
2661          removed; please see PR 35150 for details about the issue.  */
2662       se->expr = convert (pvoid_type_node, se->expr);
2663       se->expr = gfc_evaluate_now (se->expr, &se->pre);
2664
2665       return 1;
2666     }
2667   else if (sym->intmod_sym_id == ISOCBINDING_FUNLOC)
2668     {
2669       arg->expr->ts.type = sym->ts.u.derived->ts.type;
2670       arg->expr->ts.f90_type = sym->ts.u.derived->ts.f90_type;
2671       arg->expr->ts.kind = sym->ts.u.derived->ts.kind;
2672       gfc_conv_expr_reference (se, arg->expr);
2673   
2674       return 1;
2675     }
2676   else if ((sym->intmod_sym_id == ISOCBINDING_F_POINTER
2677             && arg->next->expr->rank == 0)
2678            || sym->intmod_sym_id == ISOCBINDING_F_PROCPOINTER)
2679     {
2680       /* Convert c_f_pointer if fptr is a scalar
2681          and convert c_f_procpointer.  */
2682       gfc_se cptrse;
2683       gfc_se fptrse;
2684
2685       gfc_init_se (&cptrse, NULL);
2686       gfc_conv_expr (&cptrse, arg->expr);
2687       gfc_add_block_to_block (&se->pre, &cptrse.pre);
2688       gfc_add_block_to_block (&se->post, &cptrse.post);
2689
2690       gfc_init_se (&fptrse, NULL);
2691       if (sym->intmod_sym_id == ISOCBINDING_F_POINTER
2692           || gfc_is_proc_ptr_comp (arg->next->expr, NULL))
2693         fptrse.want_pointer = 1;
2694
2695       gfc_conv_expr (&fptrse, arg->next->expr);
2696       gfc_add_block_to_block (&se->pre, &fptrse.pre);
2697       gfc_add_block_to_block (&se->post, &fptrse.post);
2698       
2699       if (arg->next->expr->symtree->n.sym->attr.proc_pointer
2700           && arg->next->expr->symtree->n.sym->attr.dummy)
2701         fptrse.expr = build_fold_indirect_ref_loc (input_location,
2702                                                    fptrse.expr);
2703       
2704       se->expr = fold_build2_loc (input_location, MODIFY_EXPR,
2705                                   TREE_TYPE (fptrse.expr),
2706                                   fptrse.expr,
2707                                   fold_convert (TREE_TYPE (fptrse.expr),
2708                                                 cptrse.expr));
2709
2710       return 1;
2711     }
2712   else if (sym->intmod_sym_id == ISOCBINDING_ASSOCIATED)
2713     {
2714       gfc_se arg1se;
2715       gfc_se arg2se;
2716
2717       /* Build the addr_expr for the first argument.  The argument is
2718          already an *address* so we don't need to set want_pointer in
2719          the gfc_se.  */
2720       gfc_init_se (&arg1se, NULL);
2721       gfc_conv_expr (&arg1se, arg->expr);
2722       gfc_add_block_to_block (&se->pre, &arg1se.pre);
2723       gfc_add_block_to_block (&se->post, &arg1se.post);
2724
2725       /* See if we were given two arguments.  */
2726       if (arg->next == NULL)
2727         /* Only given one arg so generate a null and do a
2728            not-equal comparison against the first arg.  */
2729         se->expr = fold_build2_loc (input_location, NE_EXPR, boolean_type_node,
2730                                     arg1se.expr,
2731                                     fold_convert (TREE_TYPE (arg1se.expr),
2732                                                   null_pointer_node));
2733       else
2734         {
2735           tree eq_expr;
2736           tree not_null_expr;
2737           
2738           /* Given two arguments so build the arg2se from second arg.  */
2739           gfc_init_se (&arg2se, NULL);
2740           gfc_conv_expr (&arg2se, arg->next->expr);
2741           gfc_add_block_to_block (&se->pre, &arg2se.pre);
2742           gfc_add_block_to_block (&se->post, &arg2se.post);
2743
2744           /* Generate test to compare that the two args are equal.  */
2745           eq_expr = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
2746                                      arg1se.expr, arg2se.expr);
2747           /* Generate test to ensure that the first arg is not null.  */
2748           not_null_expr = fold_build2_loc (input_location, NE_EXPR,
2749                                            boolean_type_node,
2750                                            arg1se.expr, null_pointer_node);
2751
2752           /* Finally, the generated test must check that both arg1 is not
2753              NULL and that it is equal to the second arg.  */
2754           se->expr = fold_build2_loc (input_location, TRUTH_AND_EXPR,
2755                                       boolean_type_node,
2756                                       not_null_expr, eq_expr);
2757         }
2758
2759       return 1;
2760     }
2761     
2762   /* Nothing was done.  */
2763   return 0;
2764 }
2765
2766 /* Generate code for a procedure call.  Note can return se->post != NULL.
2767    If se->direct_byref is set then se->expr contains the return parameter.
2768    Return nonzero, if the call has alternate specifiers.
2769    'expr' is only needed for procedure pointer components.  */
2770
2771 int
2772 gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
2773                          gfc_actual_arglist * arg, gfc_expr * expr,
2774                          VEC(tree,gc) *append_args)
2775 {
2776   gfc_interface_mapping mapping;
2777   VEC(tree,gc) *arglist;
2778   VEC(tree,gc) *retargs;
2779   tree tmp;
2780   tree fntype;
2781   gfc_se parmse;
2782   gfc_ss *argss;
2783   gfc_ss_info *info;
2784   int byref;
2785   int parm_kind;
2786   tree type;
2787   tree var;
2788   tree len;
2789   VEC(tree,gc) *stringargs;
2790   tree result = NULL;
2791   gfc_formal_arglist *formal;
2792   int has_alternate_specifier = 0;
2793   bool need_interface_mapping;
2794   bool callee_alloc;
2795   gfc_typespec ts;
2796   gfc_charlen cl;
2797   gfc_expr *e;
2798   gfc_symbol *fsym;
2799   stmtblock_t post;
2800   enum {MISSING = 0, ELEMENTAL, SCALAR, SCALAR_POINTER, ARRAY};
2801   gfc_component *comp = NULL;
2802   int arglen;
2803
2804   arglist = NULL;
2805   retargs = NULL;
2806   stringargs = NULL;
2807   var = NULL_TREE;
2808   len = NULL_TREE;
2809   gfc_clear_ts (&ts);
2810
2811   if (sym->from_intmod == INTMOD_ISO_C_BINDING
2812       && conv_isocbinding_procedure (se, sym, arg))
2813     return 0;
2814
2815   gfc_is_proc_ptr_comp (expr, &comp);
2816
2817   if (se->ss != NULL)
2818     {
2819       if (!sym->attr.elemental)
2820         {
2821           gcc_assert (se->ss->type == GFC_SS_FUNCTION);
2822           if (se->ss->useflags)
2823             {
2824               gcc_assert ((!comp && gfc_return_by_reference (sym)
2825                            && sym->result->attr.dimension)
2826                           || (comp && comp->attr.dimension));
2827               gcc_assert (se->loop != NULL);
2828
2829               /* Access the previously obtained result.  */
2830               gfc_conv_tmp_array_ref (se);
2831               gfc_advance_se_ss_chain (se);
2832               return 0;
2833             }
2834         }
2835       info = &se->ss->data.info;
2836     }
2837   else
2838     info = NULL;
2839
2840   gfc_init_block (&post);
2841   gfc_init_interface_mapping (&mapping);
2842   if (!comp)
2843     {
2844       formal = sym->formal;
2845       need_interface_mapping = sym->attr.dimension ||
2846                                (sym->ts.type == BT_CHARACTER
2847                                 && sym->ts.u.cl->length
2848                                 && sym->ts.u.cl->length->expr_type
2849                                    != EXPR_CONSTANT);
2850     }
2851   else
2852     {
2853       formal = comp->formal;
2854       need_interface_mapping = comp->attr.dimension ||
2855                                (comp->ts.type == BT_CHARACTER
2856                                 && comp->ts.u.cl->length
2857                                 && comp->ts.u.cl->length->expr_type
2858                                    != EXPR_CONSTANT);
2859     }
2860
2861   /* Evaluate the arguments.  */
2862   for (; arg != NULL; arg = arg->next, formal = formal ? formal->next : NULL)
2863     {
2864       e = arg->expr;
2865       fsym = formal ? formal->sym : NULL;
2866       parm_kind = MISSING;
2867
2868       if (e == NULL)
2869         {
2870           if (se->ignore_optional)
2871             {
2872               /* Some intrinsics have already been resolved to the correct
2873                  parameters.  */
2874               continue;
2875             }
2876           else if (arg->label)
2877             {
2878               has_alternate_specifier = 1;
2879               continue;
2880             }
2881           else
2882             {
2883               /* Pass a NULL pointer for an absent arg.  */
2884               gfc_init_se (&parmse, NULL);
2885               parmse.expr = null_pointer_node;
2886               if (arg->missing_arg_type == BT_CHARACTER)
2887                 parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
2888             }
2889         }
2890       else if (arg->expr->expr_type == EXPR_NULL && fsym && !fsym->attr.pointer)
2891         {
2892           /* Pass a NULL pointer to denote an absent arg.  */
2893           gcc_assert (fsym->attr.optional && !fsym->attr.allocatable);
2894           gfc_init_se (&parmse, NULL);
2895           parmse.expr = null_pointer_node;
2896           if (arg->missing_arg_type == BT_CHARACTER)
2897             parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
2898         }
2899       else if (fsym && fsym->ts.type == BT_CLASS
2900                  && e->ts.type == BT_DERIVED)
2901         {
2902           /* The derived type needs to be converted to a temporary
2903              CLASS object.  */
2904           gfc_init_se (&parmse, se);
2905           gfc_conv_derived_to_class (&parmse, e, fsym->ts);
2906         }
2907       else if (se->ss && se->ss->useflags)
2908         {
2909           /* An elemental function inside a scalarized loop.  */
2910           gfc_init_se (&parmse, se);
2911           gfc_conv_expr_reference (&parmse, e);
2912           parm_kind = ELEMENTAL;
2913         }
2914       else
2915         {
2916           /* A scalar or transformational function.  */
2917           gfc_init_se (&parmse, NULL);
2918           argss = gfc_walk_expr (e);
2919
2920           if (argss == gfc_ss_terminator)
2921             {
2922               if (e->expr_type == EXPR_VARIABLE
2923                     && e->symtree->n.sym->attr.cray_pointee
2924                     && fsym && fsym->attr.flavor == FL_PROCEDURE)
2925                 {
2926                     /* The Cray pointer needs to be converted to a pointer to
2927                        a type given by the expression.  */
2928                     gfc_conv_expr (&parmse, e);
2929                     type = build_pointer_type (TREE_TYPE (parmse.expr));
2930                     tmp = gfc_get_symbol_decl (e->symtree->n.sym->cp_pointer);
2931                     parmse.expr = convert (type, tmp);
2932                 }
2933               else if (fsym && fsym->attr.value)
2934                 {
2935                   if (fsym->ts.type == BT_CHARACTER
2936                       && fsym->ts.is_c_interop
2937                       && fsym->ns->proc_name != NULL
2938                       && fsym->ns->proc_name->attr.is_bind_c)
2939                     {
2940                       parmse.expr = NULL;
2941                       gfc_conv_scalar_char_value (fsym, &parmse, &e);
2942                       if (parmse.expr == NULL)
2943                         gfc_conv_expr (&parmse, e);
2944                     }
2945                   else
2946                     gfc_conv_expr (&parmse, e);
2947                 }
2948               else if (arg->name && arg->name[0] == '%')
2949                 /* Argument list functions %VAL, %LOC and %REF are signalled
2950                    through arg->name.  */
2951                 conv_arglist_function (&parmse, arg->expr, arg->name);
2952               else if ((e->expr_type == EXPR_FUNCTION)
2953                         && ((e->value.function.esym
2954                              && e->value.function.esym->result->attr.pointer)
2955                             || (!e->value.function.esym
2956                                 && e->symtree->n.sym->attr.pointer))
2957                         && fsym && fsym->attr.target)
2958                 {
2959                   gfc_conv_expr (&parmse, e);
2960                   parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
2961                 }
2962               else if (e->expr_type == EXPR_FUNCTION
2963                        && e->symtree->n.sym->result
2964                        && e->symtree->n.sym->result != e->symtree->n.sym
2965                        && e->symtree->n.sym->result->attr.proc_pointer)
2966                 {
2967                   /* Functions returning procedure pointers.  */
2968                   gfc_conv_expr (&parmse, e);
2969                   if (fsym && fsym->attr.proc_pointer)
2970                     parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
2971                 }
2972               else
2973                 {
2974                   gfc_conv_expr_reference (&parmse, e);
2975
2976                   /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is 
2977                      allocated on entry, it must be deallocated.  */
2978                   if (fsym && fsym->attr.allocatable
2979                       && fsym->attr.intent == INTENT_OUT)
2980                     {
2981                       stmtblock_t block;
2982
2983                       gfc_init_block  (&block);
2984                       tmp = gfc_deallocate_with_status (parmse.expr, NULL_TREE,
2985                                                         true, NULL);
2986                       gfc_add_expr_to_block (&block, tmp);
2987                       tmp = fold_build2_loc (input_location, MODIFY_EXPR,
2988                                              void_type_node, parmse.expr,
2989                                              null_pointer_node);
2990                       gfc_add_expr_to_block (&block, tmp);
2991
2992                       if (fsym->attr.optional
2993                           && e->expr_type == EXPR_VARIABLE
2994                           && e->symtree->n.sym->attr.optional)
2995                         {
2996                           tmp = fold_build3_loc (input_location, COND_EXPR,
2997                                      void_type_node,
2998                                      gfc_conv_expr_present (e->symtree->n.sym),
2999                                             gfc_finish_block (&block),
3000                                             build_empty_stmt (input_location));
3001                         }
3002                       else
3003                         tmp = gfc_finish_block (&block);
3004
3005                       gfc_add_expr_to_block (&se->pre, tmp);
3006                     }
3007
3008                   if (fsym && e->expr_type != EXPR_NULL
3009                       && ((fsym->attr.pointer
3010                            && fsym->attr.flavor != FL_PROCEDURE)
3011                           || (fsym->attr.proc_pointer
3012                               && !(e->expr_type == EXPR_VARIABLE
3013                               && e->symtree->n.sym->attr.dummy))
3014                           || (e->expr_type == EXPR_VARIABLE
3015                               && gfc_is_proc_ptr_comp (e, NULL))
3016                           || fsym->attr.allocatable))
3017                     {
3018                       /* Scalar pointer dummy args require an extra level of
3019                          indirection. The null pointer already contains
3020                          this level of indirection.  */
3021                       parm_kind = SCALAR_POINTER;
3022                       parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
3023                     }
3024                 }
3025             }
3026           else
3027             {
3028               /* If the procedure requires an explicit interface, the actual
3029                  argument is passed according to the corresponding formal
3030                  argument.  If the corresponding formal argument is a POINTER,
3031                  ALLOCATABLE or assumed shape, we do not use g77's calling
3032                  convention, and pass the address of the array descriptor
3033                  instead. Otherwise we use g77's calling convention.  */
3034               bool f;
3035               f = (fsym != NULL)
3036                   && !(fsym->attr.pointer || fsym->attr.allocatable)
3037                   && fsym->as && fsym->as->type != AS_ASSUMED_SHAPE;
3038               if (comp)
3039                 f = f || !comp->attr.always_explicit;
3040               else
3041                 f = f || !sym->attr.always_explicit;
3042
3043               if (e->expr_type == EXPR_VARIABLE
3044                     && is_subref_array (e))
3045                 /* The actual argument is a component reference to an
3046                    array of derived types.  In this case, the argument
3047                    is converted to a temporary, which is passed and then
3048                    written back after the procedure call.  */
3049                 gfc_conv_subref_array_arg (&parmse, e, f,
3050                                 fsym ? fsym->attr.intent : INTENT_INOUT,
3051                                 fsym && fsym->attr.pointer);
3052               else
3053                 gfc_conv_array_parameter (&parmse, e, argss, f, fsym,
3054                                           sym->name, NULL);
3055
3056               /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is 
3057                  allocated on entry, it must be deallocated.  */
3058               if (fsym && fsym->attr.allocatable
3059                   && fsym->attr.intent == INTENT_OUT)
3060                 {
3061                   tmp = build_fold_indirect_ref_loc (input_location,
3062                                                      parmse.expr);
3063                   tmp = gfc_trans_dealloc_allocated (tmp);
3064                   if (fsym->attr.optional
3065                       && e->expr_type == EXPR_VARIABLE
3066                       && e->symtree->n.sym->attr.optional)
3067                     tmp = fold_build3_loc (input_location, COND_EXPR,
3068                                      void_type_node,
3069                                      gfc_conv_expr_present (e->symtree->n.sym),
3070                                        tmp, build_empty_stmt (input_location));
3071                   gfc_add_expr_to_block (&se->pre, tmp);
3072                 }
3073             } 
3074         }
3075
3076       /* The case with fsym->attr.optional is that of a user subroutine
3077          with an interface indicating an optional argument.  When we call
3078          an intrinsic subroutine, however, fsym is NULL, but we might still
3079          have an optional argument, so we proceed to the substitution
3080          just in case.  */
3081       if (e && (fsym == NULL || fsym->attr.optional))
3082         {
3083           /* If an optional argument is itself an optional dummy argument,
3084              check its presence and substitute a null if absent.  This is
3085              only needed when passing an array to an elemental procedure
3086              as then array elements are accessed - or no NULL pointer is
3087              allowed and a "1" or "0" should be passed if not present.
3088              When passing a non-array-descriptor full array to a
3089              non-array-descriptor dummy, no check is needed. For
3090              array-descriptor actual to array-descriptor dummy, see
3091              PR 41911 for why a check has to be inserted.
3092              fsym == NULL is checked as intrinsics required the descriptor
3093              but do not always set fsym.  */
3094           if (e->expr_type == EXPR_VARIABLE
3095               && e->symtree->n.sym->attr.optional
3096               && ((e->rank > 0 && sym->attr.elemental)
3097                   || e->representation.length || e->ts.type == BT_CHARACTER
3098                   || (e->rank > 0
3099                       && (fsym == NULL || fsym->as->type == AS_ASSUMED_SHAPE
3100                           || fsym->as->type == AS_DEFERRED))))
3101             gfc_conv_missing_dummy (&parmse, e, fsym ? fsym->ts : e->ts,
3102                                     e->representation.length);
3103         }
3104
3105       if (fsym && e)
3106         {
3107           /* Obtain the character length of an assumed character length
3108              length procedure from the typespec.  */
3109           if (fsym->ts.type == BT_CHARACTER
3110               && parmse.string_length == NULL_TREE
3111               && e->ts.type == BT_PROCEDURE
3112               && e->symtree->n.sym->ts.type == BT_CHARACTER
3113               && e->symtree->n.sym->ts.u.cl->length != NULL
3114               && e->symtree->n.sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
3115             {
3116               gfc_conv_const_charlen (e->symtree->n.sym->ts.u.cl);
3117               parmse.string_length = e->symtree->n.sym->ts.u.cl->backend_decl;
3118             }
3119         }
3120
3121       if (fsym && need_interface_mapping && e)
3122         gfc_add_interface_mapping (&mapping, fsym, &parmse, e);
3123
3124       gfc_add_block_to_block (&se->pre, &parmse.pre);
3125       gfc_add_block_to_block (&post, &parmse.post);
3126
3127       /* Allocated allocatable components of derived types must be
3128          deallocated for non-variable scalars.  Non-variable arrays are
3129          dealt with in trans-array.c(gfc_conv_array_parameter).  */
3130       if (e && e->ts.type == BT_DERIVED
3131             && e->ts.u.derived->attr.alloc_comp
3132             && !(e->symtree && e->symtree->n.sym->attr.pointer)
3133             && (e->expr_type != EXPR_VARIABLE && !e->rank))
3134         {
3135           int parm_rank;
3136           tmp = build_fold_indirect_ref_loc (input_location,
3137                                          parmse.expr);
3138           parm_rank = e->rank;
3139           switch (parm_kind)
3140             {
3141             case (ELEMENTAL):
3142             case (SCALAR):
3143               parm_rank = 0;
3144               break;
3145
3146             case (SCALAR_POINTER):
3147               tmp = build_fold_indirect_ref_loc (input_location,
3148                                              tmp);
3149               break;
3150             }
3151
3152           if (e->expr_type == EXPR_OP
3153                 && e->value.op.op == INTRINSIC_PARENTHESES
3154                 && e->value.op.op1->expr_type == EXPR_VARIABLE)
3155             {
3156               tree local_tmp;
3157               local_tmp = gfc_evaluate_now (tmp, &se->pre);
3158               local_tmp = gfc_copy_alloc_comp (e->ts.u.derived, local_tmp, tmp, parm_rank);
3159               gfc_add_expr_to_block (&se->post, local_tmp);
3160             }
3161
3162           tmp = gfc_deallocate_alloc_comp (e->ts.u.derived, tmp, parm_rank);
3163
3164           gfc_add_expr_to_block (&se->post, tmp);
3165         }
3166
3167       /* Add argument checking of passing an unallocated/NULL actual to
3168          a nonallocatable/nonpointer dummy.  */
3169
3170       if (gfc_option.rtcheck & GFC_RTCHECK_POINTER && e != NULL)
3171         {
3172           symbol_attribute attr;
3173           char *msg;
3174           tree cond;
3175
3176           if (e->expr_type == EXPR_VARIABLE || e->expr_type == EXPR_FUNCTION)
3177             attr = gfc_expr_attr (e);
3178           else
3179             goto end_pointer_check;
3180
3181           if (attr.optional)
3182             {
3183               /* If the actual argument is an optional pointer/allocatable and
3184                  the formal argument takes an nonpointer optional value,
3185                  it is invalid to pass a non-present argument on, even
3186                  though there is no technical reason for this in gfortran.
3187                  See Fortran 2003, Section 12.4.1.6 item (7)+(8).  */
3188               tree present, null_ptr, type;
3189
3190               if (attr.allocatable
3191                   && (fsym == NULL || !fsym->attr.allocatable))
3192                 asprintf (&msg, "Allocatable actual argument '%s' is not "
3193                           "allocated or not present", e->symtree->n.sym->name);
3194               else if (attr.pointer
3195                        && (fsym == NULL || !fsym->attr.pointer))
3196                 asprintf (&msg, "Pointer actual argument '%s' is not "
3197                           "associated or not present",
3198                           e->symtree->n.sym->name);
3199               else if (attr.proc_pointer
3200                        && (fsym == NULL || !fsym->attr.proc_pointer))
3201                 asprintf (&msg, "Proc-pointer actual argument '%s' is not "
3202                           "associated or not present",
3203                           e->symtree->n.sym->name);
3204               else
3205                 goto end_pointer_check;
3206
3207               present = gfc_conv_expr_present (e->symtree->n.sym);
3208               type = TREE_TYPE (present);
3209               present = fold_build2_loc (input_location, EQ_EXPR,
3210                                          boolean_type_node, present,
3211                                          fold_convert (type,
3212                                                        null_pointer_node));
3213               type = TREE_TYPE (parmse.expr);
3214               null_ptr = fold_build2_loc (input_location, EQ_EXPR,
3215                                           boolean_type_node, parmse.expr,
3216                                           fold_convert (type,
3217                                                         null_pointer_node));
3218               cond = fold_build2_loc (input_location, TRUTH_ORIF_EXPR,
3219                                       boolean_type_node, present, null_ptr);
3220             }
3221           else
3222             {
3223               if (attr.allocatable
3224                   && (fsym == NULL || !fsym->attr.allocatable))
3225                 asprintf (&msg, "Allocatable actual argument '%s' is not "
3226                       "allocated", e->symtree->n.sym->name);
3227               else if (attr.pointer
3228                        && (fsym == NULL || !fsym->attr.pointer))
3229                 asprintf (&msg, "Pointer actual argument '%s' is not "
3230                       "associated", e->symtree->n.sym->name);
3231               else if (attr.proc_pointer
3232                        && (fsym == NULL || !fsym->attr.proc_pointer))
3233                 asprintf (&msg, "Proc-pointer actual argument '%s' is not "
3234                       "associated", e->symtree->n.sym->name);
3235               else
3236                 goto end_pointer_check;
3237
3238
3239               cond = fold_build2_loc (input_location, EQ_EXPR,
3240                                       boolean_type_node, parmse.expr,
3241                                       fold_convert (TREE_TYPE (parmse.expr),
3242                                                     null_pointer_node));
3243             }
3244  
3245           gfc_trans_runtime_check (true, false, cond, &se->pre, &e->where,
3246                                    msg);
3247           gfc_free (msg);
3248         }
3249       end_pointer_check:
3250
3251
3252       /* Character strings are passed as two parameters, a length and a
3253          pointer - except for Bind(c) which only passes the pointer.  */
3254       if (parmse.string_length != NULL_TREE && !sym->attr.is_bind_c)
3255         VEC_safe_push (tree, gc, stringargs, parmse.string_length);
3256
3257       VEC_safe_push (tree, gc, arglist, parmse.expr);
3258     }
3259   gfc_finish_interface_mapping (&mapping, &se->pre, &se->post);
3260
3261   if (comp)
3262     ts = comp->ts;
3263   else
3264    ts = sym->ts;
3265
3266   if (ts.type == BT_CHARACTER && sym->attr.is_bind_c)
3267     se->string_length = build_int_cst (gfc_charlen_type_node, 1);
3268   else if (ts.type == BT_CHARACTER)
3269     {
3270       if (ts.u.cl->length == NULL)
3271         {
3272           /* Assumed character length results are not allowed by 5.1.1.5 of the
3273              standard and are trapped in resolve.c; except in the case of SPREAD
3274              (and other intrinsics?) and dummy functions.  In the case of SPREAD,
3275              we take the character length of the first argument for the result.
3276              For dummies, we have to look through the formal argument list for
3277              this function and use the character length found there.*/
3278           if (!sym->attr.dummy)
3279             cl.backend_decl = VEC_index (tree, stringargs, 0);
3280           else
3281             {
3282               formal = sym->ns->proc_name->formal;
3283               for (; formal; formal = formal->next)
3284                 if (strcmp (formal->sym->name, sym->name) == 0)
3285                   cl.backend_decl = formal->sym->ts.u.cl->backend_decl;
3286             }
3287         }
3288       else
3289         {
3290           tree tmp;
3291
3292           /* Calculate the length of the returned string.  */
3293           gfc_init_se (&parmse, NULL);
3294           if (need_interface_mapping)
3295             gfc_apply_interface_mapping (&mapping, &parmse, ts.u.cl->length);
3296           else
3297             gfc_conv_expr (&parmse, ts.u.cl->length);
3298           gfc_add_block_to_block (&se->pre, &parmse.pre);
3299           gfc_add_block_to_block (&se->post, &parmse.post);
3300           
3301           tmp = fold_convert (gfc_charlen_type_node, parmse.expr);
3302           tmp = fold_build2_loc (input_location, MAX_EXPR,
3303                                  gfc_charlen_type_node, tmp,
3304                                  build_int_cst (gfc_charlen_type_node, 0));
3305           cl.backend_decl = tmp;
3306         }
3307
3308       /* Set up a charlen structure for it.  */
3309       cl.next = NULL;
3310       cl.length = NULL;
3311       ts.u.cl = &cl;
3312
3313       len = cl.backend_decl;
3314     }
3315
3316   byref = (comp && (comp->attr.dimension || comp->ts.type == BT_CHARACTER))
3317           || (!comp && gfc_return_by_reference (sym));
3318   if (byref)
3319     {
3320       if (se->direct_byref)
3321         {
3322           /* Sometimes, too much indirection can be applied; e.g. for
3323              function_result = array_valued_recursive_function.  */
3324           if (TREE_TYPE (TREE_TYPE (se->expr))
3325                 && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))
3326                 && GFC_DESCRIPTOR_TYPE_P
3327                         (TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))))
3328             se->expr = build_fold_indirect_ref_loc (input_location,
3329                                                 se->expr);
3330
3331           result = build_fold_indirect_ref_loc (input_location,
3332                                                 se->expr);
3333           VEC_safe_push (tree, gc, retargs, se->expr);
3334         }
3335       else if (comp && comp->attr.dimension)
3336         {
3337           gcc_assert (se->loop && info);
3338
3339           /* Set the type of the array.  */
3340           tmp = gfc_typenode_for_spec (&comp->ts);
3341           info->dimen = se->loop->dimen;
3342
3343           /* Evaluate the bounds of the result, if known.  */
3344           gfc_set_loop_bounds_from_array_spec (&mapping, se, comp->as);
3345
3346           /* Create a temporary to store the result.  In case the function
3347              returns a pointer, the temporary will be a shallow copy and
3348              mustn't be deallocated.  */
3349           callee_alloc = comp->attr.allocatable || comp->attr.pointer;
3350           gfc_trans_create_temp_array (&se->pre, &se->post, se->loop, info, tmp,
3351                                        NULL_TREE, false, !comp->attr.pointer,
3352                                        callee_alloc, &se->ss->expr->where);
3353
3354           /* Pass the temporary as the first argument.  */
3355           result = info->descriptor;
3356           tmp = gfc_build_addr_expr (NULL_TREE, result);
3357           VEC_safe_push (tree, gc, retargs, tmp);
3358         }
3359       else if (!comp && sym->result->attr.dimension)
3360         {
3361           gcc_assert (se->loop && info);
3362
3363           /* Set the type of the array.  */
3364           tmp = gfc_typenode_for_spec (&ts);
3365           info->dimen = se->loop->dimen;
3366
3367           /* Evaluate the bounds of the result, if known.  */
3368           gfc_set_loop_bounds_from_array_spec (&mapping, se, sym->result->as);
3369
3370           /* Create a temporary to store the result.  In case the function
3371              returns a pointer, the temporary will be a shallow copy and
3372              mustn't be deallocated.  */
3373           callee_alloc = sym->attr.allocatable || sym->attr.pointer;
3374           gfc_trans_create_temp_array (&se->pre, &se->post, se->loop, info, tmp,
3375                                        NULL_TREE, false, !sym->attr.pointer,
3376                                        callee_alloc, &se->ss->expr->where);
3377
3378           /* Pass the temporary as the first argument.  */
3379           result = info->descriptor;
3380           tmp = gfc_build_addr_expr (NULL_TREE, result);
3381           VEC_safe_push (tree, gc, retargs, tmp);
3382         }
3383       else if (ts.type == BT_CHARACTER)
3384         {
3385           /* Pass the string length.  */
3386           type = gfc_get_character_type (ts.kind, ts.u.cl);
3387           type = build_pointer_type (type);
3388
3389           /* Return an address to a char[0:len-1]* temporary for
3390              character pointers.  */
3391           if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
3392                || (comp && (comp->attr.pointer || comp->attr.allocatable)))
3393             {
3394               var = gfc_create_var (type, "pstr");
3395
3396               if ((!comp && sym->attr.allocatable)
3397                   || (comp && comp->attr.allocatable))
3398                 gfc_add_modify (&se->pre, var,
3399                                 fold_convert (TREE_TYPE (var),
3400                                               null_pointer_node));
3401
3402               /* Provide an address expression for the function arguments.  */
3403               var = gfc_build_addr_expr (NULL_TREE, var);
3404             }
3405           else
3406             var = gfc_conv_string_tmp (se, type, len);
3407
3408           VEC_safe_push (tree, gc, retargs, var);
3409         }
3410       else
3411         {
3412           gcc_assert (gfc_option.flag_f2c && ts.type == BT_COMPLEX);
3413
3414           type = gfc_get_complex_type (ts.kind);
3415           var = gfc_build_addr_expr (NULL_TREE, gfc_create_var (type, "cmplx"));
3416           VEC_safe_push (tree, gc, retargs, var);
3417         }
3418
3419       /* Add the string length to the argument list.  */
3420       if (ts.type == BT_CHARACTER)
3421         VEC_safe_push (tree, gc, retargs, len);
3422     }
3423   gfc_free_interface_mapping (&mapping);
3424
3425   /* We need to glom RETARGS + ARGLIST + STRINGARGS + APPEND_ARGS.  */
3426   arglen = (VEC_length (tree, arglist)
3427             + VEC_length (tree, stringargs) + VEC_length (tree, append_args));
3428   VEC_reserve_exact (tree, gc, retargs, arglen);
3429
3430   /* Add the return arguments.  */
3431   VEC_splice (tree, retargs, arglist);
3432
3433   /* Add the hidden string length parameters to the arguments.  */
3434   VEC_splice (tree, retargs, stringargs);
3435
3436   /* We may want to append extra arguments here.  This is used e.g. for
3437      calls to libgfortran_matmul_??, which need extra information.  */
3438   if (!VEC_empty (tree, append_args))
3439     VEC_splice (tree, retargs, append_args);
3440   arglist = retargs;
3441
3442   /* Generate the actual call.  */
3443   conv_function_val (se, sym, expr);
3444
3445   /* If there are alternate return labels, function type should be
3446      integer.  Can't modify the type in place though, since it can be shared
3447      with other functions.  For dummy arguments, the typing is done to
3448      to this result, even if it has to be repeated for each call.  */
3449   if (has_alternate_specifier
3450       && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) != integer_type_node)
3451     {
3452       if (!sym->attr.dummy)
3453         {
3454           TREE_TYPE (sym->backend_decl)
3455                 = build_function_type (integer_type_node,
3456                       TYPE_ARG_TYPES (TREE_TYPE (sym->backend_decl)));
3457           se->expr = gfc_build_addr_expr (NULL_TREE, sym->backend_decl);
3458         }
3459       else
3460         TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) = integer_type_node;
3461     }
3462
3463   fntype = TREE_TYPE (TREE_TYPE (se->expr));
3464   se->expr = build_call_vec (TREE_TYPE (fntype), se->expr, arglist);
3465
3466   /* If we have a pointer function, but we don't want a pointer, e.g.
3467      something like
3468         x = f()
3469      where f is pointer valued, we have to dereference the result.  */
3470   if (!se->want_pointer && !byref
3471       && (sym->attr.pointer || sym->attr.allocatable)
3472       && !gfc_is_proc_ptr_comp (expr, NULL))
3473     se->expr = build_fold_indirect_ref_loc (input_location,
3474                                         se->expr);
3475
3476   /* f2c calling conventions require a scalar default real function to
3477      return a double precision result.  Convert this back to default
3478      real.  We only care about the cases that can happen in Fortran 77.
3479   */
3480   if (gfc_option.flag_f2c && sym->ts.type == BT_REAL
3481       && sym->ts.kind == gfc_default_real_kind
3482       && !sym->attr.always_explicit)
3483     se->expr = fold_convert (gfc_get_real_type (sym->ts.kind), se->expr);
3484
3485   /* A pure function may still have side-effects - it may modify its
3486      parameters.  */
3487   TREE_SIDE_EFFECTS (se->expr) = 1;
3488 #if 0
3489   if (!sym->attr.pure)
3490     TREE_SIDE_EFFECTS (se->expr) = 1;
3491 #endif
3492
3493   if (byref)
3494     {
3495       /* Add the function call to the pre chain.  There is no expression.  */
3496       gfc_add_expr_to_block (&se->pre, se->expr);
3497       se->expr = NULL_TREE;
3498
3499       if (!se->direct_byref)
3500         {
3501           if (sym->attr.dimension || (comp && comp->attr.dimension))
3502             {
3503               if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
3504                 {
3505                   /* Check the data pointer hasn't been modified.  This would
3506                      happen in a function returning a pointer.  */
3507                   tmp = gfc_conv_descriptor_data_get (info->descriptor);
3508                   tmp = fold_build2_loc (input_location, NE_EXPR,
3509                                          boolean_type_node,
3510                                          tmp, info->data);
3511                   gfc_trans_runtime_check (true, false, tmp, &se->pre, NULL,
3512                                            gfc_msg_fault);
3513                 }
3514               se->expr = info->descriptor;
3515               /* Bundle in the string length.  */
3516               se->string_length = len;
3517             }
3518           else if (ts.type == BT_CHARACTER)
3519             {
3520               /* Dereference for character pointer results.  */
3521               if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
3522                   || (comp && (comp->attr.pointer || comp->attr.allocatable)))
3523                 se->expr = build_fold_indirect_ref_loc (input_location, var);
3524               else
3525                 se->expr = var;
3526
3527               se->string_length = len;
3528             }
3529           else
3530             {
3531               gcc_assert (ts.type == BT_COMPLEX && gfc_option.flag_f2c);
3532               se->expr = build_fold_indirect_ref_loc (input_location, var);
3533             }
3534         }
3535     }
3536
3537   /* Follow the function call with the argument post block.  */
3538   if (byref)
3539     {
3540       gfc_add_block_to_block (&se->pre, &post);
3541
3542       /* Transformational functions of derived types with allocatable
3543          components must have the result allocatable components copied.  */
3544       arg = expr->value.function.actual;
3545       if (result && arg && expr->rank
3546             && expr->value.function.isym
3547             && expr->value.function.isym->transformational
3548             && arg->expr->ts.type == BT_DERIVED
3549             && arg->expr->ts.u.derived->attr.alloc_comp)
3550         {
3551           tree tmp2;
3552           /* Copy the allocatable components.  We have to use a
3553              temporary here to prevent source allocatable components
3554              from being corrupted.  */
3555           tmp2 = gfc_evaluate_now (result, &se->pre);
3556           tmp = gfc_copy_alloc_comp (arg->expr->ts.u.derived,
3557                                      result, tmp2, expr->rank);
3558           gfc_add_expr_to_block (&se->pre, tmp);
3559           tmp = gfc_copy_allocatable_data (result, tmp2, TREE_TYPE(tmp2),
3560                                            expr->rank);
3561           gfc_add_expr_to_block (&se->pre, tmp);
3562
3563           /* Finally free the temporary's data field.  */
3564           tmp = gfc_conv_descriptor_data_get (tmp2);
3565           tmp = gfc_deallocate_with_status (tmp, NULL_TREE, true, NULL);
3566           gfc_add_expr_to_block (&se->pre, tmp);
3567         }
3568     }
3569   else
3570     gfc_add_block_to_block (&se->post, &post);
3571
3572   return has_alternate_specifier;
3573 }
3574
3575
3576 /* Fill a character string with spaces.  */
3577
3578 static tree
3579 fill_with_spaces (tree start, tree type, tree size)
3580 {
3581   stmtblock_t block, loop;
3582   tree i, el, exit_label, cond, tmp;
3583
3584   /* For a simple char type, we can call memset().  */
3585   if (compare_tree_int (TYPE_SIZE_UNIT (type), 1) == 0)
3586     return build_call_expr_loc (input_location,
3587                             built_in_decls[BUILT_IN_MEMSET], 3, start,
3588                             build_int_cst (gfc_get_int_type (gfc_c_int_kind),
3589                                            lang_hooks.to_target_charset (' ')),
3590                             size);
3591
3592   /* Otherwise, we use a loop:
3593         for (el = start, i = size; i > 0; el--, i+= TYPE_SIZE_UNIT (type))
3594           *el = (type) ' ';
3595    */
3596
3597   /* Initialize variables.  */
3598   gfc_init_block (&block);
3599   i = gfc_create_var (sizetype, "i");
3600   gfc_add_modify (&block, i, fold_convert (sizetype, size));
3601   el = gfc_create_var (build_pointer_type (type), "el");
3602   gfc_add_modify (&block, el, fold_convert (TREE_TYPE (el), start));
3603   exit_label = gfc_build_label_decl (NULL_TREE);
3604   TREE_USED (exit_label) = 1;
3605
3606
3607   /* Loop body.  */
3608   gfc_init_block (&loop);
3609
3610   /* Exit condition.  */
3611   cond = fold_build2_loc (input_location, LE_EXPR, boolean_type_node, i,
3612                           fold_convert (sizetype, integer_zero_node));
3613   tmp = build1_v (GOTO_EXPR, exit_label);
3614   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
3615                          build_empty_stmt (input_location));
3616   gfc_add_expr_to_block (&loop, tmp);
3617
3618   /* Assignment.  */
3619   gfc_add_modify (&loop,
3620                   fold_build1_loc (input_location, INDIRECT_REF, type, el),
3621                   build_int_cst (type, lang_hooks.to_target_charset (' ')));
3622
3623   /* Increment loop variables.  */
3624   gfc_add_modify (&loop, i,
3625                   fold_build2_loc (input_location, MINUS_EXPR, sizetype, i,
3626                                    TYPE_SIZE_UNIT (type)));
3627   gfc_add_modify (&loop, el,
3628                   fold_build2_loc (input_location, POINTER_PLUS_EXPR,
3629                                    TREE_TYPE (el), el, TYPE_SIZE_UNIT (type)));
3630
3631   /* Making the loop... actually loop!  */
3632   tmp = gfc_finish_block (&loop);
3633   tmp = build1_v (LOOP_EXPR, tmp);
3634   gfc_add_expr_to_block (&block, tmp);
3635
3636   /* The exit label.  */
3637   tmp = build1_v (LABEL_EXPR, exit_label);
3638   gfc_add_expr_to_block (&block, tmp);
3639
3640
3641   return gfc_finish_block (&block);
3642 }
3643
3644
3645 /* Generate code to copy a string.  */
3646
3647 void
3648 gfc_trans_string_copy (stmtblock_t * block, tree dlength, tree dest,
3649                        int dkind, tree slength, tree src, int skind)
3650 {
3651   tree tmp, dlen, slen;
3652   tree dsc;
3653   tree ssc;
3654   tree cond;
3655   tree cond2;
3656   tree tmp2;
3657   tree tmp3;
3658   tree tmp4;
3659   tree chartype;
3660   stmtblock_t tempblock;
3661
3662   gcc_assert (dkind == skind);
3663
3664   if (slength != NULL_TREE)
3665     {
3666       slen = fold_convert (size_type_node, gfc_evaluate_now (slength, block));
3667       ssc = gfc_string_to_single_character (slen, src, skind);
3668     }
3669   else
3670     {
3671       slen = build_int_cst (size_type_node, 1);
3672       ssc =  src;
3673     }
3674
3675   if (dlength != NULL_TREE)
3676     {
3677       dlen = fold_convert (size_type_node, gfc_evaluate_now (dlength, block));
3678       dsc = gfc_string_to_single_character (dlen, dest, dkind);
3679     }
3680   else
3681     {
3682       dlen = build_int_cst (size_type_node, 1);
3683       dsc =  dest;
3684     }
3685
3686   /* Assign directly if the types are compatible.  */
3687   if (dsc != NULL_TREE && ssc != NULL_TREE
3688       && TREE_TYPE (dsc) == TREE_TYPE (ssc))
3689     {
3690       gfc_add_modify (block, dsc, ssc);
3691       return;
3692     }
3693
3694   /* Do nothing if the destination length is zero.  */
3695   cond = fold_build2_loc (input_location, GT_EXPR, boolean_type_node, dlen,
3696                           build_int_cst (size_type_node, 0));
3697
3698   /* The following code was previously in _gfortran_copy_string:
3699
3700        // The two strings may overlap so we use memmove.
3701        void
3702        copy_string (GFC_INTEGER_4 destlen, char * dest,
3703                     GFC_INTEGER_4 srclen, const char * src)
3704        {
3705          if (srclen >= destlen)
3706            {
3707              // This will truncate if too long.
3708              memmove (dest, src, destlen);
3709            }
3710          else
3711            {
3712              memmove (dest, src, srclen);
3713              // Pad with spaces.
3714              memset (&dest[srclen], ' ', destlen - srclen);
3715            }
3716        }
3717
3718      We're now doing it here for better optimization, but the logic
3719      is the same.  */
3720
3721   /* For non-default character kinds, we have to multiply the string
3722      length by the base type size.  */
3723   chartype = gfc_get_char_type (dkind);
3724   slen = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
3725                           fold_convert (size_type_node, slen),
3726                           fold_convert (size_type_node,
3727                                         TYPE_SIZE_UNIT (chartype)));
3728   dlen = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
3729                           fold_convert (size_type_node, dlen),
3730                           fold_convert (size_type_node,
3731                                         TYPE_SIZE_UNIT (chartype)));
3732
3733   if (dlength)
3734     dest = fold_convert (pvoid_type_node, dest);
3735   else
3736     dest = gfc_build_addr_expr (pvoid_type_node, dest);
3737
3738   if (slength)
3739     src = fold_convert (pvoid_type_node, src);
3740   else
3741     src = gfc_build_addr_expr (pvoid_type_node, src);
3742
3743   /* Truncate string if source is too long.  */
3744   cond2 = fold_build2_loc (input_location, GE_EXPR, boolean_type_node, slen,
3745                            dlen);
3746   tmp2 = build_call_expr_loc (input_location,
3747                           built_in_decls[BUILT_IN_MEMMOVE],
3748                           3, dest, src, dlen);
3749
3750   /* Else copy and pad with spaces.  */
3751   tmp3 = build_call_expr_loc (input_location,
3752                           built_in_decls[BUILT_IN_MEMMOVE],
3753                           3, dest, src, slen);
3754
3755   tmp4 = fold_build2_loc (input_location, POINTER_PLUS_EXPR, TREE_TYPE (dest),
3756                           dest, fold_convert (sizetype, slen));
3757   tmp4 = fill_with_spaces (tmp4, chartype,
3758                            fold_build2_loc (input_location, MINUS_EXPR,
3759                                             TREE_TYPE(dlen), dlen, slen));
3760
3761   gfc_init_block (&tempblock);
3762   gfc_add_expr_to_block (&tempblock, tmp3);
3763   gfc_add_expr_to_block (&tempblock, tmp4);
3764   tmp3 = gfc_finish_block (&tempblock);
3765
3766   /* The whole copy_string function is there.  */
3767   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond2,
3768                          tmp2, tmp3);
3769   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
3770                          build_empty_stmt (input_location));
3771   gfc_add_expr_to_block (block, tmp);
3772 }
3773
3774
3775 /* Translate a statement function.
3776    The value of a statement function reference is obtained by evaluating the
3777    expression using the values of the actual arguments for the values of the
3778    corresponding dummy arguments.  */
3779
3780 static void
3781 gfc_conv_statement_function (gfc_se * se, gfc_expr * expr)
3782 {
3783   gfc_symbol *sym;
3784   gfc_symbol *fsym;
3785   gfc_formal_arglist *fargs;
3786   gfc_actual_arglist *args;
3787   gfc_se lse;
3788   gfc_se rse;
3789   gfc_saved_var *saved_vars;
3790   tree *temp_vars;
3791   tree type;
3792   tree tmp;
3793   int n;
3794
3795   sym = expr->symtree->n.sym;
3796   args = expr->value.function.actual;
3797   gfc_init_se (&lse, NULL);
3798   gfc_init_se (&rse, NULL);
3799
3800   n = 0;
3801   for (fargs = sym->formal; fargs; fargs = fargs->next)
3802     n++;
3803   saved_vars = (gfc_saved_var *)gfc_getmem (n * sizeof (gfc_saved_var));
3804   temp_vars = (tree *)gfc_getmem (n * sizeof (tree));
3805
3806   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
3807     {
3808       /* Each dummy shall be specified, explicitly or implicitly, to be
3809          scalar.  */
3810       gcc_assert (fargs->sym->attr.dimension == 0);
3811       fsym = fargs->sym;
3812
3813       /* Create a temporary to hold the value.  */
3814       type = gfc_typenode_for_spec (&fsym->ts);
3815       temp_vars[n] = gfc_create_var (type, fsym->name);
3816
3817       if (fsym->ts.type == BT_CHARACTER)
3818         {
3819           /* Copy string arguments.  */
3820           tree arglen;
3821
3822           gcc_assert (fsym->ts.u.cl && fsym->ts.u.cl->length
3823                       && fsym->ts.u.cl->length->expr_type == EXPR_CONSTANT);
3824
3825           arglen = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
3826           tmp = gfc_build_addr_expr (build_pointer_type (type),
3827                                      temp_vars[n]);
3828
3829           gfc_conv_expr (&rse, args->expr);
3830           gfc_conv_string_parameter (&rse);
3831           gfc_add_block_to_block (&se->pre, &lse.pre);
3832           gfc_add_block_to_block (&se->pre, &rse.pre);
3833
3834           gfc_trans_string_copy (&se->pre, arglen, tmp, fsym->ts.kind,
3835                                  rse.string_length, rse.expr, fsym->ts.kind);
3836           gfc_add_block_to_block (&se->pre, &lse.post);
3837           gfc_add_block_to_block (&se->pre, &rse.post);
3838         }
3839       else
3840         {
3841           /* For everything else, just evaluate the expression.  */
3842           gfc_conv_expr (&lse, args->expr);
3843
3844           gfc_add_block_to_block (&se->pre, &lse.pre);
3845           gfc_add_modify (&se->pre, temp_vars[n], lse.expr);
3846           gfc_add_block_to_block (&se->pre, &lse.post);
3847         }
3848
3849       args = args->next;
3850     }
3851
3852   /* Use the temporary variables in place of the real ones.  */
3853   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
3854     gfc_shadow_sym (fargs->sym, temp_vars[n], &saved_vars[n]);
3855
3856   gfc_conv_expr (se, sym->value);
3857
3858   if (sym->ts.type == BT_CHARACTER)
3859     {
3860       gfc_conv_const_charlen (sym->ts.u.cl);
3861
3862       /* Force the expression to the correct length.  */
3863       if (!INTEGER_CST_P (se->string_length)
3864           || tree_int_cst_lt (se->string_length,
3865                               sym->ts.u.cl->backend_decl))
3866         {
3867           type = gfc_get_character_type (sym->ts.kind, sym->ts.u.cl);
3868           tmp = gfc_create_var (type, sym->name);
3869           tmp = gfc_build_addr_expr (build_pointer_type (type), tmp);
3870           gfc_trans_string_copy (&se->pre, sym->ts.u.cl->backend_decl, tmp,
3871                                  sym->ts.kind, se->string_length, se->expr,
3872                                  sym->ts.kind);
3873           se->expr = tmp;
3874         }
3875       se->string_length = sym->ts.u.cl->backend_decl;
3876     }
3877
3878   /* Restore the original variables.  */
3879   for (fargs = sym->formal, n = 0; fargs; fargs = fargs->next, n++)
3880     gfc_restore_sym (fargs->sym, &saved_vars[n]);
3881   gfc_free (saved_vars);
3882 }
3883
3884
3885 /* Translate a function expression.  */
3886
3887 static void
3888 gfc_conv_function_expr (gfc_se * se, gfc_expr * expr)
3889 {
3890   gfc_symbol *sym;
3891
3892   if (expr->value.function.isym)
3893     {
3894       gfc_conv_intrinsic_function (se, expr);
3895       return;
3896     }
3897
3898   /* We distinguish statement functions from general functions to improve
3899      runtime performance.  */
3900   if (expr->symtree->n.sym->attr.proc == PROC_ST_FUNCTION)
3901     {
3902       gfc_conv_statement_function (se, expr);
3903       return;
3904     }
3905
3906   /* expr.value.function.esym is the resolved (specific) function symbol for
3907      most functions.  However this isn't set for dummy procedures.  */
3908   sym = expr->value.function.esym;
3909   if (!sym)
3910     sym = expr->symtree->n.sym;
3911
3912   gfc_conv_procedure_call (se, sym, expr->value.function.actual, expr, NULL);
3913 }
3914
3915
3916 /* Determine whether the given EXPR_CONSTANT is a zero initializer.  */
3917
3918 static bool
3919 is_zero_initializer_p (gfc_expr * expr)
3920 {
3921   if (expr->expr_type != EXPR_CONSTANT)
3922     return false;
3923
3924   /* We ignore constants with prescribed memory representations for now.  */
3925   if (expr->representation.string)
3926     return false;
3927
3928   switch (expr->ts.type)
3929     {
3930     case BT_INTEGER:
3931       return mpz_cmp_si (expr->value.integer, 0) == 0;
3932
3933     case BT_REAL:
3934       return mpfr_zero_p (expr->value.real)
3935              && MPFR_SIGN (expr->value.real) >= 0;
3936
3937     case BT_LOGICAL:
3938       return expr->value.logical == 0;
3939
3940     case BT_COMPLEX:
3941       return mpfr_zero_p (mpc_realref (expr->value.complex))
3942              && MPFR_SIGN (mpc_realref (expr->value.complex)) >= 0
3943              && mpfr_zero_p (mpc_imagref (expr->value.complex))
3944              && MPFR_SIGN (mpc_imagref (expr->value.complex)) >= 0;
3945
3946     default:
3947       break;
3948     }
3949   return false;
3950 }
3951
3952
3953 static void
3954 gfc_conv_array_constructor_expr (gfc_se * se, gfc_expr * expr)
3955 {
3956   gcc_assert (se->ss != NULL && se->ss != gfc_ss_terminator);
3957   gcc_assert (se->ss->expr == expr && se->ss->type == GFC_SS_CONSTRUCTOR);
3958
3959   gfc_conv_tmp_array_ref (se);
3960   gfc_advance_se_ss_chain (se);
3961 }
3962
3963
3964 /* Build a static initializer.  EXPR is the expression for the initial value.
3965    The other parameters describe the variable of the component being 
3966    initialized. EXPR may be null.  */
3967
3968 tree
3969 gfc_conv_initializer (gfc_expr * expr, gfc_typespec * ts, tree type,
3970                       bool array, bool pointer, bool procptr)
3971 {
3972   gfc_se se;
3973
3974   if (!(expr || pointer || procptr))
3975     return NULL_TREE;
3976
3977   /* Check if we have ISOCBINDING_NULL_PTR or ISOCBINDING_NULL_FUNPTR
3978      (these are the only two iso_c_binding derived types that can be
3979      used as initialization expressions).  If so, we need to modify
3980      the 'expr' to be that for a (void *).  */
3981   if (expr != NULL && expr->ts.type == BT_DERIVED
3982       && expr->ts.is_iso_c && expr->ts.u.derived)
3983     {
3984       gfc_symbol *derived = expr->ts.u.derived;
3985
3986       /* The derived symbol has already been converted to a (void *).  Use
3987          its kind.  */
3988       expr = gfc_get_int_expr (derived->ts.kind, NULL, 0);
3989       expr->ts.f90_type = derived->ts.f90_type;
3990
3991       gfc_init_se (&se, NULL);
3992       gfc_conv_constant (&se, expr);
3993       gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
3994       return se.expr;
3995     }
3996   
3997   if (array && !procptr)
3998     {
3999       tree ctor;
4000       /* Arrays need special handling.  */
4001       if (pointer)
4002         ctor = gfc_build_null_descriptor (type);
4003       /* Special case assigning an array to zero.  */
4004       else if (is_zero_initializer_p (expr))
4005         ctor = build_constructor (type, NULL);
4006       else
4007         ctor = gfc_conv_array_initializer (type, expr);
4008       TREE_STATIC (ctor) = 1;
4009       return ctor;
4010     }
4011   else if (pointer || procptr)
4012     {
4013       if (!expr || expr->expr_type == EXPR_NULL)
4014         return fold_convert (type, null_pointer_node);
4015       else
4016         {
4017           gfc_init_se (&se, NULL);
4018           se.want_pointer = 1;
4019           gfc_conv_expr (&se, expr);
4020           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
4021           return se.expr;
4022         }
4023     }
4024   else
4025     {
4026       switch (ts->type)
4027         {
4028         case BT_DERIVED:
4029         case BT_CLASS:
4030           gfc_init_se (&se, NULL);
4031           if (ts->type == BT_CLASS && expr->expr_type == EXPR_NULL)
4032             gfc_conv_structure (&se, gfc_class_null_initializer(ts), 1);
4033           else
4034             gfc_conv_structure (&se, expr, 1);
4035           gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
4036           TREE_STATIC (se.expr) = 1;
4037           return se.expr;
4038
4039         case BT_CHARACTER:
4040           {
4041             tree ctor = gfc_conv_string_init (ts->u.cl->backend_decl,expr);
4042             TREE_STATIC (ctor) = 1;
4043             return ctor;
4044           }
4045
4046         default:
4047           gfc_init_se (&se, NULL);
4048           gfc_conv_constant (&se, expr);
4049           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
4050           return se.expr;
4051         }
4052     }
4053 }
4054   
4055 static tree
4056 gfc_trans_subarray_assign (tree dest, gfc_component * cm, gfc_expr * expr)
4057 {
4058   gfc_se rse;
4059   gfc_se lse;
4060   gfc_ss *rss;
4061   gfc_ss *lss;
4062   stmtblock_t body;
4063   stmtblock_t block;
4064   gfc_loopinfo loop;
4065   int n;
4066   tree tmp;
4067
4068   gfc_start_block (&block);
4069
4070   /* Initialize the scalarizer.  */
4071   gfc_init_loopinfo (&loop);
4072
4073   gfc_init_se (&lse, NULL);
4074   gfc_init_se (&rse, NULL);
4075
4076   /* Walk the rhs.  */
4077   rss = gfc_walk_expr (expr);
4078   if (rss == gfc_ss_terminator)
4079     {
4080       /* The rhs is scalar.  Add a ss for the expression.  */
4081       rss = gfc_get_ss ();
4082       rss->next = gfc_ss_terminator;
4083       rss->type = GFC_SS_SCALAR;
4084       rss->expr = expr;
4085     }
4086
4087   /* Create a SS for the destination.  */
4088   lss = gfc_get_ss ();
4089   lss->type = GFC_SS_COMPONENT;
4090   lss->expr = NULL;
4091   lss->shape = gfc_get_shape (cm->as->rank);
4092   lss->next = gfc_ss_terminator;
4093   lss->data.info.dimen = cm->as->rank;
4094   lss->data.info.descriptor = dest;
4095   lss->data.info.data = gfc_conv_array_data (dest);
4096   lss->data.info.offset = gfc_conv_array_offset (dest);
4097   for (n = 0; n < cm->as->rank; n++)
4098     {
4099       lss->data.info.dim[n] = n;
4100       lss->data.info.start[n] = gfc_conv_array_lbound (dest, n);
4101       lss->data.info.stride[n] = gfc_index_one_node;
4102
4103       mpz_init (lss->shape[n]);
4104       mpz_sub (lss->shape[n], cm->as->upper[n]->value.integer,
4105                cm->as->lower[n]->value.integer);
4106       mpz_add_ui (lss->shape[n], lss->shape[n], 1);
4107     }
4108   
4109   /* Associate the SS with the loop.  */
4110   gfc_add_ss_to_loop (&loop, lss);
4111   gfc_add_ss_to_loop (&loop, rss);
4112
4113   /* Calculate the bounds of the scalarization.  */
4114   gfc_conv_ss_startstride (&loop);
4115
4116   /* Setup the scalarizing loops.  */
4117   gfc_conv_loop_setup (&loop, &expr->where);
4118
4119   /* Setup the gfc_se structures.  */
4120   gfc_copy_loopinfo_to_se (&lse, &loop);
4121   gfc_copy_loopinfo_to_se (&rse, &loop);
4122
4123   rse.ss = rss;
4124   gfc_mark_ss_chain_used (rss, 1);
4125   lse.ss = lss;
4126   gfc_mark_ss_chain_used (lss, 1);
4127
4128   /* Start the scalarized loop body.  */
4129   gfc_start_scalarized_body (&loop, &body);
4130
4131   gfc_conv_tmp_array_ref (&lse);
4132   if (cm->ts.type == BT_CHARACTER)
4133     lse.string_length = cm->ts.u.cl->backend_decl;
4134
4135   gfc_conv_expr (&rse, expr);
4136
4137   tmp = gfc_trans_scalar_assign (&lse, &rse, cm->ts, true, false, true);
4138   gfc_add_expr_to_block (&body, tmp);
4139
4140   gcc_assert (rse.ss == gfc_ss_terminator);
4141
4142   /* Generate the copying loops.  */
4143   gfc_trans_scalarizing_loops (&loop, &body);
4144
4145   /* Wrap the whole thing up.  */
4146   gfc_add_block_to_block (&block, &loop.pre);
4147   gfc_add_block_to_block (&block, &loop.post);
4148
4149   for (n = 0; n < cm->as->rank; n++)
4150     mpz_clear (lss->shape[n]);
4151   gfc_free (lss->shape);
4152
4153   gfc_cleanup_loop (&loop);
4154
4155   return gfc_finish_block (&block);
4156 }
4157
4158
4159 static tree
4160 gfc_trans_alloc_subarray_assign (tree dest, gfc_component * cm,
4161                                  gfc_expr * expr)
4162 {
4163   gfc_se se;
4164   gfc_ss *rss;
4165   stmtblock_t block;
4166   tree offset;
4167   int n;
4168   tree tmp;
4169   tree tmp2;
4170   gfc_array_spec *as;
4171   gfc_expr *arg = NULL;
4172
4173   gfc_start_block (&block);
4174   gfc_init_se (&se, NULL);
4175
4176   /* Get the descriptor for the expressions.  */ 
4177   rss = gfc_walk_expr (expr);
4178   se.want_pointer = 0;
4179   gfc_conv_expr_descriptor (&se, expr, rss);
4180   gfc_add_block_to_block (&block, &se.pre);
4181   gfc_add_modify (&block, dest, se.expr);
4182
4183   /* Deal with arrays of derived types with allocatable components.  */
4184   if (cm->ts.type == BT_DERIVED
4185         && cm->ts.u.derived->attr.alloc_comp)
4186     tmp = gfc_copy_alloc_comp (cm->ts.u.derived,
4187                                se.expr, dest,
4188                                cm->as->rank);
4189   else
4190     tmp = gfc_duplicate_allocatable (dest, se.expr,
4191                                      TREE_TYPE(cm->backend_decl),
4192                                      cm->as->rank);
4193
4194   gfc_add_expr_to_block (&block, tmp);
4195   gfc_add_block_to_block (&block, &se.post);
4196
4197   if (expr->expr_type != EXPR_VARIABLE)
4198     gfc_conv_descriptor_data_set (&block, se.expr,
4199                                   null_pointer_node);
4200
4201   /* We need to know if the argument of a conversion function is a
4202      variable, so that the correct lower bound can be used.  */
4203   if (expr->expr_type == EXPR_FUNCTION
4204         && expr->value.function.isym
4205         && expr->value.function.isym->conversion
4206         && expr->value.function.actual->expr
4207         && expr->value.function.actual->expr->expr_type == EXPR_VARIABLE)
4208     arg = expr->value.function.actual->expr;
4209
4210   /* Obtain the array spec of full array references.  */
4211   if (arg)
4212     as = gfc_get_full_arrayspec_from_expr (arg);
4213   else
4214     as = gfc_get_full_arrayspec_from_expr (expr);
4215
4216   /* Shift the lbound and ubound of temporaries to being unity,
4217      rather than zero, based. Always calculate the offset.  */
4218   offset = gfc_conv_descriptor_offset_get (dest);
4219   gfc_add_modify (&block, offset, gfc_index_zero_node);
4220   tmp2 =gfc_create_var (gfc_array_index_type, NULL);
4221
4222   for (n = 0; n < expr->rank; n++)
4223     {
4224       tree span;
4225       tree lbound;
4226
4227       /* Obtain the correct lbound - ISO/IEC TR 15581:2001 page 9.
4228          TODO It looks as if gfc_conv_expr_descriptor should return
4229          the correct bounds and that the following should not be
4230          necessary.  This would simplify gfc_conv_intrinsic_bound
4231          as well.  */
4232       if (as && as->lower[n])
4233         {
4234           gfc_se lbse;
4235           gfc_init_se (&lbse, NULL);
4236           gfc_conv_expr (&lbse, as->lower[n]);
4237           gfc_add_block_to_block (&block, &lbse.pre);
4238           lbound = gfc_evaluate_now (lbse.expr, &block);
4239         }
4240       else if (as && arg)
4241         {
4242           tmp = gfc_get_symbol_decl (arg->symtree->n.sym);
4243           lbound = gfc_conv_descriptor_lbound_get (tmp,
4244                                         gfc_rank_cst[n]);
4245         }
4246       else if (as)
4247         lbound = gfc_conv_descriptor_lbound_get (dest,
4248                                                 gfc_rank_cst[n]);
4249       else
4250         lbound = gfc_index_one_node;
4251
4252       lbound = fold_convert (gfc_array_index_type, lbound);
4253
4254       /* Shift the bounds and set the offset accordingly.  */
4255       tmp = gfc_conv_descriptor_ubound_get (dest, gfc_rank_cst[n]);
4256       span = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
4257                 tmp, gfc_conv_descriptor_lbound_get (dest, gfc_rank_cst[n]));
4258       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
4259                              span, lbound);
4260       gfc_conv_descriptor_ubound_set (&block, dest,
4261                                       gfc_rank_cst[n], tmp);
4262       gfc_conv_descriptor_lbound_set (&block, dest,
4263                                       gfc_rank_cst[n], lbound);
4264
4265       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
4266                          gfc_conv_descriptor_lbound_get (dest,
4267                                                          gfc_rank_cst[n]),
4268                          gfc_conv_descriptor_stride_get (dest,
4269                                                          gfc_rank_cst[n]));
4270       gfc_add_modify (&block, tmp2, tmp);
4271       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
4272                              offset, tmp2);
4273       gfc_conv_descriptor_offset_set (&block, dest, tmp);
4274     }
4275
4276   if (arg)
4277     {
4278       /* If a conversion expression has a null data pointer
4279          argument, nullify the allocatable component.  */
4280       tree non_null_expr;
4281       tree null_expr;
4282
4283       if (arg->symtree->n.sym->attr.allocatable
4284             || arg->symtree->n.sym->attr.pointer)
4285         {
4286           non_null_expr = gfc_finish_block (&block);
4287           gfc_start_block (&block);
4288           gfc_conv_descriptor_data_set (&block, dest,
4289                                         null_pointer_node);
4290           null_expr = gfc_finish_block (&block);
4291           tmp = gfc_conv_descriptor_data_get (arg->symtree->n.sym->backend_decl);
4292           tmp = build2_loc (input_location, EQ_EXPR, boolean_type_node, tmp,
4293                             fold_convert (TREE_TYPE (tmp), null_pointer_node));
4294           return build3_v (COND_EXPR, tmp,
4295                            null_expr, non_null_expr);
4296         }
4297     }
4298
4299   return gfc_finish_block (&block);
4300 }
4301
4302
4303 /* Assign a single component of a derived type constructor.  */
4304
4305 static tree
4306 gfc_trans_subcomponent_assign (tree dest, gfc_component * cm, gfc_expr * expr)
4307 {
4308   gfc_se se;
4309   gfc_se lse;
4310   gfc_ss *rss;
4311   stmtblock_t block;
4312   tree tmp;
4313
4314   gfc_start_block (&block);
4315
4316   if (cm->attr.pointer)
4317     {
4318       gfc_init_se (&se, NULL);
4319       /* Pointer component.  */
4320       if (cm->attr.dimension)
4321         {
4322           /* Array pointer.  */
4323           if (expr->expr_type == EXPR_NULL)
4324             gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
4325           else
4326             {
4327               rss = gfc_walk_expr (expr);
4328               se.direct_byref = 1;
4329               se.expr = dest;
4330               gfc_conv_expr_descriptor (&se, expr, rss);
4331               gfc_add_block_to_block (&block, &se.pre);
4332               gfc_add_block_to_block (&block, &se.post);
4333             }
4334         }
4335       else
4336         {
4337           /* Scalar pointers.  */
4338           se.want_pointer = 1;
4339           gfc_conv_expr (&se, expr);
4340           gfc_add_block_to_block (&block, &se.pre);
4341           gfc_add_modify (&block, dest,
4342                                fold_convert (TREE_TYPE (dest), se.expr));
4343           gfc_add_block_to_block (&block, &se.post);
4344         }
4345     }
4346   else if (cm->ts.type == BT_CLASS && expr->expr_type == EXPR_NULL)
4347     {
4348       /* NULL initialization for CLASS components.  */
4349       tmp = gfc_trans_structure_assign (dest,
4350                                         gfc_class_null_initializer (&cm->ts));
4351       gfc_add_expr_to_block (&block, tmp);
4352     }
4353   else if (cm->attr.dimension)
4354     {
4355       if (cm->attr.allocatable && expr->expr_type == EXPR_NULL)
4356         gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
4357       else if (cm->attr.allocatable)
4358         {
4359           tmp = gfc_trans_alloc_subarray_assign (dest, cm, expr);
4360           gfc_add_expr_to_block (&block, tmp);
4361         }
4362       else
4363         {
4364           tmp = gfc_trans_subarray_assign (dest, cm, expr);
4365           gfc_add_expr_to_block (&block, tmp);
4366         }
4367     }
4368   else if (expr->ts.type == BT_DERIVED)
4369     {
4370       if (expr->expr_type != EXPR_STRUCTURE)
4371         {
4372           gfc_init_se (&se, NULL);
4373           gfc_conv_expr (&se, expr);
4374           gfc_add_block_to_block (&block, &se.pre);
4375           gfc_add_modify (&block, dest,
4376                                fold_convert (TREE_TYPE (dest), se.expr));
4377           gfc_add_block_to_block (&block, &se.post);
4378         }
4379       else
4380         {
4381           /* Nested constructors.  */
4382           tmp = gfc_trans_structure_assign (dest, expr);
4383           gfc_add_expr_to_block (&block, tmp);
4384         }
4385     }
4386   else
4387     {
4388       /* Scalar component.  */
4389       gfc_init_se (&se, NULL);
4390       gfc_init_se (&lse, NULL);
4391
4392       gfc_conv_expr (&se, expr);
4393       if (cm->ts.type == BT_CHARACTER)
4394         lse.string_length = cm->ts.u.cl->backend_decl;
4395       lse.expr = dest;
4396       tmp = gfc_trans_scalar_assign (&lse, &se, cm->ts, true, false, true);
4397       gfc_add_expr_to_block (&block, tmp);
4398     }
4399   return gfc_finish_block (&block);
4400 }
4401
4402 /* Assign a derived type constructor to a variable.  */
4403
4404 static tree
4405 gfc_trans_structure_assign (tree dest, gfc_expr * expr)
4406 {
4407   gfc_constructor *c;
4408   gfc_component *cm;
4409   stmtblock_t block;
4410   tree field;
4411   tree tmp;
4412
4413   gfc_start_block (&block);
4414   cm = expr->ts.u.derived->components;
4415   for (c = gfc_constructor_first (expr->value.constructor);
4416        c; c = gfc_constructor_next (c), cm = cm->next)
4417     {
4418       /* Skip absent members in default initializers.  */
4419       if (!c->expr)
4420         continue;
4421
4422       /* Handle c_null_(fun)ptr.  */
4423       if (c && c->expr && c->expr->ts.is_iso_c)
4424         {
4425           field = cm->backend_decl;
4426           tmp = fold_build3_loc (input_location, COMPONENT_REF,
4427                                  TREE_TYPE (field),
4428                                  dest, field, NULL_TREE);
4429           tmp = fold_build2_loc (input_location, MODIFY_EXPR, TREE_TYPE (tmp),
4430                                  tmp, fold_convert (TREE_TYPE (tmp),
4431                                                     null_pointer_node));
4432           gfc_add_expr_to_block (&block, tmp);
4433           continue;
4434         }
4435
4436       field = cm->backend_decl;
4437       tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
4438                              dest, field, NULL_TREE);
4439       tmp = gfc_trans_subcomponent_assign (tmp, cm, c->expr);
4440       gfc_add_expr_to_block (&block, tmp);
4441     }
4442   return gfc_finish_block (&block);
4443 }
4444
4445 /* Build an expression for a constructor. If init is nonzero then
4446    this is part of a static variable initializer.  */
4447
4448 void
4449 gfc_conv_structure (gfc_se * se, gfc_expr * expr, int init)
4450 {
4451   gfc_constructor *c;
4452   gfc_component *cm;
4453   tree val;
4454   tree type;
4455   tree tmp;
4456   VEC(constructor_elt,gc) *v = NULL;
4457
4458   gcc_assert (se->ss == NULL);
4459   gcc_assert (expr->expr_type == EXPR_STRUCTURE);
4460   type = gfc_typenode_for_spec (&expr->ts);
4461
4462   if (!init)
4463     {
4464       /* Create a temporary variable and fill it in.  */
4465       se->expr = gfc_create_var (type, expr->ts.u.derived->name);
4466       tmp = gfc_trans_structure_assign (se->expr, expr);
4467       gfc_add_expr_to_block (&se->pre, tmp);
4468       return;
4469     }
4470
4471   cm = expr->ts.u.derived->components;
4472
4473   for (c = gfc_constructor_first (expr->value.constructor);
4474        c; c = gfc_constructor_next (c), cm = cm->next)
4475     {
4476       /* Skip absent members in default initializers and allocatable
4477          components.  Although the latter have a default initializer
4478          of EXPR_NULL,... by default, the static nullify is not needed
4479          since this is done every time we come into scope.  */
4480       if (!c->expr || cm->attr.allocatable)
4481         continue;
4482
4483       if (strcmp (cm->name, "$size") == 0)
4484         {
4485           val = TYPE_SIZE_UNIT (gfc_get_derived_type (cm->ts.u.derived));
4486           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
4487         }
4488       else if (cm->initializer && cm->initializer->expr_type != EXPR_NULL
4489                && strcmp (cm->name, "$extends") == 0)
4490         {
4491           tree vtab;
4492           gfc_symbol *vtabs;
4493           vtabs = cm->initializer->symtree->n.sym;
4494           vtab = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtabs));
4495           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, vtab);
4496         }
4497       else
4498         {
4499           val = gfc_conv_initializer (c->expr, &cm->ts,
4500                                       TREE_TYPE (cm->backend_decl),
4501                                       cm->attr.dimension, cm->attr.pointer,
4502                                       cm->attr.proc_pointer);
4503
4504           /* Append it to the constructor list.  */
4505           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
4506         }
4507     }
4508   se->expr = build_constructor (type, v);
4509   if (init) 
4510     TREE_CONSTANT (se->expr) = 1;
4511 }
4512
4513
4514 /* Translate a substring expression.  */
4515
4516 static void
4517 gfc_conv_substring_expr (gfc_se * se, gfc_expr * expr)
4518 {
4519   gfc_ref *ref;
4520
4521   ref = expr->ref;
4522
4523   gcc_assert (ref == NULL || ref->type == REF_SUBSTRING);
4524
4525   se->expr = gfc_build_wide_string_const (expr->ts.kind,
4526                                           expr->value.character.length,
4527                                           expr->value.character.string);
4528
4529   se->string_length = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (se->expr)));
4530   TYPE_STRING_FLAG (TREE_TYPE (se->expr)) = 1;
4531
4532   if (ref)
4533     gfc_conv_substring (se, ref, expr->ts.kind, NULL, &expr->where);
4534 }
4535
4536
4537 /* Entry point for expression translation.  Evaluates a scalar quantity.
4538    EXPR is the expression to be translated, and SE is the state structure if
4539    called from within the scalarized.  */
4540
4541 void
4542 gfc_conv_expr (gfc_se * se, gfc_expr * expr)
4543 {
4544   if (se->ss && se->ss->expr == expr
4545       && (se->ss->type == GFC_SS_SCALAR || se->ss->type == GFC_SS_REFERENCE))
4546     {
4547       /* Substitute a scalar expression evaluated outside the scalarization
4548          loop.  */
4549       se->expr = se->ss->data.scalar.expr;
4550       if (se->ss->type == GFC_SS_REFERENCE)
4551         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
4552       se->string_length = se->ss->string_length;
4553       gfc_advance_se_ss_chain (se);
4554       return;
4555     }
4556
4557   /* We need to convert the expressions for the iso_c_binding derived types.
4558      C_NULL_PTR and C_NULL_FUNPTR will be made EXPR_NULL, which evaluates to
4559      null_pointer_node.  C_PTR and C_FUNPTR are converted to match the
4560      typespec for the C_PTR and C_FUNPTR symbols, which has already been
4561      updated to be an integer with a kind equal to the size of a (void *).  */
4562   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived
4563       && expr->ts.u.derived->attr.is_iso_c)
4564     {
4565       if (expr->symtree->n.sym->intmod_sym_id == ISOCBINDING_NULL_PTR
4566           || expr->symtree->n.sym->intmod_sym_id == ISOCBINDING_NULL_FUNPTR)
4567         {
4568           /* Set expr_type to EXPR_NULL, which will result in
4569              null_pointer_node being used below.  */
4570           expr->expr_type = EXPR_NULL;
4571         }
4572       else
4573         {
4574           /* Update the type/kind of the expression to be what the new
4575              type/kind are for the updated symbols of C_PTR/C_FUNPTR.  */
4576           expr->ts.type = expr->ts.u.derived->ts.type;
4577           expr->ts.f90_type = expr->ts.u.derived->ts.f90_type;
4578           expr->ts.kind = expr->ts.u.derived->ts.kind;
4579         }
4580     }
4581   
4582   switch (expr->expr_type)
4583     {
4584     case EXPR_OP:
4585       gfc_conv_expr_op (se, expr);
4586       break;
4587
4588     case EXPR_FUNCTION:
4589       gfc_conv_function_expr (se, expr);
4590       break;
4591
4592     case EXPR_CONSTANT:
4593       gfc_conv_constant (se, expr);
4594       break;
4595
4596     case EXPR_VARIABLE:
4597       gfc_conv_variable (se, expr);
4598       break;
4599
4600     case EXPR_NULL:
4601       se->expr = null_pointer_node;
4602       break;
4603
4604     case EXPR_SUBSTRING:
4605       gfc_conv_substring_expr (se, expr);
4606       break;
4607
4608     case EXPR_STRUCTURE:
4609       gfc_conv_structure (se, expr, 0);
4610       break;
4611
4612     case EXPR_ARRAY:
4613       gfc_conv_array_constructor_expr (se, expr);
4614       break;
4615
4616     default:
4617       gcc_unreachable ();
4618       break;
4619     }
4620 }
4621
4622 /* Like gfc_conv_expr_val, but the value is also suitable for use in the lhs
4623    of an assignment.  */
4624 void
4625 gfc_conv_expr_lhs (gfc_se * se, gfc_expr * expr)
4626 {
4627   gfc_conv_expr (se, expr);
4628   /* All numeric lvalues should have empty post chains.  If not we need to
4629      figure out a way of rewriting an lvalue so that it has no post chain.  */
4630   gcc_assert (expr->ts.type == BT_CHARACTER || !se->post.head);
4631 }
4632
4633 /* Like gfc_conv_expr, but the POST block is guaranteed to be empty for
4634    numeric expressions.  Used for scalar values where inserting cleanup code
4635    is inconvenient.  */
4636 void
4637 gfc_conv_expr_val (gfc_se * se, gfc_expr * expr)
4638 {
4639   tree val;
4640
4641   gcc_assert (expr->ts.type != BT_CHARACTER);
4642   gfc_conv_expr (se, expr);
4643   if (se->post.head)
4644     {
4645       val = gfc_create_var (TREE_TYPE (se->expr), NULL);
4646       gfc_add_modify (&se->pre, val, se->expr);
4647       se->expr = val;
4648       gfc_add_block_to_block (&se->pre, &se->post);
4649     }
4650 }
4651
4652 /* Helper to translate an expression and convert it to a particular type.  */
4653 void
4654 gfc_conv_expr_type (gfc_se * se, gfc_expr * expr, tree type)
4655 {
4656   gfc_conv_expr_val (se, expr);
4657   se->expr = convert (type, se->expr);
4658 }
4659
4660
4661 /* Converts an expression so that it can be passed by reference.  Scalar
4662    values only.  */
4663
4664 void
4665 gfc_conv_expr_reference (gfc_se * se, gfc_expr * expr)
4666 {
4667   tree var;
4668
4669   if (se->ss && se->ss->expr == expr
4670       && se->ss->type == GFC_SS_REFERENCE)
4671     {
4672       /* Returns a reference to the scalar evaluated outside the loop
4673          for this case.  */
4674       gfc_conv_expr (se, expr);
4675       return;
4676     }
4677
4678   if (expr->ts.type == BT_CHARACTER)
4679     {
4680       gfc_conv_expr (se, expr);
4681       gfc_conv_string_parameter (se);
4682       return;
4683     }
4684
4685   if (expr->expr_type == EXPR_VARIABLE)
4686     {
4687       se->want_pointer = 1;
4688       gfc_conv_expr (se, expr);
4689       if (se->post.head)
4690         {
4691           var = gfc_create_var (TREE_TYPE (se->expr), NULL);
4692           gfc_add_modify (&se->pre, var, se->expr);
4693           gfc_add_block_to_block (&se->pre, &se->post);
4694           se->expr = var;
4695         }
4696       return;
4697     }
4698
4699   if (expr->expr_type == EXPR_FUNCTION
4700       && ((expr->value.function.esym
4701            && expr->value.function.esym->result->attr.pointer
4702            && !expr->value.function.esym->result->attr.dimension)
4703           || (!expr->value.function.esym
4704               && expr->symtree->n.sym->attr.pointer
4705               && !expr->symtree->n.sym->attr.dimension)))
4706     {
4707       se->want_pointer = 1;
4708       gfc_conv_expr (se, expr);
4709       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
4710       gfc_add_modify (&se->pre, var, se->expr);
4711       se->expr = var;
4712       return;
4713     }
4714
4715
4716   gfc_conv_expr (se, expr);
4717
4718   /* Create a temporary var to hold the value.  */
4719   if (TREE_CONSTANT (se->expr))
4720     {
4721       tree tmp = se->expr;
4722       STRIP_TYPE_NOPS (tmp);
4723       var = build_decl (input_location,
4724                         CONST_DECL, NULL, TREE_TYPE (tmp));
4725       DECL_INITIAL (var) = tmp;
4726       TREE_STATIC (var) = 1;
4727       pushdecl (var);
4728     }
4729   else
4730     {
4731       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
4732       gfc_add_modify (&se->pre, var, se->expr);
4733     }
4734   gfc_add_block_to_block (&se->pre, &se->post);
4735
4736   /* Take the address of that value.  */
4737   se->expr = gfc_build_addr_expr (NULL_TREE, var);
4738 }
4739
4740
4741 tree
4742 gfc_trans_pointer_assign (gfc_code * code)
4743 {
4744   return gfc_trans_pointer_assignment (code->expr1, code->expr2);
4745 }
4746
4747
4748 /* Generate code for a pointer assignment.  */
4749
4750 tree
4751 gfc_trans_pointer_assignment (gfc_expr * expr1, gfc_expr * expr2)
4752 {
4753   gfc_se lse;
4754   gfc_se rse;
4755   gfc_ss *lss;
4756   gfc_ss *rss;
4757   stmtblock_t block;
4758   tree desc;
4759   tree tmp;
4760   tree decl;
4761
4762   gfc_start_block (&block);
4763
4764   gfc_init_se (&lse, NULL);
4765
4766   lss = gfc_walk_expr (expr1);
4767   rss = gfc_walk_expr (expr2);
4768   if (lss == gfc_ss_terminator)
4769     {
4770       /* Scalar pointers.  */
4771       lse.want_pointer = 1;
4772       gfc_conv_expr (&lse, expr1);
4773       gcc_assert (rss == gfc_ss_terminator);
4774       gfc_init_se (&rse, NULL);
4775       rse.want_pointer = 1;
4776       gfc_conv_expr (&rse, expr2);
4777
4778       if (expr1->symtree->n.sym->attr.proc_pointer
4779           && expr1->symtree->n.sym->attr.dummy)
4780         lse.expr = build_fold_indirect_ref_loc (input_location,
4781                                             lse.expr);
4782
4783       if (expr2->symtree && expr2->symtree->n.sym->attr.proc_pointer
4784           && expr2->symtree->n.sym->attr.dummy)
4785         rse.expr = build_fold_indirect_ref_loc (input_location,
4786                                             rse.expr);
4787
4788       gfc_add_block_to_block (&block, &lse.pre);
4789       gfc_add_block_to_block (&block, &rse.pre);
4790
4791       /* Check character lengths if character expression.  The test is only
4792          really added if -fbounds-check is enabled.  */
4793       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL
4794           && !expr1->symtree->n.sym->attr.proc_pointer
4795           && !gfc_is_proc_ptr_comp (expr1, NULL))
4796         {
4797           gcc_assert (expr2->ts.type == BT_CHARACTER);
4798           gcc_assert (lse.string_length && rse.string_length);
4799           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
4800                                        lse.string_length, rse.string_length,
4801                                        &block);
4802         }
4803
4804       gfc_add_modify (&block, lse.expr,
4805                            fold_convert (TREE_TYPE (lse.expr), rse.expr));
4806
4807       gfc_add_block_to_block (&block, &rse.post);
4808       gfc_add_block_to_block (&block, &lse.post);
4809     }
4810   else
4811     {
4812       gfc_ref* remap;
4813       bool rank_remap;
4814       tree strlen_lhs;
4815       tree strlen_rhs = NULL_TREE;
4816
4817       /* Array pointer.  Find the last reference on the LHS and if it is an
4818          array section ref, we're dealing with bounds remapping.  In this case,
4819          set it to AR_FULL so that gfc_conv_expr_descriptor does
4820          not see it and process the bounds remapping afterwards explicitely.  */
4821       for (remap = expr1->ref; remap; remap = remap->next)
4822         if (!remap->next && remap->type == REF_ARRAY
4823             && remap->u.ar.type == AR_SECTION)
4824           {  
4825             remap->u.ar.type = AR_FULL;
4826             break;
4827           }
4828       rank_remap = (remap && remap->u.ar.end[0]);
4829
4830       gfc_conv_expr_descriptor (&lse, expr1, lss);
4831       strlen_lhs = lse.string_length;
4832       desc = lse.expr;
4833
4834       if (expr2->expr_type == EXPR_NULL)
4835         {
4836           /* Just set the data pointer to null.  */
4837           gfc_conv_descriptor_data_set (&lse.pre, lse.expr, null_pointer_node);
4838         }
4839       else if (rank_remap)
4840         {
4841           /* If we are rank-remapping, just get the RHS's descriptor and
4842              process this later on.  */
4843           gfc_init_se (&rse, NULL);
4844           rse.direct_byref = 1;
4845           rse.byref_noassign = 1;
4846           gfc_conv_expr_descriptor (&rse, expr2, rss);
4847           strlen_rhs = rse.string_length;
4848         }
4849       else if (expr2->expr_type == EXPR_VARIABLE)
4850         {
4851           /* Assign directly to the LHS's descriptor.  */
4852           lse.direct_byref = 1;
4853           gfc_conv_expr_descriptor (&lse, expr2, rss);
4854           strlen_rhs = lse.string_length;
4855
4856           /* If this is a subreference array pointer assignment, use the rhs
4857              descriptor element size for the lhs span.  */
4858           if (expr1->symtree->n.sym->attr.subref_array_pointer)
4859             {
4860               decl = expr1->symtree->n.sym->backend_decl;
4861               gfc_init_se (&rse, NULL);
4862               rse.descriptor_only = 1;
4863               gfc_conv_expr (&rse, expr2);
4864               tmp = gfc_get_element_type (TREE_TYPE (rse.expr));
4865               tmp = fold_convert (gfc_array_index_type, size_in_bytes (tmp));
4866               if (!INTEGER_CST_P (tmp))
4867                 gfc_add_block_to_block (&lse.post, &rse.pre);
4868               gfc_add_modify (&lse.post, GFC_DECL_SPAN(decl), tmp);
4869             }
4870         }
4871       else
4872         {
4873           /* Assign to a temporary descriptor and then copy that
4874              temporary to the pointer.  */
4875           tmp = gfc_create_var (TREE_TYPE (desc), "ptrtemp");
4876
4877           lse.expr = tmp;
4878           lse.direct_byref = 1;
4879           gfc_conv_expr_descriptor (&lse, expr2, rss);
4880           strlen_rhs = lse.string_length;
4881           gfc_add_modify (&lse.pre, desc, tmp);
4882         }
4883
4884       gfc_add_block_to_block (&block, &lse.pre);
4885       if (rank_remap)
4886         gfc_add_block_to_block (&block, &rse.pre);
4887
4888       /* If we do bounds remapping, update LHS descriptor accordingly.  */
4889       if (remap)
4890         {
4891           int dim;
4892           gcc_assert (remap->u.ar.dimen == expr1->rank);
4893
4894           if (rank_remap)
4895             {
4896               /* Do rank remapping.  We already have the RHS's descriptor
4897                  converted in rse and now have to build the correct LHS
4898                  descriptor for it.  */
4899
4900               tree dtype, data;
4901               tree offs, stride;
4902               tree lbound, ubound;
4903
4904               /* Set dtype.  */
4905               dtype = gfc_conv_descriptor_dtype (desc);
4906               tmp = gfc_get_dtype (TREE_TYPE (desc));
4907               gfc_add_modify (&block, dtype, tmp);
4908
4909               /* Copy data pointer.  */
4910               data = gfc_conv_descriptor_data_get (rse.expr);
4911               gfc_conv_descriptor_data_set (&block, desc, data);
4912
4913               /* Copy offset but adjust it such that it would correspond
4914                  to a lbound of zero.  */
4915               offs = gfc_conv_descriptor_offset_get (rse.expr);
4916               for (dim = 0; dim < expr2->rank; ++dim)
4917                 {
4918                   stride = gfc_conv_descriptor_stride_get (rse.expr,
4919                                                            gfc_rank_cst[dim]);
4920                   lbound = gfc_conv_descriptor_lbound_get (rse.expr,
4921                                                            gfc_rank_cst[dim]);
4922                   tmp = fold_build2_loc (input_location, MULT_EXPR,
4923                                          gfc_array_index_type, stride, lbound);
4924                   offs = fold_build2_loc (input_location, PLUS_EXPR,
4925                                           gfc_array_index_type, offs, tmp);
4926                 }
4927               gfc_conv_descriptor_offset_set (&block, desc, offs);
4928
4929               /* Set the bounds as declared for the LHS and calculate strides as
4930                  well as another offset update accordingly.  */
4931               stride = gfc_conv_descriptor_stride_get (rse.expr,
4932                                                        gfc_rank_cst[0]);
4933               for (dim = 0; dim < expr1->rank; ++dim)
4934                 {
4935                   gfc_se lower_se;
4936                   gfc_se upper_se;
4937
4938                   gcc_assert (remap->u.ar.start[dim] && remap->u.ar.end[dim]);
4939
4940                   /* Convert declared bounds.  */
4941                   gfc_init_se (&lower_se, NULL);
4942                   gfc_init_se (&upper_se, NULL);
4943                   gfc_conv_expr (&lower_se, remap->u.ar.start[dim]);
4944                   gfc_conv_expr (&upper_se, remap->u.ar.end[dim]);
4945
4946                   gfc_add_block_to_block (&block, &lower_se.pre);
4947                   gfc_add_block_to_block (&block, &upper_se.pre);
4948
4949                   lbound = fold_convert (gfc_array_index_type, lower_se.expr);
4950                   ubound = fold_convert (gfc_array_index_type, upper_se.expr);
4951
4952                   lbound = gfc_evaluate_now (lbound, &block);
4953                   ubound = gfc_evaluate_now (ubound, &block);
4954
4955                   gfc_add_block_to_block (&block, &lower_se.post);
4956                   gfc_add_block_to_block (&block, &upper_se.post);
4957
4958                   /* Set bounds in descriptor.  */
4959                   gfc_conv_descriptor_lbound_set (&block, desc,
4960                                                   gfc_rank_cst[dim], lbound);
4961                   gfc_conv_descriptor_ubound_set (&block, desc,
4962                                                   gfc_rank_cst[dim], ubound);
4963
4964                   /* Set stride.  */
4965                   stride = gfc_evaluate_now (stride, &block);
4966                   gfc_conv_descriptor_stride_set (&block, desc,
4967                                                   gfc_rank_cst[dim], stride);
4968
4969                   /* Update offset.  */
4970                   offs = gfc_conv_descriptor_offset_get (desc);
4971                   tmp = fold_build2_loc (input_location, MULT_EXPR,
4972                                          gfc_array_index_type, lbound, stride);
4973                   offs = fold_build2_loc (input_location, MINUS_EXPR,
4974                                           gfc_array_index_type, offs, tmp);
4975                   offs = gfc_evaluate_now (offs, &block);
4976                   gfc_conv_descriptor_offset_set (&block, desc, offs);
4977
4978                   /* Update stride.  */
4979                   tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
4980                   stride = fold_build2_loc (input_location, MULT_EXPR,
4981                                             gfc_array_index_type, stride, tmp);
4982                 }
4983             }
4984           else
4985             {
4986               /* Bounds remapping.  Just shift the lower bounds.  */
4987
4988               gcc_assert (expr1->rank == expr2->rank);
4989
4990               for (dim = 0; dim < remap->u.ar.dimen; ++dim)
4991                 {
4992                   gfc_se lbound_se;
4993
4994                   gcc_assert (remap->u.ar.start[dim]);
4995                   gcc_assert (!remap->u.ar.end[dim]);
4996                   gfc_init_se (&lbound_se, NULL);
4997                   gfc_conv_expr (&lbound_se, remap->u.ar.start[dim]);
4998
4999                   gfc_add_block_to_block (&block, &lbound_se.pre);
5000                   gfc_conv_shift_descriptor_lbound (&block, desc,
5001                                                     dim, lbound_se.expr);
5002                   gfc_add_block_to_block (&block, &lbound_se.post);
5003                 }
5004             }
5005         }
5006
5007       /* Check string lengths if applicable.  The check is only really added
5008          to the output code if -fbounds-check is enabled.  */
5009       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL)
5010         {
5011           gcc_assert (expr2->ts.type == BT_CHARACTER);
5012           gcc_assert (strlen_lhs && strlen_rhs);
5013           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
5014                                        strlen_lhs, strlen_rhs, &block);
5015         }
5016
5017       /* If rank remapping was done, check with -fcheck=bounds that
5018          the target is at least as large as the pointer.  */
5019       if (rank_remap && (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS))
5020         {
5021           tree lsize, rsize;
5022           tree fault;
5023           const char* msg;
5024
5025           lsize = gfc_conv_descriptor_size (lse.expr, expr1->rank);
5026           rsize = gfc_conv_descriptor_size (rse.expr, expr2->rank);
5027
5028           lsize = gfc_evaluate_now (lsize, &block);
5029           rsize = gfc_evaluate_now (rsize, &block);
5030           fault = fold_build2_loc (input_location, LT_EXPR, boolean_type_node,
5031                                    rsize, lsize);
5032
5033           msg = _("Target of rank remapping is too small (%ld < %ld)");
5034           gfc_trans_runtime_check (true, false, fault, &block, &expr2->where,
5035                                    msg, rsize, lsize);
5036         }
5037
5038       gfc_add_block_to_block (&block, &lse.post);
5039       if (rank_remap)
5040         gfc_add_block_to_block (&block, &rse.post);
5041     }
5042
5043   return gfc_finish_block (&block);
5044 }
5045
5046
5047 /* Makes sure se is suitable for passing as a function string parameter.  */
5048 /* TODO: Need to check all callers of this function.  It may be abused.  */
5049
5050 void
5051 gfc_conv_string_parameter (gfc_se * se)
5052 {
5053   tree type;
5054
5055   if (TREE_CODE (se->expr) == STRING_CST)
5056     {
5057       type = TREE_TYPE (TREE_TYPE (se->expr));
5058       se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
5059       return;
5060     }
5061
5062   if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
5063     {
5064       if (TREE_CODE (se->expr) != INDIRECT_REF)
5065         {
5066           type = TREE_TYPE (se->expr);
5067           se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
5068         }
5069       else
5070         {
5071           type = gfc_get_character_type_len (gfc_default_character_kind,
5072                                              se->string_length);
5073           type = build_pointer_type (type);
5074           se->expr = gfc_build_addr_expr (type, se->expr);
5075         }
5076     }
5077
5078   gcc_assert (POINTER_TYPE_P (TREE_TYPE (se->expr)));
5079   gcc_assert (se->string_length
5080           && TREE_CODE (TREE_TYPE (se->string_length)) == INTEGER_TYPE);
5081 }
5082
5083
5084 /* Generate code for assignment of scalar variables.  Includes character
5085    strings and derived types with allocatable components.
5086    If you know that the LHS has no allocations, set dealloc to false.  */
5087
5088 tree
5089 gfc_trans_scalar_assign (gfc_se * lse, gfc_se * rse, gfc_typespec ts,
5090                          bool l_is_temp, bool r_is_var, bool dealloc)
5091 {
5092   stmtblock_t block;
5093   tree tmp;
5094   tree cond;
5095
5096   gfc_init_block (&block);
5097
5098   if (ts.type == BT_CHARACTER)
5099     {
5100       tree rlen = NULL;
5101       tree llen = NULL;
5102
5103       if (lse->string_length != NULL_TREE)
5104         {
5105           gfc_conv_string_parameter (lse);
5106           gfc_add_block_to_block (&block, &lse->pre);
5107           llen = lse->string_length;
5108         }
5109
5110       if (rse->string_length != NULL_TREE)
5111         {
5112           gcc_assert (rse->string_length != NULL_TREE);
5113           gfc_conv_string_parameter (rse);
5114           gfc_add_block_to_block (&block, &rse->pre);
5115           rlen = rse->string_length;
5116         }
5117
5118       gfc_trans_string_copy (&block, llen, lse->expr, ts.kind, rlen,
5119                              rse->expr, ts.kind);
5120     }
5121   else if (ts.type == BT_DERIVED && ts.u.derived->attr.alloc_comp)
5122     {
5123       cond = NULL_TREE;
5124         
5125       /* Are the rhs and the lhs the same?  */
5126       if (r_is_var)
5127         {
5128           cond = fold_build2_loc (input_location, EQ_EXPR, boolean_type_node,
5129                                   gfc_build_addr_expr (NULL_TREE, lse->expr),
5130                                   gfc_build_addr_expr (NULL_TREE, rse->expr));
5131           cond = gfc_evaluate_now (cond, &lse->pre);
5132         }
5133
5134       /* Deallocate the lhs allocated components as long as it is not
5135          the same as the rhs.  This must be done following the assignment
5136          to prevent deallocating data that could be used in the rhs
5137          expression.  */
5138       if (!l_is_temp && dealloc)
5139         {
5140           tmp = gfc_evaluate_now (lse->expr, &lse->pre);
5141           tmp = gfc_deallocate_alloc_comp (ts.u.derived, tmp, 0);
5142           if (r_is_var)
5143             tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
5144                             tmp);
5145           gfc_add_expr_to_block (&lse->post, tmp);
5146         }
5147
5148       gfc_add_block_to_block (&block, &rse->pre);
5149       gfc_add_block_to_block (&block, &lse->pre);
5150
5151       gfc_add_modify (&block, lse->expr,
5152                            fold_convert (TREE_TYPE (lse->expr), rse->expr));
5153
5154       /* Do a deep copy if the rhs is a variable, if it is not the
5155          same as the lhs.  */
5156       if (r_is_var)
5157         {
5158           tmp = gfc_copy_alloc_comp (ts.u.derived, rse->expr, lse->expr, 0);
5159           tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
5160                           tmp);
5161           gfc_add_expr_to_block (&block, tmp);
5162         }
5163     }
5164   else if (ts.type == BT_DERIVED || ts.type == BT_CLASS)
5165     {
5166       gfc_add_block_to_block (&block, &lse->pre);
5167       gfc_add_block_to_block (&block, &rse->pre);
5168       tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
5169                              TREE_TYPE (lse->expr), rse->expr);
5170       gfc_add_modify (&block, lse->expr, tmp);
5171     }
5172   else
5173     {
5174       gfc_add_block_to_block (&block, &lse->pre);
5175       gfc_add_block_to_block (&block, &rse->pre);
5176
5177       gfc_add_modify (&block, lse->expr,
5178                       fold_convert (TREE_TYPE (lse->expr), rse->expr));
5179     }
5180
5181   gfc_add_block_to_block (&block, &lse->post);
5182   gfc_add_block_to_block (&block, &rse->post);
5183
5184   return gfc_finish_block (&block);
5185 }
5186
5187
5188 /* There are quite a lot of restrictions on the optimisation in using an
5189    array function assign without a temporary.  */
5190
5191 static bool
5192 arrayfunc_assign_needs_temporary (gfc_expr * expr1, gfc_expr * expr2)
5193 {
5194   gfc_ref * ref;
5195   bool seen_array_ref;
5196   bool c = false;
5197   gfc_symbol *sym = expr1->symtree->n.sym;
5198
5199   /* The caller has already checked rank>0 and expr_type == EXPR_FUNCTION.  */
5200   if (expr2->value.function.isym && !gfc_is_intrinsic_libcall (expr2))
5201     return true;
5202
5203   /* Elemental functions are scalarized so that they don't need a
5204      temporary in gfc_trans_assignment_1, so return a true.  Otherwise,
5205      they would need special treatment in gfc_trans_arrayfunc_assign.  */
5206   if (expr2->value.function.esym != NULL
5207       && expr2->value.function.esym->attr.elemental)
5208     return true;
5209
5210   /* Need a temporary if rhs is not FULL or a contiguous section.  */
5211   if (expr1->ref && !(gfc_full_array_ref_p (expr1->ref, &c) || c))
5212     return true;
5213
5214   /* Need a temporary if EXPR1 can't be expressed as a descriptor.  */
5215   if (gfc_ref_needs_temporary_p (expr1->ref))
5216     return true;
5217
5218   /* Functions returning pointers need temporaries.  */
5219   if (expr2->symtree->n.sym->attr.pointer 
5220       || expr2->symtree->n.sym->attr.allocatable)
5221     return true;
5222
5223   /* Character array functions need temporaries unless the
5224      character lengths are the same.  */
5225   if (expr2->ts.type == BT_CHARACTER && expr2->rank > 0)
5226     {
5227       if (expr1->ts.u.cl->length == NULL
5228             || expr1->ts.u.cl->length->expr_type != EXPR_CONSTANT)
5229         return true;
5230
5231       if (expr2->ts.u.cl->length == NULL
5232             || expr2->ts.u.cl->length->expr_type != EXPR_CONSTANT)
5233         return true;
5234
5235       if (mpz_cmp (expr1->ts.u.cl->length->value.integer,
5236                      expr2->ts.u.cl->length->value.integer) != 0)
5237         return true;
5238     }
5239
5240   /* Check that no LHS component references appear during an array
5241      reference. This is needed because we do not have the means to
5242      span any arbitrary stride with an array descriptor. This check
5243      is not needed for the rhs because the function result has to be
5244      a complete type.  */
5245   seen_array_ref = false;
5246   for (ref = expr1->ref; ref; ref = ref->next)
5247     {
5248       if (ref->type == REF_ARRAY)
5249         seen_array_ref= true;
5250       else if (ref->type == REF_COMPONENT && seen_array_ref)
5251         return true;
5252     }
5253
5254   /* Check for a dependency.  */
5255   if (gfc_check_fncall_dependency (expr1, INTENT_OUT,
5256                                    expr2->value.function.esym,
5257                                    expr2->value.function.actual,
5258                                    NOT_ELEMENTAL))
5259     return true;
5260
5261   /* If we have reached here with an intrinsic function, we do not
5262      need a temporary.  */
5263   if (expr2->value.function.isym)
5264     return false;
5265
5266   /* If the LHS is a dummy, we need a temporary if it is not
5267      INTENT(OUT).  */
5268   if (sym->attr.dummy && sym->attr.intent != INTENT_OUT)
5269     return true;
5270
5271   /* A PURE function can unconditionally be called without a temporary.  */
5272   if (expr2->value.function.esym != NULL
5273       && expr2->value.function.esym->attr.pure)
5274     return false;
5275
5276   /* TODO a function that could correctly be declared PURE but is not
5277      could do with returning false as well.  */
5278
5279   if (!sym->attr.use_assoc
5280         && !sym->attr.in_common
5281         && !sym->attr.pointer
5282         && !sym->attr.target
5283         && expr2->value.function.esym)
5284     {
5285       /* A temporary is not needed if the function is not contained and
5286          the variable is local or host associated and not a pointer or
5287          a target. */
5288       if (!expr2->value.function.esym->attr.contained)
5289         return false;
5290
5291       /* A temporary is not needed if the lhs has never been host
5292          associated and the procedure is contained.  */
5293       else if (!sym->attr.host_assoc)
5294         return false;
5295
5296       /* A temporary is not needed if the variable is local and not
5297          a pointer, a target or a result.  */
5298       if (sym->ns->parent
5299             && expr2->value.function.esym->ns == sym->ns->parent)
5300         return false;
5301     }
5302
5303   /* Default to temporary use.  */
5304   return true;
5305 }
5306
5307
5308 /* Try to translate array(:) = func (...), where func is a transformational
5309    array function, without using a temporary.  Returns NULL if this isn't the
5310    case.  */
5311
5312 static tree
5313 gfc_trans_arrayfunc_assign (gfc_expr * expr1, gfc_expr * expr2)
5314 {
5315   gfc_se se;
5316   gfc_ss *ss;
5317   gfc_component *comp = NULL;
5318
5319   if (arrayfunc_assign_needs_temporary (expr1, expr2))
5320     return NULL;
5321
5322   /* The frontend doesn't seem to bother filling in expr->symtree for intrinsic
5323      functions.  */
5324   gcc_assert (expr2->value.function.isym
5325               || (gfc_is_proc_ptr_comp (expr2, &comp)
5326                   && comp && comp->attr.dimension)
5327               || (!comp && gfc_return_by_reference (expr2->value.function.esym)
5328                   && expr2->value.function.esym->result->attr.dimension));
5329
5330   ss = gfc_walk_expr (expr1);
5331   gcc_assert (ss != gfc_ss_terminator);
5332   gfc_init_se (&se, NULL);
5333   gfc_start_block (&se.pre);
5334   se.want_pointer = 1;
5335
5336   gfc_conv_array_parameter (&se, expr1, ss, false, NULL, NULL, NULL);
5337
5338   if (expr1->ts.type == BT_DERIVED
5339         && expr1->ts.u.derived->attr.alloc_comp)
5340     {
5341       tree tmp;
5342       tmp = gfc_deallocate_alloc_comp (expr1->ts.u.derived, se.expr,
5343                                        expr1->rank);
5344       gfc_add_expr_to_block (&se.pre, tmp);
5345     }
5346
5347   se.direct_byref = 1;
5348   se.ss = gfc_walk_expr (expr2);
5349   gcc_assert (se.ss != gfc_ss_terminator);
5350   gfc_conv_function_expr (&se, expr2);
5351   gfc_add_block_to_block (&se.pre, &se.post);
5352
5353   return gfc_finish_block (&se.pre);
5354 }
5355
5356
5357 /* Try to efficiently translate array(:) = 0.  Return NULL if this
5358    can't be done.  */
5359
5360 static tree
5361 gfc_trans_zero_assign (gfc_expr * expr)
5362 {
5363   tree dest, len, type;
5364   tree tmp;
5365   gfc_symbol *sym;
5366
5367   sym = expr->symtree->n.sym;
5368   dest = gfc_get_symbol_decl (sym);
5369
5370   type = TREE_TYPE (dest);
5371   if (POINTER_TYPE_P (type))
5372     type = TREE_TYPE (type);
5373   if (!GFC_ARRAY_TYPE_P (type))
5374     return NULL_TREE;
5375
5376   /* Determine the length of the array.  */
5377   len = GFC_TYPE_ARRAY_SIZE (type);
5378   if (!len || TREE_CODE (len) != INTEGER_CST)
5379     return NULL_TREE;
5380
5381   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
5382   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
5383                          fold_convert (gfc_array_index_type, tmp));
5384
5385   /* If we are zeroing a local array avoid taking its address by emitting
5386      a = {} instead.  */
5387   if (!POINTER_TYPE_P (TREE_TYPE (dest)))
5388     return build2_loc (input_location, MODIFY_EXPR, void_type_node,
5389                        dest, build_constructor (TREE_TYPE (dest), NULL));
5390
5391   /* Convert arguments to the correct types.  */
5392   dest = fold_convert (pvoid_type_node, dest);
5393   len = fold_convert (size_type_node, len);
5394
5395   /* Construct call to __builtin_memset.  */
5396   tmp = build_call_expr_loc (input_location,
5397                          built_in_decls[BUILT_IN_MEMSET],
5398                          3, dest, integer_zero_node, len);
5399   return fold_convert (void_type_node, tmp);
5400 }
5401
5402
5403 /* Helper for gfc_trans_array_copy and gfc_trans_array_constructor_copy
5404    that constructs the call to __builtin_memcpy.  */
5405
5406 tree
5407 gfc_build_memcpy_call (tree dst, tree src, tree len)
5408 {
5409   tree tmp;
5410
5411   /* Convert arguments to the correct types.  */
5412   if (!POINTER_TYPE_P (TREE_TYPE (dst)))
5413     dst = gfc_build_addr_expr (pvoid_type_node, dst);
5414   else
5415     dst = fold_convert (pvoid_type_node, dst);
5416
5417   if (!POINTER_TYPE_P (TREE_TYPE (src)))
5418     src = gfc_build_addr_expr (pvoid_type_node, src);
5419   else
5420     src = fold_convert (pvoid_type_node, src);
5421
5422   len = fold_convert (size_type_node, len);
5423
5424   /* Construct call to __builtin_memcpy.  */
5425   tmp = build_call_expr_loc (input_location,
5426                          built_in_decls[BUILT_IN_MEMCPY], 3, dst, src, len);
5427   return fold_convert (void_type_node, tmp);
5428 }
5429
5430
5431 /* Try to efficiently translate dst(:) = src(:).  Return NULL if this
5432    can't be done.  EXPR1 is the destination/lhs and EXPR2 is the
5433    source/rhs, both are gfc_full_array_ref_p which have been checked for
5434    dependencies.  */
5435
5436 static tree
5437 gfc_trans_array_copy (gfc_expr * expr1, gfc_expr * expr2)
5438 {
5439   tree dst, dlen, dtype;
5440   tree src, slen, stype;
5441   tree tmp;
5442
5443   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
5444   src = gfc_get_symbol_decl (expr2->symtree->n.sym);
5445
5446   dtype = TREE_TYPE (dst);
5447   if (POINTER_TYPE_P (dtype))
5448     dtype = TREE_TYPE (dtype);
5449   stype = TREE_TYPE (src);
5450   if (POINTER_TYPE_P (stype))
5451     stype = TREE_TYPE (stype);
5452
5453   if (!GFC_ARRAY_TYPE_P (dtype) || !GFC_ARRAY_TYPE_P (stype))
5454     return NULL_TREE;
5455
5456   /* Determine the lengths of the arrays.  */
5457   dlen = GFC_TYPE_ARRAY_SIZE (dtype);
5458   if (!dlen || TREE_CODE (dlen) != INTEGER_CST)
5459     return NULL_TREE;
5460   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
5461   dlen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
5462                           dlen, fold_convert (gfc_array_index_type, tmp));
5463
5464   slen = GFC_TYPE_ARRAY_SIZE (stype);
5465   if (!slen || TREE_CODE (slen) != INTEGER_CST)
5466     return NULL_TREE;
5467   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (stype));
5468   slen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
5469                           slen, fold_convert (gfc_array_index_type, tmp));
5470
5471   /* Sanity check that they are the same.  This should always be
5472      the case, as we should already have checked for conformance.  */
5473   if (!tree_int_cst_equal (slen, dlen))
5474     return NULL_TREE;
5475
5476   return gfc_build_memcpy_call (dst, src, dlen);
5477 }
5478
5479
5480 /* Try to efficiently translate array(:) = (/ ... /).  Return NULL if
5481    this can't be done.  EXPR1 is the destination/lhs for which
5482    gfc_full_array_ref_p is true, and EXPR2 is the source/rhs.  */
5483
5484 static tree
5485 gfc_trans_array_constructor_copy (gfc_expr * expr1, gfc_expr * expr2)
5486 {
5487   unsigned HOST_WIDE_INT nelem;
5488   tree dst, dtype;
5489   tree src, stype;
5490   tree len;
5491   tree tmp;
5492
5493   nelem = gfc_constant_array_constructor_p (expr2->value.constructor);
5494   if (nelem == 0)
5495     return NULL_TREE;
5496
5497   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
5498   dtype = TREE_TYPE (dst);
5499   if (POINTER_TYPE_P (dtype))
5500     dtype = TREE_TYPE (dtype);
5501   if (!GFC_ARRAY_TYPE_P (dtype))
5502     return NULL_TREE;
5503
5504   /* Determine the lengths of the array.  */
5505   len = GFC_TYPE_ARRAY_SIZE (dtype);
5506   if (!len || TREE_CODE (len) != INTEGER_CST)
5507     return NULL_TREE;
5508
5509   /* Confirm that the constructor is the same size.  */
5510   if (compare_tree_int (len, nelem) != 0)
5511     return NULL_TREE;
5512
5513   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
5514   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
5515                          fold_convert (gfc_array_index_type, tmp));
5516
5517   stype = gfc_typenode_for_spec (&expr2->ts);
5518   src = gfc_build_constant_array_constructor (expr2, stype);
5519
5520   stype = TREE_TYPE (src);
5521   if (POINTER_TYPE_P (stype))
5522     stype = TREE_TYPE (stype);
5523
5524   return gfc_build_memcpy_call (dst, src, len);
5525 }
5526
5527
5528 /* Tells whether the expression is to be treated as a variable reference.  */
5529
5530 static bool
5531 expr_is_variable (gfc_expr *expr)
5532 {
5533   gfc_expr *arg;
5534
5535   if (expr->expr_type == EXPR_VARIABLE)
5536     return true;
5537
5538   arg = gfc_get_noncopying_intrinsic_argument (expr);
5539   if (arg)
5540     {
5541       gcc_assert (expr->value.function.isym->id == GFC_ISYM_TRANSPOSE);
5542       return expr_is_variable (arg);
5543     }
5544
5545   return false;
5546 }
5547
5548
5549 /* Subroutine of gfc_trans_assignment that actually scalarizes the
5550    assignment.  EXPR1 is the destination/LHS and EXPR2 is the source/RHS.
5551    init_flag indicates initialization expressions and dealloc that no
5552    deallocate prior assignment is needed (if in doubt, set true).  */
5553
5554 static tree
5555 gfc_trans_assignment_1 (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
5556                         bool dealloc)
5557 {
5558   gfc_se lse;
5559   gfc_se rse;
5560   gfc_ss *lss;
5561   gfc_ss *lss_section;
5562   gfc_ss *rss;
5563   gfc_loopinfo loop;
5564   tree tmp;
5565   stmtblock_t block;
5566   stmtblock_t body;
5567   bool l_is_temp;
5568   bool scalar_to_array;
5569   tree string_length;
5570   int n;
5571
5572   /* Assignment of the form lhs = rhs.  */
5573   gfc_start_block (&block);
5574
5575   gfc_init_se (&lse, NULL);
5576   gfc_init_se (&rse, NULL);
5577
5578   /* Walk the lhs.  */
5579   lss = gfc_walk_expr (expr1);
5580   rss = NULL;
5581   if (lss != gfc_ss_terminator)
5582     {
5583       /* Allow the scalarizer to workshare array assignments.  */
5584       if (ompws_flags & OMPWS_WORKSHARE_FLAG)
5585         ompws_flags |= OMPWS_SCALARIZER_WS;
5586
5587       /* The assignment needs scalarization.  */
5588       lss_section = lss;
5589
5590       /* Find a non-scalar SS from the lhs.  */
5591       while (lss_section != gfc_ss_terminator
5592              && lss_section->type != GFC_SS_SECTION)
5593         lss_section = lss_section->next;
5594
5595       gcc_assert (lss_section != gfc_ss_terminator);
5596
5597       /* Initialize the scalarizer.  */
5598       gfc_init_loopinfo (&loop);
5599
5600       /* Walk the rhs.  */
5601       rss = gfc_walk_expr (expr2);
5602       if (rss == gfc_ss_terminator)
5603         {
5604           /* The rhs is scalar.  Add a ss for the expression.  */
5605           rss = gfc_get_ss ();
5606           rss->next = gfc_ss_terminator;
5607           rss->type = GFC_SS_SCALAR;
5608           rss->expr = expr2;
5609         }
5610       /* Associate the SS with the loop.  */
5611       gfc_add_ss_to_loop (&loop, lss);
5612       gfc_add_ss_to_loop (&loop, rss);
5613
5614       /* Calculate the bounds of the scalarization.  */
5615       gfc_conv_ss_startstride (&loop);
5616       /* Enable loop reversal.  */
5617       for (n = 0; n < loop.dimen; n++)
5618         loop.reverse[n] = GFC_REVERSE_NOT_SET;
5619       /* Resolve any data dependencies in the statement.  */
5620       gfc_conv_resolve_dependencies (&loop, lss, rss);
5621       /* Setup the scalarizing loops.  */
5622       gfc_conv_loop_setup (&loop, &expr2->where);
5623
5624       /* Setup the gfc_se structures.  */
5625       gfc_copy_loopinfo_to_se (&lse, &loop);
5626       gfc_copy_loopinfo_to_se (&rse, &loop);
5627
5628       rse.ss = rss;
5629       gfc_mark_ss_chain_used (rss, 1);
5630       if (loop.temp_ss == NULL)
5631         {
5632           lse.ss = lss;
5633           gfc_mark_ss_chain_used (lss, 1);
5634         }
5635       else
5636         {
5637           lse.ss = loop.temp_ss;
5638           gfc_mark_ss_chain_used (lss, 3);
5639           gfc_mark_ss_chain_used (loop.temp_ss, 3);
5640         }
5641
5642       /* Start the scalarized loop body.  */
5643       gfc_start_scalarized_body (&loop, &body);
5644     }
5645   else
5646     gfc_init_block (&body);
5647
5648   l_is_temp = (lss != gfc_ss_terminator && loop.temp_ss != NULL);
5649
5650   /* Translate the expression.  */
5651   gfc_conv_expr (&rse, expr2);
5652
5653   /* Stabilize a string length for temporaries.  */
5654   if (expr2->ts.type == BT_CHARACTER)
5655     string_length = gfc_evaluate_now (rse.string_length, &rse.pre);
5656   else
5657     string_length = NULL_TREE;
5658
5659   if (l_is_temp)
5660     {
5661       gfc_conv_tmp_array_ref (&lse);
5662       gfc_advance_se_ss_chain (&lse);
5663       if (expr2->ts.type == BT_CHARACTER)
5664         lse.string_length = string_length;
5665     }
5666   else
5667     gfc_conv_expr (&lse, expr1);
5668
5669   /* Assignments of scalar derived types with allocatable components
5670      to arrays must be done with a deep copy and the rhs temporary
5671      must have its components deallocated afterwards.  */
5672   scalar_to_array = (expr2->ts.type == BT_DERIVED
5673                        && expr2->ts.u.derived->attr.alloc_comp
5674                        && !expr_is_variable (expr2)
5675                        && !gfc_is_constant_expr (expr2)
5676                        && expr1->rank && !expr2->rank);
5677   if (scalar_to_array && dealloc)
5678     {
5679       tmp = gfc_deallocate_alloc_comp (expr2->ts.u.derived, rse.expr, 0);
5680       gfc_add_expr_to_block (&loop.post, tmp);
5681     }
5682
5683   tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
5684                                  l_is_temp || init_flag,
5685                                  expr_is_variable (expr2) || scalar_to_array,
5686                                  dealloc);
5687   gfc_add_expr_to_block (&body, tmp);
5688
5689   if (lss == gfc_ss_terminator)
5690     {
5691       /* Use the scalar assignment as is.  */
5692       gfc_add_block_to_block (&block, &body);
5693     }
5694   else
5695     {
5696       gcc_assert (lse.ss == gfc_ss_terminator
5697                   && rse.ss == gfc_ss_terminator);
5698
5699       if (l_is_temp)
5700         {
5701           gfc_trans_scalarized_loop_boundary (&loop, &body);
5702
5703           /* We need to copy the temporary to the actual lhs.  */
5704           gfc_init_se (&lse, NULL);
5705           gfc_init_se (&rse, NULL);
5706           gfc_copy_loopinfo_to_se (&lse, &loop);
5707           gfc_copy_loopinfo_to_se (&rse, &loop);
5708
5709           rse.ss = loop.temp_ss;
5710           lse.ss = lss;
5711
5712           gfc_conv_tmp_array_ref (&rse);
5713           gfc_advance_se_ss_chain (&rse);
5714           gfc_conv_expr (&lse, expr1);
5715
5716           gcc_assert (lse.ss == gfc_ss_terminator
5717                       && rse.ss == gfc_ss_terminator);
5718
5719           if (expr2->ts.type == BT_CHARACTER)
5720             rse.string_length = string_length;
5721
5722           tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
5723                                          false, false, dealloc);
5724           gfc_add_expr_to_block (&body, tmp);
5725         }
5726
5727       /* Generate the copying loops.  */
5728       gfc_trans_scalarizing_loops (&loop, &body);
5729
5730       /* Wrap the whole thing up.  */
5731       gfc_add_block_to_block (&block, &loop.pre);
5732       gfc_add_block_to_block (&block, &loop.post);
5733
5734       gfc_cleanup_loop (&loop);
5735     }
5736
5737   return gfc_finish_block (&block);
5738 }
5739
5740
5741 /* Check whether EXPR is a copyable array.  */
5742
5743 static bool
5744 copyable_array_p (gfc_expr * expr)
5745 {
5746   if (expr->expr_type != EXPR_VARIABLE)
5747     return false;
5748
5749   /* First check it's an array.  */
5750   if (expr->rank < 1 || !expr->ref || expr->ref->next)
5751     return false;
5752
5753   if (!gfc_full_array_ref_p (expr->ref, NULL))
5754     return false;
5755
5756   /* Next check that it's of a simple enough type.  */
5757   switch (expr->ts.type)
5758     {
5759     case BT_INTEGER:
5760     case BT_REAL:
5761     case BT_COMPLEX:
5762     case BT_LOGICAL:
5763       return true;
5764
5765     case BT_CHARACTER:
5766       return false;
5767
5768     case BT_DERIVED:
5769       return !expr->ts.u.derived->attr.alloc_comp;
5770
5771     default:
5772       break;
5773     }
5774
5775   return false;
5776 }
5777
5778 /* Translate an assignment.  */
5779
5780 tree
5781 gfc_trans_assignment (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
5782                       bool dealloc)
5783 {
5784   tree tmp;
5785
5786   /* Special case a single function returning an array.  */
5787   if (expr2->expr_type == EXPR_FUNCTION && expr2->rank > 0)
5788     {
5789       tmp = gfc_trans_arrayfunc_assign (expr1, expr2);
5790       if (tmp)
5791         return tmp;
5792     }
5793
5794   /* Special case assigning an array to zero.  */
5795   if (copyable_array_p (expr1)
5796       && is_zero_initializer_p (expr2))
5797     {
5798       tmp = gfc_trans_zero_assign (expr1);
5799       if (tmp)
5800         return tmp;
5801     }
5802
5803   /* Special case copying one array to another.  */
5804   if (copyable_array_p (expr1)
5805       && copyable_array_p (expr2)
5806       && gfc_compare_types (&expr1->ts, &expr2->ts)
5807       && !gfc_check_dependency (expr1, expr2, 0))
5808     {
5809       tmp = gfc_trans_array_copy (expr1, expr2);
5810       if (tmp)
5811         return tmp;
5812     }
5813
5814   /* Special case initializing an array from a constant array constructor.  */
5815   if (copyable_array_p (expr1)
5816       && expr2->expr_type == EXPR_ARRAY
5817       && gfc_compare_types (&expr1->ts, &expr2->ts))
5818     {
5819       tmp = gfc_trans_array_constructor_copy (expr1, expr2);
5820       if (tmp)
5821         return tmp;
5822     }
5823
5824   /* Fallback to the scalarizer to generate explicit loops.  */
5825   return gfc_trans_assignment_1 (expr1, expr2, init_flag, dealloc);
5826 }
5827
5828 tree
5829 gfc_trans_init_assign (gfc_code * code)
5830 {
5831   return gfc_trans_assignment (code->expr1, code->expr2, true, false);
5832 }
5833
5834 tree
5835 gfc_trans_assign (gfc_code * code)
5836 {
5837   return gfc_trans_assignment (code->expr1, code->expr2, false, true);
5838 }
5839
5840
5841 /* Special case for initializing a polymorphic dummy with INTENT(OUT).
5842    A MEMCPY is needed to copy the full data from the default initializer
5843    of the dynamic type.  */
5844
5845 tree
5846 gfc_trans_class_init_assign (gfc_code *code)
5847 {
5848   stmtblock_t block;
5849   tree tmp;
5850   gfc_se dst,src,memsz;
5851   gfc_expr *lhs,*rhs,*sz;
5852
5853   gfc_start_block (&block);
5854
5855   lhs = gfc_copy_expr (code->expr1);
5856   gfc_add_component_ref (lhs, "$data");
5857
5858   rhs = gfc_copy_expr (code->expr1);
5859   gfc_add_component_ref (rhs, "$vptr");
5860   gfc_add_component_ref (rhs, "$def_init");
5861
5862   sz = gfc_copy_expr (code->expr1);
5863   gfc_add_component_ref (sz, "$vptr");
5864   gfc_add_component_ref (sz, "$size");
5865
5866   gfc_init_se (&dst, NULL);
5867   gfc_init_se (&src, NULL);
5868   gfc_init_se (&memsz, NULL);
5869   gfc_conv_expr (&dst, lhs);
5870   gfc_conv_expr (&src, rhs);
5871   gfc_conv_expr (&memsz, sz);
5872   gfc_add_block_to_block (&block, &src.pre);
5873   tmp = gfc_build_memcpy_call (dst.expr, src.expr, memsz.expr);
5874   gfc_add_expr_to_block (&block, tmp);
5875   
5876   return gfc_finish_block (&block);
5877 }
5878
5879
5880 /* Translate an assignment to a CLASS object
5881    (pointer or ordinary assignment).  */
5882
5883 tree
5884 gfc_trans_class_assign (gfc_expr *expr1, gfc_expr *expr2, gfc_exec_op op)
5885 {
5886   stmtblock_t block;
5887   tree tmp;
5888   gfc_expr *lhs;
5889   gfc_expr *rhs;
5890
5891   gfc_start_block (&block);
5892
5893   if (expr2->ts.type != BT_CLASS)
5894     {
5895       /* Insert an additional assignment which sets the '$vptr' field.  */
5896       lhs = gfc_copy_expr (expr1);
5897       gfc_add_component_ref (lhs, "$vptr");
5898       if (expr2->ts.type == BT_DERIVED)
5899         {
5900           gfc_symbol *vtab;
5901           gfc_symtree *st;
5902           vtab = gfc_find_derived_vtab (expr2->ts.u.derived);
5903           gcc_assert (vtab);
5904           rhs = gfc_get_expr ();
5905           rhs->expr_type = EXPR_VARIABLE;
5906           gfc_find_sym_tree (vtab->name, NULL, 1, &st);
5907           rhs->symtree = st;
5908           rhs->ts = vtab->ts;
5909         }
5910       else if (expr2->expr_type == EXPR_NULL)
5911         rhs = gfc_get_int_expr (gfc_default_integer_kind, NULL, 0);
5912       else
5913         gcc_unreachable ();
5914
5915       tmp = gfc_trans_pointer_assignment (lhs, rhs);
5916       gfc_add_expr_to_block (&block, tmp);
5917
5918       gfc_free_expr (lhs);
5919       gfc_free_expr (rhs);
5920     }
5921
5922   /* Do the actual CLASS assignment.  */
5923   if (expr2->ts.type == BT_CLASS)
5924     op = EXEC_ASSIGN;
5925   else
5926     gfc_add_component_ref (expr1, "$data");
5927
5928   if (op == EXEC_ASSIGN)
5929     tmp = gfc_trans_assignment (expr1, expr2, false, true);
5930   else if (op == EXEC_POINTER_ASSIGN)
5931     tmp = gfc_trans_pointer_assignment (expr1, expr2);
5932   else
5933     gcc_unreachable();
5934
5935   gfc_add_expr_to_block (&block, tmp);
5936
5937   return gfc_finish_block (&block);
5938 }