re PR fortran/87397 (Clobbering intent(out) variables caused regression in OpenCoarra...
[platform/upstream/gcc.git] / gcc / fortran / trans-expr.c
1 /* Expression translation
2    Copyright (C) 2002-2018 Free Software Foundation, Inc.
3    Contributed by Paul Brook <paul@nowt.org>
4    and Steven Bosscher <s.bosscher@student.tudelft.nl>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* trans-expr.c-- generate GENERIC trees for gfc_expr.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "options.h"
28 #include "tree.h"
29 #include "gfortran.h"
30 #include "trans.h"
31 #include "stringpool.h"
32 #include "diagnostic-core.h"    /* For fatal_error.  */
33 #include "fold-const.h"
34 #include "langhooks.h"
35 #include "arith.h"
36 #include "constructor.h"
37 #include "trans-const.h"
38 #include "trans-types.h"
39 #include "trans-array.h"
40 /* Only for gfc_trans_assign and gfc_trans_pointer_assign.  */
41 #include "trans-stmt.h"
42 #include "dependency.h"
43 #include "gimplify.h"
44
45 /* Convert a scalar to an array descriptor. To be used for assumed-rank
46    arrays.  */
47
48 static tree
49 get_scalar_to_descriptor_type (tree scalar, symbol_attribute attr)
50 {
51   enum gfc_array_kind akind;
52
53   if (attr.pointer)
54     akind = GFC_ARRAY_POINTER_CONT;
55   else if (attr.allocatable)
56     akind = GFC_ARRAY_ALLOCATABLE;
57   else
58     akind = GFC_ARRAY_ASSUMED_SHAPE_CONT;
59
60   if (POINTER_TYPE_P (TREE_TYPE (scalar)))
61     scalar = TREE_TYPE (scalar);
62   return gfc_get_array_type_bounds (TREE_TYPE (scalar), 0, 0, NULL, NULL, 1,
63                                     akind, !(attr.pointer || attr.target));
64 }
65
66 tree
67 gfc_conv_scalar_to_descriptor (gfc_se *se, tree scalar, symbol_attribute attr)
68 {
69   tree desc, type, etype;
70
71   type = get_scalar_to_descriptor_type (scalar, attr);
72   etype = TREE_TYPE (scalar);
73   desc = gfc_create_var (type, "desc");
74   DECL_ARTIFICIAL (desc) = 1;
75
76   if (CONSTANT_CLASS_P (scalar))
77     {
78       tree tmp;
79       tmp = gfc_create_var (TREE_TYPE (scalar), "scalar");
80       gfc_add_modify (&se->pre, tmp, scalar);
81       scalar = tmp;
82     }
83   if (!POINTER_TYPE_P (TREE_TYPE (scalar)))
84     scalar = gfc_build_addr_expr (NULL_TREE, scalar);
85   else if (TREE_TYPE (etype) && TREE_CODE (TREE_TYPE (etype)) == ARRAY_TYPE)
86     etype = TREE_TYPE (etype);
87   gfc_add_modify (&se->pre, gfc_conv_descriptor_dtype (desc),
88                   gfc_get_dtype_rank_type (0, etype));
89   gfc_conv_descriptor_data_set (&se->pre, desc, scalar);
90
91   /* Copy pointer address back - but only if it could have changed and
92      if the actual argument is a pointer and not, e.g., NULL().  */
93   if ((attr.pointer || attr.allocatable) && attr.intent != INTENT_IN)
94     gfc_add_modify (&se->post, scalar,
95                     fold_convert (TREE_TYPE (scalar),
96                                   gfc_conv_descriptor_data_get (desc)));
97   return desc;
98 }
99
100
101 /* Get the coarray token from the ultimate array or component ref.
102    Returns a NULL_TREE, when the ref object is not allocatable or pointer.  */
103
104 tree
105 gfc_get_ultimate_alloc_ptr_comps_caf_token (gfc_se *outerse, gfc_expr *expr)
106 {
107   gfc_symbol *sym = expr->symtree->n.sym;
108   bool is_coarray = sym->attr.codimension;
109   gfc_expr *caf_expr = gfc_copy_expr (expr);
110   gfc_ref *ref = caf_expr->ref, *last_caf_ref = NULL;
111
112   while (ref)
113     {
114       if (ref->type == REF_COMPONENT
115           && (ref->u.c.component->attr.allocatable
116               || ref->u.c.component->attr.pointer)
117           && (is_coarray || ref->u.c.component->attr.codimension))
118           last_caf_ref = ref;
119       ref = ref->next;
120     }
121
122   if (last_caf_ref == NULL)
123     return NULL_TREE;
124
125   tree comp = last_caf_ref->u.c.component->caf_token, caf;
126   gfc_se se;
127   bool comp_ref = !last_caf_ref->u.c.component->attr.dimension;
128   if (comp == NULL_TREE && comp_ref)
129     return NULL_TREE;
130   gfc_init_se (&se, outerse);
131   gfc_free_ref_list (last_caf_ref->next);
132   last_caf_ref->next = NULL;
133   caf_expr->rank = comp_ref ? 0 : last_caf_ref->u.c.component->as->rank;
134   se.want_pointer = comp_ref;
135   gfc_conv_expr (&se, caf_expr);
136   gfc_add_block_to_block (&outerse->pre, &se.pre);
137
138   if (TREE_CODE (se.expr) == COMPONENT_REF && comp_ref)
139     se.expr = TREE_OPERAND (se.expr, 0);
140   gfc_free_expr (caf_expr);
141
142   if (comp_ref)
143     caf = fold_build3_loc (input_location, COMPONENT_REF,
144                            TREE_TYPE (comp), se.expr, comp, NULL_TREE);
145   else
146     caf = gfc_conv_descriptor_token (se.expr);
147   return gfc_build_addr_expr (NULL_TREE, caf);
148 }
149
150
151 /* This is the seed for an eventual trans-class.c
152
153    The following parameters should not be used directly since they might
154    in future implementations.  Use the corresponding APIs.  */
155 #define CLASS_DATA_FIELD 0
156 #define CLASS_VPTR_FIELD 1
157 #define CLASS_LEN_FIELD 2
158 #define VTABLE_HASH_FIELD 0
159 #define VTABLE_SIZE_FIELD 1
160 #define VTABLE_EXTENDS_FIELD 2
161 #define VTABLE_DEF_INIT_FIELD 3
162 #define VTABLE_COPY_FIELD 4
163 #define VTABLE_FINAL_FIELD 5
164 #define VTABLE_DEALLOCATE_FIELD 6
165
166
167 tree
168 gfc_class_set_static_fields (tree decl, tree vptr, tree data)
169 {
170   tree tmp;
171   tree field;
172   vec<constructor_elt, va_gc> *init = NULL;
173
174   field = TYPE_FIELDS (TREE_TYPE (decl));
175   tmp = gfc_advance_chain (field, CLASS_DATA_FIELD);
176   CONSTRUCTOR_APPEND_ELT (init, tmp, data);
177
178   tmp = gfc_advance_chain (field, CLASS_VPTR_FIELD);
179   CONSTRUCTOR_APPEND_ELT (init, tmp, vptr);
180
181   return build_constructor (TREE_TYPE (decl), init);
182 }
183
184
185 tree
186 gfc_class_data_get (tree decl)
187 {
188   tree data;
189   if (POINTER_TYPE_P (TREE_TYPE (decl)))
190     decl = build_fold_indirect_ref_loc (input_location, decl);
191   data = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
192                             CLASS_DATA_FIELD);
193   return fold_build3_loc (input_location, COMPONENT_REF,
194                           TREE_TYPE (data), decl, data,
195                           NULL_TREE);
196 }
197
198
199 tree
200 gfc_class_vptr_get (tree decl)
201 {
202   tree vptr;
203   /* For class arrays decl may be a temporary descriptor handle, the vptr is
204      then available through the saved descriptor.  */
205   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
206       && GFC_DECL_SAVED_DESCRIPTOR (decl))
207     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
208   if (POINTER_TYPE_P (TREE_TYPE (decl)))
209     decl = build_fold_indirect_ref_loc (input_location, decl);
210   vptr = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
211                             CLASS_VPTR_FIELD);
212   return fold_build3_loc (input_location, COMPONENT_REF,
213                           TREE_TYPE (vptr), decl, vptr,
214                           NULL_TREE);
215 }
216
217
218 tree
219 gfc_class_len_get (tree decl)
220 {
221   tree len;
222   /* For class arrays decl may be a temporary descriptor handle, the len is
223      then available through the saved descriptor.  */
224   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
225       && GFC_DECL_SAVED_DESCRIPTOR (decl))
226     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
227   if (POINTER_TYPE_P (TREE_TYPE (decl)))
228     decl = build_fold_indirect_ref_loc (input_location, decl);
229   len = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
230                            CLASS_LEN_FIELD);
231   return fold_build3_loc (input_location, COMPONENT_REF,
232                           TREE_TYPE (len), decl, len,
233                           NULL_TREE);
234 }
235
236
237 /* Try to get the _len component of a class.  When the class is not unlimited
238    poly, i.e. no _len field exists, then return a zero node.  */
239
240 tree
241 gfc_class_len_or_zero_get (tree decl)
242 {
243   tree len;
244   /* For class arrays decl may be a temporary descriptor handle, the vptr is
245      then available through the saved descriptor.  */
246   if (VAR_P (decl) && DECL_LANG_SPECIFIC (decl)
247       && GFC_DECL_SAVED_DESCRIPTOR (decl))
248     decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
249   if (POINTER_TYPE_P (TREE_TYPE (decl)))
250     decl = build_fold_indirect_ref_loc (input_location, decl);
251   len = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (decl)),
252                            CLASS_LEN_FIELD);
253   return len != NULL_TREE ? fold_build3_loc (input_location, COMPONENT_REF,
254                                              TREE_TYPE (len), decl, len,
255                                              NULL_TREE)
256     : build_zero_cst (gfc_charlen_type_node);
257 }
258
259
260 /* Get the specified FIELD from the VPTR.  */
261
262 static tree
263 vptr_field_get (tree vptr, int fieldno)
264 {
265   tree field;
266   vptr = build_fold_indirect_ref_loc (input_location, vptr);
267   field = gfc_advance_chain (TYPE_FIELDS (TREE_TYPE (vptr)),
268                              fieldno);
269   field = fold_build3_loc (input_location, COMPONENT_REF,
270                            TREE_TYPE (field), vptr, field,
271                            NULL_TREE);
272   gcc_assert (field);
273   return field;
274 }
275
276
277 /* Get the field from the class' vptr.  */
278
279 static tree
280 class_vtab_field_get (tree decl, int fieldno)
281 {
282   tree vptr;
283   vptr = gfc_class_vptr_get (decl);
284   return vptr_field_get (vptr, fieldno);
285 }
286
287
288 /* Define a macro for creating the class_vtab_* and vptr_* accessors in
289    unison.  */
290 #define VTAB_GET_FIELD_GEN(name, field) tree \
291 gfc_class_vtab_## name ##_get (tree cl) \
292 { \
293   return class_vtab_field_get (cl, field); \
294 } \
295  \
296 tree \
297 gfc_vptr_## name ##_get (tree vptr) \
298 { \
299   return vptr_field_get (vptr, field); \
300 }
301
302 VTAB_GET_FIELD_GEN (hash, VTABLE_HASH_FIELD)
303 VTAB_GET_FIELD_GEN (extends, VTABLE_EXTENDS_FIELD)
304 VTAB_GET_FIELD_GEN (def_init, VTABLE_DEF_INIT_FIELD)
305 VTAB_GET_FIELD_GEN (copy, VTABLE_COPY_FIELD)
306 VTAB_GET_FIELD_GEN (final, VTABLE_FINAL_FIELD)
307 VTAB_GET_FIELD_GEN (deallocate, VTABLE_DEALLOCATE_FIELD)
308
309
310 /* The size field is returned as an array index type.  Therefore treat
311    it and only it specially.  */
312
313 tree
314 gfc_class_vtab_size_get (tree cl)
315 {
316   tree size;
317   size = class_vtab_field_get (cl, VTABLE_SIZE_FIELD);
318   /* Always return size as an array index type.  */
319   size = fold_convert (gfc_array_index_type, size);
320   gcc_assert (size);
321   return size;
322 }
323
324 tree
325 gfc_vptr_size_get (tree vptr)
326 {
327   tree size;
328   size = vptr_field_get (vptr, VTABLE_SIZE_FIELD);
329   /* Always return size as an array index type.  */
330   size = fold_convert (gfc_array_index_type, size);
331   gcc_assert (size);
332   return size;
333 }
334
335
336 #undef CLASS_DATA_FIELD
337 #undef CLASS_VPTR_FIELD
338 #undef CLASS_LEN_FIELD
339 #undef VTABLE_HASH_FIELD
340 #undef VTABLE_SIZE_FIELD
341 #undef VTABLE_EXTENDS_FIELD
342 #undef VTABLE_DEF_INIT_FIELD
343 #undef VTABLE_COPY_FIELD
344 #undef VTABLE_FINAL_FIELD
345
346
347 /* Search for the last _class ref in the chain of references of this
348    expression and cut the chain there.  Albeit this routine is similiar
349    to class.c::gfc_add_component_ref (), is there a significant
350    difference: gfc_add_component_ref () concentrates on an array ref to
351    be the last ref in the chain.  This routine is oblivious to the kind
352    of refs following.  */
353
354 gfc_expr *
355 gfc_find_and_cut_at_last_class_ref (gfc_expr *e)
356 {
357   gfc_expr *base_expr;
358   gfc_ref *ref, *class_ref, *tail = NULL, *array_ref;
359
360   /* Find the last class reference.  */
361   class_ref = NULL;
362   array_ref = NULL;
363   for (ref = e->ref; ref; ref = ref->next)
364     {
365       if (ref->type == REF_ARRAY && ref->u.ar.type != AR_ELEMENT)
366         array_ref = ref;
367
368       if (ref->type == REF_COMPONENT
369           && ref->u.c.component->ts.type == BT_CLASS)
370         {
371           /* Component to the right of a part reference with nonzero rank
372              must not have the ALLOCATABLE attribute.  If attempts are
373              made to reference such a component reference, an error results
374              followed by an ICE.  */
375           if (array_ref && CLASS_DATA (ref->u.c.component)->attr.allocatable)
376             return NULL;
377           class_ref = ref;
378         }
379
380       if (ref->next == NULL)
381         break;
382     }
383
384   /* Remove and store all subsequent references after the
385      CLASS reference.  */
386   if (class_ref)
387     {
388       tail = class_ref->next;
389       class_ref->next = NULL;
390     }
391   else if (e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
392     {
393       tail = e->ref;
394       e->ref = NULL;
395     }
396
397   base_expr = gfc_expr_to_initialize (e);
398
399   /* Restore the original tail expression.  */
400   if (class_ref)
401     {
402       gfc_free_ref_list (class_ref->next);
403       class_ref->next = tail;
404     }
405   else if (e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
406     {
407       gfc_free_ref_list (e->ref);
408       e->ref = tail;
409     }
410   return base_expr;
411 }
412
413
414 /* Reset the vptr to the declared type, e.g. after deallocation.  */
415
416 void
417 gfc_reset_vptr (stmtblock_t *block, gfc_expr *e)
418 {
419   gfc_symbol *vtab;
420   tree vptr;
421   tree vtable;
422   gfc_se se;
423
424   /* Evaluate the expression and obtain the vptr from it.  */
425   gfc_init_se (&se, NULL);
426   if (e->rank)
427     gfc_conv_expr_descriptor (&se, e);
428   else
429     gfc_conv_expr (&se, e);
430   gfc_add_block_to_block (block, &se.pre);
431   vptr = gfc_get_vptr_from_expr (se.expr);
432
433   /* If a vptr is not found, we can do nothing more.  */
434   if (vptr == NULL_TREE)
435     return;
436
437   if (UNLIMITED_POLY (e))
438     gfc_add_modify (block, vptr, build_int_cst (TREE_TYPE (vptr), 0));
439   else
440     {
441       /* Return the vptr to the address of the declared type.  */
442       vtab = gfc_find_derived_vtab (e->ts.u.derived);
443       vtable = vtab->backend_decl;
444       if (vtable == NULL_TREE)
445         vtable = gfc_get_symbol_decl (vtab);
446       vtable = gfc_build_addr_expr (NULL, vtable);
447       vtable = fold_convert (TREE_TYPE (vptr), vtable);
448       gfc_add_modify (block, vptr, vtable);
449     }
450 }
451
452
453 /* Reset the len for unlimited polymorphic objects.  */
454
455 void
456 gfc_reset_len (stmtblock_t *block, gfc_expr *expr)
457 {
458   gfc_expr *e;
459   gfc_se se_len;
460   e = gfc_find_and_cut_at_last_class_ref (expr);
461   if (e == NULL)
462     return;
463   gfc_add_len_component (e);
464   gfc_init_se (&se_len, NULL);
465   gfc_conv_expr (&se_len, e);
466   gfc_add_modify (block, se_len.expr,
467                   fold_convert (TREE_TYPE (se_len.expr), integer_zero_node));
468   gfc_free_expr (e);
469 }
470
471
472 /* Obtain the vptr of the last class reference in an expression.
473    Return NULL_TREE if no class reference is found.  */
474
475 tree
476 gfc_get_vptr_from_expr (tree expr)
477 {
478   tree tmp;
479   tree type;
480
481   for (tmp = expr; tmp; tmp = TREE_OPERAND (tmp, 0))
482     {
483       type = TREE_TYPE (tmp);
484       while (type)
485         {
486           if (GFC_CLASS_TYPE_P (type))
487             return gfc_class_vptr_get (tmp);
488           if (type != TYPE_CANONICAL (type))
489             type = TYPE_CANONICAL (type);
490           else
491             type = NULL_TREE;
492         }
493       if (VAR_P (tmp) || TREE_CODE (tmp) == PARM_DECL)
494         break;
495     }
496
497   if (POINTER_TYPE_P (TREE_TYPE (tmp)))
498     tmp = build_fold_indirect_ref_loc (input_location, tmp);
499
500   if (GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
501     return gfc_class_vptr_get (tmp);
502
503   return NULL_TREE;
504 }
505
506
507 static void
508 class_array_data_assign (stmtblock_t *block, tree lhs_desc, tree rhs_desc,
509                          bool lhs_type)
510 {
511   tree tmp, tmp2, type;
512
513   gfc_conv_descriptor_data_set (block, lhs_desc,
514                                 gfc_conv_descriptor_data_get (rhs_desc));
515   gfc_conv_descriptor_offset_set (block, lhs_desc,
516                                   gfc_conv_descriptor_offset_get (rhs_desc));
517
518   gfc_add_modify (block, gfc_conv_descriptor_dtype (lhs_desc),
519                   gfc_conv_descriptor_dtype (rhs_desc));
520
521   /* Assign the dimension as range-ref.  */
522   tmp = gfc_get_descriptor_dimension (lhs_desc);
523   tmp2 = gfc_get_descriptor_dimension (rhs_desc);
524
525   type = lhs_type ? TREE_TYPE (tmp) : TREE_TYPE (tmp2);
526   tmp = build4_loc (input_location, ARRAY_RANGE_REF, type, tmp,
527                     gfc_index_zero_node, NULL_TREE, NULL_TREE);
528   tmp2 = build4_loc (input_location, ARRAY_RANGE_REF, type, tmp2,
529                      gfc_index_zero_node, NULL_TREE, NULL_TREE);
530   gfc_add_modify (block, tmp, tmp2);
531 }
532
533
534 /* Takes a derived type expression and returns the address of a temporary
535    class object of the 'declared' type.  If vptr is not NULL, this is
536    used for the temporary class object.
537    optional_alloc_ptr is false when the dummy is neither allocatable
538    nor a pointer; that's only relevant for the optional handling.  */
539 void
540 gfc_conv_derived_to_class (gfc_se *parmse, gfc_expr *e,
541                            gfc_typespec class_ts, tree vptr, bool optional,
542                            bool optional_alloc_ptr)
543 {
544   gfc_symbol *vtab;
545   tree cond_optional = NULL_TREE;
546   gfc_ss *ss;
547   tree ctree;
548   tree var;
549   tree tmp;
550   int dim;
551
552   /* The derived type needs to be converted to a temporary
553      CLASS object.  */
554   tmp = gfc_typenode_for_spec (&class_ts);
555   var = gfc_create_var (tmp, "class");
556
557   /* Set the vptr.  */
558   ctree =  gfc_class_vptr_get (var);
559
560   if (vptr != NULL_TREE)
561     {
562       /* Use the dynamic vptr.  */
563       tmp = vptr;
564     }
565   else
566     {
567       /* In this case the vtab corresponds to the derived type and the
568          vptr must point to it.  */
569       vtab = gfc_find_derived_vtab (e->ts.u.derived);
570       gcc_assert (vtab);
571       tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
572     }
573   gfc_add_modify (&parmse->pre, ctree,
574                   fold_convert (TREE_TYPE (ctree), tmp));
575
576   /* Now set the data field.  */
577   ctree =  gfc_class_data_get (var);
578
579   if (optional)
580     cond_optional = gfc_conv_expr_present (e->symtree->n.sym);
581
582   if (parmse->expr && POINTER_TYPE_P (TREE_TYPE (parmse->expr)))
583     {
584       /* If there is a ready made pointer to a derived type, use it
585          rather than evaluating the expression again.  */
586       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
587       gfc_add_modify (&parmse->pre, ctree, tmp);
588     }
589   else if (parmse->ss && parmse->ss->info && parmse->ss->info->useflags)
590     {
591       /* For an array reference in an elemental procedure call we need
592          to retain the ss to provide the scalarized array reference.  */
593       gfc_conv_expr_reference (parmse, e);
594       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
595       if (optional)
596         tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
597                           cond_optional, tmp,
598                           fold_convert (TREE_TYPE (tmp), null_pointer_node));
599       gfc_add_modify (&parmse->pre, ctree, tmp);
600     }
601   else
602     {
603       ss = gfc_walk_expr (e);
604       if (ss == gfc_ss_terminator)
605         {
606           parmse->ss = NULL;
607           gfc_conv_expr_reference (parmse, e);
608
609           /* Scalar to an assumed-rank array.  */
610           if (class_ts.u.derived->components->as)
611             {
612               tree type;
613               type = get_scalar_to_descriptor_type (parmse->expr,
614                                                     gfc_expr_attr (e));
615               gfc_add_modify (&parmse->pre, gfc_conv_descriptor_dtype (ctree),
616                               gfc_get_dtype (type));
617               if (optional)
618                 parmse->expr = build3_loc (input_location, COND_EXPR,
619                                            TREE_TYPE (parmse->expr),
620                                            cond_optional, parmse->expr,
621                                            fold_convert (TREE_TYPE (parmse->expr),
622                                                          null_pointer_node));
623               gfc_conv_descriptor_data_set (&parmse->pre, ctree, parmse->expr);
624             }
625           else
626             {
627               tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
628               if (optional)
629                 tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
630                                   cond_optional, tmp,
631                                   fold_convert (TREE_TYPE (tmp),
632                                                 null_pointer_node));
633               gfc_add_modify (&parmse->pre, ctree, tmp);
634             }
635         }
636       else
637         {
638           stmtblock_t block;
639           gfc_init_block (&block);
640           gfc_ref *ref;
641
642           parmse->ss = ss;
643           parmse->use_offset = 1;
644           gfc_conv_expr_descriptor (parmse, e);
645
646           /* Detect any array references with vector subscripts.  */
647           for (ref = e->ref; ref; ref = ref->next)
648             if (ref->type == REF_ARRAY
649                 && ref->u.ar.type != AR_ELEMENT
650                 && ref->u.ar.type != AR_FULL)
651               {
652                 for (dim = 0; dim < ref->u.ar.dimen; dim++)
653                   if (ref->u.ar.dimen_type[dim] == DIMEN_VECTOR)
654                     break;
655                 if (dim < ref->u.ar.dimen)
656                   break;
657               }
658
659           /* Array references with vector subscripts and non-variable expressions
660              need be converted to a one-based descriptor.  */
661           if (ref || e->expr_type != EXPR_VARIABLE)
662             {
663               for (dim = 0; dim < e->rank; ++dim)
664                 gfc_conv_shift_descriptor_lbound (&block, parmse->expr, dim,
665                                                   gfc_index_one_node);
666             }
667
668           if (e->rank != class_ts.u.derived->components->as->rank)
669             {
670               gcc_assert (class_ts.u.derived->components->as->type
671                           == AS_ASSUMED_RANK);
672               class_array_data_assign (&block, ctree, parmse->expr, false);
673             }
674           else
675             {
676               if (gfc_expr_attr (e).codimension)
677                 parmse->expr = fold_build1_loc (input_location,
678                                                 VIEW_CONVERT_EXPR,
679                                                 TREE_TYPE (ctree),
680                                                 parmse->expr);
681               gfc_add_modify (&block, ctree, parmse->expr);
682             }
683
684           if (optional)
685             {
686               tmp = gfc_finish_block (&block);
687
688               gfc_init_block (&block);
689               gfc_conv_descriptor_data_set (&block, ctree, null_pointer_node);
690
691               tmp = build3_v (COND_EXPR, cond_optional, tmp,
692                               gfc_finish_block (&block));
693               gfc_add_expr_to_block (&parmse->pre, tmp);
694             }
695           else
696             gfc_add_block_to_block (&parmse->pre, &block);
697         }
698     }
699
700   if (class_ts.u.derived->components->ts.type == BT_DERIVED
701       && class_ts.u.derived->components->ts.u.derived
702                  ->attr.unlimited_polymorphic)
703     {
704       /* Take care about initializing the _len component correctly.  */
705       ctree = gfc_class_len_get (var);
706       if (UNLIMITED_POLY (e))
707         {
708           gfc_expr *len;
709           gfc_se se;
710
711           len = gfc_copy_expr (e);
712           gfc_add_len_component (len);
713           gfc_init_se (&se, NULL);
714           gfc_conv_expr (&se, len);
715           if (optional)
716             tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se.expr),
717                               cond_optional, se.expr,
718                               fold_convert (TREE_TYPE (se.expr),
719                                             integer_zero_node));
720           else
721             tmp = se.expr;
722         }
723       else
724         tmp = integer_zero_node;
725       gfc_add_modify (&parmse->pre, ctree, fold_convert (TREE_TYPE (ctree),
726                                                           tmp));
727     }
728   /* Pass the address of the class object.  */
729   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
730
731   if (optional && optional_alloc_ptr)
732     parmse->expr = build3_loc (input_location, COND_EXPR,
733                                TREE_TYPE (parmse->expr),
734                                cond_optional, parmse->expr,
735                                fold_convert (TREE_TYPE (parmse->expr),
736                                              null_pointer_node));
737 }
738
739
740 /* Create a new class container, which is required as scalar coarrays
741    have an array descriptor while normal scalars haven't. Optionally,
742    NULL pointer checks are added if the argument is OPTIONAL.  */
743
744 static void
745 class_scalar_coarray_to_class (gfc_se *parmse, gfc_expr *e,
746                                gfc_typespec class_ts, bool optional)
747 {
748   tree var, ctree, tmp;
749   stmtblock_t block;
750   gfc_ref *ref;
751   gfc_ref *class_ref;
752
753   gfc_init_block (&block);
754
755   class_ref = NULL;
756   for (ref = e->ref; ref; ref = ref->next)
757     {
758       if (ref->type == REF_COMPONENT
759             && ref->u.c.component->ts.type == BT_CLASS)
760         class_ref = ref;
761     }
762
763   if (class_ref == NULL
764         && e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
765     tmp = e->symtree->n.sym->backend_decl;
766   else
767     {
768       /* Remove everything after the last class reference, convert the
769          expression and then recover its tailend once more.  */
770       gfc_se tmpse;
771       ref = class_ref->next;
772       class_ref->next = NULL;
773       gfc_init_se (&tmpse, NULL);
774       gfc_conv_expr (&tmpse, e);
775       class_ref->next = ref;
776       tmp = tmpse.expr;
777     }
778
779   var = gfc_typenode_for_spec (&class_ts);
780   var = gfc_create_var (var, "class");
781
782   ctree = gfc_class_vptr_get (var);
783   gfc_add_modify (&block, ctree,
784                   fold_convert (TREE_TYPE (ctree), gfc_class_vptr_get (tmp)));
785
786   ctree = gfc_class_data_get (var);
787   tmp = gfc_conv_descriptor_data_get (gfc_class_data_get (tmp));
788   gfc_add_modify (&block, ctree, fold_convert (TREE_TYPE (ctree), tmp));
789
790   /* Pass the address of the class object.  */
791   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
792
793   if (optional)
794     {
795       tree cond = gfc_conv_expr_present (e->symtree->n.sym);
796       tree tmp2;
797
798       tmp = gfc_finish_block (&block);
799
800       gfc_init_block (&block);
801       tmp2 = gfc_class_data_get (var);
802       gfc_add_modify (&block, tmp2, fold_convert (TREE_TYPE (tmp2),
803                                                   null_pointer_node));
804       tmp2 = gfc_finish_block (&block);
805
806       tmp = build3_loc (input_location, COND_EXPR, void_type_node,
807                         cond, tmp, tmp2);
808       gfc_add_expr_to_block (&parmse->pre, tmp);
809     }
810   else
811     gfc_add_block_to_block (&parmse->pre, &block);
812 }
813
814
815 /* Takes an intrinsic type expression and returns the address of a temporary
816    class object of the 'declared' type.  */
817 void
818 gfc_conv_intrinsic_to_class (gfc_se *parmse, gfc_expr *e,
819                              gfc_typespec class_ts)
820 {
821   gfc_symbol *vtab;
822   gfc_ss *ss;
823   tree ctree;
824   tree var;
825   tree tmp;
826
827   /* The intrinsic type needs to be converted to a temporary
828      CLASS object.  */
829   tmp = gfc_typenode_for_spec (&class_ts);
830   var = gfc_create_var (tmp, "class");
831
832   /* Set the vptr.  */
833   ctree = gfc_class_vptr_get (var);
834
835   vtab = gfc_find_vtab (&e->ts);
836   gcc_assert (vtab);
837   tmp = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtab));
838   gfc_add_modify (&parmse->pre, ctree,
839                   fold_convert (TREE_TYPE (ctree), tmp));
840
841   /* Now set the data field.  */
842   ctree = gfc_class_data_get (var);
843   if (parmse->ss && parmse->ss->info->useflags)
844     {
845       /* For an array reference in an elemental procedure call we need
846          to retain the ss to provide the scalarized array reference.  */
847       gfc_conv_expr_reference (parmse, e);
848       tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
849       gfc_add_modify (&parmse->pre, ctree, tmp);
850     }
851   else
852     {
853       ss = gfc_walk_expr (e);
854       if (ss == gfc_ss_terminator)
855         {
856           parmse->ss = NULL;
857           gfc_conv_expr_reference (parmse, e);
858           if (class_ts.u.derived->components->as
859               && class_ts.u.derived->components->as->type == AS_ASSUMED_RANK)
860             {
861               tmp = gfc_conv_scalar_to_descriptor (parmse, parmse->expr,
862                                                    gfc_expr_attr (e));
863               tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
864                                      TREE_TYPE (ctree), tmp);
865             }
866           else
867               tmp = fold_convert (TREE_TYPE (ctree), parmse->expr);
868           gfc_add_modify (&parmse->pre, ctree, tmp);
869         }
870       else
871         {
872           parmse->ss = ss;
873           parmse->use_offset = 1;
874           gfc_conv_expr_descriptor (parmse, e);
875           if (class_ts.u.derived->components->as->rank != e->rank)
876             {
877               tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
878                                      TREE_TYPE (ctree), parmse->expr);
879               gfc_add_modify (&parmse->pre, ctree, tmp);
880             }
881           else
882             gfc_add_modify (&parmse->pre, ctree, parmse->expr);
883         }
884     }
885
886   gcc_assert (class_ts.type == BT_CLASS);
887   if (class_ts.u.derived->components->ts.type == BT_DERIVED
888       && class_ts.u.derived->components->ts.u.derived
889                  ->attr.unlimited_polymorphic)
890     {
891       ctree = gfc_class_len_get (var);
892       /* When the actual arg is a char array, then set the _len component of the
893          unlimited polymorphic entity to the length of the string.  */
894       if (e->ts.type == BT_CHARACTER)
895         {
896           /* Start with parmse->string_length because this seems to be set to a
897            correct value more often.  */
898           if (parmse->string_length)
899             tmp = parmse->string_length;
900           /* When the string_length is not yet set, then try the backend_decl of
901            the cl.  */
902           else if (e->ts.u.cl->backend_decl)
903             tmp = e->ts.u.cl->backend_decl;
904           /* If both of the above approaches fail, then try to generate an
905            expression from the input, which is only feasible currently, when the
906            expression can be evaluated to a constant one.  */
907           else
908             {
909               /* Try to simplify the expression.  */
910               gfc_simplify_expr (e, 0);
911               if (e->expr_type == EXPR_CONSTANT && !e->ts.u.cl->resolved)
912                 {
913                   /* Amazingly all data is present to compute the length of a
914                    constant string, but the expression is not yet there.  */
915                   e->ts.u.cl->length = gfc_get_constant_expr (BT_INTEGER,
916                                                               gfc_charlen_int_kind,
917                                                               &e->where);
918                   mpz_set_ui (e->ts.u.cl->length->value.integer,
919                               e->value.character.length);
920                   gfc_conv_const_charlen (e->ts.u.cl);
921                   e->ts.u.cl->resolved = 1;
922                   tmp = e->ts.u.cl->backend_decl;
923                 }
924               else
925                 {
926                   gfc_error ("Can't compute the length of the char array at %L.",
927                              &e->where);
928                 }
929             }
930         }
931       else
932         tmp = integer_zero_node;
933
934       gfc_add_modify (&parmse->pre, ctree, fold_convert (TREE_TYPE (ctree), tmp));
935     }
936   else if (class_ts.type == BT_CLASS
937            && class_ts.u.derived->components
938            && class_ts.u.derived->components->ts.u
939                 .derived->attr.unlimited_polymorphic)
940     {
941       ctree = gfc_class_len_get (var);
942       gfc_add_modify (&parmse->pre, ctree,
943                       fold_convert (TREE_TYPE (ctree),
944                                     integer_zero_node));
945     }
946   /* Pass the address of the class object.  */
947   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
948 }
949
950
951 /* Takes a scalarized class array expression and returns the
952    address of a temporary scalar class object of the 'declared'
953    type.
954    OOP-TODO: This could be improved by adding code that branched on
955    the dynamic type being the same as the declared type. In this case
956    the original class expression can be passed directly.
957    optional_alloc_ptr is false when the dummy is neither allocatable
958    nor a pointer; that's relevant for the optional handling.
959    Set copyback to true if class container's _data and _vtab pointers
960    might get modified.  */
961
962 void
963 gfc_conv_class_to_class (gfc_se *parmse, gfc_expr *e, gfc_typespec class_ts,
964                          bool elemental, bool copyback, bool optional,
965                          bool optional_alloc_ptr)
966 {
967   tree ctree;
968   tree var;
969   tree tmp;
970   tree vptr;
971   tree cond = NULL_TREE;
972   tree slen = NULL_TREE;
973   gfc_ref *ref;
974   gfc_ref *class_ref;
975   stmtblock_t block;
976   bool full_array = false;
977
978   gfc_init_block (&block);
979
980   class_ref = NULL;
981   for (ref = e->ref; ref; ref = ref->next)
982     {
983       if (ref->type == REF_COMPONENT
984             && ref->u.c.component->ts.type == BT_CLASS)
985         class_ref = ref;
986
987       if (ref->next == NULL)
988         break;
989     }
990
991   if ((ref == NULL || class_ref == ref)
992       && !(gfc_is_class_array_function (e) && parmse->class_vptr != NULL_TREE)
993       && (!class_ts.u.derived->components->as
994           || class_ts.u.derived->components->as->rank != -1))
995     return;
996
997   /* Test for FULL_ARRAY.  */
998   if (e->rank == 0 && gfc_expr_attr (e).codimension
999       && gfc_expr_attr (e).dimension)
1000     full_array = true;
1001   else
1002     gfc_is_class_array_ref (e, &full_array);
1003
1004   /* The derived type needs to be converted to a temporary
1005      CLASS object.  */
1006   tmp = gfc_typenode_for_spec (&class_ts);
1007   var = gfc_create_var (tmp, "class");
1008
1009   /* Set the data.  */
1010   ctree = gfc_class_data_get (var);
1011   if (class_ts.u.derived->components->as
1012       && e->rank != class_ts.u.derived->components->as->rank)
1013     {
1014       if (e->rank == 0)
1015         {
1016           tree type = get_scalar_to_descriptor_type (parmse->expr,
1017                                                      gfc_expr_attr (e));
1018           gfc_add_modify (&block, gfc_conv_descriptor_dtype (ctree),
1019                           gfc_get_dtype (type));
1020
1021           tmp = gfc_class_data_get (parmse->expr);
1022           if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
1023             tmp = gfc_build_addr_expr (NULL_TREE, tmp);
1024
1025           gfc_conv_descriptor_data_set (&block, ctree, tmp);
1026         }
1027       else
1028         class_array_data_assign (&block, ctree, parmse->expr, false);
1029     }
1030   else
1031     {
1032       if (TREE_TYPE (parmse->expr) != TREE_TYPE (ctree))
1033         parmse->expr = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
1034                                         TREE_TYPE (ctree), parmse->expr);
1035       gfc_add_modify (&block, ctree, parmse->expr);
1036     }
1037
1038   /* Return the data component, except in the case of scalarized array
1039      references, where nullification of the cannot occur and so there
1040      is no need.  */
1041   if (!elemental && full_array && copyback)
1042     {
1043       if (class_ts.u.derived->components->as
1044           && e->rank != class_ts.u.derived->components->as->rank)
1045         {
1046           if (e->rank == 0)
1047             gfc_add_modify (&parmse->post, gfc_class_data_get (parmse->expr),
1048                             gfc_conv_descriptor_data_get (ctree));
1049           else
1050             class_array_data_assign (&parmse->post, parmse->expr, ctree, true);
1051         }
1052       else
1053         gfc_add_modify (&parmse->post, parmse->expr, ctree);
1054     }
1055
1056   /* Set the vptr.  */
1057   ctree = gfc_class_vptr_get (var);
1058
1059   /* The vptr is the second field of the actual argument.
1060      First we have to find the corresponding class reference.  */
1061
1062   tmp = NULL_TREE;
1063   if (gfc_is_class_array_function (e)
1064       && parmse->class_vptr != NULL_TREE)
1065     tmp = parmse->class_vptr;
1066   else if (class_ref == NULL
1067            && e->symtree && e->symtree->n.sym->ts.type == BT_CLASS)
1068     {
1069       tmp = e->symtree->n.sym->backend_decl;
1070
1071       if (TREE_CODE (tmp) == FUNCTION_DECL)
1072         tmp = gfc_get_fake_result_decl (e->symtree->n.sym, 0);
1073
1074       if (DECL_LANG_SPECIFIC (tmp) && GFC_DECL_SAVED_DESCRIPTOR (tmp))
1075         tmp = GFC_DECL_SAVED_DESCRIPTOR (tmp);
1076
1077       slen = build_zero_cst (size_type_node);
1078     }
1079   else
1080     {
1081       /* Remove everything after the last class reference, convert the
1082          expression and then recover its tailend once more.  */
1083       gfc_se tmpse;
1084       ref = class_ref->next;
1085       class_ref->next = NULL;
1086       gfc_init_se (&tmpse, NULL);
1087       gfc_conv_expr (&tmpse, e);
1088       class_ref->next = ref;
1089       tmp = tmpse.expr;
1090       slen = tmpse.string_length;
1091     }
1092
1093   gcc_assert (tmp != NULL_TREE);
1094
1095   /* Dereference if needs be.  */
1096   if (TREE_CODE (TREE_TYPE (tmp)) == REFERENCE_TYPE)
1097     tmp = build_fold_indirect_ref_loc (input_location, tmp);
1098
1099   if (!(gfc_is_class_array_function (e) && parmse->class_vptr))
1100     vptr = gfc_class_vptr_get (tmp);
1101   else
1102     vptr = tmp;
1103
1104   gfc_add_modify (&block, ctree,
1105                   fold_convert (TREE_TYPE (ctree), vptr));
1106
1107   /* Return the vptr component, except in the case of scalarized array
1108      references, where the dynamic type cannot change.  */
1109   if (!elemental && full_array && copyback)
1110     gfc_add_modify (&parmse->post, vptr,
1111                     fold_convert (TREE_TYPE (vptr), ctree));
1112
1113   /* For unlimited polymorphic objects also set the _len component.  */
1114   if (class_ts.type == BT_CLASS
1115       && class_ts.u.derived->components
1116       && class_ts.u.derived->components->ts.u
1117                       .derived->attr.unlimited_polymorphic)
1118     {
1119       ctree = gfc_class_len_get (var);
1120       if (UNLIMITED_POLY (e))
1121         tmp = gfc_class_len_get (tmp);
1122       else if (e->ts.type == BT_CHARACTER)
1123         {
1124           gcc_assert (slen != NULL_TREE);
1125           tmp = slen;
1126         }
1127       else
1128         tmp = build_zero_cst (size_type_node);
1129       gfc_add_modify (&parmse->pre, ctree,
1130                       fold_convert (TREE_TYPE (ctree), tmp));
1131
1132       /* Return the len component, except in the case of scalarized array
1133         references, where the dynamic type cannot change.  */
1134       if (!elemental && full_array && copyback)
1135           gfc_add_modify (&parmse->post, tmp,
1136                           fold_convert (TREE_TYPE (tmp), ctree));
1137     }
1138
1139   if (optional)
1140     {
1141       tree tmp2;
1142
1143       cond = gfc_conv_expr_present (e->symtree->n.sym);
1144       /* parmse->pre may contain some preparatory instructions for the
1145          temporary array descriptor.  Those may only be executed when the
1146          optional argument is set, therefore add parmse->pre's instructions
1147          to block, which is later guarded by an if (optional_arg_given).  */
1148       gfc_add_block_to_block (&parmse->pre, &block);
1149       block.head = parmse->pre.head;
1150       parmse->pre.head = NULL_TREE;
1151       tmp = gfc_finish_block (&block);
1152
1153       if (optional_alloc_ptr)
1154         tmp2 = build_empty_stmt (input_location);
1155       else
1156         {
1157           gfc_init_block (&block);
1158
1159           tmp2 = gfc_conv_descriptor_data_get (gfc_class_data_get (var));
1160           gfc_add_modify (&block, tmp2, fold_convert (TREE_TYPE (tmp2),
1161                                                       null_pointer_node));
1162           tmp2 = gfc_finish_block (&block);
1163         }
1164
1165       tmp = build3_loc (input_location, COND_EXPR, void_type_node,
1166                         cond, tmp, tmp2);
1167       gfc_add_expr_to_block (&parmse->pre, tmp);
1168     }
1169   else
1170     gfc_add_block_to_block (&parmse->pre, &block);
1171
1172   /* Pass the address of the class object.  */
1173   parmse->expr = gfc_build_addr_expr (NULL_TREE, var);
1174
1175   if (optional && optional_alloc_ptr)
1176     parmse->expr = build3_loc (input_location, COND_EXPR,
1177                                TREE_TYPE (parmse->expr),
1178                                cond, parmse->expr,
1179                                fold_convert (TREE_TYPE (parmse->expr),
1180                                              null_pointer_node));
1181 }
1182
1183
1184 /* Given a class array declaration and an index, returns the address
1185    of the referenced element.  */
1186
1187 tree
1188 gfc_get_class_array_ref (tree index, tree class_decl, tree data_comp,
1189                          bool unlimited)
1190 {
1191   tree data, size, tmp, ctmp, offset, ptr;
1192
1193   data = data_comp != NULL_TREE ? data_comp :
1194                                   gfc_class_data_get (class_decl);
1195   size = gfc_class_vtab_size_get (class_decl);
1196
1197   if (unlimited)
1198     {
1199       tmp = fold_convert (gfc_array_index_type,
1200                           gfc_class_len_get (class_decl));
1201       ctmp = fold_build2_loc (input_location, MULT_EXPR,
1202                               gfc_array_index_type, size, tmp);
1203       tmp = fold_build2_loc (input_location, GT_EXPR,
1204                              logical_type_node, tmp,
1205                              build_zero_cst (TREE_TYPE (tmp)));
1206       size = fold_build3_loc (input_location, COND_EXPR,
1207                               gfc_array_index_type, tmp, ctmp, size);
1208     }
1209
1210   offset = fold_build2_loc (input_location, MULT_EXPR,
1211                             gfc_array_index_type,
1212                             index, size);
1213
1214   data = gfc_conv_descriptor_data_get (data);
1215   ptr = fold_convert (pvoid_type_node, data);
1216   ptr = fold_build_pointer_plus_loc (input_location, ptr, offset);
1217   return fold_convert (TREE_TYPE (data), ptr);
1218 }
1219
1220
1221 /* Copies one class expression to another, assuming that if either
1222    'to' or 'from' are arrays they are packed.  Should 'from' be
1223    NULL_TREE, the initialization expression for 'to' is used, assuming
1224    that the _vptr is set.  */
1225
1226 tree
1227 gfc_copy_class_to_class (tree from, tree to, tree nelems, bool unlimited)
1228 {
1229   tree fcn;
1230   tree fcn_type;
1231   tree from_data;
1232   tree from_len;
1233   tree to_data;
1234   tree to_len;
1235   tree to_ref;
1236   tree from_ref;
1237   vec<tree, va_gc> *args;
1238   tree tmp;
1239   tree stdcopy;
1240   tree extcopy;
1241   tree index;
1242   bool is_from_desc = false, is_to_class = false;
1243
1244   args = NULL;
1245   /* To prevent warnings on uninitialized variables.  */
1246   from_len = to_len = NULL_TREE;
1247
1248   if (from != NULL_TREE)
1249     fcn = gfc_class_vtab_copy_get (from);
1250   else
1251     fcn = gfc_class_vtab_copy_get (to);
1252
1253   fcn_type = TREE_TYPE (TREE_TYPE (fcn));
1254
1255   if (from != NULL_TREE)
1256     {
1257       is_from_desc = GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (from));
1258       if (is_from_desc)
1259         {
1260           from_data = from;
1261           from = GFC_DECL_SAVED_DESCRIPTOR (from);
1262         }
1263       else
1264         {
1265           /* Check that from is a class.  When the class is part of a coarray,
1266              then from is a common pointer and is to be used as is.  */
1267           tmp = POINTER_TYPE_P (TREE_TYPE (from))
1268               ? build_fold_indirect_ref (from) : from;
1269           from_data =
1270               (GFC_CLASS_TYPE_P (TREE_TYPE (tmp))
1271                || (DECL_P (tmp) && GFC_DECL_CLASS (tmp)))
1272               ? gfc_class_data_get (from) : from;
1273           is_from_desc = GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (from_data));
1274         }
1275      }
1276   else
1277     from_data = gfc_class_vtab_def_init_get (to);
1278
1279   if (unlimited)
1280     {
1281       if (from != NULL_TREE && unlimited)
1282         from_len = gfc_class_len_or_zero_get (from);
1283       else
1284         from_len = build_zero_cst (size_type_node);
1285     }
1286
1287   if (GFC_CLASS_TYPE_P (TREE_TYPE (to)))
1288     {
1289       is_to_class = true;
1290       to_data = gfc_class_data_get (to);
1291       if (unlimited)
1292         to_len = gfc_class_len_get (to);
1293     }
1294   else
1295     /* When to is a BT_DERIVED and not a BT_CLASS, then to_data == to.  */
1296     to_data = to;
1297
1298   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (to_data)))
1299     {
1300       stmtblock_t loopbody;
1301       stmtblock_t body;
1302       stmtblock_t ifbody;
1303       gfc_loopinfo loop;
1304       tree orig_nelems = nelems; /* Needed for bounds check.  */
1305
1306       gfc_init_block (&body);
1307       tmp = fold_build2_loc (input_location, MINUS_EXPR,
1308                              gfc_array_index_type, nelems,
1309                              gfc_index_one_node);
1310       nelems = gfc_evaluate_now (tmp, &body);
1311       index = gfc_create_var (gfc_array_index_type, "S");
1312
1313       if (is_from_desc)
1314         {
1315           from_ref = gfc_get_class_array_ref (index, from, from_data,
1316                                               unlimited);
1317           vec_safe_push (args, from_ref);
1318         }
1319       else
1320         vec_safe_push (args, from_data);
1321
1322       if (is_to_class)
1323         to_ref = gfc_get_class_array_ref (index, to, to_data, unlimited);
1324       else
1325         {
1326           tmp = gfc_conv_array_data (to);
1327           tmp = build_fold_indirect_ref_loc (input_location, tmp);
1328           to_ref = gfc_build_addr_expr (NULL_TREE,
1329                                         gfc_build_array_ref (tmp, index, to));
1330         }
1331       vec_safe_push (args, to_ref);
1332
1333       /* Add bounds check.  */
1334       if ((gfc_option.rtcheck & GFC_RTCHECK_BOUNDS) > 0 && is_from_desc)
1335         {
1336           char *msg;
1337           const char *name = "<<unknown>>";
1338           tree from_len;
1339
1340           if (DECL_P (to))
1341             name = (const char *)(DECL_NAME (to)->identifier.id.str);
1342
1343           from_len = gfc_conv_descriptor_size (from_data, 1);
1344           tmp = fold_build2_loc (input_location, NE_EXPR,
1345                                   logical_type_node, from_len, orig_nelems);
1346           msg = xasprintf ("Array bound mismatch for dimension %d "
1347                            "of array '%s' (%%ld/%%ld)",
1348                            1, name);
1349
1350           gfc_trans_runtime_check (true, false, tmp, &body,
1351                                    &gfc_current_locus, msg,
1352                              fold_convert (long_integer_type_node, orig_nelems),
1353                                fold_convert (long_integer_type_node, from_len));
1354
1355           free (msg);
1356         }
1357
1358       tmp = build_call_vec (fcn_type, fcn, args);
1359
1360       /* Build the body of the loop.  */
1361       gfc_init_block (&loopbody);
1362       gfc_add_expr_to_block (&loopbody, tmp);
1363
1364       /* Build the loop and return.  */
1365       gfc_init_loopinfo (&loop);
1366       loop.dimen = 1;
1367       loop.from[0] = gfc_index_zero_node;
1368       loop.loopvar[0] = index;
1369       loop.to[0] = nelems;
1370       gfc_trans_scalarizing_loops (&loop, &loopbody);
1371       gfc_init_block (&ifbody);
1372       gfc_add_block_to_block (&ifbody, &loop.pre);
1373       stdcopy = gfc_finish_block (&ifbody);
1374       /* In initialization mode from_len is a constant zero.  */
1375       if (unlimited && !integer_zerop (from_len))
1376         {
1377           vec_safe_push (args, from_len);
1378           vec_safe_push (args, to_len);
1379           tmp = build_call_vec (fcn_type, fcn, args);
1380           /* Build the body of the loop.  */
1381           gfc_init_block (&loopbody);
1382           gfc_add_expr_to_block (&loopbody, tmp);
1383
1384           /* Build the loop and return.  */
1385           gfc_init_loopinfo (&loop);
1386           loop.dimen = 1;
1387           loop.from[0] = gfc_index_zero_node;
1388           loop.loopvar[0] = index;
1389           loop.to[0] = nelems;
1390           gfc_trans_scalarizing_loops (&loop, &loopbody);
1391           gfc_init_block (&ifbody);
1392           gfc_add_block_to_block (&ifbody, &loop.pre);
1393           extcopy = gfc_finish_block (&ifbody);
1394
1395           tmp = fold_build2_loc (input_location, GT_EXPR,
1396                                  logical_type_node, from_len,
1397                                  build_zero_cst (TREE_TYPE (from_len)));
1398           tmp = fold_build3_loc (input_location, COND_EXPR,
1399                                  void_type_node, tmp, extcopy, stdcopy);
1400           gfc_add_expr_to_block (&body, tmp);
1401           tmp = gfc_finish_block (&body);
1402         }
1403       else
1404         {
1405           gfc_add_expr_to_block (&body, stdcopy);
1406           tmp = gfc_finish_block (&body);
1407         }
1408       gfc_cleanup_loop (&loop);
1409     }
1410   else
1411     {
1412       gcc_assert (!is_from_desc);
1413       vec_safe_push (args, from_data);
1414       vec_safe_push (args, to_data);
1415       stdcopy = build_call_vec (fcn_type, fcn, args);
1416
1417       /* In initialization mode from_len is a constant zero.  */
1418       if (unlimited && !integer_zerop (from_len))
1419         {
1420           vec_safe_push (args, from_len);
1421           vec_safe_push (args, to_len);
1422           extcopy = build_call_vec (fcn_type, fcn, args);
1423           tmp = fold_build2_loc (input_location, GT_EXPR,
1424                                  logical_type_node, from_len,
1425                                  build_zero_cst (TREE_TYPE (from_len)));
1426           tmp = fold_build3_loc (input_location, COND_EXPR,
1427                                  void_type_node, tmp, extcopy, stdcopy);
1428         }
1429       else
1430         tmp = stdcopy;
1431     }
1432
1433   /* Only copy _def_init to to_data, when it is not a NULL-pointer.  */
1434   if (from == NULL_TREE)
1435     {
1436       tree cond;
1437       cond = fold_build2_loc (input_location, NE_EXPR,
1438                               logical_type_node,
1439                               from_data, null_pointer_node);
1440       tmp = fold_build3_loc (input_location, COND_EXPR,
1441                              void_type_node, cond,
1442                              tmp, build_empty_stmt (input_location));
1443     }
1444
1445   return tmp;
1446 }
1447
1448
1449 static tree
1450 gfc_trans_class_array_init_assign (gfc_expr *rhs, gfc_expr *lhs, gfc_expr *obj)
1451 {
1452   gfc_actual_arglist *actual;
1453   gfc_expr *ppc;
1454   gfc_code *ppc_code;
1455   tree res;
1456
1457   actual = gfc_get_actual_arglist ();
1458   actual->expr = gfc_copy_expr (rhs);
1459   actual->next = gfc_get_actual_arglist ();
1460   actual->next->expr = gfc_copy_expr (lhs);
1461   ppc = gfc_copy_expr (obj);
1462   gfc_add_vptr_component (ppc);
1463   gfc_add_component_ref (ppc, "_copy");
1464   ppc_code = gfc_get_code (EXEC_CALL);
1465   ppc_code->resolved_sym = ppc->symtree->n.sym;
1466   /* Although '_copy' is set to be elemental in class.c, it is
1467      not staying that way.  Find out why, sometime....  */
1468   ppc_code->resolved_sym->attr.elemental = 1;
1469   ppc_code->ext.actual = actual;
1470   ppc_code->expr1 = ppc;
1471   /* Since '_copy' is elemental, the scalarizer will take care
1472      of arrays in gfc_trans_call.  */
1473   res = gfc_trans_call (ppc_code, false, NULL, NULL, false);
1474   gfc_free_statements (ppc_code);
1475
1476   if (UNLIMITED_POLY(obj))
1477     {
1478       /* Check if rhs is non-NULL. */
1479       gfc_se src;
1480       gfc_init_se (&src, NULL);
1481       gfc_conv_expr (&src, rhs);
1482       src.expr = gfc_build_addr_expr (NULL_TREE, src.expr);
1483       tree cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node,
1484                                    src.expr, fold_convert (TREE_TYPE (src.expr),
1485                                                            null_pointer_node));
1486       res = build3_loc (input_location, COND_EXPR, TREE_TYPE (res), cond, res,
1487                         build_empty_stmt (input_location));
1488     }
1489
1490   return res;
1491 }
1492
1493 /* Special case for initializing a polymorphic dummy with INTENT(OUT).
1494    A MEMCPY is needed to copy the full data from the default initializer
1495    of the dynamic type.  */
1496
1497 tree
1498 gfc_trans_class_init_assign (gfc_code *code)
1499 {
1500   stmtblock_t block;
1501   tree tmp;
1502   gfc_se dst,src,memsz;
1503   gfc_expr *lhs, *rhs, *sz;
1504
1505   gfc_start_block (&block);
1506
1507   lhs = gfc_copy_expr (code->expr1);
1508
1509   rhs = gfc_copy_expr (code->expr1);
1510   gfc_add_vptr_component (rhs);
1511
1512   /* Make sure that the component backend_decls have been built, which
1513      will not have happened if the derived types concerned have not
1514      been referenced.  */
1515   gfc_get_derived_type (rhs->ts.u.derived);
1516   gfc_add_def_init_component (rhs);
1517   /* The _def_init is always scalar.  */
1518   rhs->rank = 0;
1519
1520   if (code->expr1->ts.type == BT_CLASS
1521       && CLASS_DATA (code->expr1)->attr.dimension)
1522     {
1523       gfc_array_spec *tmparr = gfc_get_array_spec ();
1524       *tmparr = *CLASS_DATA (code->expr1)->as;
1525       /* Adding the array ref to the class expression results in correct
1526          indexing to the dynamic type.  */
1527       gfc_add_full_array_ref (lhs, tmparr);
1528       tmp = gfc_trans_class_array_init_assign (rhs, lhs, code->expr1);
1529     }
1530   else
1531     {
1532       /* Scalar initialization needs the _data component.  */
1533       gfc_add_data_component (lhs);
1534       sz = gfc_copy_expr (code->expr1);
1535       gfc_add_vptr_component (sz);
1536       gfc_add_size_component (sz);
1537
1538       gfc_init_se (&dst, NULL);
1539       gfc_init_se (&src, NULL);
1540       gfc_init_se (&memsz, NULL);
1541       gfc_conv_expr (&dst, lhs);
1542       gfc_conv_expr (&src, rhs);
1543       gfc_conv_expr (&memsz, sz);
1544       gfc_add_block_to_block (&block, &src.pre);
1545       src.expr = gfc_build_addr_expr (NULL_TREE, src.expr);
1546
1547       tmp = gfc_build_memcpy_call (dst.expr, src.expr, memsz.expr);
1548
1549       if (UNLIMITED_POLY(code->expr1))
1550         {
1551           /* Check if _def_init is non-NULL. */
1552           tree cond = fold_build2_loc (input_location, NE_EXPR,
1553                                        logical_type_node, src.expr,
1554                                        fold_convert (TREE_TYPE (src.expr),
1555                                                      null_pointer_node));
1556           tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), cond,
1557                             tmp, build_empty_stmt (input_location));
1558         }
1559     }
1560
1561   if (code->expr1->symtree->n.sym->attr.optional
1562       || code->expr1->symtree->n.sym->ns->proc_name->attr.entry_master)
1563     {
1564       tree present = gfc_conv_expr_present (code->expr1->symtree->n.sym);
1565       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp),
1566                         present, tmp,
1567                         build_empty_stmt (input_location));
1568     }
1569
1570   gfc_add_expr_to_block (&block, tmp);
1571
1572   return gfc_finish_block (&block);
1573 }
1574
1575
1576 /* End of prototype trans-class.c  */
1577
1578
1579 static void
1580 realloc_lhs_warning (bt type, bool array, locus *where)
1581 {
1582   if (array && type != BT_CLASS && type != BT_DERIVED && warn_realloc_lhs)
1583     gfc_warning (OPT_Wrealloc_lhs,
1584                  "Code for reallocating the allocatable array at %L will "
1585                  "be added", where);
1586   else if (warn_realloc_lhs_all)
1587     gfc_warning (OPT_Wrealloc_lhs_all,
1588                  "Code for reallocating the allocatable variable at %L "
1589                  "will be added", where);
1590 }
1591
1592
1593 static void gfc_apply_interface_mapping_to_expr (gfc_interface_mapping *,
1594                                                  gfc_expr *);
1595
1596 /* Copy the scalarization loop variables.  */
1597
1598 static void
1599 gfc_copy_se_loopvars (gfc_se * dest, gfc_se * src)
1600 {
1601   dest->ss = src->ss;
1602   dest->loop = src->loop;
1603 }
1604
1605
1606 /* Initialize a simple expression holder.
1607
1608    Care must be taken when multiple se are created with the same parent.
1609    The child se must be kept in sync.  The easiest way is to delay creation
1610    of a child se until after after the previous se has been translated.  */
1611
1612 void
1613 gfc_init_se (gfc_se * se, gfc_se * parent)
1614 {
1615   memset (se, 0, sizeof (gfc_se));
1616   gfc_init_block (&se->pre);
1617   gfc_init_block (&se->post);
1618
1619   se->parent = parent;
1620
1621   if (parent)
1622     gfc_copy_se_loopvars (se, parent);
1623 }
1624
1625
1626 /* Advances to the next SS in the chain.  Use this rather than setting
1627    se->ss = se->ss->next because all the parents needs to be kept in sync.
1628    See gfc_init_se.  */
1629
1630 void
1631 gfc_advance_se_ss_chain (gfc_se * se)
1632 {
1633   gfc_se *p;
1634   gfc_ss *ss;
1635
1636   gcc_assert (se != NULL && se->ss != NULL && se->ss != gfc_ss_terminator);
1637
1638   p = se;
1639   /* Walk down the parent chain.  */
1640   while (p != NULL)
1641     {
1642       /* Simple consistency check.  */
1643       gcc_assert (p->parent == NULL || p->parent->ss == p->ss
1644                   || p->parent->ss->nested_ss == p->ss);
1645
1646       /* If we were in a nested loop, the next scalarized expression can be
1647          on the parent ss' next pointer.  Thus we should not take the next
1648          pointer blindly, but rather go up one nest level as long as next
1649          is the end of chain.  */
1650       ss = p->ss;
1651       while (ss->next == gfc_ss_terminator && ss->parent != NULL)
1652         ss = ss->parent;
1653
1654       p->ss = ss->next;
1655
1656       p = p->parent;
1657     }
1658 }
1659
1660
1661 /* Ensures the result of the expression as either a temporary variable
1662    or a constant so that it can be used repeatedly.  */
1663
1664 void
1665 gfc_make_safe_expr (gfc_se * se)
1666 {
1667   tree var;
1668
1669   if (CONSTANT_CLASS_P (se->expr))
1670     return;
1671
1672   /* We need a temporary for this result.  */
1673   var = gfc_create_var (TREE_TYPE (se->expr), NULL);
1674   gfc_add_modify (&se->pre, var, se->expr);
1675   se->expr = var;
1676 }
1677
1678
1679 /* Return an expression which determines if a dummy parameter is present.
1680    Also used for arguments to procedures with multiple entry points.  */
1681
1682 tree
1683 gfc_conv_expr_present (gfc_symbol * sym)
1684 {
1685   tree decl, cond;
1686
1687   gcc_assert (sym->attr.dummy);
1688   decl = gfc_get_symbol_decl (sym);
1689
1690   /* Intrinsic scalars with VALUE attribute which are passed by value
1691      use a hidden argument to denote the present status.  */
1692   if (sym->attr.value && sym->ts.type != BT_CHARACTER
1693       && sym->ts.type != BT_CLASS && sym->ts.type != BT_DERIVED
1694       && !sym->attr.dimension)
1695     {
1696       char name[GFC_MAX_SYMBOL_LEN + 2];
1697       tree tree_name;
1698
1699       gcc_assert (TREE_CODE (decl) == PARM_DECL);
1700       name[0] = '_';
1701       strcpy (&name[1], sym->name);
1702       tree_name = get_identifier (name);
1703
1704       /* Walk function argument list to find hidden arg.  */
1705       cond = DECL_ARGUMENTS (DECL_CONTEXT (decl));
1706       for ( ; cond != NULL_TREE; cond = TREE_CHAIN (cond))
1707         if (DECL_NAME (cond) == tree_name)
1708           break;
1709
1710       gcc_assert (cond);
1711       return cond;
1712     }
1713
1714   if (TREE_CODE (decl) != PARM_DECL)
1715     {
1716       /* Array parameters use a temporary descriptor, we want the real
1717          parameter.  */
1718       gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl))
1719              || GFC_ARRAY_TYPE_P (TREE_TYPE (decl)));
1720       decl = GFC_DECL_SAVED_DESCRIPTOR (decl);
1721     }
1722
1723   cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node, decl,
1724                           fold_convert (TREE_TYPE (decl), null_pointer_node));
1725
1726   /* Fortran 2008 allows to pass null pointers and non-associated pointers
1727      as actual argument to denote absent dummies. For array descriptors,
1728      we thus also need to check the array descriptor.  For BT_CLASS, it
1729      can also occur for scalars and F2003 due to type->class wrapping and
1730      class->class wrapping.  Note further that BT_CLASS always uses an
1731      array descriptor for arrays, also for explicit-shape/assumed-size.  */
1732
1733   if (!sym->attr.allocatable
1734       && ((sym->ts.type != BT_CLASS && !sym->attr.pointer)
1735           || (sym->ts.type == BT_CLASS
1736               && !CLASS_DATA (sym)->attr.allocatable
1737               && !CLASS_DATA (sym)->attr.class_pointer))
1738       && ((gfc_option.allow_std & GFC_STD_F2008) != 0
1739           || sym->ts.type == BT_CLASS))
1740     {
1741       tree tmp;
1742
1743       if ((sym->as && (sym->as->type == AS_ASSUMED_SHAPE
1744                        || sym->as->type == AS_ASSUMED_RANK
1745                        || sym->attr.codimension))
1746           || (sym->ts.type == BT_CLASS && CLASS_DATA (sym)->as))
1747         {
1748           tmp = build_fold_indirect_ref_loc (input_location, decl);
1749           if (sym->ts.type == BT_CLASS)
1750             tmp = gfc_class_data_get (tmp);
1751           tmp = gfc_conv_array_data (tmp);
1752         }
1753       else if (sym->ts.type == BT_CLASS)
1754         tmp = gfc_class_data_get (decl);
1755       else
1756         tmp = NULL_TREE;
1757
1758       if (tmp != NULL_TREE)
1759         {
1760           tmp = fold_build2_loc (input_location, NE_EXPR, logical_type_node, tmp,
1761                                  fold_convert (TREE_TYPE (tmp), null_pointer_node));
1762           cond = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
1763                                   logical_type_node, cond, tmp);
1764         }
1765     }
1766
1767   return cond;
1768 }
1769
1770
1771 /* Converts a missing, dummy argument into a null or zero.  */
1772
1773 void
1774 gfc_conv_missing_dummy (gfc_se * se, gfc_expr * arg, gfc_typespec ts, int kind)
1775 {
1776   tree present;
1777   tree tmp;
1778
1779   present = gfc_conv_expr_present (arg->symtree->n.sym);
1780
1781   if (kind > 0)
1782     {
1783       /* Create a temporary and convert it to the correct type.  */
1784       tmp = gfc_get_int_type (kind);
1785       tmp = fold_convert (tmp, build_fold_indirect_ref_loc (input_location,
1786                                                         se->expr));
1787
1788       /* Test for a NULL value.  */
1789       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (tmp), present,
1790                         tmp, fold_convert (TREE_TYPE (tmp), integer_one_node));
1791       tmp = gfc_evaluate_now (tmp, &se->pre);
1792       se->expr = gfc_build_addr_expr (NULL_TREE, tmp);
1793     }
1794   else
1795     {
1796       tmp = build3_loc (input_location, COND_EXPR, TREE_TYPE (se->expr),
1797                         present, se->expr,
1798                         build_zero_cst (TREE_TYPE (se->expr)));
1799       tmp = gfc_evaluate_now (tmp, &se->pre);
1800       se->expr = tmp;
1801     }
1802
1803   if (ts.type == BT_CHARACTER)
1804     {
1805       tmp = build_int_cst (gfc_charlen_type_node, 0);
1806       tmp = fold_build3_loc (input_location, COND_EXPR, gfc_charlen_type_node,
1807                              present, se->string_length, tmp);
1808       tmp = gfc_evaluate_now (tmp, &se->pre);
1809       se->string_length = tmp;
1810     }
1811   return;
1812 }
1813
1814
1815 /* Get the character length of an expression, looking through gfc_refs
1816    if necessary.  */
1817
1818 tree
1819 gfc_get_expr_charlen (gfc_expr *e)
1820 {
1821   gfc_ref *r;
1822   tree length;
1823
1824   gcc_assert (e->expr_type == EXPR_VARIABLE
1825               && e->ts.type == BT_CHARACTER);
1826
1827   length = NULL; /* To silence compiler warning.  */
1828
1829   if (is_subref_array (e) && e->ts.u.cl->length)
1830     {
1831       gfc_se tmpse;
1832       gfc_init_se (&tmpse, NULL);
1833       gfc_conv_expr_type (&tmpse, e->ts.u.cl->length, gfc_charlen_type_node);
1834       e->ts.u.cl->backend_decl = tmpse.expr;
1835       return tmpse.expr;
1836     }
1837
1838   /* First candidate: if the variable is of type CHARACTER, the
1839      expression's length could be the length of the character
1840      variable.  */
1841   if (e->symtree->n.sym->ts.type == BT_CHARACTER)
1842     length = e->symtree->n.sym->ts.u.cl->backend_decl;
1843
1844   /* Look through the reference chain for component references.  */
1845   for (r = e->ref; r; r = r->next)
1846     {
1847       switch (r->type)
1848         {
1849         case REF_COMPONENT:
1850           if (r->u.c.component->ts.type == BT_CHARACTER)
1851             length = r->u.c.component->ts.u.cl->backend_decl;
1852           break;
1853
1854         case REF_ARRAY:
1855           /* Do nothing.  */
1856           break;
1857
1858         default:
1859           /* We should never got substring references here.  These will be
1860              broken down by the scalarizer.  */
1861           gcc_unreachable ();
1862           break;
1863         }
1864     }
1865
1866   gcc_assert (length != NULL);
1867   return length;
1868 }
1869
1870
1871 /* Return for an expression the backend decl of the coarray.  */
1872
1873 tree
1874 gfc_get_tree_for_caf_expr (gfc_expr *expr)
1875 {
1876   tree caf_decl;
1877   bool found = false;
1878   gfc_ref *ref;
1879
1880   gcc_assert (expr && expr->expr_type == EXPR_VARIABLE);
1881
1882   /* Not-implemented diagnostic.  */
1883   if (expr->symtree->n.sym->ts.type == BT_CLASS
1884       && UNLIMITED_POLY (expr->symtree->n.sym)
1885       && CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
1886     gfc_error ("Sorry, coindexed access to an unlimited polymorphic object at "
1887                "%L is not supported", &expr->where);
1888
1889   for (ref = expr->ref; ref; ref = ref->next)
1890     if (ref->type == REF_COMPONENT)
1891       {
1892         if (ref->u.c.component->ts.type == BT_CLASS
1893             && UNLIMITED_POLY (ref->u.c.component)
1894             && CLASS_DATA (ref->u.c.component)->attr.codimension)
1895           gfc_error ("Sorry, coindexed access to an unlimited polymorphic "
1896                      "component at %L is not supported", &expr->where);
1897       }
1898
1899   /* Make sure the backend_decl is present before accessing it.  */
1900   caf_decl = expr->symtree->n.sym->backend_decl == NULL_TREE
1901       ? gfc_get_symbol_decl (expr->symtree->n.sym)
1902       : expr->symtree->n.sym->backend_decl;
1903
1904   if (expr->symtree->n.sym->ts.type == BT_CLASS)
1905     {
1906       if (expr->ref && expr->ref->type == REF_ARRAY)
1907         {
1908           caf_decl = gfc_class_data_get (caf_decl);
1909           if (CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
1910             return caf_decl;
1911         }
1912       for (ref = expr->ref; ref; ref = ref->next)
1913         {
1914           if (ref->type == REF_COMPONENT
1915               && strcmp (ref->u.c.component->name, "_data") != 0)
1916             {
1917               caf_decl = gfc_class_data_get (caf_decl);
1918               if (CLASS_DATA (expr->symtree->n.sym)->attr.codimension)
1919                 return caf_decl;
1920               break;
1921             }
1922           else if (ref->type == REF_ARRAY && ref->u.ar.dimen)
1923             break;
1924         }
1925     }
1926   if (expr->symtree->n.sym->attr.codimension)
1927     return caf_decl;
1928
1929   /* The following code assumes that the coarray is a component reachable via
1930      only scalar components/variables; the Fortran standard guarantees this.  */
1931
1932   for (ref = expr->ref; ref; ref = ref->next)
1933     if (ref->type == REF_COMPONENT)
1934       {
1935         gfc_component *comp = ref->u.c.component;
1936
1937         if (POINTER_TYPE_P (TREE_TYPE (caf_decl)))
1938           caf_decl = build_fold_indirect_ref_loc (input_location, caf_decl);
1939         caf_decl = fold_build3_loc (input_location, COMPONENT_REF,
1940                                     TREE_TYPE (comp->backend_decl), caf_decl,
1941                                     comp->backend_decl, NULL_TREE);
1942         if (comp->ts.type == BT_CLASS)
1943           {
1944             caf_decl = gfc_class_data_get (caf_decl);
1945             if (CLASS_DATA (comp)->attr.codimension)
1946               {
1947                 found = true;
1948                 break;
1949               }
1950           }
1951         if (comp->attr.codimension)
1952           {
1953             found = true;
1954             break;
1955           }
1956       }
1957   gcc_assert (found && caf_decl);
1958   return caf_decl;
1959 }
1960
1961
1962 /* Obtain the Coarray token - and optionally also the offset.  */
1963
1964 void
1965 gfc_get_caf_token_offset (gfc_se *se, tree *token, tree *offset, tree caf_decl,
1966                           tree se_expr, gfc_expr *expr)
1967 {
1968   tree tmp;
1969
1970   /* Coarray token.  */
1971   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl)))
1972     {
1973       gcc_assert (GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl))
1974                     == GFC_ARRAY_ALLOCATABLE
1975                   || expr->symtree->n.sym->attr.select_type_temporary);
1976       *token = gfc_conv_descriptor_token (caf_decl);
1977     }
1978   else if (DECL_LANG_SPECIFIC (caf_decl)
1979            && GFC_DECL_TOKEN (caf_decl) != NULL_TREE)
1980     *token = GFC_DECL_TOKEN (caf_decl);
1981   else
1982     {
1983       gcc_assert (GFC_ARRAY_TYPE_P (TREE_TYPE (caf_decl))
1984                   && GFC_TYPE_ARRAY_CAF_TOKEN (TREE_TYPE (caf_decl)) != NULL_TREE);
1985       *token = GFC_TYPE_ARRAY_CAF_TOKEN (TREE_TYPE (caf_decl));
1986     }
1987
1988   if (offset == NULL)
1989     return;
1990
1991   /* Offset between the coarray base address and the address wanted.  */
1992   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl))
1993       && (GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl)) == GFC_ARRAY_ALLOCATABLE
1994           || GFC_TYPE_ARRAY_AKIND (TREE_TYPE (caf_decl)) == GFC_ARRAY_POINTER))
1995     *offset = build_int_cst (gfc_array_index_type, 0);
1996   else if (DECL_LANG_SPECIFIC (caf_decl)
1997            && GFC_DECL_CAF_OFFSET (caf_decl) != NULL_TREE)
1998     *offset = GFC_DECL_CAF_OFFSET (caf_decl);
1999   else if (GFC_TYPE_ARRAY_CAF_OFFSET (TREE_TYPE (caf_decl)) != NULL_TREE)
2000     *offset = GFC_TYPE_ARRAY_CAF_OFFSET (TREE_TYPE (caf_decl));
2001   else
2002     *offset = build_int_cst (gfc_array_index_type, 0);
2003
2004   if (POINTER_TYPE_P (TREE_TYPE (se_expr))
2005       && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se_expr))))
2006     {
2007       tmp = build_fold_indirect_ref_loc (input_location, se_expr);
2008       tmp = gfc_conv_descriptor_data_get (tmp);
2009     }
2010   else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (se_expr)))
2011     tmp = gfc_conv_descriptor_data_get (se_expr);
2012   else
2013     {
2014       gcc_assert (POINTER_TYPE_P (TREE_TYPE (se_expr)));
2015       tmp = se_expr;
2016     }
2017
2018   *offset = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
2019                              *offset, fold_convert (gfc_array_index_type, tmp));
2020
2021   if (expr->symtree->n.sym->ts.type == BT_DERIVED
2022       && expr->symtree->n.sym->attr.codimension
2023       && expr->symtree->n.sym->ts.u.derived->attr.alloc_comp)
2024     {
2025       gfc_expr *base_expr = gfc_copy_expr (expr);
2026       gfc_ref *ref = base_expr->ref;
2027       gfc_se base_se;
2028
2029       // Iterate through the refs until the last one.
2030       while (ref->next)
2031           ref = ref->next;
2032
2033       if (ref->type == REF_ARRAY
2034           && ref->u.ar.type != AR_FULL)
2035         {
2036           const int ranksum = ref->u.ar.dimen + ref->u.ar.codimen;
2037           int i;
2038           for (i = 0; i < ranksum; ++i)
2039             {
2040               ref->u.ar.start[i] = NULL;
2041               ref->u.ar.end[i] = NULL;
2042             }
2043           ref->u.ar.type = AR_FULL;
2044         }
2045       gfc_init_se (&base_se, NULL);
2046       if (gfc_caf_attr (base_expr).dimension)
2047         {
2048           gfc_conv_expr_descriptor (&base_se, base_expr);
2049           tmp = gfc_conv_descriptor_data_get (base_se.expr);
2050         }
2051       else
2052         {
2053           gfc_conv_expr (&base_se, base_expr);
2054           tmp = base_se.expr;
2055         }
2056
2057       gfc_free_expr (base_expr);
2058       gfc_add_block_to_block (&se->pre, &base_se.pre);
2059       gfc_add_block_to_block (&se->post, &base_se.post);
2060     }
2061   else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (caf_decl)))
2062     tmp = gfc_conv_descriptor_data_get (caf_decl);
2063   else
2064    {
2065      gcc_assert (POINTER_TYPE_P (TREE_TYPE (caf_decl)));
2066      tmp = caf_decl;
2067    }
2068
2069   *offset = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
2070                             fold_convert (gfc_array_index_type, *offset),
2071                             fold_convert (gfc_array_index_type, tmp));
2072 }
2073
2074
2075 /* Convert the coindex of a coarray into an image index; the result is
2076    image_num =  (idx(1)-lcobound(1)+1) + (idx(2)-lcobound(2))*extent(1)
2077               + (idx(3)-lcobound(3))*extend(1)*extent(2) + ...  */
2078
2079 tree
2080 gfc_caf_get_image_index (stmtblock_t *block, gfc_expr *e, tree desc)
2081 {
2082   gfc_ref *ref;
2083   tree lbound, ubound, extent, tmp, img_idx;
2084   gfc_se se;
2085   int i;
2086
2087   for (ref = e->ref; ref; ref = ref->next)
2088     if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
2089       break;
2090   gcc_assert (ref != NULL);
2091
2092   if (ref->u.ar.dimen_type[ref->u.ar.dimen] == DIMEN_THIS_IMAGE)
2093     {
2094       return build_call_expr_loc (input_location, gfor_fndecl_caf_this_image, 1,
2095                                   integer_zero_node);
2096     }
2097
2098   img_idx = build_zero_cst (gfc_array_index_type);
2099   extent = build_one_cst (gfc_array_index_type);
2100   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (desc)))
2101     for (i = ref->u.ar.dimen; i < ref->u.ar.dimen + ref->u.ar.codimen; i++)
2102       {
2103         gfc_init_se (&se, NULL);
2104         gfc_conv_expr_type (&se, ref->u.ar.start[i], gfc_array_index_type);
2105         gfc_add_block_to_block (block, &se.pre);
2106         lbound = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[i]);
2107         tmp = fold_build2_loc (input_location, MINUS_EXPR,
2108                                TREE_TYPE (lbound), se.expr, lbound);
2109         tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (tmp),
2110                                extent, tmp);
2111         img_idx = fold_build2_loc (input_location, PLUS_EXPR,
2112                                    TREE_TYPE (tmp), img_idx, tmp);
2113         if (i < ref->u.ar.dimen + ref->u.ar.codimen - 1)
2114           {
2115             ubound = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[i]);
2116             tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
2117             extent = fold_build2_loc (input_location, MULT_EXPR,
2118                                       TREE_TYPE (tmp), extent, tmp);
2119           }
2120       }
2121   else
2122     for (i = ref->u.ar.dimen; i < ref->u.ar.dimen + ref->u.ar.codimen; i++)
2123       {
2124         gfc_init_se (&se, NULL);
2125         gfc_conv_expr_type (&se, ref->u.ar.start[i], gfc_array_index_type);
2126         gfc_add_block_to_block (block, &se.pre);
2127         lbound = GFC_TYPE_ARRAY_LBOUND (TREE_TYPE (desc), i);
2128         tmp = fold_build2_loc (input_location, MINUS_EXPR,
2129                                TREE_TYPE (lbound), se.expr, lbound);
2130         tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (tmp),
2131                                extent, tmp);
2132         img_idx = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (tmp),
2133                                    img_idx, tmp);
2134         if (i < ref->u.ar.dimen + ref->u.ar.codimen - 1)
2135           {
2136             ubound = GFC_TYPE_ARRAY_UBOUND (TREE_TYPE (desc), i);
2137             tmp = fold_build2_loc (input_location, MINUS_EXPR,
2138                                    TREE_TYPE (ubound), ubound, lbound);
2139             tmp = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (tmp),
2140                                    tmp, build_one_cst (TREE_TYPE (tmp)));
2141             extent = fold_build2_loc (input_location, MULT_EXPR,
2142                                       TREE_TYPE (tmp), extent, tmp);
2143           }
2144       }
2145   img_idx = fold_build2_loc (input_location, PLUS_EXPR, TREE_TYPE (img_idx),
2146                              img_idx, build_one_cst (TREE_TYPE (img_idx)));
2147   return fold_convert (integer_type_node, img_idx);
2148 }
2149
2150
2151 /* For each character array constructor subexpression without a ts.u.cl->length,
2152    replace it by its first element (if there aren't any elements, the length
2153    should already be set to zero).  */
2154
2155 static void
2156 flatten_array_ctors_without_strlen (gfc_expr* e)
2157 {
2158   gfc_actual_arglist* arg;
2159   gfc_constructor* c;
2160
2161   if (!e)
2162     return;
2163
2164   switch (e->expr_type)
2165     {
2166
2167     case EXPR_OP:
2168       flatten_array_ctors_without_strlen (e->value.op.op1);
2169       flatten_array_ctors_without_strlen (e->value.op.op2);
2170       break;
2171
2172     case EXPR_COMPCALL:
2173       /* TODO: Implement as with EXPR_FUNCTION when needed.  */
2174       gcc_unreachable ();
2175
2176     case EXPR_FUNCTION:
2177       for (arg = e->value.function.actual; arg; arg = arg->next)
2178         flatten_array_ctors_without_strlen (arg->expr);
2179       break;
2180
2181     case EXPR_ARRAY:
2182
2183       /* We've found what we're looking for.  */
2184       if (e->ts.type == BT_CHARACTER && !e->ts.u.cl->length)
2185         {
2186           gfc_constructor *c;
2187           gfc_expr* new_expr;
2188
2189           gcc_assert (e->value.constructor);
2190
2191           c = gfc_constructor_first (e->value.constructor);
2192           new_expr = c->expr;
2193           c->expr = NULL;
2194
2195           flatten_array_ctors_without_strlen (new_expr);
2196           gfc_replace_expr (e, new_expr);
2197           break;
2198         }
2199
2200       /* Otherwise, fall through to handle constructor elements.  */
2201       gcc_fallthrough ();
2202     case EXPR_STRUCTURE:
2203       for (c = gfc_constructor_first (e->value.constructor);
2204            c; c = gfc_constructor_next (c))
2205         flatten_array_ctors_without_strlen (c->expr);
2206       break;
2207
2208     default:
2209       break;
2210
2211     }
2212 }
2213
2214
2215 /* Generate code to initialize a string length variable. Returns the
2216    value.  For array constructors, cl->length might be NULL and in this case,
2217    the first element of the constructor is needed.  expr is the original
2218    expression so we can access it but can be NULL if this is not needed.  */
2219
2220 void
2221 gfc_conv_string_length (gfc_charlen * cl, gfc_expr * expr, stmtblock_t * pblock)
2222 {
2223   gfc_se se;
2224
2225   gfc_init_se (&se, NULL);
2226
2227   if (!cl->length && cl->backend_decl && VAR_P (cl->backend_decl))
2228     return;
2229
2230   /* If cl->length is NULL, use gfc_conv_expr to obtain the string length but
2231      "flatten" array constructors by taking their first element; all elements
2232      should be the same length or a cl->length should be present.  */
2233   if (!cl->length)
2234     {
2235       gfc_expr* expr_flat;
2236       if (!expr)
2237         return;
2238       expr_flat = gfc_copy_expr (expr);
2239       flatten_array_ctors_without_strlen (expr_flat);
2240       gfc_resolve_expr (expr_flat);
2241
2242       gfc_conv_expr (&se, expr_flat);
2243       gfc_add_block_to_block (pblock, &se.pre);
2244       cl->backend_decl = convert (gfc_charlen_type_node, se.string_length);
2245
2246       gfc_free_expr (expr_flat);
2247       return;
2248     }
2249
2250   /* Convert cl->length.  */
2251
2252   gcc_assert (cl->length);
2253
2254   gfc_conv_expr_type (&se, cl->length, gfc_charlen_type_node);
2255   se.expr = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
2256                              se.expr, build_zero_cst (TREE_TYPE (se.expr)));
2257   gfc_add_block_to_block (pblock, &se.pre);
2258
2259   if (cl->backend_decl)
2260     gfc_add_modify (pblock, cl->backend_decl, se.expr);
2261   else
2262     cl->backend_decl = gfc_evaluate_now (se.expr, pblock);
2263 }
2264
2265
2266 static void
2267 gfc_conv_substring (gfc_se * se, gfc_ref * ref, int kind,
2268                     const char *name, locus *where)
2269 {
2270   tree tmp;
2271   tree type;
2272   tree fault;
2273   gfc_se start;
2274   gfc_se end;
2275   char *msg;
2276   mpz_t length;
2277
2278   type = gfc_get_character_type (kind, ref->u.ss.length);
2279   type = build_pointer_type (type);
2280
2281   gfc_init_se (&start, se);
2282   gfc_conv_expr_type (&start, ref->u.ss.start, gfc_charlen_type_node);
2283   gfc_add_block_to_block (&se->pre, &start.pre);
2284
2285   if (integer_onep (start.expr))
2286     gfc_conv_string_parameter (se);
2287   else
2288     {
2289       tmp = start.expr;
2290       STRIP_NOPS (tmp);
2291       /* Avoid multiple evaluation of substring start.  */
2292       if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
2293         start.expr = gfc_evaluate_now (start.expr, &se->pre);
2294
2295       /* Change the start of the string.  */
2296       if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
2297         tmp = se->expr;
2298       else
2299         tmp = build_fold_indirect_ref_loc (input_location,
2300                                        se->expr);
2301       tmp = gfc_build_array_ref (tmp, start.expr, NULL);
2302       se->expr = gfc_build_addr_expr (type, tmp);
2303     }
2304
2305   /* Length = end + 1 - start.  */
2306   gfc_init_se (&end, se);
2307   if (ref->u.ss.end == NULL)
2308     end.expr = se->string_length;
2309   else
2310     {
2311       gfc_conv_expr_type (&end, ref->u.ss.end, gfc_charlen_type_node);
2312       gfc_add_block_to_block (&se->pre, &end.pre);
2313     }
2314   tmp = end.expr;
2315   STRIP_NOPS (tmp);
2316   if (!CONSTANT_CLASS_P (tmp) && !DECL_P (tmp))
2317     end.expr = gfc_evaluate_now (end.expr, &se->pre);
2318
2319   if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
2320     {
2321       tree nonempty = fold_build2_loc (input_location, LE_EXPR,
2322                                        logical_type_node, start.expr,
2323                                        end.expr);
2324
2325       /* Check lower bound.  */
2326       fault = fold_build2_loc (input_location, LT_EXPR, logical_type_node,
2327                                start.expr,
2328                                build_one_cst (TREE_TYPE (start.expr)));
2329       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
2330                                logical_type_node, nonempty, fault);
2331       if (name)
2332         msg = xasprintf ("Substring out of bounds: lower bound (%%ld) of '%s' "
2333                          "is less than one", name);
2334       else
2335         msg = xasprintf ("Substring out of bounds: lower bound (%%ld) "
2336                          "is less than one");
2337       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2338                                fold_convert (long_integer_type_node,
2339                                              start.expr));
2340       free (msg);
2341
2342       /* Check upper bound.  */
2343       fault = fold_build2_loc (input_location, GT_EXPR, logical_type_node,
2344                                end.expr, se->string_length);
2345       fault = fold_build2_loc (input_location, TRUTH_ANDIF_EXPR,
2346                                logical_type_node, nonempty, fault);
2347       if (name)
2348         msg = xasprintf ("Substring out of bounds: upper bound (%%ld) of '%s' "
2349                          "exceeds string length (%%ld)", name);
2350       else
2351         msg = xasprintf ("Substring out of bounds: upper bound (%%ld) "
2352                          "exceeds string length (%%ld)");
2353       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2354                                fold_convert (long_integer_type_node, end.expr),
2355                                fold_convert (long_integer_type_node,
2356                                              se->string_length));
2357       free (msg);
2358     }
2359
2360   /* Try to calculate the length from the start and end expressions.  */
2361   if (ref->u.ss.end
2362       && gfc_dep_difference (ref->u.ss.end, ref->u.ss.start, &length))
2363     {
2364       HOST_WIDE_INT i_len;
2365
2366       i_len = gfc_mpz_get_hwi (length) + 1;
2367       if (i_len < 0)
2368         i_len = 0;
2369
2370       tmp = build_int_cst (gfc_charlen_type_node, i_len);
2371       mpz_clear (length);  /* Was initialized by gfc_dep_difference.  */
2372     }
2373   else
2374     {
2375       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_charlen_type_node,
2376                              fold_convert (gfc_charlen_type_node, end.expr),
2377                              fold_convert (gfc_charlen_type_node, start.expr));
2378       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_charlen_type_node,
2379                              build_int_cst (gfc_charlen_type_node, 1), tmp);
2380       tmp = fold_build2_loc (input_location, MAX_EXPR, gfc_charlen_type_node,
2381                              tmp, build_int_cst (gfc_charlen_type_node, 0));
2382     }
2383
2384   se->string_length = tmp;
2385 }
2386
2387
2388 /* Convert a derived type component reference.  */
2389
2390 static void
2391 gfc_conv_component_ref (gfc_se * se, gfc_ref * ref)
2392 {
2393   gfc_component *c;
2394   tree tmp;
2395   tree decl;
2396   tree field;
2397   tree context;
2398
2399   c = ref->u.c.component;
2400
2401   if (c->backend_decl == NULL_TREE
2402       && ref->u.c.sym != NULL)
2403     gfc_get_derived_type (ref->u.c.sym);
2404
2405   field = c->backend_decl;
2406   gcc_assert (field && TREE_CODE (field) == FIELD_DECL);
2407   decl = se->expr;
2408   context = DECL_FIELD_CONTEXT (field);
2409
2410   /* Components can correspond to fields of different containing
2411      types, as components are created without context, whereas
2412      a concrete use of a component has the type of decl as context.
2413      So, if the type doesn't match, we search the corresponding
2414      FIELD_DECL in the parent type.  To not waste too much time
2415      we cache this result in norestrict_decl.
2416      On the other hand, if the context is a UNION or a MAP (a
2417      RECORD_TYPE within a UNION_TYPE) always use the given FIELD_DECL.  */
2418
2419   if (context != TREE_TYPE (decl)
2420       && !(   TREE_CODE (TREE_TYPE (field)) == UNION_TYPE /* Field is union */
2421            || TREE_CODE (context) == UNION_TYPE))         /* Field is map */
2422     {
2423       tree f2 = c->norestrict_decl;
2424       if (!f2 || DECL_FIELD_CONTEXT (f2) != TREE_TYPE (decl))
2425         for (f2 = TYPE_FIELDS (TREE_TYPE (decl)); f2; f2 = DECL_CHAIN (f2))
2426           if (TREE_CODE (f2) == FIELD_DECL
2427               && DECL_NAME (f2) == DECL_NAME (field))
2428             break;
2429       gcc_assert (f2);
2430       c->norestrict_decl = f2;
2431       field = f2;
2432     }
2433
2434   if (ref->u.c.sym && ref->u.c.sym->ts.type == BT_CLASS
2435       && strcmp ("_data", c->name) == 0)
2436     {
2437       /* Found a ref to the _data component.  Store the associated ref to
2438          the vptr in se->class_vptr.  */
2439       se->class_vptr = gfc_class_vptr_get (decl);
2440     }
2441   else
2442     se->class_vptr = NULL_TREE;
2443
2444   tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
2445                          decl, field, NULL_TREE);
2446
2447   se->expr = tmp;
2448
2449   /* Allocatable deferred char arrays are to be handled by the gfc_deferred_
2450      strlen () conditional below.  */
2451   if (c->ts.type == BT_CHARACTER && !c->attr.proc_pointer
2452       && !(c->attr.allocatable && c->ts.deferred)
2453       && !c->attr.pdt_string)
2454     {
2455       tmp = c->ts.u.cl->backend_decl;
2456       /* Components must always be constant length.  */
2457       gcc_assert (tmp && INTEGER_CST_P (tmp));
2458       se->string_length = tmp;
2459     }
2460
2461   if (gfc_deferred_strlen (c, &field))
2462     {
2463       tmp = fold_build3_loc (input_location, COMPONENT_REF,
2464                              TREE_TYPE (field),
2465                              decl, field, NULL_TREE);
2466       se->string_length = tmp;
2467     }
2468
2469   if (((c->attr.pointer || c->attr.allocatable)
2470        && (!c->attr.dimension && !c->attr.codimension)
2471        && c->ts.type != BT_CHARACTER)
2472       || c->attr.proc_pointer)
2473     se->expr = build_fold_indirect_ref_loc (input_location,
2474                                         se->expr);
2475 }
2476
2477
2478 /* This function deals with component references to components of the
2479    parent type for derived type extensions.  */
2480 static void
2481 conv_parent_component_references (gfc_se * se, gfc_ref * ref)
2482 {
2483   gfc_component *c;
2484   gfc_component *cmp;
2485   gfc_symbol *dt;
2486   gfc_ref parent;
2487
2488   dt = ref->u.c.sym;
2489   c = ref->u.c.component;
2490
2491   /* Return if the component is in the parent type.  */
2492   for (cmp = dt->components; cmp; cmp = cmp->next)
2493     if (strcmp (c->name, cmp->name) == 0)
2494       return;
2495
2496   /* Build a gfc_ref to recursively call gfc_conv_component_ref.  */
2497   parent.type = REF_COMPONENT;
2498   parent.next = NULL;
2499   parent.u.c.sym = dt;
2500   parent.u.c.component = dt->components;
2501
2502   if (dt->backend_decl == NULL)
2503     gfc_get_derived_type (dt);
2504
2505   /* Build the reference and call self.  */
2506   gfc_conv_component_ref (se, &parent);
2507   parent.u.c.sym = dt->components->ts.u.derived;
2508   parent.u.c.component = c;
2509   conv_parent_component_references (se, &parent);
2510 }
2511
2512 /* Return the contents of a variable. Also handles reference/pointer
2513    variables (all Fortran pointer references are implicit).  */
2514
2515 static void
2516 gfc_conv_variable (gfc_se * se, gfc_expr * expr)
2517 {
2518   gfc_ss *ss;
2519   gfc_ref *ref;
2520   gfc_symbol *sym;
2521   tree parent_decl = NULL_TREE;
2522   int parent_flag;
2523   bool return_value;
2524   bool alternate_entry;
2525   bool entry_master;
2526   bool is_classarray;
2527   bool first_time = true;
2528
2529   sym = expr->symtree->n.sym;
2530   is_classarray = IS_CLASS_ARRAY (sym);
2531   ss = se->ss;
2532   if (ss != NULL)
2533     {
2534       gfc_ss_info *ss_info = ss->info;
2535
2536       /* Check that something hasn't gone horribly wrong.  */
2537       gcc_assert (ss != gfc_ss_terminator);
2538       gcc_assert (ss_info->expr == expr);
2539
2540       /* A scalarized term.  We already know the descriptor.  */
2541       se->expr = ss_info->data.array.descriptor;
2542       se->string_length = ss_info->string_length;
2543       ref = ss_info->data.array.ref;
2544       if (ref)
2545         gcc_assert (ref->type == REF_ARRAY
2546                     && ref->u.ar.type != AR_ELEMENT);
2547       else
2548         gfc_conv_tmp_array_ref (se);
2549     }
2550   else
2551     {
2552       tree se_expr = NULL_TREE;
2553
2554       se->expr = gfc_get_symbol_decl (sym);
2555
2556       /* Deal with references to a parent results or entries by storing
2557          the current_function_decl and moving to the parent_decl.  */
2558       return_value = sym->attr.function && sym->result == sym;
2559       alternate_entry = sym->attr.function && sym->attr.entry
2560                         && sym->result == sym;
2561       entry_master = sym->attr.result
2562                      && sym->ns->proc_name->attr.entry_master
2563                      && !gfc_return_by_reference (sym->ns->proc_name);
2564       if (current_function_decl)
2565         parent_decl = DECL_CONTEXT (current_function_decl);
2566
2567       if ((se->expr == parent_decl && return_value)
2568            || (sym->ns && sym->ns->proc_name
2569                && parent_decl
2570                && sym->ns->proc_name->backend_decl == parent_decl
2571                && (alternate_entry || entry_master)))
2572         parent_flag = 1;
2573       else
2574         parent_flag = 0;
2575
2576       /* Special case for assigning the return value of a function.
2577          Self recursive functions must have an explicit return value.  */
2578       if (return_value && (se->expr == current_function_decl || parent_flag))
2579         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2580
2581       /* Similarly for alternate entry points.  */
2582       else if (alternate_entry
2583                && (sym->ns->proc_name->backend_decl == current_function_decl
2584                    || parent_flag))
2585         {
2586           gfc_entry_list *el = NULL;
2587
2588           for (el = sym->ns->entries; el; el = el->next)
2589             if (sym == el->sym)
2590               {
2591                 se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2592                 break;
2593               }
2594         }
2595
2596       else if (entry_master
2597                && (sym->ns->proc_name->backend_decl == current_function_decl
2598                    || parent_flag))
2599         se_expr = gfc_get_fake_result_decl (sym, parent_flag);
2600
2601       if (se_expr)
2602         se->expr = se_expr;
2603
2604       /* Procedure actual arguments.  Look out for temporary variables
2605          with the same attributes as function values.  */
2606       else if (!sym->attr.temporary
2607                && sym->attr.flavor == FL_PROCEDURE
2608                && se->expr != current_function_decl)
2609         {
2610           if (!sym->attr.dummy && !sym->attr.proc_pointer)
2611             {
2612               gcc_assert (TREE_CODE (se->expr) == FUNCTION_DECL);
2613               se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
2614             }
2615           return;
2616         }
2617
2618
2619       /* Dereference the expression, where needed. Since characters
2620          are entirely different from other types, they are treated
2621          separately.  */
2622       if (sym->ts.type == BT_CHARACTER)
2623         {
2624           /* Dereference character pointer dummy arguments
2625              or results.  */
2626           if ((sym->attr.pointer || sym->attr.allocatable)
2627               && (sym->attr.dummy
2628                   || sym->attr.function
2629                   || sym->attr.result))
2630             se->expr = build_fold_indirect_ref_loc (input_location,
2631                                                 se->expr);
2632
2633         }
2634       else if (!sym->attr.value)
2635         {
2636           /* Dereference temporaries for class array dummy arguments.  */
2637           if (sym->attr.dummy && is_classarray
2638               && GFC_ARRAY_TYPE_P (TREE_TYPE (se->expr)))
2639             {
2640               if (!se->descriptor_only)
2641                 se->expr = GFC_DECL_SAVED_DESCRIPTOR (se->expr);
2642
2643               se->expr = build_fold_indirect_ref_loc (input_location,
2644                                                       se->expr);
2645             }
2646
2647           /* Dereference non-character scalar dummy arguments.  */
2648           if (sym->attr.dummy && !sym->attr.dimension
2649               && !(sym->attr.codimension && sym->attr.allocatable)
2650               && (sym->ts.type != BT_CLASS
2651                   || (!CLASS_DATA (sym)->attr.dimension
2652                       && !(CLASS_DATA (sym)->attr.codimension
2653                            && CLASS_DATA (sym)->attr.allocatable))))
2654             se->expr = build_fold_indirect_ref_loc (input_location,
2655                                                 se->expr);
2656
2657           /* Dereference scalar hidden result.  */
2658           if (flag_f2c && sym->ts.type == BT_COMPLEX
2659               && (sym->attr.function || sym->attr.result)
2660               && !sym->attr.dimension && !sym->attr.pointer
2661               && !sym->attr.always_explicit)
2662             se->expr = build_fold_indirect_ref_loc (input_location,
2663                                                 se->expr);
2664
2665           /* Dereference non-character, non-class pointer variables.
2666              These must be dummies, results, or scalars.  */
2667           if (!is_classarray
2668               && (sym->attr.pointer || sym->attr.allocatable
2669                   || gfc_is_associate_pointer (sym)
2670                   || (sym->as && sym->as->type == AS_ASSUMED_RANK))
2671               && (sym->attr.dummy
2672                   || sym->attr.function
2673                   || sym->attr.result
2674                   || (!sym->attr.dimension
2675                       && (!sym->attr.codimension || !sym->attr.allocatable))))
2676             se->expr = build_fold_indirect_ref_loc (input_location,
2677                                                 se->expr);
2678           /* Now treat the class array pointer variables accordingly.  */
2679           else if (sym->ts.type == BT_CLASS
2680                    && sym->attr.dummy
2681                    && (CLASS_DATA (sym)->attr.dimension
2682                        || CLASS_DATA (sym)->attr.codimension)
2683                    && ((CLASS_DATA (sym)->as
2684                         && CLASS_DATA (sym)->as->type == AS_ASSUMED_RANK)
2685                        || CLASS_DATA (sym)->attr.allocatable
2686                        || CLASS_DATA (sym)->attr.class_pointer))
2687             se->expr = build_fold_indirect_ref_loc (input_location,
2688                                                 se->expr);
2689           /* And the case where a non-dummy, non-result, non-function,
2690              non-allotable and non-pointer classarray is present.  This case was
2691              previously covered by the first if, but with introducing the
2692              condition !is_classarray there, that case has to be covered
2693              explicitly.  */
2694           else if (sym->ts.type == BT_CLASS
2695                    && !sym->attr.dummy
2696                    && !sym->attr.function
2697                    && !sym->attr.result
2698                    && (CLASS_DATA (sym)->attr.dimension
2699                        || CLASS_DATA (sym)->attr.codimension)
2700                    && (sym->assoc
2701                        || !CLASS_DATA (sym)->attr.allocatable)
2702                    && !CLASS_DATA (sym)->attr.class_pointer)
2703             se->expr = build_fold_indirect_ref_loc (input_location,
2704                                                 se->expr);
2705         }
2706
2707       ref = expr->ref;
2708     }
2709
2710   /* For character variables, also get the length.  */
2711   if (sym->ts.type == BT_CHARACTER)
2712     {
2713       /* If the character length of an entry isn't set, get the length from
2714          the master function instead.  */
2715       if (sym->attr.entry && !sym->ts.u.cl->backend_decl)
2716         se->string_length = sym->ns->proc_name->ts.u.cl->backend_decl;
2717       else
2718         se->string_length = sym->ts.u.cl->backend_decl;
2719       gcc_assert (se->string_length);
2720     }
2721
2722   while (ref)
2723     {
2724       switch (ref->type)
2725         {
2726         case REF_ARRAY:
2727           /* Return the descriptor if that's what we want and this is an array
2728              section reference.  */
2729           if (se->descriptor_only && ref->u.ar.type != AR_ELEMENT)
2730             return;
2731 /* TODO: Pointers to single elements of array sections, eg elemental subs.  */
2732           /* Return the descriptor for array pointers and allocations.  */
2733           if (se->want_pointer
2734               && ref->next == NULL && (se->descriptor_only))
2735             return;
2736
2737           gfc_conv_array_ref (se, &ref->u.ar, expr, &expr->where);
2738           /* Return a pointer to an element.  */
2739           break;
2740
2741         case REF_COMPONENT:
2742           if (first_time && is_classarray && sym->attr.dummy
2743               && se->descriptor_only
2744               && !CLASS_DATA (sym)->attr.allocatable
2745               && !CLASS_DATA (sym)->attr.class_pointer
2746               && CLASS_DATA (sym)->as
2747               && CLASS_DATA (sym)->as->type != AS_ASSUMED_RANK
2748               && strcmp ("_data", ref->u.c.component->name) == 0)
2749             /* Skip the first ref of a _data component, because for class
2750                arrays that one is already done by introducing a temporary
2751                array descriptor.  */
2752             break;
2753
2754           if (ref->u.c.sym->attr.extension)
2755             conv_parent_component_references (se, ref);
2756
2757           gfc_conv_component_ref (se, ref);
2758           if (!ref->next && ref->u.c.sym->attr.codimension
2759               && se->want_pointer && se->descriptor_only)
2760             return;
2761
2762           break;
2763
2764         case REF_SUBSTRING:
2765           gfc_conv_substring (se, ref, expr->ts.kind,
2766                               expr->symtree->name, &expr->where);
2767           break;
2768
2769         default:
2770           gcc_unreachable ();
2771           break;
2772         }
2773       first_time = false;
2774       ref = ref->next;
2775     }
2776   /* Pointer assignment, allocation or pass by reference.  Arrays are handled
2777      separately.  */
2778   if (se->want_pointer)
2779     {
2780       if (expr->ts.type == BT_CHARACTER && !gfc_is_proc_ptr_comp (expr))
2781         gfc_conv_string_parameter (se);
2782       else
2783         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
2784     }
2785 }
2786
2787
2788 /* Unary ops are easy... Or they would be if ! was a valid op.  */
2789
2790 static void
2791 gfc_conv_unary_op (enum tree_code code, gfc_se * se, gfc_expr * expr)
2792 {
2793   gfc_se operand;
2794   tree type;
2795
2796   gcc_assert (expr->ts.type != BT_CHARACTER);
2797   /* Initialize the operand.  */
2798   gfc_init_se (&operand, se);
2799   gfc_conv_expr_val (&operand, expr->value.op.op1);
2800   gfc_add_block_to_block (&se->pre, &operand.pre);
2801
2802   type = gfc_typenode_for_spec (&expr->ts);
2803
2804   /* TRUTH_NOT_EXPR is not a "true" unary operator in GCC.
2805      We must convert it to a compare to 0 (e.g. EQ_EXPR (op1, 0)).
2806      All other unary operators have an equivalent GIMPLE unary operator.  */
2807   if (code == TRUTH_NOT_EXPR)
2808     se->expr = fold_build2_loc (input_location, EQ_EXPR, type, operand.expr,
2809                                 build_int_cst (type, 0));
2810   else
2811     se->expr = fold_build1_loc (input_location, code, type, operand.expr);
2812
2813 }
2814
2815 /* Expand power operator to optimal multiplications when a value is raised
2816    to a constant integer n. See section 4.6.3, "Evaluation of Powers" of
2817    Donald E. Knuth, "Seminumerical Algorithms", Vol. 2, "The Art of Computer
2818    Programming", 3rd Edition, 1998.  */
2819
2820 /* This code is mostly duplicated from expand_powi in the backend.
2821    We establish the "optimal power tree" lookup table with the defined size.
2822    The items in the table are the exponents used to calculate the index
2823    exponents. Any integer n less than the value can get an "addition chain",
2824    with the first node being one.  */
2825 #define POWI_TABLE_SIZE 256
2826
2827 /* The table is from builtins.c.  */
2828 static const unsigned char powi_table[POWI_TABLE_SIZE] =
2829   {
2830       0,   1,   1,   2,   2,   3,   3,   4,  /*   0 -   7 */
2831       4,   6,   5,   6,   6,  10,   7,   9,  /*   8 -  15 */
2832       8,  16,   9,  16,  10,  12,  11,  13,  /*  16 -  23 */
2833      12,  17,  13,  18,  14,  24,  15,  26,  /*  24 -  31 */
2834      16,  17,  17,  19,  18,  33,  19,  26,  /*  32 -  39 */
2835      20,  25,  21,  40,  22,  27,  23,  44,  /*  40 -  47 */
2836      24,  32,  25,  34,  26,  29,  27,  44,  /*  48 -  55 */
2837      28,  31,  29,  34,  30,  60,  31,  36,  /*  56 -  63 */
2838      32,  64,  33,  34,  34,  46,  35,  37,  /*  64 -  71 */
2839      36,  65,  37,  50,  38,  48,  39,  69,  /*  72 -  79 */
2840      40,  49,  41,  43,  42,  51,  43,  58,  /*  80 -  87 */
2841      44,  64,  45,  47,  46,  59,  47,  76,  /*  88 -  95 */
2842      48,  65,  49,  66,  50,  67,  51,  66,  /*  96 - 103 */
2843      52,  70,  53,  74,  54, 104,  55,  74,  /* 104 - 111 */
2844      56,  64,  57,  69,  58,  78,  59,  68,  /* 112 - 119 */
2845      60,  61,  61,  80,  62,  75,  63,  68,  /* 120 - 127 */
2846      64,  65,  65, 128,  66, 129,  67,  90,  /* 128 - 135 */
2847      68,  73,  69, 131,  70,  94,  71,  88,  /* 136 - 143 */
2848      72, 128,  73,  98,  74, 132,  75, 121,  /* 144 - 151 */
2849      76, 102,  77, 124,  78, 132,  79, 106,  /* 152 - 159 */
2850      80,  97,  81, 160,  82,  99,  83, 134,  /* 160 - 167 */
2851      84,  86,  85,  95,  86, 160,  87, 100,  /* 168 - 175 */
2852      88, 113,  89,  98,  90, 107,  91, 122,  /* 176 - 183 */
2853      92, 111,  93, 102,  94, 126,  95, 150,  /* 184 - 191 */
2854      96, 128,  97, 130,  98, 133,  99, 195,  /* 192 - 199 */
2855     100, 128, 101, 123, 102, 164, 103, 138,  /* 200 - 207 */
2856     104, 145, 105, 146, 106, 109, 107, 149,  /* 208 - 215 */
2857     108, 200, 109, 146, 110, 170, 111, 157,  /* 216 - 223 */
2858     112, 128, 113, 130, 114, 182, 115, 132,  /* 224 - 231 */
2859     116, 200, 117, 132, 118, 158, 119, 206,  /* 232 - 239 */
2860     120, 240, 121, 162, 122, 147, 123, 152,  /* 240 - 247 */
2861     124, 166, 125, 214, 126, 138, 127, 153,  /* 248 - 255 */
2862   };
2863
2864 /* If n is larger than lookup table's max index, we use the "window
2865    method".  */
2866 #define POWI_WINDOW_SIZE 3
2867
2868 /* Recursive function to expand the power operator. The temporary
2869    values are put in tmpvar. The function returns tmpvar[1] ** n.  */
2870 static tree
2871 gfc_conv_powi (gfc_se * se, unsigned HOST_WIDE_INT n, tree * tmpvar)
2872 {
2873   tree op0;
2874   tree op1;
2875   tree tmp;
2876   int digit;
2877
2878   if (n < POWI_TABLE_SIZE)
2879     {
2880       if (tmpvar[n])
2881         return tmpvar[n];
2882
2883       op0 = gfc_conv_powi (se, n - powi_table[n], tmpvar);
2884       op1 = gfc_conv_powi (se, powi_table[n], tmpvar);
2885     }
2886   else if (n & 1)
2887     {
2888       digit = n & ((1 << POWI_WINDOW_SIZE) - 1);
2889       op0 = gfc_conv_powi (se, n - digit, tmpvar);
2890       op1 = gfc_conv_powi (se, digit, tmpvar);
2891     }
2892   else
2893     {
2894       op0 = gfc_conv_powi (se, n >> 1, tmpvar);
2895       op1 = op0;
2896     }
2897
2898   tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (op0), op0, op1);
2899   tmp = gfc_evaluate_now (tmp, &se->pre);
2900
2901   if (n < POWI_TABLE_SIZE)
2902     tmpvar[n] = tmp;
2903
2904   return tmp;
2905 }
2906
2907
2908 /* Expand lhs ** rhs. rhs is a constant integer. If it expands successfully,
2909    return 1. Else return 0 and a call to runtime library functions
2910    will have to be built.  */
2911 static int
2912 gfc_conv_cst_int_power (gfc_se * se, tree lhs, tree rhs)
2913 {
2914   tree cond;
2915   tree tmp;
2916   tree type;
2917   tree vartmp[POWI_TABLE_SIZE];
2918   HOST_WIDE_INT m;
2919   unsigned HOST_WIDE_INT n;
2920   int sgn;
2921   wi::tree_to_wide_ref wrhs = wi::to_wide (rhs);
2922
2923   /* If exponent is too large, we won't expand it anyway, so don't bother
2924      with large integer values.  */
2925   if (!wi::fits_shwi_p (wrhs))
2926     return 0;
2927
2928   m = wrhs.to_shwi ();
2929   /* Use the wide_int's routine to reliably get the absolute value on all
2930      platforms.  Then convert it to a HOST_WIDE_INT like above.  */
2931   n = wi::abs (wrhs).to_shwi ();
2932
2933   type = TREE_TYPE (lhs);
2934   sgn = tree_int_cst_sgn (rhs);
2935
2936   if (((FLOAT_TYPE_P (type) && !flag_unsafe_math_optimizations)
2937        || optimize_size) && (m > 2 || m < -1))
2938     return 0;
2939
2940   /* rhs == 0  */
2941   if (sgn == 0)
2942     {
2943       se->expr = gfc_build_const (type, integer_one_node);
2944       return 1;
2945     }
2946
2947   /* If rhs < 0 and lhs is an integer, the result is -1, 0 or 1.  */
2948   if ((sgn == -1) && (TREE_CODE (type) == INTEGER_TYPE))
2949     {
2950       tmp = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
2951                              lhs, build_int_cst (TREE_TYPE (lhs), -1));
2952       cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
2953                               lhs, build_int_cst (TREE_TYPE (lhs), 1));
2954
2955       /* If rhs is even,
2956          result = (lhs == 1 || lhs == -1) ? 1 : 0.  */
2957       if ((n & 1) == 0)
2958         {
2959           tmp = fold_build2_loc (input_location, TRUTH_OR_EXPR,
2960                                  logical_type_node, tmp, cond);
2961           se->expr = fold_build3_loc (input_location, COND_EXPR, type,
2962                                       tmp, build_int_cst (type, 1),
2963                                       build_int_cst (type, 0));
2964           return 1;
2965         }
2966       /* If rhs is odd,
2967          result = (lhs == 1) ? 1 : (lhs == -1) ? -1 : 0.  */
2968       tmp = fold_build3_loc (input_location, COND_EXPR, type, tmp,
2969                              build_int_cst (type, -1),
2970                              build_int_cst (type, 0));
2971       se->expr = fold_build3_loc (input_location, COND_EXPR, type,
2972                                   cond, build_int_cst (type, 1), tmp);
2973       return 1;
2974     }
2975
2976   memset (vartmp, 0, sizeof (vartmp));
2977   vartmp[1] = lhs;
2978   if (sgn == -1)
2979     {
2980       tmp = gfc_build_const (type, integer_one_node);
2981       vartmp[1] = fold_build2_loc (input_location, RDIV_EXPR, type, tmp,
2982                                    vartmp[1]);
2983     }
2984
2985   se->expr = gfc_conv_powi (se, n, vartmp);
2986
2987   return 1;
2988 }
2989
2990
2991 /* Power op (**).  Constant integer exponent has special handling.  */
2992
2993 static void
2994 gfc_conv_power_op (gfc_se * se, gfc_expr * expr)
2995 {
2996   tree gfc_int4_type_node;
2997   int kind;
2998   int ikind;
2999   int res_ikind_1, res_ikind_2;
3000   gfc_se lse;
3001   gfc_se rse;
3002   tree fndecl = NULL;
3003
3004   gfc_init_se (&lse, se);
3005   gfc_conv_expr_val (&lse, expr->value.op.op1);
3006   lse.expr = gfc_evaluate_now (lse.expr, &lse.pre);
3007   gfc_add_block_to_block (&se->pre, &lse.pre);
3008
3009   gfc_init_se (&rse, se);
3010   gfc_conv_expr_val (&rse, expr->value.op.op2);
3011   gfc_add_block_to_block (&se->pre, &rse.pre);
3012
3013   if (expr->value.op.op2->ts.type == BT_INTEGER
3014       && expr->value.op.op2->expr_type == EXPR_CONSTANT)
3015     if (gfc_conv_cst_int_power (se, lse.expr, rse.expr))
3016       return;
3017
3018   gfc_int4_type_node = gfc_get_int_type (4);
3019
3020   /* In case of integer operands with kinds 1 or 2, we call the integer kind 4
3021      library routine.  But in the end, we have to convert the result back
3022      if this case applies -- with res_ikind_K, we keep track whether operand K
3023      falls into this case.  */
3024   res_ikind_1 = -1;
3025   res_ikind_2 = -1;
3026
3027   kind = expr->value.op.op1->ts.kind;
3028   switch (expr->value.op.op2->ts.type)
3029     {
3030     case BT_INTEGER:
3031       ikind = expr->value.op.op2->ts.kind;
3032       switch (ikind)
3033         {
3034         case 1:
3035         case 2:
3036           rse.expr = convert (gfc_int4_type_node, rse.expr);
3037           res_ikind_2 = ikind;
3038           /* Fall through.  */
3039
3040         case 4:
3041           ikind = 0;
3042           break;
3043
3044         case 8:
3045           ikind = 1;
3046           break;
3047
3048         case 16:
3049           ikind = 2;
3050           break;
3051
3052         default:
3053           gcc_unreachable ();
3054         }
3055       switch (kind)
3056         {
3057         case 1:
3058         case 2:
3059           if (expr->value.op.op1->ts.type == BT_INTEGER)
3060             {
3061               lse.expr = convert (gfc_int4_type_node, lse.expr);
3062               res_ikind_1 = kind;
3063             }
3064           else
3065             gcc_unreachable ();
3066           /* Fall through.  */
3067
3068         case 4:
3069           kind = 0;
3070           break;
3071
3072         case 8:
3073           kind = 1;
3074           break;
3075
3076         case 10:
3077           kind = 2;
3078           break;
3079
3080         case 16:
3081           kind = 3;
3082           break;
3083
3084         default:
3085           gcc_unreachable ();
3086         }
3087
3088       switch (expr->value.op.op1->ts.type)
3089         {
3090         case BT_INTEGER:
3091           if (kind == 3) /* Case 16 was not handled properly above.  */
3092             kind = 2;
3093           fndecl = gfor_fndecl_math_powi[kind][ikind].integer;
3094           break;
3095
3096         case BT_REAL:
3097           /* Use builtins for real ** int4.  */
3098           if (ikind == 0)
3099             {
3100               switch (kind)
3101                 {
3102                 case 0:
3103                   fndecl = builtin_decl_explicit (BUILT_IN_POWIF);
3104                   break;
3105
3106                 case 1:
3107                   fndecl = builtin_decl_explicit (BUILT_IN_POWI);
3108                   break;
3109
3110                 case 2:
3111                   fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
3112                   break;
3113
3114                 case 3:
3115                   /* Use the __builtin_powil() only if real(kind=16) is
3116                      actually the C long double type.  */
3117                   if (!gfc_real16_is_float128)
3118                     fndecl = builtin_decl_explicit (BUILT_IN_POWIL);
3119                   break;
3120
3121                 default:
3122                   gcc_unreachable ();
3123                 }
3124             }
3125
3126           /* If we don't have a good builtin for this, go for the
3127              library function.  */
3128           if (!fndecl)
3129             fndecl = gfor_fndecl_math_powi[kind][ikind].real;
3130           break;
3131
3132         case BT_COMPLEX:
3133           fndecl = gfor_fndecl_math_powi[kind][ikind].cmplx;
3134           break;
3135
3136         default:
3137           gcc_unreachable ();
3138         }
3139       break;
3140
3141     case BT_REAL:
3142       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_POW, kind);
3143       break;
3144
3145     case BT_COMPLEX:
3146       fndecl = gfc_builtin_decl_for_float_kind (BUILT_IN_CPOW, kind);
3147       break;
3148
3149     default:
3150       gcc_unreachable ();
3151       break;
3152     }
3153
3154   se->expr = build_call_expr_loc (input_location,
3155                               fndecl, 2, lse.expr, rse.expr);
3156
3157   /* Convert the result back if it is of wrong integer kind.  */
3158   if (res_ikind_1 != -1 && res_ikind_2 != -1)
3159     {
3160       /* We want the maximum of both operand kinds as result.  */
3161       if (res_ikind_1 < res_ikind_2)
3162         res_ikind_1 = res_ikind_2;
3163       se->expr = convert (gfc_get_int_type (res_ikind_1), se->expr);
3164     }
3165 }
3166
3167
3168 /* Generate code to allocate a string temporary.  */
3169
3170 tree
3171 gfc_conv_string_tmp (gfc_se * se, tree type, tree len)
3172 {
3173   tree var;
3174   tree tmp;
3175
3176   if (gfc_can_put_var_on_stack (len))
3177     {
3178       /* Create a temporary variable to hold the result.  */
3179       tmp = fold_build2_loc (input_location, MINUS_EXPR,
3180                              TREE_TYPE (len), len,
3181                              build_int_cst (TREE_TYPE (len), 1));
3182       tmp = build_range_type (gfc_charlen_type_node, size_zero_node, tmp);
3183
3184       if (TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
3185         tmp = build_array_type (TREE_TYPE (TREE_TYPE (type)), tmp);
3186       else
3187         tmp = build_array_type (TREE_TYPE (type), tmp);
3188
3189       var = gfc_create_var (tmp, "str");
3190       var = gfc_build_addr_expr (type, var);
3191     }
3192   else
3193     {
3194       /* Allocate a temporary to hold the result.  */
3195       var = gfc_create_var (type, "pstr");
3196       gcc_assert (POINTER_TYPE_P (type));
3197       tmp = TREE_TYPE (type);
3198       if (TREE_CODE (tmp) == ARRAY_TYPE)
3199         tmp = TREE_TYPE (tmp);
3200       tmp = TYPE_SIZE_UNIT (tmp);
3201       tmp = fold_build2_loc (input_location, MULT_EXPR, size_type_node,
3202                             fold_convert (size_type_node, len),
3203                             fold_convert (size_type_node, tmp));
3204       tmp = gfc_call_malloc (&se->pre, type, tmp);
3205       gfc_add_modify (&se->pre, var, tmp);
3206
3207       /* Free the temporary afterwards.  */
3208       tmp = gfc_call_free (var);
3209       gfc_add_expr_to_block (&se->post, tmp);
3210     }
3211
3212   return var;
3213 }
3214
3215
3216 /* Handle a string concatenation operation.  A temporary will be allocated to
3217    hold the result.  */
3218
3219 static void
3220 gfc_conv_concat_op (gfc_se * se, gfc_expr * expr)
3221 {
3222   gfc_se lse, rse;
3223   tree len, type, var, tmp, fndecl;
3224
3225   gcc_assert (expr->value.op.op1->ts.type == BT_CHARACTER
3226               && expr->value.op.op2->ts.type == BT_CHARACTER);
3227   gcc_assert (expr->value.op.op1->ts.kind == expr->value.op.op2->ts.kind);
3228
3229   gfc_init_se (&lse, se);
3230   gfc_conv_expr (&lse, expr->value.op.op1);
3231   gfc_conv_string_parameter (&lse);
3232   gfc_init_se (&rse, se);
3233   gfc_conv_expr (&rse, expr->value.op.op2);
3234   gfc_conv_string_parameter (&rse);
3235
3236   gfc_add_block_to_block (&se->pre, &lse.pre);
3237   gfc_add_block_to_block (&se->pre, &rse.pre);
3238
3239   type = gfc_get_character_type (expr->ts.kind, expr->ts.u.cl);
3240   len = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
3241   if (len == NULL_TREE)
3242     {
3243       len = fold_build2_loc (input_location, PLUS_EXPR,
3244                              gfc_charlen_type_node,
3245                              fold_convert (gfc_charlen_type_node,
3246                                            lse.string_length),
3247                              fold_convert (gfc_charlen_type_node,
3248                                            rse.string_length));
3249     }
3250
3251   type = build_pointer_type (type);
3252
3253   var = gfc_conv_string_tmp (se, type, len);
3254
3255   /* Do the actual concatenation.  */
3256   if (expr->ts.kind == 1)
3257     fndecl = gfor_fndecl_concat_string;
3258   else if (expr->ts.kind == 4)
3259     fndecl = gfor_fndecl_concat_string_char4;
3260   else
3261     gcc_unreachable ();
3262
3263   tmp = build_call_expr_loc (input_location,
3264                          fndecl, 6, len, var, lse.string_length, lse.expr,
3265                          rse.string_length, rse.expr);
3266   gfc_add_expr_to_block (&se->pre, tmp);
3267
3268   /* Add the cleanup for the operands.  */
3269   gfc_add_block_to_block (&se->pre, &rse.post);
3270   gfc_add_block_to_block (&se->pre, &lse.post);
3271
3272   se->expr = var;
3273   se->string_length = len;
3274 }
3275
3276 /* Translates an op expression. Common (binary) cases are handled by this
3277    function, others are passed on. Recursion is used in either case.
3278    We use the fact that (op1.ts == op2.ts) (except for the power
3279    operator **).
3280    Operators need no special handling for scalarized expressions as long as
3281    they call gfc_conv_simple_val to get their operands.
3282    Character strings get special handling.  */
3283
3284 static void
3285 gfc_conv_expr_op (gfc_se * se, gfc_expr * expr)
3286 {
3287   enum tree_code code;
3288   gfc_se lse;
3289   gfc_se rse;
3290   tree tmp, type;
3291   int lop;
3292   int checkstring;
3293
3294   checkstring = 0;
3295   lop = 0;
3296   switch (expr->value.op.op)
3297     {
3298     case INTRINSIC_PARENTHESES:
3299       if ((expr->ts.type == BT_REAL || expr->ts.type == BT_COMPLEX)
3300           && flag_protect_parens)
3301         {
3302           gfc_conv_unary_op (PAREN_EXPR, se, expr);
3303           gcc_assert (FLOAT_TYPE_P (TREE_TYPE (se->expr)));
3304           return;
3305         }
3306
3307       /* Fallthrough.  */
3308     case INTRINSIC_UPLUS:
3309       gfc_conv_expr (se, expr->value.op.op1);
3310       return;
3311
3312     case INTRINSIC_UMINUS:
3313       gfc_conv_unary_op (NEGATE_EXPR, se, expr);
3314       return;
3315
3316     case INTRINSIC_NOT:
3317       gfc_conv_unary_op (TRUTH_NOT_EXPR, se, expr);
3318       return;
3319
3320     case INTRINSIC_PLUS:
3321       code = PLUS_EXPR;
3322       break;
3323
3324     case INTRINSIC_MINUS:
3325       code = MINUS_EXPR;
3326       break;
3327
3328     case INTRINSIC_TIMES:
3329       code = MULT_EXPR;
3330       break;
3331
3332     case INTRINSIC_DIVIDE:
3333       /* If expr is a real or complex expr, use an RDIV_EXPR. If op1 is
3334          an integer, we must round towards zero, so we use a
3335          TRUNC_DIV_EXPR.  */
3336       if (expr->ts.type == BT_INTEGER)
3337         code = TRUNC_DIV_EXPR;
3338       else
3339         code = RDIV_EXPR;
3340       break;
3341
3342     case INTRINSIC_POWER:
3343       gfc_conv_power_op (se, expr);
3344       return;
3345
3346     case INTRINSIC_CONCAT:
3347       gfc_conv_concat_op (se, expr);
3348       return;
3349
3350     case INTRINSIC_AND:
3351       code = flag_frontend_optimize ? TRUTH_ANDIF_EXPR : TRUTH_AND_EXPR;
3352       lop = 1;
3353       break;
3354
3355     case INTRINSIC_OR:
3356       code = flag_frontend_optimize ? TRUTH_ORIF_EXPR : TRUTH_OR_EXPR;
3357       lop = 1;
3358       break;
3359
3360       /* EQV and NEQV only work on logicals, but since we represent them
3361          as integers, we can use EQ_EXPR and NE_EXPR for them in GIMPLE.  */
3362     case INTRINSIC_EQ:
3363     case INTRINSIC_EQ_OS:
3364     case INTRINSIC_EQV:
3365       code = EQ_EXPR;
3366       checkstring = 1;
3367       lop = 1;
3368       break;
3369
3370     case INTRINSIC_NE:
3371     case INTRINSIC_NE_OS:
3372     case INTRINSIC_NEQV:
3373       code = NE_EXPR;
3374       checkstring = 1;
3375       lop = 1;
3376       break;
3377
3378     case INTRINSIC_GT:
3379     case INTRINSIC_GT_OS:
3380       code = GT_EXPR;
3381       checkstring = 1;
3382       lop = 1;
3383       break;
3384
3385     case INTRINSIC_GE:
3386     case INTRINSIC_GE_OS:
3387       code = GE_EXPR;
3388       checkstring = 1;
3389       lop = 1;
3390       break;
3391
3392     case INTRINSIC_LT:
3393     case INTRINSIC_LT_OS:
3394       code = LT_EXPR;
3395       checkstring = 1;
3396       lop = 1;
3397       break;
3398
3399     case INTRINSIC_LE:
3400     case INTRINSIC_LE_OS:
3401       code = LE_EXPR;
3402       checkstring = 1;
3403       lop = 1;
3404       break;
3405
3406     case INTRINSIC_USER:
3407     case INTRINSIC_ASSIGN:
3408       /* These should be converted into function calls by the frontend.  */
3409       gcc_unreachable ();
3410
3411     default:
3412       fatal_error (input_location, "Unknown intrinsic op");
3413       return;
3414     }
3415
3416   /* The only exception to this is **, which is handled separately anyway.  */
3417   gcc_assert (expr->value.op.op1->ts.type == expr->value.op.op2->ts.type);
3418
3419   if (checkstring && expr->value.op.op1->ts.type != BT_CHARACTER)
3420     checkstring = 0;
3421
3422   /* lhs */
3423   gfc_init_se (&lse, se);
3424   gfc_conv_expr (&lse, expr->value.op.op1);
3425   gfc_add_block_to_block (&se->pre, &lse.pre);
3426
3427   /* rhs */
3428   gfc_init_se (&rse, se);
3429   gfc_conv_expr (&rse, expr->value.op.op2);
3430   gfc_add_block_to_block (&se->pre, &rse.pre);
3431
3432   if (checkstring)
3433     {
3434       gfc_conv_string_parameter (&lse);
3435       gfc_conv_string_parameter (&rse);
3436
3437       lse.expr = gfc_build_compare_string (lse.string_length, lse.expr,
3438                                            rse.string_length, rse.expr,
3439                                            expr->value.op.op1->ts.kind,
3440                                            code);
3441       rse.expr = build_int_cst (TREE_TYPE (lse.expr), 0);
3442       gfc_add_block_to_block (&lse.post, &rse.post);
3443     }
3444
3445   type = gfc_typenode_for_spec (&expr->ts);
3446
3447   if (lop)
3448     {
3449       /* The result of logical ops is always logical_type_node.  */
3450       tmp = fold_build2_loc (input_location, code, logical_type_node,
3451                              lse.expr, rse.expr);
3452       se->expr = convert (type, tmp);
3453     }
3454   else
3455     se->expr = fold_build2_loc (input_location, code, type, lse.expr, rse.expr);
3456
3457   /* Add the post blocks.  */
3458   gfc_add_block_to_block (&se->post, &rse.post);
3459   gfc_add_block_to_block (&se->post, &lse.post);
3460 }
3461
3462 /* If a string's length is one, we convert it to a single character.  */
3463
3464 tree
3465 gfc_string_to_single_character (tree len, tree str, int kind)
3466 {
3467
3468   if (len == NULL
3469       || !tree_fits_uhwi_p (len)
3470       || !POINTER_TYPE_P (TREE_TYPE (str)))
3471     return NULL_TREE;
3472
3473   if (TREE_INT_CST_LOW (len) == 1)
3474     {
3475       str = fold_convert (gfc_get_pchar_type (kind), str);
3476       return build_fold_indirect_ref_loc (input_location, str);
3477     }
3478
3479   if (kind == 1
3480       && TREE_CODE (str) == ADDR_EXPR
3481       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
3482       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
3483       && array_ref_low_bound (TREE_OPERAND (str, 0))
3484          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
3485       && TREE_INT_CST_LOW (len) > 1
3486       && TREE_INT_CST_LOW (len)
3487          == (unsigned HOST_WIDE_INT)
3488             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
3489     {
3490       tree ret = fold_convert (gfc_get_pchar_type (kind), str);
3491       ret = build_fold_indirect_ref_loc (input_location, ret);
3492       if (TREE_CODE (ret) == INTEGER_CST)
3493         {
3494           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
3495           int i, length = TREE_STRING_LENGTH (string_cst);
3496           const char *ptr = TREE_STRING_POINTER (string_cst);
3497
3498           for (i = 1; i < length; i++)
3499             if (ptr[i] != ' ')
3500               return NULL_TREE;
3501
3502           return ret;
3503         }
3504     }
3505
3506   return NULL_TREE;
3507 }
3508
3509
3510 void
3511 gfc_conv_scalar_char_value (gfc_symbol *sym, gfc_se *se, gfc_expr **expr)
3512 {
3513
3514   if (sym->backend_decl)
3515     {
3516       /* This becomes the nominal_type in
3517          function.c:assign_parm_find_data_types.  */
3518       TREE_TYPE (sym->backend_decl) = unsigned_char_type_node;
3519       /* This becomes the passed_type in
3520          function.c:assign_parm_find_data_types.  C promotes char to
3521          integer for argument passing.  */
3522       DECL_ARG_TYPE (sym->backend_decl) = unsigned_type_node;
3523
3524       DECL_BY_REFERENCE (sym->backend_decl) = 0;
3525     }
3526
3527   if (expr != NULL)
3528     {
3529       /* If we have a constant character expression, make it into an
3530          integer.  */
3531       if ((*expr)->expr_type == EXPR_CONSTANT)
3532         {
3533           gfc_typespec ts;
3534           gfc_clear_ts (&ts);
3535
3536           *expr = gfc_get_int_expr (gfc_default_integer_kind, NULL,
3537                                     (int)(*expr)->value.character.string[0]);
3538           if ((*expr)->ts.kind != gfc_c_int_kind)
3539             {
3540               /* The expr needs to be compatible with a C int.  If the
3541                  conversion fails, then the 2 causes an ICE.  */
3542               ts.type = BT_INTEGER;
3543               ts.kind = gfc_c_int_kind;
3544               gfc_convert_type (*expr, &ts, 2);
3545             }
3546         }
3547       else if (se != NULL && (*expr)->expr_type == EXPR_VARIABLE)
3548         {
3549           if ((*expr)->ref == NULL)
3550             {
3551               se->expr = gfc_string_to_single_character
3552                 (build_int_cst (integer_type_node, 1),
3553                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
3554                                       gfc_get_symbol_decl
3555                                       ((*expr)->symtree->n.sym)),
3556                  (*expr)->ts.kind);
3557             }
3558           else
3559             {
3560               gfc_conv_variable (se, *expr);
3561               se->expr = gfc_string_to_single_character
3562                 (build_int_cst (integer_type_node, 1),
3563                  gfc_build_addr_expr (gfc_get_pchar_type ((*expr)->ts.kind),
3564                                       se->expr),
3565                  (*expr)->ts.kind);
3566             }
3567         }
3568     }
3569 }
3570
3571 /* Helper function for gfc_build_compare_string.  Return LEN_TRIM value
3572    if STR is a string literal, otherwise return -1.  */
3573
3574 static int
3575 gfc_optimize_len_trim (tree len, tree str, int kind)
3576 {
3577   if (kind == 1
3578       && TREE_CODE (str) == ADDR_EXPR
3579       && TREE_CODE (TREE_OPERAND (str, 0)) == ARRAY_REF
3580       && TREE_CODE (TREE_OPERAND (TREE_OPERAND (str, 0), 0)) == STRING_CST
3581       && array_ref_low_bound (TREE_OPERAND (str, 0))
3582          == TREE_OPERAND (TREE_OPERAND (str, 0), 1)
3583       && tree_fits_uhwi_p (len)
3584       && tree_to_uhwi (len) >= 1
3585       && tree_to_uhwi (len)
3586          == (unsigned HOST_WIDE_INT)
3587             TREE_STRING_LENGTH (TREE_OPERAND (TREE_OPERAND (str, 0), 0)))
3588     {
3589       tree folded = fold_convert (gfc_get_pchar_type (kind), str);
3590       folded = build_fold_indirect_ref_loc (input_location, folded);
3591       if (TREE_CODE (folded) == INTEGER_CST)
3592         {
3593           tree string_cst = TREE_OPERAND (TREE_OPERAND (str, 0), 0);
3594           int length = TREE_STRING_LENGTH (string_cst);
3595           const char *ptr = TREE_STRING_POINTER (string_cst);
3596
3597           for (; length > 0; length--)
3598             if (ptr[length - 1] != ' ')
3599               break;
3600
3601           return length;
3602         }
3603     }
3604   return -1;
3605 }
3606
3607 /* Helper to build a call to memcmp.  */
3608
3609 static tree
3610 build_memcmp_call (tree s1, tree s2, tree n)
3611 {
3612   tree tmp;
3613
3614   if (!POINTER_TYPE_P (TREE_TYPE (s1)))
3615     s1 = gfc_build_addr_expr (pvoid_type_node, s1);
3616   else
3617     s1 = fold_convert (pvoid_type_node, s1);
3618
3619   if (!POINTER_TYPE_P (TREE_TYPE (s2)))
3620     s2 = gfc_build_addr_expr (pvoid_type_node, s2);
3621   else
3622     s2 = fold_convert (pvoid_type_node, s2);
3623
3624   n = fold_convert (size_type_node, n);
3625
3626   tmp = build_call_expr_loc (input_location,
3627                              builtin_decl_explicit (BUILT_IN_MEMCMP),
3628                              3, s1, s2, n);
3629
3630   return fold_convert (integer_type_node, tmp);
3631 }
3632
3633 /* Compare two strings. If they are all single characters, the result is the
3634    subtraction of them. Otherwise, we build a library call.  */
3635
3636 tree
3637 gfc_build_compare_string (tree len1, tree str1, tree len2, tree str2, int kind,
3638                           enum tree_code code)
3639 {
3640   tree sc1;
3641   tree sc2;
3642   tree fndecl;
3643
3644   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str1)));
3645   gcc_assert (POINTER_TYPE_P (TREE_TYPE (str2)));
3646
3647   sc1 = gfc_string_to_single_character (len1, str1, kind);
3648   sc2 = gfc_string_to_single_character (len2, str2, kind);
3649
3650   if (sc1 != NULL_TREE && sc2 != NULL_TREE)
3651     {
3652       /* Deal with single character specially.  */
3653       sc1 = fold_convert (integer_type_node, sc1);
3654       sc2 = fold_convert (integer_type_node, sc2);
3655       return fold_build2_loc (input_location, MINUS_EXPR, integer_type_node,
3656                               sc1, sc2);
3657     }
3658
3659   if ((code == EQ_EXPR || code == NE_EXPR)
3660       && optimize
3661       && INTEGER_CST_P (len1) && INTEGER_CST_P (len2))
3662     {
3663       /* If one string is a string literal with LEN_TRIM longer
3664          than the length of the second string, the strings
3665          compare unequal.  */
3666       int len = gfc_optimize_len_trim (len1, str1, kind);
3667       if (len > 0 && compare_tree_int (len2, len) < 0)
3668         return integer_one_node;
3669       len = gfc_optimize_len_trim (len2, str2, kind);
3670       if (len > 0 && compare_tree_int (len1, len) < 0)
3671         return integer_one_node;
3672     }
3673
3674   /* We can compare via memcpy if the strings are known to be equal
3675      in length and they are
3676      - kind=1
3677      - kind=4 and the comparison is for (in)equality.  */
3678
3679   if (INTEGER_CST_P (len1) && INTEGER_CST_P (len2)
3680       && tree_int_cst_equal (len1, len2)
3681       && (kind == 1 || code == EQ_EXPR || code == NE_EXPR))
3682     {
3683       tree tmp;
3684       tree chartype;
3685
3686       chartype = gfc_get_char_type (kind);
3687       tmp = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE(len1),
3688                              fold_convert (TREE_TYPE(len1),
3689                                            TYPE_SIZE_UNIT(chartype)),
3690                              len1);
3691       return build_memcmp_call (str1, str2, tmp);
3692     }
3693
3694   /* Build a call for the comparison.  */
3695   if (kind == 1)
3696     fndecl = gfor_fndecl_compare_string;
3697   else if (kind == 4)
3698     fndecl = gfor_fndecl_compare_string_char4;
3699   else
3700     gcc_unreachable ();
3701
3702   return build_call_expr_loc (input_location, fndecl, 4,
3703                               len1, str1, len2, str2);
3704 }
3705
3706
3707 /* Return the backend_decl for a procedure pointer component.  */
3708
3709 static tree
3710 get_proc_ptr_comp (gfc_expr *e)
3711 {
3712   gfc_se comp_se;
3713   gfc_expr *e2;
3714   expr_t old_type;
3715
3716   gfc_init_se (&comp_se, NULL);
3717   e2 = gfc_copy_expr (e);
3718   /* We have to restore the expr type later so that gfc_free_expr frees
3719      the exact same thing that was allocated.
3720      TODO: This is ugly.  */
3721   old_type = e2->expr_type;
3722   e2->expr_type = EXPR_VARIABLE;
3723   gfc_conv_expr (&comp_se, e2);
3724   e2->expr_type = old_type;
3725   gfc_free_expr (e2);
3726   return build_fold_addr_expr_loc (input_location, comp_se.expr);
3727 }
3728
3729
3730 /* Convert a typebound function reference from a class object.  */
3731 static void
3732 conv_base_obj_fcn_val (gfc_se * se, tree base_object, gfc_expr * expr)
3733 {
3734   gfc_ref *ref;
3735   tree var;
3736
3737   if (!VAR_P (base_object))
3738     {
3739       var = gfc_create_var (TREE_TYPE (base_object), NULL);
3740       gfc_add_modify (&se->pre, var, base_object);
3741     }
3742   se->expr = gfc_class_vptr_get (base_object);
3743   se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
3744   ref = expr->ref;
3745   while (ref && ref->next)
3746     ref = ref->next;
3747   gcc_assert (ref && ref->type == REF_COMPONENT);
3748   if (ref->u.c.sym->attr.extension)
3749     conv_parent_component_references (se, ref);
3750   gfc_conv_component_ref (se, ref);
3751   se->expr = build_fold_addr_expr_loc (input_location, se->expr);
3752 }
3753
3754
3755 static void
3756 conv_function_val (gfc_se * se, gfc_symbol * sym, gfc_expr * expr)
3757 {
3758   tree tmp;
3759
3760   if (gfc_is_proc_ptr_comp (expr))
3761     tmp = get_proc_ptr_comp (expr);
3762   else if (sym->attr.dummy)
3763     {
3764       tmp = gfc_get_symbol_decl (sym);
3765       if (sym->attr.proc_pointer)
3766         tmp = build_fold_indirect_ref_loc (input_location,
3767                                        tmp);
3768       gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == POINTER_TYPE
3769               && TREE_CODE (TREE_TYPE (TREE_TYPE (tmp))) == FUNCTION_TYPE);
3770     }
3771   else
3772     {
3773       if (!sym->backend_decl)
3774         sym->backend_decl = gfc_get_extern_function_decl (sym);
3775
3776       TREE_USED (sym->backend_decl) = 1;
3777
3778       tmp = sym->backend_decl;
3779
3780       if (sym->attr.cray_pointee)
3781         {
3782           /* TODO - make the cray pointee a pointer to a procedure,
3783              assign the pointer to it and use it for the call.  This
3784              will do for now!  */
3785           tmp = convert (build_pointer_type (TREE_TYPE (tmp)),
3786                          gfc_get_symbol_decl (sym->cp_pointer));
3787           tmp = gfc_evaluate_now (tmp, &se->pre);
3788         }
3789
3790       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
3791         {
3792           gcc_assert (TREE_CODE (tmp) == FUNCTION_DECL);
3793           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
3794         }
3795     }
3796   se->expr = tmp;
3797 }
3798
3799
3800 /* Initialize MAPPING.  */
3801
3802 void
3803 gfc_init_interface_mapping (gfc_interface_mapping * mapping)
3804 {
3805   mapping->syms = NULL;
3806   mapping->charlens = NULL;
3807 }
3808
3809
3810 /* Free all memory held by MAPPING (but not MAPPING itself).  */
3811
3812 void
3813 gfc_free_interface_mapping (gfc_interface_mapping * mapping)
3814 {
3815   gfc_interface_sym_mapping *sym;
3816   gfc_interface_sym_mapping *nextsym;
3817   gfc_charlen *cl;
3818   gfc_charlen *nextcl;
3819
3820   for (sym = mapping->syms; sym; sym = nextsym)
3821     {
3822       nextsym = sym->next;
3823       sym->new_sym->n.sym->formal = NULL;
3824       gfc_free_symbol (sym->new_sym->n.sym);
3825       gfc_free_expr (sym->expr);
3826       free (sym->new_sym);
3827       free (sym);
3828     }
3829   for (cl = mapping->charlens; cl; cl = nextcl)
3830     {
3831       nextcl = cl->next;
3832       gfc_free_expr (cl->length);
3833       free (cl);
3834     }
3835 }
3836
3837
3838 /* Return a copy of gfc_charlen CL.  Add the returned structure to
3839    MAPPING so that it will be freed by gfc_free_interface_mapping.  */
3840
3841 static gfc_charlen *
3842 gfc_get_interface_mapping_charlen (gfc_interface_mapping * mapping,
3843                                    gfc_charlen * cl)
3844 {
3845   gfc_charlen *new_charlen;
3846
3847   new_charlen = gfc_get_charlen ();
3848   new_charlen->next = mapping->charlens;
3849   new_charlen->length = gfc_copy_expr (cl->length);
3850
3851   mapping->charlens = new_charlen;
3852   return new_charlen;
3853 }
3854
3855
3856 /* A subroutine of gfc_add_interface_mapping.  Return a descriptorless
3857    array variable that can be used as the actual argument for dummy
3858    argument SYM.  Add any initialization code to BLOCK.  PACKED is as
3859    for gfc_get_nodesc_array_type and DATA points to the first element
3860    in the passed array.  */
3861
3862 static tree
3863 gfc_get_interface_mapping_array (stmtblock_t * block, gfc_symbol * sym,
3864                                  gfc_packed packed, tree data)
3865 {
3866   tree type;
3867   tree var;
3868
3869   type = gfc_typenode_for_spec (&sym->ts);
3870   type = gfc_get_nodesc_array_type (type, sym->as, packed,
3871                                     !sym->attr.target && !sym->attr.pointer
3872                                     && !sym->attr.proc_pointer);
3873
3874   var = gfc_create_var (type, "ifm");
3875   gfc_add_modify (block, var, fold_convert (type, data));
3876
3877   return var;
3878 }
3879
3880
3881 /* A subroutine of gfc_add_interface_mapping.  Set the stride, upper bounds
3882    and offset of descriptorless array type TYPE given that it has the same
3883    size as DESC.  Add any set-up code to BLOCK.  */
3884
3885 static void
3886 gfc_set_interface_mapping_bounds (stmtblock_t * block, tree type, tree desc)
3887 {
3888   int n;
3889   tree dim;
3890   tree offset;
3891   tree tmp;
3892
3893   offset = gfc_index_zero_node;
3894   for (n = 0; n < GFC_TYPE_ARRAY_RANK (type); n++)
3895     {
3896       dim = gfc_rank_cst[n];
3897       GFC_TYPE_ARRAY_STRIDE (type, n) = gfc_conv_array_stride (desc, n);
3898       if (GFC_TYPE_ARRAY_LBOUND (type, n) == NULL_TREE)
3899         {
3900           GFC_TYPE_ARRAY_LBOUND (type, n)
3901                 = gfc_conv_descriptor_lbound_get (desc, dim);
3902           GFC_TYPE_ARRAY_UBOUND (type, n)
3903                 = gfc_conv_descriptor_ubound_get (desc, dim);
3904         }
3905       else if (GFC_TYPE_ARRAY_UBOUND (type, n) == NULL_TREE)
3906         {
3907           tmp = fold_build2_loc (input_location, MINUS_EXPR,
3908                                  gfc_array_index_type,
3909                                  gfc_conv_descriptor_ubound_get (desc, dim),
3910                                  gfc_conv_descriptor_lbound_get (desc, dim));
3911           tmp = fold_build2_loc (input_location, PLUS_EXPR,
3912                                  gfc_array_index_type,
3913                                  GFC_TYPE_ARRAY_LBOUND (type, n), tmp);
3914           tmp = gfc_evaluate_now (tmp, block);
3915           GFC_TYPE_ARRAY_UBOUND (type, n) = tmp;
3916         }
3917       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
3918                              GFC_TYPE_ARRAY_LBOUND (type, n),
3919                              GFC_TYPE_ARRAY_STRIDE (type, n));
3920       offset = fold_build2_loc (input_location, MINUS_EXPR,
3921                                 gfc_array_index_type, offset, tmp);
3922     }
3923   offset = gfc_evaluate_now (offset, block);
3924   GFC_TYPE_ARRAY_OFFSET (type) = offset;
3925 }
3926
3927
3928 /* Extend MAPPING so that it maps dummy argument SYM to the value stored
3929    in SE.  The caller may still use se->expr and se->string_length after
3930    calling this function.  */
3931
3932 void
3933 gfc_add_interface_mapping (gfc_interface_mapping * mapping,
3934                            gfc_symbol * sym, gfc_se * se,
3935                            gfc_expr *expr)
3936 {
3937   gfc_interface_sym_mapping *sm;
3938   tree desc;
3939   tree tmp;
3940   tree value;
3941   gfc_symbol *new_sym;
3942   gfc_symtree *root;
3943   gfc_symtree *new_symtree;
3944
3945   /* Create a new symbol to represent the actual argument.  */
3946   new_sym = gfc_new_symbol (sym->name, NULL);
3947   new_sym->ts = sym->ts;
3948   new_sym->as = gfc_copy_array_spec (sym->as);
3949   new_sym->attr.referenced = 1;
3950   new_sym->attr.dimension = sym->attr.dimension;
3951   new_sym->attr.contiguous = sym->attr.contiguous;
3952   new_sym->attr.codimension = sym->attr.codimension;
3953   new_sym->attr.pointer = sym->attr.pointer;
3954   new_sym->attr.allocatable = sym->attr.allocatable;
3955   new_sym->attr.flavor = sym->attr.flavor;
3956   new_sym->attr.function = sym->attr.function;
3957
3958   /* Ensure that the interface is available and that
3959      descriptors are passed for array actual arguments.  */
3960   if (sym->attr.flavor == FL_PROCEDURE)
3961     {
3962       new_sym->formal = expr->symtree->n.sym->formal;
3963       new_sym->attr.always_explicit
3964             = expr->symtree->n.sym->attr.always_explicit;
3965     }
3966
3967   /* Create a fake symtree for it.  */
3968   root = NULL;
3969   new_symtree = gfc_new_symtree (&root, sym->name);
3970   new_symtree->n.sym = new_sym;
3971   gcc_assert (new_symtree == root);
3972
3973   /* Create a dummy->actual mapping.  */
3974   sm = XCNEW (gfc_interface_sym_mapping);
3975   sm->next = mapping->syms;
3976   sm->old = sym;
3977   sm->new_sym = new_symtree;
3978   sm->expr = gfc_copy_expr (expr);
3979   mapping->syms = sm;
3980
3981   /* Stabilize the argument's value.  */
3982   if (!sym->attr.function && se)
3983     se->expr = gfc_evaluate_now (se->expr, &se->pre);
3984
3985   if (sym->ts.type == BT_CHARACTER)
3986     {
3987       /* Create a copy of the dummy argument's length.  */
3988       new_sym->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, sym->ts.u.cl);
3989       sm->expr->ts.u.cl = new_sym->ts.u.cl;
3990
3991       /* If the length is specified as "*", record the length that
3992          the caller is passing.  We should use the callee's length
3993          in all other cases.  */
3994       if (!new_sym->ts.u.cl->length && se)
3995         {
3996           se->string_length = gfc_evaluate_now (se->string_length, &se->pre);
3997           new_sym->ts.u.cl->backend_decl = se->string_length;
3998         }
3999     }
4000
4001   if (!se)
4002     return;
4003
4004   /* Use the passed value as-is if the argument is a function.  */
4005   if (sym->attr.flavor == FL_PROCEDURE)
4006     value = se->expr;
4007
4008   /* If the argument is a pass-by-value scalar, use the value as is.  */
4009   else if (!sym->attr.dimension && sym->attr.value)
4010     value = se->expr;
4011
4012   /* If the argument is either a string or a pointer to a string,
4013      convert it to a boundless character type.  */
4014   else if (!sym->attr.dimension && sym->ts.type == BT_CHARACTER)
4015     {
4016       tmp = gfc_get_character_type_len (sym->ts.kind, NULL);
4017       tmp = build_pointer_type (tmp);
4018       if (sym->attr.pointer)
4019         value = build_fold_indirect_ref_loc (input_location,
4020                                          se->expr);
4021       else
4022         value = se->expr;
4023       value = fold_convert (tmp, value);
4024     }
4025
4026   /* If the argument is a scalar, a pointer to an array or an allocatable,
4027      dereference it.  */
4028   else if (!sym->attr.dimension || sym->attr.pointer || sym->attr.allocatable)
4029     value = build_fold_indirect_ref_loc (input_location,
4030                                      se->expr);
4031
4032   /* For character(*), use the actual argument's descriptor.  */
4033   else if (sym->ts.type == BT_CHARACTER && !new_sym->ts.u.cl->length)
4034     value = build_fold_indirect_ref_loc (input_location,
4035                                      se->expr);
4036
4037   /* If the argument is an array descriptor, use it to determine
4038      information about the actual argument's shape.  */
4039   else if (POINTER_TYPE_P (TREE_TYPE (se->expr))
4040            && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se->expr))))
4041     {
4042       /* Get the actual argument's descriptor.  */
4043       desc = build_fold_indirect_ref_loc (input_location,
4044                                       se->expr);
4045
4046       /* Create the replacement variable.  */
4047       tmp = gfc_conv_descriptor_data_get (desc);
4048       value = gfc_get_interface_mapping_array (&se->pre, sym,
4049                                                PACKED_NO, tmp);
4050
4051       /* Use DESC to work out the upper bounds, strides and offset.  */
4052       gfc_set_interface_mapping_bounds (&se->pre, TREE_TYPE (value), desc);
4053     }
4054   else
4055     /* Otherwise we have a packed array.  */
4056     value = gfc_get_interface_mapping_array (&se->pre, sym,
4057                                              PACKED_FULL, se->expr);
4058
4059   new_sym->backend_decl = value;
4060 }
4061
4062
4063 /* Called once all dummy argument mappings have been added to MAPPING,
4064    but before the mapping is used to evaluate expressions.  Pre-evaluate
4065    the length of each argument, adding any initialization code to PRE and
4066    any finalization code to POST.  */
4067
4068 void
4069 gfc_finish_interface_mapping (gfc_interface_mapping * mapping,
4070                               stmtblock_t * pre, stmtblock_t * post)
4071 {
4072   gfc_interface_sym_mapping *sym;
4073   gfc_expr *expr;
4074   gfc_se se;
4075
4076   for (sym = mapping->syms; sym; sym = sym->next)
4077     if (sym->new_sym->n.sym->ts.type == BT_CHARACTER
4078         && !sym->new_sym->n.sym->ts.u.cl->backend_decl)
4079       {
4080         expr = sym->new_sym->n.sym->ts.u.cl->length;
4081         gfc_apply_interface_mapping_to_expr (mapping, expr);
4082         gfc_init_se (&se, NULL);
4083         gfc_conv_expr (&se, expr);
4084         se.expr = fold_convert (gfc_charlen_type_node, se.expr);
4085         se.expr = gfc_evaluate_now (se.expr, &se.pre);
4086         gfc_add_block_to_block (pre, &se.pre);
4087         gfc_add_block_to_block (post, &se.post);
4088
4089         sym->new_sym->n.sym->ts.u.cl->backend_decl = se.expr;
4090       }
4091 }
4092
4093
4094 /* Like gfc_apply_interface_mapping_to_expr, but applied to
4095    constructor C.  */
4096
4097 static void
4098 gfc_apply_interface_mapping_to_cons (gfc_interface_mapping * mapping,
4099                                      gfc_constructor_base base)
4100 {
4101   gfc_constructor *c;
4102   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
4103     {
4104       gfc_apply_interface_mapping_to_expr (mapping, c->expr);
4105       if (c->iterator)
4106         {
4107           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->start);
4108           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->end);
4109           gfc_apply_interface_mapping_to_expr (mapping, c->iterator->step);
4110         }
4111     }
4112 }
4113
4114
4115 /* Like gfc_apply_interface_mapping_to_expr, but applied to
4116    reference REF.  */
4117
4118 static void
4119 gfc_apply_interface_mapping_to_ref (gfc_interface_mapping * mapping,
4120                                     gfc_ref * ref)
4121 {
4122   int n;
4123
4124   for (; ref; ref = ref->next)
4125     switch (ref->type)
4126       {
4127       case REF_ARRAY:
4128         for (n = 0; n < ref->u.ar.dimen; n++)
4129           {
4130             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.start[n]);
4131             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.end[n]);
4132             gfc_apply_interface_mapping_to_expr (mapping, ref->u.ar.stride[n]);
4133           }
4134         break;
4135
4136       case REF_COMPONENT:
4137         break;
4138
4139       case REF_SUBSTRING:
4140         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.start);
4141         gfc_apply_interface_mapping_to_expr (mapping, ref->u.ss.end);
4142         break;
4143       }
4144 }
4145
4146
4147 /* Convert intrinsic function calls into result expressions.  */
4148
4149 static bool
4150 gfc_map_intrinsic_function (gfc_expr *expr, gfc_interface_mapping *mapping)
4151 {
4152   gfc_symbol *sym;
4153   gfc_expr *new_expr;
4154   gfc_expr *arg1;
4155   gfc_expr *arg2;
4156   int d, dup;
4157
4158   arg1 = expr->value.function.actual->expr;
4159   if (expr->value.function.actual->next)
4160     arg2 = expr->value.function.actual->next->expr;
4161   else
4162     arg2 = NULL;
4163
4164   sym = arg1->symtree->n.sym;
4165
4166   if (sym->attr.dummy)
4167     return false;
4168
4169   new_expr = NULL;
4170
4171   switch (expr->value.function.isym->id)
4172     {
4173     case GFC_ISYM_LEN:
4174       /* TODO figure out why this condition is necessary.  */
4175       if (sym->attr.function
4176           && (arg1->ts.u.cl->length == NULL
4177               || (arg1->ts.u.cl->length->expr_type != EXPR_CONSTANT
4178                   && arg1->ts.u.cl->length->expr_type != EXPR_VARIABLE)))
4179         return false;
4180
4181       new_expr = gfc_copy_expr (arg1->ts.u.cl->length);
4182       break;
4183
4184     case GFC_ISYM_LEN_TRIM:
4185       new_expr = gfc_copy_expr (arg1);
4186       gfc_apply_interface_mapping_to_expr (mapping, new_expr);
4187
4188       if (!new_expr)
4189         return false;
4190
4191       gfc_replace_expr (arg1, new_expr);
4192       return true;
4193
4194     case GFC_ISYM_SIZE:
4195       if (!sym->as || sym->as->rank == 0)
4196         return false;
4197
4198       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
4199         {
4200           dup = mpz_get_si (arg2->value.integer);
4201           d = dup - 1;
4202         }
4203       else
4204         {
4205           dup = sym->as->rank;
4206           d = 0;
4207         }
4208
4209       for (; d < dup; d++)
4210         {
4211           gfc_expr *tmp;
4212
4213           if (!sym->as->upper[d] || !sym->as->lower[d])
4214             {
4215               gfc_free_expr (new_expr);
4216               return false;
4217             }
4218
4219           tmp = gfc_add (gfc_copy_expr (sym->as->upper[d]),
4220                                         gfc_get_int_expr (gfc_default_integer_kind,
4221                                                           NULL, 1));
4222           tmp = gfc_subtract (tmp, gfc_copy_expr (sym->as->lower[d]));
4223           if (new_expr)
4224             new_expr = gfc_multiply (new_expr, tmp);
4225           else
4226             new_expr = tmp;
4227         }
4228       break;
4229
4230     case GFC_ISYM_LBOUND:
4231     case GFC_ISYM_UBOUND:
4232         /* TODO These implementations of lbound and ubound do not limit if
4233            the size < 0, according to F95's 13.14.53 and 13.14.113.  */
4234
4235       if (!sym->as || sym->as->rank == 0)
4236         return false;
4237
4238       if (arg2 && arg2->expr_type == EXPR_CONSTANT)
4239         d = mpz_get_si (arg2->value.integer) - 1;
4240       else
4241         return false;
4242
4243       if (expr->value.function.isym->id == GFC_ISYM_LBOUND)
4244         {
4245           if (sym->as->lower[d])
4246             new_expr = gfc_copy_expr (sym->as->lower[d]);
4247         }
4248       else
4249         {
4250           if (sym->as->upper[d])
4251             new_expr = gfc_copy_expr (sym->as->upper[d]);
4252         }
4253       break;
4254
4255     default:
4256       break;
4257     }
4258
4259   gfc_apply_interface_mapping_to_expr (mapping, new_expr);
4260   if (!new_expr)
4261     return false;
4262
4263   gfc_replace_expr (expr, new_expr);
4264   return true;
4265 }
4266
4267
4268 static void
4269 gfc_map_fcn_formal_to_actual (gfc_expr *expr, gfc_expr *map_expr,
4270                               gfc_interface_mapping * mapping)
4271 {
4272   gfc_formal_arglist *f;
4273   gfc_actual_arglist *actual;
4274
4275   actual = expr->value.function.actual;
4276   f = gfc_sym_get_dummy_args (map_expr->symtree->n.sym);
4277
4278   for (; f && actual; f = f->next, actual = actual->next)
4279     {
4280       if (!actual->expr)
4281         continue;
4282
4283       gfc_add_interface_mapping (mapping, f->sym, NULL, actual->expr);
4284     }
4285
4286   if (map_expr->symtree->n.sym->attr.dimension)
4287     {
4288       int d;
4289       gfc_array_spec *as;
4290
4291       as = gfc_copy_array_spec (map_expr->symtree->n.sym->as);
4292
4293       for (d = 0; d < as->rank; d++)
4294         {
4295           gfc_apply_interface_mapping_to_expr (mapping, as->lower[d]);
4296           gfc_apply_interface_mapping_to_expr (mapping, as->upper[d]);
4297         }
4298
4299       expr->value.function.esym->as = as;
4300     }
4301
4302   if (map_expr->symtree->n.sym->ts.type == BT_CHARACTER)
4303     {
4304       expr->value.function.esym->ts.u.cl->length
4305         = gfc_copy_expr (map_expr->symtree->n.sym->ts.u.cl->length);
4306
4307       gfc_apply_interface_mapping_to_expr (mapping,
4308                         expr->value.function.esym->ts.u.cl->length);
4309     }
4310 }
4311
4312
4313 /* EXPR is a copy of an expression that appeared in the interface
4314    associated with MAPPING.  Walk it recursively looking for references to
4315    dummy arguments that MAPPING maps to actual arguments.  Replace each such
4316    reference with a reference to the associated actual argument.  */
4317
4318 static void
4319 gfc_apply_interface_mapping_to_expr (gfc_interface_mapping * mapping,
4320                                      gfc_expr * expr)
4321 {
4322   gfc_interface_sym_mapping *sym;
4323   gfc_actual_arglist *actual;
4324
4325   if (!expr)
4326     return;
4327
4328   /* Copying an expression does not copy its length, so do that here.  */
4329   if (expr->ts.type == BT_CHARACTER && expr->ts.u.cl)
4330     {
4331       expr->ts.u.cl = gfc_get_interface_mapping_charlen (mapping, expr->ts.u.cl);
4332       gfc_apply_interface_mapping_to_expr (mapping, expr->ts.u.cl->length);
4333     }
4334
4335   /* Apply the mapping to any references.  */
4336   gfc_apply_interface_mapping_to_ref (mapping, expr->ref);
4337
4338   /* ...and to the expression's symbol, if it has one.  */
4339   /* TODO Find out why the condition on expr->symtree had to be moved into
4340      the loop rather than being outside it, as originally.  */
4341   for (sym = mapping->syms; sym; sym = sym->next)
4342     if (expr->symtree && sym->old == expr->symtree->n.sym)
4343       {
4344         if (sym->new_sym->n.sym->backend_decl)
4345           expr->symtree = sym->new_sym;
4346         else if (sym->expr)
4347           gfc_replace_expr (expr, gfc_copy_expr (sym->expr));
4348       }
4349
4350       /* ...and to subexpressions in expr->value.  */
4351   switch (expr->expr_type)
4352     {
4353     case EXPR_VARIABLE:
4354     case EXPR_CONSTANT:
4355     case EXPR_NULL:
4356     case EXPR_SUBSTRING:
4357       break;
4358
4359     case EXPR_OP:
4360       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op1);
4361       gfc_apply_interface_mapping_to_expr (mapping, expr->value.op.op2);
4362       break;
4363
4364     case EXPR_FUNCTION:
4365       for (actual = expr->value.function.actual; actual; actual = actual->next)
4366         gfc_apply_interface_mapping_to_expr (mapping, actual->expr);
4367
4368       if (expr->value.function.esym == NULL
4369             && expr->value.function.isym != NULL
4370             && expr->value.function.actual
4371             && expr->value.function.actual->expr
4372             && expr->value.function.actual->expr->symtree
4373             && gfc_map_intrinsic_function (expr, mapping))
4374         break;
4375
4376       for (sym = mapping->syms; sym; sym = sym->next)
4377         if (sym->old == expr->value.function.esym)
4378           {
4379             expr->value.function.esym = sym->new_sym->n.sym;
4380             gfc_map_fcn_formal_to_actual (expr, sym->expr, mapping);
4381             expr->value.function.esym->result = sym->new_sym->n.sym;
4382           }
4383       break;
4384
4385     case EXPR_ARRAY:
4386     case EXPR_STRUCTURE:
4387       gfc_apply_interface_mapping_to_cons (mapping, expr->value.constructor);
4388       break;
4389
4390     case EXPR_COMPCALL:
4391     case EXPR_PPC:
4392       gcc_unreachable ();
4393       break;
4394     }
4395
4396   return;
4397 }
4398
4399
4400 /* Evaluate interface expression EXPR using MAPPING.  Store the result
4401    in SE.  */
4402
4403 void
4404 gfc_apply_interface_mapping (gfc_interface_mapping * mapping,
4405                              gfc_se * se, gfc_expr * expr)
4406 {
4407   expr = gfc_copy_expr (expr);
4408   gfc_apply_interface_mapping_to_expr (mapping, expr);
4409   gfc_conv_expr (se, expr);
4410   se->expr = gfc_evaluate_now (se->expr, &se->pre);
4411   gfc_free_expr (expr);
4412 }
4413
4414
4415 /* Returns a reference to a temporary array into which a component of
4416    an actual argument derived type array is copied and then returned
4417    after the function call.  */
4418 void
4419 gfc_conv_subref_array_arg (gfc_se * parmse, gfc_expr * expr, int g77,
4420                            sym_intent intent, bool formal_ptr)
4421 {
4422   gfc_se lse;
4423   gfc_se rse;
4424   gfc_ss *lss;
4425   gfc_ss *rss;
4426   gfc_loopinfo loop;
4427   gfc_loopinfo loop2;
4428   gfc_array_info *info;
4429   tree offset;
4430   tree tmp_index;
4431   tree tmp;
4432   tree base_type;
4433   tree size;
4434   stmtblock_t body;
4435   int n;
4436   int dimen;
4437
4438   gfc_init_se (&lse, NULL);
4439   gfc_init_se (&rse, NULL);
4440
4441   /* Walk the argument expression.  */
4442   rss = gfc_walk_expr (expr);
4443
4444   gcc_assert (rss != gfc_ss_terminator);
4445
4446   /* Initialize the scalarizer.  */
4447   gfc_init_loopinfo (&loop);
4448   gfc_add_ss_to_loop (&loop, rss);
4449
4450   /* Calculate the bounds of the scalarization.  */
4451   gfc_conv_ss_startstride (&loop);
4452
4453   /* Build an ss for the temporary.  */
4454   if (expr->ts.type == BT_CHARACTER && !expr->ts.u.cl->backend_decl)
4455     gfc_conv_string_length (expr->ts.u.cl, expr, &parmse->pre);
4456
4457   base_type = gfc_typenode_for_spec (&expr->ts);
4458   if (GFC_ARRAY_TYPE_P (base_type)
4459                 || GFC_DESCRIPTOR_TYPE_P (base_type))
4460     base_type = gfc_get_element_type (base_type);
4461
4462   if (expr->ts.type == BT_CLASS)
4463     base_type = gfc_typenode_for_spec (&CLASS_DATA (expr)->ts);
4464
4465   loop.temp_ss = gfc_get_temp_ss (base_type, ((expr->ts.type == BT_CHARACTER)
4466                                               ? expr->ts.u.cl->backend_decl
4467                                               : NULL),
4468                                   loop.dimen);
4469
4470   parmse->string_length = loop.temp_ss->info->string_length;
4471
4472   /* Associate the SS with the loop.  */
4473   gfc_add_ss_to_loop (&loop, loop.temp_ss);
4474
4475   /* Setup the scalarizing loops.  */
4476   gfc_conv_loop_setup (&loop, &expr->where);
4477
4478   /* Pass the temporary descriptor back to the caller.  */
4479   info = &loop.temp_ss->info->data.array;
4480   parmse->expr = info->descriptor;
4481
4482   /* Setup the gfc_se structures.  */
4483   gfc_copy_loopinfo_to_se (&lse, &loop);
4484   gfc_copy_loopinfo_to_se (&rse, &loop);
4485
4486   rse.ss = rss;
4487   lse.ss = loop.temp_ss;
4488   gfc_mark_ss_chain_used (rss, 1);
4489   gfc_mark_ss_chain_used (loop.temp_ss, 1);
4490
4491   /* Start the scalarized loop body.  */
4492   gfc_start_scalarized_body (&loop, &body);
4493
4494   /* Translate the expression.  */
4495   gfc_conv_expr (&rse, expr);
4496
4497   /* Reset the offset for the function call since the loop
4498      is zero based on the data pointer.  Note that the temp
4499      comes first in the loop chain since it is added second.  */
4500   if (gfc_is_class_array_function (expr))
4501     {
4502       tmp = loop.ss->loop_chain->info->data.array.descriptor;
4503       gfc_conv_descriptor_offset_set (&loop.pre, tmp,
4504                                       gfc_index_zero_node);
4505     }
4506
4507   gfc_conv_tmp_array_ref (&lse);
4508
4509   if (intent != INTENT_OUT)
4510     {
4511       tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, false);
4512       gfc_add_expr_to_block (&body, tmp);
4513       gcc_assert (rse.ss == gfc_ss_terminator);
4514       gfc_trans_scalarizing_loops (&loop, &body);
4515     }
4516   else
4517     {
4518       /* Make sure that the temporary declaration survives by merging
4519        all the loop declarations into the current context.  */
4520       for (n = 0; n < loop.dimen; n++)
4521         {
4522           gfc_merge_block_scope (&body);
4523           body = loop.code[loop.order[n]];
4524         }
4525       gfc_merge_block_scope (&body);
4526     }
4527
4528   /* Add the post block after the second loop, so that any
4529      freeing of allocated memory is done at the right time.  */
4530   gfc_add_block_to_block (&parmse->pre, &loop.pre);
4531
4532   /**********Copy the temporary back again.*********/
4533
4534   gfc_init_se (&lse, NULL);
4535   gfc_init_se (&rse, NULL);
4536
4537   /* Walk the argument expression.  */
4538   lss = gfc_walk_expr (expr);
4539   rse.ss = loop.temp_ss;
4540   lse.ss = lss;
4541
4542   /* Initialize the scalarizer.  */
4543   gfc_init_loopinfo (&loop2);
4544   gfc_add_ss_to_loop (&loop2, lss);
4545
4546   dimen = rse.ss->dimen;
4547
4548   /* Skip the write-out loop for this case.  */
4549   if (gfc_is_class_array_function (expr))
4550     goto class_array_fcn;
4551
4552   /* Calculate the bounds of the scalarization.  */
4553   gfc_conv_ss_startstride (&loop2);
4554
4555   /* Setup the scalarizing loops.  */
4556   gfc_conv_loop_setup (&loop2, &expr->where);
4557
4558   gfc_copy_loopinfo_to_se (&lse, &loop2);
4559   gfc_copy_loopinfo_to_se (&rse, &loop2);
4560
4561   gfc_mark_ss_chain_used (lss, 1);
4562   gfc_mark_ss_chain_used (loop.temp_ss, 1);
4563
4564   /* Declare the variable to hold the temporary offset and start the
4565      scalarized loop body.  */
4566   offset = gfc_create_var (gfc_array_index_type, NULL);
4567   gfc_start_scalarized_body (&loop2, &body);
4568
4569   /* Build the offsets for the temporary from the loop variables.  The
4570      temporary array has lbounds of zero and strides of one in all
4571      dimensions, so this is very simple.  The offset is only computed
4572      outside the innermost loop, so the overall transfer could be
4573      optimized further.  */
4574   info = &rse.ss->info->data.array;
4575
4576   tmp_index = gfc_index_zero_node;
4577   for (n = dimen - 1; n > 0; n--)
4578     {
4579       tree tmp_str;
4580       tmp = rse.loop->loopvar[n];
4581       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
4582                              tmp, rse.loop->from[n]);
4583       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
4584                              tmp, tmp_index);
4585
4586       tmp_str = fold_build2_loc (input_location, MINUS_EXPR,
4587                                  gfc_array_index_type,
4588                                  rse.loop->to[n-1], rse.loop->from[n-1]);
4589       tmp_str = fold_build2_loc (input_location, PLUS_EXPR,
4590                                  gfc_array_index_type,
4591                                  tmp_str, gfc_index_one_node);
4592
4593       tmp_index = fold_build2_loc (input_location, MULT_EXPR,
4594                                    gfc_array_index_type, tmp, tmp_str);
4595     }
4596
4597   tmp_index = fold_build2_loc (input_location, MINUS_EXPR,
4598                                gfc_array_index_type,
4599                                tmp_index, rse.loop->from[0]);
4600   gfc_add_modify (&rse.loop->code[0], offset, tmp_index);
4601
4602   tmp_index = fold_build2_loc (input_location, PLUS_EXPR,
4603                                gfc_array_index_type,
4604                                rse.loop->loopvar[0], offset);
4605
4606   /* Now use the offset for the reference.  */
4607   tmp = build_fold_indirect_ref_loc (input_location,
4608                                  info->data);
4609   rse.expr = gfc_build_array_ref (tmp, tmp_index, NULL);
4610
4611   if (expr->ts.type == BT_CHARACTER)
4612     rse.string_length = expr->ts.u.cl->backend_decl;
4613
4614   gfc_conv_expr (&lse, expr);
4615
4616   gcc_assert (lse.ss == gfc_ss_terminator);
4617
4618   tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, false, true);
4619   gfc_add_expr_to_block (&body, tmp);
4620
4621   /* Generate the copying loops.  */
4622   gfc_trans_scalarizing_loops (&loop2, &body);
4623
4624   /* Wrap the whole thing up by adding the second loop to the post-block
4625      and following it by the post-block of the first loop.  In this way,
4626      if the temporary needs freeing, it is done after use!  */
4627   if (intent != INTENT_IN)
4628     {
4629       gfc_add_block_to_block (&parmse->post, &loop2.pre);
4630       gfc_add_block_to_block (&parmse->post, &loop2.post);
4631     }
4632
4633 class_array_fcn:
4634
4635   gfc_add_block_to_block (&parmse->post, &loop.post);
4636
4637   gfc_cleanup_loop (&loop);
4638   gfc_cleanup_loop (&loop2);
4639
4640   /* Pass the string length to the argument expression.  */
4641   if (expr->ts.type == BT_CHARACTER)
4642     parmse->string_length = expr->ts.u.cl->backend_decl;
4643
4644   /* Determine the offset for pointer formal arguments and set the
4645      lbounds to one.  */
4646   if (formal_ptr)
4647     {
4648       size = gfc_index_one_node;
4649       offset = gfc_index_zero_node;
4650       for (n = 0; n < dimen; n++)
4651         {
4652           tmp = gfc_conv_descriptor_ubound_get (parmse->expr,
4653                                                 gfc_rank_cst[n]);
4654           tmp = fold_build2_loc (input_location, PLUS_EXPR,
4655                                  gfc_array_index_type, tmp,
4656                                  gfc_index_one_node);
4657           gfc_conv_descriptor_ubound_set (&parmse->pre,
4658                                           parmse->expr,
4659                                           gfc_rank_cst[n],
4660                                           tmp);
4661           gfc_conv_descriptor_lbound_set (&parmse->pre,
4662                                           parmse->expr,
4663                                           gfc_rank_cst[n],
4664                                           gfc_index_one_node);
4665           size = gfc_evaluate_now (size, &parmse->pre);
4666           offset = fold_build2_loc (input_location, MINUS_EXPR,
4667                                     gfc_array_index_type,
4668                                     offset, size);
4669           offset = gfc_evaluate_now (offset, &parmse->pre);
4670           tmp = fold_build2_loc (input_location, MINUS_EXPR,
4671                                  gfc_array_index_type,
4672                                  rse.loop->to[n], rse.loop->from[n]);
4673           tmp = fold_build2_loc (input_location, PLUS_EXPR,
4674                                  gfc_array_index_type,
4675                                  tmp, gfc_index_one_node);
4676           size = fold_build2_loc (input_location, MULT_EXPR,
4677                                   gfc_array_index_type, size, tmp);
4678         }
4679
4680       gfc_conv_descriptor_offset_set (&parmse->pre, parmse->expr,
4681                                       offset);
4682     }
4683
4684   /* We want either the address for the data or the address of the descriptor,
4685      depending on the mode of passing array arguments.  */
4686   if (g77)
4687     parmse->expr = gfc_conv_descriptor_data_get (parmse->expr);
4688   else
4689     parmse->expr = gfc_build_addr_expr (NULL_TREE, parmse->expr);
4690
4691   return;
4692 }
4693
4694
4695 /* Generate the code for argument list functions.  */
4696
4697 static void
4698 conv_arglist_function (gfc_se *se, gfc_expr *expr, const char *name)
4699 {
4700   /* Pass by value for g77 %VAL(arg), pass the address
4701      indirectly for %LOC, else by reference.  Thus %REF
4702      is a "do-nothing" and %LOC is the same as an F95
4703      pointer.  */
4704   if (strcmp (name, "%VAL") == 0)
4705     gfc_conv_expr (se, expr);
4706   else if (strcmp (name, "%LOC") == 0)
4707     {
4708       gfc_conv_expr_reference (se, expr);
4709       se->expr = gfc_build_addr_expr (NULL, se->expr);
4710     }
4711   else if (strcmp (name, "%REF") == 0)
4712     gfc_conv_expr_reference (se, expr);
4713   else
4714     gfc_error ("Unknown argument list function at %L", &expr->where);
4715 }
4716
4717
4718 /* This function tells whether the middle-end representation of the expression
4719    E given as input may point to data otherwise accessible through a variable
4720    (sub-)reference.
4721    It is assumed that the only expressions that may alias are variables,
4722    and array constructors if ARRAY_MAY_ALIAS is true and some of its elements
4723    may alias.
4724    This function is used to decide whether freeing an expression's allocatable
4725    components is safe or should be avoided.
4726
4727    If ARRAY_MAY_ALIAS is true, an array constructor may alias if some of
4728    its elements are copied from a variable.  This ARRAY_MAY_ALIAS trick
4729    is necessary because for array constructors, aliasing depends on how
4730    the array is used:
4731     - If E is an array constructor used as argument to an elemental procedure,
4732       the array, which is generated through shallow copy by the scalarizer,
4733       is used directly and can alias the expressions it was copied from.
4734     - If E is an array constructor used as argument to a non-elemental
4735       procedure,the scalarizer is used in gfc_conv_expr_descriptor to generate
4736       the array as in the previous case, but then that array is used
4737       to initialize a new descriptor through deep copy.  There is no alias
4738       possible in that case.
4739    Thus, the ARRAY_MAY_ALIAS flag is necessary to distinguish the two cases
4740    above.  */
4741
4742 static bool
4743 expr_may_alias_variables (gfc_expr *e, bool array_may_alias)
4744 {
4745   gfc_constructor *c;
4746
4747   if (e->expr_type == EXPR_VARIABLE)
4748     return true;
4749   else if (e->expr_type == EXPR_FUNCTION)
4750     {
4751       gfc_symbol *proc_ifc = gfc_get_proc_ifc_for_expr (e);
4752
4753       if (proc_ifc->result != NULL
4754           && ((proc_ifc->result->ts.type == BT_CLASS
4755                && proc_ifc->result->ts.u.derived->attr.is_class
4756                && CLASS_DATA (proc_ifc->result)->attr.class_pointer)
4757               || proc_ifc->result->attr.pointer))
4758         return true;
4759       else
4760         return false;
4761     }
4762   else if (e->expr_type != EXPR_ARRAY || !array_may_alias)
4763     return false;
4764
4765   for (c = gfc_constructor_first (e->value.constructor);
4766        c; c = gfc_constructor_next (c))
4767     if (c->expr
4768         && expr_may_alias_variables (c->expr, array_may_alias))
4769       return true;
4770
4771   return false;
4772 }
4773
4774
4775 /* Generate code for a procedure call.  Note can return se->post != NULL.
4776    If se->direct_byref is set then se->expr contains the return parameter.
4777    Return nonzero, if the call has alternate specifiers.
4778    'expr' is only needed for procedure pointer components.  */
4779
4780 int
4781 gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
4782                          gfc_actual_arglist * args, gfc_expr * expr,
4783                          vec<tree, va_gc> *append_args)
4784 {
4785   gfc_interface_mapping mapping;
4786   vec<tree, va_gc> *arglist;
4787   vec<tree, va_gc> *retargs;
4788   tree tmp;
4789   tree fntype;
4790   gfc_se parmse;
4791   gfc_array_info *info;
4792   int byref;
4793   int parm_kind;
4794   tree type;
4795   tree var;
4796   tree len;
4797   tree base_object;
4798   vec<tree, va_gc> *stringargs;
4799   vec<tree, va_gc> *optionalargs;
4800   tree result = NULL;
4801   gfc_formal_arglist *formal;
4802   gfc_actual_arglist *arg;
4803   int has_alternate_specifier = 0;
4804   bool need_interface_mapping;
4805   bool callee_alloc;
4806   bool ulim_copy;
4807   gfc_typespec ts;
4808   gfc_charlen cl;
4809   gfc_expr *e;
4810   gfc_symbol *fsym;
4811   stmtblock_t post;
4812   enum {MISSING = 0, ELEMENTAL, SCALAR, SCALAR_POINTER, ARRAY};
4813   gfc_component *comp = NULL;
4814   int arglen;
4815   unsigned int argc;
4816
4817   arglist = NULL;
4818   retargs = NULL;
4819   stringargs = NULL;
4820   optionalargs = NULL;
4821   var = NULL_TREE;
4822   len = NULL_TREE;
4823   gfc_clear_ts (&ts);
4824
4825   comp = gfc_get_proc_ptr_comp (expr);
4826
4827   bool elemental_proc = (comp
4828                          && comp->ts.interface
4829                          && comp->ts.interface->attr.elemental)
4830                         || (comp && comp->attr.elemental)
4831                         || sym->attr.elemental;
4832
4833   if (se->ss != NULL)
4834     {
4835       if (!elemental_proc)
4836         {
4837           gcc_assert (se->ss->info->type == GFC_SS_FUNCTION);
4838           if (se->ss->info->useflags)
4839             {
4840               gcc_assert ((!comp && gfc_return_by_reference (sym)
4841                            && sym->result->attr.dimension)
4842                           || (comp && comp->attr.dimension)
4843                           || gfc_is_class_array_function (expr));
4844               gcc_assert (se->loop != NULL);
4845               /* Access the previously obtained result.  */
4846               gfc_conv_tmp_array_ref (se);
4847               return 0;
4848             }
4849         }
4850       info = &se->ss->info->data.array;
4851     }
4852   else
4853     info = NULL;
4854
4855   gfc_init_block (&post);
4856   gfc_init_interface_mapping (&mapping);
4857   if (!comp)
4858     {
4859       formal = gfc_sym_get_dummy_args (sym);
4860       need_interface_mapping = sym->attr.dimension ||
4861                                (sym->ts.type == BT_CHARACTER
4862                                 && sym->ts.u.cl->length
4863                                 && sym->ts.u.cl->length->expr_type
4864                                    != EXPR_CONSTANT);
4865     }
4866   else
4867     {
4868       formal = comp->ts.interface ? comp->ts.interface->formal : NULL;
4869       need_interface_mapping = comp->attr.dimension ||
4870                                (comp->ts.type == BT_CHARACTER
4871                                 && comp->ts.u.cl->length
4872                                 && comp->ts.u.cl->length->expr_type
4873                                    != EXPR_CONSTANT);
4874     }
4875
4876   base_object = NULL_TREE;
4877   /* For _vprt->_copy () routines no formal symbol is present.  Nevertheless
4878      is the third and fourth argument to such a function call a value
4879      denoting the number of elements to copy (i.e., most of the time the
4880      length of a deferred length string).  */
4881   ulim_copy = (formal == NULL)
4882                && UNLIMITED_POLY (sym)
4883                && comp && (strcmp ("_copy", comp->name) == 0);
4884
4885   /* Evaluate the arguments.  */
4886   for (arg = args, argc = 0; arg != NULL;
4887        arg = arg->next, formal = formal ? formal->next : NULL, ++argc)
4888     {
4889       bool finalized = false;
4890
4891       e = arg->expr;
4892       fsym = formal ? formal->sym : NULL;
4893       parm_kind = MISSING;
4894
4895       /* If the procedure requires an explicit interface, the actual
4896          argument is passed according to the corresponding formal
4897          argument.  If the corresponding formal argument is a POINTER,
4898          ALLOCATABLE or assumed shape, we do not use g77's calling
4899          convention, and pass the address of the array descriptor
4900          instead.  Otherwise we use g77's calling convention, in other words
4901          pass the array data pointer without descriptor.  */
4902       bool nodesc_arg = fsym != NULL
4903                         && !(fsym->attr.pointer || fsym->attr.allocatable)
4904                         && fsym->as
4905                         && fsym->as->type != AS_ASSUMED_SHAPE
4906                         && fsym->as->type != AS_ASSUMED_RANK;
4907       if (comp)
4908         nodesc_arg = nodesc_arg || !comp->attr.always_explicit;
4909       else
4910         nodesc_arg = nodesc_arg || !sym->attr.always_explicit;
4911
4912       /* Class array expressions are sometimes coming completely unadorned
4913          with either arrayspec or _data component.  Correct that here.
4914          OOP-TODO: Move this to the frontend.  */
4915       if (e && e->expr_type == EXPR_VARIABLE
4916             && !e->ref
4917             && e->ts.type == BT_CLASS
4918             && (CLASS_DATA (e)->attr.codimension
4919                 || CLASS_DATA (e)->attr.dimension))
4920         {
4921           gfc_typespec temp_ts = e->ts;
4922           gfc_add_class_array_ref (e);
4923           e->ts = temp_ts;
4924         }
4925
4926       if (e == NULL)
4927         {
4928           if (se->ignore_optional)
4929             {
4930               /* Some intrinsics have already been resolved to the correct
4931                  parameters.  */
4932               continue;
4933             }
4934           else if (arg->label)
4935             {
4936               has_alternate_specifier = 1;
4937               continue;
4938             }
4939           else
4940             {
4941               gfc_init_se (&parmse, NULL);
4942
4943               /* For scalar arguments with VALUE attribute which are passed by
4944                  value, pass "0" and a hidden argument gives the optional
4945                  status.  */
4946               if (fsym && fsym->attr.optional && fsym->attr.value
4947                   && !fsym->attr.dimension && fsym->ts.type != BT_CHARACTER
4948                   && fsym->ts.type != BT_CLASS && fsym->ts.type != BT_DERIVED)
4949                 {
4950                   parmse.expr = fold_convert (gfc_sym_type (fsym),
4951                                               integer_zero_node);
4952                   vec_safe_push (optionalargs, boolean_false_node);
4953                 }
4954               else
4955                 {
4956                   /* Pass a NULL pointer for an absent arg.  */
4957                   parmse.expr = null_pointer_node;
4958                   if (arg->missing_arg_type == BT_CHARACTER)
4959                     parmse.string_length = build_int_cst (gfc_charlen_type_node,
4960                                                           0);
4961                 }
4962             }
4963         }
4964       else if (arg->expr->expr_type == EXPR_NULL
4965                && fsym && !fsym->attr.pointer
4966                && (fsym->ts.type != BT_CLASS
4967                    || !CLASS_DATA (fsym)->attr.class_pointer))
4968         {
4969           /* Pass a NULL pointer to denote an absent arg.  */
4970           gcc_assert (fsym->attr.optional && !fsym->attr.allocatable
4971                       && (fsym->ts.type != BT_CLASS
4972                           || !CLASS_DATA (fsym)->attr.allocatable));
4973           gfc_init_se (&parmse, NULL);
4974           parmse.expr = null_pointer_node;
4975           if (arg->missing_arg_type == BT_CHARACTER)
4976             parmse.string_length = build_int_cst (gfc_charlen_type_node, 0);
4977         }
4978       else if (fsym && fsym->ts.type == BT_CLASS
4979                  && e->ts.type == BT_DERIVED)
4980         {
4981           /* The derived type needs to be converted to a temporary
4982              CLASS object.  */
4983           gfc_init_se (&parmse, se);
4984           gfc_conv_derived_to_class (&parmse, e, fsym->ts, NULL,
4985                                      fsym->attr.optional
4986                                      && e->expr_type == EXPR_VARIABLE
4987                                      && e->symtree->n.sym->attr.optional,
4988                                      CLASS_DATA (fsym)->attr.class_pointer
4989                                      || CLASS_DATA (fsym)->attr.allocatable);
4990         }
4991       else if (UNLIMITED_POLY (fsym) && e->ts.type != BT_CLASS)
4992         {
4993           /* The intrinsic type needs to be converted to a temporary
4994              CLASS object for the unlimited polymorphic formal.  */
4995           gfc_init_se (&parmse, se);
4996           gfc_conv_intrinsic_to_class (&parmse, e, fsym->ts);
4997         }
4998       else if (se->ss && se->ss->info->useflags)
4999         {
5000           gfc_ss *ss;
5001
5002           ss = se->ss;
5003
5004           /* An elemental function inside a scalarized loop.  */
5005           gfc_init_se (&parmse, se);
5006           parm_kind = ELEMENTAL;
5007
5008           /* When no fsym is present, ulim_copy is set and this is a third or
5009              fourth argument, use call-by-value instead of by reference to
5010              hand the length properties to the copy routine (i.e., most of the
5011              time this will be a call to a __copy_character_* routine where the
5012              third and fourth arguments are the lengths of a deferred length
5013              char array).  */
5014           if ((fsym && fsym->attr.value)
5015               || (ulim_copy && (argc == 2 || argc == 3)))
5016             gfc_conv_expr (&parmse, e);
5017           else
5018             gfc_conv_expr_reference (&parmse, e);
5019
5020           if (e->ts.type == BT_CHARACTER && !e->rank
5021               && e->expr_type == EXPR_FUNCTION)
5022             parmse.expr = build_fold_indirect_ref_loc (input_location,
5023                                                        parmse.expr);
5024
5025           if (fsym && fsym->ts.type == BT_DERIVED
5026               && gfc_is_class_container_ref (e))
5027             {
5028               parmse.expr = gfc_class_data_get (parmse.expr);
5029
5030               if (fsym->attr.optional && e->expr_type == EXPR_VARIABLE
5031                   && e->symtree->n.sym->attr.optional)
5032                 {
5033                   tree cond = gfc_conv_expr_present (e->symtree->n.sym);
5034                   parmse.expr = build3_loc (input_location, COND_EXPR,
5035                                         TREE_TYPE (parmse.expr),
5036                                         cond, parmse.expr,
5037                                         fold_convert (TREE_TYPE (parmse.expr),
5038                                                       null_pointer_node));
5039                 }
5040             }
5041
5042           /* If we are passing an absent array as optional dummy to an
5043              elemental procedure, make sure that we pass NULL when the data
5044              pointer is NULL.  We need this extra conditional because of
5045              scalarization which passes arrays elements to the procedure,
5046              ignoring the fact that the array can be absent/unallocated/...  */
5047           if (ss->info->can_be_null_ref && ss->info->type != GFC_SS_REFERENCE)
5048             {
5049               tree descriptor_data;
5050
5051               descriptor_data = ss->info->data.array.data;
5052               tmp = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
5053                                      descriptor_data,
5054                                      fold_convert (TREE_TYPE (descriptor_data),
5055                                                    null_pointer_node));
5056               parmse.expr
5057                 = fold_build3_loc (input_location, COND_EXPR,
5058                                    TREE_TYPE (parmse.expr),
5059                                    gfc_unlikely (tmp, PRED_FORTRAN_ABSENT_DUMMY),
5060                                    fold_convert (TREE_TYPE (parmse.expr),
5061                                                  null_pointer_node),
5062                                    parmse.expr);
5063             }
5064
5065           /* The scalarizer does not repackage the reference to a class
5066              array - instead it returns a pointer to the data element.  */
5067           if (fsym && fsym->ts.type == BT_CLASS && e->ts.type == BT_CLASS)
5068             gfc_conv_class_to_class (&parmse, e, fsym->ts, true,
5069                                      fsym->attr.intent != INTENT_IN
5070                                      && (CLASS_DATA (fsym)->attr.class_pointer
5071                                          || CLASS_DATA (fsym)->attr.allocatable),
5072                                      fsym->attr.optional
5073                                      && e->expr_type == EXPR_VARIABLE
5074                                      && e->symtree->n.sym->attr.optional,
5075                                      CLASS_DATA (fsym)->attr.class_pointer
5076                                      || CLASS_DATA (fsym)->attr.allocatable);
5077         }
5078       else
5079         {
5080           bool scalar;
5081           gfc_ss *argss;
5082
5083           gfc_init_se (&parmse, NULL);
5084
5085           /* Check whether the expression is a scalar or not; we cannot use
5086              e->rank as it can be nonzero for functions arguments.  */
5087           argss = gfc_walk_expr (e);
5088           scalar = argss == gfc_ss_terminator;
5089           if (!scalar)
5090             gfc_free_ss_chain (argss);
5091
5092           /* Special handling for passing scalar polymorphic coarrays;
5093              otherwise one passes "class->_data.data" instead of "&class".  */
5094           if (e->rank == 0 && e->ts.type == BT_CLASS
5095               && fsym && fsym->ts.type == BT_CLASS
5096               && CLASS_DATA (fsym)->attr.codimension
5097               && !CLASS_DATA (fsym)->attr.dimension)
5098             {
5099               gfc_add_class_array_ref (e);
5100               parmse.want_coarray = 1;
5101               scalar = false;
5102             }
5103
5104           /* A scalar or transformational function.  */
5105           if (scalar)
5106             {
5107               if (e->expr_type == EXPR_VARIABLE
5108                     && e->symtree->n.sym->attr.cray_pointee
5109                     && fsym && fsym->attr.flavor == FL_PROCEDURE)
5110                 {
5111                     /* The Cray pointer needs to be converted to a pointer to
5112                        a type given by the expression.  */
5113                     gfc_conv_expr (&parmse, e);
5114                     type = build_pointer_type (TREE_TYPE (parmse.expr));
5115                     tmp = gfc_get_symbol_decl (e->symtree->n.sym->cp_pointer);
5116                     parmse.expr = convert (type, tmp);
5117                 }
5118               else if (fsym && fsym->attr.value)
5119                 {
5120                   if (fsym->ts.type == BT_CHARACTER
5121                       && fsym->ts.is_c_interop
5122                       && fsym->ns->proc_name != NULL
5123                       && fsym->ns->proc_name->attr.is_bind_c)
5124                     {
5125                       parmse.expr = NULL;
5126                       gfc_conv_scalar_char_value (fsym, &parmse, &e);
5127                       if (parmse.expr == NULL)
5128                         gfc_conv_expr (&parmse, e);
5129                     }
5130                   else
5131                     {
5132                     gfc_conv_expr (&parmse, e);
5133                     if (fsym->attr.optional
5134                         && fsym->ts.type != BT_CLASS
5135                         && fsym->ts.type != BT_DERIVED)
5136                       {
5137                         if (e->expr_type != EXPR_VARIABLE
5138                             || !e->symtree->n.sym->attr.optional
5139                             || e->ref != NULL)
5140                           vec_safe_push (optionalargs, boolean_true_node);
5141                         else
5142                           {
5143                             tmp = gfc_conv_expr_present (e->symtree->n.sym);
5144                             if (!e->symtree->n.sym->attr.value)
5145                               parmse.expr
5146                                 = fold_build3_loc (input_location, COND_EXPR,
5147                                         TREE_TYPE (parmse.expr),
5148                                         tmp, parmse.expr,
5149                                         fold_convert (TREE_TYPE (parmse.expr),
5150                                                       integer_zero_node));
5151
5152                             vec_safe_push (optionalargs, tmp);
5153                           }
5154                       }
5155                     }
5156                 }
5157               else if (arg->name && arg->name[0] == '%')
5158                 /* Argument list functions %VAL, %LOC and %REF are signalled
5159                    through arg->name.  */
5160                 conv_arglist_function (&parmse, arg->expr, arg->name);
5161               else if ((e->expr_type == EXPR_FUNCTION)
5162                         && ((e->value.function.esym
5163                              && e->value.function.esym->result->attr.pointer)
5164                             || (!e->value.function.esym
5165                                 && e->symtree->n.sym->attr.pointer))
5166                         && fsym && fsym->attr.target)
5167                 {
5168                   gfc_conv_expr (&parmse, e);
5169                   parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
5170                 }
5171               else if (e->expr_type == EXPR_FUNCTION
5172                        && e->symtree->n.sym->result
5173                        && e->symtree->n.sym->result != e->symtree->n.sym
5174                        && e->symtree->n.sym->result->attr.proc_pointer)
5175                 {
5176                   /* Functions returning procedure pointers.  */
5177                   gfc_conv_expr (&parmse, e);
5178                   if (fsym && fsym->attr.proc_pointer)
5179                     parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
5180                 }
5181               else
5182                 {
5183                   if (e->ts.type == BT_CLASS && fsym
5184                       && fsym->ts.type == BT_CLASS
5185                       && (!CLASS_DATA (fsym)->as
5186                           || CLASS_DATA (fsym)->as->type != AS_ASSUMED_RANK)
5187                       && CLASS_DATA (e)->attr.codimension)
5188                     {
5189                       gcc_assert (!CLASS_DATA (fsym)->attr.codimension);
5190                       gcc_assert (!CLASS_DATA (fsym)->as);
5191                       gfc_add_class_array_ref (e);
5192                       parmse.want_coarray = 1;
5193                       gfc_conv_expr_reference (&parmse, e);
5194                       class_scalar_coarray_to_class (&parmse, e, fsym->ts,
5195                                      fsym->attr.optional
5196                                      && e->expr_type == EXPR_VARIABLE);
5197                     }
5198                   else if (e->ts.type == BT_CLASS && fsym
5199                            && fsym->ts.type == BT_CLASS
5200                            && !CLASS_DATA (fsym)->as
5201                            && !CLASS_DATA (e)->as
5202                            && strcmp (fsym->ts.u.derived->name,
5203                                       e->ts.u.derived->name))
5204                     {
5205                       type = gfc_typenode_for_spec (&fsym->ts);
5206                       var = gfc_create_var (type, fsym->name);
5207                       gfc_conv_expr (&parmse, e);
5208                       if (fsym->attr.optional
5209                           && e->expr_type == EXPR_VARIABLE
5210                           && e->symtree->n.sym->attr.optional)
5211                         {
5212                           stmtblock_t block;
5213                           tree cond;
5214                           tmp = gfc_build_addr_expr (NULL_TREE, parmse.expr);
5215                           cond = fold_build2_loc (input_location, NE_EXPR,
5216                                                   logical_type_node, tmp,
5217                                                   fold_convert (TREE_TYPE (tmp),
5218                                                             null_pointer_node));
5219                           gfc_start_block (&block);
5220                           gfc_add_modify (&block, var,
5221                                           fold_build1_loc (input_location,
5222                                                            VIEW_CONVERT_EXPR,
5223                                                            type, parmse.expr));
5224                           gfc_add_expr_to_block (&parmse.pre,
5225                                  fold_build3_loc (input_location,
5226                                          COND_EXPR, void_type_node,
5227                                          cond, gfc_finish_block (&block),
5228                                          build_empty_stmt (input_location)));
5229                           parmse.expr = gfc_build_addr_expr (NULL_TREE, var);
5230                           parmse.expr = build3_loc (input_location, COND_EXPR,
5231                                          TREE_TYPE (parmse.expr),
5232                                          cond, parmse.expr,
5233                                          fold_convert (TREE_TYPE (parmse.expr),
5234                                                        null_pointer_node));
5235                         }
5236                       else
5237                         {
5238                           /* Since the internal representation of unlimited
5239                              polymorphic expressions includes an extra field
5240                              that other class objects do not, a cast to the
5241                              formal type does not work.  */
5242                           if (!UNLIMITED_POLY (e) && UNLIMITED_POLY (fsym))
5243                             {
5244                               tree efield;
5245
5246                               /* Set the _data field.  */
5247                               tmp = gfc_class_data_get (var);
5248                               efield = fold_convert (TREE_TYPE (tmp),
5249                                         gfc_class_data_get (parmse.expr));
5250                               gfc_add_modify (&parmse.pre, tmp, efield);
5251
5252                               /* Set the _vptr field.  */
5253                               tmp = gfc_class_vptr_get (var);
5254                               efield = fold_convert (TREE_TYPE (tmp),
5255                                         gfc_class_vptr_get (parmse.expr));
5256                               gfc_add_modify (&parmse.pre, tmp, efield);
5257
5258                               /* Set the _len field.  */
5259                               tmp = gfc_class_len_get (var);
5260                               gfc_add_modify (&parmse.pre, tmp,
5261                                               build_int_cst (TREE_TYPE (tmp), 0));
5262                             }
5263                           else
5264                             {
5265                               tmp = fold_build1_loc (input_location,
5266                                                      VIEW_CONVERT_EXPR,
5267                                                      type, parmse.expr);
5268                               gfc_add_modify (&parmse.pre, var, tmp);
5269                                               ;
5270                             }
5271                           parmse.expr = gfc_build_addr_expr (NULL_TREE, var);
5272                         }
5273                     }
5274                   else
5275                     {
5276                       bool add_clobber;
5277                       add_clobber = fsym && fsym->attr.intent == INTENT_OUT
5278                         && !fsym->attr.allocatable && !fsym->attr.pointer
5279                         && !e->symtree->n.sym->attr.dimension
5280                         && !e->symtree->n.sym->attr.pointer
5281                         /* See PR 41453.  */
5282                         && !e->symtree->n.sym->attr.dummy
5283                         /* FIXME - PR 87395 and PR 41453  */
5284                         && e->symtree->n.sym->attr.save == SAVE_NONE 
5285                         && e->ts.type != BT_CHARACTER && e->ts.type != BT_DERIVED
5286                         && e->ts.type != BT_CLASS && !sym->attr.elemental;
5287
5288                       gfc_conv_expr_reference (&parmse, e, add_clobber);
5289                     }
5290                   /* Catch base objects that are not variables.  */
5291                   if (e->ts.type == BT_CLASS
5292                         && e->expr_type != EXPR_VARIABLE
5293                         && expr && e == expr->base_expr)
5294                     base_object = build_fold_indirect_ref_loc (input_location,
5295                                                                parmse.expr);
5296
5297                   /* A class array element needs converting back to be a
5298                      class object, if the formal argument is a class object.  */
5299                   if (fsym && fsym->ts.type == BT_CLASS
5300                         && e->ts.type == BT_CLASS
5301                         && ((CLASS_DATA (fsym)->as
5302                              && CLASS_DATA (fsym)->as->type == AS_ASSUMED_RANK)
5303                             || CLASS_DATA (e)->attr.dimension))
5304                     gfc_conv_class_to_class (&parmse, e, fsym->ts, false,
5305                                      fsym->attr.intent != INTENT_IN
5306                                      && (CLASS_DATA (fsym)->attr.class_pointer
5307                                          || CLASS_DATA (fsym)->attr.allocatable),
5308                                      fsym->attr.optional
5309                                      && e->expr_type == EXPR_VARIABLE
5310                                      && e->symtree->n.sym->attr.optional,
5311                                      CLASS_DATA (fsym)->attr.class_pointer
5312                                      || CLASS_DATA (fsym)->attr.allocatable);
5313
5314                   /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
5315                      allocated on entry, it must be deallocated.  */
5316                   if (fsym && fsym->attr.intent == INTENT_OUT
5317                       && (fsym->attr.allocatable
5318                           || (fsym->ts.type == BT_CLASS
5319                               && CLASS_DATA (fsym)->attr.allocatable)))
5320                     {
5321                       stmtblock_t block;
5322                       tree ptr;
5323
5324                       gfc_init_block  (&block);
5325                       ptr = parmse.expr;
5326                       if (e->ts.type == BT_CLASS)
5327                         ptr = gfc_class_data_get (ptr);
5328
5329                       tmp = gfc_deallocate_scalar_with_status (ptr, NULL_TREE,
5330                                                                NULL_TREE, true,
5331                                                                e, e->ts);
5332                       gfc_add_expr_to_block (&block, tmp);
5333                       tmp = fold_build2_loc (input_location, MODIFY_EXPR,
5334                                              void_type_node, ptr,
5335                                              null_pointer_node);
5336                       gfc_add_expr_to_block (&block, tmp);
5337
5338                       if (fsym->ts.type == BT_CLASS && UNLIMITED_POLY (fsym))
5339                         {
5340                           gfc_add_modify (&block, ptr,
5341                                           fold_convert (TREE_TYPE (ptr),
5342                                                         null_pointer_node));
5343                           gfc_add_expr_to_block (&block, tmp);
5344                         }
5345                       else if (fsym->ts.type == BT_CLASS)
5346                         {
5347                           gfc_symbol *vtab;
5348                           vtab = gfc_find_derived_vtab (fsym->ts.u.derived);
5349                           tmp = gfc_get_symbol_decl (vtab);
5350                           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
5351                           ptr = gfc_class_vptr_get (parmse.expr);
5352                           gfc_add_modify (&block, ptr,
5353                                           fold_convert (TREE_TYPE (ptr), tmp));
5354                           gfc_add_expr_to_block (&block, tmp);
5355                         }
5356
5357                       if (fsym->attr.optional
5358                           && e->expr_type == EXPR_VARIABLE
5359                           && e->symtree->n.sym->attr.optional)
5360                         {
5361                           tmp = fold_build3_loc (input_location, COND_EXPR,
5362                                      void_type_node,
5363                                      gfc_conv_expr_present (e->symtree->n.sym),
5364                                             gfc_finish_block (&block),
5365                                             build_empty_stmt (input_location));
5366                         }
5367                       else
5368                         tmp = gfc_finish_block (&block);
5369
5370                       gfc_add_expr_to_block (&se->pre, tmp);
5371                     }
5372
5373                   if (fsym && (fsym->ts.type == BT_DERIVED
5374                                || fsym->ts.type == BT_ASSUMED)
5375                       && e->ts.type == BT_CLASS
5376                       && !CLASS_DATA (e)->attr.dimension
5377                       && !CLASS_DATA (e)->attr.codimension)
5378                     {
5379                       parmse.expr = gfc_class_data_get (parmse.expr);
5380                       /* The result is a class temporary, whose _data component
5381                          must be freed to avoid a memory leak.  */
5382                       if (e->expr_type == EXPR_FUNCTION
5383                           && CLASS_DATA (e)->attr.allocatable)
5384                         {
5385                           tree zero;
5386
5387                           gfc_expr *var;
5388
5389                           /* Borrow the function symbol to make a call to
5390                              gfc_add_finalizer_call and then restore it.  */
5391                           tmp = e->symtree->n.sym->backend_decl;
5392                           e->symtree->n.sym->backend_decl
5393                                         = TREE_OPERAND (parmse.expr, 0);
5394                           e->symtree->n.sym->attr.flavor = FL_VARIABLE;
5395                           var = gfc_lval_expr_from_sym (e->symtree->n.sym);
5396                           finalized = gfc_add_finalizer_call (&parmse.post,
5397                                                               var);
5398                           gfc_free_expr (var);
5399                           e->symtree->n.sym->backend_decl = tmp;
5400                           e->symtree->n.sym->attr.flavor = FL_PROCEDURE;
5401
5402                           /* Then free the class _data.  */
5403                           zero = build_int_cst (TREE_TYPE (parmse.expr), 0);
5404                           tmp = fold_build2_loc (input_location, NE_EXPR,
5405                                                  logical_type_node,
5406                                                  parmse.expr, zero);
5407                           tmp = build3_v (COND_EXPR, tmp,
5408                                           gfc_call_free (parmse.expr),
5409                                           build_empty_stmt (input_location));
5410                           gfc_add_expr_to_block (&parmse.post, tmp);
5411                           gfc_add_modify (&parmse.post, parmse.expr, zero);
5412                         }
5413                     }
5414
5415                   /* Wrap scalar variable in a descriptor. We need to convert
5416                      the address of a pointer back to the pointer itself before,
5417                      we can assign it to the data field.  */
5418
5419                   if (fsym && fsym->as && fsym->as->type == AS_ASSUMED_RANK
5420                       && fsym->ts.type != BT_CLASS && e->expr_type != EXPR_NULL)
5421                     {
5422                       tmp = parmse.expr;
5423                       if (TREE_CODE (tmp) == ADDR_EXPR)
5424                         tmp = build_fold_indirect_ref_loc (input_location, tmp);
5425                       parmse.expr = gfc_conv_scalar_to_descriptor (&parmse, tmp,
5426                                                                    fsym->attr);
5427                       parmse.expr = gfc_build_addr_expr (NULL_TREE,
5428                                                          parmse.expr);
5429                     }
5430                   else if (fsym && e->expr_type != EXPR_NULL
5431                       && ((fsym->attr.pointer
5432                            && fsym->attr.flavor != FL_PROCEDURE)
5433                           || (fsym->attr.proc_pointer
5434                               && !(e->expr_type == EXPR_VARIABLE
5435                                    && e->symtree->n.sym->attr.dummy))
5436                           || (fsym->attr.proc_pointer
5437                               && e->expr_type == EXPR_VARIABLE
5438                               && gfc_is_proc_ptr_comp (e))
5439                           || (fsym->attr.allocatable
5440                               && fsym->attr.flavor != FL_PROCEDURE)))
5441                     {
5442                       /* Scalar pointer dummy args require an extra level of
5443                          indirection. The null pointer already contains
5444                          this level of indirection.  */
5445                       parm_kind = SCALAR_POINTER;
5446                       parmse.expr = gfc_build_addr_expr (NULL_TREE, parmse.expr);
5447                     }
5448                 }
5449             }
5450           else if (e->ts.type == BT_CLASS
5451                     && fsym && fsym->ts.type == BT_CLASS
5452                     && (CLASS_DATA (fsym)->attr.dimension
5453                         || CLASS_DATA (fsym)->attr.codimension))
5454             {
5455               /* Pass a class array.  */
5456               parmse.use_offset = 1;
5457               gfc_conv_expr_descriptor (&parmse, e);
5458
5459               /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
5460                  allocated on entry, it must be deallocated.  */
5461               if (fsym->attr.intent == INTENT_OUT
5462                   && CLASS_DATA (fsym)->attr.allocatable)
5463                 {
5464                   stmtblock_t block;
5465                   tree ptr;
5466
5467                   gfc_init_block  (&block);
5468                   ptr = parmse.expr;
5469                   ptr = gfc_class_data_get (ptr);
5470
5471                   tmp = gfc_deallocate_with_status (ptr, NULL_TREE,
5472                                                     NULL_TREE, NULL_TREE,
5473                                                     NULL_TREE, true, e,
5474                                                     GFC_CAF_COARRAY_NOCOARRAY);
5475                   gfc_add_expr_to_block (&block, tmp);
5476                   tmp = fold_build2_loc (input_location, MODIFY_EXPR,
5477                                          void_type_node, ptr,
5478                                          null_pointer_node);
5479                   gfc_add_expr_to_block (&block, tmp);
5480                   gfc_reset_vptr (&block, e);
5481
5482                   if (fsym->attr.optional
5483                       && e->expr_type == EXPR_VARIABLE
5484                       && (!e->ref
5485                           || (e->ref->type == REF_ARRAY
5486                               && e->ref->u.ar.type != AR_FULL))
5487                       && e->symtree->n.sym->attr.optional)
5488                     {
5489                       tmp = fold_build3_loc (input_location, COND_EXPR,
5490                                     void_type_node,
5491                                     gfc_conv_expr_present (e->symtree->n.sym),
5492                                     gfc_finish_block (&block),
5493                                     build_empty_stmt (input_location));
5494                     }
5495                   else
5496                     tmp = gfc_finish_block (&block);
5497
5498                   gfc_add_expr_to_block (&se->pre, tmp);
5499                 }
5500
5501               /* The conversion does not repackage the reference to a class
5502                  array - _data descriptor.  */
5503               gfc_conv_class_to_class (&parmse, e, fsym->ts, false,
5504                                      fsym->attr.intent != INTENT_IN
5505                                      && (CLASS_DATA (fsym)->attr.class_pointer
5506                                          || CLASS_DATA (fsym)->attr.allocatable),
5507                                      fsym->attr.optional
5508                                      && e->expr_type == EXPR_VARIABLE
5509                                      && e->symtree->n.sym->attr.optional,
5510                                      CLASS_DATA (fsym)->attr.class_pointer
5511                                      || CLASS_DATA (fsym)->attr.allocatable);
5512             }
5513           else
5514             {
5515               /* If the argument is a function call that may not create
5516                  a temporary for the result, we have to check that we
5517                  can do it, i.e. that there is no alias between this
5518                  argument and another one.  */
5519               if (gfc_get_noncopying_intrinsic_argument (e) != NULL)
5520                 {
5521                   gfc_expr *iarg;
5522                   sym_intent intent;
5523
5524                   if (fsym != NULL)
5525                     intent = fsym->attr.intent;
5526                   else
5527                     intent = INTENT_UNKNOWN;
5528
5529                   if (gfc_check_fncall_dependency (e, intent, sym, args,
5530                                                    NOT_ELEMENTAL))
5531                     parmse.force_tmp = 1;
5532
5533                   iarg = e->value.function.actual->expr;
5534
5535                   /* Temporary needed if aliasing due to host association.  */
5536                   if (sym->attr.contained
5537                         && !sym->attr.pure
5538                         && !sym->attr.implicit_pure
5539                         && !sym->attr.use_assoc
5540                         && iarg->expr_type == EXPR_VARIABLE
5541                         && sym->ns == iarg->symtree->n.sym->ns)
5542                     parmse.force_tmp = 1;
5543
5544                   /* Ditto within module.  */
5545                   if (sym->attr.use_assoc
5546                         && !sym->attr.pure
5547                         && !sym->attr.implicit_pure
5548                         && iarg->expr_type == EXPR_VARIABLE
5549                         && sym->module == iarg->symtree->n.sym->module)
5550                     parmse.force_tmp = 1;
5551                 }
5552
5553               if (e->expr_type == EXPR_VARIABLE
5554                     && is_subref_array (e)
5555                     && !(fsym && fsym->attr.pointer))
5556                 /* The actual argument is a component reference to an
5557                    array of derived types.  In this case, the argument
5558                    is converted to a temporary, which is passed and then
5559                    written back after the procedure call.  */
5560                 gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
5561                                 fsym ? fsym->attr.intent : INTENT_INOUT,
5562                                 fsym && fsym->attr.pointer);
5563               else if (gfc_is_class_array_ref (e, NULL)
5564                          && fsym && fsym->ts.type == BT_DERIVED)
5565                 /* The actual argument is a component reference to an
5566                    array of derived types.  In this case, the argument
5567                    is converted to a temporary, which is passed and then
5568                    written back after the procedure call.
5569                    OOP-TODO: Insert code so that if the dynamic type is
5570                    the same as the declared type, copy-in/copy-out does
5571                    not occur.  */
5572                 gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
5573                                 fsym ? fsym->attr.intent : INTENT_INOUT,
5574                                 fsym && fsym->attr.pointer);
5575
5576               else if (gfc_is_class_array_function (e)
5577                          && fsym && fsym->ts.type == BT_DERIVED)
5578                 /* See previous comment.  For function actual argument,
5579                    the write out is not needed so the intent is set as
5580                    intent in.  */
5581                 {
5582                   e->must_finalize = 1;
5583                   gfc_conv_subref_array_arg (&parmse, e, nodesc_arg,
5584                                              INTENT_IN,
5585                                              fsym && fsym->attr.pointer);
5586                 }
5587               else
5588                 gfc_conv_array_parameter (&parmse, e, nodesc_arg, fsym,
5589                                           sym->name, NULL);
5590
5591               /* If an ALLOCATABLE dummy argument has INTENT(OUT) and is
5592                  allocated on entry, it must be deallocated.  */
5593               if (fsym && fsym->attr.allocatable
5594                   && fsym->attr.intent == INTENT_OUT)
5595                 {
5596                   if (fsym->ts.type == BT_DERIVED
5597                       && fsym->ts.u.derived->attr.alloc_comp)
5598                   {
5599                     // deallocate the components first
5600                     tmp = gfc_deallocate_alloc_comp (fsym->ts.u.derived,
5601                                                      parmse.expr, e->rank);
5602                     if (tmp != NULL_TREE)
5603                       gfc_add_expr_to_block (&se->pre, tmp);
5604                   }
5605
5606                   tmp = build_fold_indirect_ref_loc (input_location,
5607                                                      parmse.expr);
5608                   if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp)))
5609                     tmp = gfc_conv_descriptor_data_get (tmp);
5610                   tmp = gfc_deallocate_with_status (tmp, NULL_TREE, NULL_TREE,
5611                                                     NULL_TREE, NULL_TREE, true,
5612                                                     e,
5613                                                     GFC_CAF_COARRAY_NOCOARRAY);
5614                   if (fsym->attr.optional
5615                       && e->expr_type == EXPR_VARIABLE
5616                       && e->symtree->n.sym->attr.optional)
5617                     tmp = fold_build3_loc (input_location, COND_EXPR,
5618                                      void_type_node,
5619                                      gfc_conv_expr_present (e->symtree->n.sym),
5620                                        tmp, build_empty_stmt (input_location));
5621                   gfc_add_expr_to_block (&se->pre, tmp);
5622                 }
5623             }
5624         }
5625
5626       /* The case with fsym->attr.optional is that of a user subroutine
5627          with an interface indicating an optional argument.  When we call
5628          an intrinsic subroutine, however, fsym is NULL, but we might still
5629          have an optional argument, so we proceed to the substitution
5630          just in case.  */
5631       if (e && (fsym == NULL || fsym->attr.optional))
5632         {
5633           /* If an optional argument is itself an optional dummy argument,
5634              check its presence and substitute a null if absent.  This is
5635              only needed when passing an array to an elemental procedure
5636              as then array elements are accessed - or no NULL pointer is
5637              allowed and a "1" or "0" should be passed if not present.
5638              When passing a non-array-descriptor full array to a
5639              non-array-descriptor dummy, no check is needed. For
5640              array-descriptor actual to array-descriptor dummy, see
5641              PR 41911 for why a check has to be inserted.
5642              fsym == NULL is checked as intrinsics required the descriptor
5643              but do not always set fsym.  */
5644           if (e->expr_type == EXPR_VARIABLE
5645               && e->symtree->n.sym->attr.optional
5646               && ((e->rank != 0 && elemental_proc)
5647                   || e->representation.length || e->ts.type == BT_CHARACTER
5648                   || (e->rank != 0
5649                       && (fsym == NULL
5650                           || (fsym-> as
5651                               && (fsym->as->type == AS_ASSUMED_SHAPE
5652                                   || fsym->as->type == AS_ASSUMED_RANK
5653                                   || fsym->as->type == AS_DEFERRED))))))
5654             gfc_conv_missing_dummy (&parmse, e, fsym ? fsym->ts : e->ts,
5655                                     e->representation.length);
5656         }
5657
5658       if (fsym && e)
5659         {
5660           /* Obtain the character length of an assumed character length
5661              length procedure from the typespec.  */
5662           if (fsym->ts.type == BT_CHARACTER
5663               && parmse.string_length == NULL_TREE
5664               && e->ts.type == BT_PROCEDURE
5665               && e->symtree->n.sym->ts.type == BT_CHARACTER
5666               && e->symtree->n.sym->ts.u.cl->length != NULL
5667               && e->symtree->n.sym->ts.u.cl->length->expr_type == EXPR_CONSTANT)
5668             {
5669               gfc_conv_const_charlen (e->symtree->n.sym->ts.u.cl);
5670               parmse.string_length = e->symtree->n.sym->ts.u.cl->backend_decl;
5671             }
5672         }
5673
5674       if (fsym && need_interface_mapping && e)
5675         gfc_add_interface_mapping (&mapping, fsym, &parmse, e);
5676
5677       gfc_add_block_to_block (&se->pre, &parmse.pre);
5678       gfc_add_block_to_block (&post, &parmse.post);
5679
5680       /* Allocated allocatable components of derived types must be
5681          deallocated for non-variable scalars, array arguments to elemental
5682          procedures, and array arguments with descriptor to non-elemental
5683          procedures.  As bounds information for descriptorless arrays is no
5684          longer available here, they are dealt with in trans-array.c
5685          (gfc_conv_array_parameter).  */
5686       if (e && (e->ts.type == BT_DERIVED || e->ts.type == BT_CLASS)
5687             && e->ts.u.derived->attr.alloc_comp
5688             && (e->rank == 0 || elemental_proc || !nodesc_arg)
5689             && !expr_may_alias_variables (e, elemental_proc))
5690         {
5691           int parm_rank;
5692           /* It is known the e returns a structure type with at least one
5693              allocatable component.  When e is a function, ensure that the
5694              function is called once only by using a temporary variable.  */
5695           if (!DECL_P (parmse.expr))
5696             parmse.expr = gfc_evaluate_now_loc (input_location,
5697                                                 parmse.expr, &se->pre);
5698
5699           if (fsym && fsym->attr.value)
5700             tmp = parmse.expr;
5701           else
5702             tmp = build_fold_indirect_ref_loc (input_location,
5703                                                parmse.expr);
5704
5705           parm_rank = e->rank;
5706           switch (parm_kind)
5707             {
5708             case (ELEMENTAL):
5709             case (SCALAR):
5710               parm_rank = 0;
5711               break;
5712
5713             case (SCALAR_POINTER):
5714               tmp = build_fold_indirect_ref_loc (input_location,
5715                                              tmp);
5716               break;
5717             }
5718
5719           if (e->expr_type == EXPR_OP
5720                 && e->value.op.op == INTRINSIC_PARENTHESES
5721                 && e->value.op.op1->expr_type == EXPR_VARIABLE)
5722             {
5723               tree local_tmp;
5724               local_tmp = gfc_evaluate_now (tmp, &se->pre);
5725               local_tmp = gfc_copy_alloc_comp (e->ts.u.derived, local_tmp, tmp,
5726                                                parm_rank, 0);
5727               gfc_add_expr_to_block (&se->post, local_tmp);
5728             }
5729
5730           if (e->ts.type == BT_DERIVED && fsym && fsym->ts.type == BT_CLASS)
5731             {
5732               /* The derived type is passed to gfc_deallocate_alloc_comp.
5733                  Therefore, class actuals can handled correctly but derived
5734                  types passed to class formals need the _data component.  */
5735               tmp = gfc_class_data_get (tmp);
5736               if (!CLASS_DATA (fsym)->attr.dimension)
5737                 tmp = build_fold_indirect_ref_loc (input_location, tmp);
5738             }
5739
5740           if (!finalized && !e->must_finalize)
5741             {
5742               if ((e->ts.type == BT_CLASS
5743                    && GFC_CLASS_TYPE_P (TREE_TYPE (tmp)))
5744                   || e->ts.type == BT_DERIVED)
5745                 tmp = gfc_deallocate_alloc_comp (e->ts.u.derived, tmp,
5746                                                  parm_rank);
5747               else if (e->ts.type == BT_CLASS)
5748                 tmp = gfc_deallocate_alloc_comp (CLASS_DATA (e)->ts.u.derived,
5749                                                  tmp, parm_rank);
5750               gfc_prepend_expr_to_block (&post, tmp);
5751             }
5752         }
5753
5754       /* Add argument checking of passing an unallocated/NULL actual to
5755          a nonallocatable/nonpointer dummy.  */
5756
5757       if (gfc_option.rtcheck & GFC_RTCHECK_POINTER && e != NULL)
5758         {
5759           symbol_attribute attr;
5760           char *msg;
5761           tree cond;
5762
5763           if (e->expr_type == EXPR_VARIABLE || e->expr_type == EXPR_FUNCTION)
5764             attr = gfc_expr_attr (e);
5765           else
5766             goto end_pointer_check;
5767
5768           /*  In Fortran 2008 it's allowed to pass a NULL pointer/nonallocated
5769               allocatable to an optional dummy, cf. 12.5.2.12.  */
5770           if (fsym != NULL && fsym->attr.optional && !attr.proc_pointer
5771               && (gfc_option.allow_std & GFC_STD_F2008) != 0)
5772             goto end_pointer_check;
5773
5774           if (attr.optional)
5775             {
5776               /* If the actual argument is an optional pointer/allocatable and
5777                  the formal argument takes an nonpointer optional value,
5778                  it is invalid to pass a non-present argument on, even
5779                  though there is no technical reason for this in gfortran.
5780                  See Fortran 2003, Section 12.4.1.6 item (7)+(8).  */
5781               tree present, null_ptr, type;
5782
5783               if (attr.allocatable
5784                   && (fsym == NULL || !fsym->attr.allocatable))
5785                 msg = xasprintf ("Allocatable actual argument '%s' is not "
5786                                  "allocated or not present",
5787                                  e->symtree->n.sym->name);
5788               else if (attr.pointer
5789                        && (fsym == NULL || !fsym->attr.pointer))
5790                 msg = xasprintf ("Pointer actual argument '%s' is not "
5791                                  "associated or not present",
5792                                  e->symtree->n.sym->name);
5793               else if (attr.proc_pointer
5794                        && (fsym == NULL || !fsym->attr.proc_pointer))
5795                 msg = xasprintf ("Proc-pointer actual argument '%s' is not "
5796                                  "associated or not present",
5797                                  e->symtree->n.sym->name);
5798               else
5799                 goto end_pointer_check;
5800
5801               present = gfc_conv_expr_present (e->symtree->n.sym);
5802               type = TREE_TYPE (present);
5803               present = fold_build2_loc (input_location, EQ_EXPR,
5804                                          logical_type_node, present,
5805                                          fold_convert (type,
5806                                                        null_pointer_node));
5807               type = TREE_TYPE (parmse.expr);
5808               null_ptr = fold_build2_loc (input_location, EQ_EXPR,
5809                                           logical_type_node, parmse.expr,
5810                                           fold_convert (type,
5811                                                         null_pointer_node));
5812               cond = fold_build2_loc (input_location, TRUTH_ORIF_EXPR,
5813                                       logical_type_node, present, null_ptr);
5814             }
5815           else
5816             {
5817               if (attr.allocatable
5818                   && (fsym == NULL || !fsym->attr.allocatable))
5819                 msg = xasprintf ("Allocatable actual argument '%s' is not "
5820                                  "allocated", e->symtree->n.sym->name);
5821               else if (attr.pointer
5822                        && (fsym == NULL || !fsym->attr.pointer))
5823                 msg = xasprintf ("Pointer actual argument '%s' is not "
5824                                  "associated", e->symtree->n.sym->name);
5825               else if (attr.proc_pointer
5826                        && (fsym == NULL || !fsym->attr.proc_pointer))
5827                 msg = xasprintf ("Proc-pointer actual argument '%s' is not "
5828                                  "associated", e->symtree->n.sym->name);
5829               else
5830                 goto end_pointer_check;
5831
5832               tmp = parmse.expr;
5833
5834               /* If the argument is passed by value, we need to strip the
5835                  INDIRECT_REF.  */
5836               if (!POINTER_TYPE_P (TREE_TYPE (parmse.expr)))
5837                 tmp = gfc_build_addr_expr (NULL_TREE, tmp);
5838
5839               cond = fold_build2_loc (input_location, EQ_EXPR,
5840                                       logical_type_node, tmp,
5841                                       fold_convert (TREE_TYPE (tmp),
5842                                                     null_pointer_node));
5843             }
5844
5845           gfc_trans_runtime_check (true, false, cond, &se->pre, &e->where,
5846                                    msg);
5847           free (msg);
5848         }
5849       end_pointer_check:
5850
5851       /* Deferred length dummies pass the character length by reference
5852          so that the value can be returned.  */
5853       if (parmse.string_length && fsym && fsym->ts.deferred)
5854         {
5855           if (INDIRECT_REF_P (parmse.string_length))
5856             /* In chains of functions/procedure calls the string_length already
5857                is a pointer to the variable holding the length.  Therefore
5858                remove the deref on call.  */
5859             parmse.string_length = TREE_OPERAND (parmse.string_length, 0);
5860           else
5861             {
5862               tmp = parmse.string_length;
5863               if (!VAR_P (tmp) && TREE_CODE (tmp) != COMPONENT_REF)
5864                 tmp = gfc_evaluate_now (parmse.string_length, &se->pre);
5865               parmse.string_length = gfc_build_addr_expr (NULL_TREE, tmp);
5866             }
5867         }
5868
5869       /* Character strings are passed as two parameters, a length and a
5870          pointer - except for Bind(c) which only passes the pointer.
5871          An unlimited polymorphic formal argument likewise does not
5872          need the length.  */
5873       if (parmse.string_length != NULL_TREE
5874           && !sym->attr.is_bind_c
5875           && !(fsym && UNLIMITED_POLY (fsym)))
5876         vec_safe_push (stringargs, parmse.string_length);
5877
5878       /* When calling __copy for character expressions to unlimited
5879          polymorphic entities, the dst argument needs a string length.  */
5880       if (sym->name[0] == '_' && e && e->ts.type == BT_CHARACTER
5881           && gfc_str_startswith (sym->name, "__vtab_CHARACTER")
5882           && arg->next && arg->next->expr
5883           && (arg->next->expr->ts.type == BT_DERIVED
5884               || arg->next->expr->ts.type == BT_CLASS)
5885           && arg->next->expr->ts.u.derived->attr.unlimited_polymorphic)
5886         vec_safe_push (stringargs, parmse.string_length);
5887
5888       /* For descriptorless coarrays and assumed-shape coarray dummies, we
5889          pass the token and the offset as additional arguments.  */
5890       if (fsym && e == NULL && flag_coarray == GFC_FCOARRAY_LIB
5891           && ((fsym->ts.type != BT_CLASS && fsym->attr.codimension
5892                && !fsym->attr.allocatable)
5893               || (fsym->ts.type == BT_CLASS
5894                   && CLASS_DATA (fsym)->attr.codimension
5895                   && !CLASS_DATA (fsym)->attr.allocatable)))
5896         {
5897           /* Token and offset.  */
5898           vec_safe_push (stringargs, null_pointer_node);
5899           vec_safe_push (stringargs, build_int_cst (gfc_array_index_type, 0));
5900           gcc_assert (fsym->attr.optional);
5901         }
5902       else if (fsym && flag_coarray == GFC_FCOARRAY_LIB
5903                && ((fsym->ts.type != BT_CLASS && fsym->attr.codimension
5904                     && !fsym->attr.allocatable)
5905                    || (fsym->ts.type == BT_CLASS
5906                        && CLASS_DATA (fsym)->attr.codimension
5907                        && !CLASS_DATA (fsym)->attr.allocatable)))
5908         {
5909           tree caf_decl, caf_type;
5910           tree offset, tmp2;
5911
5912           caf_decl = gfc_get_tree_for_caf_expr (e);
5913           caf_type = TREE_TYPE (caf_decl);
5914
5915           if (GFC_DESCRIPTOR_TYPE_P (caf_type)
5916               && (GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE
5917                   || GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_POINTER))
5918             tmp = gfc_conv_descriptor_token (caf_decl);
5919           else if (DECL_LANG_SPECIFIC (caf_decl)
5920                    && GFC_DECL_TOKEN (caf_decl) != NULL_TREE)
5921             tmp = GFC_DECL_TOKEN (caf_decl);
5922           else
5923             {
5924               gcc_assert (GFC_ARRAY_TYPE_P (caf_type)
5925                           && GFC_TYPE_ARRAY_CAF_TOKEN (caf_type) != NULL_TREE);
5926               tmp = GFC_TYPE_ARRAY_CAF_TOKEN (caf_type);
5927             }
5928
5929           vec_safe_push (stringargs, tmp);
5930
5931           if (GFC_DESCRIPTOR_TYPE_P (caf_type)
5932               && GFC_TYPE_ARRAY_AKIND (caf_type) == GFC_ARRAY_ALLOCATABLE)
5933             offset = build_int_cst (gfc_array_index_type, 0);
5934           else if (DECL_LANG_SPECIFIC (caf_decl)
5935                    && GFC_DECL_CAF_OFFSET (caf_decl) != NULL_TREE)
5936             offset = GFC_DECL_CAF_OFFSET (caf_decl);
5937           else if (GFC_TYPE_ARRAY_CAF_OFFSET (caf_type) != NULL_TREE)
5938             offset = GFC_TYPE_ARRAY_CAF_OFFSET (caf_type);
5939           else
5940             offset = build_int_cst (gfc_array_index_type, 0);
5941
5942           if (GFC_DESCRIPTOR_TYPE_P (caf_type))
5943             tmp = gfc_conv_descriptor_data_get (caf_decl);
5944           else
5945             {
5946               gcc_assert (POINTER_TYPE_P (caf_type));
5947               tmp = caf_decl;
5948             }
5949
5950           tmp2 = fsym->ts.type == BT_CLASS
5951                  ? gfc_class_data_get (parmse.expr) : parmse.expr;
5952           if ((fsym->ts.type != BT_CLASS
5953                && (fsym->as->type == AS_ASSUMED_SHAPE
5954                    || fsym->as->type == AS_ASSUMED_RANK))
5955               || (fsym->ts.type == BT_CLASS
5956                   && (CLASS_DATA (fsym)->as->type == AS_ASSUMED_SHAPE
5957                       || CLASS_DATA (fsym)->as->type == AS_ASSUMED_RANK)))
5958             {
5959               if (fsym->ts.type == BT_CLASS)
5960                 gcc_assert (!POINTER_TYPE_P (TREE_TYPE (tmp2)));
5961               else
5962                 {
5963                   gcc_assert (POINTER_TYPE_P (TREE_TYPE (tmp2)));
5964                   tmp2 = build_fold_indirect_ref_loc (input_location, tmp2);
5965                 }
5966               gcc_assert (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp2)));
5967               tmp2 = gfc_conv_descriptor_data_get (tmp2);
5968             }
5969           else if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (tmp2)))
5970             tmp2 = gfc_conv_descriptor_data_get (tmp2);
5971           else
5972             {
5973               gcc_assert (POINTER_TYPE_P (TREE_TYPE (tmp2)));
5974             }
5975
5976           tmp = fold_build2_loc (input_location, MINUS_EXPR,
5977                                  gfc_array_index_type,
5978                                  fold_convert (gfc_array_index_type, tmp2),
5979                                  fold_convert (gfc_array_index_type, tmp));
5980           offset = fold_build2_loc (input_location, PLUS_EXPR,
5981                                     gfc_array_index_type, offset, tmp);
5982
5983           vec_safe_push (stringargs, offset);
5984         }
5985
5986       vec_safe_push (arglist, parmse.expr);
5987     }
5988   gfc_finish_interface_mapping (&mapping, &se->pre, &se->post);
5989
5990   if (comp)
5991     ts = comp->ts;
5992   else if (sym->ts.type == BT_CLASS)
5993     ts = CLASS_DATA (sym)->ts;
5994   else
5995     ts = sym->ts;
5996
5997   if (ts.type == BT_CHARACTER && sym->attr.is_bind_c)
5998     se->string_length = build_int_cst (gfc_charlen_type_node, 1);
5999   else if (ts.type == BT_CHARACTER)
6000     {
6001       if (ts.u.cl->length == NULL)
6002         {
6003           /* Assumed character length results are not allowed by C418 of the 2003
6004              standard and are trapped in resolve.c; except in the case of SPREAD
6005              (and other intrinsics?) and dummy functions.  In the case of SPREAD,
6006              we take the character length of the first argument for the result.
6007              For dummies, we have to look through the formal argument list for
6008              this function and use the character length found there.*/
6009           if (ts.deferred)
6010             cl.backend_decl = gfc_create_var (gfc_charlen_type_node, "slen");
6011           else if (!sym->attr.dummy)
6012             cl.backend_decl = (*stringargs)[0];
6013           else
6014             {
6015               formal = gfc_sym_get_dummy_args (sym->ns->proc_name);
6016               for (; formal; formal = formal->next)
6017                 if (strcmp (formal->sym->name, sym->name) == 0)
6018                   cl.backend_decl = formal->sym->ts.u.cl->backend_decl;
6019             }
6020           len = cl.backend_decl;
6021         }
6022       else
6023         {
6024           tree tmp;
6025
6026           /* Calculate the length of the returned string.  */
6027           gfc_init_se (&parmse, NULL);
6028           if (need_interface_mapping)
6029             gfc_apply_interface_mapping (&mapping, &parmse, ts.u.cl->length);
6030           else
6031             gfc_conv_expr (&parmse, ts.u.cl->length);
6032           gfc_add_block_to_block (&se->pre, &parmse.pre);
6033           gfc_add_block_to_block (&se->post, &parmse.post);
6034           tmp = parmse.expr;
6035           /* TODO: It would be better to have the charlens as
6036              gfc_charlen_type_node already when the interface is
6037              created instead of converting it here (see PR 84615).  */
6038           tmp = fold_build2_loc (input_location, MAX_EXPR,
6039                                  gfc_charlen_type_node,
6040                                  fold_convert (gfc_charlen_type_node, tmp),
6041                                  build_zero_cst (gfc_charlen_type_node));
6042           cl.backend_decl = tmp;
6043         }
6044
6045       /* Set up a charlen structure for it.  */
6046       cl.next = NULL;
6047       cl.length = NULL;
6048       ts.u.cl = &cl;
6049
6050       len = cl.backend_decl;
6051     }
6052
6053   byref = (comp && (comp->attr.dimension
6054            || (comp->ts.type == BT_CHARACTER && !sym->attr.is_bind_c)))
6055            || (!comp && gfc_return_by_reference (sym));
6056   if (byref)
6057     {
6058       if (se->direct_byref)
6059         {
6060           /* Sometimes, too much indirection can be applied; e.g. for
6061              function_result = array_valued_recursive_function.  */
6062           if (TREE_TYPE (TREE_TYPE (se->expr))
6063                 && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))
6064                 && GFC_DESCRIPTOR_TYPE_P
6065                         (TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr)))))
6066             se->expr = build_fold_indirect_ref_loc (input_location,
6067                                                     se->expr);
6068
6069           /* If the lhs of an assignment x = f(..) is allocatable and
6070              f2003 is allowed, we must do the automatic reallocation.
6071              TODO - deal with intrinsics, without using a temporary.  */
6072           if (flag_realloc_lhs
6073                 && se->ss && se->ss->loop_chain
6074                 && se->ss->loop_chain->is_alloc_lhs
6075                 && !expr->value.function.isym
6076                 && sym->result->as != NULL)
6077             {
6078               /* Evaluate the bounds of the result, if known.  */
6079               gfc_set_loop_bounds_from_array_spec (&mapping, se,
6080                                                    sym->result->as);
6081
6082               /* Perform the automatic reallocation.  */
6083               tmp = gfc_alloc_allocatable_for_assignment (se->loop,
6084                                                           expr, NULL);
6085               gfc_add_expr_to_block (&se->pre, tmp);
6086
6087               /* Pass the temporary as the first argument.  */
6088               result = info->descriptor;
6089             }
6090           else
6091             result = build_fold_indirect_ref_loc (input_location,
6092                                                   se->expr);
6093           vec_safe_push (retargs, se->expr);
6094         }
6095       else if (comp && comp->attr.dimension)
6096         {
6097           gcc_assert (se->loop && info);
6098
6099           /* Set the type of the array.  */
6100           tmp = gfc_typenode_for_spec (&comp->ts);
6101           gcc_assert (se->ss->dimen == se->loop->dimen);
6102
6103           /* Evaluate the bounds of the result, if known.  */
6104           gfc_set_loop_bounds_from_array_spec (&mapping, se, comp->as);
6105
6106           /* If the lhs of an assignment x = f(..) is allocatable and
6107              f2003 is allowed, we must not generate the function call
6108              here but should just send back the results of the mapping.
6109              This is signalled by the function ss being flagged.  */
6110           if (flag_realloc_lhs && se->ss && se->ss->is_alloc_lhs)
6111             {
6112               gfc_free_interface_mapping (&mapping);
6113               return has_alternate_specifier;
6114             }
6115
6116           /* Create a temporary to store the result.  In case the function
6117              returns a pointer, the temporary will be a shallow copy and
6118              mustn't be deallocated.  */
6119           callee_alloc = comp->attr.allocatable || comp->attr.pointer;
6120           gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
6121                                        tmp, NULL_TREE, false,
6122                                        !comp->attr.pointer, callee_alloc,
6123                                        &se->ss->info->expr->where);
6124
6125           /* Pass the temporary as the first argument.  */
6126           result = info->descriptor;
6127           tmp = gfc_build_addr_expr (NULL_TREE, result);
6128           vec_safe_push (retargs, tmp);
6129         }
6130       else if (!comp && sym->result->attr.dimension)
6131         {
6132           gcc_assert (se->loop && info);
6133
6134           /* Set the type of the array.  */
6135           tmp = gfc_typenode_for_spec (&ts);
6136           gcc_assert (se->ss->dimen == se->loop->dimen);
6137
6138           /* Evaluate the bounds of the result, if known.  */
6139           gfc_set_loop_bounds_from_array_spec (&mapping, se, sym->result->as);
6140
6141           /* If the lhs of an assignment x = f(..) is allocatable and
6142              f2003 is allowed, we must not generate the function call
6143              here but should just send back the results of the mapping.
6144              This is signalled by the function ss being flagged.  */
6145           if (flag_realloc_lhs && se->ss && se->ss->is_alloc_lhs)
6146             {
6147               gfc_free_interface_mapping (&mapping);
6148               return has_alternate_specifier;
6149             }
6150
6151           /* Create a temporary to store the result.  In case the function
6152              returns a pointer, the temporary will be a shallow copy and
6153              mustn't be deallocated.  */
6154           callee_alloc = sym->attr.allocatable || sym->attr.pointer;
6155           gfc_trans_create_temp_array (&se->pre, &se->post, se->ss,
6156                                        tmp, NULL_TREE, false,
6157                                        !sym->attr.pointer, callee_alloc,
6158                                        &se->ss->info->expr->where);
6159
6160           /* Pass the temporary as the first argument.  */
6161           result = info->descriptor;
6162           tmp = gfc_build_addr_expr (NULL_TREE, result);
6163           vec_safe_push (retargs, tmp);
6164         }
6165       else if (ts.type == BT_CHARACTER)
6166         {
6167           /* Pass the string length.  */
6168           type = gfc_get_character_type (ts.kind, ts.u.cl);
6169           type = build_pointer_type (type);
6170
6171           /* Emit a DECL_EXPR for the VLA type.  */
6172           tmp = TREE_TYPE (type);
6173           if (TYPE_SIZE (tmp)
6174               && TREE_CODE (TYPE_SIZE (tmp)) != INTEGER_CST)
6175             {
6176               tmp = build_decl (input_location, TYPE_DECL, NULL_TREE, tmp);
6177               DECL_ARTIFICIAL (tmp) = 1;
6178               DECL_IGNORED_P (tmp) = 1;
6179               tmp = fold_build1_loc (input_location, DECL_EXPR,
6180                                      TREE_TYPE (tmp), tmp);
6181               gfc_add_expr_to_block (&se->pre, tmp);
6182             }
6183
6184           /* Return an address to a char[0:len-1]* temporary for
6185              character pointers.  */
6186           if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
6187                || (comp && (comp->attr.pointer || comp->attr.allocatable)))
6188             {
6189               var = gfc_create_var (type, "pstr");
6190
6191               if ((!comp && sym->attr.allocatable)
6192                   || (comp && comp->attr.allocatable))
6193                 {
6194                   gfc_add_modify (&se->pre, var,
6195                                   fold_convert (TREE_TYPE (var),
6196                                                 null_pointer_node));
6197                   tmp = gfc_call_free (var);
6198                   gfc_add_expr_to_block (&se->post, tmp);
6199                 }
6200
6201               /* Provide an address expression for the function arguments.  */
6202               var = gfc_build_addr_expr (NULL_TREE, var);
6203             }
6204           else
6205             var = gfc_conv_string_tmp (se, type, len);
6206
6207           vec_safe_push (retargs, var);
6208         }
6209       else
6210         {
6211           gcc_assert (flag_f2c && ts.type == BT_COMPLEX);
6212
6213           type = gfc_get_complex_type (ts.kind);
6214           var = gfc_build_addr_expr (NULL_TREE, gfc_create_var (type, "cmplx"));
6215           vec_safe_push (retargs, var);
6216         }
6217
6218       /* Add the string length to the argument list.  */
6219       if (ts.type == BT_CHARACTER && ts.deferred)
6220         {
6221           tmp = len;
6222           if (!VAR_P (tmp))
6223             tmp = gfc_evaluate_now (len, &se->pre);
6224           TREE_STATIC (tmp) = 1;
6225           gfc_add_modify (&se->pre, tmp,
6226                           build_int_cst (TREE_TYPE (tmp), 0));
6227           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
6228           vec_safe_push (retargs, tmp);
6229         }
6230       else if (ts.type == BT_CHARACTER)
6231         vec_safe_push (retargs, len);
6232     }
6233   gfc_free_interface_mapping (&mapping);
6234
6235   /* We need to glom RETARGS + ARGLIST + STRINGARGS + APPEND_ARGS.  */
6236   arglen = (vec_safe_length (arglist) + vec_safe_length (optionalargs)
6237             + vec_safe_length (stringargs) + vec_safe_length (append_args));
6238   vec_safe_reserve (retargs, arglen);
6239
6240   /* Add the return arguments.  */
6241   vec_safe_splice (retargs, arglist);
6242
6243   /* Add the hidden present status for optional+value to the arguments.  */
6244   vec_safe_splice (retargs, optionalargs);
6245
6246   /* Add the hidden string length parameters to the arguments.  */
6247   vec_safe_splice (retargs, stringargs);
6248
6249   /* We may want to append extra arguments here.  This is used e.g. for
6250      calls to libgfortran_matmul_??, which need extra information.  */
6251   vec_safe_splice (retargs, append_args);
6252
6253   arglist = retargs;
6254
6255   /* Generate the actual call.  */
6256   if (base_object == NULL_TREE)
6257     conv_function_val (se, sym, expr);
6258   else
6259     conv_base_obj_fcn_val (se, base_object, expr);
6260
6261   /* If there are alternate return labels, function type should be
6262      integer.  Can't modify the type in place though, since it can be shared
6263      with other functions.  For dummy arguments, the typing is done to
6264      this result, even if it has to be repeated for each call.  */
6265   if (has_alternate_specifier
6266       && TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) != integer_type_node)
6267     {
6268       if (!sym->attr.dummy)
6269         {
6270           TREE_TYPE (sym->backend_decl)
6271                 = build_function_type (integer_type_node,
6272                       TYPE_ARG_TYPES (TREE_TYPE (sym->backend_decl)));
6273           se->expr = gfc_build_addr_expr (NULL_TREE, sym->backend_decl);
6274         }
6275       else
6276         TREE_TYPE (TREE_TYPE (TREE_TYPE (se->expr))) = integer_type_node;
6277     }
6278
6279   fntype = TREE_TYPE (TREE_TYPE (se->expr));
6280   se->expr = build_call_vec (TREE_TYPE (fntype), se->expr, arglist);
6281
6282   /* Allocatable scalar function results must be freed and nullified
6283      after use. This necessitates the creation of a temporary to
6284      hold the result to prevent duplicate calls.  */
6285   if (!byref && sym->ts.type != BT_CHARACTER
6286       && ((sym->attr.allocatable && !sym->attr.dimension && !comp)
6287           || (comp && comp->attr.allocatable && !comp->attr.dimension)))
6288     {
6289       tmp = gfc_create_var (TREE_TYPE (se->expr), NULL);
6290       gfc_add_modify (&se->pre, tmp, se->expr);
6291       se->expr = tmp;
6292       tmp = gfc_call_free (tmp);
6293       gfc_add_expr_to_block (&post, tmp);
6294       gfc_add_modify (&post, se->expr, build_int_cst (TREE_TYPE (se->expr), 0));
6295     }
6296
6297   /* If we have a pointer function, but we don't want a pointer, e.g.
6298      something like
6299         x = f()
6300      where f is pointer valued, we have to dereference the result.  */
6301   if (!se->want_pointer && !byref
6302       && ((!comp && (sym->attr.pointer || sym->attr.allocatable))
6303           || (comp && (comp->attr.pointer || comp->attr.allocatable))))
6304     se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
6305
6306   /* f2c calling conventions require a scalar default real function to
6307      return a double precision result.  Convert this back to default
6308      real.  We only care about the cases that can happen in Fortran 77.
6309   */
6310   if (flag_f2c && sym->ts.type == BT_REAL
6311       && sym->ts.kind == gfc_default_real_kind
6312       && !sym->attr.always_explicit)
6313     se->expr = fold_convert (gfc_get_real_type (sym->ts.kind), se->expr);
6314
6315   /* A pure function may still have side-effects - it may modify its
6316      parameters.  */
6317   TREE_SIDE_EFFECTS (se->expr) = 1;
6318 #if 0
6319   if (!sym->attr.pure)
6320     TREE_SIDE_EFFECTS (se->expr) = 1;
6321 #endif
6322
6323   if (byref)
6324     {
6325       /* Add the function call to the pre chain.  There is no expression.  */
6326       gfc_add_expr_to_block (&se->pre, se->expr);
6327       se->expr = NULL_TREE;
6328
6329       if (!se->direct_byref)
6330         {
6331           if ((sym->attr.dimension && !comp) || (comp && comp->attr.dimension))
6332             {
6333               if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
6334                 {
6335                   /* Check the data pointer hasn't been modified.  This would
6336                      happen in a function returning a pointer.  */
6337                   tmp = gfc_conv_descriptor_data_get (info->descriptor);
6338                   tmp = fold_build2_loc (input_location, NE_EXPR,
6339                                          logical_type_node,
6340                                          tmp, info->data);
6341                   gfc_trans_runtime_check (true, false, tmp, &se->pre, NULL,
6342                                            gfc_msg_fault);
6343                 }
6344               se->expr = info->descriptor;
6345               /* Bundle in the string length.  */
6346               se->string_length = len;
6347             }
6348           else if (ts.type == BT_CHARACTER)
6349             {
6350               /* Dereference for character pointer results.  */
6351               if ((!comp && (sym->attr.pointer || sym->attr.allocatable))
6352                   || (comp && (comp->attr.pointer || comp->attr.allocatable)))
6353                 se->expr = build_fold_indirect_ref_loc (input_location, var);
6354               else
6355                 se->expr = var;
6356
6357               se->string_length = len;
6358             }
6359           else
6360             {
6361               gcc_assert (ts.type == BT_COMPLEX && flag_f2c);
6362               se->expr = build_fold_indirect_ref_loc (input_location, var);
6363             }
6364         }
6365     }
6366
6367   /* Associate the rhs class object's meta-data with the result, when the
6368      result is a temporary.  */
6369   if (args && args->expr && args->expr->ts.type == BT_CLASS
6370       && sym->ts.type == BT_CLASS && result != NULL_TREE && DECL_P (result)
6371       && !GFC_CLASS_TYPE_P (TREE_TYPE (result)))
6372     {
6373       gfc_se parmse;
6374       gfc_expr *class_expr = gfc_find_and_cut_at_last_class_ref (args->expr);
6375
6376       gfc_init_se (&parmse, NULL);
6377       parmse.data_not_needed = 1;
6378       gfc_conv_expr (&parmse, class_expr);
6379       if (!DECL_LANG_SPECIFIC (result))
6380         gfc_allocate_lang_decl (result);
6381       GFC_DECL_SAVED_DESCRIPTOR (result) = parmse.expr;
6382       gfc_free_expr (class_expr);
6383       gcc_assert (parmse.pre.head == NULL_TREE
6384                   && parmse.post.head == NULL_TREE);
6385     }
6386
6387   /* Follow the function call with the argument post block.  */
6388   if (byref)
6389     {
6390       gfc_add_block_to_block (&se->pre, &post);
6391
6392       /* Transformational functions of derived types with allocatable
6393          components must have the result allocatable components copied when the
6394          argument is actually given.  */
6395       arg = expr->value.function.actual;
6396       if (result && arg && expr->rank
6397           && expr->value.function.isym
6398           && expr->value.function.isym->transformational
6399           && arg->expr
6400           && arg->expr->ts.type == BT_DERIVED
6401           && arg->expr->ts.u.derived->attr.alloc_comp)
6402         {
6403           tree tmp2;
6404           /* Copy the allocatable components.  We have to use a
6405              temporary here to prevent source allocatable components
6406              from being corrupted.  */
6407           tmp2 = gfc_evaluate_now (result, &se->pre);
6408           tmp = gfc_copy_alloc_comp (arg->expr->ts.u.derived,
6409                                      result, tmp2, expr->rank, 0);
6410           gfc_add_expr_to_block (&se->pre, tmp);
6411           tmp = gfc_copy_allocatable_data (result, tmp2, TREE_TYPE(tmp2),
6412                                            expr->rank);
6413           gfc_add_expr_to_block (&se->pre, tmp);
6414
6415           /* Finally free the temporary's data field.  */
6416           tmp = gfc_conv_descriptor_data_get (tmp2);
6417           tmp = gfc_deallocate_with_status (tmp, NULL_TREE, NULL_TREE,
6418                                             NULL_TREE, NULL_TREE, true,
6419                                             NULL, GFC_CAF_COARRAY_NOCOARRAY);
6420           gfc_add_expr_to_block (&se->pre, tmp);
6421         }
6422     }
6423   else
6424     {
6425       /* For a function with a class array result, save the result as
6426          a temporary, set the info fields needed by the scalarizer and
6427          call the finalization function of the temporary. Note that the
6428          nullification of allocatable components needed by the result
6429          is done in gfc_trans_assignment_1.  */
6430       if (expr && ((gfc_is_class_array_function (expr)
6431                     && se->ss && se->ss->loop)
6432                    || gfc_is_alloc_class_scalar_function (expr))
6433           && se->expr && GFC_CLASS_TYPE_P (TREE_TYPE (se->expr))
6434           && expr->must_finalize)
6435         {
6436           tree final_fndecl;
6437           tree is_final;
6438           int n;
6439           if (se->ss && se->ss->loop)
6440             {
6441               gfc_add_block_to_block (&se->ss->loop->pre, &se->pre);
6442               se->expr = gfc_evaluate_now (se->expr, &se->ss->loop->pre);
6443               tmp = gfc_class_data_get (se->expr);
6444               info->descriptor = tmp;
6445               info->data = gfc_conv_descriptor_data_get (tmp);
6446               info->offset = gfc_conv_descriptor_offset_get (tmp);
6447               for (n = 0; n < se->ss->loop->dimen; n++)
6448                 {
6449                   tree dim = gfc_rank_cst[n];
6450                   se->ss->loop->to[n] = gfc_conv_descriptor_ubound_get (tmp, dim);
6451                   se->ss->loop->from[n] = gfc_conv_descriptor_lbound_get (tmp, dim);
6452                 }
6453             }
6454           else
6455             {
6456               /* TODO Eliminate the doubling of temporaries. This
6457                  one is necessary to ensure no memory leakage.  */
6458               se->expr = gfc_evaluate_now (se->expr, &se->pre);
6459               tmp = gfc_class_data_get (se->expr);
6460               tmp = gfc_conv_scalar_to_descriptor (se, tmp,
6461                         CLASS_DATA (expr->value.function.esym->result)->attr);
6462             }
6463
6464           if ((gfc_is_class_array_function (expr)
6465                || gfc_is_alloc_class_scalar_function (expr))
6466               && CLASS_DATA (expr->value.function.esym->result)->attr.pointer)
6467             goto no_finalization;
6468
6469           final_fndecl = gfc_class_vtab_final_get (se->expr);
6470           is_final = fold_build2_loc (input_location, NE_EXPR,
6471                                       logical_type_node,
6472                                       final_fndecl,
6473                                       fold_convert (TREE_TYPE (final_fndecl),
6474                                                     null_pointer_node));
6475           final_fndecl = build_fold_indirect_ref_loc (input_location,
6476                                                       final_fndecl);
6477           tmp = build_call_expr_loc (input_location,
6478                                      final_fndecl, 3,
6479                                      gfc_build_addr_expr (NULL, tmp),
6480                                      gfc_class_vtab_size_get (se->expr),
6481                                      boolean_false_node);
6482           tmp = fold_build3_loc (input_location, COND_EXPR,
6483                                  void_type_node, is_final, tmp,
6484                                  build_empty_stmt (input_location));
6485
6486           if (se->ss && se->ss->loop)
6487             {
6488               gfc_prepend_expr_to_block (&se->ss->loop->post, tmp);
6489               tmp = fold_build2_loc (input_location, NE_EXPR,
6490                                      logical_type_node,
6491                                      info->data,
6492                                      fold_convert (TREE_TYPE (info->data),
6493                                                     null_pointer_node));
6494               tmp = fold_build3_loc (input_location, COND_EXPR,
6495                                      void_type_node, tmp,
6496                                      gfc_call_free (info->data),
6497                                      build_empty_stmt (input_location));
6498               gfc_add_expr_to_block (&se->ss->loop->post, tmp);
6499             }
6500           else
6501             {
6502               tree classdata;
6503               gfc_prepend_expr_to_block (&se->post, tmp);
6504               classdata = gfc_class_data_get (se->expr);
6505               tmp = fold_build2_loc (input_location, NE_EXPR,
6506                                      logical_type_node,
6507                                      classdata,
6508                                      fold_convert (TREE_TYPE (classdata),
6509                                                     null_pointer_node));
6510               tmp = fold_build3_loc (input_location, COND_EXPR,
6511                                      void_type_node, tmp,
6512                                      gfc_call_free (classdata),
6513                                      build_empty_stmt (input_location));
6514               gfc_add_expr_to_block (&se->post, tmp);
6515             }
6516         }
6517
6518 no_finalization:
6519       gfc_add_block_to_block (&se->post, &post);
6520     }
6521
6522   return has_alternate_specifier;
6523 }
6524
6525
6526 /* Fill a character string with spaces.  */
6527
6528 static tree
6529 fill_with_spaces (tree start, tree type, tree size)
6530 {
6531   stmtblock_t block, loop;
6532   tree i, el, exit_label, cond, tmp;
6533
6534   /* For a simple char type, we can call memset().  */
6535   if (compare_tree_int (TYPE_SIZE_UNIT (type), 1) == 0)
6536     return build_call_expr_loc (input_location,
6537                             builtin_decl_explicit (BUILT_IN_MEMSET),
6538                             3, start,
6539                             build_int_cst (gfc_get_int_type (gfc_c_int_kind),
6540                                            lang_hooks.to_target_charset (' ')),
6541                                 fold_convert (size_type_node, size));
6542
6543   /* Otherwise, we use a loop:
6544         for (el = start, i = size; i > 0; el--, i+= TYPE_SIZE_UNIT (type))
6545           *el = (type) ' ';
6546    */
6547
6548   /* Initialize variables.  */
6549   gfc_init_block (&block);
6550   i = gfc_create_var (sizetype, "i");
6551   gfc_add_modify (&block, i, fold_convert (sizetype, size));
6552   el = gfc_create_var (build_pointer_type (type), "el");
6553   gfc_add_modify (&block, el, fold_convert (TREE_TYPE (el), start));
6554   exit_label = gfc_build_label_decl (NULL_TREE);
6555   TREE_USED (exit_label) = 1;
6556
6557
6558   /* Loop body.  */
6559   gfc_init_block (&loop);
6560
6561   /* Exit condition.  */
6562   cond = fold_build2_loc (input_location, LE_EXPR, logical_type_node, i,
6563                           build_zero_cst (sizetype));
6564   tmp = build1_v (GOTO_EXPR, exit_label);
6565   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
6566                          build_empty_stmt (input_location));
6567   gfc_add_expr_to_block (&loop, tmp);
6568
6569   /* Assignment.  */
6570   gfc_add_modify (&loop,
6571                   fold_build1_loc (input_location, INDIRECT_REF, type, el),
6572                   build_int_cst (type, lang_hooks.to_target_charset (' ')));
6573
6574   /* Increment loop variables.  */
6575   gfc_add_modify (&loop, i,
6576                   fold_build2_loc (input_location, MINUS_EXPR, sizetype, i,
6577                                    TYPE_SIZE_UNIT (type)));
6578   gfc_add_modify (&loop, el,
6579                   fold_build_pointer_plus_loc (input_location,
6580                                                el, TYPE_SIZE_UNIT (type)));
6581
6582   /* Making the loop... actually loop!  */
6583   tmp = gfc_finish_block (&loop);
6584   tmp = build1_v (LOOP_EXPR, tmp);
6585   gfc_add_expr_to_block (&block, tmp);
6586
6587   /* The exit label.  */
6588   tmp = build1_v (LABEL_EXPR, exit_label);
6589   gfc_add_expr_to_block (&block, tmp);
6590
6591
6592   return gfc_finish_block (&block);
6593 }
6594
6595
6596 /* Generate code to copy a string.  */
6597
6598 void
6599 gfc_trans_string_copy (stmtblock_t * block, tree dlength, tree dest,
6600                        int dkind, tree slength, tree src, int skind)
6601 {
6602   tree tmp, dlen, slen;
6603   tree dsc;
6604   tree ssc;
6605   tree cond;
6606   tree cond2;
6607   tree tmp2;
6608   tree tmp3;
6609   tree tmp4;
6610   tree chartype;
6611   stmtblock_t tempblock;
6612
6613   gcc_assert (dkind == skind);
6614
6615   if (slength != NULL_TREE)
6616     {
6617       slen = gfc_evaluate_now (fold_convert (gfc_charlen_type_node, slength), block);
6618       ssc = gfc_string_to_single_character (slen, src, skind);
6619     }
6620   else
6621     {
6622       slen = build_one_cst (gfc_charlen_type_node);
6623       ssc =  src;
6624     }
6625
6626   if (dlength != NULL_TREE)
6627     {
6628       dlen = gfc_evaluate_now (fold_convert (gfc_charlen_type_node, dlength), block);
6629       dsc = gfc_string_to_single_character (dlen, dest, dkind);
6630     }
6631   else
6632     {
6633       dlen = build_one_cst (gfc_charlen_type_node);
6634       dsc =  dest;
6635     }
6636
6637   /* Assign directly if the types are compatible.  */
6638   if (dsc != NULL_TREE && ssc != NULL_TREE
6639       && TREE_TYPE (dsc) == TREE_TYPE (ssc))
6640     {
6641       gfc_add_modify (block, dsc, ssc);
6642       return;
6643     }
6644
6645   /* The string copy algorithm below generates code like
6646
6647      if (destlen > 0)
6648        {
6649          if (srclen < destlen)
6650            {
6651              memmove (dest, src, srclen);
6652              // Pad with spaces.
6653              memset (&dest[srclen], ' ', destlen - srclen);
6654            }
6655          else
6656            {
6657              // Truncate if too long.
6658              memmove (dest, src, destlen);
6659            }
6660        }
6661   */
6662
6663   /* Do nothing if the destination length is zero.  */
6664   cond = fold_build2_loc (input_location, GT_EXPR, logical_type_node, dlen,
6665                           build_zero_cst (TREE_TYPE (dlen)));
6666
6667   /* For non-default character kinds, we have to multiply the string
6668      length by the base type size.  */
6669   chartype = gfc_get_char_type (dkind);
6670   slen = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (slen),
6671                           slen,
6672                           fold_convert (TREE_TYPE (slen),
6673                                         TYPE_SIZE_UNIT (chartype)));
6674   dlen = fold_build2_loc (input_location, MULT_EXPR, TREE_TYPE (dlen),
6675                           dlen,
6676                           fold_convert (TREE_TYPE (dlen),
6677                                         TYPE_SIZE_UNIT (chartype)));
6678
6679   if (dlength && POINTER_TYPE_P (TREE_TYPE (dest)))
6680     dest = fold_convert (pvoid_type_node, dest);
6681   else
6682     dest = gfc_build_addr_expr (pvoid_type_node, dest);
6683
6684   if (slength && POINTER_TYPE_P (TREE_TYPE (src)))
6685     src = fold_convert (pvoid_type_node, src);
6686   else
6687     src = gfc_build_addr_expr (pvoid_type_node, src);
6688
6689   /* Truncate string if source is too long.  */
6690   cond2 = fold_build2_loc (input_location, LT_EXPR, logical_type_node, slen,
6691                            dlen);
6692
6693   /* Copy and pad with spaces.  */
6694   tmp3 = build_call_expr_loc (input_location,
6695                               builtin_decl_explicit (BUILT_IN_MEMMOVE),
6696                               3, dest, src,
6697                               fold_convert (size_type_node, slen));
6698
6699   /* Wstringop-overflow appears at -O3 even though this warning is not
6700      explicitly available in fortran nor can it be switched off. If the
6701      source length is a constant, its negative appears as a very large
6702      postive number and triggers the warning in BUILTIN_MEMSET. Fixing
6703      the result of the MINUS_EXPR suppresses this spurious warning.  */
6704   tmp = fold_build2_loc (input_location, MINUS_EXPR,
6705                          TREE_TYPE(dlen), dlen, slen);
6706   if (slength && TREE_CONSTANT (slength))
6707     tmp = gfc_evaluate_now (tmp, block);
6708
6709   tmp4 = fold_build_pointer_plus_loc (input_location, dest, slen);
6710   tmp4 = fill_with_spaces (tmp4, chartype, tmp);
6711
6712   gfc_init_block (&tempblock);
6713   gfc_add_expr_to_block (&tempblock, tmp3);
6714   gfc_add_expr_to_block (&tempblock, tmp4);
6715   tmp3 = gfc_finish_block (&tempblock);
6716
6717   /* The truncated memmove if the slen >= dlen.  */
6718   tmp2 = build_call_expr_loc (input_location,
6719                               builtin_decl_explicit (BUILT_IN_MEMMOVE),
6720                               3, dest, src,
6721                               fold_convert (size_type_node, dlen));
6722
6723   /* The whole copy_string function is there.  */
6724   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond2,
6725                          tmp3, tmp2);
6726   tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, tmp,
6727                          build_empty_stmt (input_location));
6728   gfc_add_expr_to_block (block, tmp);
6729 }
6730
6731
6732 /* Translate a statement function.
6733    The value of a statement function reference is obtained by evaluating the
6734    expression using the values of the actual arguments for the values of the
6735    corresponding dummy arguments.  */
6736
6737 static void
6738 gfc_conv_statement_function (gfc_se * se, gfc_expr * expr)
6739 {
6740   gfc_symbol *sym;
6741   gfc_symbol *fsym;
6742   gfc_formal_arglist *fargs;
6743   gfc_actual_arglist *args;
6744   gfc_se lse;
6745   gfc_se rse;
6746   gfc_saved_var *saved_vars;
6747   tree *temp_vars;
6748   tree type;
6749   tree tmp;
6750   int n;
6751
6752   sym = expr->symtree->n.sym;
6753   args = expr->value.function.actual;
6754   gfc_init_se (&lse, NULL);
6755   gfc_init_se (&rse, NULL);
6756
6757   n = 0;
6758   for (fargs = gfc_sym_get_dummy_args (sym); fargs; fargs = fargs->next)
6759     n++;
6760   saved_vars = XCNEWVEC (gfc_saved_var, n);
6761   temp_vars = XCNEWVEC (tree, n);
6762
6763   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
6764        fargs = fargs->next, n++)
6765     {
6766       /* Each dummy shall be specified, explicitly or implicitly, to be
6767          scalar.  */
6768       gcc_assert (fargs->sym->attr.dimension == 0);
6769       fsym = fargs->sym;
6770
6771       if (fsym->ts.type == BT_CHARACTER)
6772         {
6773           /* Copy string arguments.  */
6774           tree arglen;
6775
6776           gcc_assert (fsym->ts.u.cl && fsym->ts.u.cl->length
6777                       && fsym->ts.u.cl->length->expr_type == EXPR_CONSTANT);
6778
6779           /* Create a temporary to hold the value.  */
6780           if (fsym->ts.u.cl->backend_decl == NULL_TREE)
6781              fsym->ts.u.cl->backend_decl
6782                 = gfc_conv_constant_to_tree (fsym->ts.u.cl->length);
6783
6784           type = gfc_get_character_type (fsym->ts.kind, fsym->ts.u.cl);
6785           temp_vars[n] = gfc_create_var (type, fsym->name);
6786
6787           arglen = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
6788
6789           gfc_conv_expr (&rse, args->expr);
6790           gfc_conv_string_parameter (&rse);
6791           gfc_add_block_to_block (&se->pre, &lse.pre);
6792           gfc_add_block_to_block (&se->pre, &rse.pre);
6793
6794           gfc_trans_string_copy (&se->pre, arglen, temp_vars[n], fsym->ts.kind,
6795                                  rse.string_length, rse.expr, fsym->ts.kind);
6796           gfc_add_block_to_block (&se->pre, &lse.post);
6797           gfc_add_block_to_block (&se->pre, &rse.post);
6798         }
6799       else
6800         {
6801           /* For everything else, just evaluate the expression.  */
6802
6803           /* Create a temporary to hold the value.  */
6804           type = gfc_typenode_for_spec (&fsym->ts);
6805           temp_vars[n] = gfc_create_var (type, fsym->name);
6806
6807           gfc_conv_expr (&lse, args->expr);
6808
6809           gfc_add_block_to_block (&se->pre, &lse.pre);
6810           gfc_add_modify (&se->pre, temp_vars[n], lse.expr);
6811           gfc_add_block_to_block (&se->pre, &lse.post);
6812         }
6813
6814       args = args->next;
6815     }
6816
6817   /* Use the temporary variables in place of the real ones.  */
6818   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
6819        fargs = fargs->next, n++)
6820     gfc_shadow_sym (fargs->sym, temp_vars[n], &saved_vars[n]);
6821
6822   gfc_conv_expr (se, sym->value);
6823
6824   if (sym->ts.type == BT_CHARACTER)
6825     {
6826       gfc_conv_const_charlen (sym->ts.u.cl);
6827
6828       /* Force the expression to the correct length.  */
6829       if (!INTEGER_CST_P (se->string_length)
6830           || tree_int_cst_lt (se->string_length,
6831                               sym->ts.u.cl->backend_decl))
6832         {
6833           type = gfc_get_character_type (sym->ts.kind, sym->ts.u.cl);
6834           tmp = gfc_create_var (type, sym->name);
6835           tmp = gfc_build_addr_expr (build_pointer_type (type), tmp);
6836           gfc_trans_string_copy (&se->pre, sym->ts.u.cl->backend_decl, tmp,
6837                                  sym->ts.kind, se->string_length, se->expr,
6838                                  sym->ts.kind);
6839           se->expr = tmp;
6840         }
6841       se->string_length = sym->ts.u.cl->backend_decl;
6842     }
6843
6844   /* Restore the original variables.  */
6845   for (fargs = gfc_sym_get_dummy_args (sym), n = 0; fargs;
6846        fargs = fargs->next, n++)
6847     gfc_restore_sym (fargs->sym, &saved_vars[n]);
6848   free (temp_vars);
6849   free (saved_vars);
6850 }
6851
6852
6853 /* Translate a function expression.  */
6854
6855 static void
6856 gfc_conv_function_expr (gfc_se * se, gfc_expr * expr)
6857 {
6858   gfc_symbol *sym;
6859
6860   if (expr->value.function.isym)
6861     {
6862       gfc_conv_intrinsic_function (se, expr);
6863       return;
6864     }
6865
6866   /* expr.value.function.esym is the resolved (specific) function symbol for
6867      most functions.  However this isn't set for dummy procedures.  */
6868   sym = expr->value.function.esym;
6869   if (!sym)
6870     sym = expr->symtree->n.sym;
6871
6872   /* The IEEE_ARITHMETIC functions are caught here. */
6873   if (sym->from_intmod == INTMOD_IEEE_ARITHMETIC)
6874     if (gfc_conv_ieee_arithmetic_function (se, expr))
6875       return;
6876
6877   /* We distinguish statement functions from general functions to improve
6878      runtime performance.  */
6879   if (sym->attr.proc == PROC_ST_FUNCTION)
6880     {
6881       gfc_conv_statement_function (se, expr);
6882       return;
6883     }
6884
6885   gfc_conv_procedure_call (se, sym, expr->value.function.actual, expr,
6886                            NULL);
6887 }
6888
6889
6890 /* Determine whether the given EXPR_CONSTANT is a zero initializer.  */
6891
6892 static bool
6893 is_zero_initializer_p (gfc_expr * expr)
6894 {
6895   if (expr->expr_type != EXPR_CONSTANT)
6896     return false;
6897
6898   /* We ignore constants with prescribed memory representations for now.  */
6899   if (expr->representation.string)
6900     return false;
6901
6902   switch (expr->ts.type)
6903     {
6904     case BT_INTEGER:
6905       return mpz_cmp_si (expr->value.integer, 0) == 0;
6906
6907     case BT_REAL:
6908       return mpfr_zero_p (expr->value.real)
6909              && MPFR_SIGN (expr->value.real) >= 0;
6910
6911     case BT_LOGICAL:
6912       return expr->value.logical == 0;
6913
6914     case BT_COMPLEX:
6915       return mpfr_zero_p (mpc_realref (expr->value.complex))
6916              && MPFR_SIGN (mpc_realref (expr->value.complex)) >= 0
6917              && mpfr_zero_p (mpc_imagref (expr->value.complex))
6918              && MPFR_SIGN (mpc_imagref (expr->value.complex)) >= 0;
6919
6920     default:
6921       break;
6922     }
6923   return false;
6924 }
6925
6926
6927 static void
6928 gfc_conv_array_constructor_expr (gfc_se * se, gfc_expr * expr)
6929 {
6930   gfc_ss *ss;
6931
6932   ss = se->ss;
6933   gcc_assert (ss != NULL && ss != gfc_ss_terminator);
6934   gcc_assert (ss->info->expr == expr && ss->info->type == GFC_SS_CONSTRUCTOR);
6935
6936   gfc_conv_tmp_array_ref (se);
6937 }
6938
6939
6940 /* Build a static initializer.  EXPR is the expression for the initial value.
6941    The other parameters describe the variable of the component being
6942    initialized. EXPR may be null.  */
6943
6944 tree
6945 gfc_conv_initializer (gfc_expr * expr, gfc_typespec * ts, tree type,
6946                       bool array, bool pointer, bool procptr)
6947 {
6948   gfc_se se;
6949
6950   if (flag_coarray != GFC_FCOARRAY_LIB && ts->type == BT_DERIVED
6951       && ts->u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
6952       && ts->u.derived->intmod_sym_id == ISOFORTRAN_EVENT_TYPE)
6953     return build_constructor (type, NULL);
6954
6955   if (!(expr || pointer || procptr))
6956     return NULL_TREE;
6957
6958   /* Check if we have ISOCBINDING_NULL_PTR or ISOCBINDING_NULL_FUNPTR
6959      (these are the only two iso_c_binding derived types that can be
6960      used as initialization expressions).  If so, we need to modify
6961      the 'expr' to be that for a (void *).  */
6962   if (expr != NULL && expr->ts.type == BT_DERIVED
6963       && expr->ts.is_iso_c && expr->ts.u.derived)
6964     {
6965       gfc_symbol *derived = expr->ts.u.derived;
6966
6967       /* The derived symbol has already been converted to a (void *).  Use
6968          its kind.  */
6969       if (derived->ts.kind == 0)
6970         derived->ts.kind = gfc_default_integer_kind;
6971       expr = gfc_get_int_expr (derived->ts.kind, NULL, 0);
6972       expr->ts.f90_type = derived->ts.f90_type;
6973
6974       gfc_init_se (&se, NULL);
6975       gfc_conv_constant (&se, expr);
6976       gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
6977       return se.expr;
6978     }
6979
6980   if (array && !procptr)
6981     {
6982       tree ctor;
6983       /* Arrays need special handling.  */
6984       if (pointer)
6985         ctor = gfc_build_null_descriptor (type);
6986       /* Special case assigning an array to zero.  */
6987       else if (is_zero_initializer_p (expr))
6988         ctor = build_constructor (type, NULL);
6989       else
6990         ctor = gfc_conv_array_initializer (type, expr);
6991       TREE_STATIC (ctor) = 1;
6992       return ctor;
6993     }
6994   else if (pointer || procptr)
6995     {
6996       if (ts->type == BT_CLASS && !procptr)
6997         {
6998           gfc_init_se (&se, NULL);
6999           gfc_conv_structure (&se, gfc_class_initializer (ts, expr), 1);
7000           gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
7001           TREE_STATIC (se.expr) = 1;
7002           return se.expr;
7003         }
7004       else if (!expr || expr->expr_type == EXPR_NULL)
7005         return fold_convert (type, null_pointer_node);
7006       else
7007         {
7008           gfc_init_se (&se, NULL);
7009           se.want_pointer = 1;
7010           gfc_conv_expr (&se, expr);
7011           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
7012           return se.expr;
7013         }
7014     }
7015   else
7016     {
7017       switch (ts->type)
7018         {
7019         case_bt_struct:
7020         case BT_CLASS:
7021           gfc_init_se (&se, NULL);
7022           if (ts->type == BT_CLASS && expr->expr_type == EXPR_NULL)
7023             gfc_conv_structure (&se, gfc_class_initializer (ts, expr), 1);
7024           else
7025             gfc_conv_structure (&se, expr, 1);
7026           gcc_assert (TREE_CODE (se.expr) == CONSTRUCTOR);
7027           TREE_STATIC (se.expr) = 1;
7028           return se.expr;
7029
7030         case BT_CHARACTER:
7031           {
7032             tree ctor = gfc_conv_string_init (ts->u.cl->backend_decl,expr);
7033             TREE_STATIC (ctor) = 1;
7034             return ctor;
7035           }
7036
7037         default:
7038           gfc_init_se (&se, NULL);
7039           gfc_conv_constant (&se, expr);
7040           gcc_assert (TREE_CODE (se.expr) != CONSTRUCTOR);
7041           return se.expr;
7042         }
7043     }
7044 }
7045
7046 static tree
7047 gfc_trans_subarray_assign (tree dest, gfc_component * cm, gfc_expr * expr)
7048 {
7049   gfc_se rse;
7050   gfc_se lse;
7051   gfc_ss *rss;
7052   gfc_ss *lss;
7053   gfc_array_info *lss_array;
7054   stmtblock_t body;
7055   stmtblock_t block;
7056   gfc_loopinfo loop;
7057   int n;
7058   tree tmp;
7059
7060   gfc_start_block (&block);
7061
7062   /* Initialize the scalarizer.  */
7063   gfc_init_loopinfo (&loop);
7064
7065   gfc_init_se (&lse, NULL);
7066   gfc_init_se (&rse, NULL);
7067
7068   /* Walk the rhs.  */
7069   rss = gfc_walk_expr (expr);
7070   if (rss == gfc_ss_terminator)
7071     /* The rhs is scalar.  Add a ss for the expression.  */
7072     rss = gfc_get_scalar_ss (gfc_ss_terminator, expr);
7073
7074   /* Create a SS for the destination.  */
7075   lss = gfc_get_array_ss (gfc_ss_terminator, NULL, cm->as->rank,
7076                           GFC_SS_COMPONENT);
7077   lss_array = &lss->info->data.array;
7078   lss_array->shape = gfc_get_shape (cm->as->rank);
7079   lss_array->descriptor = dest;
7080   lss_array->data = gfc_conv_array_data (dest);
7081   lss_array->offset = gfc_conv_array_offset (dest);
7082   for (n = 0; n < cm->as->rank; n++)
7083     {
7084       lss_array->start[n] = gfc_conv_array_lbound (dest, n);
7085       lss_array->stride[n] = gfc_index_one_node;
7086
7087       mpz_init (lss_array->shape[n]);
7088       mpz_sub (lss_array->shape[n], cm->as->upper[n]->value.integer,
7089                cm->as->lower[n]->value.integer);
7090       mpz_add_ui (lss_array->shape[n], lss_array->shape[n], 1);
7091     }
7092
7093   /* Associate the SS with the loop.  */
7094   gfc_add_ss_to_loop (&loop, lss);
7095   gfc_add_ss_to_loop (&loop, rss);
7096
7097   /* Calculate the bounds of the scalarization.  */
7098   gfc_conv_ss_startstride (&loop);
7099
7100   /* Setup the scalarizing loops.  */
7101   gfc_conv_loop_setup (&loop, &expr->where);
7102
7103   /* Setup the gfc_se structures.  */
7104   gfc_copy_loopinfo_to_se (&lse, &loop);
7105   gfc_copy_loopinfo_to_se (&rse, &loop);
7106
7107   rse.ss = rss;
7108   gfc_mark_ss_chain_used (rss, 1);
7109   lse.ss = lss;
7110   gfc_mark_ss_chain_used (lss, 1);
7111
7112   /* Start the scalarized loop body.  */
7113   gfc_start_scalarized_body (&loop, &body);
7114
7115   gfc_conv_tmp_array_ref (&lse);
7116   if (cm->ts.type == BT_CHARACTER)
7117     lse.string_length = cm->ts.u.cl->backend_decl;
7118
7119   gfc_conv_expr (&rse, expr);
7120
7121   tmp = gfc_trans_scalar_assign (&lse, &rse, cm->ts, true, false);
7122   gfc_add_expr_to_block (&body, tmp);
7123
7124   gcc_assert (rse.ss == gfc_ss_terminator);
7125
7126   /* Generate the copying loops.  */
7127   gfc_trans_scalarizing_loops (&loop, &body);
7128
7129   /* Wrap the whole thing up.  */
7130   gfc_add_block_to_block (&block, &loop.pre);
7131   gfc_add_block_to_block (&block, &loop.post);
7132
7133   gcc_assert (lss_array->shape != NULL);
7134   gfc_free_shape (&lss_array->shape, cm->as->rank);
7135   gfc_cleanup_loop (&loop);
7136
7137   return gfc_finish_block (&block);
7138 }
7139
7140
7141 static tree
7142 gfc_trans_alloc_subarray_assign (tree dest, gfc_component * cm,
7143                                  gfc_expr * expr)
7144 {
7145   gfc_se se;
7146   stmtblock_t block;
7147   tree offset;
7148   int n;
7149   tree tmp;
7150   tree tmp2;
7151   gfc_array_spec *as;
7152   gfc_expr *arg = NULL;
7153
7154   gfc_start_block (&block);
7155   gfc_init_se (&se, NULL);
7156
7157   /* Get the descriptor for the expressions.  */
7158   se.want_pointer = 0;
7159   gfc_conv_expr_descriptor (&se, expr);
7160   gfc_add_block_to_block (&block, &se.pre);
7161   gfc_add_modify (&block, dest, se.expr);
7162
7163   /* Deal with arrays of derived types with allocatable components.  */
7164   if (gfc_bt_struct (cm->ts.type)
7165         && cm->ts.u.derived->attr.alloc_comp)
7166     // TODO: Fix caf_mode
7167     tmp = gfc_copy_alloc_comp (cm->ts.u.derived,
7168                                se.expr, dest,
7169                                cm->as->rank, 0);
7170   else if (cm->ts.type == BT_CLASS && expr->ts.type == BT_DERIVED
7171            && CLASS_DATA(cm)->attr.allocatable)
7172     {
7173       if (cm->ts.u.derived->attr.alloc_comp)
7174         // TODO: Fix caf_mode
7175         tmp = gfc_copy_alloc_comp (expr->ts.u.derived,
7176                                    se.expr, dest,
7177                                    expr->rank, 0);
7178       else
7179         {
7180           tmp = TREE_TYPE (dest);
7181           tmp = gfc_duplicate_allocatable (dest, se.expr,
7182                                            tmp, expr->rank, NULL_TREE);
7183         }
7184     }
7185   else
7186     tmp = gfc_duplicate_allocatable (dest, se.expr,
7187                                      TREE_TYPE(cm->backend_decl),
7188                                      cm->as->rank, NULL_TREE);
7189
7190   gfc_add_expr_to_block (&block, tmp);
7191   gfc_add_block_to_block (&block, &se.post);
7192
7193   if (expr->expr_type != EXPR_VARIABLE)
7194     gfc_conv_descriptor_data_set (&block, se.expr,
7195                                   null_pointer_node);
7196
7197   /* We need to know if the argument of a conversion function is a
7198      variable, so that the correct lower bound can be used.  */
7199   if (expr->expr_type == EXPR_FUNCTION
7200         && expr->value.function.isym
7201         && expr->value.function.isym->conversion
7202         && expr->value.function.actual->expr
7203         && expr->value.function.actual->expr->expr_type == EXPR_VARIABLE)
7204     arg = expr->value.function.actual->expr;
7205
7206   /* Obtain the array spec of full array references.  */
7207   if (arg)
7208     as = gfc_get_full_arrayspec_from_expr (arg);
7209   else
7210     as = gfc_get_full_arrayspec_from_expr (expr);
7211
7212   /* Shift the lbound and ubound of temporaries to being unity,
7213      rather than zero, based. Always calculate the offset.  */
7214   offset = gfc_conv_descriptor_offset_get (dest);
7215   gfc_add_modify (&block, offset, gfc_index_zero_node);
7216   tmp2 =gfc_create_var (gfc_array_index_type, NULL);
7217
7218   for (n = 0; n < expr->rank; n++)
7219     {
7220       tree span;
7221       tree lbound;
7222
7223       /* Obtain the correct lbound - ISO/IEC TR 15581:2001 page 9.
7224          TODO It looks as if gfc_conv_expr_descriptor should return
7225          the correct bounds and that the following should not be
7226          necessary.  This would simplify gfc_conv_intrinsic_bound
7227          as well.  */
7228       if (as && as->lower[n])
7229         {
7230           gfc_se lbse;
7231           gfc_init_se (&lbse, NULL);
7232           gfc_conv_expr (&lbse, as->lower[n]);
7233           gfc_add_block_to_block (&block, &lbse.pre);
7234           lbound = gfc_evaluate_now (lbse.expr, &block);
7235         }
7236       else if (as && arg)
7237         {
7238           tmp = gfc_get_symbol_decl (arg->symtree->n.sym);
7239           lbound = gfc_conv_descriptor_lbound_get (tmp,
7240                                         gfc_rank_cst[n]);
7241         }
7242       else if (as)
7243         lbound = gfc_conv_descriptor_lbound_get (dest,
7244                                                 gfc_rank_cst[n]);
7245       else
7246         lbound = gfc_index_one_node;
7247
7248       lbound = fold_convert (gfc_array_index_type, lbound);
7249
7250       /* Shift the bounds and set the offset accordingly.  */
7251       tmp = gfc_conv_descriptor_ubound_get (dest, gfc_rank_cst[n]);
7252       span = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
7253                 tmp, gfc_conv_descriptor_lbound_get (dest, gfc_rank_cst[n]));
7254       tmp = fold_build2_loc (input_location, PLUS_EXPR, gfc_array_index_type,
7255                              span, lbound);
7256       gfc_conv_descriptor_ubound_set (&block, dest,
7257                                       gfc_rank_cst[n], tmp);
7258       gfc_conv_descriptor_lbound_set (&block, dest,
7259                                       gfc_rank_cst[n], lbound);
7260
7261       tmp = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
7262                          gfc_conv_descriptor_lbound_get (dest,
7263                                                          gfc_rank_cst[n]),
7264                          gfc_conv_descriptor_stride_get (dest,
7265                                                          gfc_rank_cst[n]));
7266       gfc_add_modify (&block, tmp2, tmp);
7267       tmp = fold_build2_loc (input_location, MINUS_EXPR, gfc_array_index_type,
7268                              offset, tmp2);
7269       gfc_conv_descriptor_offset_set (&block, dest, tmp);
7270     }
7271
7272   if (arg)
7273     {
7274       /* If a conversion expression has a null data pointer
7275          argument, nullify the allocatable component.  */
7276       tree non_null_expr;
7277       tree null_expr;
7278
7279       if (arg->symtree->n.sym->attr.allocatable
7280             || arg->symtree->n.sym->attr.pointer)
7281         {
7282           non_null_expr = gfc_finish_block (&block);
7283           gfc_start_block (&block);
7284           gfc_conv_descriptor_data_set (&block, dest,
7285                                         null_pointer_node);
7286           null_expr = gfc_finish_block (&block);
7287           tmp = gfc_conv_descriptor_data_get (arg->symtree->n.sym->backend_decl);
7288           tmp = build2_loc (input_location, EQ_EXPR, logical_type_node, tmp,
7289                             fold_convert (TREE_TYPE (tmp), null_pointer_node));
7290           return build3_v (COND_EXPR, tmp,
7291                            null_expr, non_null_expr);
7292         }
7293     }
7294
7295   return gfc_finish_block (&block);
7296 }
7297
7298
7299 /* Allocate or reallocate scalar component, as necessary.  */
7300
7301 static void
7302 alloc_scalar_allocatable_for_subcomponent_assignment (stmtblock_t *block,
7303                                                       tree comp,
7304                                                       gfc_component *cm,
7305                                                       gfc_expr *expr2,
7306                                                       gfc_symbol *sym)
7307 {
7308   tree tmp;
7309   tree ptr;
7310   tree size;
7311   tree size_in_bytes;
7312   tree lhs_cl_size = NULL_TREE;
7313
7314   if (!comp)
7315     return;
7316
7317   if (!expr2 || expr2->rank)
7318     return;
7319
7320   realloc_lhs_warning (expr2->ts.type, false, &expr2->where);
7321
7322   if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
7323     {
7324       char name[GFC_MAX_SYMBOL_LEN+9];
7325       gfc_component *strlen;
7326       /* Use the rhs string length and the lhs element size.  */
7327       gcc_assert (expr2->ts.type == BT_CHARACTER);
7328       if (!expr2->ts.u.cl->backend_decl)
7329         {
7330           gfc_conv_string_length (expr2->ts.u.cl, expr2, block);
7331           gcc_assert (expr2->ts.u.cl->backend_decl);
7332         }
7333
7334       size = expr2->ts.u.cl->backend_decl;
7335
7336       /* Ensure that cm->ts.u.cl->backend_decl is a componentref to _%s_length
7337          component.  */
7338       sprintf (name, "_%s_length", cm->name);
7339       strlen = gfc_find_component (sym, name, true, true, NULL);
7340       lhs_cl_size = fold_build3_loc (input_location, COMPONENT_REF,
7341                                      gfc_charlen_type_node,
7342                                      TREE_OPERAND (comp, 0),
7343                                      strlen->backend_decl, NULL_TREE);
7344
7345       tmp = TREE_TYPE (gfc_typenode_for_spec (&cm->ts));
7346       tmp = TYPE_SIZE_UNIT (tmp);
7347       size_in_bytes = fold_build2_loc (input_location, MULT_EXPR,
7348                                        TREE_TYPE (tmp), tmp,
7349                                        fold_convert (TREE_TYPE (tmp), size));
7350     }
7351   else if (cm->ts.type == BT_CLASS)
7352     {
7353       gcc_assert (expr2->ts.type == BT_CLASS || expr2->ts.type == BT_DERIVED);
7354       if (expr2->ts.type == BT_DERIVED)
7355         {
7356           tmp = gfc_get_symbol_decl (expr2->ts.u.derived);
7357           size = TYPE_SIZE_UNIT (tmp);
7358         }
7359       else
7360         {
7361           gfc_expr *e2vtab;
7362           gfc_se se;
7363           e2vtab = gfc_find_and_cut_at_last_class_ref (expr2);
7364           gfc_add_vptr_component (e2vtab);
7365           gfc_add_size_component (e2vtab);
7366           gfc_init_se (&se, NULL);
7367           gfc_conv_expr (&se, e2vtab);
7368           gfc_add_block_to_block (block, &se.pre);
7369           size = fold_convert (size_type_node, se.expr);
7370           gfc_free_expr (e2vtab);
7371         }
7372       size_in_bytes = size;
7373     }
7374   else
7375     {
7376       /* Otherwise use the length in bytes of the rhs.  */
7377       size = TYPE_SIZE_UNIT (gfc_typenode_for_spec (&cm->ts));
7378       size_in_bytes = size;
7379     }
7380
7381   size_in_bytes = fold_build2_loc (input_location, MAX_EXPR, size_type_node,
7382                                    size_in_bytes, size_one_node);
7383
7384   if (cm->ts.type == BT_DERIVED && cm->ts.u.derived->attr.alloc_comp)
7385     {
7386       tmp = build_call_expr_loc (input_location,
7387                                  builtin_decl_explicit (BUILT_IN_CALLOC),
7388                                  2, build_one_cst (size_type_node),
7389                                  size_in_bytes);
7390       tmp = fold_convert (TREE_TYPE (comp), tmp);
7391       gfc_add_modify (block, comp, tmp);
7392     }
7393   else
7394     {
7395       tmp = build_call_expr_loc (input_location,
7396                                  builtin_decl_explicit (BUILT_IN_MALLOC),
7397                                  1, size_in_bytes);
7398       if (GFC_CLASS_TYPE_P (TREE_TYPE (comp)))
7399         ptr = gfc_class_data_get (comp);
7400       else
7401         ptr = comp;
7402       tmp = fold_convert (TREE_TYPE (ptr), tmp);
7403       gfc_add_modify (block, ptr, tmp);
7404     }
7405
7406   if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
7407     /* Update the lhs character length.  */
7408     gfc_add_modify (block, lhs_cl_size,
7409                     fold_convert (TREE_TYPE (lhs_cl_size), size));
7410 }
7411
7412
7413 /* Assign a single component of a derived type constructor.  */
7414
7415 static tree
7416 gfc_trans_subcomponent_assign (tree dest, gfc_component * cm, gfc_expr * expr,
7417                                gfc_symbol *sym, bool init)
7418 {
7419   gfc_se se;
7420   gfc_se lse;
7421   stmtblock_t block;
7422   tree tmp;
7423   tree vtab;
7424
7425   gfc_start_block (&block);
7426
7427   if (cm->attr.pointer || cm->attr.proc_pointer)
7428     {
7429       /* Only care about pointers here, not about allocatables.  */
7430       gfc_init_se (&se, NULL);
7431       /* Pointer component.  */
7432       if ((cm->attr.dimension || cm->attr.codimension)
7433           && !cm->attr.proc_pointer)
7434         {
7435           /* Array pointer.  */
7436           if (expr->expr_type == EXPR_NULL)
7437             gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
7438           else
7439             {
7440               se.direct_byref = 1;
7441               se.expr = dest;
7442               gfc_conv_expr_descriptor (&se, expr);
7443               gfc_add_block_to_block (&block, &se.pre);
7444               gfc_add_block_to_block (&block, &se.post);
7445             }
7446         }
7447       else
7448         {
7449           /* Scalar pointers.  */
7450           se.want_pointer = 1;
7451           gfc_conv_expr (&se, expr);
7452           gfc_add_block_to_block (&block, &se.pre);
7453
7454           if (expr->symtree && expr->symtree->n.sym->attr.proc_pointer
7455               && expr->symtree->n.sym->attr.dummy)
7456             se.expr = build_fold_indirect_ref_loc (input_location, se.expr);
7457
7458           gfc_add_modify (&block, dest,
7459                                fold_convert (TREE_TYPE (dest), se.expr));
7460           gfc_add_block_to_block (&block, &se.post);
7461         }
7462     }
7463   else if (cm->ts.type == BT_CLASS && expr->expr_type == EXPR_NULL)
7464     {
7465       /* NULL initialization for CLASS components.  */
7466       tmp = gfc_trans_structure_assign (dest,
7467                                         gfc_class_initializer (&cm->ts, expr),
7468                                         false);
7469       gfc_add_expr_to_block (&block, tmp);
7470     }
7471   else if ((cm->attr.dimension || cm->attr.codimension)
7472            && !cm->attr.proc_pointer)
7473     {
7474       if (cm->attr.allocatable && expr->expr_type == EXPR_NULL)
7475         gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
7476       else if (cm->attr.allocatable || cm->attr.pdt_array)
7477         {
7478           tmp = gfc_trans_alloc_subarray_assign (dest, cm, expr);
7479           gfc_add_expr_to_block (&block, tmp);
7480         }
7481       else
7482         {
7483           tmp = gfc_trans_subarray_assign (dest, cm, expr);
7484           gfc_add_expr_to_block (&block, tmp);
7485         }
7486     }
7487   else if (cm->ts.type == BT_CLASS
7488            && CLASS_DATA (cm)->attr.dimension
7489            && CLASS_DATA (cm)->attr.allocatable
7490            && expr->ts.type == BT_DERIVED)
7491     {
7492       vtab = gfc_get_symbol_decl (gfc_find_vtab (&expr->ts));
7493       vtab = gfc_build_addr_expr (NULL_TREE, vtab);
7494       tmp = gfc_class_vptr_get (dest);
7495       gfc_add_modify (&block, tmp,
7496                       fold_convert (TREE_TYPE (tmp), vtab));
7497       tmp = gfc_class_data_get (dest);
7498       tmp = gfc_trans_alloc_subarray_assign (tmp, cm, expr);
7499       gfc_add_expr_to_block (&block, tmp);
7500     }
7501   else if (init && cm->attr.allocatable && expr->expr_type == EXPR_NULL)
7502     {
7503       /* NULL initialization for allocatable components.  */
7504       gfc_add_modify (&block, dest, fold_convert (TREE_TYPE (dest),
7505                                                   null_pointer_node));
7506     }
7507   else if (init && (cm->attr.allocatable
7508            || (cm->ts.type == BT_CLASS && CLASS_DATA (cm)->attr.allocatable
7509                && expr->ts.type != BT_CLASS)))
7510     {
7511       /* Take care about non-array allocatable components here.  The alloc_*
7512          routine below is motivated by the alloc_scalar_allocatable_for_
7513          assignment() routine, but with the realloc portions removed and
7514          different input.  */
7515       alloc_scalar_allocatable_for_subcomponent_assignment (&block,
7516                                                             dest,
7517                                                             cm,
7518                                                             expr,
7519                                                             sym);
7520       /* The remainder of these instructions follow the if (cm->attr.pointer)
7521          if (!cm->attr.dimension) part above.  */
7522       gfc_init_se (&se, NULL);
7523       gfc_conv_expr (&se, expr);
7524       gfc_add_block_to_block (&block, &se.pre);
7525
7526       if (expr->symtree && expr->symtree->n.sym->attr.proc_pointer
7527           && expr->symtree->n.sym->attr.dummy)
7528         se.expr = build_fold_indirect_ref_loc (input_location, se.expr);
7529
7530       if (cm->ts.type == BT_CLASS && expr->ts.type == BT_DERIVED)
7531         {
7532           tmp = gfc_class_data_get (dest);
7533           tmp = build_fold_indirect_ref_loc (input_location, tmp);
7534           vtab = gfc_get_symbol_decl (gfc_find_vtab (&expr->ts));
7535           vtab = gfc_build_addr_expr (NULL_TREE, vtab);
7536           gfc_add_modify (&block, gfc_class_vptr_get (dest),
7537                  fold_convert (TREE_TYPE (gfc_class_vptr_get (dest)), vtab));
7538         }
7539       else
7540         tmp = build_fold_indirect_ref_loc (input_location, dest);
7541
7542       /* For deferred strings insert a memcpy.  */
7543       if (cm->ts.type == BT_CHARACTER && cm->ts.deferred)
7544         {
7545           tree size;
7546           gcc_assert (se.string_length || expr->ts.u.cl->backend_decl);
7547           size = size_of_string_in_bytes (cm->ts.kind, se.string_length
7548                                                 ? se.string_length
7549                                                 : expr->ts.u.cl->backend_decl);
7550           tmp = gfc_build_memcpy_call (tmp, se.expr, size);
7551           gfc_add_expr_to_block (&block, tmp);
7552         }
7553       else
7554         gfc_add_modify (&block, tmp,
7555                         fold_convert (TREE_TYPE (tmp), se.expr));
7556       gfc_add_block_to_block (&block, &se.post);
7557     }
7558   else if (expr->ts.type == BT_UNION)
7559     {
7560       tree tmp;
7561       gfc_constructor *c = gfc_constructor_first (expr->value.constructor);
7562       /* We mark that the entire union should be initialized with a contrived
7563          EXPR_NULL expression at the beginning.  */
7564       if (c != NULL && c->n.component == NULL
7565           && c->expr != NULL && c->expr->expr_type == EXPR_NULL)
7566         {
7567           tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
7568                             dest, build_constructor (TREE_TYPE (dest), NULL));
7569           gfc_add_expr_to_block (&block, tmp);
7570           c = gfc_constructor_next (c);
7571         }
7572       /* The following constructor expression, if any, represents a specific
7573          map intializer, as given by the user.  */
7574       if (c != NULL && c->expr != NULL)
7575         {
7576           gcc_assert (expr->expr_type == EXPR_STRUCTURE);
7577           tmp = gfc_trans_structure_assign (dest, expr, expr->symtree != NULL);
7578           gfc_add_expr_to_block (&block, tmp);
7579         }
7580     }
7581   else if (expr->ts.type == BT_DERIVED && expr->ts.f90_type != BT_VOID)
7582     {
7583       if (expr->expr_type != EXPR_STRUCTURE)
7584         {
7585           tree dealloc = NULL_TREE;
7586           gfc_init_se (&se, NULL);
7587           gfc_conv_expr (&se, expr);
7588           gfc_add_block_to_block (&block, &se.pre);
7589           /* Prevent repeat evaluations in gfc_copy_alloc_comp by fixing the
7590              expression in  a temporary variable and deallocate the allocatable
7591              components. Then we can the copy the expression to the result.  */
7592           if (cm->ts.u.derived->attr.alloc_comp
7593               && expr->expr_type != EXPR_VARIABLE)
7594             {
7595               se.expr = gfc_evaluate_now (se.expr, &block);
7596               dealloc = gfc_deallocate_alloc_comp (cm->ts.u.derived, se.expr,
7597                                                    expr->rank);
7598             }
7599           gfc_add_modify (&block, dest,
7600                           fold_convert (TREE_TYPE (dest), se.expr));
7601           if (cm->ts.u.derived->attr.alloc_comp
7602               && expr->expr_type != EXPR_NULL)
7603             {
7604               // TODO: Fix caf_mode
7605               tmp = gfc_copy_alloc_comp (cm->ts.u.derived, se.expr,
7606                                          dest, expr->rank, 0);
7607               gfc_add_expr_to_block (&block, tmp);
7608               if (dealloc != NULL_TREE)
7609                 gfc_add_expr_to_block (&block, dealloc);
7610             }
7611           gfc_add_block_to_block (&block, &se.post);
7612         }
7613       else
7614         {
7615           /* Nested constructors.  */
7616           tmp = gfc_trans_structure_assign (dest, expr, expr->symtree != NULL);
7617           gfc_add_expr_to_block (&block, tmp);
7618         }
7619     }
7620   else if (gfc_deferred_strlen (cm, &tmp))
7621     {
7622       tree strlen;
7623       strlen = tmp;
7624       gcc_assert (strlen);
7625       strlen = fold_build3_loc (input_location, COMPONENT_REF,
7626                                 TREE_TYPE (strlen),
7627                                 TREE_OPERAND (dest, 0),
7628                                 strlen, NULL_TREE);
7629
7630       if (expr->expr_type == EXPR_NULL)
7631         {
7632           tmp = build_int_cst (TREE_TYPE (cm->backend_decl), 0);
7633           gfc_add_modify (&block, dest, tmp);
7634           tmp = build_int_cst (TREE_TYPE (strlen), 0);
7635           gfc_add_modify (&block, strlen, tmp);
7636         }
7637       else
7638         {
7639           tree size;
7640           gfc_init_se (&se, NULL);
7641           gfc_conv_expr (&se, expr);
7642           size = size_of_string_in_bytes (cm->ts.kind, se.string_length);
7643           tmp = build_call_expr_loc (input_location,
7644                                      builtin_decl_explicit (BUILT_IN_MALLOC),
7645                                      1, size);
7646           gfc_add_modify (&block, dest,
7647                           fold_convert (TREE_TYPE (dest), tmp));
7648           gfc_add_modify (&block, strlen,
7649                           fold_convert (TREE_TYPE (strlen), se.string_length));
7650           tmp = gfc_build_memcpy_call (dest, se.expr, size);
7651           gfc_add_expr_to_block (&block, tmp);
7652         }
7653     }
7654   else if (!cm->attr.artificial)
7655     {
7656       /* Scalar component (excluding deferred parameters).  */
7657       gfc_init_se (&se, NULL);
7658       gfc_init_se (&lse, NULL);
7659
7660       gfc_conv_expr (&se, expr);
7661       if (cm->ts.type == BT_CHARACTER)
7662         lse.string_length = cm->ts.u.cl->backend_decl;
7663       lse.expr = dest;
7664       tmp = gfc_trans_scalar_assign (&lse, &se, cm->ts, false, false);
7665       gfc_add_expr_to_block (&block, tmp);
7666     }
7667   return gfc_finish_block (&block);
7668 }
7669
7670 /* Assign a derived type constructor to a variable.  */
7671
7672 tree
7673 gfc_trans_structure_assign (tree dest, gfc_expr * expr, bool init, bool coarray)
7674 {
7675   gfc_constructor *c;
7676   gfc_component *cm;
7677   stmtblock_t block;
7678   tree field;
7679   tree tmp;
7680   gfc_se se;
7681
7682   gfc_start_block (&block);
7683   cm = expr->ts.u.derived->components;
7684
7685   if (expr->ts.u.derived->from_intmod == INTMOD_ISO_C_BINDING
7686       && (expr->ts.u.derived->intmod_sym_id == ISOCBINDING_PTR
7687           || expr->ts.u.derived->intmod_sym_id == ISOCBINDING_FUNPTR))
7688     {
7689       gfc_se lse;
7690
7691       gfc_init_se (&se, NULL);
7692       gfc_init_se (&lse, NULL);
7693       gfc_conv_expr (&se, gfc_constructor_first (expr->value.constructor)->expr);
7694       lse.expr = dest;
7695       gfc_add_modify (&block, lse.expr,
7696                       fold_convert (TREE_TYPE (lse.expr), se.expr));
7697
7698       return gfc_finish_block (&block);
7699     }
7700
7701   if (coarray)
7702     gfc_init_se (&se, NULL);
7703
7704   for (c = gfc_constructor_first (expr->value.constructor);
7705        c; c = gfc_constructor_next (c), cm = cm->next)
7706     {
7707       /* Skip absent members in default initializers.  */
7708       if (!c->expr && !cm->attr.allocatable)
7709         continue;
7710
7711       /* Register the component with the caf-lib before it is initialized.
7712          Register only allocatable components, that are not coarray'ed
7713          components (%comp[*]).  Only register when the constructor is not the
7714          null-expression.  */
7715       if (coarray && !cm->attr.codimension
7716           && (cm->attr.allocatable || cm->attr.pointer)
7717           && (!c->expr || c->expr->expr_type == EXPR_NULL))
7718         {
7719           tree token, desc, size;
7720           bool is_array = cm->ts.type == BT_CLASS
7721               ? CLASS_DATA (cm)->attr.dimension : cm->attr.dimension;
7722
7723           field = cm->backend_decl;
7724           field = fold_build3_loc (input_location, COMPONENT_REF,
7725                                    TREE_TYPE (field), dest, field, NULL_TREE);
7726           if (cm->ts.type == BT_CLASS)
7727             field = gfc_class_data_get (field);
7728
7729           token = is_array ? gfc_conv_descriptor_token (field)
7730                            : fold_build3_loc (input_location, COMPONENT_REF,
7731                                               TREE_TYPE (cm->caf_token), dest,
7732                                               cm->caf_token, NULL_TREE);
7733
7734           if (is_array)
7735             {
7736               /* The _caf_register routine looks at the rank of the array
7737                  descriptor to decide whether the data registered is an array
7738                  or not.  */
7739               int rank = cm->ts.type == BT_CLASS ? CLASS_DATA (cm)->as->rank
7740                                                  : cm->as->rank;
7741               /* When the rank is not known just set a positive rank, which
7742                  suffices to recognize the data as array.  */
7743               if (rank < 0)
7744                 rank = 1;
7745               size = build_zero_cst (size_type_node);
7746               desc = field;
7747               gfc_add_modify (&block, gfc_conv_descriptor_rank (desc),
7748                               build_int_cst (signed_char_type_node, rank));
7749             }
7750           else
7751             {
7752               desc = gfc_conv_scalar_to_descriptor (&se, field,
7753                                                     cm->ts.type == BT_CLASS
7754                                                     ? CLASS_DATA (cm)->attr
7755                                                     : cm->attr);
7756               size = TYPE_SIZE_UNIT (TREE_TYPE (field));
7757             }
7758           gfc_add_block_to_block (&block, &se.pre);
7759           tmp =  build_call_expr_loc (input_location, gfor_fndecl_caf_register,
7760                                       7, size, build_int_cst (
7761                                         integer_type_node,
7762                                         GFC_CAF_COARRAY_ALLOC_REGISTER_ONLY),
7763                                       gfc_build_addr_expr (pvoid_type_node,
7764                                                            token),
7765                                       gfc_build_addr_expr (NULL_TREE, desc),
7766                                       null_pointer_node, null_pointer_node,
7767                                       integer_zero_node);
7768           gfc_add_expr_to_block (&block, tmp);
7769         }
7770       field = cm->backend_decl;
7771       tmp = fold_build3_loc (input_location, COMPONENT_REF, TREE_TYPE (field),
7772                              dest, field, NULL_TREE);
7773       if (!c->expr)
7774         {
7775           gfc_expr *e = gfc_get_null_expr (NULL);
7776           tmp = gfc_trans_subcomponent_assign (tmp, cm, e, expr->ts.u.derived,
7777                                                init);
7778           gfc_free_expr (e);
7779         }
7780       else
7781         tmp = gfc_trans_subcomponent_assign (tmp, cm, c->expr,
7782                                              expr->ts.u.derived, init);
7783       gfc_add_expr_to_block (&block, tmp);
7784     }
7785   return gfc_finish_block (&block);
7786 }
7787
7788 void
7789 gfc_conv_union_initializer (vec<constructor_elt, va_gc> *v,
7790                             gfc_component *un, gfc_expr *init)
7791 {
7792   gfc_constructor *ctor;
7793
7794   if (un->ts.type != BT_UNION || un == NULL || init == NULL)
7795     return;
7796
7797   ctor = gfc_constructor_first (init->value.constructor);
7798
7799   if (ctor == NULL || ctor->expr == NULL)
7800     return;
7801
7802   gcc_assert (init->expr_type == EXPR_STRUCTURE);
7803
7804   /* If we have an 'initialize all' constructor, do it first.  */
7805   if (ctor->expr->expr_type == EXPR_NULL)
7806     {
7807       tree union_type = TREE_TYPE (un->backend_decl);
7808       tree val = build_constructor (union_type, NULL);
7809       CONSTRUCTOR_APPEND_ELT (v, un->backend_decl, val);
7810       ctor = gfc_constructor_next (ctor);
7811     }
7812
7813   /* Add the map initializer on top.  */
7814   if (ctor != NULL && ctor->expr != NULL)
7815     {
7816       gcc_assert (ctor->expr->expr_type == EXPR_STRUCTURE);
7817       tree val = gfc_conv_initializer (ctor->expr, &un->ts,
7818                                        TREE_TYPE (un->backend_decl),
7819                                        un->attr.dimension, un->attr.pointer,
7820                                        un->attr.proc_pointer);
7821       CONSTRUCTOR_APPEND_ELT (v, un->backend_decl, val);
7822     }
7823 }
7824
7825 /* Build an expression for a constructor. If init is nonzero then
7826    this is part of a static variable initializer.  */
7827
7828 void
7829 gfc_conv_structure (gfc_se * se, gfc_expr * expr, int init)
7830 {
7831   gfc_constructor *c;
7832   gfc_component *cm;
7833   tree val;
7834   tree type;
7835   tree tmp;
7836   vec<constructor_elt, va_gc> *v = NULL;
7837
7838   gcc_assert (se->ss == NULL);
7839   gcc_assert (expr->expr_type == EXPR_STRUCTURE);
7840   type = gfc_typenode_for_spec (&expr->ts);
7841
7842   if (!init)
7843     {
7844       /* Create a temporary variable and fill it in.  */
7845       se->expr = gfc_create_var (type, expr->ts.u.derived->name);
7846       /* The symtree in expr is NULL, if the code to generate is for
7847          initializing the static members only.  */
7848       tmp = gfc_trans_structure_assign (se->expr, expr, expr->symtree != NULL,
7849                                         se->want_coarray);
7850       gfc_add_expr_to_block (&se->pre, tmp);
7851       return;
7852     }
7853
7854   cm = expr->ts.u.derived->components;
7855
7856   for (c = gfc_constructor_first (expr->value.constructor);
7857        c; c = gfc_constructor_next (c), cm = cm->next)
7858     {
7859       /* Skip absent members in default initializers and allocatable
7860          components.  Although the latter have a default initializer
7861          of EXPR_NULL,... by default, the static nullify is not needed
7862          since this is done every time we come into scope.  */
7863       if (!c->expr || (cm->attr.allocatable && cm->attr.flavor != FL_PROCEDURE))
7864         continue;
7865
7866       if (cm->initializer && cm->initializer->expr_type != EXPR_NULL
7867           && strcmp (cm->name, "_extends") == 0
7868           && cm->initializer->symtree)
7869         {
7870           tree vtab;
7871           gfc_symbol *vtabs;
7872           vtabs = cm->initializer->symtree->n.sym;
7873           vtab = gfc_build_addr_expr (NULL_TREE, gfc_get_symbol_decl (vtabs));
7874           vtab = unshare_expr_without_location (vtab);
7875           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, vtab);
7876         }
7877       else if (cm->ts.u.derived && strcmp (cm->name, "_size") == 0)
7878         {
7879           val = TYPE_SIZE_UNIT (gfc_get_derived_type (cm->ts.u.derived));
7880           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl,
7881                                   fold_convert (TREE_TYPE (cm->backend_decl),
7882                                                 val));
7883         }
7884       else if (cm->ts.type == BT_INTEGER && strcmp (cm->name, "_len") == 0)
7885         CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl,
7886                                 fold_convert (TREE_TYPE (cm->backend_decl),
7887                                               integer_zero_node));
7888       else if (cm->ts.type == BT_UNION)
7889         gfc_conv_union_initializer (v, cm, c->expr);
7890       else
7891         {
7892           val = gfc_conv_initializer (c->expr, &cm->ts,
7893                                       TREE_TYPE (cm->backend_decl),
7894                                       cm->attr.dimension, cm->attr.pointer,
7895                                       cm->attr.proc_pointer);
7896           val = unshare_expr_without_location (val);
7897
7898           /* Append it to the constructor list.  */
7899           CONSTRUCTOR_APPEND_ELT (v, cm->backend_decl, val);
7900         }
7901     }
7902
7903   se->expr = build_constructor (type, v);
7904   if (init)
7905     TREE_CONSTANT (se->expr) = 1;
7906 }
7907
7908
7909 /* Translate a substring expression.  */
7910
7911 static void
7912 gfc_conv_substring_expr (gfc_se * se, gfc_expr * expr)
7913 {
7914   gfc_ref *ref;
7915
7916   ref = expr->ref;
7917
7918   gcc_assert (ref == NULL || ref->type == REF_SUBSTRING);
7919
7920   se->expr = gfc_build_wide_string_const (expr->ts.kind,
7921                                           expr->value.character.length,
7922                                           expr->value.character.string);
7923
7924   se->string_length = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (se->expr)));
7925   TYPE_STRING_FLAG (TREE_TYPE (se->expr)) = 1;
7926
7927   if (ref)
7928     gfc_conv_substring (se, ref, expr->ts.kind, NULL, &expr->where);
7929 }
7930
7931
7932 /* Entry point for expression translation.  Evaluates a scalar quantity.
7933    EXPR is the expression to be translated, and SE is the state structure if
7934    called from within the scalarized.  */
7935
7936 void
7937 gfc_conv_expr (gfc_se * se, gfc_expr * expr)
7938 {
7939   gfc_ss *ss;
7940
7941   ss = se->ss;
7942   if (ss && ss->info->expr == expr
7943       && (ss->info->type == GFC_SS_SCALAR
7944           || ss->info->type == GFC_SS_REFERENCE))
7945     {
7946       gfc_ss_info *ss_info;
7947
7948       ss_info = ss->info;
7949       /* Substitute a scalar expression evaluated outside the scalarization
7950          loop.  */
7951       se->expr = ss_info->data.scalar.value;
7952       if (gfc_scalar_elemental_arg_saved_as_reference (ss_info))
7953         se->expr = build_fold_indirect_ref_loc (input_location, se->expr);
7954
7955       se->string_length = ss_info->string_length;
7956       gfc_advance_se_ss_chain (se);
7957       return;
7958     }
7959
7960   /* We need to convert the expressions for the iso_c_binding derived types.
7961      C_NULL_PTR and C_NULL_FUNPTR will be made EXPR_NULL, which evaluates to
7962      null_pointer_node.  C_PTR and C_FUNPTR are converted to match the
7963      typespec for the C_PTR and C_FUNPTR symbols, which has already been
7964      updated to be an integer with a kind equal to the size of a (void *).  */
7965   if (expr->ts.type == BT_DERIVED && expr->ts.u.derived->ts.f90_type == BT_VOID
7966       && expr->ts.u.derived->attr.is_bind_c)
7967     {
7968       if (expr->expr_type == EXPR_VARIABLE
7969           && (expr->symtree->n.sym->intmod_sym_id == ISOCBINDING_NULL_PTR
7970               || expr->symtree->n.sym->intmod_sym_id
7971                  == ISOCBINDING_NULL_FUNPTR))
7972         {
7973           /* Set expr_type to EXPR_NULL, which will result in
7974              null_pointer_node being used below.  */
7975           expr->expr_type = EXPR_NULL;
7976         }
7977       else
7978         {
7979           /* Update the type/kind of the expression to be what the new
7980              type/kind are for the updated symbols of C_PTR/C_FUNPTR.  */
7981           expr->ts.type = BT_INTEGER;
7982           expr->ts.f90_type = BT_VOID;
7983           expr->ts.kind = gfc_index_integer_kind;
7984         }
7985     }
7986
7987   gfc_fix_class_refs (expr);
7988
7989   switch (expr->expr_type)
7990     {
7991     case EXPR_OP:
7992       gfc_conv_expr_op (se, expr);
7993       break;
7994
7995     case EXPR_FUNCTION:
7996       gfc_conv_function_expr (se, expr);
7997       break;
7998
7999     case EXPR_CONSTANT:
8000       gfc_conv_constant (se, expr);
8001       break;
8002
8003     case EXPR_VARIABLE:
8004       gfc_conv_variable (se, expr);
8005       break;
8006
8007     case EXPR_NULL:
8008       se->expr = null_pointer_node;
8009       break;
8010
8011     case EXPR_SUBSTRING:
8012       gfc_conv_substring_expr (se, expr);
8013       break;
8014
8015     case EXPR_STRUCTURE:
8016       gfc_conv_structure (se, expr, 0);
8017       break;
8018
8019     case EXPR_ARRAY:
8020       gfc_conv_array_constructor_expr (se, expr);
8021       break;
8022
8023     default:
8024       gcc_unreachable ();
8025       break;
8026     }
8027 }
8028
8029 /* Like gfc_conv_expr_val, but the value is also suitable for use in the lhs
8030    of an assignment.  */
8031 void
8032 gfc_conv_expr_lhs (gfc_se * se, gfc_expr * expr)
8033 {
8034   gfc_conv_expr (se, expr);
8035   /* All numeric lvalues should have empty post chains.  If not we need to
8036      figure out a way of rewriting an lvalue so that it has no post chain.  */
8037   gcc_assert (expr->ts.type == BT_CHARACTER || !se->post.head);
8038 }
8039
8040 /* Like gfc_conv_expr, but the POST block is guaranteed to be empty for
8041    numeric expressions.  Used for scalar values where inserting cleanup code
8042    is inconvenient.  */
8043 void
8044 gfc_conv_expr_val (gfc_se * se, gfc_expr * expr)
8045 {
8046   tree val;
8047
8048   gcc_assert (expr->ts.type != BT_CHARACTER);
8049   gfc_conv_expr (se, expr);
8050   if (se->post.head)
8051     {
8052       val = gfc_create_var (TREE_TYPE (se->expr), NULL);
8053       gfc_add_modify (&se->pre, val, se->expr);
8054       se->expr = val;
8055       gfc_add_block_to_block (&se->pre, &se->post);
8056     }
8057 }
8058
8059 /* Helper to translate an expression and convert it to a particular type.  */
8060 void
8061 gfc_conv_expr_type (gfc_se * se, gfc_expr * expr, tree type)
8062 {
8063   gfc_conv_expr_val (se, expr);
8064   se->expr = convert (type, se->expr);
8065 }
8066
8067
8068 /* Converts an expression so that it can be passed by reference.  Scalar
8069    values only.  */
8070
8071 void
8072 gfc_conv_expr_reference (gfc_se * se, gfc_expr * expr, bool add_clobber)
8073 {
8074   gfc_ss *ss;
8075   tree var;
8076
8077   ss = se->ss;
8078   if (ss && ss->info->expr == expr
8079       && ss->info->type == GFC_SS_REFERENCE)
8080     {
8081       /* Returns a reference to the scalar evaluated outside the loop
8082          for this case.  */
8083       gfc_conv_expr (se, expr);
8084
8085       if (expr->ts.type == BT_CHARACTER
8086           && expr->expr_type != EXPR_FUNCTION)
8087         gfc_conv_string_parameter (se);
8088      else
8089         se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
8090
8091       return;
8092     }
8093
8094   if (expr->ts.type == BT_CHARACTER)
8095     {
8096       gfc_conv_expr (se, expr);
8097       gfc_conv_string_parameter (se);
8098       return;
8099     }
8100
8101   if (expr->expr_type == EXPR_VARIABLE)
8102     {
8103       se->want_pointer = 1;
8104       gfc_conv_expr (se, expr);
8105       if (se->post.head)
8106         {
8107           var = gfc_create_var (TREE_TYPE (se->expr), NULL);
8108           gfc_add_modify (&se->pre, var, se->expr);
8109           gfc_add_block_to_block (&se->pre, &se->post);
8110           se->expr = var;
8111         }
8112       else if (add_clobber)
8113         {
8114           tree clobber;
8115           tree var;
8116           /* FIXME: This fails if var is passed by reference, see PR
8117              41453.  */
8118           var = expr->symtree->n.sym->backend_decl;
8119           clobber = build_clobber (TREE_TYPE (var));
8120           gfc_add_modify (&se->pre, var, clobber);
8121         }
8122       return;
8123     }
8124
8125   if (expr->expr_type == EXPR_FUNCTION
8126       && ((expr->value.function.esym
8127            && expr->value.function.esym->result->attr.pointer
8128            && !expr->value.function.esym->result->attr.dimension)
8129           || (!expr->value.function.esym && !expr->ref
8130               && expr->symtree->n.sym->attr.pointer
8131               && !expr->symtree->n.sym->attr.dimension)))
8132     {
8133       se->want_pointer = 1;
8134       gfc_conv_expr (se, expr);
8135       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
8136       gfc_add_modify (&se->pre, var, se->expr);
8137       se->expr = var;
8138       return;
8139     }
8140
8141   gfc_conv_expr (se, expr);
8142
8143   /* Create a temporary var to hold the value.  */
8144   if (TREE_CONSTANT (se->expr))
8145     {
8146       tree tmp = se->expr;
8147       STRIP_TYPE_NOPS (tmp);
8148       var = build_decl (input_location,
8149                         CONST_DECL, NULL, TREE_TYPE (tmp));
8150       DECL_INITIAL (var) = tmp;
8151       TREE_STATIC (var) = 1;
8152       pushdecl (var);
8153     }
8154   else
8155     {
8156       var = gfc_create_var (TREE_TYPE (se->expr), NULL);
8157       gfc_add_modify (&se->pre, var, se->expr);
8158     }
8159
8160   if (!expr->must_finalize)
8161     gfc_add_block_to_block (&se->pre, &se->post);
8162
8163   /* Take the address of that value.  */
8164   se->expr = gfc_build_addr_expr (NULL_TREE, var);
8165 }
8166
8167
8168 /* Get the _len component for an unlimited polymorphic expression.  */
8169
8170 static tree
8171 trans_get_upoly_len (stmtblock_t *block, gfc_expr *expr)
8172 {
8173   gfc_se se;
8174   gfc_ref *ref = expr->ref;
8175
8176   gfc_init_se (&se, NULL);
8177   while (ref && ref->next)
8178     ref = ref->next;
8179   gfc_add_len_component (expr);
8180   gfc_conv_expr (&se, expr);
8181   gfc_add_block_to_block (block, &se.pre);
8182   gcc_assert (se.post.head == NULL_TREE);
8183   if (ref)
8184     {
8185       gfc_free_ref_list (ref->next);
8186       ref->next = NULL;
8187     }
8188   else
8189     {
8190       gfc_free_ref_list (expr->ref);
8191       expr->ref = NULL;
8192     }
8193   return se.expr;
8194 }
8195
8196
8197 /* Assign _vptr and _len components as appropriate.  BLOCK should be a
8198    statement-list outside of the scalarizer-loop.  When code is generated, that
8199    depends on the scalarized expression, it is added to RSE.PRE.
8200    Returns le's _vptr tree and when set the len expressions in to_lenp and
8201    from_lenp to form a le%_vptr%_copy (re, le, [from_lenp, to_lenp])
8202    expression.  */
8203
8204 static tree
8205 trans_class_vptr_len_assignment (stmtblock_t *block, gfc_expr * le,
8206                                  gfc_expr * re, gfc_se *rse,
8207                                  tree * to_lenp, tree * from_lenp)
8208 {
8209   gfc_se se;
8210   gfc_expr * vptr_expr;
8211   tree tmp, to_len = NULL_TREE, from_len = NULL_TREE, lhs_vptr;
8212   bool set_vptr = false, temp_rhs = false;
8213   stmtblock_t *pre = block;
8214
8215   /* Create a temporary for complicated expressions.  */
8216   if (re->expr_type != EXPR_VARIABLE && re->expr_type != EXPR_NULL
8217       && rse->expr != NULL_TREE && !DECL_P (rse->expr))
8218     {
8219       tmp = gfc_create_var (TREE_TYPE (rse->expr), "rhs");
8220       pre = &rse->pre;
8221       gfc_add_modify (&rse->pre, tmp, rse->expr);
8222       rse->expr = tmp;
8223       temp_rhs = true;
8224     }
8225
8226   /* Get the _vptr for the left-hand side expression.  */
8227   gfc_init_se (&se, NULL);
8228   vptr_expr = gfc_find_and_cut_at_last_class_ref (le);
8229   if (vptr_expr != NULL && gfc_expr_attr (vptr_expr).class_ok)
8230     {
8231       /* Care about _len for unlimited polymorphic entities.  */
8232       if (UNLIMITED_POLY (vptr_expr)
8233           || (vptr_expr->ts.type == BT_DERIVED
8234               && vptr_expr->ts.u.derived->attr.unlimited_polymorphic))
8235         to_len = trans_get_upoly_len (block, vptr_expr);
8236       gfc_add_vptr_component (vptr_expr);
8237       set_vptr = true;
8238     }
8239   else
8240     vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&le->ts));
8241   se.want_pointer = 1;
8242   gfc_conv_expr (&se, vptr_expr);
8243   gfc_free_expr (vptr_expr);
8244   gfc_add_block_to_block (block, &se.pre);
8245   gcc_assert (se.post.head == NULL_TREE);
8246   lhs_vptr = se.expr;
8247   STRIP_NOPS (lhs_vptr);
8248
8249   /* Set the _vptr only when the left-hand side of the assignment is a
8250      class-object.  */
8251   if (set_vptr)
8252     {
8253       /* Get the vptr from the rhs expression only, when it is variable.
8254          Functions are expected to be assigned to a temporary beforehand.  */
8255       vptr_expr = (re->expr_type == EXPR_VARIABLE && re->ts.type == BT_CLASS)
8256           ? gfc_find_and_cut_at_last_class_ref (re)
8257           : NULL;
8258       if (vptr_expr != NULL && vptr_expr->ts.type == BT_CLASS)
8259         {
8260           if (to_len != NULL_TREE)
8261             {
8262               /* Get the _len information from the rhs.  */
8263               if (UNLIMITED_POLY (vptr_expr)
8264                   || (vptr_expr->ts.type == BT_DERIVED
8265                       && vptr_expr->ts.u.derived->attr.unlimited_polymorphic))
8266                 from_len = trans_get_upoly_len (block, vptr_expr);
8267             }
8268           gfc_add_vptr_component (vptr_expr);
8269         }
8270       else
8271         {
8272           if (re->expr_type == EXPR_VARIABLE
8273               && DECL_P (re->symtree->n.sym->backend_decl)
8274               && DECL_LANG_SPECIFIC (re->symtree->n.sym->backend_decl)
8275               && GFC_DECL_SAVED_DESCRIPTOR (re->symtree->n.sym->backend_decl)
8276               && GFC_CLASS_TYPE_P (TREE_TYPE (GFC_DECL_SAVED_DESCRIPTOR (
8277                                            re->symtree->n.sym->backend_decl))))
8278             {
8279               vptr_expr = NULL;
8280               se.expr = gfc_class_vptr_get (GFC_DECL_SAVED_DESCRIPTOR (
8281                                              re->symtree->n.sym->backend_decl));
8282               if (to_len)
8283                 from_len = gfc_class_len_get (GFC_DECL_SAVED_DESCRIPTOR (
8284                                              re->symtree->n.sym->backend_decl));
8285             }
8286           else if (temp_rhs && re->ts.type == BT_CLASS)
8287             {
8288               vptr_expr = NULL;
8289               se.expr = gfc_class_vptr_get (rse->expr);
8290               if (UNLIMITED_POLY (re))
8291                 from_len = gfc_class_len_get (rse->expr);
8292             }
8293           else if (re->expr_type != EXPR_NULL)
8294             /* Only when rhs is non-NULL use its declared type for vptr
8295                initialisation.  */
8296             vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&re->ts));
8297           else
8298             /* When the rhs is NULL use the vtab of lhs' declared type.  */
8299             vptr_expr = gfc_lval_expr_from_sym (gfc_find_vtab (&le->ts));
8300         }
8301
8302       if (vptr_expr)
8303         {
8304           gfc_init_se (&se, NULL);
8305           se.want_pointer = 1;
8306           gfc_conv_expr (&se, vptr_expr);
8307           gfc_free_expr (vptr_expr);
8308           gfc_add_block_to_block (block, &se.pre);
8309           gcc_assert (se.post.head == NULL_TREE);
8310         }
8311       gfc_add_modify (pre, lhs_vptr, fold_convert (TREE_TYPE (lhs_vptr),
8312                                                 se.expr));
8313
8314       if (to_len != NULL_TREE)
8315         {
8316           /* The _len component needs to be set.  Figure how to get the
8317              value of the right-hand side.  */
8318           if (from_len == NULL_TREE)
8319             {
8320               if (rse->string_length != NULL_TREE)
8321                 from_len = rse->string_length;
8322               else if (re->ts.type == BT_CHARACTER && re->ts.u.cl->length)
8323                 {
8324                   from_len = gfc_get_expr_charlen (re);
8325                   gfc_init_se (&se, NULL);
8326                   gfc_conv_expr (&se, re->ts.u.cl->length);
8327                   gfc_add_block_to_block (block, &se.pre);
8328                   gcc_assert (se.post.head == NULL_TREE);
8329                   from_len = gfc_evaluate_now (se.expr, block);
8330                 }
8331               else
8332                 from_len = build_zero_cst (gfc_charlen_type_node);
8333             }
8334           gfc_add_modify (pre, to_len, fold_convert (TREE_TYPE (to_len),
8335                                                      from_len));
8336         }
8337     }
8338
8339   /* Return the _len trees only, when requested.  */
8340   if (to_lenp)
8341     *to_lenp = to_len;
8342   if (from_lenp)
8343     *from_lenp = from_len;
8344   return lhs_vptr;
8345 }
8346
8347
8348 /* Assign tokens for pointer components.  */
8349
8350 static void
8351 trans_caf_token_assign (gfc_se *lse, gfc_se *rse, gfc_expr *expr1,
8352                         gfc_expr *expr2)
8353 {
8354   symbol_attribute lhs_attr, rhs_attr;
8355   tree tmp, lhs_tok, rhs_tok;
8356   /* Flag to indicated component refs on the rhs.  */
8357   bool rhs_cr;
8358
8359   lhs_attr = gfc_caf_attr (expr1);
8360   if (expr2->expr_type != EXPR_NULL)
8361     {
8362       rhs_attr = gfc_caf_attr (expr2, false, &rhs_cr);
8363       if (lhs_attr.codimension && rhs_attr.codimension)
8364         {
8365           lhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (lse, expr1);
8366           lhs_tok = build_fold_indirect_ref (lhs_tok);
8367
8368           if (rhs_cr)
8369             rhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (rse, expr2);
8370           else
8371             {
8372               tree caf_decl;
8373               caf_decl = gfc_get_tree_for_caf_expr (expr2);
8374               gfc_get_caf_token_offset (rse, &rhs_tok, NULL, caf_decl,
8375                                         NULL_TREE, NULL);
8376             }
8377           tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
8378                             lhs_tok,
8379                             fold_convert (TREE_TYPE (lhs_tok), rhs_tok));
8380           gfc_prepend_expr_to_block (&lse->post, tmp);
8381         }
8382     }
8383   else if (lhs_attr.codimension)
8384     {
8385       lhs_tok = gfc_get_ultimate_alloc_ptr_comps_caf_token (lse, expr1);
8386       lhs_tok = build_fold_indirect_ref (lhs_tok);
8387       tmp = build2_loc (input_location, MODIFY_EXPR, void_type_node,
8388                         lhs_tok, null_pointer_node);
8389       gfc_prepend_expr_to_block (&lse->post, tmp);
8390     }
8391 }
8392
8393 /* Indentify class valued proc_pointer assignments.  */
8394
8395 static bool
8396 pointer_assignment_is_proc_pointer (gfc_expr * expr1, gfc_expr * expr2)
8397 {
8398   gfc_ref * ref;
8399
8400   ref = expr1->ref;
8401   while (ref && ref->next)
8402      ref = ref->next;
8403
8404   return ref && ref->type == REF_COMPONENT
8405       && ref->u.c.component->attr.proc_pointer
8406       && expr2->expr_type == EXPR_VARIABLE
8407       && expr2->symtree->n.sym->attr.flavor == FL_PROCEDURE;
8408 }
8409
8410
8411 /* Do everything that is needed for a CLASS function expr2.  */
8412
8413 static tree
8414 trans_class_pointer_fcn (stmtblock_t *block, gfc_se *lse, gfc_se *rse,
8415                          gfc_expr *expr1, gfc_expr *expr2)
8416 {
8417   tree expr1_vptr = NULL_TREE;
8418   tree tmp;
8419
8420   gfc_conv_function_expr (rse, expr2);
8421   rse->expr = gfc_evaluate_now (rse->expr, &rse->pre);
8422
8423   if (expr1->ts.type != BT_CLASS)
8424       rse->expr = gfc_class_data_get (rse->expr);
8425   else
8426     {
8427       expr1_vptr = trans_class_vptr_len_assignment (block, expr1,
8428                                                     expr2, rse,
8429                                                     NULL, NULL);
8430       gfc_add_block_to_block (block, &rse->pre);
8431       tmp = gfc_create_var (TREE_TYPE (rse->expr), "ptrtemp");
8432       gfc_add_modify (&lse->pre, tmp, rse->expr);
8433
8434       gfc_add_modify (&lse->pre, expr1_vptr,
8435                       fold_convert (TREE_TYPE (expr1_vptr),
8436                       gfc_class_vptr_get (tmp)));
8437       rse->expr = gfc_class_data_get (tmp);
8438     }
8439
8440   return expr1_vptr;
8441 }
8442
8443
8444 tree
8445 gfc_trans_pointer_assign (gfc_code * code)
8446 {
8447   return gfc_trans_pointer_assignment (code->expr1, code->expr2);
8448 }
8449
8450
8451 /* Generate code for a pointer assignment.  */
8452
8453 tree
8454 gfc_trans_pointer_assignment (gfc_expr * expr1, gfc_expr * expr2)
8455 {
8456   gfc_se lse;
8457   gfc_se rse;
8458   stmtblock_t block;
8459   tree desc;
8460   tree tmp;
8461   tree expr1_vptr = NULL_TREE;
8462   bool scalar, non_proc_pointer_assign;
8463   gfc_ss *ss;
8464
8465   gfc_start_block (&block);
8466
8467   gfc_init_se (&lse, NULL);
8468
8469   /* Usually testing whether this is not a proc pointer assignment.  */
8470   non_proc_pointer_assign = !pointer_assignment_is_proc_pointer (expr1, expr2);
8471
8472   /* Check whether the expression is a scalar or not; we cannot use
8473      expr1->rank as it can be nonzero for proc pointers.  */
8474   ss = gfc_walk_expr (expr1);
8475   scalar = ss == gfc_ss_terminator;
8476   if (!scalar)
8477     gfc_free_ss_chain (ss);
8478
8479   if (expr1->ts.type == BT_DERIVED && expr2->ts.type == BT_CLASS
8480       && expr2->expr_type != EXPR_FUNCTION && non_proc_pointer_assign)
8481     {
8482       gfc_add_data_component (expr2);
8483       /* The following is required as gfc_add_data_component doesn't
8484          update ts.type if there is a tailing REF_ARRAY.  */
8485       expr2->ts.type = BT_DERIVED;
8486     }
8487
8488   if (scalar)
8489     {
8490       /* Scalar pointers.  */
8491       lse.want_pointer = 1;
8492       gfc_conv_expr (&lse, expr1);
8493       gfc_init_se (&rse, NULL);
8494       rse.want_pointer = 1;
8495       if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
8496         trans_class_pointer_fcn (&block, &lse, &rse, expr1, expr2);
8497       else
8498         gfc_conv_expr (&rse, expr2);
8499
8500       if (non_proc_pointer_assign && expr1->ts.type == BT_CLASS)
8501         {
8502           trans_class_vptr_len_assignment (&block, expr1, expr2, &rse, NULL,
8503                                            NULL);
8504           lse.expr = gfc_class_data_get (lse.expr);
8505         }
8506
8507       if (expr1->symtree->n.sym->attr.proc_pointer
8508           && expr1->symtree->n.sym->attr.dummy)
8509         lse.expr = build_fold_indirect_ref_loc (input_location,
8510                                                 lse.expr);
8511
8512       if (expr2->symtree && expr2->symtree->n.sym->attr.proc_pointer
8513           && expr2->symtree->n.sym->attr.dummy)
8514         rse.expr = build_fold_indirect_ref_loc (input_location,
8515                                                 rse.expr);
8516
8517       gfc_add_block_to_block (&block, &lse.pre);
8518       gfc_add_block_to_block (&block, &rse.pre);
8519
8520       /* Check character lengths if character expression.  The test is only
8521          really added if -fbounds-check is enabled.  Exclude deferred
8522          character length lefthand sides.  */
8523       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL
8524           && !expr1->ts.deferred
8525           && !expr1->symtree->n.sym->attr.proc_pointer
8526           && !gfc_is_proc_ptr_comp (expr1))
8527         {
8528           gcc_assert (expr2->ts.type == BT_CHARACTER);
8529           gcc_assert (lse.string_length && rse.string_length);
8530           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
8531                                        lse.string_length, rse.string_length,
8532                                        &block);
8533         }
8534
8535       /* The assignment to an deferred character length sets the string
8536          length to that of the rhs.  */
8537       if (expr1->ts.deferred)
8538         {
8539           if (expr2->expr_type != EXPR_NULL && lse.string_length != NULL)
8540             gfc_add_modify (&block, lse.string_length,
8541                             fold_convert (TREE_TYPE (lse.string_length),
8542                                           rse.string_length));
8543           else if (lse.string_length != NULL)
8544             gfc_add_modify (&block, lse.string_length,
8545                             build_zero_cst (TREE_TYPE (lse.string_length)));
8546         }
8547
8548       gfc_add_modify (&block, lse.expr,
8549                       fold_convert (TREE_TYPE (lse.expr), rse.expr));
8550
8551       /* Also set the tokens for pointer components in derived typed
8552          coarrays.  */
8553       if (flag_coarray == GFC_FCOARRAY_LIB)
8554         trans_caf_token_assign (&lse, &rse, expr1, expr2);
8555
8556       gfc_add_block_to_block (&block, &rse.post);
8557       gfc_add_block_to_block (&block, &lse.post);
8558     }
8559   else
8560     {
8561       gfc_ref* remap;
8562       bool rank_remap;
8563       tree strlen_lhs;
8564       tree strlen_rhs = NULL_TREE;
8565
8566       /* Array pointer.  Find the last reference on the LHS and if it is an
8567          array section ref, we're dealing with bounds remapping.  In this case,
8568          set it to AR_FULL so that gfc_conv_expr_descriptor does
8569          not see it and process the bounds remapping afterwards explicitly.  */
8570       for (remap = expr1->ref; remap; remap = remap->next)
8571         if (!remap->next && remap->type == REF_ARRAY
8572             && remap->u.ar.type == AR_SECTION)
8573           break;
8574       rank_remap = (remap && remap->u.ar.end[0]);
8575
8576       gfc_init_se (&lse, NULL);
8577       if (remap)
8578         lse.descriptor_only = 1;
8579       gfc_conv_expr_descriptor (&lse, expr1);
8580       strlen_lhs = lse.string_length;
8581       desc = lse.expr;
8582
8583       if (expr2->expr_type == EXPR_NULL)
8584         {
8585           /* Just set the data pointer to null.  */
8586           gfc_conv_descriptor_data_set (&lse.pre, lse.expr, null_pointer_node);
8587         }
8588       else if (rank_remap)
8589         {
8590           /* If we are rank-remapping, just get the RHS's descriptor and
8591              process this later on.  */
8592           gfc_init_se (&rse, NULL);
8593           rse.direct_byref = 1;
8594           rse.byref_noassign = 1;
8595
8596           if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
8597             expr1_vptr = trans_class_pointer_fcn (&block, &lse, &rse,
8598                                                   expr1, expr2);
8599           else if (expr2->expr_type == EXPR_FUNCTION)
8600             {
8601               tree bound[GFC_MAX_DIMENSIONS];
8602               int i;
8603
8604               for (i = 0; i < expr2->rank; i++)
8605                 bound[i] = NULL_TREE;
8606               tmp = gfc_typenode_for_spec (&expr2->ts);
8607               tmp = gfc_get_array_type_bounds (tmp, expr2->rank, 0,
8608                                                bound, bound, 0,
8609                                                GFC_ARRAY_POINTER_CONT, false);
8610               tmp = gfc_create_var (tmp, "ptrtemp");
8611               rse.descriptor_only = 0;
8612               rse.expr = tmp;
8613               rse.direct_byref = 1;
8614               gfc_conv_expr_descriptor (&rse, expr2);
8615               strlen_rhs = rse.string_length;
8616               rse.expr = tmp;
8617             }
8618           else
8619             {
8620               gfc_conv_expr_descriptor (&rse, expr2);
8621               strlen_rhs = rse.string_length;
8622               if (expr1->ts.type == BT_CLASS)
8623                 expr1_vptr = trans_class_vptr_len_assignment (&block, expr1,
8624                                                               expr2, &rse,
8625                                                               NULL, NULL);
8626             }
8627         }
8628       else if (expr2->expr_type == EXPR_VARIABLE)
8629         {
8630           /* Assign directly to the LHS's descriptor.  */
8631           lse.descriptor_only = 0;
8632           lse.direct_byref = 1;
8633           gfc_conv_expr_descriptor (&lse, expr2);
8634           strlen_rhs = lse.string_length;
8635
8636           if (expr1->ts.type == BT_CLASS)
8637             {
8638               rse.expr = NULL_TREE;
8639               rse.string_length = NULL_TREE;
8640               trans_class_vptr_len_assignment (&block, expr1, expr2, &rse,
8641                                                NULL, NULL);
8642             }
8643
8644           if (remap == NULL)
8645             {
8646               /* If the target is not a whole array, use the target array
8647                  reference for remap.  */
8648               for (remap = expr2->ref; remap; remap = remap->next)
8649                 if (remap->type == REF_ARRAY
8650                     && remap->u.ar.type == AR_FULL
8651                     && remap->next)
8652                   break;
8653             }
8654         }
8655       else if (expr2->expr_type == EXPR_FUNCTION && expr2->ts.type == BT_CLASS)
8656         {
8657           gfc_init_se (&rse, NULL);
8658           rse.want_pointer = 1;
8659           gfc_conv_function_expr (&rse, expr2);
8660           if (expr1->ts.type != BT_CLASS)
8661             {
8662               rse.expr = gfc_class_data_get (rse.expr);
8663               gfc_add_modify (&lse.pre, desc, rse.expr);
8664               /* Set the lhs span.  */
8665               tmp = TREE_TYPE (rse.expr);
8666               tmp = TYPE_SIZE_UNIT (gfc_get_element_type (tmp));
8667               tmp = fold_convert (gfc_array_index_type, tmp);
8668               gfc_conv_descriptor_span_set (&lse.pre, desc, tmp);
8669             }
8670           else
8671             {
8672               expr1_vptr = trans_class_vptr_len_assignment (&block, expr1,
8673                                                             expr2, &rse, NULL,
8674                                                             NULL);
8675               gfc_add_block_to_block (&block, &rse.pre);
8676               tmp = gfc_create_var (TREE_TYPE (rse.expr), "ptrtemp");
8677               gfc_add_modify (&lse.pre, tmp, rse.expr);
8678
8679               gfc_add_modify (&lse.pre, expr1_vptr,
8680                               fold_convert (TREE_TYPE (expr1_vptr),
8681                                         gfc_class_vptr_get (tmp)));
8682               rse.expr = gfc_class_data_get (tmp);
8683               gfc_add_modify (&lse.pre, desc, rse.expr);
8684             }
8685         }
8686       else
8687         {
8688           /* Assign to a temporary descriptor and then copy that
8689              temporary to the pointer.  */
8690           tmp = gfc_create_var (TREE_TYPE (desc), "ptrtemp");
8691           lse.descriptor_only = 0;
8692           lse.expr = tmp;
8693           lse.direct_byref = 1;
8694           gfc_conv_expr_descriptor (&lse, expr2);
8695           strlen_rhs = lse.string_length;
8696           gfc_add_modify (&lse.pre, desc, tmp);
8697         }
8698
8699       gfc_add_block_to_block (&block, &lse.pre);
8700       if (rank_remap)
8701         gfc_add_block_to_block (&block, &rse.pre);
8702
8703       /* If we do bounds remapping, update LHS descriptor accordingly.  */
8704       if (remap)
8705         {
8706           int dim;
8707           gcc_assert (remap->u.ar.dimen == expr1->rank);
8708
8709           if (rank_remap)
8710             {
8711               /* Do rank remapping.  We already have the RHS's descriptor
8712                  converted in rse and now have to build the correct LHS
8713                  descriptor for it.  */
8714
8715               tree dtype, data, span;
8716               tree offs, stride;
8717               tree lbound, ubound;
8718
8719               /* Set dtype.  */
8720               dtype = gfc_conv_descriptor_dtype (desc);
8721               tmp = gfc_get_dtype (TREE_TYPE (desc));
8722               gfc_add_modify (&block, dtype, tmp);
8723
8724               /* Copy data pointer.  */
8725               data = gfc_conv_descriptor_data_get (rse.expr);
8726               gfc_conv_descriptor_data_set (&block, desc, data);
8727
8728               /* Copy the span.  */
8729               if (TREE_CODE (rse.expr) == VAR_DECL
8730                   && GFC_DECL_PTR_ARRAY_P (rse.expr))
8731                 span = gfc_conv_descriptor_span_get (rse.expr);
8732               else
8733                 {
8734                   tmp = TREE_TYPE (rse.expr);
8735                   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (tmp));
8736                   span = fold_convert (gfc_array_index_type, tmp);
8737                 }
8738               gfc_conv_descriptor_span_set (&block, desc, span);
8739
8740               /* Copy offset but adjust it such that it would correspond
8741                  to a lbound of zero.  */
8742               offs = gfc_conv_descriptor_offset_get (rse.expr);
8743               for (dim = 0; dim < expr2->rank; ++dim)
8744                 {
8745                   stride = gfc_conv_descriptor_stride_get (rse.expr,
8746                                                            gfc_rank_cst[dim]);
8747                   lbound = gfc_conv_descriptor_lbound_get (rse.expr,
8748                                                            gfc_rank_cst[dim]);
8749                   tmp = fold_build2_loc (input_location, MULT_EXPR,
8750                                          gfc_array_index_type, stride, lbound);
8751                   offs = fold_build2_loc (input_location, PLUS_EXPR,
8752                                           gfc_array_index_type, offs, tmp);
8753                 }
8754               gfc_conv_descriptor_offset_set (&block, desc, offs);
8755
8756               /* Set the bounds as declared for the LHS and calculate strides as
8757                  well as another offset update accordingly.  */
8758               stride = gfc_conv_descriptor_stride_get (rse.expr,
8759                                                        gfc_rank_cst[0]);
8760               for (dim = 0; dim < expr1->rank; ++dim)
8761                 {
8762                   gfc_se lower_se;
8763                   gfc_se upper_se;
8764
8765                   gcc_assert (remap->u.ar.start[dim] && remap->u.ar.end[dim]);
8766
8767                   /* Convert declared bounds.  */
8768                   gfc_init_se (&lower_se, NULL);
8769                   gfc_init_se (&upper_se, NULL);
8770                   gfc_conv_expr (&lower_se, remap->u.ar.start[dim]);
8771                   gfc_conv_expr (&upper_se, remap->u.ar.end[dim]);
8772
8773                   gfc_add_block_to_block (&block, &lower_se.pre);
8774                   gfc_add_block_to_block (&block, &upper_se.pre);
8775
8776                   lbound = fold_convert (gfc_array_index_type, lower_se.expr);
8777                   ubound = fold_convert (gfc_array_index_type, upper_se.expr);
8778
8779                   lbound = gfc_evaluate_now (lbound, &block);
8780                   ubound = gfc_evaluate_now (ubound, &block);
8781
8782                   gfc_add_block_to_block (&block, &lower_se.post);
8783                   gfc_add_block_to_block (&block, &upper_se.post);
8784
8785                   /* Set bounds in descriptor.  */
8786                   gfc_conv_descriptor_lbound_set (&block, desc,
8787                                                   gfc_rank_cst[dim], lbound);
8788                   gfc_conv_descriptor_ubound_set (&block, desc,
8789                                                   gfc_rank_cst[dim], ubound);
8790
8791                   /* Set stride.  */
8792                   stride = gfc_evaluate_now (stride, &block);
8793                   gfc_conv_descriptor_stride_set (&block, desc,
8794                                                   gfc_rank_cst[dim], stride);
8795
8796                   /* Update offset.  */
8797                   offs = gfc_conv_descriptor_offset_get (desc);
8798                   tmp = fold_build2_loc (input_location, MULT_EXPR,
8799                                          gfc_array_index_type, lbound, stride);
8800                   offs = fold_build2_loc (input_location, MINUS_EXPR,
8801                                           gfc_array_index_type, offs, tmp);
8802                   offs = gfc_evaluate_now (offs, &block);
8803                   gfc_conv_descriptor_offset_set (&block, desc, offs);
8804
8805                   /* Update stride.  */
8806                   tmp = gfc_conv_array_extent_dim (lbound, ubound, NULL);
8807                   stride = fold_build2_loc (input_location, MULT_EXPR,
8808                                             gfc_array_index_type, stride, tmp);
8809                 }
8810             }
8811           else
8812             {
8813               /* Bounds remapping.  Just shift the lower bounds.  */
8814
8815               gcc_assert (expr1->rank == expr2->rank);
8816
8817               for (dim = 0; dim < remap->u.ar.dimen; ++dim)
8818                 {
8819                   gfc_se lbound_se;
8820
8821                   gcc_assert (!remap->u.ar.end[dim]);
8822                   gfc_init_se (&lbound_se, NULL);
8823                   if (remap->u.ar.start[dim])
8824                     {
8825                       gfc_conv_expr (&lbound_se, remap->u.ar.start[dim]);
8826                       gfc_add_block_to_block (&block, &lbound_se.pre);
8827                     }
8828                   else
8829                     /* This remap arises from a target that is not a whole
8830                        array. The start expressions will be NULL but we need
8831                        the lbounds to be one.  */
8832                     lbound_se.expr = gfc_index_one_node;
8833                   gfc_conv_shift_descriptor_lbound (&block, desc,
8834                                                     dim, lbound_se.expr);
8835                   gfc_add_block_to_block (&block, &lbound_se.post);
8836                 }
8837             }
8838         }
8839
8840       /* Check string lengths if applicable.  The check is only really added
8841          to the output code if -fbounds-check is enabled.  */
8842       if (expr1->ts.type == BT_CHARACTER && expr2->expr_type != EXPR_NULL)
8843         {
8844           gcc_assert (expr2->ts.type == BT_CHARACTER);
8845           gcc_assert (strlen_lhs && strlen_rhs);
8846           gfc_trans_same_strlen_check ("pointer assignment", &expr1->where,
8847                                        strlen_lhs, strlen_rhs, &block);
8848         }
8849
8850       /* If rank remapping was done, check with -fcheck=bounds that
8851          the target is at least as large as the pointer.  */
8852       if (rank_remap && (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS))
8853         {
8854           tree lsize, rsize;
8855           tree fault;
8856           const char* msg;
8857
8858           lsize = gfc_conv_descriptor_size (lse.expr, expr1->rank);
8859           rsize = gfc_conv_descriptor_size (rse.expr, expr2->rank);
8860
8861           lsize = gfc_evaluate_now (lsize, &block);
8862           rsize = gfc_evaluate_now (rsize, &block);
8863           fault = fold_build2_loc (input_location, LT_EXPR, logical_type_node,
8864                                    rsize, lsize);
8865
8866           msg = _("Target of rank remapping is too small (%ld < %ld)");
8867           gfc_trans_runtime_check (true, false, fault, &block, &expr2->where,
8868                                    msg, rsize, lsize);
8869         }
8870
8871       gfc_add_block_to_block (&block, &lse.post);
8872       if (rank_remap)
8873         gfc_add_block_to_block (&block, &rse.post);
8874     }
8875
8876   return gfc_finish_block (&block);
8877 }
8878
8879
8880 /* Makes sure se is suitable for passing as a function string parameter.  */
8881 /* TODO: Need to check all callers of this function.  It may be abused.  */
8882
8883 void
8884 gfc_conv_string_parameter (gfc_se * se)
8885 {
8886   tree type;
8887
8888   if (TREE_CODE (se->expr) == STRING_CST)
8889     {
8890       type = TREE_TYPE (TREE_TYPE (se->expr));
8891       se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
8892       return;
8893     }
8894
8895   if (TYPE_STRING_FLAG (TREE_TYPE (se->expr)))
8896     {
8897       if (TREE_CODE (se->expr) != INDIRECT_REF)
8898         {
8899           type = TREE_TYPE (se->expr);
8900           se->expr = gfc_build_addr_expr (build_pointer_type (type), se->expr);
8901         }
8902       else
8903         {
8904           type = gfc_get_character_type_len (gfc_default_character_kind,
8905                                              se->string_length);
8906           type = build_pointer_type (type);
8907           se->expr = gfc_build_addr_expr (type, se->expr);
8908         }
8909     }
8910
8911   gcc_assert (POINTER_TYPE_P (TREE_TYPE (se->expr)));
8912 }
8913
8914
8915 /* Generate code for assignment of scalar variables.  Includes character
8916    strings and derived types with allocatable components.
8917    If you know that the LHS has no allocations, set dealloc to false.
8918
8919    DEEP_COPY has no effect if the typespec TS is not a derived type with
8920    allocatable components.  Otherwise, if it is set, an explicit copy of each
8921    allocatable component is made.  This is necessary as a simple copy of the
8922    whole object would copy array descriptors as is, so that the lhs's
8923    allocatable components would point to the rhs's after the assignment.
8924    Typically, setting DEEP_COPY is necessary if the rhs is a variable, and not
8925    necessary if the rhs is a non-pointer function, as the allocatable components
8926    are not accessible by other means than the function's result after the
8927    function has returned.  It is even more subtle when temporaries are involved,
8928    as the two following examples show:
8929     1.  When we evaluate an array constructor, a temporary is created.  Thus
8930       there is theoretically no alias possible.  However, no deep copy is
8931       made for this temporary, so that if the constructor is made of one or
8932       more variable with allocatable components, those components still point
8933       to the variable's: DEEP_COPY should be set for the assignment from the
8934       temporary to the lhs in that case.
8935     2.  When assigning a scalar to an array, we evaluate the scalar value out
8936       of the loop, store it into a temporary variable, and assign from that.
8937       In that case, deep copying when assigning to the temporary would be a
8938       waste of resources; however deep copies should happen when assigning from
8939       the temporary to each array element: again DEEP_COPY should be set for
8940       the assignment from the temporary to the lhs.  */
8941
8942 tree
8943 gfc_trans_scalar_assign (gfc_se * lse, gfc_se * rse, gfc_typespec ts,
8944                          bool deep_copy, bool dealloc, bool in_coarray)
8945 {
8946   stmtblock_t block;
8947   tree tmp;
8948   tree cond;
8949
8950   gfc_init_block (&block);
8951
8952   if (ts.type == BT_CHARACTER)
8953     {
8954       tree rlen = NULL;
8955       tree llen = NULL;
8956
8957       if (lse->string_length != NULL_TREE)
8958         {
8959           gfc_conv_string_parameter (lse);
8960           gfc_add_block_to_block (&block, &lse->pre);
8961           llen = lse->string_length;
8962         }
8963
8964       if (rse->string_length != NULL_TREE)
8965         {
8966           gfc_conv_string_parameter (rse);
8967           gfc_add_block_to_block (&block, &rse->pre);
8968           rlen = rse->string_length;
8969         }
8970
8971       gfc_trans_string_copy (&block, llen, lse->expr, ts.kind, rlen,
8972                              rse->expr, ts.kind);
8973     }
8974   else if (gfc_bt_struct (ts.type)
8975            && (ts.u.derived->attr.alloc_comp
8976                 || (deep_copy && ts.u.derived->attr.pdt_type)))
8977     {
8978       tree tmp_var = NULL_TREE;
8979       cond = NULL_TREE;
8980
8981       /* Are the rhs and the lhs the same?  */
8982       if (deep_copy)
8983         {
8984           cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
8985                                   gfc_build_addr_expr (NULL_TREE, lse->expr),
8986                                   gfc_build_addr_expr (NULL_TREE, rse->expr));
8987           cond = gfc_evaluate_now (cond, &lse->pre);
8988         }
8989
8990       /* Deallocate the lhs allocated components as long as it is not
8991          the same as the rhs.  This must be done following the assignment
8992          to prevent deallocating data that could be used in the rhs
8993          expression.  */
8994       if (dealloc)
8995         {
8996           tmp_var = gfc_evaluate_now (lse->expr, &lse->pre);
8997           tmp = gfc_deallocate_alloc_comp_no_caf (ts.u.derived, tmp_var, 0);
8998           if (deep_copy)
8999             tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9000                             tmp);
9001           gfc_add_expr_to_block (&lse->post, tmp);
9002         }
9003
9004       gfc_add_block_to_block (&block, &rse->pre);
9005       gfc_add_block_to_block (&block, &lse->pre);
9006
9007       gfc_add_modify (&block, lse->expr,
9008                            fold_convert (TREE_TYPE (lse->expr), rse->expr));
9009
9010       /* Restore pointer address of coarray components.  */
9011       if (ts.u.derived->attr.coarray_comp && deep_copy && tmp_var != NULL_TREE)
9012         {
9013           tmp = gfc_reassign_alloc_comp_caf (ts.u.derived, tmp_var, lse->expr);
9014           tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9015                           tmp);
9016           gfc_add_expr_to_block (&block, tmp);
9017         }
9018
9019       /* Do a deep copy if the rhs is a variable, if it is not the
9020          same as the lhs.  */
9021       if (deep_copy)
9022         {
9023           int caf_mode = in_coarray ? (GFC_STRUCTURE_CAF_MODE_ENABLE_COARRAY
9024                                        | GFC_STRUCTURE_CAF_MODE_IN_COARRAY) : 0;
9025           tmp = gfc_copy_alloc_comp (ts.u.derived, rse->expr, lse->expr, 0,
9026                                      caf_mode);
9027           tmp = build3_v (COND_EXPR, cond, build_empty_stmt (input_location),
9028                           tmp);
9029           gfc_add_expr_to_block (&block, tmp);
9030         }
9031     }
9032   else if (gfc_bt_struct (ts.type) || ts.type == BT_CLASS)
9033     {
9034       gfc_add_block_to_block (&block, &lse->pre);
9035       gfc_add_block_to_block (&block, &rse->pre);
9036       tmp = fold_build1_loc (input_location, VIEW_CONVERT_EXPR,
9037                              TREE_TYPE (lse->expr), rse->expr);
9038       gfc_add_modify (&block, lse->expr, tmp);
9039     }
9040   else
9041     {
9042       gfc_add_block_to_block (&block, &lse->pre);
9043       gfc_add_block_to_block (&block, &rse->pre);
9044
9045       gfc_add_modify (&block, lse->expr,
9046                       fold_convert (TREE_TYPE (lse->expr), rse->expr));
9047     }
9048
9049   gfc_add_block_to_block (&block, &lse->post);
9050   gfc_add_block_to_block (&block, &rse->post);
9051
9052   return gfc_finish_block (&block);
9053 }
9054
9055
9056 /* There are quite a lot of restrictions on the optimisation in using an
9057    array function assign without a temporary.  */
9058
9059 static bool
9060 arrayfunc_assign_needs_temporary (gfc_expr * expr1, gfc_expr * expr2)
9061 {
9062   gfc_ref * ref;
9063   bool seen_array_ref;
9064   bool c = false;
9065   gfc_symbol *sym = expr1->symtree->n.sym;
9066
9067   /* Play it safe with class functions assigned to a derived type.  */
9068   if (gfc_is_class_array_function (expr2)
9069       && expr1->ts.type == BT_DERIVED)
9070     return true;
9071
9072   /* The caller has already checked rank>0 and expr_type == EXPR_FUNCTION.  */
9073   if (expr2->value.function.isym && !gfc_is_intrinsic_libcall (expr2))
9074     return true;
9075
9076   /* Elemental functions are scalarized so that they don't need a
9077      temporary in gfc_trans_assignment_1, so return a true.  Otherwise,
9078      they would need special treatment in gfc_trans_arrayfunc_assign.  */
9079   if (expr2->value.function.esym != NULL
9080       && expr2->value.function.esym->attr.elemental)
9081     return true;
9082
9083   /* Need a temporary if rhs is not FULL or a contiguous section.  */
9084   if (expr1->ref && !(gfc_full_array_ref_p (expr1->ref, &c) || c))
9085     return true;
9086
9087   /* Need a temporary if EXPR1 can't be expressed as a descriptor.  */
9088   if (gfc_ref_needs_temporary_p (expr1->ref))
9089     return true;
9090
9091   /* Functions returning pointers or allocatables need temporaries.  */
9092   c = expr2->value.function.esym
9093       ? (expr2->value.function.esym->attr.pointer
9094          || expr2->value.function.esym->attr.allocatable)
9095       : (expr2->symtree->n.sym->attr.pointer
9096          || expr2->symtree->n.sym->attr.allocatable);
9097   if (c)
9098     return true;
9099
9100   /* Character array functions need temporaries unless the
9101      character lengths are the same.  */
9102   if (expr2->ts.type == BT_CHARACTER && expr2->rank > 0)
9103     {
9104       if (expr1->ts.u.cl->length == NULL
9105             || expr1->ts.u.cl->length->expr_type != EXPR_CONSTANT)
9106         return true;
9107
9108       if (expr2->ts.u.cl->length == NULL
9109             || expr2->ts.u.cl->length->expr_type != EXPR_CONSTANT)
9110         return true;
9111
9112       if (mpz_cmp (expr1->ts.u.cl->length->value.integer,
9113                      expr2->ts.u.cl->length->value.integer) != 0)
9114         return true;
9115     }
9116
9117   /* Check that no LHS component references appear during an array
9118      reference. This is needed because we do not have the means to
9119      span any arbitrary stride with an array descriptor. This check
9120      is not needed for the rhs because the function result has to be
9121      a complete type.  */
9122   seen_array_ref = false;
9123   for (ref = expr1->ref; ref; ref = ref->next)
9124     {
9125       if (ref->type == REF_ARRAY)
9126         seen_array_ref= true;
9127       else if (ref->type == REF_COMPONENT && seen_array_ref)
9128         return true;
9129     }
9130
9131   /* Check for a dependency.  */
9132   if (gfc_check_fncall_dependency (expr1, INTENT_OUT,
9133                                    expr2->value.function.esym,
9134                                    expr2->value.function.actual,
9135                                    NOT_ELEMENTAL))
9136     return true;
9137
9138   /* If we have reached here with an intrinsic function, we do not
9139      need a temporary except in the particular case that reallocation
9140      on assignment is active and the lhs is allocatable and a target.  */
9141   if (expr2->value.function.isym)
9142     return (flag_realloc_lhs && sym->attr.allocatable && sym->attr.target);
9143
9144   /* If the LHS is a dummy, we need a temporary if it is not
9145      INTENT(OUT).  */
9146   if (sym->attr.dummy && sym->attr.intent != INTENT_OUT)
9147     return true;
9148
9149   /* If the lhs has been host_associated, is in common, a pointer or is
9150      a target and the function is not using a RESULT variable, aliasing
9151      can occur and a temporary is needed.  */
9152   if ((sym->attr.host_assoc
9153            || sym->attr.in_common
9154            || sym->attr.pointer
9155            || sym->attr.cray_pointee
9156            || sym->attr.target)
9157         && expr2->symtree != NULL
9158         && expr2->symtree->n.sym == expr2->symtree->n.sym->result)
9159     return true;
9160
9161   /* A PURE function can unconditionally be called without a temporary.  */
9162   if (expr2->value.function.esym != NULL
9163       && expr2->value.function.esym->attr.pure)
9164     return false;
9165
9166   /* Implicit_pure functions are those which could legally be declared
9167      to be PURE.  */
9168   if (expr2->value.function.esym != NULL
9169       && expr2->value.function.esym->attr.implicit_pure)
9170     return false;
9171
9172   if (!sym->attr.use_assoc
9173         && !sym->attr.in_common
9174         && !sym->attr.pointer
9175         && !sym->attr.target
9176         && !sym->attr.cray_pointee
9177         && expr2->value.function.esym)
9178     {
9179       /* A temporary is not needed if the function is not contained and
9180          the variable is local or host associated and not a pointer or
9181          a target.  */
9182       if (!expr2->value.function.esym->attr.contained)
9183         return false;
9184
9185       /* A temporary is not needed if the lhs has never been host
9186          associated and the procedure is contained.  */
9187       else if (!sym->attr.host_assoc)
9188         return false;
9189
9190       /* A temporary is not needed if the variable is local and not
9191          a pointer, a target or a result.  */
9192       if (sym->ns->parent
9193             && expr2->value.function.esym->ns == sym->ns->parent)
9194         return false;
9195     }
9196
9197   /* Default to temporary use.  */
9198   return true;
9199 }
9200
9201
9202 /* Provide the loop info so that the lhs descriptor can be built for
9203    reallocatable assignments from extrinsic function calls.  */
9204
9205 static void
9206 realloc_lhs_loop_for_fcn_call (gfc_se *se, locus *where, gfc_ss **ss,
9207                                gfc_loopinfo *loop)
9208 {
9209   /* Signal that the function call should not be made by
9210      gfc_conv_loop_setup.  */
9211   se->ss->is_alloc_lhs = 1;
9212   gfc_init_loopinfo (loop);
9213   gfc_add_ss_to_loop (loop, *ss);
9214   gfc_add_ss_to_loop (loop, se->ss);
9215   gfc_conv_ss_startstride (loop);
9216   gfc_conv_loop_setup (loop, where);
9217   gfc_copy_loopinfo_to_se (se, loop);
9218   gfc_add_block_to_block (&se->pre, &loop->pre);
9219   gfc_add_block_to_block (&se->pre, &loop->post);
9220   se->ss->is_alloc_lhs = 0;
9221 }
9222
9223
9224 /* For assignment to a reallocatable lhs from intrinsic functions,
9225    replace the se.expr (ie. the result) with a temporary descriptor.
9226    Null the data field so that the library allocates space for the
9227    result. Free the data of the original descriptor after the function,
9228    in case it appears in an argument expression and transfer the
9229    result to the original descriptor.  */
9230
9231 static void
9232 fcncall_realloc_result (gfc_se *se, int rank)
9233 {
9234   tree desc;
9235   tree res_desc;
9236   tree tmp;
9237   tree offset;
9238   tree zero_cond;
9239   int n;
9240
9241   /* Use the allocation done by the library.  Substitute the lhs
9242      descriptor with a copy, whose data field is nulled.*/
9243   desc = build_fold_indirect_ref_loc (input_location, se->expr);
9244   if (POINTER_TYPE_P (TREE_TYPE (desc)))
9245     desc = build_fold_indirect_ref_loc (input_location, desc);
9246
9247   /* Unallocated, the descriptor does not have a dtype.  */
9248   tmp = gfc_conv_descriptor_dtype (desc);
9249   gfc_add_modify (&se->pre, tmp, gfc_get_dtype (TREE_TYPE (desc)));
9250
9251   res_desc = gfc_evaluate_now (desc, &se->pre);
9252   gfc_conv_descriptor_data_set (&se->pre, res_desc, null_pointer_node);
9253   se->expr = gfc_build_addr_expr (NULL_TREE, res_desc);
9254
9255   /* Free the lhs after the function call and copy the result data to
9256      the lhs descriptor.  */
9257   tmp = gfc_conv_descriptor_data_get (desc);
9258   zero_cond = fold_build2_loc (input_location, EQ_EXPR,
9259                                logical_type_node, tmp,
9260                                build_int_cst (TREE_TYPE (tmp), 0));
9261   zero_cond = gfc_evaluate_now (zero_cond, &se->post);
9262   tmp = gfc_call_free (tmp);
9263   gfc_add_expr_to_block (&se->post, tmp);
9264
9265   tmp = gfc_conv_descriptor_data_get (res_desc);
9266   gfc_conv_descriptor_data_set (&se->post, desc, tmp);
9267
9268   /* Check that the shapes are the same between lhs and expression.  */
9269   for (n = 0 ; n < rank; n++)
9270     {
9271       tree tmp1;
9272       tmp = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]);
9273       tmp1 = gfc_conv_descriptor_lbound_get (res_desc, gfc_rank_cst[n]);
9274       tmp = fold_build2_loc (input_location, MINUS_EXPR,
9275                              gfc_array_index_type, tmp, tmp1);
9276       tmp1 = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[n]);
9277       tmp = fold_build2_loc (input_location, MINUS_EXPR,
9278                              gfc_array_index_type, tmp, tmp1);
9279       tmp1 = gfc_conv_descriptor_ubound_get (res_desc, gfc_rank_cst[n]);
9280       tmp = fold_build2_loc (input_location, PLUS_EXPR,
9281                              gfc_array_index_type, tmp, tmp1);
9282       tmp = fold_build2_loc (input_location, NE_EXPR,
9283                              logical_type_node, tmp,
9284                              gfc_index_zero_node);
9285       tmp = gfc_evaluate_now (tmp, &se->post);
9286       zero_cond = fold_build2_loc (input_location, TRUTH_OR_EXPR,
9287                                    logical_type_node, tmp,
9288                                    zero_cond);
9289     }
9290
9291   /* 'zero_cond' being true is equal to lhs not being allocated or the
9292      shapes being different.  */
9293   zero_cond = gfc_evaluate_now (zero_cond, &se->post);
9294
9295   /* Now reset the bounds returned from the function call to bounds based
9296      on the lhs lbounds, except where the lhs is not allocated or the shapes
9297      of 'variable and 'expr' are different. Set the offset accordingly.  */
9298   offset = gfc_index_zero_node;
9299   for (n = 0 ; n < rank; n++)
9300     {
9301       tree lbound;
9302
9303       lbound = gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]);
9304       lbound = fold_build3_loc (input_location, COND_EXPR,
9305                                 gfc_array_index_type, zero_cond,
9306                                 gfc_index_one_node, lbound);
9307       lbound = gfc_evaluate_now (lbound, &se->post);
9308
9309       tmp = gfc_conv_descriptor_ubound_get (res_desc, gfc_rank_cst[n]);
9310       tmp = fold_build2_loc (input_location, PLUS_EXPR,
9311                              gfc_array_index_type, tmp, lbound);
9312       gfc_conv_descriptor_lbound_set (&se->post, desc,
9313                                       gfc_rank_cst[n], lbound);
9314       gfc_conv_descriptor_ubound_set (&se->post, desc,
9315                                       gfc_rank_cst[n], tmp);
9316
9317       /* Set stride and accumulate the offset.  */
9318       tmp = gfc_conv_descriptor_stride_get (res_desc, gfc_rank_cst[n]);
9319       gfc_conv_descriptor_stride_set (&se->post, desc,
9320                                       gfc_rank_cst[n], tmp);
9321       tmp = fold_build2_loc (input_location, MULT_EXPR,
9322                              gfc_array_index_type, lbound, tmp);
9323       offset = fold_build2_loc (input_location, MINUS_EXPR,
9324                                 gfc_array_index_type, offset, tmp);
9325       offset = gfc_evaluate_now (offset, &se->post);
9326     }
9327
9328   gfc_conv_descriptor_offset_set (&se->post, desc, offset);
9329 }
9330
9331
9332
9333 /* Try to translate array(:) = func (...), where func is a transformational
9334    array function, without using a temporary.  Returns NULL if this isn't the
9335    case.  */
9336
9337 static tree
9338 gfc_trans_arrayfunc_assign (gfc_expr * expr1, gfc_expr * expr2)
9339 {
9340   gfc_se se;
9341   gfc_ss *ss = NULL;
9342   gfc_component *comp = NULL;
9343   gfc_loopinfo loop;
9344
9345   if (arrayfunc_assign_needs_temporary (expr1, expr2))
9346     return NULL;
9347
9348   /* The frontend doesn't seem to bother filling in expr->symtree for intrinsic
9349      functions.  */
9350   comp = gfc_get_proc_ptr_comp (expr2);
9351
9352   if (!(expr2->value.function.isym
9353               || (comp && comp->attr.dimension)
9354               || (!comp && gfc_return_by_reference (expr2->value.function.esym)
9355                   && expr2->value.function.esym->result->attr.dimension)))
9356     return NULL;
9357
9358   gfc_init_se (&se, NULL);
9359   gfc_start_block (&se.pre);
9360   se.want_pointer = 1;
9361
9362   gfc_conv_array_parameter (&se, expr1, false, NULL, NULL, NULL);
9363
9364   if (expr1->ts.type == BT_DERIVED
9365         && expr1->ts.u.derived->attr.alloc_comp)
9366     {
9367       tree tmp;
9368       tmp = gfc_deallocate_alloc_comp_no_caf (expr1->ts.u.derived, se.expr,
9369                                               expr1->rank);
9370       gfc_add_expr_to_block (&se.pre, tmp);
9371     }
9372
9373   se.direct_byref = 1;
9374   se.ss = gfc_walk_expr (expr2);
9375   gcc_assert (se.ss != gfc_ss_terminator);
9376
9377   /* Reallocate on assignment needs the loopinfo for extrinsic functions.
9378      This is signalled to gfc_conv_procedure_call by setting is_alloc_lhs.
9379      Clearly, this cannot be done for an allocatable function result, since
9380      the shape of the result is unknown and, in any case, the function must
9381      correctly take care of the reallocation internally. For intrinsic
9382      calls, the array data is freed and the library takes care of allocation.
9383      TODO: Add logic of trans-array.c: gfc_alloc_allocatable_for_assignment
9384      to the library.  */
9385   if (flag_realloc_lhs
9386         && gfc_is_reallocatable_lhs (expr1)
9387         && !gfc_expr_attr (expr1).codimension
9388         && !gfc_is_coindexed (expr1)
9389         && !(expr2->value.function.esym
9390             && expr2->value.function.esym->result->attr.allocatable))
9391     {
9392       realloc_lhs_warning (expr1->ts.type, true, &expr1->where);
9393
9394       if (!expr2->value.function.isym)
9395         {
9396           ss = gfc_walk_expr (expr1);
9397           gcc_assert (ss != gfc_ss_terminator);
9398
9399           realloc_lhs_loop_for_fcn_call (&se, &expr1->where, &ss, &loop);
9400           ss->is_alloc_lhs = 1;
9401         }
9402       else
9403         fcncall_realloc_result (&se, expr1->rank);
9404     }
9405
9406   gfc_conv_function_expr (&se, expr2);
9407   gfc_add_block_to_block (&se.pre, &se.post);
9408
9409   if (ss)
9410     gfc_cleanup_loop (&loop);
9411   else
9412     gfc_free_ss_chain (se.ss);
9413
9414   return gfc_finish_block (&se.pre);
9415 }
9416
9417
9418 /* Try to efficiently translate array(:) = 0.  Return NULL if this
9419    can't be done.  */
9420
9421 static tree
9422 gfc_trans_zero_assign (gfc_expr * expr)
9423 {
9424   tree dest, len, type;
9425   tree tmp;
9426   gfc_symbol *sym;
9427
9428   sym = expr->symtree->n.sym;
9429   dest = gfc_get_symbol_decl (sym);
9430
9431   type = TREE_TYPE (dest);
9432   if (POINTER_TYPE_P (type))
9433     type = TREE_TYPE (type);
9434   if (!GFC_ARRAY_TYPE_P (type))
9435     return NULL_TREE;
9436
9437   /* Determine the length of the array.  */
9438   len = GFC_TYPE_ARRAY_SIZE (type);
9439   if (!len || TREE_CODE (len) != INTEGER_CST)
9440     return NULL_TREE;
9441
9442   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
9443   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
9444                          fold_convert (gfc_array_index_type, tmp));
9445
9446   /* If we are zeroing a local array avoid taking its address by emitting
9447      a = {} instead.  */
9448   if (!POINTER_TYPE_P (TREE_TYPE (dest)))
9449     return build2_loc (input_location, MODIFY_EXPR, void_type_node,
9450                        dest, build_constructor (TREE_TYPE (dest),
9451                                               NULL));
9452
9453   /* Convert arguments to the correct types.  */
9454   dest = fold_convert (pvoid_type_node, dest);
9455   len = fold_convert (size_type_node, len);
9456
9457   /* Construct call to __builtin_memset.  */
9458   tmp = build_call_expr_loc (input_location,
9459                              builtin_decl_explicit (BUILT_IN_MEMSET),
9460                              3, dest, integer_zero_node, len);
9461   return fold_convert (void_type_node, tmp);
9462 }
9463
9464
9465 /* Helper for gfc_trans_array_copy and gfc_trans_array_constructor_copy
9466    that constructs the call to __builtin_memcpy.  */
9467
9468 tree
9469 gfc_build_memcpy_call (tree dst, tree src, tree len)
9470 {
9471   tree tmp;
9472
9473   /* Convert arguments to the correct types.  */
9474   if (!POINTER_TYPE_P (TREE_TYPE (dst)))
9475     dst = gfc_build_addr_expr (pvoid_type_node, dst);
9476   else
9477     dst = fold_convert (pvoid_type_node, dst);
9478
9479   if (!POINTER_TYPE_P (TREE_TYPE (src)))
9480     src = gfc_build_addr_expr (pvoid_type_node, src);
9481   else
9482     src = fold_convert (pvoid_type_node, src);
9483
9484   len = fold_convert (size_type_node, len);
9485
9486   /* Construct call to __builtin_memcpy.  */
9487   tmp = build_call_expr_loc (input_location,
9488                              builtin_decl_explicit (BUILT_IN_MEMCPY),
9489                              3, dst, src, len);
9490   return fold_convert (void_type_node, tmp);
9491 }
9492
9493
9494 /* Try to efficiently translate dst(:) = src(:).  Return NULL if this
9495    can't be done.  EXPR1 is the destination/lhs and EXPR2 is the
9496    source/rhs, both are gfc_full_array_ref_p which have been checked for
9497    dependencies.  */
9498
9499 static tree
9500 gfc_trans_array_copy (gfc_expr * expr1, gfc_expr * expr2)
9501 {
9502   tree dst, dlen, dtype;
9503   tree src, slen, stype;
9504   tree tmp;
9505
9506   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
9507   src = gfc_get_symbol_decl (expr2->symtree->n.sym);
9508
9509   dtype = TREE_TYPE (dst);
9510   if (POINTER_TYPE_P (dtype))
9511     dtype = TREE_TYPE (dtype);
9512   stype = TREE_TYPE (src);
9513   if (POINTER_TYPE_P (stype))
9514     stype = TREE_TYPE (stype);
9515
9516   if (!GFC_ARRAY_TYPE_P (dtype) || !GFC_ARRAY_TYPE_P (stype))
9517     return NULL_TREE;
9518
9519   /* Determine the lengths of the arrays.  */
9520   dlen = GFC_TYPE_ARRAY_SIZE (dtype);
9521   if (!dlen || TREE_CODE (dlen) != INTEGER_CST)
9522     return NULL_TREE;
9523   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
9524   dlen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
9525                           dlen, fold_convert (gfc_array_index_type, tmp));
9526
9527   slen = GFC_TYPE_ARRAY_SIZE (stype);
9528   if (!slen || TREE_CODE (slen) != INTEGER_CST)
9529     return NULL_TREE;
9530   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (stype));
9531   slen = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type,
9532                           slen, fold_convert (gfc_array_index_type, tmp));
9533
9534   /* Sanity check that they are the same.  This should always be
9535      the case, as we should already have checked for conformance.  */
9536   if (!tree_int_cst_equal (slen, dlen))
9537     return NULL_TREE;
9538
9539   return gfc_build_memcpy_call (dst, src, dlen);
9540 }
9541
9542
9543 /* Try to efficiently translate array(:) = (/ ... /).  Return NULL if
9544    this can't be done.  EXPR1 is the destination/lhs for which
9545    gfc_full_array_ref_p is true, and EXPR2 is the source/rhs.  */
9546
9547 static tree
9548 gfc_trans_array_constructor_copy (gfc_expr * expr1, gfc_expr * expr2)
9549 {
9550   unsigned HOST_WIDE_INT nelem;
9551   tree dst, dtype;
9552   tree src, stype;
9553   tree len;
9554   tree tmp;
9555
9556   nelem = gfc_constant_array_constructor_p (expr2->value.constructor);
9557   if (nelem == 0)
9558     return NULL_TREE;
9559
9560   dst = gfc_get_symbol_decl (expr1->symtree->n.sym);
9561   dtype = TREE_TYPE (dst);
9562   if (POINTER_TYPE_P (dtype))
9563     dtype = TREE_TYPE (dtype);
9564   if (!GFC_ARRAY_TYPE_P (dtype))
9565     return NULL_TREE;
9566
9567   /* Determine the lengths of the array.  */
9568   len = GFC_TYPE_ARRAY_SIZE (dtype);
9569   if (!len || TREE_CODE (len) != INTEGER_CST)
9570     return NULL_TREE;
9571
9572   /* Confirm that the constructor is the same size.  */
9573   if (compare_tree_int (len, nelem) != 0)
9574     return NULL_TREE;
9575
9576   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (dtype));
9577   len = fold_build2_loc (input_location, MULT_EXPR, gfc_array_index_type, len,
9578                          fold_convert (gfc_array_index_type, tmp));
9579
9580   stype = gfc_typenode_for_spec (&expr2->ts);
9581   src = gfc_build_constant_array_constructor (expr2, stype);
9582
9583   stype = TREE_TYPE (src);
9584   if (POINTER_TYPE_P (stype))
9585     stype = TREE_TYPE (stype);
9586
9587   return gfc_build_memcpy_call (dst, src, len);
9588 }
9589
9590
9591 /* Tells whether the expression is to be treated as a variable reference.  */
9592
9593 bool
9594 gfc_expr_is_variable (gfc_expr *expr)
9595 {
9596   gfc_expr *arg;
9597   gfc_component *comp;
9598   gfc_symbol *func_ifc;
9599
9600   if (expr->expr_type == EXPR_VARIABLE)
9601     return true;
9602
9603   arg = gfc_get_noncopying_intrinsic_argument (expr);
9604   if (arg)
9605     {
9606       gcc_assert (expr->value.function.isym->id == GFC_ISYM_TRANSPOSE);
9607       return gfc_expr_is_variable (arg);
9608     }
9609
9610   /* A data-pointer-returning function should be considered as a variable
9611      too.  */
9612   if (expr->expr_type == EXPR_FUNCTION
9613       && expr->ref == NULL)
9614     {
9615       if (expr->value.function.isym != NULL)
9616         return false;
9617
9618       if (expr->value.function.esym != NULL)
9619         {
9620           func_ifc = expr->value.function.esym;
9621           goto found_ifc;
9622         }
9623       else
9624         {
9625           gcc_assert (expr->symtree);
9626           func_ifc = expr->symtree->n.sym;
9627           goto found_ifc;
9628         }
9629
9630       gcc_unreachable ();
9631     }
9632
9633   comp = gfc_get_proc_ptr_comp (expr);
9634   if ((expr->expr_type == EXPR_PPC || expr->expr_type == EXPR_FUNCTION)
9635       && comp)
9636     {
9637       func_ifc = comp->ts.interface;
9638       goto found_ifc;
9639     }
9640
9641   if (expr->expr_type == EXPR_COMPCALL)
9642     {
9643       gcc_assert (!expr->value.compcall.tbp->is_generic);
9644       func_ifc = expr->value.compcall.tbp->u.specific->n.sym;
9645       goto found_ifc;
9646     }
9647
9648   return false;
9649
9650 found_ifc:
9651   gcc_assert (func_ifc->attr.function
9652               && func_ifc->result != NULL);
9653   return func_ifc->result->attr.pointer;
9654 }
9655
9656
9657 /* Is the lhs OK for automatic reallocation?  */
9658
9659 static bool
9660 is_scalar_reallocatable_lhs (gfc_expr *expr)
9661 {
9662   gfc_ref * ref;
9663
9664   /* An allocatable variable with no reference.  */
9665   if (expr->symtree->n.sym->attr.allocatable
9666         && !expr->ref)
9667     return true;
9668
9669   /* All that can be left are allocatable components.  However, we do
9670      not check for allocatable components here because the expression
9671      could be an allocatable component of a pointer component.  */
9672   if (expr->symtree->n.sym->ts.type != BT_DERIVED
9673         && expr->symtree->n.sym->ts.type != BT_CLASS)
9674     return false;
9675
9676   /* Find an allocatable component ref last.  */
9677   for (ref = expr->ref; ref; ref = ref->next)
9678     if (ref->type == REF_COMPONENT
9679           && !ref->next
9680           && ref->u.c.component->attr.allocatable)
9681       return true;
9682
9683   return false;
9684 }
9685
9686
9687 /* Allocate or reallocate scalar lhs, as necessary.  */
9688
9689 static void
9690 alloc_scalar_allocatable_for_assignment (stmtblock_t *block,
9691                                          tree string_length,
9692                                          gfc_expr *expr1,
9693                                          gfc_expr *expr2)
9694
9695 {
9696   tree cond;
9697   tree tmp;
9698   tree size;
9699   tree size_in_bytes;
9700   tree jump_label1;
9701   tree jump_label2;
9702   gfc_se lse;
9703   gfc_ref *ref;
9704
9705   if (!expr1 || expr1->rank)
9706     return;
9707
9708   if (!expr2 || expr2->rank)
9709     return;
9710
9711   for (ref = expr1->ref; ref; ref = ref->next)
9712     if (ref->type == REF_SUBSTRING)
9713       return;
9714
9715   realloc_lhs_warning (expr2->ts.type, false, &expr2->where);
9716
9717   /* Since this is a scalar lhs, we can afford to do this.  That is,
9718      there is no risk of side effects being repeated.  */
9719   gfc_init_se (&lse, NULL);
9720   lse.want_pointer = 1;
9721   gfc_conv_expr (&lse, expr1);
9722
9723   jump_label1 = gfc_build_label_decl (NULL_TREE);
9724   jump_label2 = gfc_build_label_decl (NULL_TREE);
9725
9726   /* Do the allocation if the lhs is NULL. Otherwise go to label 1.  */
9727   tmp = build_int_cst (TREE_TYPE (lse.expr), 0);
9728   cond = fold_build2_loc (input_location, NE_EXPR, logical_type_node,
9729                           lse.expr, tmp);
9730   tmp = build3_v (COND_EXPR, cond,
9731                   build1_v (GOTO_EXPR, jump_label1),
9732                   build_empty_stmt (input_location));
9733   gfc_add_expr_to_block (block, tmp);
9734
9735   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
9736     {
9737       /* Use the rhs string length and the lhs element size.  */
9738       size = string_length;
9739       tmp = TREE_TYPE (gfc_typenode_for_spec (&expr1->ts));
9740       tmp = TYPE_SIZE_UNIT (tmp);
9741       size_in_bytes = fold_build2_loc (input_location, MULT_EXPR,
9742                                        TREE_TYPE (tmp), tmp,
9743                                        fold_convert (TREE_TYPE (tmp), size));
9744     }
9745   else
9746     {
9747       /* Otherwise use the length in bytes of the rhs.  */
9748       size = TYPE_SIZE_UNIT (gfc_typenode_for_spec (&expr1->ts));
9749       size_in_bytes = size;
9750     }
9751
9752   size_in_bytes = fold_build2_loc (input_location, MAX_EXPR, size_type_node,
9753                                    size_in_bytes, size_one_node);
9754
9755   if (gfc_caf_attr (expr1).codimension && flag_coarray == GFC_FCOARRAY_LIB)
9756     {
9757       tree caf_decl, token;
9758       gfc_se caf_se;
9759       symbol_attribute attr;
9760
9761       gfc_clear_attr (&attr);
9762       gfc_init_se (&caf_se, NULL);
9763
9764       caf_decl = gfc_get_tree_for_caf_expr (expr1);
9765       gfc_get_caf_token_offset (&caf_se, &token, NULL, caf_decl, NULL_TREE,
9766                                 NULL);
9767       gfc_add_block_to_block (block, &caf_se.pre);
9768       gfc_allocate_allocatable (block, lse.expr, size_in_bytes,
9769                                 gfc_build_addr_expr (NULL_TREE, token),
9770                                 NULL_TREE, NULL_TREE, NULL_TREE, jump_label1,
9771                                 expr1, 1);
9772     }
9773   else if (expr1->ts.type == BT_DERIVED && expr1->ts.u.derived->attr.alloc_comp)
9774     {
9775       tmp = build_call_expr_loc (input_location,
9776                                  builtin_decl_explicit (BUILT_IN_CALLOC),
9777                                  2, build_one_cst (size_type_node),
9778                                  size_in_bytes);
9779       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
9780       gfc_add_modify (block, lse.expr, tmp);
9781     }
9782   else
9783     {
9784       tmp = build_call_expr_loc (input_location,
9785                                  builtin_decl_explicit (BUILT_IN_MALLOC),
9786                                  1, size_in_bytes);
9787       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
9788       gfc_add_modify (block, lse.expr, tmp);
9789     }
9790
9791   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
9792     {
9793       /* Deferred characters need checking for lhs and rhs string
9794          length.  Other deferred parameter variables will have to
9795          come here too.  */
9796       tmp = build1_v (GOTO_EXPR, jump_label2);
9797       gfc_add_expr_to_block (block, tmp);
9798     }
9799   tmp = build1_v (LABEL_EXPR, jump_label1);
9800   gfc_add_expr_to_block (block, tmp);
9801
9802   /* For a deferred length character, reallocate if lengths of lhs and
9803      rhs are different.  */
9804   if (expr1->ts.type == BT_CHARACTER && expr1->ts.deferred)
9805     {
9806       cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
9807                               lse.string_length,
9808                               fold_convert (TREE_TYPE (lse.string_length),
9809                                             size));
9810       /* Jump past the realloc if the lengths are the same.  */
9811       tmp = build3_v (COND_EXPR, cond,
9812                       build1_v (GOTO_EXPR, jump_label2),
9813                       build_empty_stmt (input_location));
9814       gfc_add_expr_to_block (block, tmp);
9815       tmp = build_call_expr_loc (input_location,
9816                                  builtin_decl_explicit (BUILT_IN_REALLOC),
9817                                  2, fold_convert (pvoid_type_node, lse.expr),
9818                                  size_in_bytes);
9819       tmp = fold_convert (TREE_TYPE (lse.expr), tmp);
9820       gfc_add_modify (block, lse.expr, tmp);
9821       tmp = build1_v (LABEL_EXPR, jump_label2);
9822       gfc_add_expr_to_block (block, tmp);
9823
9824       /* Update the lhs character length.  */
9825       size = string_length;
9826       gfc_add_modify (block, lse.string_length,
9827                       fold_convert (TREE_TYPE (lse.string_length), size));
9828     }
9829 }
9830
9831 /* Check for assignments of the type
9832
9833    a = a + 4
9834
9835    to make sure we do not check for reallocation unneccessarily.  */
9836
9837
9838 static bool
9839 is_runtime_conformable (gfc_expr *expr1, gfc_expr *expr2)
9840 {
9841   gfc_actual_arglist *a;
9842   gfc_expr *e1, *e2;
9843
9844   switch (expr2->expr_type)
9845     {
9846     case EXPR_VARIABLE:
9847       return gfc_dep_compare_expr (expr1, expr2) == 0;
9848
9849     case EXPR_FUNCTION:
9850       if (expr2->value.function.esym
9851           && expr2->value.function.esym->attr.elemental)
9852         {
9853           for (a = expr2->value.function.actual; a != NULL; a = a->next)
9854             {
9855               e1 = a->expr;
9856               if (e1 && e1->rank > 0 && !is_runtime_conformable (expr1, e1))
9857                 return false;
9858             }
9859           return true;
9860         }
9861       else if (expr2->value.function.isym
9862                && expr2->value.function.isym->elemental)
9863         {
9864           for (a = expr2->value.function.actual; a != NULL; a = a->next)
9865             {
9866               e1 = a->expr;
9867               if (e1 && e1->rank > 0 && !is_runtime_conformable (expr1, e1))
9868                 return false;
9869             }
9870           return true;
9871         }
9872
9873       break;
9874
9875     case EXPR_OP:
9876       switch (expr2->value.op.op)
9877         {
9878         case INTRINSIC_NOT:
9879         case INTRINSIC_UPLUS:
9880         case INTRINSIC_UMINUS:
9881         case INTRINSIC_PARENTHESES:
9882           return is_runtime_conformable (expr1, expr2->value.op.op1);
9883
9884         case INTRINSIC_PLUS:
9885         case INTRINSIC_MINUS:
9886         case INTRINSIC_TIMES:
9887         case INTRINSIC_DIVIDE:
9888         case INTRINSIC_POWER:
9889         case INTRINSIC_AND:
9890         case INTRINSIC_OR:
9891         case INTRINSIC_EQV:
9892         case INTRINSIC_NEQV:
9893         case INTRINSIC_EQ:
9894         case INTRINSIC_NE:
9895         case INTRINSIC_GT:
9896         case INTRINSIC_GE:
9897         case INTRINSIC_LT:
9898         case INTRINSIC_LE:
9899         case INTRINSIC_EQ_OS:
9900         case INTRINSIC_NE_OS:
9901         case INTRINSIC_GT_OS:
9902         case INTRINSIC_GE_OS:
9903         case INTRINSIC_LT_OS:
9904         case INTRINSIC_LE_OS:
9905
9906           e1 = expr2->value.op.op1;
9907           e2 = expr2->value.op.op2;
9908
9909           if (e1->rank == 0 && e2->rank > 0)
9910             return is_runtime_conformable (expr1, e2);
9911           else if (e1->rank > 0 && e2->rank == 0)
9912             return is_runtime_conformable (expr1, e1);
9913           else if (e1->rank > 0 && e2->rank > 0)
9914             return is_runtime_conformable (expr1, e1)
9915               && is_runtime_conformable (expr1, e2);
9916           break;
9917
9918         default:
9919           break;
9920
9921         }
9922
9923       break;
9924
9925     default:
9926       break;
9927     }
9928   return false;
9929 }
9930
9931
9932 static tree
9933 trans_class_assignment (stmtblock_t *block, gfc_expr *lhs, gfc_expr *rhs,
9934                         gfc_se *lse, gfc_se *rse, bool use_vptr_copy,
9935                         bool class_realloc)
9936 {
9937   tree tmp, fcn, stdcopy, to_len, from_len, vptr;
9938   vec<tree, va_gc> *args = NULL;
9939
9940   vptr = trans_class_vptr_len_assignment (block, lhs, rhs, rse, &to_len,
9941                                          &from_len);
9942
9943   /* Generate allocation of the lhs.  */
9944   if (class_realloc)
9945     {
9946       stmtblock_t alloc;
9947       tree class_han;
9948
9949       tmp = gfc_vptr_size_get (vptr);
9950       class_han = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
9951           ? gfc_class_data_get (lse->expr) : lse->expr;
9952       gfc_init_block (&alloc);
9953       gfc_allocate_using_malloc (&alloc, class_han, tmp, NULL_TREE);
9954       tmp = fold_build2_loc (input_location, EQ_EXPR,
9955                              logical_type_node, class_han,
9956                              build_int_cst (prvoid_type_node, 0));
9957       tmp = fold_build3_loc (input_location, COND_EXPR, void_type_node,
9958                              gfc_unlikely (tmp,
9959                                            PRED_FORTRAN_FAIL_ALLOC),
9960                              gfc_finish_block (&alloc),
9961                              build_empty_stmt (input_location));
9962       gfc_add_expr_to_block (&lse->pre, tmp);
9963     }
9964
9965   fcn = gfc_vptr_copy_get (vptr);
9966
9967   tmp = GFC_CLASS_TYPE_P (TREE_TYPE (rse->expr))
9968       ? gfc_class_data_get (rse->expr) : rse->expr;
9969   if (use_vptr_copy)
9970     {
9971       if (!POINTER_TYPE_P (TREE_TYPE (tmp))
9972           || INDIRECT_REF_P (tmp)
9973           || (rhs->ts.type == BT_DERIVED
9974               && rhs->ts.u.derived->attr.unlimited_polymorphic
9975               && !rhs->ts.u.derived->attr.pointer
9976               && !rhs->ts.u.derived->attr.allocatable)
9977           || (UNLIMITED_POLY (rhs)
9978               && !CLASS_DATA (rhs)->attr.pointer
9979               && !CLASS_DATA (rhs)->attr.allocatable))
9980         vec_safe_push (args, gfc_build_addr_expr (NULL_TREE, tmp));
9981       else
9982         vec_safe_push (args, tmp);
9983       tmp = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
9984           ? gfc_class_data_get (lse->expr) : lse->expr;
9985       if (!POINTER_TYPE_P (TREE_TYPE (tmp))
9986           || INDIRECT_REF_P (tmp)
9987           || (lhs->ts.type == BT_DERIVED
9988               && lhs->ts.u.derived->attr.unlimited_polymorphic
9989               && !lhs->ts.u.derived->attr.pointer
9990               && !lhs->ts.u.derived->attr.allocatable)
9991           || (UNLIMITED_POLY (lhs)
9992               && !CLASS_DATA (lhs)->attr.pointer
9993               && !CLASS_DATA (lhs)->attr.allocatable))
9994         vec_safe_push (args, gfc_build_addr_expr (NULL_TREE, tmp));
9995       else
9996         vec_safe_push (args, tmp);
9997
9998       stdcopy = build_call_vec (TREE_TYPE (TREE_TYPE (fcn)), fcn, args);
9999
10000       if (to_len != NULL_TREE && !integer_zerop (from_len))
10001         {
10002           tree extcopy;
10003           vec_safe_push (args, from_len);
10004           vec_safe_push (args, to_len);
10005           extcopy = build_call_vec (TREE_TYPE (TREE_TYPE (fcn)), fcn, args);
10006
10007           tmp = fold_build2_loc (input_location, GT_EXPR,
10008                                  logical_type_node, from_len,
10009                                  build_zero_cst (TREE_TYPE (from_len)));
10010           return fold_build3_loc (input_location, COND_EXPR,
10011                                   void_type_node, tmp,
10012                                   extcopy, stdcopy);
10013         }
10014       else
10015         return stdcopy;
10016     }
10017   else
10018     {
10019       tree rhst = GFC_CLASS_TYPE_P (TREE_TYPE (lse->expr))
10020           ? gfc_class_data_get (lse->expr) : lse->expr;
10021       stmtblock_t tblock;
10022       gfc_init_block (&tblock);
10023       if (!POINTER_TYPE_P (TREE_TYPE (tmp)))
10024         tmp = gfc_build_addr_expr (NULL_TREE, tmp);
10025       if (!POINTER_TYPE_P (TREE_TYPE (rhst)))
10026         rhst = gfc_build_addr_expr (NULL_TREE, rhst);
10027       /* When coming from a ptr_copy lhs and rhs are swapped.  */
10028       gfc_add_modify_loc (input_location, &tblock, rhst,
10029                           fold_convert (TREE_TYPE (rhst), tmp));
10030       return gfc_finish_block (&tblock);
10031     }
10032 }
10033
10034 /* Subroutine of gfc_trans_assignment that actually scalarizes the
10035    assignment.  EXPR1 is the destination/LHS and EXPR2 is the source/RHS.
10036    init_flag indicates initialization expressions and dealloc that no
10037    deallocate prior assignment is needed (if in doubt, set true).
10038    When PTR_COPY is set and expr1 is a class type, then use the _vptr-copy
10039    routine instead of a pointer assignment.  Alias resolution is only done,
10040    when MAY_ALIAS is set (the default).  This flag is used by ALLOCATE()
10041    where it is known, that newly allocated memory on the lhs can never be
10042    an alias of the rhs.  */
10043
10044 static tree
10045 gfc_trans_assignment_1 (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
10046                         bool dealloc, bool use_vptr_copy, bool may_alias)
10047 {
10048   gfc_se lse;
10049   gfc_se rse;
10050   gfc_ss *lss;
10051   gfc_ss *lss_section;
10052   gfc_ss *rss;
10053   gfc_loopinfo loop;
10054   tree tmp;
10055   stmtblock_t block;
10056   stmtblock_t body;
10057   bool l_is_temp;
10058   bool scalar_to_array;
10059   tree string_length;
10060   int n;
10061   bool maybe_workshare = false, lhs_refs_comp = false, rhs_refs_comp = false;
10062   symbol_attribute lhs_caf_attr, rhs_caf_attr, lhs_attr;
10063   bool is_poly_assign;
10064
10065   /* Assignment of the form lhs = rhs.  */
10066   gfc_start_block (&block);
10067
10068   gfc_init_se (&lse, NULL);
10069   gfc_init_se (&rse, NULL);
10070
10071   /* Walk the lhs.  */
10072   lss = gfc_walk_expr (expr1);
10073   if (gfc_is_reallocatable_lhs (expr1))
10074     {
10075       lss->no_bounds_check = 1;
10076       if (!(expr2->expr_type == EXPR_FUNCTION
10077             && expr2->value.function.isym != NULL
10078             && !(expr2->value.function.isym->elemental
10079                  || expr2->value.function.isym->conversion)))
10080         lss->is_alloc_lhs = 1;
10081     }
10082   else
10083     lss->no_bounds_check = expr1->no_bounds_check;
10084
10085   rss = NULL;
10086
10087   if ((expr1->ts.type == BT_DERIVED)
10088       && (gfc_is_class_array_function (expr2)
10089           || gfc_is_alloc_class_scalar_function (expr2)))
10090     expr2->must_finalize = 1;
10091
10092   /* Checking whether a class assignment is desired is quite complicated and
10093      needed at two locations, so do it once only before the information is
10094      needed.  */
10095   lhs_attr = gfc_expr_attr (expr1);
10096   is_poly_assign = (use_vptr_copy || lhs_attr.pointer
10097                     || (lhs_attr.allocatable && !lhs_attr.dimension))
10098                    && (expr1->ts.type == BT_CLASS
10099                        || gfc_is_class_array_ref (expr1, NULL)
10100                        || gfc_is_class_scalar_expr (expr1)
10101                        || gfc_is_class_array_ref (expr2, NULL)
10102                        || gfc_is_class_scalar_expr (expr2));
10103
10104
10105   /* Only analyze the expressions for coarray properties, when in coarray-lib
10106      mode.  */
10107   if (flag_coarray == GFC_FCOARRAY_LIB)
10108     {
10109       lhs_caf_attr = gfc_caf_attr (expr1, false, &lhs_refs_comp);
10110       rhs_caf_attr = gfc_caf_attr (expr2, false, &rhs_refs_comp);
10111     }
10112
10113   if (lss != gfc_ss_terminator)
10114     {
10115       /* The assignment needs scalarization.  */
10116       lss_section = lss;
10117
10118       /* Find a non-scalar SS from the lhs.  */
10119       while (lss_section != gfc_ss_terminator
10120              && lss_section->info->type != GFC_SS_SECTION)
10121         lss_section = lss_section->next;
10122
10123       gcc_assert (lss_section != gfc_ss_terminator);
10124
10125       /* Initialize the scalarizer.  */
10126       gfc_init_loopinfo (&loop);
10127
10128       /* Walk the rhs.  */
10129       rss = gfc_walk_expr (expr2);
10130       if (rss == gfc_ss_terminator)
10131         /* The rhs is scalar.  Add a ss for the expression.  */
10132         rss = gfc_get_scalar_ss (gfc_ss_terminator, expr2);
10133       /* When doing a class assign, then the handle to the rhs needs to be a
10134          pointer to allow for polymorphism.  */
10135       if (is_poly_assign && expr2->rank == 0 && !UNLIMITED_POLY (expr2))
10136         rss->info->type = GFC_SS_REFERENCE;
10137
10138       rss->no_bounds_check = expr2->no_bounds_check;
10139       /* Associate the SS with the loop.  */
10140       gfc_add_ss_to_loop (&loop, lss);
10141       gfc_add_ss_to_loop (&loop, rss);
10142
10143       /* Calculate the bounds of the scalarization.  */
10144       gfc_conv_ss_startstride (&loop);
10145       /* Enable loop reversal.  */
10146       for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
10147         loop.reverse[n] = GFC_ENABLE_REVERSE;
10148       /* Resolve any data dependencies in the statement.  */
10149       if (may_alias)
10150         gfc_conv_resolve_dependencies (&loop, lss, rss);
10151       /* Setup the scalarizing loops.  */
10152       gfc_conv_loop_setup (&loop, &expr2->where);
10153
10154       /* Setup the gfc_se structures.  */
10155       gfc_copy_loopinfo_to_se (&lse, &loop);
10156       gfc_copy_loopinfo_to_se (&rse, &loop);
10157
10158       rse.ss = rss;
10159       gfc_mark_ss_chain_used (rss, 1);
10160       if (loop.temp_ss == NULL)
10161         {
10162           lse.ss = lss;
10163           gfc_mark_ss_chain_used (lss, 1);
10164         }
10165       else
10166         {
10167           lse.ss = loop.temp_ss;
10168           gfc_mark_ss_chain_used (lss, 3);
10169           gfc_mark_ss_chain_used (loop.temp_ss, 3);
10170         }
10171
10172       /* Allow the scalarizer to workshare array assignments.  */
10173       if ((ompws_flags & (OMPWS_WORKSHARE_FLAG | OMPWS_SCALARIZER_BODY))
10174           == OMPWS_WORKSHARE_FLAG
10175           && loop.temp_ss == NULL)
10176         {
10177           maybe_workshare = true;
10178           ompws_flags |= OMPWS_SCALARIZER_WS | OMPWS_SCALARIZER_BODY;
10179         }
10180
10181       /* Start the scalarized loop body.  */
10182       gfc_start_scalarized_body (&loop, &body);
10183     }
10184   else
10185     gfc_init_block (&body);
10186
10187   l_is_temp = (lss != gfc_ss_terminator && loop.temp_ss != NULL);
10188
10189   /* Translate the expression.  */
10190   rse.want_coarray = flag_coarray == GFC_FCOARRAY_LIB && init_flag
10191       && lhs_caf_attr.codimension;
10192   gfc_conv_expr (&rse, expr2);
10193
10194   /* Deal with the case of a scalar class function assigned to a derived type.  */
10195   if (gfc_is_alloc_class_scalar_function (expr2)
10196       && expr1->ts.type == BT_DERIVED)
10197     {
10198       rse.expr = gfc_class_data_get (rse.expr);
10199       rse.expr = build_fold_indirect_ref_loc (input_location, rse.expr);
10200     }
10201
10202   /* Stabilize a string length for temporaries.  */
10203   if (expr2->ts.type == BT_CHARACTER && !expr1->ts.deferred
10204       && !(VAR_P (rse.string_length)
10205            || TREE_CODE (rse.string_length) == PARM_DECL
10206            || TREE_CODE (rse.string_length) == INDIRECT_REF))
10207     string_length = gfc_evaluate_now (rse.string_length, &rse.pre);
10208   else if (expr2->ts.type == BT_CHARACTER)
10209     string_length = rse.string_length;
10210   else
10211     string_length = NULL_TREE;
10212
10213   if (l_is_temp)
10214     {
10215       gfc_conv_tmp_array_ref (&lse);
10216       if (expr2->ts.type == BT_CHARACTER)
10217         lse.string_length = string_length;
10218     }
10219   else
10220     {
10221       gfc_conv_expr (&lse, expr1);
10222       if (gfc_option.rtcheck & GFC_RTCHECK_MEM
10223           && !init_flag
10224           && gfc_expr_attr (expr1).allocatable
10225           && expr1->rank
10226           && !expr2->rank)
10227         {
10228           tree cond;
10229           const char* msg;
10230
10231           tmp = INDIRECT_REF_P (lse.expr)
10232               ? gfc_build_addr_expr (NULL_TREE, lse.expr) : lse.expr;
10233
10234           /* We should only get array references here.  */
10235           gcc_assert (TREE_CODE (tmp) == POINTER_PLUS_EXPR
10236                       || TREE_CODE (tmp) == ARRAY_REF);
10237
10238           /* 'tmp' is either the pointer to the array(POINTER_PLUS_EXPR)
10239              or the array itself(ARRAY_REF).  */
10240           tmp = TREE_OPERAND (tmp, 0);
10241
10242           /* Provide the address of the array.  */
10243           if (TREE_CODE (lse.expr) == ARRAY_REF)
10244             tmp = gfc_build_addr_expr (NULL_TREE, tmp);
10245
10246           cond = fold_build2_loc (input_location, EQ_EXPR, logical_type_node,
10247                                   tmp, build_int_cst (TREE_TYPE (tmp), 0));
10248           msg = _("Assignment of scalar to unallocated array");
10249           gfc_trans_runtime_check (true, false, cond, &loop.pre,
10250                                    &expr1->where, msg);
10251         }
10252
10253       /* Deallocate the lhs parameterized components if required.  */
10254       if (dealloc && expr2->expr_type == EXPR_FUNCTION
10255           && !expr1->symtree->n.sym->attr.associate_var)
10256         {
10257           if (expr1->ts.type == BT_DERIVED
10258               && expr1->ts.u.derived
10259               && expr1->ts.u.derived->attr.pdt_type)
10260             {
10261               tmp = gfc_deallocate_pdt_comp (expr1->ts.u.derived, lse.expr,
10262                                              expr1->rank);
10263               gfc_add_expr_to_block (&lse.pre, tmp);
10264             }
10265           else if (expr1->ts.type == BT_CLASS
10266                    && CLASS_DATA (expr1)->ts.u.derived
10267                    && CLASS_DATA (expr1)->ts.u.derived->attr.pdt_type)
10268             {
10269               tmp = gfc_class_data_get (lse.expr);
10270               tmp = gfc_deallocate_pdt_comp (CLASS_DATA (expr1)->ts.u.derived,
10271                                              tmp, expr1->rank);
10272               gfc_add_expr_to_block (&lse.pre, tmp);
10273             }
10274         }
10275     }
10276
10277   /* Assignments of scalar derived types with allocatable components
10278      to arrays must be done with a deep copy and the rhs temporary
10279      must have its components deallocated afterwards.  */
10280   scalar_to_array = (expr2->ts.type == BT_DERIVED
10281                        && expr2->ts.u.derived->attr.alloc_comp
10282                        && !gfc_expr_is_variable (expr2)
10283                        && expr1->rank && !expr2->rank);
10284   scalar_to_array |= (expr1->ts.type == BT_DERIVED
10285                                     && expr1->rank
10286                                     && expr1->ts.u.derived->attr.alloc_comp
10287                                     && gfc_is_alloc_class_scalar_function (expr2));
10288   if (scalar_to_array && dealloc)
10289     {
10290       tmp = gfc_deallocate_alloc_comp_no_caf (expr2->ts.u.derived, rse.expr, 0);
10291       gfc_prepend_expr_to_block (&loop.post, tmp);
10292     }
10293
10294   /* When assigning a character function result to a deferred-length variable,
10295      the function call must happen before the (re)allocation of the lhs -
10296      otherwise the character length of the result is not known.
10297      NOTE 1: This relies on having the exact dependence of the length type
10298      parameter available to the caller; gfortran saves it in the .mod files.
10299      NOTE 2: Vector array references generate an index temporary that must
10300      not go outside the loop. Otherwise, variables should not generate
10301      a pre block.
10302      NOTE 3: The concatenation operation generates a temporary pointer,
10303      whose allocation must go to the innermost loop.
10304      NOTE 4: Elemental functions may generate a temporary, too.  */
10305   if (flag_realloc_lhs
10306       && expr2->ts.type == BT_CHARACTER && expr1->ts.deferred
10307       && !(lss != gfc_ss_terminator
10308            && rss != gfc_ss_terminator
10309            && ((expr2->expr_type == EXPR_VARIABLE && expr2->rank)
10310                || (expr2->expr_type == EXPR_FUNCTION
10311                    && expr2->value.function.esym != NULL
10312                    && expr2->value.function.esym->attr.elemental)
10313                || (expr2->expr_type == EXPR_FUNCTION
10314                    && expr2->value.function.isym != NULL
10315                    && expr2->value.function.isym->elemental)
10316                || (expr2->expr_type == EXPR_OP
10317                    && expr2->value.op.op == INTRINSIC_CONCAT))))
10318     gfc_add_block_to_block (&block, &rse.pre);
10319
10320   /* Nullify the allocatable components corresponding to those of the lhs
10321      derived type, so that the finalization of the function result does not
10322      affect the lhs of the assignment. Prepend is used to ensure that the
10323      nullification occurs before the call to the finalizer. In the case of
10324      a scalar to array assignment, this is done in gfc_trans_scalar_assign
10325      as part of the deep copy.  */
10326   if (!scalar_to_array && expr1->ts.type == BT_DERIVED
10327                        && (gfc_is_class_array_function (expr2)
10328                            || gfc_is_alloc_class_scalar_function (expr2)))
10329     {
10330       tmp = rse.expr;
10331       tmp = gfc_nullify_alloc_comp (expr1->ts.u.derived, rse.expr, 0);
10332       gfc_prepend_expr_to_block (&rse.post, tmp);
10333       if (lss != gfc_ss_terminator && rss == gfc_ss_terminator)
10334         gfc_add_block_to_block (&loop.post, &rse.post);
10335     }
10336
10337   tmp = NULL_TREE;
10338
10339   if (is_poly_assign)
10340     tmp = trans_class_assignment (&body, expr1, expr2, &lse, &rse,
10341                                   use_vptr_copy || (lhs_attr.allocatable
10342                                                     && !lhs_attr.dimension),
10343                                   flag_realloc_lhs && !lhs_attr.pointer);
10344   else if (flag_coarray == GFC_FCOARRAY_LIB
10345            && lhs_caf_attr.codimension && rhs_caf_attr.codimension
10346            && ((lhs_caf_attr.allocatable && lhs_refs_comp)
10347                || (rhs_caf_attr.allocatable && rhs_refs_comp)))
10348     {
10349       /* Only detour to caf_send[get][_by_ref] () when the lhs or rhs is an
10350          allocatable component, because those need to be accessed via the
10351          caf-runtime.  No need to check for coindexes here, because resolve
10352          has rewritten those already.  */
10353       gfc_code code;
10354       gfc_actual_arglist a1, a2;
10355       /* Clear the structures to prevent accessing garbage.  */
10356       memset (&code, '\0', sizeof (gfc_code));
10357       memset (&a1, '\0', sizeof (gfc_actual_arglist));
10358       memset (&a2, '\0', sizeof (gfc_actual_arglist));
10359       a1.expr = expr1;
10360       a1.next = &a2;
10361       a2.expr = expr2;
10362       a2.next = NULL;
10363       code.ext.actual = &a1;
10364       code.resolved_isym = gfc_intrinsic_subroutine_by_id (GFC_ISYM_CAF_SEND);
10365       tmp = gfc_conv_intrinsic_subroutine (&code);
10366     }
10367   else if (!is_poly_assign && expr2->must_finalize
10368            && expr1->ts.type == BT_CLASS
10369            && expr2->ts.type == BT_CLASS)
10370     {
10371       /* This case comes about when the scalarizer provides array element
10372          references. Use the vptr copy function, since this does a deep
10373          copy of allocatable components, without which the finalizer call */
10374       tmp = gfc_get_vptr_from_expr (rse.expr);
10375       if (tmp != NULL_TREE)
10376         {
10377           tree fcn = gfc_vptr_copy_get (tmp);
10378           if (POINTER_TYPE_P (TREE_TYPE (fcn)))
10379             fcn = build_fold_indirect_ref_loc (input_location, fcn);
10380           tmp = build_call_expr_loc (input_location,
10381                                      fcn, 2,
10382                                      gfc_build_addr_expr (NULL, rse.expr),
10383                                      gfc_build_addr_expr (NULL, lse.expr));
10384         }
10385     }
10386
10387   /* If nothing else works, do it the old fashioned way!  */
10388   if (tmp == NULL_TREE)
10389     tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
10390                                    gfc_expr_is_variable (expr2)
10391                                    || scalar_to_array
10392                                    || expr2->expr_type == EXPR_ARRAY,
10393                                    !(l_is_temp || init_flag) && dealloc,
10394                                    expr1->symtree->n.sym->attr.codimension);
10395
10396   /* Add the pre blocks to the body.  */
10397   gfc_add_block_to_block (&body, &rse.pre);
10398   gfc_add_block_to_block (&body, &lse.pre);
10399   gfc_add_expr_to_block (&body, tmp);
10400   /* Add the post blocks to the body.  */
10401   gfc_add_block_to_block (&body, &rse.post);
10402   gfc_add_block_to_block (&body, &lse.post);
10403
10404   if (lss == gfc_ss_terminator)
10405     {
10406       /* F2003: Add the code for reallocation on assignment.  */
10407       if (flag_realloc_lhs && is_scalar_reallocatable_lhs (expr1)
10408           && !is_poly_assign)
10409         alloc_scalar_allocatable_for_assignment (&block, string_length,
10410                                                  expr1, expr2);
10411
10412       /* Use the scalar assignment as is.  */
10413       gfc_add_block_to_block (&block, &body);
10414     }
10415   else
10416     {
10417       gcc_assert (lse.ss == gfc_ss_terminator
10418                   && rse.ss == gfc_ss_terminator);
10419
10420       if (l_is_temp)
10421         {
10422           gfc_trans_scalarized_loop_boundary (&loop, &body);
10423
10424           /* We need to copy the temporary to the actual lhs.  */
10425           gfc_init_se (&lse, NULL);
10426           gfc_init_se (&rse, NULL);
10427           gfc_copy_loopinfo_to_se (&lse, &loop);
10428           gfc_copy_loopinfo_to_se (&rse, &loop);
10429
10430           rse.ss = loop.temp_ss;
10431           lse.ss = lss;
10432
10433           gfc_conv_tmp_array_ref (&rse);
10434           gfc_conv_expr (&lse, expr1);
10435
10436           gcc_assert (lse.ss == gfc_ss_terminator
10437                       && rse.ss == gfc_ss_terminator);
10438
10439           if (expr2->ts.type == BT_CHARACTER)
10440             rse.string_length = string_length;
10441
10442           tmp = gfc_trans_scalar_assign (&lse, &rse, expr1->ts,
10443                                          false, dealloc);
10444           gfc_add_expr_to_block (&body, tmp);
10445         }
10446
10447       /* F2003: Allocate or reallocate lhs of allocatable array.  */
10448       if (flag_realloc_lhs
10449           && gfc_is_reallocatable_lhs (expr1)
10450           && expr2->rank
10451           && !is_runtime_conformable (expr1, expr2))
10452         {
10453           realloc_lhs_warning (expr1->ts.type, true, &expr1->where);
10454           ompws_flags &= ~OMPWS_SCALARIZER_WS;
10455           tmp = gfc_alloc_allocatable_for_assignment (&loop, expr1, expr2);
10456           if (tmp != NULL_TREE)
10457             gfc_add_expr_to_block (&loop.code[expr1->rank - 1], tmp);
10458         }
10459
10460       if (maybe_workshare)
10461         ompws_flags &= ~OMPWS_SCALARIZER_BODY;
10462
10463       /* Generate the copying loops.  */
10464       gfc_trans_scalarizing_loops (&loop, &body);
10465
10466       /* Wrap the whole thing up.  */
10467       gfc_add_block_to_block (&block, &loop.pre);
10468       gfc_add_block_to_block (&block, &loop.post);
10469
10470       gfc_cleanup_loop (&loop);
10471     }
10472
10473   return gfc_finish_block (&block);
10474 }
10475
10476
10477 /* Check whether EXPR is a copyable array.  */
10478
10479 static bool
10480 copyable_array_p (gfc_expr * expr)
10481 {
10482   if (expr->expr_type != EXPR_VARIABLE)
10483     return false;
10484
10485   /* First check it's an array.  */
10486   if (expr->rank < 1 || !expr->ref || expr->ref->next)
10487     return false;
10488
10489   if (!gfc_full_array_ref_p (expr->ref, NULL))
10490     return false;
10491
10492   /* Next check that it's of a simple enough type.  */
10493   switch (expr->ts.type)
10494     {
10495     case BT_INTEGER:
10496     case BT_REAL:
10497     case BT_COMPLEX:
10498     case BT_LOGICAL:
10499       return true;
10500
10501     case BT_CHARACTER:
10502       return false;
10503
10504     case_bt_struct:
10505       return !expr->ts.u.derived->attr.alloc_comp;
10506
10507     default:
10508       break;
10509     }
10510
10511   return false;
10512 }
10513
10514 /* Translate an assignment.  */
10515
10516 tree
10517 gfc_trans_assignment (gfc_expr * expr1, gfc_expr * expr2, bool init_flag,
10518                       bool dealloc, bool use_vptr_copy, bool may_alias)
10519 {
10520   tree tmp;
10521
10522   /* Special case a single function returning an array.  */
10523   if (expr2->expr_type == EXPR_FUNCTION && expr2->rank > 0)
10524     {
10525       tmp = gfc_trans_arrayfunc_assign (expr1, expr2);
10526       if (tmp)
10527         return tmp;
10528     }
10529
10530   /* Special case assigning an array to zero.  */
10531   if (copyable_array_p (expr1)
10532       && is_zero_initializer_p (expr2))
10533     {
10534       tmp = gfc_trans_zero_assign (expr1);
10535       if (tmp)
10536         return tmp;
10537     }
10538
10539   /* Special case copying one array to another.  */
10540   if (copyable_array_p (expr1)
10541       && copyable_array_p (expr2)
10542       && gfc_compare_types (&expr1->ts, &expr2->ts)
10543       && !gfc_check_dependency (expr1, expr2, 0))
10544     {
10545       tmp = gfc_trans_array_copy (expr1, expr2);
10546       if (tmp)
10547         return tmp;
10548     }
10549
10550   /* Special case initializing an array from a constant array constructor.  */
10551   if (copyable_array_p (expr1)
10552       && expr2->expr_type == EXPR_ARRAY
10553       && gfc_compare_types (&expr1->ts, &expr2->ts))
10554     {
10555       tmp = gfc_trans_array_constructor_copy (expr1, expr2);
10556       if (tmp)
10557         return tmp;
10558     }
10559
10560   if (UNLIMITED_POLY (expr1) && expr1->rank
10561       && expr2->ts.type != BT_CLASS)
10562     use_vptr_copy = true;
10563
10564   /* Fallback to the scalarizer to generate explicit loops.  */
10565   return gfc_trans_assignment_1 (expr1, expr2, init_flag, dealloc,
10566                                  use_vptr_copy, may_alias);
10567 }
10568
10569 tree
10570 gfc_trans_init_assign (gfc_code * code)
10571 {
10572   return gfc_trans_assignment (code->expr1, code->expr2, true, false, true);
10573 }
10574
10575 tree
10576 gfc_trans_assign (gfc_code * code)
10577 {
10578   return gfc_trans_assignment (code->expr1, code->expr2, false, true);
10579 }