OSDN Git Service

2010-04-12 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-array.c
1 /* Array translation routines
2    Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Paul Brook <paul@nowt.org>
5    and Steven Bosscher <s.bosscher@student.tudelft.nl>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* trans-array.c-- Various array related code, including scalarization,
24                    allocation, initialization and other support routines.  */
25
26 /* How the scalarizer works.
27    In gfortran, array expressions use the same core routines as scalar
28    expressions.
29    First, a Scalarization State (SS) chain is built.  This is done by walking
30    the expression tree, and building a linear list of the terms in the
31    expression.  As the tree is walked, scalar subexpressions are translated.
32
33    The scalarization parameters are stored in a gfc_loopinfo structure.
34    First the start and stride of each term is calculated by
35    gfc_conv_ss_startstride.  During this process the expressions for the array
36    descriptors and data pointers are also translated.
37
38    If the expression is an assignment, we must then resolve any dependencies.
39    In fortran all the rhs values of an assignment must be evaluated before
40    any assignments take place.  This can require a temporary array to store the
41    values.  We also require a temporary when we are passing array expressions
42    or vector subscripts as procedure parameters.
43
44    Array sections are passed without copying to a temporary.  These use the
45    scalarizer to determine the shape of the section.  The flag
46    loop->array_parameter tells the scalarizer that the actual values and loop
47    variables will not be required.
48
49    The function gfc_conv_loop_setup generates the scalarization setup code.
50    It determines the range of the scalarizing loop variables.  If a temporary
51    is required, this is created and initialized.  Code for scalar expressions
52    taken outside the loop is also generated at this time.  Next the offset and
53    scaling required to translate from loop variables to array indices for each
54    term is calculated.
55
56    A call to gfc_start_scalarized_body marks the start of the scalarized
57    expression.  This creates a scope and declares the loop variables.  Before
58    calling this gfc_make_ss_chain_used must be used to indicate which terms
59    will be used inside this loop.
60
61    The scalar gfc_conv_* functions are then used to build the main body of the
62    scalarization loop.  Scalarization loop variables and precalculated scalar
63    values are automatically substituted.  Note that gfc_advance_se_ss_chain
64    must be used, rather than changing the se->ss directly.
65
66    For assignment expressions requiring a temporary two sub loops are
67    generated.  The first stores the result of the expression in the temporary,
68    the second copies it to the result.  A call to
69    gfc_trans_scalarized_loop_boundary marks the end of the main loop code and
70    the start of the copying loop.  The temporary may be less than full rank.
71
72    Finally gfc_trans_scalarizing_loops is called to generate the implicit do
73    loops.  The loops are added to the pre chain of the loopinfo.  The post
74    chain may still contain cleanup code.
75
76    After the loop code has been added into its parent scope gfc_cleanup_loop
77    is called to free all the SS allocated by the scalarizer.  */
78
79 #include "config.h"
80 #include "system.h"
81 #include "coretypes.h"
82 #include "tree.h"
83 #include "gimple.h"
84 #include "ggc.h"
85 #include "toplev.h"
86 #include "real.h"
87 #include "flags.h"
88 #include "gfortran.h"
89 #include "constructor.h"
90 #include "trans.h"
91 #include "trans-stmt.h"
92 #include "trans-types.h"
93 #include "trans-array.h"
94 #include "trans-const.h"
95 #include "dependency.h"
96
97 static gfc_ss *gfc_walk_subexpr (gfc_ss *, gfc_expr *);
98 static bool gfc_get_array_constructor_size (mpz_t *, gfc_constructor_base);
99
100 /* The contents of this structure aren't actually used, just the address.  */
101 static gfc_ss gfc_ss_terminator_var;
102 gfc_ss * const gfc_ss_terminator = &gfc_ss_terminator_var;
103
104
105 static tree
106 gfc_array_dataptr_type (tree desc)
107 {
108   return (GFC_TYPE_ARRAY_DATAPTR_TYPE (TREE_TYPE (desc)));
109 }
110
111
112 /* Build expressions to access the members of an array descriptor.
113    It's surprisingly easy to mess up here, so never access
114    an array descriptor by "brute force", always use these
115    functions.  This also avoids problems if we change the format
116    of an array descriptor.
117
118    To understand these magic numbers, look at the comments
119    before gfc_build_array_type() in trans-types.c.
120
121    The code within these defines should be the only code which knows the format
122    of an array descriptor.
123
124    Any code just needing to read obtain the bounds of an array should use
125    gfc_conv_array_* rather than the following functions as these will return
126    know constant values, and work with arrays which do not have descriptors.
127
128    Don't forget to #undef these!  */
129
130 #define DATA_FIELD 0
131 #define OFFSET_FIELD 1
132 #define DTYPE_FIELD 2
133 #define DIMENSION_FIELD 3
134
135 #define STRIDE_SUBFIELD 0
136 #define LBOUND_SUBFIELD 1
137 #define UBOUND_SUBFIELD 2
138
139 /* This provides READ-ONLY access to the data field.  The field itself
140    doesn't have the proper type.  */
141
142 tree
143 gfc_conv_descriptor_data_get (tree desc)
144 {
145   tree field, type, t;
146
147   type = TREE_TYPE (desc);
148   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
149
150   field = TYPE_FIELDS (type);
151   gcc_assert (DATA_FIELD == 0);
152
153   t = fold_build3 (COMPONENT_REF, TREE_TYPE (field), desc, field, NULL_TREE);
154   t = fold_convert (GFC_TYPE_ARRAY_DATAPTR_TYPE (type), t);
155
156   return t;
157 }
158
159 /* This provides WRITE access to the data field.
160
161    TUPLES_P is true if we are generating tuples.
162    
163    This function gets called through the following macros:
164      gfc_conv_descriptor_data_set
165      gfc_conv_descriptor_data_set.  */
166
167 void
168 gfc_conv_descriptor_data_set (stmtblock_t *block, tree desc, tree value)
169 {
170   tree field, type, t;
171
172   type = TREE_TYPE (desc);
173   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
174
175   field = TYPE_FIELDS (type);
176   gcc_assert (DATA_FIELD == 0);
177
178   t = fold_build3 (COMPONENT_REF, TREE_TYPE (field), desc, field, NULL_TREE);
179   gfc_add_modify (block, t, fold_convert (TREE_TYPE (field), value));
180 }
181
182
183 /* This provides address access to the data field.  This should only be
184    used by array allocation, passing this on to the runtime.  */
185
186 tree
187 gfc_conv_descriptor_data_addr (tree desc)
188 {
189   tree field, type, t;
190
191   type = TREE_TYPE (desc);
192   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
193
194   field = TYPE_FIELDS (type);
195   gcc_assert (DATA_FIELD == 0);
196
197   t = fold_build3 (COMPONENT_REF, TREE_TYPE (field), desc, field, NULL_TREE);
198   return gfc_build_addr_expr (NULL_TREE, t);
199 }
200
201 static tree
202 gfc_conv_descriptor_offset (tree desc)
203 {
204   tree type;
205   tree field;
206
207   type = TREE_TYPE (desc);
208   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
209
210   field = gfc_advance_chain (TYPE_FIELDS (type), OFFSET_FIELD);
211   gcc_assert (field != NULL_TREE && TREE_TYPE (field) == gfc_array_index_type);
212
213   return fold_build3 (COMPONENT_REF, TREE_TYPE (field),
214                       desc, field, NULL_TREE);
215 }
216
217 tree
218 gfc_conv_descriptor_offset_get (tree desc)
219 {
220   return gfc_conv_descriptor_offset (desc);
221 }
222
223 void
224 gfc_conv_descriptor_offset_set (stmtblock_t *block, tree desc,
225                                 tree value)
226 {
227   tree t = gfc_conv_descriptor_offset (desc);
228   gfc_add_modify (block, t, fold_convert (TREE_TYPE (t), value));
229 }
230
231
232 tree
233 gfc_conv_descriptor_dtype (tree desc)
234 {
235   tree field;
236   tree type;
237
238   type = TREE_TYPE (desc);
239   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
240
241   field = gfc_advance_chain (TYPE_FIELDS (type), DTYPE_FIELD);
242   gcc_assert (field != NULL_TREE && TREE_TYPE (field) == gfc_array_index_type);
243
244   return fold_build3 (COMPONENT_REF, TREE_TYPE (field),
245                       desc, field, NULL_TREE);
246 }
247
248 static tree
249 gfc_conv_descriptor_dimension (tree desc, tree dim)
250 {
251   tree field;
252   tree type;
253   tree tmp;
254
255   type = TREE_TYPE (desc);
256   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
257
258   field = gfc_advance_chain (TYPE_FIELDS (type), DIMENSION_FIELD);
259   gcc_assert (field != NULL_TREE
260           && TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE
261           && TREE_CODE (TREE_TYPE (TREE_TYPE (field))) == RECORD_TYPE);
262
263   tmp = fold_build3 (COMPONENT_REF, TREE_TYPE (field),
264                      desc, field, NULL_TREE);
265   tmp = gfc_build_array_ref (tmp, dim, NULL);
266   return tmp;
267 }
268
269 static tree
270 gfc_conv_descriptor_stride (tree desc, tree dim)
271 {
272   tree tmp;
273   tree field;
274
275   tmp = gfc_conv_descriptor_dimension (desc, dim);
276   field = TYPE_FIELDS (TREE_TYPE (tmp));
277   field = gfc_advance_chain (field, STRIDE_SUBFIELD);
278   gcc_assert (field != NULL_TREE && TREE_TYPE (field) == gfc_array_index_type);
279
280   tmp = fold_build3 (COMPONENT_REF, TREE_TYPE (field),
281                      tmp, field, NULL_TREE);
282   return tmp;
283 }
284
285 tree
286 gfc_conv_descriptor_stride_get (tree desc, tree dim)
287 {
288   tree type = TREE_TYPE (desc);
289   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
290   if (integer_zerop (dim)
291       && GFC_TYPE_ARRAY_AKIND (type) == GFC_ARRAY_ALLOCATABLE)
292     return gfc_index_one_node;
293
294   return gfc_conv_descriptor_stride (desc, dim);
295 }
296
297 void
298 gfc_conv_descriptor_stride_set (stmtblock_t *block, tree desc,
299                                 tree dim, tree value)
300 {
301   tree t = gfc_conv_descriptor_stride (desc, dim);
302   gfc_add_modify (block, t, fold_convert (TREE_TYPE (t), value));
303 }
304
305 static tree
306 gfc_conv_descriptor_lbound (tree desc, tree dim)
307 {
308   tree tmp;
309   tree field;
310
311   tmp = gfc_conv_descriptor_dimension (desc, dim);
312   field = TYPE_FIELDS (TREE_TYPE (tmp));
313   field = gfc_advance_chain (field, LBOUND_SUBFIELD);
314   gcc_assert (field != NULL_TREE && TREE_TYPE (field) == gfc_array_index_type);
315
316   tmp = fold_build3 (COMPONENT_REF, TREE_TYPE (field),
317                      tmp, field, NULL_TREE);
318   return tmp;
319 }
320
321 tree
322 gfc_conv_descriptor_lbound_get (tree desc, tree dim)
323 {
324   return gfc_conv_descriptor_lbound (desc, dim);
325 }
326
327 void
328 gfc_conv_descriptor_lbound_set (stmtblock_t *block, tree desc,
329                                 tree dim, tree value)
330 {
331   tree t = gfc_conv_descriptor_lbound (desc, dim);
332   gfc_add_modify (block, t, fold_convert (TREE_TYPE (t), value));
333 }
334
335 static tree
336 gfc_conv_descriptor_ubound (tree desc, tree dim)
337 {
338   tree tmp;
339   tree field;
340
341   tmp = gfc_conv_descriptor_dimension (desc, dim);
342   field = TYPE_FIELDS (TREE_TYPE (tmp));
343   field = gfc_advance_chain (field, UBOUND_SUBFIELD);
344   gcc_assert (field != NULL_TREE && TREE_TYPE (field) == gfc_array_index_type);
345
346   tmp = fold_build3 (COMPONENT_REF, TREE_TYPE (field),
347                      tmp, field, NULL_TREE);
348   return tmp;
349 }
350
351 tree
352 gfc_conv_descriptor_ubound_get (tree desc, tree dim)
353 {
354   return gfc_conv_descriptor_ubound (desc, dim);
355 }
356
357 void
358 gfc_conv_descriptor_ubound_set (stmtblock_t *block, tree desc,
359                                 tree dim, tree value)
360 {
361   tree t = gfc_conv_descriptor_ubound (desc, dim);
362   gfc_add_modify (block, t, fold_convert (TREE_TYPE (t), value));
363 }
364
365 /* Build a null array descriptor constructor.  */
366
367 tree
368 gfc_build_null_descriptor (tree type)
369 {
370   tree field;
371   tree tmp;
372
373   gcc_assert (GFC_DESCRIPTOR_TYPE_P (type));
374   gcc_assert (DATA_FIELD == 0);
375   field = TYPE_FIELDS (type);
376
377   /* Set a NULL data pointer.  */
378   tmp = build_constructor_single (type, field, null_pointer_node);
379   TREE_CONSTANT (tmp) = 1;
380   /* All other fields are ignored.  */
381
382   return tmp;
383 }
384
385
386 /* Cleanup those #defines.  */
387
388 #undef DATA_FIELD
389 #undef OFFSET_FIELD
390 #undef DTYPE_FIELD
391 #undef DIMENSION_FIELD
392 #undef STRIDE_SUBFIELD
393 #undef LBOUND_SUBFIELD
394 #undef UBOUND_SUBFIELD
395
396
397 /* Mark a SS chain as used.  Flags specifies in which loops the SS is used.
398    flags & 1 = Main loop body.
399    flags & 2 = temp copy loop.  */
400
401 void
402 gfc_mark_ss_chain_used (gfc_ss * ss, unsigned flags)
403 {
404   for (; ss != gfc_ss_terminator; ss = ss->next)
405     ss->useflags = flags;
406 }
407
408 static void gfc_free_ss (gfc_ss *);
409
410
411 /* Free a gfc_ss chain.  */
412
413 static void
414 gfc_free_ss_chain (gfc_ss * ss)
415 {
416   gfc_ss *next;
417
418   while (ss != gfc_ss_terminator)
419     {
420       gcc_assert (ss != NULL);
421       next = ss->next;
422       gfc_free_ss (ss);
423       ss = next;
424     }
425 }
426
427
428 /* Free a SS.  */
429
430 static void
431 gfc_free_ss (gfc_ss * ss)
432 {
433   int n;
434
435   switch (ss->type)
436     {
437     case GFC_SS_SECTION:
438       for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
439         {
440           if (ss->data.info.subscript[n])
441             gfc_free_ss_chain (ss->data.info.subscript[n]);
442         }
443       break;
444
445     default:
446       break;
447     }
448
449   gfc_free (ss);
450 }
451
452
453 /* Free all the SS associated with a loop.  */
454
455 void
456 gfc_cleanup_loop (gfc_loopinfo * loop)
457 {
458   gfc_ss *ss;
459   gfc_ss *next;
460
461   ss = loop->ss;
462   while (ss != gfc_ss_terminator)
463     {
464       gcc_assert (ss != NULL);
465       next = ss->loop_chain;
466       gfc_free_ss (ss);
467       ss = next;
468     }
469 }
470
471
472 /* Associate a SS chain with a loop.  */
473
474 void
475 gfc_add_ss_to_loop (gfc_loopinfo * loop, gfc_ss * head)
476 {
477   gfc_ss *ss;
478
479   if (head == gfc_ss_terminator)
480     return;
481
482   ss = head;
483   for (; ss && ss != gfc_ss_terminator; ss = ss->next)
484     {
485       if (ss->next == gfc_ss_terminator)
486         ss->loop_chain = loop->ss;
487       else
488         ss->loop_chain = ss->next;
489     }
490   gcc_assert (ss == gfc_ss_terminator);
491   loop->ss = head;
492 }
493
494
495 /* Generate an initializer for a static pointer or allocatable array.  */
496
497 void
498 gfc_trans_static_array_pointer (gfc_symbol * sym)
499 {
500   tree type;
501
502   gcc_assert (TREE_STATIC (sym->backend_decl));
503   /* Just zero the data member.  */
504   type = TREE_TYPE (sym->backend_decl);
505   DECL_INITIAL (sym->backend_decl) = gfc_build_null_descriptor (type);
506 }
507
508
509 /* If the bounds of SE's loop have not yet been set, see if they can be
510    determined from array spec AS, which is the array spec of a called
511    function.  MAPPING maps the callee's dummy arguments to the values
512    that the caller is passing.  Add any initialization and finalization
513    code to SE.  */
514
515 void
516 gfc_set_loop_bounds_from_array_spec (gfc_interface_mapping * mapping,
517                                      gfc_se * se, gfc_array_spec * as)
518 {
519   int n, dim;
520   gfc_se tmpse;
521   tree lower;
522   tree upper;
523   tree tmp;
524
525   if (as && as->type == AS_EXPLICIT)
526     for (dim = 0; dim < se->loop->dimen; dim++)
527       {
528         n = se->loop->order[dim];
529         if (se->loop->to[n] == NULL_TREE)
530           {
531             /* Evaluate the lower bound.  */
532             gfc_init_se (&tmpse, NULL);
533             gfc_apply_interface_mapping (mapping, &tmpse, as->lower[dim]);
534             gfc_add_block_to_block (&se->pre, &tmpse.pre);
535             gfc_add_block_to_block (&se->post, &tmpse.post);
536             lower = fold_convert (gfc_array_index_type, tmpse.expr);
537
538             /* ...and the upper bound.  */
539             gfc_init_se (&tmpse, NULL);
540             gfc_apply_interface_mapping (mapping, &tmpse, as->upper[dim]);
541             gfc_add_block_to_block (&se->pre, &tmpse.pre);
542             gfc_add_block_to_block (&se->post, &tmpse.post);
543             upper = fold_convert (gfc_array_index_type, tmpse.expr);
544
545             /* Set the upper bound of the loop to UPPER - LOWER.  */
546             tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, upper, lower);
547             tmp = gfc_evaluate_now (tmp, &se->pre);
548             se->loop->to[n] = tmp;
549           }
550       }
551 }
552
553
554 /* Generate code to allocate an array temporary, or create a variable to
555    hold the data.  If size is NULL, zero the descriptor so that the
556    callee will allocate the array.  If DEALLOC is true, also generate code to
557    free the array afterwards.
558
559    If INITIAL is not NULL, it is packed using internal_pack and the result used
560    as data instead of allocating a fresh, unitialized area of memory.
561
562    Initialization code is added to PRE and finalization code to POST.
563    DYNAMIC is true if the caller may want to extend the array later
564    using realloc.  This prevents us from putting the array on the stack.  */
565
566 static void
567 gfc_trans_allocate_array_storage (stmtblock_t * pre, stmtblock_t * post,
568                                   gfc_ss_info * info, tree size, tree nelem,
569                                   tree initial, bool dynamic, bool dealloc)
570 {
571   tree tmp;
572   tree desc;
573   bool onstack;
574
575   desc = info->descriptor;
576   info->offset = gfc_index_zero_node;
577   if (size == NULL_TREE || integer_zerop (size))
578     {
579       /* A callee allocated array.  */
580       gfc_conv_descriptor_data_set (pre, desc, null_pointer_node);
581       onstack = FALSE;
582     }
583   else
584     {
585       /* Allocate the temporary.  */
586       onstack = !dynamic && initial == NULL_TREE
587                          && gfc_can_put_var_on_stack (size);
588
589       if (onstack)
590         {
591           /* Make a temporary variable to hold the data.  */
592           tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (nelem), nelem,
593                              gfc_index_one_node);
594           tmp = build_range_type (gfc_array_index_type, gfc_index_zero_node,
595                                   tmp);
596           tmp = build_array_type (gfc_get_element_type (TREE_TYPE (desc)),
597                                   tmp);
598           tmp = gfc_create_var (tmp, "A");
599           tmp = gfc_build_addr_expr (NULL_TREE, tmp);
600           gfc_conv_descriptor_data_set (pre, desc, tmp);
601         }
602       else
603         {
604           /* Allocate memory to hold the data or call internal_pack.  */
605           if (initial == NULL_TREE)
606             {
607               tmp = gfc_call_malloc (pre, NULL, size);
608               tmp = gfc_evaluate_now (tmp, pre);
609             }
610           else
611             {
612               tree packed;
613               tree source_data;
614               tree was_packed;
615               stmtblock_t do_copying;
616
617               tmp = TREE_TYPE (initial); /* Pointer to descriptor.  */
618               gcc_assert (TREE_CODE (tmp) == POINTER_TYPE);
619               tmp = TREE_TYPE (tmp); /* The descriptor itself.  */
620               tmp = gfc_get_element_type (tmp);
621               gcc_assert (tmp == gfc_get_element_type (TREE_TYPE (desc)));
622               packed = gfc_create_var (build_pointer_type (tmp), "data");
623
624               tmp = build_call_expr_loc (input_location,
625                                      gfor_fndecl_in_pack, 1, initial);
626               tmp = fold_convert (TREE_TYPE (packed), tmp);
627               gfc_add_modify (pre, packed, tmp);
628
629               tmp = build_fold_indirect_ref_loc (input_location,
630                                              initial);
631               source_data = gfc_conv_descriptor_data_get (tmp);
632
633               /* internal_pack may return source->data without any allocation
634                  or copying if it is already packed.  If that's the case, we
635                  need to allocate and copy manually.  */
636
637               gfc_start_block (&do_copying);
638               tmp = gfc_call_malloc (&do_copying, NULL, size);
639               tmp = fold_convert (TREE_TYPE (packed), tmp);
640               gfc_add_modify (&do_copying, packed, tmp);
641               tmp = gfc_build_memcpy_call (packed, source_data, size);
642               gfc_add_expr_to_block (&do_copying, tmp);
643
644               was_packed = fold_build2 (EQ_EXPR, boolean_type_node,
645                                         packed, source_data);
646               tmp = gfc_finish_block (&do_copying);
647               tmp = build3_v (COND_EXPR, was_packed, tmp,
648                               build_empty_stmt (input_location));
649               gfc_add_expr_to_block (pre, tmp);
650
651               tmp = fold_convert (pvoid_type_node, packed);
652             }
653
654           gfc_conv_descriptor_data_set (pre, desc, tmp);
655         }
656     }
657   info->data = gfc_conv_descriptor_data_get (desc);
658
659   /* The offset is zero because we create temporaries with a zero
660      lower bound.  */
661   gfc_conv_descriptor_offset_set (pre, desc, gfc_index_zero_node);
662
663   if (dealloc && !onstack)
664     {
665       /* Free the temporary.  */
666       tmp = gfc_conv_descriptor_data_get (desc);
667       tmp = gfc_call_free (fold_convert (pvoid_type_node, tmp));
668       gfc_add_expr_to_block (post, tmp);
669     }
670 }
671
672
673 /* Generate code to create and initialize the descriptor for a temporary
674    array.  This is used for both temporaries needed by the scalarizer, and
675    functions returning arrays.  Adjusts the loop variables to be
676    zero-based, and calculates the loop bounds for callee allocated arrays.
677    Allocate the array unless it's callee allocated (we have a callee
678    allocated array if 'callee_alloc' is true, or if loop->to[n] is
679    NULL_TREE for any n).  Also fills in the descriptor, data and offset
680    fields of info if known.  Returns the size of the array, or NULL for a
681    callee allocated array.
682
683    PRE, POST, INITIAL, DYNAMIC and DEALLOC are as for
684    gfc_trans_allocate_array_storage.
685  */
686
687 tree
688 gfc_trans_create_temp_array (stmtblock_t * pre, stmtblock_t * post,
689                              gfc_loopinfo * loop, gfc_ss_info * info,
690                              tree eltype, tree initial, bool dynamic,
691                              bool dealloc, bool callee_alloc, locus * where)
692 {
693   tree type;
694   tree desc;
695   tree tmp;
696   tree size;
697   tree nelem;
698   tree cond;
699   tree or_expr;
700   int n;
701   int dim;
702
703   gcc_assert (info->dimen > 0);
704
705   if (gfc_option.warn_array_temp && where)
706     gfc_warning ("Creating array temporary at %L", where);
707
708   /* Set the lower bound to zero.  */
709   for (dim = 0; dim < info->dimen; dim++)
710     {
711       n = loop->order[dim];
712       /* Callee allocated arrays may not have a known bound yet.  */
713       if (loop->to[n])
714         loop->to[n] = gfc_evaluate_now (fold_build2 (MINUS_EXPR,
715                                         gfc_array_index_type,
716                                         loop->to[n], loop->from[n]), pre);
717       loop->from[n] = gfc_index_zero_node;
718
719       info->delta[dim] = gfc_index_zero_node;
720       info->start[dim] = gfc_index_zero_node;
721       info->end[dim] = gfc_index_zero_node;
722       info->stride[dim] = gfc_index_one_node;
723       info->dim[dim] = dim;
724     }
725
726   /* Initialize the descriptor.  */
727   type =
728     gfc_get_array_type_bounds (eltype, info->dimen, loop->from, loop->to, 1,
729                                GFC_ARRAY_UNKNOWN, true);
730   desc = gfc_create_var (type, "atmp");
731   GFC_DECL_PACKED_ARRAY (desc) = 1;
732
733   info->descriptor = desc;
734   size = gfc_index_one_node;
735
736   /* Fill in the array dtype.  */
737   tmp = gfc_conv_descriptor_dtype (desc);
738   gfc_add_modify (pre, tmp, gfc_get_dtype (TREE_TYPE (desc)));
739
740   /*
741      Fill in the bounds and stride.  This is a packed array, so:
742
743      size = 1;
744      for (n = 0; n < rank; n++)
745        {
746          stride[n] = size
747          delta = ubound[n] + 1 - lbound[n];
748          size = size * delta;
749        }
750      size = size * sizeof(element);
751   */
752
753   or_expr = NULL_TREE;
754
755   /* If there is at least one null loop->to[n], it is a callee allocated 
756      array.  */
757   for (n = 0; n < info->dimen; n++)
758     if (loop->to[n] == NULL_TREE)
759       {
760         size = NULL_TREE;
761         break;
762       }
763
764   for (n = 0; n < info->dimen; n++)
765      {
766       if (size == NULL_TREE)
767         {
768           /* For a callee allocated array express the loop bounds in terms
769              of the descriptor fields.  */
770           tmp =
771             fold_build2 (MINUS_EXPR, gfc_array_index_type,
772                          gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[n]),
773                          gfc_conv_descriptor_lbound_get (desc, gfc_rank_cst[n]));
774           loop->to[n] = tmp;
775           continue;
776         }
777         
778       /* Store the stride and bound components in the descriptor.  */
779       gfc_conv_descriptor_stride_set (pre, desc, gfc_rank_cst[n], size);
780
781       gfc_conv_descriptor_lbound_set (pre, desc, gfc_rank_cst[n],
782                                       gfc_index_zero_node);
783
784       gfc_conv_descriptor_ubound_set (pre, desc, gfc_rank_cst[n], loop->to[n]);
785
786       tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
787                          loop->to[n], gfc_index_one_node);
788
789       /* Check whether the size for this dimension is negative.  */
790       cond = fold_build2 (LE_EXPR, boolean_type_node, tmp,
791                           gfc_index_zero_node);
792       cond = gfc_evaluate_now (cond, pre);
793
794       if (n == 0)
795         or_expr = cond;
796       else
797         or_expr = fold_build2 (TRUTH_OR_EXPR, boolean_type_node, or_expr, cond);
798
799       size = fold_build2 (MULT_EXPR, gfc_array_index_type, size, tmp);
800       size = gfc_evaluate_now (size, pre);
801     }
802
803   /* Get the size of the array.  */
804
805   if (size && !callee_alloc)
806     {
807       /* If or_expr is true, then the extent in at least one
808          dimension is zero and the size is set to zero.  */
809       size = fold_build3 (COND_EXPR, gfc_array_index_type,
810                           or_expr, gfc_index_zero_node, size);
811
812       nelem = size;
813       size = fold_build2 (MULT_EXPR, gfc_array_index_type, size,
814                 fold_convert (gfc_array_index_type,
815                               TYPE_SIZE_UNIT (gfc_get_element_type (type))));
816     }
817   else
818     {
819       nelem = size;
820       size = NULL_TREE;
821     }
822
823   gfc_trans_allocate_array_storage (pre, post, info, size, nelem, initial,
824                                     dynamic, dealloc);
825
826   if (info->dimen > loop->temp_dim)
827     loop->temp_dim = info->dimen;
828
829   return size;
830 }
831
832
833 /* Generate code to transpose array EXPR by creating a new descriptor
834    in which the dimension specifications have been reversed.  */
835
836 void
837 gfc_conv_array_transpose (gfc_se * se, gfc_expr * expr)
838 {
839   tree dest, src, dest_index, src_index;
840   gfc_loopinfo *loop;
841   gfc_ss_info *dest_info;
842   gfc_ss *dest_ss, *src_ss;
843   gfc_se src_se;
844   int n;
845
846   loop = se->loop;
847
848   src_ss = gfc_walk_expr (expr);
849   dest_ss = se->ss;
850
851   dest_info = &dest_ss->data.info;
852   gcc_assert (dest_info->dimen == 2);
853
854   /* Get a descriptor for EXPR.  */
855   gfc_init_se (&src_se, NULL);
856   gfc_conv_expr_descriptor (&src_se, expr, src_ss);
857   gfc_add_block_to_block (&se->pre, &src_se.pre);
858   gfc_add_block_to_block (&se->post, &src_se.post);
859   src = src_se.expr;
860
861   /* Allocate a new descriptor for the return value.  */
862   dest = gfc_create_var (TREE_TYPE (src), "atmp");
863   dest_info->descriptor = dest;
864   se->expr = dest;
865
866   /* Copy across the dtype field.  */
867   gfc_add_modify (&se->pre,
868                        gfc_conv_descriptor_dtype (dest),
869                        gfc_conv_descriptor_dtype (src));
870
871   /* Copy the dimension information, renumbering dimension 1 to 0 and
872      0 to 1.  */
873   for (n = 0; n < 2; n++)
874     {
875       dest_info->delta[n] = gfc_index_zero_node;
876       dest_info->start[n] = gfc_index_zero_node;
877       dest_info->end[n] = gfc_index_zero_node;
878       dest_info->stride[n] = gfc_index_one_node;
879       dest_info->dim[n] = n;
880
881       dest_index = gfc_rank_cst[n];
882       src_index = gfc_rank_cst[1 - n];
883
884       gfc_conv_descriptor_stride_set (&se->pre, dest, dest_index,
885                            gfc_conv_descriptor_stride_get (src, src_index));
886
887       gfc_conv_descriptor_lbound_set (&se->pre, dest, dest_index,
888                            gfc_conv_descriptor_lbound_get (src, src_index));
889
890       gfc_conv_descriptor_ubound_set (&se->pre, dest, dest_index,
891                            gfc_conv_descriptor_ubound_get (src, src_index));
892
893       if (!loop->to[n])
894         {
895           gcc_assert (integer_zerop (loop->from[n]));
896           loop->to[n] =
897             fold_build2 (MINUS_EXPR, gfc_array_index_type,
898                          gfc_conv_descriptor_ubound_get (dest, dest_index),
899                          gfc_conv_descriptor_lbound_get (dest, dest_index));
900         }
901     }
902
903   /* Copy the data pointer.  */
904   dest_info->data = gfc_conv_descriptor_data_get (src);
905   gfc_conv_descriptor_data_set (&se->pre, dest, dest_info->data);
906
907   /* Copy the offset.  This is not changed by transposition; the top-left
908      element is still at the same offset as before, except where the loop
909      starts at zero.  */
910   if (!integer_zerop (loop->from[0]))
911     dest_info->offset = gfc_conv_descriptor_offset_get (src);
912   else
913     dest_info->offset = gfc_index_zero_node;
914
915   gfc_conv_descriptor_offset_set (&se->pre, dest,
916                                   dest_info->offset);
917           
918   if (dest_info->dimen > loop->temp_dim)
919     loop->temp_dim = dest_info->dimen;
920 }
921
922
923 /* Return the number of iterations in a loop that starts at START,
924    ends at END, and has step STEP.  */
925
926 static tree
927 gfc_get_iteration_count (tree start, tree end, tree step)
928 {
929   tree tmp;
930   tree type;
931
932   type = TREE_TYPE (step);
933   tmp = fold_build2 (MINUS_EXPR, type, end, start);
934   tmp = fold_build2 (FLOOR_DIV_EXPR, type, tmp, step);
935   tmp = fold_build2 (PLUS_EXPR, type, tmp, build_int_cst (type, 1));
936   tmp = fold_build2 (MAX_EXPR, type, tmp, build_int_cst (type, 0));
937   return fold_convert (gfc_array_index_type, tmp);
938 }
939
940
941 /* Extend the data in array DESC by EXTRA elements.  */
942
943 static void
944 gfc_grow_array (stmtblock_t * pblock, tree desc, tree extra)
945 {
946   tree arg0, arg1;
947   tree tmp;
948   tree size;
949   tree ubound;
950
951   if (integer_zerop (extra))
952     return;
953
954   ubound = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[0]);
955
956   /* Add EXTRA to the upper bound.  */
957   tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, ubound, extra);
958   gfc_conv_descriptor_ubound_set (pblock, desc, gfc_rank_cst[0], tmp);
959
960   /* Get the value of the current data pointer.  */
961   arg0 = gfc_conv_descriptor_data_get (desc);
962
963   /* Calculate the new array size.  */
964   size = TYPE_SIZE_UNIT (gfc_get_element_type (TREE_TYPE (desc)));
965   tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
966                      ubound, gfc_index_one_node);
967   arg1 = fold_build2 (MULT_EXPR, size_type_node,
968                        fold_convert (size_type_node, tmp),
969                        fold_convert (size_type_node, size));
970
971   /* Call the realloc() function.  */
972   tmp = gfc_call_realloc (pblock, arg0, arg1);
973   gfc_conv_descriptor_data_set (pblock, desc, tmp);
974 }
975
976
977 /* Return true if the bounds of iterator I can only be determined
978    at run time.  */
979
980 static inline bool
981 gfc_iterator_has_dynamic_bounds (gfc_iterator * i)
982 {
983   return (i->start->expr_type != EXPR_CONSTANT
984           || i->end->expr_type != EXPR_CONSTANT
985           || i->step->expr_type != EXPR_CONSTANT);
986 }
987
988
989 /* Split the size of constructor element EXPR into the sum of two terms,
990    one of which can be determined at compile time and one of which must
991    be calculated at run time.  Set *SIZE to the former and return true
992    if the latter might be nonzero.  */
993
994 static bool
995 gfc_get_array_constructor_element_size (mpz_t * size, gfc_expr * expr)
996 {
997   if (expr->expr_type == EXPR_ARRAY)
998     return gfc_get_array_constructor_size (size, expr->value.constructor);
999   else if (expr->rank > 0)
1000     {
1001       /* Calculate everything at run time.  */
1002       mpz_set_ui (*size, 0);
1003       return true;
1004     }
1005   else
1006     {
1007       /* A single element.  */
1008       mpz_set_ui (*size, 1);
1009       return false;
1010     }
1011 }
1012
1013
1014 /* Like gfc_get_array_constructor_element_size, but applied to the whole
1015    of array constructor C.  */
1016
1017 static bool
1018 gfc_get_array_constructor_size (mpz_t * size, gfc_constructor_base base)
1019 {
1020   gfc_constructor *c;
1021   gfc_iterator *i;
1022   mpz_t val;
1023   mpz_t len;
1024   bool dynamic;
1025
1026   mpz_set_ui (*size, 0);
1027   mpz_init (len);
1028   mpz_init (val);
1029
1030   dynamic = false;
1031   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1032     {
1033       i = c->iterator;
1034       if (i && gfc_iterator_has_dynamic_bounds (i))
1035         dynamic = true;
1036       else
1037         {
1038           dynamic |= gfc_get_array_constructor_element_size (&len, c->expr);
1039           if (i)
1040             {
1041               /* Multiply the static part of the element size by the
1042                  number of iterations.  */
1043               mpz_sub (val, i->end->value.integer, i->start->value.integer);
1044               mpz_fdiv_q (val, val, i->step->value.integer);
1045               mpz_add_ui (val, val, 1);
1046               if (mpz_sgn (val) > 0)
1047                 mpz_mul (len, len, val);
1048               else
1049                 mpz_set_ui (len, 0);
1050             }
1051           mpz_add (*size, *size, len);
1052         }
1053     }
1054   mpz_clear (len);
1055   mpz_clear (val);
1056   return dynamic;
1057 }
1058
1059
1060 /* Make sure offset is a variable.  */
1061
1062 static void
1063 gfc_put_offset_into_var (stmtblock_t * pblock, tree * poffset,
1064                          tree * offsetvar)
1065 {
1066   /* We should have already created the offset variable.  We cannot
1067      create it here because we may be in an inner scope.  */
1068   gcc_assert (*offsetvar != NULL_TREE);
1069   gfc_add_modify (pblock, *offsetvar, *poffset);
1070   *poffset = *offsetvar;
1071   TREE_USED (*offsetvar) = 1;
1072 }
1073
1074
1075 /* Variables needed for bounds-checking.  */
1076 static bool first_len;
1077 static tree first_len_val; 
1078 static bool typespec_chararray_ctor;
1079
1080 static void
1081 gfc_trans_array_ctor_element (stmtblock_t * pblock, tree desc,
1082                               tree offset, gfc_se * se, gfc_expr * expr)
1083 {
1084   tree tmp;
1085
1086   gfc_conv_expr (se, expr);
1087
1088   /* Store the value.  */
1089   tmp = build_fold_indirect_ref_loc (input_location,
1090                                  gfc_conv_descriptor_data_get (desc));
1091   tmp = gfc_build_array_ref (tmp, offset, NULL);
1092
1093   if (expr->ts.type == BT_CHARACTER)
1094     {
1095       int i = gfc_validate_kind (BT_CHARACTER, expr->ts.kind, false);
1096       tree esize;
1097
1098       esize = size_in_bytes (gfc_get_element_type (TREE_TYPE (desc)));
1099       esize = fold_convert (gfc_charlen_type_node, esize);
1100       esize = fold_build2 (TRUNC_DIV_EXPR, gfc_charlen_type_node, esize,
1101                            build_int_cst (gfc_charlen_type_node,
1102                                           gfc_character_kinds[i].bit_size / 8));
1103
1104       gfc_conv_string_parameter (se);
1105       if (POINTER_TYPE_P (TREE_TYPE (tmp)))
1106         {
1107           /* The temporary is an array of pointers.  */
1108           se->expr = fold_convert (TREE_TYPE (tmp), se->expr);
1109           gfc_add_modify (&se->pre, tmp, se->expr);
1110         }
1111       else
1112         {
1113           /* The temporary is an array of string values.  */
1114           tmp = gfc_build_addr_expr (gfc_get_pchar_type (expr->ts.kind), tmp);
1115           /* We know the temporary and the value will be the same length,
1116              so can use memcpy.  */
1117           gfc_trans_string_copy (&se->pre, esize, tmp, expr->ts.kind,
1118                                  se->string_length, se->expr, expr->ts.kind);
1119         }
1120       if ((gfc_option.rtcheck & GFC_RTCHECK_BOUNDS) && !typespec_chararray_ctor)
1121         {
1122           if (first_len)
1123             {
1124               gfc_add_modify (&se->pre, first_len_val,
1125                                    se->string_length);
1126               first_len = false;
1127             }
1128           else
1129             {
1130               /* Verify that all constructor elements are of the same
1131                  length.  */
1132               tree cond = fold_build2 (NE_EXPR, boolean_type_node,
1133                                        first_len_val, se->string_length);
1134               gfc_trans_runtime_check
1135                 (true, false, cond, &se->pre, &expr->where,
1136                  "Different CHARACTER lengths (%ld/%ld) in array constructor",
1137                  fold_convert (long_integer_type_node, first_len_val),
1138                  fold_convert (long_integer_type_node, se->string_length));
1139             }
1140         }
1141     }
1142   else
1143     {
1144       /* TODO: Should the frontend already have done this conversion?  */
1145       se->expr = fold_convert (TREE_TYPE (tmp), se->expr);
1146       gfc_add_modify (&se->pre, tmp, se->expr);
1147     }
1148
1149   gfc_add_block_to_block (pblock, &se->pre);
1150   gfc_add_block_to_block (pblock, &se->post);
1151 }
1152
1153
1154 /* Add the contents of an array to the constructor.  DYNAMIC is as for
1155    gfc_trans_array_constructor_value.  */
1156
1157 static void
1158 gfc_trans_array_constructor_subarray (stmtblock_t * pblock,
1159                                       tree type ATTRIBUTE_UNUSED,
1160                                       tree desc, gfc_expr * expr,
1161                                       tree * poffset, tree * offsetvar,
1162                                       bool dynamic)
1163 {
1164   gfc_se se;
1165   gfc_ss *ss;
1166   gfc_loopinfo loop;
1167   stmtblock_t body;
1168   tree tmp;
1169   tree size;
1170   int n;
1171
1172   /* We need this to be a variable so we can increment it.  */
1173   gfc_put_offset_into_var (pblock, poffset, offsetvar);
1174
1175   gfc_init_se (&se, NULL);
1176
1177   /* Walk the array expression.  */
1178   ss = gfc_walk_expr (expr);
1179   gcc_assert (ss != gfc_ss_terminator);
1180
1181   /* Initialize the scalarizer.  */
1182   gfc_init_loopinfo (&loop);
1183   gfc_add_ss_to_loop (&loop, ss);
1184
1185   /* Initialize the loop.  */
1186   gfc_conv_ss_startstride (&loop);
1187   gfc_conv_loop_setup (&loop, &expr->where);
1188
1189   /* Make sure the constructed array has room for the new data.  */
1190   if (dynamic)
1191     {
1192       /* Set SIZE to the total number of elements in the subarray.  */
1193       size = gfc_index_one_node;
1194       for (n = 0; n < loop.dimen; n++)
1195         {
1196           tmp = gfc_get_iteration_count (loop.from[n], loop.to[n],
1197                                          gfc_index_one_node);
1198           size = fold_build2 (MULT_EXPR, gfc_array_index_type, size, tmp);
1199         }
1200
1201       /* Grow the constructed array by SIZE elements.  */
1202       gfc_grow_array (&loop.pre, desc, size);
1203     }
1204
1205   /* Make the loop body.  */
1206   gfc_mark_ss_chain_used (ss, 1);
1207   gfc_start_scalarized_body (&loop, &body);
1208   gfc_copy_loopinfo_to_se (&se, &loop);
1209   se.ss = ss;
1210
1211   gfc_trans_array_ctor_element (&body, desc, *poffset, &se, expr);
1212   gcc_assert (se.ss == gfc_ss_terminator);
1213
1214   /* Increment the offset.  */
1215   tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
1216                      *poffset, gfc_index_one_node);
1217   gfc_add_modify (&body, *poffset, tmp);
1218
1219   /* Finish the loop.  */
1220   gfc_trans_scalarizing_loops (&loop, &body);
1221   gfc_add_block_to_block (&loop.pre, &loop.post);
1222   tmp = gfc_finish_block (&loop.pre);
1223   gfc_add_expr_to_block (pblock, tmp);
1224
1225   gfc_cleanup_loop (&loop);
1226 }
1227
1228
1229 /* Assign the values to the elements of an array constructor.  DYNAMIC
1230    is true if descriptor DESC only contains enough data for the static
1231    size calculated by gfc_get_array_constructor_size.  When true, memory
1232    for the dynamic parts must be allocated using realloc.  */
1233
1234 static void
1235 gfc_trans_array_constructor_value (stmtblock_t * pblock, tree type,
1236                                    tree desc, gfc_constructor_base base,
1237                                    tree * poffset, tree * offsetvar,
1238                                    bool dynamic)
1239 {
1240   tree tmp;
1241   stmtblock_t body;
1242   gfc_se se;
1243   mpz_t size;
1244   gfc_constructor *c;
1245
1246   tree shadow_loopvar = NULL_TREE;
1247   gfc_saved_var saved_loopvar;
1248
1249   mpz_init (size);
1250   for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1251     {
1252       /* If this is an iterator or an array, the offset must be a variable.  */
1253       if ((c->iterator || c->expr->rank > 0) && INTEGER_CST_P (*poffset))
1254         gfc_put_offset_into_var (pblock, poffset, offsetvar);
1255
1256       /* Shadowing the iterator avoids changing its value and saves us from
1257          keeping track of it. Further, it makes sure that there's always a
1258          backend-decl for the symbol, even if there wasn't one before,
1259          e.g. in the case of an iterator that appears in a specification
1260          expression in an interface mapping.  */
1261       if (c->iterator)
1262         {
1263           gfc_symbol *sym = c->iterator->var->symtree->n.sym;
1264           tree type = gfc_typenode_for_spec (&sym->ts);
1265
1266           shadow_loopvar = gfc_create_var (type, "shadow_loopvar");
1267           gfc_shadow_sym (sym, shadow_loopvar, &saved_loopvar);
1268         }
1269
1270       gfc_start_block (&body);
1271
1272       if (c->expr->expr_type == EXPR_ARRAY)
1273         {
1274           /* Array constructors can be nested.  */
1275           gfc_trans_array_constructor_value (&body, type, desc,
1276                                              c->expr->value.constructor,
1277                                              poffset, offsetvar, dynamic);
1278         }
1279       else if (c->expr->rank > 0)
1280         {
1281           gfc_trans_array_constructor_subarray (&body, type, desc, c->expr,
1282                                                 poffset, offsetvar, dynamic);
1283         }
1284       else
1285         {
1286           /* This code really upsets the gimplifier so don't bother for now.  */
1287           gfc_constructor *p;
1288           HOST_WIDE_INT n;
1289           HOST_WIDE_INT size;
1290
1291           p = c;
1292           n = 0;
1293           while (p && !(p->iterator || p->expr->expr_type != EXPR_CONSTANT))
1294             {
1295               p = gfc_constructor_next (p);
1296               n++;
1297             }
1298           if (n < 4)
1299             {
1300               /* Scalar values.  */
1301               gfc_init_se (&se, NULL);
1302               gfc_trans_array_ctor_element (&body, desc, *poffset,
1303                                             &se, c->expr);
1304
1305               *poffset = fold_build2 (PLUS_EXPR, gfc_array_index_type,
1306                                       *poffset, gfc_index_one_node);
1307             }
1308           else
1309             {
1310               /* Collect multiple scalar constants into a constructor.  */
1311               tree list;
1312               tree init;
1313               tree bound;
1314               tree tmptype;
1315               HOST_WIDE_INT idx = 0;
1316
1317               p = c;
1318               list = NULL_TREE;
1319               /* Count the number of consecutive scalar constants.  */
1320               while (p && !(p->iterator
1321                             || p->expr->expr_type != EXPR_CONSTANT))
1322                 {
1323                   gfc_init_se (&se, NULL);
1324                   gfc_conv_constant (&se, p->expr);
1325
1326                   if (c->expr->ts.type != BT_CHARACTER)
1327                     se.expr = fold_convert (type, se.expr);
1328                   /* For constant character array constructors we build
1329                      an array of pointers.  */
1330                   else if (POINTER_TYPE_P (type))
1331                     se.expr = gfc_build_addr_expr
1332                                 (gfc_get_pchar_type (p->expr->ts.kind),
1333                                  se.expr);
1334
1335                   list = tree_cons (build_int_cst (gfc_array_index_type,
1336                                                    idx++), se.expr, list);
1337                   c = p;
1338                   p = gfc_constructor_next (p);
1339                 }
1340
1341               bound = build_int_cst (NULL_TREE, n - 1);
1342               /* Create an array type to hold them.  */
1343               tmptype = build_range_type (gfc_array_index_type,
1344                                           gfc_index_zero_node, bound);
1345               tmptype = build_array_type (type, tmptype);
1346
1347               init = build_constructor_from_list (tmptype, nreverse (list));
1348               TREE_CONSTANT (init) = 1;
1349               TREE_STATIC (init) = 1;
1350               /* Create a static variable to hold the data.  */
1351               tmp = gfc_create_var (tmptype, "data");
1352               TREE_STATIC (tmp) = 1;
1353               TREE_CONSTANT (tmp) = 1;
1354               TREE_READONLY (tmp) = 1;
1355               DECL_INITIAL (tmp) = init;
1356               init = tmp;
1357
1358               /* Use BUILTIN_MEMCPY to assign the values.  */
1359               tmp = gfc_conv_descriptor_data_get (desc);
1360               tmp = build_fold_indirect_ref_loc (input_location,
1361                                              tmp);
1362               tmp = gfc_build_array_ref (tmp, *poffset, NULL);
1363               tmp = gfc_build_addr_expr (NULL_TREE, tmp);
1364               init = gfc_build_addr_expr (NULL_TREE, init);
1365
1366               size = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (type));
1367               bound = build_int_cst (NULL_TREE, n * size);
1368               tmp = build_call_expr_loc (input_location,
1369                                      built_in_decls[BUILT_IN_MEMCPY], 3,
1370                                      tmp, init, bound);
1371               gfc_add_expr_to_block (&body, tmp);
1372
1373               *poffset = fold_build2 (PLUS_EXPR, gfc_array_index_type,
1374                                       *poffset,
1375                                       build_int_cst (gfc_array_index_type, n));
1376             }
1377           if (!INTEGER_CST_P (*poffset))
1378             {
1379               gfc_add_modify (&body, *offsetvar, *poffset);
1380               *poffset = *offsetvar;
1381             }
1382         }
1383
1384       /* The frontend should already have done any expansions
1385          at compile-time.  */
1386       if (!c->iterator)
1387         {
1388           /* Pass the code as is.  */
1389           tmp = gfc_finish_block (&body);
1390           gfc_add_expr_to_block (pblock, tmp);
1391         }
1392       else
1393         {
1394           /* Build the implied do-loop.  */
1395           stmtblock_t implied_do_block;
1396           tree cond;
1397           tree end;
1398           tree step;
1399           tree exit_label;
1400           tree loopbody;
1401           tree tmp2;
1402
1403           loopbody = gfc_finish_block (&body);
1404
1405           /* Create a new block that holds the implied-do loop. A temporary
1406              loop-variable is used.  */
1407           gfc_start_block(&implied_do_block);
1408
1409           /* Initialize the loop.  */
1410           gfc_init_se (&se, NULL);
1411           gfc_conv_expr_val (&se, c->iterator->start);
1412           gfc_add_block_to_block (&implied_do_block, &se.pre);
1413           gfc_add_modify (&implied_do_block, shadow_loopvar, se.expr);
1414
1415           gfc_init_se (&se, NULL);
1416           gfc_conv_expr_val (&se, c->iterator->end);
1417           gfc_add_block_to_block (&implied_do_block, &se.pre);
1418           end = gfc_evaluate_now (se.expr, &implied_do_block);
1419
1420           gfc_init_se (&se, NULL);
1421           gfc_conv_expr_val (&se, c->iterator->step);
1422           gfc_add_block_to_block (&implied_do_block, &se.pre);
1423           step = gfc_evaluate_now (se.expr, &implied_do_block);
1424
1425           /* If this array expands dynamically, and the number of iterations
1426              is not constant, we won't have allocated space for the static
1427              part of C->EXPR's size.  Do that now.  */
1428           if (dynamic && gfc_iterator_has_dynamic_bounds (c->iterator))
1429             {
1430               /* Get the number of iterations.  */
1431               tmp = gfc_get_iteration_count (shadow_loopvar, end, step);
1432
1433               /* Get the static part of C->EXPR's size.  */
1434               gfc_get_array_constructor_element_size (&size, c->expr);
1435               tmp2 = gfc_conv_mpz_to_tree (size, gfc_index_integer_kind);
1436
1437               /* Grow the array by TMP * TMP2 elements.  */
1438               tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, tmp, tmp2);
1439               gfc_grow_array (&implied_do_block, desc, tmp);
1440             }
1441
1442           /* Generate the loop body.  */
1443           exit_label = gfc_build_label_decl (NULL_TREE);
1444           gfc_start_block (&body);
1445
1446           /* Generate the exit condition.  Depending on the sign of
1447              the step variable we have to generate the correct
1448              comparison.  */
1449           tmp = fold_build2 (GT_EXPR, boolean_type_node, step, 
1450                              build_int_cst (TREE_TYPE (step), 0));
1451           cond = fold_build3 (COND_EXPR, boolean_type_node, tmp,
1452                               fold_build2 (GT_EXPR, boolean_type_node,
1453                                            shadow_loopvar, end),
1454                               fold_build2 (LT_EXPR, boolean_type_node,
1455                                            shadow_loopvar, end));
1456           tmp = build1_v (GOTO_EXPR, exit_label);
1457           TREE_USED (exit_label) = 1;
1458           tmp = build3_v (COND_EXPR, cond, tmp,
1459                           build_empty_stmt (input_location));
1460           gfc_add_expr_to_block (&body, tmp);
1461
1462           /* The main loop body.  */
1463           gfc_add_expr_to_block (&body, loopbody);
1464
1465           /* Increase loop variable by step.  */
1466           tmp = fold_build2 (PLUS_EXPR, TREE_TYPE (shadow_loopvar), shadow_loopvar, step);
1467           gfc_add_modify (&body, shadow_loopvar, tmp);
1468
1469           /* Finish the loop.  */
1470           tmp = gfc_finish_block (&body);
1471           tmp = build1_v (LOOP_EXPR, tmp);
1472           gfc_add_expr_to_block (&implied_do_block, tmp);
1473
1474           /* Add the exit label.  */
1475           tmp = build1_v (LABEL_EXPR, exit_label);
1476           gfc_add_expr_to_block (&implied_do_block, tmp);
1477
1478           /* Finishe the implied-do loop.  */
1479           tmp = gfc_finish_block(&implied_do_block);
1480           gfc_add_expr_to_block(pblock, tmp);
1481
1482           gfc_restore_sym (c->iterator->var->symtree->n.sym, &saved_loopvar);
1483         }
1484     }
1485   mpz_clear (size);
1486 }
1487
1488
1489 /* Figure out the string length of a variable reference expression.
1490    Used by get_array_ctor_strlen.  */
1491
1492 static void
1493 get_array_ctor_var_strlen (gfc_expr * expr, tree * len)
1494 {
1495   gfc_ref *ref;
1496   gfc_typespec *ts;
1497   mpz_t char_len;
1498
1499   /* Don't bother if we already know the length is a constant.  */
1500   if (*len && INTEGER_CST_P (*len))
1501     return;
1502
1503   ts = &expr->symtree->n.sym->ts;
1504   for (ref = expr->ref; ref; ref = ref->next)
1505     {
1506       switch (ref->type)
1507         {
1508         case REF_ARRAY:
1509           /* Array references don't change the string length.  */
1510           break;
1511
1512         case REF_COMPONENT:
1513           /* Use the length of the component.  */
1514           ts = &ref->u.c.component->ts;
1515           break;
1516
1517         case REF_SUBSTRING:
1518           if (ref->u.ss.start->expr_type != EXPR_CONSTANT
1519               || ref->u.ss.end->expr_type != EXPR_CONSTANT)
1520             break;
1521           mpz_init_set_ui (char_len, 1);
1522           mpz_add (char_len, char_len, ref->u.ss.end->value.integer);
1523           mpz_sub (char_len, char_len, ref->u.ss.start->value.integer);
1524           *len = gfc_conv_mpz_to_tree (char_len, gfc_default_integer_kind);
1525           *len = convert (gfc_charlen_type_node, *len);
1526           mpz_clear (char_len);
1527           return;
1528
1529         default:
1530           /* TODO: Substrings are tricky because we can't evaluate the
1531              expression more than once.  For now we just give up, and hope
1532              we can figure it out elsewhere.  */
1533           return;
1534         }
1535     }
1536
1537   *len = ts->u.cl->backend_decl;
1538 }
1539
1540
1541 /* A catch-all to obtain the string length for anything that is not a
1542    constant, array or variable.  */
1543 static void
1544 get_array_ctor_all_strlen (stmtblock_t *block, gfc_expr *e, tree *len)
1545 {
1546   gfc_se se;
1547   gfc_ss *ss;
1548
1549   /* Don't bother if we already know the length is a constant.  */
1550   if (*len && INTEGER_CST_P (*len))
1551     return;
1552
1553   if (!e->ref && e->ts.u.cl && e->ts.u.cl->length
1554         && e->ts.u.cl->length->expr_type == EXPR_CONSTANT)
1555     {
1556       /* This is easy.  */
1557       gfc_conv_const_charlen (e->ts.u.cl);
1558       *len = e->ts.u.cl->backend_decl;
1559     }
1560   else
1561     {
1562       /* Otherwise, be brutal even if inefficient.  */
1563       ss = gfc_walk_expr (e);
1564       gfc_init_se (&se, NULL);
1565
1566       /* No function call, in case of side effects.  */
1567       se.no_function_call = 1;
1568       if (ss == gfc_ss_terminator)
1569         gfc_conv_expr (&se, e);
1570       else
1571         gfc_conv_expr_descriptor (&se, e, ss);
1572
1573       /* Fix the value.  */
1574       *len = gfc_evaluate_now (se.string_length, &se.pre);
1575
1576       gfc_add_block_to_block (block, &se.pre);
1577       gfc_add_block_to_block (block, &se.post);
1578
1579       e->ts.u.cl->backend_decl = *len;
1580     }
1581 }
1582
1583
1584 /* Figure out the string length of a character array constructor.
1585    If len is NULL, don't calculate the length; this happens for recursive calls
1586    when a sub-array-constructor is an element but not at the first position,
1587    so when we're not interested in the length.
1588    Returns TRUE if all elements are character constants.  */
1589
1590 bool
1591 get_array_ctor_strlen (stmtblock_t *block, gfc_constructor_base base, tree * len)
1592 {
1593   gfc_constructor *c;
1594   bool is_const;
1595
1596   is_const = TRUE;
1597
1598   if (gfc_constructor_first (base) == NULL)
1599     {
1600       if (len)
1601         *len = build_int_cstu (gfc_charlen_type_node, 0);
1602       return is_const;
1603     }
1604
1605   /* Loop over all constructor elements to find out is_const, but in len we
1606      want to store the length of the first, not the last, element.  We can
1607      of course exit the loop as soon as is_const is found to be false.  */
1608   for (c = gfc_constructor_first (base);
1609        c && is_const; c = gfc_constructor_next (c))
1610     {
1611       switch (c->expr->expr_type)
1612         {
1613         case EXPR_CONSTANT:
1614           if (len && !(*len && INTEGER_CST_P (*len)))
1615             *len = build_int_cstu (gfc_charlen_type_node,
1616                                    c->expr->value.character.length);
1617           break;
1618
1619         case EXPR_ARRAY:
1620           if (!get_array_ctor_strlen (block, c->expr->value.constructor, len))
1621             is_const = false;
1622           break;
1623
1624         case EXPR_VARIABLE:
1625           is_const = false;
1626           if (len)
1627             get_array_ctor_var_strlen (c->expr, len);
1628           break;
1629
1630         default:
1631           is_const = false;
1632           if (len)
1633             get_array_ctor_all_strlen (block, c->expr, len);
1634           break;
1635         }
1636
1637       /* After the first iteration, we don't want the length modified.  */
1638       len = NULL;
1639     }
1640
1641   return is_const;
1642 }
1643
1644 /* Check whether the array constructor C consists entirely of constant
1645    elements, and if so returns the number of those elements, otherwise
1646    return zero.  Note, an empty or NULL array constructor returns zero.  */
1647
1648 unsigned HOST_WIDE_INT
1649 gfc_constant_array_constructor_p (gfc_constructor_base base)
1650 {
1651   unsigned HOST_WIDE_INT nelem = 0;
1652
1653   gfc_constructor *c = gfc_constructor_first (base);
1654   while (c)
1655     {
1656       if (c->iterator
1657           || c->expr->rank > 0
1658           || c->expr->expr_type != EXPR_CONSTANT)
1659         return 0;
1660       c = gfc_constructor_next (c);
1661       nelem++;
1662     }
1663   return nelem;
1664 }
1665
1666
1667 /* Given EXPR, the constant array constructor specified by an EXPR_ARRAY,
1668    and the tree type of it's elements, TYPE, return a static constant
1669    variable that is compile-time initialized.  */
1670
1671 tree
1672 gfc_build_constant_array_constructor (gfc_expr * expr, tree type)
1673 {
1674   tree tmptype, list, init, tmp;
1675   HOST_WIDE_INT nelem;
1676   gfc_constructor *c;
1677   gfc_array_spec as;
1678   gfc_se se;
1679   int i;
1680
1681   /* First traverse the constructor list, converting the constants
1682      to tree to build an initializer.  */
1683   nelem = 0;
1684   list = NULL_TREE;
1685   c = gfc_constructor_first (expr->value.constructor);
1686   while (c)
1687     {
1688       gfc_init_se (&se, NULL);
1689       gfc_conv_constant (&se, c->expr);
1690       if (c->expr->ts.type != BT_CHARACTER)
1691         se.expr = fold_convert (type, se.expr);
1692       else if (POINTER_TYPE_P (type))
1693         se.expr = gfc_build_addr_expr (gfc_get_pchar_type (c->expr->ts.kind),
1694                                        se.expr);
1695       list = tree_cons (build_int_cst (gfc_array_index_type, nelem),
1696                         se.expr, list);
1697       c = gfc_constructor_next (c);
1698       nelem++;
1699     }
1700
1701   /* Next determine the tree type for the array.  We use the gfortran
1702      front-end's gfc_get_nodesc_array_type in order to create a suitable
1703      GFC_ARRAY_TYPE_P that may be used by the scalarizer.  */
1704
1705   memset (&as, 0, sizeof (gfc_array_spec));
1706
1707   as.rank = expr->rank;
1708   as.type = AS_EXPLICIT;
1709   if (!expr->shape)
1710     {
1711       as.lower[0] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 0);
1712       as.upper[0] = gfc_get_int_expr (gfc_default_integer_kind,
1713                                       NULL, nelem - 1);
1714     }
1715   else
1716     for (i = 0; i < expr->rank; i++)
1717       {
1718         int tmp = (int) mpz_get_si (expr->shape[i]);
1719         as.lower[i] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 0);
1720         as.upper[i] = gfc_get_int_expr (gfc_default_integer_kind,
1721                                         NULL, tmp - 1);
1722       }
1723
1724   tmptype = gfc_get_nodesc_array_type (type, &as, PACKED_STATIC, true);
1725
1726   init = build_constructor_from_list (tmptype, nreverse (list));
1727
1728   TREE_CONSTANT (init) = 1;
1729   TREE_STATIC (init) = 1;
1730
1731   tmp = gfc_create_var (tmptype, "A");
1732   TREE_STATIC (tmp) = 1;
1733   TREE_CONSTANT (tmp) = 1;
1734   TREE_READONLY (tmp) = 1;
1735   DECL_INITIAL (tmp) = init;
1736
1737   return tmp;
1738 }
1739
1740
1741 /* Translate a constant EXPR_ARRAY array constructor for the scalarizer.
1742    This mostly initializes the scalarizer state info structure with the
1743    appropriate values to directly use the array created by the function
1744    gfc_build_constant_array_constructor.  */
1745
1746 static void
1747 gfc_trans_constant_array_constructor (gfc_loopinfo * loop,
1748                                       gfc_ss * ss, tree type)
1749 {
1750   gfc_ss_info *info;
1751   tree tmp;
1752   int i;
1753
1754   tmp = gfc_build_constant_array_constructor (ss->expr, type);
1755
1756   info = &ss->data.info;
1757
1758   info->descriptor = tmp;
1759   info->data = gfc_build_addr_expr (NULL_TREE, tmp);
1760   info->offset = gfc_index_zero_node;
1761
1762   for (i = 0; i < info->dimen; i++)
1763     {
1764       info->delta[i] = gfc_index_zero_node;
1765       info->start[i] = gfc_index_zero_node;
1766       info->end[i] = gfc_index_zero_node;
1767       info->stride[i] = gfc_index_one_node;
1768       info->dim[i] = i;
1769     }
1770
1771   if (info->dimen > loop->temp_dim)
1772     loop->temp_dim = info->dimen;
1773 }
1774
1775 /* Helper routine of gfc_trans_array_constructor to determine if the
1776    bounds of the loop specified by LOOP are constant and simple enough
1777    to use with gfc_trans_constant_array_constructor.  Returns the
1778    iteration count of the loop if suitable, and NULL_TREE otherwise.  */
1779
1780 static tree
1781 constant_array_constructor_loop_size (gfc_loopinfo * loop)
1782 {
1783   tree size = gfc_index_one_node;
1784   tree tmp;
1785   int i;
1786
1787   for (i = 0; i < loop->dimen; i++)
1788     {
1789       /* If the bounds aren't constant, return NULL_TREE.  */
1790       if (!INTEGER_CST_P (loop->from[i]) || !INTEGER_CST_P (loop->to[i]))
1791         return NULL_TREE;
1792       if (!integer_zerop (loop->from[i]))
1793         {
1794           /* Only allow nonzero "from" in one-dimensional arrays.  */
1795           if (loop->dimen != 1)
1796             return NULL_TREE;
1797           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
1798                              loop->to[i], loop->from[i]);
1799         }
1800       else
1801         tmp = loop->to[i];
1802       tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
1803                          tmp, gfc_index_one_node);
1804       size = fold_build2 (MULT_EXPR, gfc_array_index_type, size, tmp);
1805     }
1806
1807   return size;
1808 }
1809
1810
1811 /* Array constructors are handled by constructing a temporary, then using that
1812    within the scalarization loop.  This is not optimal, but seems by far the
1813    simplest method.  */
1814
1815 static void
1816 gfc_trans_array_constructor (gfc_loopinfo * loop, gfc_ss * ss, locus * where)
1817 {
1818   gfc_constructor_base c;
1819   tree offset;
1820   tree offsetvar;
1821   tree desc;
1822   tree type;
1823   bool dynamic;
1824   bool old_first_len, old_typespec_chararray_ctor;
1825   tree old_first_len_val;
1826
1827   /* Save the old values for nested checking.  */
1828   old_first_len = first_len;
1829   old_first_len_val = first_len_val;
1830   old_typespec_chararray_ctor = typespec_chararray_ctor;
1831
1832   /* Do bounds-checking here and in gfc_trans_array_ctor_element only if no
1833      typespec was given for the array constructor.  */
1834   typespec_chararray_ctor = (ss->expr->ts.u.cl
1835                              && ss->expr->ts.u.cl->length_from_typespec);
1836
1837   if ((gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
1838       && ss->expr->ts.type == BT_CHARACTER && !typespec_chararray_ctor)
1839     {  
1840       first_len_val = gfc_create_var (gfc_charlen_type_node, "len");
1841       first_len = true;
1842     }
1843
1844   ss->data.info.dimen = loop->dimen;
1845
1846   c = ss->expr->value.constructor;
1847   if (ss->expr->ts.type == BT_CHARACTER)
1848     {
1849       bool const_string;
1850       
1851       /* get_array_ctor_strlen walks the elements of the constructor, if a
1852          typespec was given, we already know the string length and want the one
1853          specified there.  */
1854       if (typespec_chararray_ctor && ss->expr->ts.u.cl->length
1855           && ss->expr->ts.u.cl->length->expr_type != EXPR_CONSTANT)
1856         {
1857           gfc_se length_se;
1858
1859           const_string = false;
1860           gfc_init_se (&length_se, NULL);
1861           gfc_conv_expr_type (&length_se, ss->expr->ts.u.cl->length,
1862                               gfc_charlen_type_node);
1863           ss->string_length = length_se.expr;
1864           gfc_add_block_to_block (&loop->pre, &length_se.pre);
1865           gfc_add_block_to_block (&loop->post, &length_se.post);
1866         }
1867       else
1868         const_string = get_array_ctor_strlen (&loop->pre, c,
1869                                               &ss->string_length);
1870
1871       /* Complex character array constructors should have been taken care of
1872          and not end up here.  */
1873       gcc_assert (ss->string_length);
1874
1875       ss->expr->ts.u.cl->backend_decl = ss->string_length;
1876
1877       type = gfc_get_character_type_len (ss->expr->ts.kind, ss->string_length);
1878       if (const_string)
1879         type = build_pointer_type (type);
1880     }
1881   else
1882     type = gfc_typenode_for_spec (&ss->expr->ts);
1883
1884   /* See if the constructor determines the loop bounds.  */
1885   dynamic = false;
1886
1887   if (ss->expr->shape && loop->dimen > 1 && loop->to[0] == NULL_TREE)
1888     {
1889       /* We have a multidimensional parameter.  */
1890       int n;
1891       for (n = 0; n < ss->expr->rank; n++)
1892       {
1893         loop->from[n] = gfc_index_zero_node;
1894         loop->to[n] = gfc_conv_mpz_to_tree (ss->expr->shape [n],
1895                                             gfc_index_integer_kind);
1896         loop->to[n] = fold_build2 (MINUS_EXPR, gfc_array_index_type,
1897                                    loop->to[n], gfc_index_one_node);
1898       }
1899     }
1900
1901   if (loop->to[0] == NULL_TREE)
1902     {
1903       mpz_t size;
1904
1905       /* We should have a 1-dimensional, zero-based loop.  */
1906       gcc_assert (loop->dimen == 1);
1907       gcc_assert (integer_zerop (loop->from[0]));
1908
1909       /* Split the constructor size into a static part and a dynamic part.
1910          Allocate the static size up-front and record whether the dynamic
1911          size might be nonzero.  */
1912       mpz_init (size);
1913       dynamic = gfc_get_array_constructor_size (&size, c);
1914       mpz_sub_ui (size, size, 1);
1915       loop->to[0] = gfc_conv_mpz_to_tree (size, gfc_index_integer_kind);
1916       mpz_clear (size);
1917     }
1918
1919   /* Special case constant array constructors.  */
1920   if (!dynamic)
1921     {
1922       unsigned HOST_WIDE_INT nelem = gfc_constant_array_constructor_p (c);
1923       if (nelem > 0)
1924         {
1925           tree size = constant_array_constructor_loop_size (loop);
1926           if (size && compare_tree_int (size, nelem) == 0)
1927             {
1928               gfc_trans_constant_array_constructor (loop, ss, type);
1929               goto finish;
1930             }
1931         }
1932     }
1933
1934   gfc_trans_create_temp_array (&loop->pre, &loop->post, loop, &ss->data.info,
1935                                type, NULL_TREE, dynamic, true, false, where);
1936
1937   desc = ss->data.info.descriptor;
1938   offset = gfc_index_zero_node;
1939   offsetvar = gfc_create_var_np (gfc_array_index_type, "offset");
1940   TREE_NO_WARNING (offsetvar) = 1;
1941   TREE_USED (offsetvar) = 0;
1942   gfc_trans_array_constructor_value (&loop->pre, type, desc, c,
1943                                      &offset, &offsetvar, dynamic);
1944
1945   /* If the array grows dynamically, the upper bound of the loop variable
1946      is determined by the array's final upper bound.  */
1947   if (dynamic)
1948     loop->to[0] = gfc_conv_descriptor_ubound_get (desc, gfc_rank_cst[0]);
1949
1950   if (TREE_USED (offsetvar))
1951     pushdecl (offsetvar);
1952   else
1953     gcc_assert (INTEGER_CST_P (offset));
1954 #if 0
1955   /* Disable bound checking for now because it's probably broken.  */
1956   if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
1957     {
1958       gcc_unreachable ();
1959     }
1960 #endif
1961
1962 finish:
1963   /* Restore old values of globals.  */
1964   first_len = old_first_len;
1965   first_len_val = old_first_len_val;
1966   typespec_chararray_ctor = old_typespec_chararray_ctor;
1967 }
1968
1969
1970 /* INFO describes a GFC_SS_SECTION in loop LOOP, and this function is
1971    called after evaluating all of INFO's vector dimensions.  Go through
1972    each such vector dimension and see if we can now fill in any missing
1973    loop bounds.  */
1974
1975 static void
1976 gfc_set_vector_loop_bounds (gfc_loopinfo * loop, gfc_ss_info * info)
1977 {
1978   gfc_se se;
1979   tree tmp;
1980   tree desc;
1981   tree zero;
1982   int n;
1983   int dim;
1984
1985   for (n = 0; n < loop->dimen; n++)
1986     {
1987       dim = info->dim[n];
1988       if (info->ref->u.ar.dimen_type[dim] == DIMEN_VECTOR
1989           && loop->to[n] == NULL)
1990         {
1991           /* Loop variable N indexes vector dimension DIM, and we don't
1992              yet know the upper bound of loop variable N.  Set it to the
1993              difference between the vector's upper and lower bounds.  */
1994           gcc_assert (loop->from[n] == gfc_index_zero_node);
1995           gcc_assert (info->subscript[dim]
1996                       && info->subscript[dim]->type == GFC_SS_VECTOR);
1997
1998           gfc_init_se (&se, NULL);
1999           desc = info->subscript[dim]->data.info.descriptor;
2000           zero = gfc_rank_cst[0];
2001           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
2002                              gfc_conv_descriptor_ubound_get (desc, zero),
2003                              gfc_conv_descriptor_lbound_get (desc, zero));
2004           tmp = gfc_evaluate_now (tmp, &loop->pre);
2005           loop->to[n] = tmp;
2006         }
2007     }
2008 }
2009
2010
2011 /* Add the pre and post chains for all the scalar expressions in a SS chain
2012    to loop.  This is called after the loop parameters have been calculated,
2013    but before the actual scalarizing loops.  */
2014
2015 static void
2016 gfc_add_loop_ss_code (gfc_loopinfo * loop, gfc_ss * ss, bool subscript,
2017                       locus * where)
2018 {
2019   gfc_se se;
2020   int n;
2021
2022   /* TODO: This can generate bad code if there are ordering dependencies,
2023      e.g., a callee allocated function and an unknown size constructor.  */
2024   gcc_assert (ss != NULL);
2025
2026   for (; ss != gfc_ss_terminator; ss = ss->loop_chain)
2027     {
2028       gcc_assert (ss);
2029
2030       switch (ss->type)
2031         {
2032         case GFC_SS_SCALAR:
2033           /* Scalar expression.  Evaluate this now.  This includes elemental
2034              dimension indices, but not array section bounds.  */
2035           gfc_init_se (&se, NULL);
2036           gfc_conv_expr (&se, ss->expr);
2037           gfc_add_block_to_block (&loop->pre, &se.pre);
2038
2039           if (ss->expr->ts.type != BT_CHARACTER)
2040             {
2041               /* Move the evaluation of scalar expressions outside the
2042                  scalarization loop, except for WHERE assignments.  */
2043               if (subscript)
2044                 se.expr = convert(gfc_array_index_type, se.expr);
2045               if (!ss->where)
2046                 se.expr = gfc_evaluate_now (se.expr, &loop->pre);
2047               gfc_add_block_to_block (&loop->pre, &se.post);
2048             }
2049           else
2050             gfc_add_block_to_block (&loop->post, &se.post);
2051
2052           ss->data.scalar.expr = se.expr;
2053           ss->string_length = se.string_length;
2054           break;
2055
2056         case GFC_SS_REFERENCE:
2057           /* Scalar reference.  Evaluate this now.  */
2058           gfc_init_se (&se, NULL);
2059           gfc_conv_expr_reference (&se, ss->expr);
2060           gfc_add_block_to_block (&loop->pre, &se.pre);
2061           gfc_add_block_to_block (&loop->post, &se.post);
2062
2063           ss->data.scalar.expr = gfc_evaluate_now (se.expr, &loop->pre);
2064           ss->string_length = se.string_length;
2065           break;
2066
2067         case GFC_SS_SECTION:
2068           /* Add the expressions for scalar and vector subscripts.  */
2069           for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
2070             if (ss->data.info.subscript[n])
2071               gfc_add_loop_ss_code (loop, ss->data.info.subscript[n], true,
2072                                     where);
2073
2074           gfc_set_vector_loop_bounds (loop, &ss->data.info);
2075           break;
2076
2077         case GFC_SS_VECTOR:
2078           /* Get the vector's descriptor and store it in SS.  */
2079           gfc_init_se (&se, NULL);
2080           gfc_conv_expr_descriptor (&se, ss->expr, gfc_walk_expr (ss->expr));
2081           gfc_add_block_to_block (&loop->pre, &se.pre);
2082           gfc_add_block_to_block (&loop->post, &se.post);
2083           ss->data.info.descriptor = se.expr;
2084           break;
2085
2086         case GFC_SS_INTRINSIC:
2087           gfc_add_intrinsic_ss_code (loop, ss);
2088           break;
2089
2090         case GFC_SS_FUNCTION:
2091           /* Array function return value.  We call the function and save its
2092              result in a temporary for use inside the loop.  */
2093           gfc_init_se (&se, NULL);
2094           se.loop = loop;
2095           se.ss = ss;
2096           gfc_conv_expr (&se, ss->expr);
2097           gfc_add_block_to_block (&loop->pre, &se.pre);
2098           gfc_add_block_to_block (&loop->post, &se.post);
2099           ss->string_length = se.string_length;
2100           break;
2101
2102         case GFC_SS_CONSTRUCTOR:
2103           if (ss->expr->ts.type == BT_CHARACTER
2104                 && ss->string_length == NULL
2105                 && ss->expr->ts.u.cl
2106                 && ss->expr->ts.u.cl->length)
2107             {
2108               gfc_init_se (&se, NULL);
2109               gfc_conv_expr_type (&se, ss->expr->ts.u.cl->length,
2110                                   gfc_charlen_type_node);
2111               ss->string_length = se.expr;
2112               gfc_add_block_to_block (&loop->pre, &se.pre);
2113               gfc_add_block_to_block (&loop->post, &se.post);
2114             }
2115           gfc_trans_array_constructor (loop, ss, where);
2116           break;
2117
2118         case GFC_SS_TEMP:
2119         case GFC_SS_COMPONENT:
2120           /* Do nothing.  These are handled elsewhere.  */
2121           break;
2122
2123         default:
2124           gcc_unreachable ();
2125         }
2126     }
2127 }
2128
2129
2130 /* Translate expressions for the descriptor and data pointer of a SS.  */
2131 /*GCC ARRAYS*/
2132
2133 static void
2134 gfc_conv_ss_descriptor (stmtblock_t * block, gfc_ss * ss, int base)
2135 {
2136   gfc_se se;
2137   tree tmp;
2138
2139   /* Get the descriptor for the array to be scalarized.  */
2140   gcc_assert (ss->expr->expr_type == EXPR_VARIABLE);
2141   gfc_init_se (&se, NULL);
2142   se.descriptor_only = 1;
2143   gfc_conv_expr_lhs (&se, ss->expr);
2144   gfc_add_block_to_block (block, &se.pre);
2145   ss->data.info.descriptor = se.expr;
2146   ss->string_length = se.string_length;
2147
2148   if (base)
2149     {
2150       /* Also the data pointer.  */
2151       tmp = gfc_conv_array_data (se.expr);
2152       /* If this is a variable or address of a variable we use it directly.
2153          Otherwise we must evaluate it now to avoid breaking dependency
2154          analysis by pulling the expressions for elemental array indices
2155          inside the loop.  */
2156       if (!(DECL_P (tmp)
2157             || (TREE_CODE (tmp) == ADDR_EXPR
2158                 && DECL_P (TREE_OPERAND (tmp, 0)))))
2159         tmp = gfc_evaluate_now (tmp, block);
2160       ss->data.info.data = tmp;
2161
2162       tmp = gfc_conv_array_offset (se.expr);
2163       ss->data.info.offset = gfc_evaluate_now (tmp, block);
2164     }
2165 }
2166
2167
2168 /* Initialize a gfc_loopinfo structure.  */
2169
2170 void
2171 gfc_init_loopinfo (gfc_loopinfo * loop)
2172 {
2173   int n;
2174
2175   memset (loop, 0, sizeof (gfc_loopinfo));
2176   gfc_init_block (&loop->pre);
2177   gfc_init_block (&loop->post);
2178
2179   /* Initially scalarize in order.  */
2180   for (n = 0; n < GFC_MAX_DIMENSIONS; n++)
2181     loop->order[n] = n;
2182
2183   loop->ss = gfc_ss_terminator;
2184 }
2185
2186
2187 /* Copies the loop variable info to a gfc_se structure. Does not copy the SS
2188    chain.  */
2189
2190 void
2191 gfc_copy_loopinfo_to_se (gfc_se * se, gfc_loopinfo * loop)
2192 {
2193   se->loop = loop;
2194 }
2195
2196
2197 /* Return an expression for the data pointer of an array.  */
2198
2199 tree
2200 gfc_conv_array_data (tree descriptor)
2201 {
2202   tree type;
2203
2204   type = TREE_TYPE (descriptor);
2205   if (GFC_ARRAY_TYPE_P (type))
2206     {
2207       if (TREE_CODE (type) == POINTER_TYPE)
2208         return descriptor;
2209       else
2210         {
2211           /* Descriptorless arrays.  */
2212           return gfc_build_addr_expr (NULL_TREE, descriptor);
2213         }
2214     }
2215   else
2216     return gfc_conv_descriptor_data_get (descriptor);
2217 }
2218
2219
2220 /* Return an expression for the base offset of an array.  */
2221
2222 tree
2223 gfc_conv_array_offset (tree descriptor)
2224 {
2225   tree type;
2226
2227   type = TREE_TYPE (descriptor);
2228   if (GFC_ARRAY_TYPE_P (type))
2229     return GFC_TYPE_ARRAY_OFFSET (type);
2230   else
2231     return gfc_conv_descriptor_offset_get (descriptor);
2232 }
2233
2234
2235 /* Get an expression for the array stride.  */
2236
2237 tree
2238 gfc_conv_array_stride (tree descriptor, int dim)
2239 {
2240   tree tmp;
2241   tree type;
2242
2243   type = TREE_TYPE (descriptor);
2244
2245   /* For descriptorless arrays use the array size.  */
2246   tmp = GFC_TYPE_ARRAY_STRIDE (type, dim);
2247   if (tmp != NULL_TREE)
2248     return tmp;
2249
2250   tmp = gfc_conv_descriptor_stride_get (descriptor, gfc_rank_cst[dim]);
2251   return tmp;
2252 }
2253
2254
2255 /* Like gfc_conv_array_stride, but for the lower bound.  */
2256
2257 tree
2258 gfc_conv_array_lbound (tree descriptor, int dim)
2259 {
2260   tree tmp;
2261   tree type;
2262
2263   type = TREE_TYPE (descriptor);
2264
2265   tmp = GFC_TYPE_ARRAY_LBOUND (type, dim);
2266   if (tmp != NULL_TREE)
2267     return tmp;
2268
2269   tmp = gfc_conv_descriptor_lbound_get (descriptor, gfc_rank_cst[dim]);
2270   return tmp;
2271 }
2272
2273
2274 /* Like gfc_conv_array_stride, but for the upper bound.  */
2275
2276 tree
2277 gfc_conv_array_ubound (tree descriptor, int dim)
2278 {
2279   tree tmp;
2280   tree type;
2281
2282   type = TREE_TYPE (descriptor);
2283
2284   tmp = GFC_TYPE_ARRAY_UBOUND (type, dim);
2285   if (tmp != NULL_TREE)
2286     return tmp;
2287
2288   /* This should only ever happen when passing an assumed shape array
2289      as an actual parameter.  The value will never be used.  */
2290   if (GFC_ARRAY_TYPE_P (TREE_TYPE (descriptor)))
2291     return gfc_index_zero_node;
2292
2293   tmp = gfc_conv_descriptor_ubound_get (descriptor, gfc_rank_cst[dim]);
2294   return tmp;
2295 }
2296
2297
2298 /* Generate code to perform an array index bound check.  */
2299
2300 static tree
2301 gfc_trans_array_bound_check (gfc_se * se, tree descriptor, tree index, int n,
2302                              locus * where, bool check_upper)
2303 {
2304   tree fault;
2305   tree tmp_lo, tmp_up;
2306   char *msg;
2307   const char * name = NULL;
2308
2309   if (!(gfc_option.rtcheck & GFC_RTCHECK_BOUNDS))
2310     return index;
2311
2312   index = gfc_evaluate_now (index, &se->pre);
2313
2314   /* We find a name for the error message.  */
2315   if (se->ss)
2316     name = se->ss->expr->symtree->name;
2317
2318   if (!name && se->loop && se->loop->ss && se->loop->ss->expr
2319       && se->loop->ss->expr->symtree)
2320     name = se->loop->ss->expr->symtree->name;
2321
2322   if (!name && se->loop && se->loop->ss && se->loop->ss->loop_chain
2323       && se->loop->ss->loop_chain->expr
2324       && se->loop->ss->loop_chain->expr->symtree)
2325     name = se->loop->ss->loop_chain->expr->symtree->name;
2326
2327   if (!name && se->loop && se->loop->ss && se->loop->ss->loop_chain
2328       && se->loop->ss->loop_chain->expr->symtree)
2329     name = se->loop->ss->loop_chain->expr->symtree->name;
2330
2331   if (!name && se->loop && se->loop->ss && se->loop->ss->expr)
2332     {
2333       if (se->loop->ss->expr->expr_type == EXPR_FUNCTION
2334           && se->loop->ss->expr->value.function.name)
2335         name = se->loop->ss->expr->value.function.name;
2336       else
2337         if (se->loop->ss->type == GFC_SS_CONSTRUCTOR
2338             || se->loop->ss->type == GFC_SS_SCALAR)
2339           name = "unnamed constant";
2340     }
2341
2342   /* If upper bound is present, include both bounds in the error message.  */
2343   if (check_upper)
2344     {
2345       tmp_lo = gfc_conv_array_lbound (descriptor, n);
2346       tmp_up = gfc_conv_array_ubound (descriptor, n);
2347
2348       if (name)
2349         asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
2350                   "outside of expected range (%%ld:%%ld)", n+1, name);
2351       else
2352         asprintf (&msg, "Index '%%ld' of dimension %d "
2353                   "outside of expected range (%%ld:%%ld)", n+1);
2354
2355       fault = fold_build2 (LT_EXPR, boolean_type_node, index, tmp_lo);
2356       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2357                                fold_convert (long_integer_type_node, index),
2358                                fold_convert (long_integer_type_node, tmp_lo),
2359                                fold_convert (long_integer_type_node, tmp_up));
2360       fault = fold_build2 (GT_EXPR, boolean_type_node, index, tmp_up);
2361       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2362                                fold_convert (long_integer_type_node, index),
2363                                fold_convert (long_integer_type_node, tmp_lo),
2364                                fold_convert (long_integer_type_node, tmp_up));
2365       gfc_free (msg);
2366     }
2367   else
2368     {
2369       tmp_lo = gfc_conv_array_lbound (descriptor, n);
2370
2371       if (name)
2372         asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
2373                   "below lower bound of %%ld", n+1, name);
2374       else
2375         asprintf (&msg, "Index '%%ld' of dimension %d "
2376                   "below lower bound of %%ld", n+1);
2377
2378       fault = fold_build2 (LT_EXPR, boolean_type_node, index, tmp_lo);
2379       gfc_trans_runtime_check (true, false, fault, &se->pre, where, msg,
2380                                fold_convert (long_integer_type_node, index),
2381                                fold_convert (long_integer_type_node, tmp_lo));
2382       gfc_free (msg);
2383     }
2384
2385   return index;
2386 }
2387
2388
2389 /* Return the offset for an index.  Performs bound checking for elemental
2390    dimensions.  Single element references are processed separately.  */
2391
2392 static tree
2393 gfc_conv_array_index_offset (gfc_se * se, gfc_ss_info * info, int dim, int i,
2394                              gfc_array_ref * ar, tree stride)
2395 {
2396   tree index;
2397   tree desc;
2398   tree data;
2399
2400   /* Get the index into the array for this dimension.  */
2401   if (ar)
2402     {
2403       gcc_assert (ar->type != AR_ELEMENT);
2404       switch (ar->dimen_type[dim])
2405         {
2406         case DIMEN_ELEMENT:
2407           /* Elemental dimension.  */
2408           gcc_assert (info->subscript[dim]
2409                       && info->subscript[dim]->type == GFC_SS_SCALAR);
2410           /* We've already translated this value outside the loop.  */
2411           index = info->subscript[dim]->data.scalar.expr;
2412
2413           index = gfc_trans_array_bound_check (se, info->descriptor,
2414                         index, dim, &ar->where,
2415                         ar->as->type != AS_ASSUMED_SIZE
2416                         || dim < ar->dimen - 1);
2417           break;
2418
2419         case DIMEN_VECTOR:
2420           gcc_assert (info && se->loop);
2421           gcc_assert (info->subscript[dim]
2422                       && info->subscript[dim]->type == GFC_SS_VECTOR);
2423           desc = info->subscript[dim]->data.info.descriptor;
2424
2425           /* Get a zero-based index into the vector.  */
2426           index = fold_build2 (MINUS_EXPR, gfc_array_index_type,
2427                                se->loop->loopvar[i], se->loop->from[i]);
2428
2429           /* Multiply the index by the stride.  */
2430           index = fold_build2 (MULT_EXPR, gfc_array_index_type,
2431                                index, gfc_conv_array_stride (desc, 0));
2432
2433           /* Read the vector to get an index into info->descriptor.  */
2434           data = build_fold_indirect_ref_loc (input_location,
2435                                           gfc_conv_array_data (desc));
2436           index = gfc_build_array_ref (data, index, NULL);
2437           index = gfc_evaluate_now (index, &se->pre);
2438
2439           /* Do any bounds checking on the final info->descriptor index.  */
2440           index = gfc_trans_array_bound_check (se, info->descriptor,
2441                         index, dim, &ar->where,
2442                         ar->as->type != AS_ASSUMED_SIZE
2443                         || dim < ar->dimen - 1);
2444           break;
2445
2446         case DIMEN_RANGE:
2447           /* Scalarized dimension.  */
2448           gcc_assert (info && se->loop);
2449
2450           /* Multiply the loop variable by the stride and delta.  */
2451           index = se->loop->loopvar[i];
2452           if (!integer_onep (info->stride[i]))
2453             index = fold_build2 (MULT_EXPR, gfc_array_index_type, index,
2454                                  info->stride[i]);
2455           if (!integer_zerop (info->delta[i]))
2456             index = fold_build2 (PLUS_EXPR, gfc_array_index_type, index,
2457                                  info->delta[i]);
2458           break;
2459
2460         default:
2461           gcc_unreachable ();
2462         }
2463     }
2464   else
2465     {
2466       /* Temporary array or derived type component.  */
2467       gcc_assert (se->loop);
2468       index = se->loop->loopvar[se->loop->order[i]];
2469       if (!integer_zerop (info->delta[i]))
2470         index = fold_build2 (PLUS_EXPR, gfc_array_index_type,
2471                              index, info->delta[i]);
2472     }
2473
2474   /* Multiply by the stride.  */
2475   if (!integer_onep (stride))
2476     index = fold_build2 (MULT_EXPR, gfc_array_index_type, index, stride);
2477
2478   return index;
2479 }
2480
2481
2482 /* Build a scalarized reference to an array.  */
2483
2484 static void
2485 gfc_conv_scalarized_array_ref (gfc_se * se, gfc_array_ref * ar)
2486 {
2487   gfc_ss_info *info;
2488   tree decl = NULL_TREE;
2489   tree index;
2490   tree tmp;
2491   int n;
2492
2493   info = &se->ss->data.info;
2494   if (ar)
2495     n = se->loop->order[0];
2496   else
2497     n = 0;
2498
2499   index = gfc_conv_array_index_offset (se, info, info->dim[n], n, ar,
2500                                        info->stride0);
2501   /* Add the offset for this dimension to the stored offset for all other
2502      dimensions.  */
2503   if (!integer_zerop (info->offset))
2504     index = fold_build2 (PLUS_EXPR, gfc_array_index_type, index, info->offset);
2505
2506   if (se->ss->expr && is_subref_array (se->ss->expr))
2507     decl = se->ss->expr->symtree->n.sym->backend_decl;
2508
2509   tmp = build_fold_indirect_ref_loc (input_location,
2510                                  info->data);
2511   se->expr = gfc_build_array_ref (tmp, index, decl);
2512 }
2513
2514
2515 /* Translate access of temporary array.  */
2516
2517 void
2518 gfc_conv_tmp_array_ref (gfc_se * se)
2519 {
2520   se->string_length = se->ss->string_length;
2521   gfc_conv_scalarized_array_ref (se, NULL);
2522 }
2523
2524
2525 /* Build an array reference.  se->expr already holds the array descriptor.
2526    This should be either a variable, indirect variable reference or component
2527    reference.  For arrays which do not have a descriptor, se->expr will be
2528    the data pointer.
2529    a(i, j, k) = base[offset + i * stride[0] + j * stride[1] + k * stride[2]]*/
2530
2531 void
2532 gfc_conv_array_ref (gfc_se * se, gfc_array_ref * ar, gfc_symbol * sym,
2533                     locus * where)
2534 {
2535   int n;
2536   tree index;
2537   tree tmp;
2538   tree stride;
2539   gfc_se indexse;
2540   gfc_se tmpse;
2541
2542   if (ar->dimen == 0)
2543     return;
2544
2545   /* Handle scalarized references separately.  */
2546   if (ar->type != AR_ELEMENT)
2547     {
2548       gfc_conv_scalarized_array_ref (se, ar);
2549       gfc_advance_se_ss_chain (se);
2550       return;
2551     }
2552
2553   index = gfc_index_zero_node;
2554
2555   /* Calculate the offsets from all the dimensions.  */
2556   for (n = 0; n < ar->dimen; n++)
2557     {
2558       /* Calculate the index for this dimension.  */
2559       gfc_init_se (&indexse, se);
2560       gfc_conv_expr_type (&indexse, ar->start[n], gfc_array_index_type);
2561       gfc_add_block_to_block (&se->pre, &indexse.pre);
2562
2563       if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
2564         {
2565           /* Check array bounds.  */
2566           tree cond;
2567           char *msg;
2568
2569           /* Evaluate the indexse.expr only once.  */
2570           indexse.expr = save_expr (indexse.expr);
2571
2572           /* Lower bound.  */
2573           tmp = gfc_conv_array_lbound (se->expr, n);
2574           if (sym->attr.temporary)
2575             {
2576               gfc_init_se (&tmpse, se);
2577               gfc_conv_expr_type (&tmpse, ar->as->lower[n],
2578                                   gfc_array_index_type);
2579               gfc_add_block_to_block (&se->pre, &tmpse.pre);
2580               tmp = tmpse.expr;
2581             }
2582
2583           cond = fold_build2 (LT_EXPR, boolean_type_node, 
2584                               indexse.expr, tmp);
2585           asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
2586                     "below lower bound of %%ld", n+1, sym->name);
2587           gfc_trans_runtime_check (true, false, cond, &se->pre, where, msg,
2588                                    fold_convert (long_integer_type_node,
2589                                                  indexse.expr),
2590                                    fold_convert (long_integer_type_node, tmp));
2591           gfc_free (msg);
2592
2593           /* Upper bound, but not for the last dimension of assumed-size
2594              arrays.  */
2595           if (n < ar->dimen - 1 || ar->as->type != AS_ASSUMED_SIZE)
2596             {
2597               tmp = gfc_conv_array_ubound (se->expr, n);
2598               if (sym->attr.temporary)
2599                 {
2600                   gfc_init_se (&tmpse, se);
2601                   gfc_conv_expr_type (&tmpse, ar->as->upper[n],
2602                                       gfc_array_index_type);
2603                   gfc_add_block_to_block (&se->pre, &tmpse.pre);
2604                   tmp = tmpse.expr;
2605                 }
2606
2607               cond = fold_build2 (GT_EXPR, boolean_type_node, 
2608                                   indexse.expr, tmp);
2609               asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
2610                         "above upper bound of %%ld", n+1, sym->name);
2611               gfc_trans_runtime_check (true, false, cond, &se->pre, where, msg,
2612                                    fold_convert (long_integer_type_node,
2613                                                  indexse.expr),
2614                                    fold_convert (long_integer_type_node, tmp));
2615               gfc_free (msg);
2616             }
2617         }
2618
2619       /* Multiply the index by the stride.  */
2620       stride = gfc_conv_array_stride (se->expr, n);
2621       tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, indexse.expr,
2622                          stride);
2623
2624       /* And add it to the total.  */
2625       index = fold_build2 (PLUS_EXPR, gfc_array_index_type, index, tmp);
2626     }
2627
2628   tmp = gfc_conv_array_offset (se->expr);
2629   if (!integer_zerop (tmp))
2630     index = fold_build2 (PLUS_EXPR, gfc_array_index_type, index, tmp);
2631
2632   /* Access the calculated element.  */
2633   tmp = gfc_conv_array_data (se->expr);
2634   tmp = build_fold_indirect_ref (tmp);
2635   se->expr = gfc_build_array_ref (tmp, index, sym->backend_decl);
2636 }
2637
2638
2639 /* Generate the code to be executed immediately before entering a
2640    scalarization loop.  */
2641
2642 static void
2643 gfc_trans_preloop_setup (gfc_loopinfo * loop, int dim, int flag,
2644                          stmtblock_t * pblock)
2645 {
2646   tree index;
2647   tree stride;
2648   gfc_ss_info *info;
2649   gfc_ss *ss;
2650   gfc_se se;
2651   int i;
2652
2653   /* This code will be executed before entering the scalarization loop
2654      for this dimension.  */
2655   for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
2656     {
2657       if ((ss->useflags & flag) == 0)
2658         continue;
2659
2660       if (ss->type != GFC_SS_SECTION
2661           && ss->type != GFC_SS_FUNCTION && ss->type != GFC_SS_CONSTRUCTOR
2662           && ss->type != GFC_SS_COMPONENT)
2663         continue;
2664
2665       info = &ss->data.info;
2666
2667       if (dim >= info->dimen)
2668         continue;
2669
2670       if (dim == info->dimen - 1)
2671         {
2672           /* For the outermost loop calculate the offset due to any
2673              elemental dimensions.  It will have been initialized with the
2674              base offset of the array.  */
2675           if (info->ref)
2676             {
2677               for (i = 0; i < info->ref->u.ar.dimen; i++)
2678                 {
2679                   if (info->ref->u.ar.dimen_type[i] != DIMEN_ELEMENT)
2680                     continue;
2681
2682                   gfc_init_se (&se, NULL);
2683                   se.loop = loop;
2684                   se.expr = info->descriptor;
2685                   stride = gfc_conv_array_stride (info->descriptor, i);
2686                   index = gfc_conv_array_index_offset (&se, info, i, -1,
2687                                                        &info->ref->u.ar,
2688                                                        stride);
2689                   gfc_add_block_to_block (pblock, &se.pre);
2690
2691                   info->offset = fold_build2 (PLUS_EXPR, gfc_array_index_type,
2692                                               info->offset, index);
2693                   info->offset = gfc_evaluate_now (info->offset, pblock);
2694                 }
2695
2696               i = loop->order[0];
2697               stride = gfc_conv_array_stride (info->descriptor, info->dim[i]);
2698             }
2699           else
2700             stride = gfc_conv_array_stride (info->descriptor, 0);
2701
2702           /* Calculate the stride of the innermost loop.  Hopefully this will
2703              allow the backend optimizers to do their stuff more effectively.
2704            */
2705           info->stride0 = gfc_evaluate_now (stride, pblock);
2706         }
2707       else
2708         {
2709           /* Add the offset for the previous loop dimension.  */
2710           gfc_array_ref *ar;
2711
2712           if (info->ref)
2713             {
2714               ar = &info->ref->u.ar;
2715               i = loop->order[dim + 1];
2716             }
2717           else
2718             {
2719               ar = NULL;
2720               i = dim + 1;
2721             }
2722
2723           gfc_init_se (&se, NULL);
2724           se.loop = loop;
2725           se.expr = info->descriptor;
2726           stride = gfc_conv_array_stride (info->descriptor, info->dim[i]);
2727           index = gfc_conv_array_index_offset (&se, info, info->dim[i], i,
2728                                                ar, stride);
2729           gfc_add_block_to_block (pblock, &se.pre);
2730           info->offset = fold_build2 (PLUS_EXPR, gfc_array_index_type,
2731                                       info->offset, index);
2732           info->offset = gfc_evaluate_now (info->offset, pblock);
2733         }
2734
2735       /* Remember this offset for the second loop.  */
2736       if (dim == loop->temp_dim - 1)
2737         info->saved_offset = info->offset;
2738     }
2739 }
2740
2741
2742 /* Start a scalarized expression.  Creates a scope and declares loop
2743    variables.  */
2744
2745 void
2746 gfc_start_scalarized_body (gfc_loopinfo * loop, stmtblock_t * pbody)
2747 {
2748   int dim;
2749   int n;
2750   int flags;
2751
2752   gcc_assert (!loop->array_parameter);
2753
2754   for (dim = loop->dimen - 1; dim >= 0; dim--)
2755     {
2756       n = loop->order[dim];
2757
2758       gfc_start_block (&loop->code[n]);
2759
2760       /* Create the loop variable.  */
2761       loop->loopvar[n] = gfc_create_var (gfc_array_index_type, "S");
2762
2763       if (dim < loop->temp_dim)
2764         flags = 3;
2765       else
2766         flags = 1;
2767       /* Calculate values that will be constant within this loop.  */
2768       gfc_trans_preloop_setup (loop, dim, flags, &loop->code[n]);
2769     }
2770   gfc_start_block (pbody);
2771 }
2772
2773
2774 /* Generates the actual loop code for a scalarization loop.  */
2775
2776 void
2777 gfc_trans_scalarized_loop_end (gfc_loopinfo * loop, int n,
2778                                stmtblock_t * pbody)
2779 {
2780   stmtblock_t block;
2781   tree cond;
2782   tree tmp;
2783   tree loopbody;
2784   tree exit_label;
2785   tree stmt;
2786   tree init;
2787   tree incr;
2788
2789   if ((ompws_flags & (OMPWS_WORKSHARE_FLAG | OMPWS_SCALARIZER_WS))
2790       == (OMPWS_WORKSHARE_FLAG | OMPWS_SCALARIZER_WS)
2791       && n == loop->dimen - 1)
2792     {
2793       /* We create an OMP_FOR construct for the outermost scalarized loop.  */
2794       init = make_tree_vec (1);
2795       cond = make_tree_vec (1);
2796       incr = make_tree_vec (1);
2797
2798       /* Cycle statement is implemented with a goto.  Exit statement must not
2799          be present for this loop.  */
2800       exit_label = gfc_build_label_decl (NULL_TREE);
2801       TREE_USED (exit_label) = 1;
2802
2803       /* Label for cycle statements (if needed).  */
2804       tmp = build1_v (LABEL_EXPR, exit_label);
2805       gfc_add_expr_to_block (pbody, tmp);
2806
2807       stmt = make_node (OMP_FOR);
2808
2809       TREE_TYPE (stmt) = void_type_node;
2810       OMP_FOR_BODY (stmt) = loopbody = gfc_finish_block (pbody);
2811
2812       OMP_FOR_CLAUSES (stmt) = build_omp_clause (input_location,
2813                                                  OMP_CLAUSE_SCHEDULE);
2814       OMP_CLAUSE_SCHEDULE_KIND (OMP_FOR_CLAUSES (stmt))
2815         = OMP_CLAUSE_SCHEDULE_STATIC;
2816       if (ompws_flags & OMPWS_NOWAIT)
2817         OMP_CLAUSE_CHAIN (OMP_FOR_CLAUSES (stmt))
2818           = build_omp_clause (input_location, OMP_CLAUSE_NOWAIT);
2819
2820       /* Initialize the loopvar.  */
2821       TREE_VEC_ELT (init, 0) = build2_v (MODIFY_EXPR, loop->loopvar[n],
2822                                          loop->from[n]);
2823       OMP_FOR_INIT (stmt) = init;
2824       /* The exit condition.  */
2825       TREE_VEC_ELT (cond, 0) = build2 (LE_EXPR, boolean_type_node,
2826                                        loop->loopvar[n], loop->to[n]);
2827       OMP_FOR_COND (stmt) = cond;
2828       /* Increment the loopvar.  */
2829       tmp = build2 (PLUS_EXPR, gfc_array_index_type,
2830           loop->loopvar[n], gfc_index_one_node);
2831       TREE_VEC_ELT (incr, 0) = fold_build2 (MODIFY_EXPR,
2832           void_type_node, loop->loopvar[n], tmp);
2833       OMP_FOR_INCR (stmt) = incr;
2834
2835       ompws_flags &= ~OMPWS_CURR_SINGLEUNIT;
2836       gfc_add_expr_to_block (&loop->code[n], stmt);
2837     }
2838   else
2839     {
2840       loopbody = gfc_finish_block (pbody);
2841
2842       /* Initialize the loopvar.  */
2843       if (loop->loopvar[n] != loop->from[n])
2844         gfc_add_modify (&loop->code[n], loop->loopvar[n], loop->from[n]);
2845
2846       exit_label = gfc_build_label_decl (NULL_TREE);
2847
2848       /* Generate the loop body.  */
2849       gfc_init_block (&block);
2850
2851       /* The exit condition.  */
2852       cond = fold_build2 (GT_EXPR, boolean_type_node,
2853                          loop->loopvar[n], loop->to[n]);
2854       tmp = build1_v (GOTO_EXPR, exit_label);
2855       TREE_USED (exit_label) = 1;
2856       tmp = build3_v (COND_EXPR, cond, tmp, build_empty_stmt (input_location));
2857       gfc_add_expr_to_block (&block, tmp);
2858
2859       /* The main body.  */
2860       gfc_add_expr_to_block (&block, loopbody);
2861
2862       /* Increment the loopvar.  */
2863       tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
2864                          loop->loopvar[n], gfc_index_one_node);
2865       gfc_add_modify (&block, loop->loopvar[n], tmp);
2866
2867       /* Build the loop.  */
2868       tmp = gfc_finish_block (&block);
2869       tmp = build1_v (LOOP_EXPR, tmp);
2870       gfc_add_expr_to_block (&loop->code[n], tmp);
2871
2872       /* Add the exit label.  */
2873       tmp = build1_v (LABEL_EXPR, exit_label);
2874       gfc_add_expr_to_block (&loop->code[n], tmp);
2875     }
2876
2877 }
2878
2879
2880 /* Finishes and generates the loops for a scalarized expression.  */
2881
2882 void
2883 gfc_trans_scalarizing_loops (gfc_loopinfo * loop, stmtblock_t * body)
2884 {
2885   int dim;
2886   int n;
2887   gfc_ss *ss;
2888   stmtblock_t *pblock;
2889   tree tmp;
2890
2891   pblock = body;
2892   /* Generate the loops.  */
2893   for (dim = 0; dim < loop->dimen; dim++)
2894     {
2895       n = loop->order[dim];
2896       gfc_trans_scalarized_loop_end (loop, n, pblock);
2897       loop->loopvar[n] = NULL_TREE;
2898       pblock = &loop->code[n];
2899     }
2900
2901   tmp = gfc_finish_block (pblock);
2902   gfc_add_expr_to_block (&loop->pre, tmp);
2903
2904   /* Clear all the used flags.  */
2905   for (ss = loop->ss; ss; ss = ss->loop_chain)
2906     ss->useflags = 0;
2907 }
2908
2909
2910 /* Finish the main body of a scalarized expression, and start the secondary
2911    copying body.  */
2912
2913 void
2914 gfc_trans_scalarized_loop_boundary (gfc_loopinfo * loop, stmtblock_t * body)
2915 {
2916   int dim;
2917   int n;
2918   stmtblock_t *pblock;
2919   gfc_ss *ss;
2920
2921   pblock = body;
2922   /* We finish as many loops as are used by the temporary.  */
2923   for (dim = 0; dim < loop->temp_dim - 1; dim++)
2924     {
2925       n = loop->order[dim];
2926       gfc_trans_scalarized_loop_end (loop, n, pblock);
2927       loop->loopvar[n] = NULL_TREE;
2928       pblock = &loop->code[n];
2929     }
2930
2931   /* We don't want to finish the outermost loop entirely.  */
2932   n = loop->order[loop->temp_dim - 1];
2933   gfc_trans_scalarized_loop_end (loop, n, pblock);
2934
2935   /* Restore the initial offsets.  */
2936   for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
2937     {
2938       if ((ss->useflags & 2) == 0)
2939         continue;
2940
2941       if (ss->type != GFC_SS_SECTION
2942           && ss->type != GFC_SS_FUNCTION && ss->type != GFC_SS_CONSTRUCTOR
2943           && ss->type != GFC_SS_COMPONENT)
2944         continue;
2945
2946       ss->data.info.offset = ss->data.info.saved_offset;
2947     }
2948
2949   /* Restart all the inner loops we just finished.  */
2950   for (dim = loop->temp_dim - 2; dim >= 0; dim--)
2951     {
2952       n = loop->order[dim];
2953
2954       gfc_start_block (&loop->code[n]);
2955
2956       loop->loopvar[n] = gfc_create_var (gfc_array_index_type, "Q");
2957
2958       gfc_trans_preloop_setup (loop, dim, 2, &loop->code[n]);
2959     }
2960
2961   /* Start a block for the secondary copying code.  */
2962   gfc_start_block (body);
2963 }
2964
2965
2966 /* Calculate the upper bound of an array section.  */
2967
2968 static tree
2969 gfc_conv_section_upper_bound (gfc_ss * ss, int n, stmtblock_t * pblock)
2970 {
2971   int dim;
2972   gfc_expr *end;
2973   tree desc;
2974   tree bound;
2975   gfc_se se;
2976   gfc_ss_info *info;
2977
2978   gcc_assert (ss->type == GFC_SS_SECTION);
2979
2980   info = &ss->data.info;
2981   dim = info->dim[n];
2982
2983   if (info->ref->u.ar.dimen_type[dim] == DIMEN_VECTOR)
2984     /* We'll calculate the upper bound once we have access to the
2985        vector's descriptor.  */
2986     return NULL;
2987
2988   gcc_assert (info->ref->u.ar.dimen_type[dim] == DIMEN_RANGE);
2989   desc = info->descriptor;
2990   end = info->ref->u.ar.end[dim];
2991
2992   if (end)
2993     {
2994       /* The upper bound was specified.  */
2995       gfc_init_se (&se, NULL);
2996       gfc_conv_expr_type (&se, end, gfc_array_index_type);
2997       gfc_add_block_to_block (pblock, &se.pre);
2998       bound = se.expr;
2999     }
3000   else
3001     {
3002       /* No upper bound was specified, so use the bound of the array.  */
3003       bound = gfc_conv_array_ubound (desc, dim);
3004     }
3005
3006   return bound;
3007 }
3008
3009
3010 /* Calculate the lower bound of an array section.  */
3011
3012 static void
3013 gfc_conv_section_startstride (gfc_loopinfo * loop, gfc_ss * ss, int n)
3014 {
3015   gfc_expr *start;
3016   gfc_expr *end;
3017   gfc_expr *stride;
3018   tree desc;
3019   gfc_se se;
3020   gfc_ss_info *info;
3021   int dim;
3022
3023   gcc_assert (ss->type == GFC_SS_SECTION);
3024
3025   info = &ss->data.info;
3026   dim = info->dim[n];
3027
3028   if (info->ref->u.ar.dimen_type[dim] == DIMEN_VECTOR)
3029     {
3030       /* We use a zero-based index to access the vector.  */
3031       info->start[n] = gfc_index_zero_node;
3032       info->end[n] = gfc_index_zero_node;
3033       info->stride[n] = gfc_index_one_node;
3034       return;
3035     }
3036
3037   gcc_assert (info->ref->u.ar.dimen_type[dim] == DIMEN_RANGE);
3038   desc = info->descriptor;
3039   start = info->ref->u.ar.start[dim];
3040   end = info->ref->u.ar.end[dim];
3041   stride = info->ref->u.ar.stride[dim];
3042
3043   /* Calculate the start of the range.  For vector subscripts this will
3044      be the range of the vector.  */
3045   if (start)
3046     {
3047       /* Specified section start.  */
3048       gfc_init_se (&se, NULL);
3049       gfc_conv_expr_type (&se, start, gfc_array_index_type);
3050       gfc_add_block_to_block (&loop->pre, &se.pre);
3051       info->start[n] = se.expr;
3052     }
3053   else
3054     {
3055       /* No lower bound specified so use the bound of the array.  */
3056       info->start[n] = gfc_conv_array_lbound (desc, dim);
3057     }
3058   info->start[n] = gfc_evaluate_now (info->start[n], &loop->pre);
3059
3060   /* Similarly calculate the end.  Although this is not used in the
3061      scalarizer, it is needed when checking bounds and where the end
3062      is an expression with side-effects.  */
3063   if (end)
3064     {
3065       /* Specified section start.  */
3066       gfc_init_se (&se, NULL);
3067       gfc_conv_expr_type (&se, end, gfc_array_index_type);
3068       gfc_add_block_to_block (&loop->pre, &se.pre);
3069       info->end[n] = se.expr;
3070     }
3071   else
3072     {
3073       /* No upper bound specified so use the bound of the array.  */
3074       info->end[n] = gfc_conv_array_ubound (desc, dim);
3075     }
3076   info->end[n] = gfc_evaluate_now (info->end[n], &loop->pre);
3077
3078   /* Calculate the stride.  */
3079   if (stride == NULL)
3080     info->stride[n] = gfc_index_one_node;
3081   else
3082     {
3083       gfc_init_se (&se, NULL);
3084       gfc_conv_expr_type (&se, stride, gfc_array_index_type);
3085       gfc_add_block_to_block (&loop->pre, &se.pre);
3086       info->stride[n] = gfc_evaluate_now (se.expr, &loop->pre);
3087     }
3088 }
3089
3090
3091 /* Calculates the range start and stride for a SS chain.  Also gets the
3092    descriptor and data pointer.  The range of vector subscripts is the size
3093    of the vector.  Array bounds are also checked.  */
3094
3095 void
3096 gfc_conv_ss_startstride (gfc_loopinfo * loop)
3097 {
3098   int n;
3099   tree tmp;
3100   gfc_ss *ss;
3101   tree desc;
3102
3103   loop->dimen = 0;
3104   /* Determine the rank of the loop.  */
3105   for (ss = loop->ss;
3106        ss != gfc_ss_terminator && loop->dimen == 0; ss = ss->loop_chain)
3107     {
3108       switch (ss->type)
3109         {
3110         case GFC_SS_SECTION:
3111         case GFC_SS_CONSTRUCTOR:
3112         case GFC_SS_FUNCTION:
3113         case GFC_SS_COMPONENT:
3114           loop->dimen = ss->data.info.dimen;
3115           break;
3116
3117         /* As usual, lbound and ubound are exceptions!.  */
3118         case GFC_SS_INTRINSIC:
3119           switch (ss->expr->value.function.isym->id)
3120             {
3121             case GFC_ISYM_LBOUND:
3122             case GFC_ISYM_UBOUND:
3123               loop->dimen = ss->data.info.dimen;
3124
3125             default:
3126               break;
3127             }
3128
3129         default:
3130           break;
3131         }
3132     }
3133
3134   /* We should have determined the rank of the expression by now.  If
3135      not, that's bad news.  */
3136   gcc_assert (loop->dimen != 0);
3137
3138   /* Loop over all the SS in the chain.  */
3139   for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
3140     {
3141       if (ss->expr && ss->expr->shape && !ss->shape)
3142         ss->shape = ss->expr->shape;
3143
3144       switch (ss->type)
3145         {
3146         case GFC_SS_SECTION:
3147           /* Get the descriptor for the array.  */
3148           gfc_conv_ss_descriptor (&loop->pre, ss, !loop->array_parameter);
3149
3150           for (n = 0; n < ss->data.info.dimen; n++)
3151             gfc_conv_section_startstride (loop, ss, n);
3152           break;
3153
3154         case GFC_SS_INTRINSIC:
3155           switch (ss->expr->value.function.isym->id)
3156             {
3157             /* Fall through to supply start and stride.  */
3158             case GFC_ISYM_LBOUND:
3159             case GFC_ISYM_UBOUND:
3160               break;
3161             default:
3162               continue;
3163             }
3164
3165         case GFC_SS_CONSTRUCTOR:
3166         case GFC_SS_FUNCTION:
3167           for (n = 0; n < ss->data.info.dimen; n++)
3168             {
3169               ss->data.info.start[n] = gfc_index_zero_node;
3170               ss->data.info.end[n] = gfc_index_zero_node;
3171               ss->data.info.stride[n] = gfc_index_one_node;
3172             }
3173           break;
3174
3175         default:
3176           break;
3177         }
3178     }
3179
3180   /* The rest is just runtime bound checking.  */
3181   if (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS)
3182     {
3183       stmtblock_t block;
3184       tree lbound, ubound;
3185       tree end;
3186       tree size[GFC_MAX_DIMENSIONS];
3187       tree stride_pos, stride_neg, non_zerosized, tmp2, tmp3;
3188       gfc_ss_info *info;
3189       char *msg;
3190       int dim;
3191
3192       gfc_start_block (&block);
3193
3194       for (n = 0; n < loop->dimen; n++)
3195         size[n] = NULL_TREE;
3196
3197       for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
3198         {
3199           stmtblock_t inner;
3200
3201           if (ss->type != GFC_SS_SECTION)
3202             continue;
3203
3204           gfc_start_block (&inner);
3205
3206           /* TODO: range checking for mapped dimensions.  */
3207           info = &ss->data.info;
3208
3209           /* This code only checks ranges.  Elemental and vector
3210              dimensions are checked later.  */
3211           for (n = 0; n < loop->dimen; n++)
3212             {
3213               bool check_upper;
3214
3215               dim = info->dim[n];
3216               if (info->ref->u.ar.dimen_type[dim] != DIMEN_RANGE)
3217                 continue;
3218
3219               if (dim == info->ref->u.ar.dimen - 1
3220                   && info->ref->u.ar.as->type == AS_ASSUMED_SIZE)
3221                 check_upper = false;
3222               else
3223                 check_upper = true;
3224
3225               /* Zero stride is not allowed.  */
3226               tmp = fold_build2 (EQ_EXPR, boolean_type_node, info->stride[n],
3227                                  gfc_index_zero_node);
3228               asprintf (&msg, "Zero stride is not allowed, for dimension %d "
3229                         "of array '%s'", info->dim[n]+1,
3230                         ss->expr->symtree->name);
3231               gfc_trans_runtime_check (true, false, tmp, &inner,
3232                                        &ss->expr->where, msg);
3233               gfc_free (msg);
3234
3235               desc = ss->data.info.descriptor;
3236
3237               /* This is the run-time equivalent of resolve.c's
3238                  check_dimension().  The logical is more readable there
3239                  than it is here, with all the trees.  */
3240               lbound = gfc_conv_array_lbound (desc, dim);
3241               end = info->end[n];
3242               if (check_upper)
3243                 ubound = gfc_conv_array_ubound (desc, dim);
3244               else
3245                 ubound = NULL;
3246
3247               /* non_zerosized is true when the selected range is not
3248                  empty.  */
3249               stride_pos = fold_build2 (GT_EXPR, boolean_type_node,
3250                                         info->stride[n], gfc_index_zero_node);
3251               tmp = fold_build2 (LE_EXPR, boolean_type_node, info->start[n],
3252                                  end);
3253               stride_pos = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3254                                         stride_pos, tmp);
3255
3256               stride_neg = fold_build2 (LT_EXPR, boolean_type_node,
3257                                         info->stride[n], gfc_index_zero_node);
3258               tmp = fold_build2 (GE_EXPR, boolean_type_node, info->start[n],
3259                                  end);
3260               stride_neg = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3261                                         stride_neg, tmp);
3262               non_zerosized = fold_build2 (TRUTH_OR_EXPR, boolean_type_node,
3263                                            stride_pos, stride_neg);
3264
3265               /* Check the start of the range against the lower and upper
3266                  bounds of the array, if the range is not empty. 
3267                  If upper bound is present, include both bounds in the 
3268                  error message.  */
3269               if (check_upper)
3270                 {
3271                   tmp = fold_build2 (LT_EXPR, boolean_type_node, 
3272                                      info->start[n], lbound);
3273                   tmp = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3274                                      non_zerosized, tmp);
3275                   tmp2 = fold_build2 (GT_EXPR, boolean_type_node,
3276                                       info->start[n], ubound);
3277                   tmp2 = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3278                                       non_zerosized, tmp2);
3279                   asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
3280                             "outside of expected range (%%ld:%%ld)", 
3281                             info->dim[n]+1, ss->expr->symtree->name);
3282                   gfc_trans_runtime_check (true, false, tmp, &inner, 
3283                                            &ss->expr->where, msg,
3284                      fold_convert (long_integer_type_node, info->start[n]),
3285                      fold_convert (long_integer_type_node, lbound), 
3286                      fold_convert (long_integer_type_node, ubound));
3287                   gfc_trans_runtime_check (true, false, tmp2, &inner, 
3288                                            &ss->expr->where, msg,
3289                      fold_convert (long_integer_type_node, info->start[n]),
3290                      fold_convert (long_integer_type_node, lbound), 
3291                      fold_convert (long_integer_type_node, ubound));
3292                   gfc_free (msg);
3293                 }
3294               else
3295                 {
3296                   tmp = fold_build2 (LT_EXPR, boolean_type_node, 
3297                                      info->start[n], lbound);
3298                   tmp = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3299                                      non_zerosized, tmp);
3300                   asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
3301                             "below lower bound of %%ld", 
3302                             info->dim[n]+1, ss->expr->symtree->name);
3303                   gfc_trans_runtime_check (true, false, tmp, &inner, 
3304                                            &ss->expr->where, msg,
3305                      fold_convert (long_integer_type_node, info->start[n]),
3306                      fold_convert (long_integer_type_node, lbound));
3307                   gfc_free (msg);
3308                 }
3309               
3310               /* Compute the last element of the range, which is not
3311                  necessarily "end" (think 0:5:3, which doesn't contain 5)
3312                  and check it against both lower and upper bounds.  */
3313
3314               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, end,
3315                                   info->start[n]);
3316               tmp = fold_build2 (TRUNC_MOD_EXPR, gfc_array_index_type, tmp,
3317                                   info->stride[n]);
3318               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, end,
3319                                   tmp);
3320               tmp2 = fold_build2 (LT_EXPR, boolean_type_node, tmp, lbound);
3321               tmp2 = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3322                                  non_zerosized, tmp2);
3323               if (check_upper)
3324                 {
3325                   tmp3 = fold_build2 (GT_EXPR, boolean_type_node, tmp, ubound);
3326                   tmp3 = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
3327                                       non_zerosized, tmp3);
3328                   asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
3329                             "outside of expected range (%%ld:%%ld)", 
3330                             info->dim[n]+1, ss->expr->symtree->name);
3331                   gfc_trans_runtime_check (true, false, tmp2, &inner,
3332                                            &ss->expr->where, msg,
3333                      fold_convert (long_integer_type_node, tmp),
3334                      fold_convert (long_integer_type_node, ubound), 
3335                      fold_convert (long_integer_type_node, lbound));
3336                   gfc_trans_runtime_check (true, false, tmp3, &inner,
3337                                            &ss->expr->where, msg,
3338                      fold_convert (long_integer_type_node, tmp),
3339                      fold_convert (long_integer_type_node, ubound), 
3340                      fold_convert (long_integer_type_node, lbound));
3341                   gfc_free (msg);
3342                 }
3343               else
3344                 {
3345                   asprintf (&msg, "Index '%%ld' of dimension %d of array '%s' "
3346                             "below lower bound of %%ld", 
3347                             info->dim[n]+1, ss->expr->symtree->name);
3348                   gfc_trans_runtime_check (true, false, tmp2, &inner,
3349                                            &ss->expr->where, msg,
3350                      fold_convert (long_integer_type_node, tmp),
3351                      fold_convert (long_integer_type_node, lbound));
3352                   gfc_free (msg);
3353                 }
3354               
3355               /* Check the section sizes match.  */
3356               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, end,
3357                                  info->start[n]);
3358               tmp = fold_build2 (FLOOR_DIV_EXPR, gfc_array_index_type, tmp,
3359                                  info->stride[n]);
3360               tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
3361                                  gfc_index_one_node, tmp);
3362               tmp = fold_build2 (MAX_EXPR, gfc_array_index_type, tmp,
3363                                  build_int_cst (gfc_array_index_type, 0));
3364               /* We remember the size of the first section, and check all the
3365                  others against this.  */
3366               if (size[n])
3367                 {
3368                   tmp3 = fold_build2 (NE_EXPR, boolean_type_node, tmp, size[n]);
3369                   asprintf (&msg, "%s, size mismatch for dimension %d "
3370                             "of array '%s' (%%ld/%%ld)", gfc_msg_bounds,
3371                             info->dim[n]+1, ss->expr->symtree->name);
3372                   gfc_trans_runtime_check (true, false, tmp3, &inner,
3373                                            &ss->expr->where, msg,
3374                         fold_convert (long_integer_type_node, tmp),
3375                         fold_convert (long_integer_type_node, size[n]));
3376                   gfc_free (msg);
3377                 }
3378               else
3379                 size[n] = gfc_evaluate_now (tmp, &inner);
3380             }
3381
3382           tmp = gfc_finish_block (&inner);
3383
3384           /* For optional arguments, only check bounds if the argument is
3385              present.  */
3386           if (ss->expr->symtree->n.sym->attr.optional
3387               || ss->expr->symtree->n.sym->attr.not_always_present)
3388             tmp = build3_v (COND_EXPR,
3389                             gfc_conv_expr_present (ss->expr->symtree->n.sym),
3390                             tmp, build_empty_stmt (input_location));
3391
3392           gfc_add_expr_to_block (&block, tmp);
3393
3394         }
3395
3396       tmp = gfc_finish_block (&block);
3397       gfc_add_expr_to_block (&loop->pre, tmp);
3398     }
3399 }
3400
3401
3402 /* Return true if the two SS could be aliased, i.e. both point to the same data
3403    object.  */
3404 /* TODO: resolve aliases based on frontend expressions.  */
3405
3406 static int
3407 gfc_could_be_alias (gfc_ss * lss, gfc_ss * rss)
3408 {
3409   gfc_ref *lref;
3410   gfc_ref *rref;
3411   gfc_symbol *lsym;
3412   gfc_symbol *rsym;
3413
3414   lsym = lss->expr->symtree->n.sym;
3415   rsym = rss->expr->symtree->n.sym;
3416   if (gfc_symbols_could_alias (lsym, rsym))
3417     return 1;
3418
3419   if (rsym->ts.type != BT_DERIVED
3420       && lsym->ts.type != BT_DERIVED)
3421     return 0;
3422
3423   /* For derived types we must check all the component types.  We can ignore
3424      array references as these will have the same base type as the previous
3425      component ref.  */
3426   for (lref = lss->expr->ref; lref != lss->data.info.ref; lref = lref->next)
3427     {
3428       if (lref->type != REF_COMPONENT)
3429         continue;
3430
3431       if (gfc_symbols_could_alias (lref->u.c.sym, rsym))
3432         return 1;
3433
3434       for (rref = rss->expr->ref; rref != rss->data.info.ref;
3435            rref = rref->next)
3436         {
3437           if (rref->type != REF_COMPONENT)
3438             continue;
3439
3440           if (gfc_symbols_could_alias (lref->u.c.sym, rref->u.c.sym))
3441             return 1;
3442         }
3443     }
3444
3445   for (rref = rss->expr->ref; rref != rss->data.info.ref; rref = rref->next)
3446     {
3447       if (rref->type != REF_COMPONENT)
3448         break;
3449
3450       if (gfc_symbols_could_alias (rref->u.c.sym, lsym))
3451         return 1;
3452     }
3453
3454   return 0;
3455 }
3456
3457
3458 /* Resolve array data dependencies.  Creates a temporary if required.  */
3459 /* TODO: Calc dependencies with gfc_expr rather than gfc_ss, and move to
3460    dependency.c.  */
3461
3462 void
3463 gfc_conv_resolve_dependencies (gfc_loopinfo * loop, gfc_ss * dest,
3464                                gfc_ss * rss)
3465 {
3466   gfc_ss *ss;
3467   gfc_ref *lref;
3468   gfc_ref *rref;
3469   int nDepend = 0;
3470
3471   loop->temp_ss = NULL;
3472
3473   for (ss = rss; ss != gfc_ss_terminator; ss = ss->next)
3474     {
3475       if (ss->type != GFC_SS_SECTION)
3476         continue;
3477
3478       if (dest->expr->symtree->n.sym != ss->expr->symtree->n.sym)
3479         {
3480           if (gfc_could_be_alias (dest, ss)
3481                 || gfc_are_equivalenced_arrays (dest->expr, ss->expr))
3482             {
3483               nDepend = 1;
3484               break;
3485             }
3486         }
3487       else
3488         {
3489           lref = dest->expr->ref;
3490           rref = ss->expr->ref;
3491
3492           nDepend = gfc_dep_resolver (lref, rref);
3493           if (nDepend == 1)
3494             break;
3495 #if 0
3496           /* TODO : loop shifting.  */
3497           if (nDepend == 1)
3498             {
3499               /* Mark the dimensions for LOOP SHIFTING */
3500               for (n = 0; n < loop->dimen; n++)
3501                 {
3502                   int dim = dest->data.info.dim[n];
3503
3504                   if (lref->u.ar.dimen_type[dim] == DIMEN_VECTOR)
3505                     depends[n] = 2;
3506                   else if (! gfc_is_same_range (&lref->u.ar,
3507                                                 &rref->u.ar, dim, 0))
3508                     depends[n] = 1;
3509                  }
3510
3511               /* Put all the dimensions with dependencies in the
3512                  innermost loops.  */
3513               dim = 0;
3514               for (n = 0; n < loop->dimen; n++)
3515                 {
3516                   gcc_assert (loop->order[n] == n);
3517                   if (depends[n])
3518                   loop->order[dim++] = n;
3519                 }
3520               for (n = 0; n < loop->dimen; n++)
3521                 {
3522                   if (! depends[n])
3523                   loop->order[dim++] = n;
3524                 }
3525
3526               gcc_assert (dim == loop->dimen);
3527               break;
3528             }
3529 #endif
3530         }
3531     }
3532
3533   if (nDepend == 1)
3534     {
3535       tree base_type = gfc_typenode_for_spec (&dest->expr->ts);
3536       if (GFC_ARRAY_TYPE_P (base_type)
3537           || GFC_DESCRIPTOR_TYPE_P (base_type))
3538         base_type = gfc_get_element_type (base_type);
3539       loop->temp_ss = gfc_get_ss ();
3540       loop->temp_ss->type = GFC_SS_TEMP;
3541       loop->temp_ss->data.temp.type = base_type;
3542       loop->temp_ss->string_length = dest->string_length;
3543       loop->temp_ss->data.temp.dimen = loop->dimen;
3544       loop->temp_ss->next = gfc_ss_terminator;
3545       gfc_add_ss_to_loop (loop, loop->temp_ss);
3546     }
3547   else
3548     loop->temp_ss = NULL;
3549 }
3550
3551
3552 /* Initialize the scalarization loop.  Creates the loop variables.  Determines
3553    the range of the loop variables.  Creates a temporary if required.
3554    Calculates how to transform from loop variables to array indices for each
3555    expression.  Also generates code for scalar expressions which have been
3556    moved outside the loop.  */
3557
3558 void
3559 gfc_conv_loop_setup (gfc_loopinfo * loop, locus * where)
3560 {
3561   int n;
3562   gfc_ss_info *info;
3563   gfc_ss_info *specinfo;
3564   gfc_ss *ss;
3565   tree tmp;
3566   gfc_ss *loopspec[GFC_MAX_DIMENSIONS];
3567   bool dynamic[GFC_MAX_DIMENSIONS];
3568   mpz_t *cshape;
3569   mpz_t i;
3570
3571   mpz_init (i);
3572   for (n = 0; n < loop->dimen; n++)
3573     {
3574       loopspec[n] = NULL;
3575       dynamic[n] = false;
3576       /* We use one SS term, and use that to determine the bounds of the
3577          loop for this dimension.  We try to pick the simplest term.  */
3578       for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
3579         {
3580           if (ss->shape)
3581             {
3582               /* The frontend has worked out the size for us.  */
3583               if (!loopspec[n] || !loopspec[n]->shape
3584                     || !integer_zerop (loopspec[n]->data.info.start[n]))
3585                 /* Prefer zero-based descriptors if possible.  */
3586                 loopspec[n] = ss;
3587               continue;
3588             }
3589
3590           if (ss->type == GFC_SS_CONSTRUCTOR)
3591             {
3592               gfc_constructor_base base;
3593               /* An unknown size constructor will always be rank one.
3594                  Higher rank constructors will either have known shape,
3595                  or still be wrapped in a call to reshape.  */
3596               gcc_assert (loop->dimen == 1);
3597
3598               /* Always prefer to use the constructor bounds if the size
3599                  can be determined at compile time.  Prefer not to otherwise,
3600                  since the general case involves realloc, and it's better to
3601                  avoid that overhead if possible.  */
3602               base = ss->expr->value.constructor;
3603               dynamic[n] = gfc_get_array_constructor_size (&i, base);
3604               if (!dynamic[n] || !loopspec[n])
3605                 loopspec[n] = ss;
3606               continue;
3607             }
3608
3609           /* TODO: Pick the best bound if we have a choice between a
3610              function and something else.  */
3611           if (ss->type == GFC_SS_FUNCTION)
3612             {
3613               loopspec[n] = ss;
3614               continue;
3615             }
3616
3617           if (ss->type != GFC_SS_SECTION)
3618             continue;
3619
3620           if (loopspec[n])
3621             specinfo = &loopspec[n]->data.info;
3622           else
3623             specinfo = NULL;
3624           info = &ss->data.info;
3625
3626           if (!specinfo)
3627             loopspec[n] = ss;
3628           /* Criteria for choosing a loop specifier (most important first):
3629              doesn't need realloc
3630              stride of one
3631              known stride
3632              known lower bound
3633              known upper bound
3634            */
3635           else if (loopspec[n]->type == GFC_SS_CONSTRUCTOR && dynamic[n])
3636             loopspec[n] = ss;
3637           else if (integer_onep (info->stride[n])
3638                    && !integer_onep (specinfo->stride[n]))
3639             loopspec[n] = ss;
3640           else if (INTEGER_CST_P (info->stride[n])
3641                    && !INTEGER_CST_P (specinfo->stride[n]))
3642             loopspec[n] = ss;
3643           else if (INTEGER_CST_P (info->start[n])
3644                    && !INTEGER_CST_P (specinfo->start[n]))
3645             loopspec[n] = ss;
3646           /* We don't work out the upper bound.
3647              else if (INTEGER_CST_P (info->finish[n])
3648              && ! INTEGER_CST_P (specinfo->finish[n]))
3649              loopspec[n] = ss; */
3650         }
3651
3652       /* We should have found the scalarization loop specifier.  If not,
3653          that's bad news.  */
3654       gcc_assert (loopspec[n]);
3655
3656       info = &loopspec[n]->data.info;
3657
3658       /* Set the extents of this range.  */
3659       cshape = loopspec[n]->shape;
3660       if (cshape && INTEGER_CST_P (info->start[n])
3661           && INTEGER_CST_P (info->stride[n]))
3662         {
3663           loop->from[n] = info->start[n];
3664           mpz_set (i, cshape[n]);
3665           mpz_sub_ui (i, i, 1);
3666           /* To = from + (size - 1) * stride.  */
3667           tmp = gfc_conv_mpz_to_tree (i, gfc_index_integer_kind);
3668           if (!integer_onep (info->stride[n]))
3669             tmp = fold_build2 (MULT_EXPR, gfc_array_index_type,
3670                                tmp, info->stride[n]);
3671           loop->to[n] = fold_build2 (PLUS_EXPR, gfc_array_index_type,
3672                                      loop->from[n], tmp);
3673         }
3674       else
3675         {
3676           loop->from[n] = info->start[n];
3677           switch (loopspec[n]->type)
3678             {
3679             case GFC_SS_CONSTRUCTOR:
3680               /* The upper bound is calculated when we expand the
3681                  constructor.  */
3682               gcc_assert (loop->to[n] == NULL_TREE);
3683               break;
3684
3685             case GFC_SS_SECTION:
3686               /* Use the end expression if it exists and is not constant,
3687                  so that it is only evaluated once.  */
3688               if (info->end[n] && !INTEGER_CST_P (info->end[n]))
3689                 loop->to[n] = info->end[n];
3690               else
3691                 loop->to[n] = gfc_conv_section_upper_bound (loopspec[n], n,
3692                                                             &loop->pre);
3693               break;
3694
3695             case GFC_SS_FUNCTION:
3696               /* The loop bound will be set when we generate the call.  */
3697               gcc_assert (loop->to[n] == NULL_TREE);
3698               break;
3699
3700             default:
3701               gcc_unreachable ();
3702             }
3703         }
3704
3705       /* Transform everything so we have a simple incrementing variable.  */
3706       if (integer_onep (info->stride[n]))
3707         info->delta[n] = gfc_index_zero_node;
3708       else
3709         {
3710           /* Set the delta for this section.  */
3711           info->delta[n] = gfc_evaluate_now (loop->from[n], &loop->pre);
3712           /* Number of iterations is (end - start + step) / step.
3713              with start = 0, this simplifies to
3714              last = end / step;
3715              for (i = 0; i<=last; i++){...};  */
3716           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
3717                              loop->to[n], loop->from[n]);
3718           tmp = fold_build2 (FLOOR_DIV_EXPR, gfc_array_index_type, 
3719                              tmp, info->stride[n]);
3720           tmp = fold_build2 (MAX_EXPR, gfc_array_index_type, tmp,
3721                              build_int_cst (gfc_array_index_type, -1));
3722           loop->to[n] = gfc_evaluate_now (tmp, &loop->pre);
3723           /* Make the loop variable start at 0.  */
3724           loop->from[n] = gfc_index_zero_node;
3725         }
3726     }
3727
3728   /* Add all the scalar code that can be taken out of the loops.
3729      This may include calculating the loop bounds, so do it before
3730      allocating the temporary.  */
3731   gfc_add_loop_ss_code (loop, loop->ss, false, where);
3732
3733   /* If we want a temporary then create it.  */
3734   if (loop->temp_ss != NULL)
3735     {
3736       gcc_assert (loop->temp_ss->type == GFC_SS_TEMP);
3737
3738       /* Make absolutely sure that this is a complete type.  */
3739       if (loop->temp_ss->string_length)
3740         loop->temp_ss->data.temp.type
3741                 = gfc_get_character_type_len_for_eltype
3742                         (TREE_TYPE (loop->temp_ss->data.temp.type),
3743                          loop->temp_ss->string_length);
3744
3745       tmp = loop->temp_ss->data.temp.type;
3746       n = loop->temp_ss->data.temp.dimen;
3747       memset (&loop->temp_ss->data.info, 0, sizeof (gfc_ss_info));
3748       loop->temp_ss->type = GFC_SS_SECTION;
3749       loop->temp_ss->data.info.dimen = n;
3750       gfc_trans_create_temp_array (&loop->pre, &loop->post, loop,
3751                                    &loop->temp_ss->data.info, tmp, NULL_TREE,
3752                                    false, true, false, where);
3753     }
3754
3755   for (n = 0; n < loop->temp_dim; n++)
3756     loopspec[loop->order[n]] = NULL;
3757
3758   mpz_clear (i);
3759
3760   /* For array parameters we don't have loop variables, so don't calculate the
3761      translations.  */
3762   if (loop->array_parameter)
3763     return;
3764
3765   /* Calculate the translation from loop variables to array indices.  */
3766   for (ss = loop->ss; ss != gfc_ss_terminator; ss = ss->loop_chain)
3767     {
3768       if (ss->type != GFC_SS_SECTION && ss->type != GFC_SS_COMPONENT
3769             && ss->type != GFC_SS_CONSTRUCTOR)
3770
3771         continue;
3772
3773       info = &ss->data.info;
3774
3775       for (n = 0; n < info->dimen; n++)
3776         {
3777           /* If we are specifying the range the delta is already set.  */
3778           if (loopspec[n] != ss)
3779             {
3780               /* Calculate the offset relative to the loop variable.
3781                  First multiply by the stride.  */
3782               tmp = loop->from[n];
3783               if (!integer_onep (info->stride[n]))
3784                 tmp = fold_build2 (MULT_EXPR, gfc_array_index_type,
3785                                    tmp, info->stride[n]);
3786
3787               /* Then subtract this from our starting value.  */
3788               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
3789                                  info->start[n], tmp);
3790
3791               info->delta[n] = gfc_evaluate_now (tmp, &loop->pre);
3792             }
3793         }
3794     }
3795 }
3796
3797
3798 /* Fills in an array descriptor, and returns the size of the array.  The size
3799    will be a simple_val, ie a variable or a constant.  Also calculates the
3800    offset of the base.  Returns the size of the array.
3801    {
3802     stride = 1;
3803     offset = 0;
3804     for (n = 0; n < rank; n++)
3805       {
3806         a.lbound[n] = specified_lower_bound;
3807         offset = offset + a.lbond[n] * stride;
3808         size = 1 - lbound;
3809         a.ubound[n] = specified_upper_bound;
3810         a.stride[n] = stride;
3811         size = siz >= 0 ? ubound + size : 0; //size = ubound + 1 - lbound
3812         stride = stride * size;
3813       }
3814     return (stride);
3815    }  */
3816 /*GCC ARRAYS*/
3817
3818 static tree
3819 gfc_array_init_size (tree descriptor, int rank, tree * poffset,
3820                      gfc_expr ** lower, gfc_expr ** upper,
3821                      stmtblock_t * pblock)
3822 {
3823   tree type;
3824   tree tmp;
3825   tree size;
3826   tree offset;
3827   tree stride;
3828   tree cond;
3829   tree or_expr;
3830   tree thencase;
3831   tree elsecase;
3832   tree var;
3833   stmtblock_t thenblock;
3834   stmtblock_t elseblock;
3835   gfc_expr *ubound;
3836   gfc_se se;
3837   int n;
3838
3839   type = TREE_TYPE (descriptor);
3840
3841   stride = gfc_index_one_node;
3842   offset = gfc_index_zero_node;
3843
3844   /* Set the dtype.  */
3845   tmp = gfc_conv_descriptor_dtype (descriptor);
3846   gfc_add_modify (pblock, tmp, gfc_get_dtype (TREE_TYPE (descriptor)));
3847
3848   or_expr = NULL_TREE;
3849
3850   for (n = 0; n < rank; n++)
3851     {
3852       /* We have 3 possibilities for determining the size of the array:
3853          lower == NULL    => lbound = 1, ubound = upper[n]
3854          upper[n] = NULL  => lbound = 1, ubound = lower[n]
3855          upper[n] != NULL => lbound = lower[n], ubound = upper[n]  */
3856       ubound = upper[n];
3857
3858       /* Set lower bound.  */
3859       gfc_init_se (&se, NULL);
3860       if (lower == NULL)
3861         se.expr = gfc_index_one_node;
3862       else
3863         {
3864           gcc_assert (lower[n]);
3865           if (ubound)
3866             {
3867               gfc_conv_expr_type (&se, lower[n], gfc_array_index_type);
3868               gfc_add_block_to_block (pblock, &se.pre);
3869             }
3870           else
3871             {
3872               se.expr = gfc_index_one_node;
3873               ubound = lower[n];
3874             }
3875         }
3876       gfc_conv_descriptor_lbound_set (pblock, descriptor, gfc_rank_cst[n],
3877                                       se.expr);
3878
3879       /* Work out the offset for this component.  */
3880       tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, se.expr, stride);
3881       offset = fold_build2 (MINUS_EXPR, gfc_array_index_type, offset, tmp);
3882
3883       /* Start the calculation for the size of this dimension.  */
3884       size = fold_build2 (MINUS_EXPR, gfc_array_index_type,
3885                           gfc_index_one_node, se.expr);
3886
3887       /* Set upper bound.  */
3888       gfc_init_se (&se, NULL);
3889       gcc_assert (ubound);
3890       gfc_conv_expr_type (&se, ubound, gfc_array_index_type);
3891       gfc_add_block_to_block (pblock, &se.pre);
3892
3893       gfc_conv_descriptor_ubound_set (pblock, descriptor, gfc_rank_cst[n], se.expr);
3894
3895       /* Store the stride.  */
3896       gfc_conv_descriptor_stride_set (pblock, descriptor, gfc_rank_cst[n], stride);
3897
3898       /* Calculate the size of this dimension.  */
3899       size = fold_build2 (PLUS_EXPR, gfc_array_index_type, se.expr, size);
3900
3901       /* Check whether the size for this dimension is negative.  */
3902       cond = fold_build2 (LE_EXPR, boolean_type_node, size,
3903                           gfc_index_zero_node);
3904       if (n == 0)
3905         or_expr = cond;
3906       else
3907         or_expr = fold_build2 (TRUTH_OR_EXPR, boolean_type_node, or_expr, cond);
3908
3909       size = fold_build3 (COND_EXPR, gfc_array_index_type, cond,
3910                           gfc_index_zero_node, size);
3911
3912       /* Multiply the stride by the number of elements in this dimension.  */
3913       stride = fold_build2 (MULT_EXPR, gfc_array_index_type, stride, size);
3914       stride = gfc_evaluate_now (stride, pblock);
3915     }
3916
3917   /* The stride is the number of elements in the array, so multiply by the
3918      size of an element to get the total size.  */
3919   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
3920   size = fold_build2 (MULT_EXPR, gfc_array_index_type, stride,
3921                       fold_convert (gfc_array_index_type, tmp));
3922
3923   if (poffset != NULL)
3924     {
3925       offset = gfc_evaluate_now (offset, pblock);
3926       *poffset = offset;
3927     }
3928
3929   if (integer_zerop (or_expr))
3930     return size;
3931   if (integer_onep (or_expr))
3932     return gfc_index_zero_node;
3933
3934   var = gfc_create_var (TREE_TYPE (size), "size");
3935   gfc_start_block (&thenblock);
3936   gfc_add_modify (&thenblock, var, gfc_index_zero_node);
3937   thencase = gfc_finish_block (&thenblock);
3938
3939   gfc_start_block (&elseblock);
3940   gfc_add_modify (&elseblock, var, size);
3941   elsecase = gfc_finish_block (&elseblock);
3942
3943   tmp = gfc_evaluate_now (or_expr, pblock);
3944   tmp = build3_v (COND_EXPR, tmp, thencase, elsecase);
3945   gfc_add_expr_to_block (pblock, tmp);
3946
3947   return var;
3948 }
3949
3950
3951 /* Initializes the descriptor and generates a call to _gfor_allocate.  Does
3952    the work for an ALLOCATE statement.  */
3953 /*GCC ARRAYS*/
3954
3955 bool
3956 gfc_array_allocate (gfc_se * se, gfc_expr * expr, tree pstat)
3957 {
3958   tree tmp;
3959   tree pointer;
3960   tree offset;
3961   tree size;
3962   gfc_expr **lower;
3963   gfc_expr **upper;
3964   gfc_ref *ref, *prev_ref = NULL;
3965   bool allocatable_array;
3966
3967   ref = expr->ref;
3968
3969   /* Find the last reference in the chain.  */
3970   while (ref && ref->next != NULL)
3971     {
3972       gcc_assert (ref->type != REF_ARRAY || ref->u.ar.type == AR_ELEMENT
3973                   || (ref->u.ar.dimen == 0 && ref->u.ar.codimen > 0));
3974       prev_ref = ref;
3975       ref = ref->next;
3976     }
3977
3978   if (ref == NULL || ref->type != REF_ARRAY)
3979     return false;
3980
3981   /* Return if this is a scalar coarray.  */
3982   if (!prev_ref && !expr->symtree->n.sym->attr.dimension)
3983     {
3984       gcc_assert (expr->symtree->n.sym->attr.codimension);
3985       return false;
3986     }
3987   else if (prev_ref && !prev_ref->u.c.component->attr.dimension)
3988     {
3989       gcc_assert (prev_ref->u.c.component->attr.codimension);
3990       return false;
3991     }
3992
3993   if (!prev_ref)
3994     allocatable_array = expr->symtree->n.sym->attr.allocatable;
3995   else
3996     allocatable_array = prev_ref->u.c.component->attr.allocatable;
3997
3998   /* Figure out the size of the array.  */
3999   switch (ref->u.ar.type)
4000     {
4001     case AR_ELEMENT:
4002       lower = NULL;
4003       upper = ref->u.ar.start;
4004       break;
4005
4006     case AR_FULL:
4007       gcc_assert (ref->u.ar.as->type == AS_EXPLICIT);
4008
4009       lower = ref->u.ar.as->lower;
4010       upper = ref->u.ar.as->upper;
4011       break;
4012
4013     case AR_SECTION:
4014       lower = ref->u.ar.start;
4015       upper = ref->u.ar.end;
4016       break;
4017
4018     default:
4019       gcc_unreachable ();
4020       break;
4021     }
4022
4023   size = gfc_array_init_size (se->expr, ref->u.ar.as->rank, &offset,
4024                               lower, upper, &se->pre);
4025
4026   /* Allocate memory to store the data.  */
4027   pointer = gfc_conv_descriptor_data_get (se->expr);
4028   STRIP_NOPS (pointer);
4029
4030   /* The allocate_array variants take the old pointer as first argument.  */
4031   if (allocatable_array)
4032     tmp = gfc_allocate_array_with_status (&se->pre, pointer, size, pstat, expr);
4033   else
4034     tmp = gfc_allocate_with_status (&se->pre, size, pstat);
4035   tmp = fold_build2 (MODIFY_EXPR, void_type_node, pointer, tmp);
4036   gfc_add_expr_to_block (&se->pre, tmp);
4037
4038   gfc_conv_descriptor_offset_set (&se->pre, se->expr, offset);
4039
4040   if (expr->ts.type == BT_DERIVED
4041         && expr->ts.u.derived->attr.alloc_comp)
4042     {
4043       tmp = gfc_nullify_alloc_comp (expr->ts.u.derived, se->expr,
4044                                     ref->u.ar.as->rank);
4045       gfc_add_expr_to_block (&se->pre, tmp);
4046     }
4047
4048   return true;
4049 }
4050
4051
4052 /* Deallocate an array variable.  Also used when an allocated variable goes
4053    out of scope.  */
4054 /*GCC ARRAYS*/
4055
4056 tree
4057 gfc_array_deallocate (tree descriptor, tree pstat, gfc_expr* expr)
4058 {
4059   tree var;
4060   tree tmp;
4061   stmtblock_t block;
4062
4063   gfc_start_block (&block);
4064   /* Get a pointer to the data.  */
4065   var = gfc_conv_descriptor_data_get (descriptor);
4066   STRIP_NOPS (var);
4067
4068   /* Parameter is the address of the data component.  */
4069   tmp = gfc_deallocate_with_status (var, pstat, false, expr);
4070   gfc_add_expr_to_block (&block, tmp);
4071
4072   /* Zero the data pointer.  */
4073   tmp = fold_build2 (MODIFY_EXPR, void_type_node,
4074                      var, build_int_cst (TREE_TYPE (var), 0));
4075   gfc_add_expr_to_block (&block, tmp);
4076
4077   return gfc_finish_block (&block);
4078 }
4079
4080
4081 /* Create an array constructor from an initialization expression.
4082    We assume the frontend already did any expansions and conversions.  */
4083
4084 tree
4085 gfc_conv_array_initializer (tree type, gfc_expr * expr)
4086 {
4087   gfc_constructor *c;
4088   tree tmp;
4089   mpz_t maxval;
4090   gfc_se se;
4091   HOST_WIDE_INT hi;
4092   unsigned HOST_WIDE_INT lo;
4093   tree index, range;
4094   VEC(constructor_elt,gc) *v = NULL;
4095
4096   switch (expr->expr_type)
4097     {
4098     case EXPR_CONSTANT:
4099     case EXPR_STRUCTURE:
4100       /* A single scalar or derived type value.  Create an array with all
4101          elements equal to that value.  */
4102       gfc_init_se (&se, NULL);
4103       
4104       if (expr->expr_type == EXPR_CONSTANT)
4105         gfc_conv_constant (&se, expr);
4106       else
4107         gfc_conv_structure (&se, expr, 1);
4108
4109       tmp = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
4110       gcc_assert (tmp && INTEGER_CST_P (tmp));
4111       hi = TREE_INT_CST_HIGH (tmp);
4112       lo = TREE_INT_CST_LOW (tmp);
4113       lo++;
4114       if (lo == 0)
4115         hi++;
4116       /* This will probably eat buckets of memory for large arrays.  */
4117       while (hi != 0 || lo != 0)
4118         {
4119           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, se.expr);
4120           if (lo == 0)
4121             hi--;
4122           lo--;
4123         }
4124       break;
4125
4126     case EXPR_ARRAY:
4127       /* Create a vector of all the elements.  */
4128       for (c = gfc_constructor_first (expr->value.constructor);
4129            c; c = gfc_constructor_next (c))
4130         {
4131           if (c->iterator)
4132             {
4133               /* Problems occur when we get something like
4134                  integer :: a(lots) = (/(i, i=1, lots)/)  */
4135               gfc_fatal_error ("The number of elements in the array constructor "
4136                                "at %L requires an increase of the allowed %d "
4137                                "upper limit.   See -fmax-array-constructor "
4138                                "option", &expr->where,
4139                                gfc_option.flag_max_array_constructor);
4140               return NULL_TREE;
4141             }
4142           if (mpz_cmp_si (c->offset, 0) != 0)
4143             index = gfc_conv_mpz_to_tree (c->offset, gfc_index_integer_kind);
4144           else
4145             index = NULL_TREE;
4146           mpz_init (maxval);
4147           if (mpz_cmp_si (c->repeat, 0) != 0)
4148             {
4149               tree tmp1, tmp2;
4150
4151               mpz_set (maxval, c->repeat);
4152               mpz_add (maxval, c->offset, maxval);
4153               mpz_sub_ui (maxval, maxval, 1);
4154               tmp2 = gfc_conv_mpz_to_tree (maxval, gfc_index_integer_kind);
4155               if (mpz_cmp_si (c->offset, 0) != 0)
4156                 {
4157                   mpz_add_ui (maxval, c->offset, 1);
4158                   tmp1 = gfc_conv_mpz_to_tree (maxval, gfc_index_integer_kind);
4159                 }
4160               else
4161                 tmp1 = gfc_conv_mpz_to_tree (c->offset, gfc_index_integer_kind);
4162
4163               range = fold_build2 (RANGE_EXPR, integer_type_node, tmp1, tmp2);
4164             }
4165           else
4166             range = NULL;
4167           mpz_clear (maxval);
4168
4169           gfc_init_se (&se, NULL);
4170           switch (c->expr->expr_type)
4171             {
4172             case EXPR_CONSTANT:
4173               gfc_conv_constant (&se, c->expr);
4174               if (range == NULL_TREE)
4175                 CONSTRUCTOR_APPEND_ELT (v, index, se.expr);
4176               else
4177                 {
4178                   if (index != NULL_TREE)
4179                     CONSTRUCTOR_APPEND_ELT (v, index, se.expr);
4180                   CONSTRUCTOR_APPEND_ELT (v, range, se.expr);
4181                 }
4182               break;
4183
4184             case EXPR_STRUCTURE:
4185               gfc_conv_structure (&se, c->expr, 1);
4186               CONSTRUCTOR_APPEND_ELT (v, index, se.expr);
4187               break;
4188
4189
4190             default:
4191               /* Catch those occasional beasts that do not simplify
4192                  for one reason or another, assuming that if they are
4193                  standard defying the frontend will catch them.  */
4194               gfc_conv_expr (&se, c->expr);
4195               if (range == NULL_TREE)
4196                 CONSTRUCTOR_APPEND_ELT (v, index, se.expr);
4197               else
4198                 {
4199                   if (index != NULL_TREE)
4200                   CONSTRUCTOR_APPEND_ELT (v, index, se.expr);
4201                   CONSTRUCTOR_APPEND_ELT (v, range, se.expr);
4202                 }
4203               break;
4204             }
4205         }
4206       break;
4207
4208     case EXPR_NULL:
4209       return gfc_build_null_descriptor (type);
4210
4211     default:
4212       gcc_unreachable ();
4213     }
4214
4215   /* Create a constructor from the list of elements.  */
4216   tmp = build_constructor (type, v);
4217   TREE_CONSTANT (tmp) = 1;
4218   return tmp;
4219 }
4220
4221
4222 /* Generate code to evaluate non-constant array bounds.  Sets *poffset and
4223    returns the size (in elements) of the array.  */
4224
4225 static tree
4226 gfc_trans_array_bounds (tree type, gfc_symbol * sym, tree * poffset,
4227                         stmtblock_t * pblock)
4228 {
4229   gfc_array_spec *as;
4230   tree size;
4231   tree stride;
4232   tree offset;
4233   tree ubound;
4234   tree lbound;
4235   tree tmp;
4236   gfc_se se;
4237
4238   int dim;
4239
4240   as = sym->as;
4241
4242   size = gfc_index_one_node;
4243   offset = gfc_index_zero_node;
4244   for (dim = 0; dim < as->rank; dim++)
4245     {
4246       /* Evaluate non-constant array bound expressions.  */
4247       lbound = GFC_TYPE_ARRAY_LBOUND (type, dim);
4248       if (as->lower[dim] && !INTEGER_CST_P (lbound))
4249         {
4250           gfc_init_se (&se, NULL);
4251           gfc_conv_expr_type (&se, as->lower[dim], gfc_array_index_type);
4252           gfc_add_block_to_block (pblock, &se.pre);
4253           gfc_add_modify (pblock, lbound, se.expr);
4254         }
4255       ubound = GFC_TYPE_ARRAY_UBOUND (type, dim);
4256       if (as->upper[dim] && !INTEGER_CST_P (ubound))
4257         {
4258           gfc_init_se (&se, NULL);
4259           gfc_conv_expr_type (&se, as->upper[dim], gfc_array_index_type);
4260           gfc_add_block_to_block (pblock, &se.pre);
4261           gfc_add_modify (pblock, ubound, se.expr);
4262         }
4263       /* The offset of this dimension.  offset = offset - lbound * stride.  */
4264       tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, lbound, size);
4265       offset = fold_build2 (MINUS_EXPR, gfc_array_index_type, offset, tmp);
4266
4267       /* The size of this dimension, and the stride of the next.  */
4268       if (dim + 1 < as->rank)
4269         stride = GFC_TYPE_ARRAY_STRIDE (type, dim + 1);
4270       else
4271         stride = GFC_TYPE_ARRAY_SIZE (type);
4272
4273       if (ubound != NULL_TREE && !(stride && INTEGER_CST_P (stride)))
4274         {
4275           /* Calculate stride = size * (ubound + 1 - lbound).  */
4276           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4277                              gfc_index_one_node, lbound);
4278           tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, ubound, tmp);
4279           tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, size, tmp);
4280           if (stride)
4281             gfc_add_modify (pblock, stride, tmp);
4282           else
4283             stride = gfc_evaluate_now (tmp, pblock);
4284
4285           /* Make sure that negative size arrays are translated
4286              to being zero size.  */
4287           tmp = fold_build2 (GE_EXPR, boolean_type_node,
4288                              stride, gfc_index_zero_node);
4289           tmp = fold_build3 (COND_EXPR, gfc_array_index_type, tmp,
4290                              stride, gfc_index_zero_node);
4291           gfc_add_modify (pblock, stride, tmp);
4292         }
4293
4294       size = stride;
4295     }
4296
4297   gfc_trans_vla_type_sizes (sym, pblock);
4298
4299   *poffset = offset;
4300   return size;
4301 }
4302
4303
4304 /* Generate code to initialize/allocate an array variable.  */
4305
4306 tree
4307 gfc_trans_auto_array_allocation (tree decl, gfc_symbol * sym, tree fnbody)
4308 {
4309   stmtblock_t block;
4310   tree type;
4311   tree tmp;
4312   tree size;
4313   tree offset;
4314   bool onstack;
4315
4316   gcc_assert (!(sym->attr.pointer || sym->attr.allocatable));
4317
4318   /* Do nothing for USEd variables.  */
4319   if (sym->attr.use_assoc)
4320     return fnbody;
4321
4322   type = TREE_TYPE (decl);
4323   gcc_assert (GFC_ARRAY_TYPE_P (type));
4324   onstack = TREE_CODE (type) != POINTER_TYPE;
4325
4326   gfc_start_block (&block);
4327
4328   /* Evaluate character string length.  */
4329   if (sym->ts.type == BT_CHARACTER
4330       && onstack && !INTEGER_CST_P (sym->ts.u.cl->backend_decl))
4331     {
4332       gfc_conv_string_length (sym->ts.u.cl, NULL, &block);
4333
4334       gfc_trans_vla_type_sizes (sym, &block);
4335
4336       /* Emit a DECL_EXPR for this variable, which will cause the
4337          gimplifier to allocate storage, and all that good stuff.  */
4338       tmp = fold_build1 (DECL_EXPR, TREE_TYPE (decl), decl);
4339       gfc_add_expr_to_block (&block, tmp);
4340     }
4341
4342   if (onstack)
4343     {
4344       gfc_add_expr_to_block (&block, fnbody);
4345       return gfc_finish_block (&block);
4346     }
4347
4348   type = TREE_TYPE (type);
4349
4350   gcc_assert (!sym->attr.use_assoc);
4351   gcc_assert (!TREE_STATIC (decl));
4352   gcc_assert (!sym->module);
4353
4354   if (sym->ts.type == BT_CHARACTER
4355       && !INTEGER_CST_P (sym->ts.u.cl->backend_decl))
4356     gfc_conv_string_length (sym->ts.u.cl, NULL, &block);
4357
4358   size = gfc_trans_array_bounds (type, sym, &offset, &block);
4359
4360   /* Don't actually allocate space for Cray Pointees.  */
4361   if (sym->attr.cray_pointee)
4362     {
4363       if (TREE_CODE (GFC_TYPE_ARRAY_OFFSET (type)) == VAR_DECL)
4364         gfc_add_modify (&block, GFC_TYPE_ARRAY_OFFSET (type), offset);
4365       gfc_add_expr_to_block (&block, fnbody);
4366       return gfc_finish_block (&block);
4367     }
4368
4369   /* The size is the number of elements in the array, so multiply by the
4370      size of an element to get the total size.  */
4371   tmp = TYPE_SIZE_UNIT (gfc_get_element_type (type));
4372   size = fold_build2 (MULT_EXPR, gfc_array_index_type, size,
4373                       fold_convert (gfc_array_index_type, tmp));
4374
4375   /* Allocate memory to hold the data.  */
4376   tmp = gfc_call_malloc (&block, TREE_TYPE (decl), size);
4377   gfc_add_modify (&block, decl, tmp);
4378
4379   /* Set offset of the array.  */
4380   if (TREE_CODE (GFC_TYPE_ARRAY_OFFSET (type)) == VAR_DECL)
4381     gfc_add_modify (&block, GFC_TYPE_ARRAY_OFFSET (type), offset);
4382
4383
4384   /* Automatic arrays should not have initializers.  */
4385   gcc_assert (!sym->value);
4386
4387   gfc_add_expr_to_block (&block, fnbody);
4388
4389   /* Free the temporary.  */
4390   tmp = gfc_call_free (convert (pvoid_type_node, decl));
4391   gfc_add_expr_to_block (&block, tmp);
4392
4393   return gfc_finish_block (&block);
4394 }
4395
4396
4397 /* Generate entry and exit code for g77 calling convention arrays.  */
4398
4399 tree
4400 gfc_trans_g77_array (gfc_symbol * sym, tree body)
4401 {
4402   tree parm;
4403   tree type;
4404   locus loc;
4405   tree offset;
4406   tree tmp;
4407   tree stmt;  
4408   stmtblock_t block;
4409
4410   gfc_get_backend_locus (&loc);
4411   gfc_set_backend_locus (&sym->declared_at);
4412
4413   /* Descriptor type.  */
4414   parm = sym->backend_decl;
4415   type = TREE_TYPE (parm);
4416   gcc_assert (GFC_ARRAY_TYPE_P (type));
4417
4418   gfc_start_block (&block);
4419
4420   if (sym->ts.type == BT_CHARACTER
4421       && TREE_CODE (sym->ts.u.cl->backend_decl) == VAR_DECL)
4422     gfc_conv_string_length (sym->ts.u.cl, NULL, &block);
4423
4424   /* Evaluate the bounds of the array.  */
4425   gfc_trans_array_bounds (type, sym, &offset, &block);
4426
4427   /* Set the offset.  */
4428   if (TREE_CODE (GFC_TYPE_ARRAY_OFFSET (type)) == VAR_DECL)
4429     gfc_add_modify (&block, GFC_TYPE_ARRAY_OFFSET (type), offset);
4430
4431   /* Set the pointer itself if we aren't using the parameter directly.  */
4432   if (TREE_CODE (parm) != PARM_DECL)
4433     {
4434       tmp = convert (TREE_TYPE (parm), GFC_DECL_SAVED_DESCRIPTOR (parm));
4435       gfc_add_modify (&block, parm, tmp);
4436     }
4437   stmt = gfc_finish_block (&block);
4438
4439   gfc_set_backend_locus (&loc);
4440
4441   gfc_start_block (&block);
4442
4443   /* Add the initialization code to the start of the function.  */
4444
4445   if (sym->attr.optional || sym->attr.not_always_present)
4446     {
4447       tmp = gfc_conv_expr_present (sym);
4448       stmt = build3_v (COND_EXPR, tmp, stmt, build_empty_stmt (input_location));
4449     }
4450   
4451   gfc_add_expr_to_block (&block, stmt);
4452   gfc_add_expr_to_block (&block, body);
4453
4454   return gfc_finish_block (&block);
4455 }
4456
4457
4458 /* Modify the descriptor of an array parameter so that it has the
4459    correct lower bound.  Also move the upper bound accordingly.
4460    If the array is not packed, it will be copied into a temporary.
4461    For each dimension we set the new lower and upper bounds.  Then we copy the
4462    stride and calculate the offset for this dimension.  We also work out
4463    what the stride of a packed array would be, and see it the two match.
4464    If the array need repacking, we set the stride to the values we just
4465    calculated, recalculate the offset and copy the array data.
4466    Code is also added to copy the data back at the end of the function.
4467    */
4468
4469 tree
4470 gfc_trans_dummy_array_bias (gfc_symbol * sym, tree tmpdesc, tree body)
4471 {
4472   tree size;
4473   tree type;
4474   tree offset;
4475   locus loc;
4476   stmtblock_t block;
4477   stmtblock_t cleanup;
4478   tree lbound;
4479   tree ubound;
4480   tree dubound;
4481   tree dlbound;
4482   tree dumdesc;
4483   tree tmp;
4484   tree stmt;
4485   tree stride, stride2;
4486   tree stmt_packed;
4487   tree stmt_unpacked;
4488   tree partial;
4489   gfc_se se;
4490   int n;
4491   int checkparm;
4492   int no_repack;
4493   bool optional_arg;
4494
4495   /* Do nothing for pointer and allocatable arrays.  */
4496   if (sym->attr.pointer || sym->attr.allocatable)
4497     return body;
4498
4499   if (sym->attr.dummy && gfc_is_nodesc_array (sym))
4500     return gfc_trans_g77_array (sym, body);
4501
4502   gfc_get_backend_locus (&loc);
4503   gfc_set_backend_locus (&sym->declared_at);
4504
4505   /* Descriptor type.  */
4506   type = TREE_TYPE (tmpdesc);
4507   gcc_assert (GFC_ARRAY_TYPE_P (type));
4508   dumdesc = GFC_DECL_SAVED_DESCRIPTOR (tmpdesc);
4509   dumdesc = build_fold_indirect_ref_loc (input_location,
4510                                      dumdesc);
4511   gfc_start_block (&block);
4512
4513   if (sym->ts.type == BT_CHARACTER
4514       && TREE_CODE (sym->ts.u.cl->backend_decl) == VAR_DECL)
4515     gfc_conv_string_length (sym->ts.u.cl, NULL, &block);
4516
4517   checkparm = (sym->as->type == AS_EXPLICIT
4518                && (gfc_option.rtcheck & GFC_RTCHECK_BOUNDS));
4519
4520   no_repack = !(GFC_DECL_PACKED_ARRAY (tmpdesc)
4521                 || GFC_DECL_PARTIAL_PACKED_ARRAY (tmpdesc));
4522
4523   if (GFC_DECL_PARTIAL_PACKED_ARRAY (tmpdesc))
4524     {
4525       /* For non-constant shape arrays we only check if the first dimension
4526          is contiguous.  Repacking higher dimensions wouldn't gain us
4527          anything as we still don't know the array stride.  */
4528       partial = gfc_create_var (boolean_type_node, "partial");
4529       TREE_USED (partial) = 1;
4530       tmp = gfc_conv_descriptor_stride_get (dumdesc, gfc_rank_cst[0]);
4531       tmp = fold_build2 (EQ_EXPR, boolean_type_node, tmp, gfc_index_one_node);
4532       gfc_add_modify (&block, partial, tmp);
4533     }
4534   else
4535     {
4536       partial = NULL_TREE;
4537     }
4538
4539   /* The naming of stmt_unpacked and stmt_packed may be counter-intuitive
4540      here, however I think it does the right thing.  */
4541   if (no_repack)
4542     {
4543       /* Set the first stride.  */
4544       stride = gfc_conv_descriptor_stride_get (dumdesc, gfc_rank_cst[0]);
4545       stride = gfc_evaluate_now (stride, &block);
4546
4547       tmp = fold_build2 (EQ_EXPR, boolean_type_node,
4548                          stride, gfc_index_zero_node);
4549       tmp = fold_build3 (COND_EXPR, gfc_array_index_type, tmp,
4550                          gfc_index_one_node, stride);
4551       stride = GFC_TYPE_ARRAY_STRIDE (type, 0);
4552       gfc_add_modify (&block, stride, tmp);
4553
4554       /* Allow the user to disable array repacking.  */
4555       stmt_unpacked = NULL_TREE;
4556     }
4557   else
4558     {
4559       gcc_assert (integer_onep (GFC_TYPE_ARRAY_STRIDE (type, 0)));
4560       /* A library call to repack the array if necessary.  */
4561       tmp = GFC_DECL_SAVED_DESCRIPTOR (tmpdesc);
4562       stmt_unpacked = build_call_expr_loc (input_location,
4563                                        gfor_fndecl_in_pack, 1, tmp);
4564
4565       stride = gfc_index_one_node;
4566
4567       if (gfc_option.warn_array_temp)
4568         gfc_warning ("Creating array temporary at %L", &loc);
4569     }
4570
4571   /* This is for the case where the array data is used directly without
4572      calling the repack function.  */
4573   if (no_repack || partial != NULL_TREE)
4574     stmt_packed = gfc_conv_descriptor_data_get (dumdesc);
4575   else
4576     stmt_packed = NULL_TREE;
4577
4578   /* Assign the data pointer.  */
4579   if (stmt_packed != NULL_TREE && stmt_unpacked != NULL_TREE)
4580     {
4581       /* Don't repack unknown shape arrays when the first stride is 1.  */
4582       tmp = fold_build3 (COND_EXPR, TREE_TYPE (stmt_packed),
4583                          partial, stmt_packed, stmt_unpacked);
4584     }
4585   else
4586     tmp = stmt_packed != NULL_TREE ? stmt_packed : stmt_unpacked;
4587   gfc_add_modify (&block, tmpdesc, fold_convert (type, tmp));
4588
4589   offset = gfc_index_zero_node;
4590   size = gfc_index_one_node;
4591
4592   /* Evaluate the bounds of the array.  */
4593   for (n = 0; n < sym->as->rank; n++)
4594     {
4595       if (checkparm || !sym->as->upper[n])
4596         {
4597           /* Get the bounds of the actual parameter.  */
4598           dubound = gfc_conv_descriptor_ubound_get (dumdesc, gfc_rank_cst[n]);
4599           dlbound = gfc_conv_descriptor_lbound_get (dumdesc, gfc_rank_cst[n]);
4600         }
4601       else
4602         {
4603           dubound = NULL_TREE;
4604           dlbound = NULL_TREE;
4605         }
4606
4607       lbound = GFC_TYPE_ARRAY_LBOUND (type, n);
4608       if (!INTEGER_CST_P (lbound))
4609         {
4610           gfc_init_se (&se, NULL);
4611           gfc_conv_expr_type (&se, sym->as->lower[n],
4612                               gfc_array_index_type);
4613           gfc_add_block_to_block (&block, &se.pre);
4614           gfc_add_modify (&block, lbound, se.expr);
4615         }
4616
4617       ubound = GFC_TYPE_ARRAY_UBOUND (type, n);
4618       /* Set the desired upper bound.  */
4619       if (sym->as->upper[n])
4620         {
4621           /* We know what we want the upper bound to be.  */
4622           if (!INTEGER_CST_P (ubound))
4623             {
4624               gfc_init_se (&se, NULL);
4625               gfc_conv_expr_type (&se, sym->as->upper[n],
4626                                   gfc_array_index_type);
4627               gfc_add_block_to_block (&block, &se.pre);
4628               gfc_add_modify (&block, ubound, se.expr);
4629             }
4630
4631           /* Check the sizes match.  */
4632           if (checkparm)
4633             {
4634               /* Check (ubound(a) - lbound(a) == ubound(b) - lbound(b)).  */
4635               char * msg;
4636
4637               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4638                                  ubound, lbound);
4639               stride2 = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4640                                      dubound, dlbound);
4641               tmp = fold_build2 (NE_EXPR, gfc_array_index_type, tmp, stride2);
4642               asprintf (&msg, "%s for dimension %d of array '%s'",
4643                         gfc_msg_bounds, n+1, sym->name);
4644               gfc_trans_runtime_check (true, false, tmp, &block, &loc, msg);
4645               gfc_free (msg);
4646             }
4647         }
4648       else
4649         {
4650           /* For assumed shape arrays move the upper bound by the same amount
4651              as the lower bound.  */
4652           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4653                              dubound, dlbound);
4654           tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type, tmp, lbound);
4655           gfc_add_modify (&block, ubound, tmp);
4656         }
4657       /* The offset of this dimension.  offset = offset - lbound * stride.  */
4658       tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, lbound, stride);
4659       offset = fold_build2 (MINUS_EXPR, gfc_array_index_type, offset, tmp);
4660
4661       /* The size of this dimension, and the stride of the next.  */
4662       if (n + 1 < sym->as->rank)
4663         {
4664           stride = GFC_TYPE_ARRAY_STRIDE (type, n + 1);
4665
4666           if (no_repack || partial != NULL_TREE)
4667             {
4668               stmt_unpacked =
4669                 gfc_conv_descriptor_stride_get (dumdesc, gfc_rank_cst[n+1]);
4670             }
4671
4672           /* Figure out the stride if not a known constant.  */
4673           if (!INTEGER_CST_P (stride))
4674             {
4675               if (no_repack)
4676                 stmt_packed = NULL_TREE;
4677               else
4678                 {
4679                   /* Calculate stride = size * (ubound + 1 - lbound).  */
4680                   tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4681                                      gfc_index_one_node, lbound);
4682                   tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
4683                                      ubound, tmp);
4684                   size = fold_build2 (MULT_EXPR, gfc_array_index_type,
4685                                       size, tmp);
4686                   stmt_packed = size;
4687                 }
4688
4689               /* Assign the stride.  */
4690               if (stmt_packed != NULL_TREE && stmt_unpacked != NULL_TREE)
4691                 tmp = fold_build3 (COND_EXPR, gfc_array_index_type, partial,
4692                                    stmt_unpacked, stmt_packed);
4693               else
4694                 tmp = (stmt_packed != NULL_TREE) ? stmt_packed : stmt_unpacked;
4695               gfc_add_modify (&block, stride, tmp);
4696             }
4697         }
4698       else
4699         {
4700           stride = GFC_TYPE_ARRAY_SIZE (type);
4701
4702           if (stride && !INTEGER_CST_P (stride))
4703             {
4704               /* Calculate size = stride * (ubound + 1 - lbound).  */
4705               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
4706                                  gfc_index_one_node, lbound);
4707               tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
4708                                  ubound, tmp);
4709               tmp = fold_build2 (MULT_EXPR, gfc_array_index_type,
4710                                  GFC_TYPE_ARRAY_STRIDE (type, n), tmp);
4711               gfc_add_modify (&block, stride, tmp);
4712             }
4713         }
4714     }
4715
4716   /* Set the offset.  */
4717   if (TREE_CODE (GFC_TYPE_ARRAY_OFFSET (type)) == VAR_DECL)
4718     gfc_add_modify (&block, GFC_TYPE_ARRAY_OFFSET (type), offset);
4719
4720   gfc_trans_vla_type_sizes (sym, &block);
4721
4722   stmt = gfc_finish_block (&block);
4723
4724   gfc_start_block (&block);
4725
4726   /* Only do the entry/initialization code if the arg is present.  */
4727   dumdesc = GFC_DECL_SAVED_DESCRIPTOR (tmpdesc);
4728   optional_arg = (sym->attr.optional
4729                   || (sym->ns->proc_name->attr.entry_master
4730                       && sym->attr.dummy));
4731   if (optional_arg)
4732     {
4733       tmp = gfc_conv_expr_present (sym);
4734       stmt = build3_v (COND_EXPR, tmp, stmt, build_empty_stmt (input_location));
4735     }
4736   gfc_add_expr_to_block (&block, stmt);
4737
4738   /* Add the main function body.  */
4739   gfc_add_expr_to_block (&block, body);
4740
4741   /* Cleanup code.  */
4742   if (!no_repack)
4743     {
4744       gfc_start_block (&cleanup);
4745       
4746       if (sym->attr.intent != INTENT_IN)
4747         {
4748           /* Copy the data back.  */
4749           tmp = build_call_expr_loc (input_location,
4750                                  gfor_fndecl_in_unpack, 2, dumdesc, tmpdesc);
4751           gfc_add_expr_to_block (&cleanup, tmp);
4752         }
4753
4754       /* Free the temporary.  */
4755       tmp = gfc_call_free (tmpdesc);
4756       gfc_add_expr_to_block (&cleanup, tmp);
4757
4758       stmt = gfc_finish_block (&cleanup);
4759         
4760       /* Only do the cleanup if the array was repacked.  */
4761       tmp = build_fold_indirect_ref_loc (input_location,
4762                                      dumdesc);
4763       tmp = gfc_conv_descriptor_data_get (tmp);
4764       tmp = fold_build2 (NE_EXPR, boolean_type_node, tmp, tmpdesc);
4765       stmt = build3_v (COND_EXPR, tmp, stmt, build_empty_stmt (input_location));
4766
4767       if (optional_arg)
4768         {
4769           tmp = gfc_conv_expr_present (sym);
4770           stmt = build3_v (COND_EXPR, tmp, stmt,
4771                            build_empty_stmt (input_location));
4772         }
4773       gfc_add_expr_to_block (&block, stmt);
4774     }
4775   /* We don't need to free any memory allocated by internal_pack as it will
4776      be freed at the end of the function by pop_context.  */
4777   return gfc_finish_block (&block);
4778 }
4779
4780
4781 /* Calculate the overall offset, including subreferences.  */
4782 static void
4783 gfc_get_dataptr_offset (stmtblock_t *block, tree parm, tree desc, tree offset,
4784                         bool subref, gfc_expr *expr)
4785 {
4786   tree tmp;
4787   tree field;
4788   tree stride;
4789   tree index;
4790   gfc_ref *ref;
4791   gfc_se start;
4792   int n;
4793
4794   /* If offset is NULL and this is not a subreferenced array, there is
4795      nothing to do.  */
4796   if (offset == NULL_TREE)
4797     {
4798       if (subref)
4799         offset = gfc_index_zero_node;
4800       else
4801         return;
4802     }
4803
4804   tmp = gfc_conv_array_data (desc);
4805   tmp = build_fold_indirect_ref_loc (input_location,
4806                                  tmp);
4807   tmp = gfc_build_array_ref (tmp, offset, NULL);
4808
4809   /* Offset the data pointer for pointer assignments from arrays with
4810      subreferences; e.g. my_integer => my_type(:)%integer_component.  */
4811   if (subref)
4812     {
4813       /* Go past the array reference.  */
4814       for (ref = expr->ref; ref; ref = ref->next)
4815         if (ref->type == REF_ARRAY &&
4816               ref->u.ar.type != AR_ELEMENT)
4817           {
4818             ref = ref->next;
4819             break;
4820           }
4821
4822       /* Calculate the offset for each subsequent subreference.  */
4823       for (; ref; ref = ref->next)
4824         {
4825           switch (ref->type)
4826             {
4827             case REF_COMPONENT:
4828               field = ref->u.c.component->backend_decl;
4829               gcc_assert (field && TREE_CODE (field) == FIELD_DECL);
4830               tmp = fold_build3 (COMPONENT_REF, TREE_TYPE (field),
4831                                  tmp, field, NULL_TREE);
4832               break;
4833
4834             case REF_SUBSTRING:
4835               gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == ARRAY_TYPE);
4836               gfc_init_se (&start, NULL);
4837               gfc_conv_expr_type (&start, ref->u.ss.start, gfc_charlen_type_node);
4838               gfc_add_block_to_block (block, &start.pre);
4839               tmp = gfc_build_array_ref (tmp, start.expr, NULL);
4840               break;
4841
4842             case REF_ARRAY:
4843               gcc_assert (TREE_CODE (TREE_TYPE (tmp)) == ARRAY_TYPE
4844                             && ref->u.ar.type == AR_ELEMENT);
4845
4846               /* TODO - Add bounds checking.  */
4847               stride = gfc_index_one_node;
4848               index = gfc_index_zero_node;
4849               for (n = 0; n < ref->u.ar.dimen; n++)
4850                 {
4851                   tree itmp;
4852                   tree jtmp;
4853
4854                   /* Update the index.  */
4855                   gfc_init_se (&start, NULL);
4856                   gfc_conv_expr_type (&start, ref->u.ar.start[n], gfc_array_index_type);
4857                   itmp = gfc_evaluate_now (start.expr, block);
4858                   gfc_init_se (&start, NULL);
4859                   gfc_conv_expr_type (&start, ref->u.ar.as->lower[n], gfc_array_index_type);
4860                   jtmp = gfc_evaluate_now (start.expr, block);
4861                   itmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, itmp, jtmp);
4862                   itmp = fold_build2 (MULT_EXPR, gfc_array_index_type, itmp, stride);
4863                   index = fold_build2 (PLUS_EXPR, gfc_array_index_type, itmp, index);
4864                   index = gfc_evaluate_now (index, block);
4865
4866                   /* Update the stride.  */
4867                   gfc_init_se (&start, NULL);
4868                   gfc_conv_expr_type (&start, ref->u.ar.as->upper[n], gfc_array_index_type);
4869                   itmp =  fold_build2 (MINUS_EXPR, gfc_array_index_type, start.expr, jtmp);
4870                   itmp =  fold_build2 (PLUS_EXPR, gfc_array_index_type,
4871                                        gfc_index_one_node, itmp);
4872                   stride =  fold_build2 (MULT_EXPR, gfc_array_index_type, stride, itmp);
4873                   stride = gfc_evaluate_now (stride, block);
4874                 }
4875
4876               /* Apply the index to obtain the array element.  */
4877               tmp = gfc_build_array_ref (tmp, index, NULL);
4878               break;
4879
4880             default:
4881               gcc_unreachable ();
4882               break;
4883             }
4884         }
4885     }
4886
4887   /* Set the target data pointer.  */
4888   offset = gfc_build_addr_expr (gfc_array_dataptr_type (desc), tmp);
4889   gfc_conv_descriptor_data_set (block, parm, offset);
4890 }
4891
4892
4893 /* gfc_conv_expr_descriptor needs the string length an expression
4894    so that the size of the temporary can be obtained.  This is done
4895    by adding up the string lengths of all the elements in the
4896    expression.  Function with non-constant expressions have their
4897    string lengths mapped onto the actual arguments using the
4898    interface mapping machinery in trans-expr.c.  */
4899 static void
4900 get_array_charlen (gfc_expr *expr, gfc_se *se)
4901 {
4902   gfc_interface_mapping mapping;
4903   gfc_formal_arglist *formal;
4904   gfc_actual_arglist *arg;
4905   gfc_se tse;
4906
4907   if (expr->ts.u.cl->length
4908         && gfc_is_constant_expr (expr->ts.u.cl->length))
4909     {
4910       if (!expr->ts.u.cl->backend_decl)
4911         gfc_conv_string_length (expr->ts.u.cl, expr, &se->pre);
4912       return;
4913     }
4914
4915   switch (expr->expr_type)
4916     {
4917     case EXPR_OP:
4918       get_array_charlen (expr->value.op.op1, se);
4919
4920       /* For parentheses the expression ts.u.cl is identical.  */
4921       if (expr->value.op.op == INTRINSIC_PARENTHESES)
4922         return;
4923
4924      expr->ts.u.cl->backend_decl =
4925                 gfc_create_var (gfc_charlen_type_node, "sln");
4926
4927       if (expr->value.op.op2)
4928         {
4929           get_array_charlen (expr->value.op.op2, se);
4930
4931           gcc_assert (expr->value.op.op == INTRINSIC_CONCAT);
4932
4933           /* Add the string lengths and assign them to the expression
4934              string length backend declaration.  */
4935           gfc_add_modify (&se->pre, expr->ts.u.cl->backend_decl,
4936                           fold_build2 (PLUS_EXPR, gfc_charlen_type_node,
4937                                 expr->value.op.op1->ts.u.cl->backend_decl,
4938                                 expr->value.op.op2->ts.u.cl->backend_decl));
4939         }
4940       else
4941         gfc_add_modify (&se->pre, expr->ts.u.cl->backend_decl,
4942                         expr->value.op.op1->ts.u.cl->backend_decl);
4943       break;
4944
4945     case EXPR_FUNCTION:
4946       if (expr->value.function.esym == NULL
4947             || expr->ts.u.cl->length->expr_type == EXPR_CONSTANT)
4948         {
4949           gfc_conv_string_length (expr->ts.u.cl, expr, &se->pre);
4950           break;
4951         }
4952
4953       /* Map expressions involving the dummy arguments onto the actual
4954          argument expressions.  */
4955       gfc_init_interface_mapping (&mapping);
4956       formal = expr->symtree->n.sym->formal;
4957       arg = expr->value.function.actual;
4958
4959       /* Set se = NULL in the calls to the interface mapping, to suppress any
4960          backend stuff.  */
4961       for (; arg != NULL; arg = arg->next, formal = formal ? formal->next : NULL)
4962         {
4963           if (!arg->expr)
4964             continue;
4965           if (formal->sym)
4966           gfc_add_interface_mapping (&mapping, formal->sym, NULL, arg->expr);
4967         }
4968
4969       gfc_init_se (&tse, NULL);
4970
4971       /* Build the expression for the character length and convert it.  */
4972       gfc_apply_interface_mapping (&mapping, &tse, expr->ts.u.cl->length);
4973
4974       gfc_add_block_to_block (&se->pre, &tse.pre);
4975       gfc_add_block_to_block (&se->post, &tse.post);
4976       tse.expr = fold_convert (gfc_charlen_type_node, tse.expr);
4977       tse.expr = fold_build2 (MAX_EXPR, gfc_charlen_type_node, tse.expr,
4978                               build_int_cst (gfc_charlen_type_node, 0));
4979       expr->ts.u.cl->backend_decl = tse.expr;
4980       gfc_free_interface_mapping (&mapping);
4981       break;
4982
4983     default:
4984       gfc_conv_string_length (expr->ts.u.cl, expr, &se->pre);
4985       break;
4986     }
4987 }
4988
4989
4990
4991 /* Convert an array for passing as an actual argument.  Expressions and
4992    vector subscripts are evaluated and stored in a temporary, which is then
4993    passed.  For whole arrays the descriptor is passed.  For array sections
4994    a modified copy of the descriptor is passed, but using the original data.
4995
4996    This function is also used for array pointer assignments, and there
4997    are three cases:
4998
4999      - se->want_pointer && !se->direct_byref
5000          EXPR is an actual argument.  On exit, se->expr contains a
5001          pointer to the array descriptor.
5002
5003      - !se->want_pointer && !se->direct_byref
5004          EXPR is an actual argument to an intrinsic function or the
5005          left-hand side of a pointer assignment.  On exit, se->expr
5006          contains the descriptor for EXPR.
5007
5008      - !se->want_pointer && se->direct_byref
5009          EXPR is the right-hand side of a pointer assignment and
5010          se->expr is the descriptor for the previously-evaluated
5011          left-hand side.  The function creates an assignment from
5012          EXPR to se->expr.  */
5013
5014 void
5015 gfc_conv_expr_descriptor (gfc_se * se, gfc_expr * expr, gfc_ss * ss)
5016 {
5017   gfc_loopinfo loop;
5018   gfc_ss *secss;
5019   gfc_ss_info *info;
5020   int need_tmp;
5021   int n;
5022   tree tmp;
5023   tree desc;
5024   stmtblock_t block;
5025   tree start;
5026   tree offset;
5027   int full;
5028   bool subref_array_target = false;
5029
5030   gcc_assert (ss != gfc_ss_terminator);
5031
5032   /* Special case things we know we can pass easily.  */
5033   switch (expr->expr_type)
5034     {
5035     case EXPR_VARIABLE:
5036       /* If we have a linear array section, we can pass it directly.
5037          Otherwise we need to copy it into a temporary.  */
5038
5039       /* Find the SS for the array section.  */
5040       secss = ss;
5041       while (secss != gfc_ss_terminator && secss->type != GFC_SS_SECTION)
5042         secss = secss->next;
5043
5044       gcc_assert (secss != gfc_ss_terminator);
5045       info = &secss->data.info;
5046
5047       /* Get the descriptor for the array.  */
5048       gfc_conv_ss_descriptor (&se->pre, secss, 0);
5049       desc = info->descriptor;
5050
5051       subref_array_target = se->direct_byref && is_subref_array (expr);
5052       need_tmp = gfc_ref_needs_temporary_p (expr->ref)
5053                         && !subref_array_target;
5054
5055       if (need_tmp)
5056         full = 0;
5057       else if (GFC_ARRAY_TYPE_P (TREE_TYPE (desc)))
5058         {
5059           /* Create a new descriptor if the array doesn't have one.  */
5060           full = 0;
5061         }
5062       else if (info->ref->u.ar.type == AR_FULL)
5063         full = 1;
5064       else if (se->direct_byref)
5065         full = 0;
5066       else
5067         full = gfc_full_array_ref_p (info->ref, NULL);
5068
5069       if (full)
5070         {
5071           if (se->direct_byref)
5072             {
5073               /* Copy the descriptor for pointer assignments.  */
5074               gfc_add_modify (&se->pre, se->expr, desc);
5075
5076               /* Add any offsets from subreferences.  */
5077               gfc_get_dataptr_offset (&se->pre, se->expr, desc, NULL_TREE,
5078                                       subref_array_target, expr);
5079             }
5080           else if (se->want_pointer)
5081             {
5082               /* We pass full arrays directly.  This means that pointers and
5083                  allocatable arrays should also work.  */
5084               se->expr = gfc_build_addr_expr (NULL_TREE, desc);
5085             }
5086           else
5087             {
5088               se->expr = desc;
5089             }
5090
5091           if (expr->ts.type == BT_CHARACTER)
5092             se->string_length = gfc_get_expr_charlen (expr);
5093
5094           return;
5095         }
5096       break;
5097       
5098     case EXPR_FUNCTION:
5099       /* A transformational function return value will be a temporary
5100          array descriptor.  We still need to go through the scalarizer
5101          to create the descriptor.  Elemental functions ar handled as
5102          arbitrary expressions, i.e. copy to a temporary.  */
5103       secss = ss;
5104       /* Look for the SS for this function.  */
5105       while (secss != gfc_ss_terminator
5106              && (secss->type != GFC_SS_FUNCTION || secss->expr != expr))
5107         secss = secss->next;
5108
5109       if (se->direct_byref)
5110         {
5111           gcc_assert (secss != gfc_ss_terminator);
5112
5113           /* For pointer assignments pass the descriptor directly.  */
5114           se->ss = secss;
5115           se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
5116           gfc_conv_expr (se, expr);
5117           return;
5118         }
5119
5120       if (secss == gfc_ss_terminator)
5121         {
5122           /* Elemental function.  */
5123           need_tmp = 1;
5124           if (expr->ts.type == BT_CHARACTER
5125                 && expr->ts.u.cl->length->expr_type != EXPR_CONSTANT)
5126             get_array_charlen (expr, se);
5127
5128           info = NULL;
5129         }
5130       else
5131         {
5132           /* Transformational function.  */
5133           info = &secss->data.info;
5134           need_tmp = 0;
5135         }
5136       break;
5137
5138     case EXPR_ARRAY:
5139       /* Constant array constructors don't need a temporary.  */
5140       if (ss->type == GFC_SS_CONSTRUCTOR
5141           && expr->ts.type != BT_CHARACTER
5142           && gfc_constant_array_constructor_p (expr->value.constructor))
5143         {
5144           need_tmp = 0;
5145           info = &ss->data.info;
5146           secss = ss;
5147         }
5148       else
5149         {
5150           need_tmp = 1;
5151           secss = NULL;
5152           info = NULL;
5153         }
5154       break;
5155
5156     default:
5157       /* Something complicated.  Copy it into a temporary.  */
5158       need_tmp = 1;
5159       secss = NULL;
5160       info = NULL;
5161       break;
5162     }
5163
5164   gfc_init_loopinfo (&loop);
5165
5166   /* Associate the SS with the loop.  */
5167   gfc_add_ss_to_loop (&loop, ss);
5168
5169   /* Tell the scalarizer not to bother creating loop variables, etc.  */
5170   if (!need_tmp)
5171     loop.array_parameter = 1;
5172   else
5173     /* The right-hand side of a pointer assignment mustn't use a temporary.  */
5174     gcc_assert (!se->direct_byref);
5175
5176   /* Setup the scalarizing loops and bounds.  */
5177   gfc_conv_ss_startstride (&loop);
5178
5179   if (need_tmp)
5180     {
5181       /* Tell the scalarizer to make a temporary.  */
5182       loop.temp_ss = gfc_get_ss ();
5183       loop.temp_ss->type = GFC_SS_TEMP;
5184       loop.temp_ss->next = gfc_ss_terminator;
5185
5186       if (expr->ts.type == BT_CHARACTER
5187             && !expr->ts.u.cl->backend_decl)
5188         get_array_charlen (expr, se);
5189
5190       loop.temp_ss->data.temp.type = gfc_typenode_for_spec (&expr->ts);
5191
5192       if (expr->ts.type == BT_CHARACTER)
5193         loop.temp_ss->string_length = expr->ts.u.cl->backend_decl;
5194       else
5195         loop.temp_ss->string_length = NULL;
5196
5197       se->string_length = loop.temp_ss->string_length;
5198       loop.temp_ss->data.temp.dimen = loop.dimen;
5199       gfc_add_ss_to_loop (&loop, loop.temp_ss);
5200     }
5201
5202   gfc_conv_loop_setup (&loop, & expr->where);
5203
5204   if (need_tmp)
5205     {
5206       /* Copy into a temporary and pass that.  We don't need to copy the data
5207          back because expressions and vector subscripts must be INTENT_IN.  */
5208       /* TODO: Optimize passing function return values.  */
5209       gfc_se lse;
5210       gfc_se rse;
5211
5212       /* Start the copying loops.  */
5213       gfc_mark_ss_chain_used (loop.temp_ss, 1);
5214       gfc_mark_ss_chain_used (ss, 1);
5215       gfc_start_scalarized_body (&loop, &block);
5216
5217       /* Copy each data element.  */
5218       gfc_init_se (&lse, NULL);
5219       gfc_copy_loopinfo_to_se (&lse, &loop);
5220       gfc_init_se (&rse, NULL);
5221       gfc_copy_loopinfo_to_se (&rse, &loop);
5222
5223       lse.ss = loop.temp_ss;
5224       rse.ss = ss;
5225
5226       gfc_conv_scalarized_array_ref (&lse, NULL);
5227       if (expr->ts.type == BT_CHARACTER)
5228         {
5229           gfc_conv_expr (&rse, expr);
5230           if (POINTER_TYPE_P (TREE_TYPE (rse.expr)))
5231             rse.expr = build_fold_indirect_ref_loc (input_location,
5232                                                 rse.expr);
5233         }
5234       else
5235         gfc_conv_expr_val (&rse, expr);
5236
5237       gfc_add_block_to_block (&block, &rse.pre);
5238       gfc_add_block_to_block (&block, &lse.pre);
5239
5240       lse.string_length = rse.string_length;
5241       tmp = gfc_trans_scalar_assign (&lse, &rse, expr->ts, true,
5242                                      expr->expr_type == EXPR_VARIABLE, true);
5243       gfc_add_expr_to_block (&block, tmp);
5244
5245       /* Finish the copying loops.  */
5246       gfc_trans_scalarizing_loops (&loop, &block);
5247
5248       desc = loop.temp_ss->data.info.descriptor;
5249
5250       gcc_assert (is_gimple_lvalue (desc));
5251     }
5252   else if (expr->expr_type == EXPR_FUNCTION)
5253     {
5254       desc = info->descriptor;
5255       se->string_length = ss->string_length;
5256     }
5257   else
5258     {
5259       /* We pass sections without copying to a temporary.  Make a new
5260          descriptor and point it at the section we want.  The loop variable
5261          limits will be the limits of the section.
5262          A function may decide to repack the array to speed up access, but
5263          we're not bothered about that here.  */
5264       int dim, ndim;
5265       tree parm;
5266       tree parmtype;
5267       tree stride;
5268       tree from;
5269       tree to;
5270       tree base;
5271
5272       /* Set the string_length for a character array.  */
5273       if (expr->ts.type == BT_CHARACTER)
5274         se->string_length =  gfc_get_expr_charlen (expr);
5275
5276       desc = info->descriptor;
5277       gcc_assert (secss && secss != gfc_ss_terminator);
5278       if (se->direct_byref)
5279         {
5280           /* For pointer assignments we fill in the destination.  */
5281           parm = se->expr;
5282           parmtype = TREE_TYPE (parm);
5283         }
5284       else
5285         {
5286           /* Otherwise make a new one.  */
5287           parmtype = gfc_get_element_type (TREE_TYPE (desc));
5288           parmtype = gfc_get_array_type_bounds (parmtype, loop.dimen,
5289                                                 loop.from, loop.to, 0,
5290                                                 GFC_ARRAY_UNKNOWN, false);
5291           parm = gfc_create_var (parmtype, "parm");
5292         }
5293
5294       offset = gfc_index_zero_node;
5295       dim = 0;
5296
5297       /* The following can be somewhat confusing.  We have two
5298          descriptors, a new one and the original array.
5299          {parm, parmtype, dim} refer to the new one.
5300          {desc, type, n, secss, loop} refer to the original, which maybe
5301          a descriptorless array.
5302          The bounds of the scalarization are the bounds of the section.
5303          We don't have to worry about numeric overflows when calculating
5304          the offsets because all elements are within the array data.  */
5305
5306       /* Set the dtype.  */
5307       tmp = gfc_conv_descriptor_dtype (parm);
5308       gfc_add_modify (&loop.pre, tmp, gfc_get_dtype (parmtype));
5309
5310       /* Set offset for assignments to pointer only to zero if it is not
5311          the full array.  */
5312       if (se->direct_byref
5313           && info->ref && info->ref->u.ar.type != AR_FULL)
5314         base = gfc_index_zero_node;
5315       else if (GFC_ARRAY_TYPE_P (TREE_TYPE (desc)))
5316         base = gfc_evaluate_now (gfc_conv_array_offset (desc), &loop.pre);
5317       else
5318         base = NULL_TREE;
5319
5320       ndim = info->ref ? info->ref->u.ar.dimen : info->dimen;
5321       for (n = 0; n < ndim; n++)
5322         {
5323           stride = gfc_conv_array_stride (desc, n);
5324
5325           /* Work out the offset.  */
5326           if (info->ref
5327               && info->ref->u.ar.dimen_type[n] == DIMEN_ELEMENT)
5328             {
5329               gcc_assert (info->subscript[n]
5330                       && info->subscript[n]->type == GFC_SS_SCALAR);
5331               start = info->subscript[n]->data.scalar.expr;
5332             }
5333           else
5334             {
5335               /* Check we haven't somehow got out of sync.  */
5336               gcc_assert (info->dim[dim] == n);
5337
5338               /* Evaluate and remember the start of the section.  */
5339               start = info->start[dim];
5340               stride = gfc_evaluate_now (stride, &loop.pre);
5341             }
5342
5343           tmp = gfc_conv_array_lbound (desc, n);
5344           tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (tmp), start, tmp);
5345
5346           tmp = fold_build2 (MULT_EXPR, TREE_TYPE (tmp), tmp, stride);
5347           offset = fold_build2 (PLUS_EXPR, TREE_TYPE (tmp), offset, tmp);
5348
5349           if (info->ref
5350               && info->ref->u.ar.dimen_type[n] == DIMEN_ELEMENT)
5351             {
5352               /* For elemental dimensions, we only need the offset.  */
5353               continue;
5354             }
5355
5356           /* Vector subscripts need copying and are handled elsewhere.  */
5357           if (info->ref)
5358             gcc_assert (info->ref->u.ar.dimen_type[n] == DIMEN_RANGE);
5359
5360           /* Set the new lower bound.  */
5361           from = loop.from[dim];
5362           to = loop.to[dim];
5363
5364           /* If we have an array section or are assigning make sure that
5365              the lower bound is 1.  References to the full
5366              array should otherwise keep the original bounds.  */
5367           if ((!info->ref
5368                   || info->ref->u.ar.type != AR_FULL)
5369               && !integer_onep (from))
5370             {
5371               tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
5372                                  gfc_index_one_node, from);
5373               to = fold_build2 (PLUS_EXPR, gfc_array_index_type, to, tmp);
5374               from = gfc_index_one_node;
5375             }
5376           gfc_conv_descriptor_lbound_set (&loop.pre, parm,
5377                                           gfc_rank_cst[dim], from);
5378
5379           /* Set the new upper bound.  */
5380           gfc_conv_descriptor_ubound_set (&loop.pre, parm,
5381                                           gfc_rank_cst[dim], to);
5382
5383           /* Multiply the stride by the section stride to get the
5384              total stride.  */
5385           stride = fold_build2 (MULT_EXPR, gfc_array_index_type,
5386                                 stride, info->stride[dim]);
5387
5388           if (se->direct_byref
5389                 && info->ref
5390                 && info->ref->u.ar.type != AR_FULL)
5391             {
5392               base = fold_build2 (MINUS_EXPR, TREE_TYPE (base),
5393                                   base, stride);
5394             }
5395           else if (GFC_ARRAY_TYPE_P (TREE_TYPE (desc)))
5396             {
5397               tmp = gfc_conv_array_lbound (desc, n);
5398               tmp = fold_build2 (MINUS_EXPR, TREE_TYPE (base),
5399                                  tmp, loop.from[dim]);
5400               tmp = fold_build2 (MULT_EXPR, TREE_TYPE (base),
5401                                  tmp, gfc_conv_array_stride (desc, n));
5402               base = fold_build2 (PLUS_EXPR, TREE_TYPE (base),
5403                                   tmp, base);
5404             }
5405
5406           /* Store the new stride.  */
5407           gfc_conv_descriptor_stride_set (&loop.pre, parm,
5408                                           gfc_rank_cst[dim], stride);
5409
5410           dim++;
5411         }
5412
5413       if (se->data_not_needed)
5414         gfc_conv_descriptor_data_set (&loop.pre, parm,
5415                                       gfc_index_zero_node);
5416       else
5417         /* Point the data pointer at the 1st element in the section.  */
5418         gfc_get_dataptr_offset (&loop.pre, parm, desc, offset,
5419                                 subref_array_target, expr);
5420
5421       if ((se->direct_byref || GFC_ARRAY_TYPE_P (TREE_TYPE (desc)))
5422           && !se->data_not_needed)
5423         {
5424           /* Set the offset.  */
5425           gfc_conv_descriptor_offset_set (&loop.pre, parm, base);
5426         }
5427       else
5428         {
5429           /* Only the callee knows what the correct offset it, so just set
5430              it to zero here.  */
5431           gfc_conv_descriptor_offset_set (&loop.pre, parm, gfc_index_zero_node);
5432         }
5433       desc = parm;
5434     }
5435
5436   if (!se->direct_byref)
5437     {
5438       /* Get a pointer to the new descriptor.  */
5439       if (se->want_pointer)
5440         se->expr = gfc_build_addr_expr (NULL_TREE, desc);
5441       else
5442         se->expr = desc;
5443     }
5444
5445   gfc_add_block_to_block (&se->pre, &loop.pre);
5446   gfc_add_block_to_block (&se->post, &loop.post);
5447
5448   /* Cleanup the scalarizer.  */
5449   gfc_cleanup_loop (&loop);
5450 }
5451
5452 /* Helper function for gfc_conv_array_parameter if array size needs to be
5453    computed.  */
5454
5455 static void
5456 array_parameter_size (tree desc, gfc_expr *expr, tree *size)
5457 {
5458   tree elem;
5459   if (GFC_ARRAY_TYPE_P (TREE_TYPE (desc)))
5460     *size = GFC_TYPE_ARRAY_SIZE (TREE_TYPE (desc));
5461   else if (expr->rank > 1)
5462     *size = build_call_expr_loc (input_location,
5463                              gfor_fndecl_size0, 1,
5464                              gfc_build_addr_expr (NULL, desc));
5465   else
5466     {
5467       tree ubound = gfc_conv_descriptor_ubound_get (desc, gfc_index_zero_node);
5468       tree lbound = gfc_conv_descriptor_lbound_get (desc, gfc_index_zero_node);
5469
5470       *size = fold_build2 (MINUS_EXPR, gfc_array_index_type, ubound, lbound);
5471       *size = fold_build2 (PLUS_EXPR, gfc_array_index_type, *size,
5472                            gfc_index_one_node);
5473       *size = fold_build2 (MAX_EXPR, gfc_array_index_type, *size,
5474                            gfc_index_zero_node);
5475     }
5476   elem = TYPE_SIZE_UNIT (gfc_get_element_type (TREE_TYPE (desc)));
5477   *size = fold_build2 (MULT_EXPR, gfc_array_index_type, *size,
5478                        fold_convert (gfc_array_index_type, elem));
5479 }
5480
5481 /* Convert an array for passing as an actual parameter.  */
5482 /* TODO: Optimize passing g77 arrays.  */
5483
5484 void
5485 gfc_conv_array_parameter (gfc_se * se, gfc_expr * expr, gfc_ss * ss, bool g77,
5486                           const gfc_symbol *fsym, const char *proc_name,
5487                           tree *size)
5488 {
5489   tree ptr;
5490   tree desc;
5491   tree tmp = NULL_TREE;
5492   tree stmt;
5493   tree parent = DECL_CONTEXT (current_function_decl);
5494   bool full_array_var;
5495   bool this_array_result;
5496   bool contiguous;
5497   bool no_pack;
5498   bool array_constructor;
5499   bool good_allocatable;
5500   bool ultimate_ptr_comp;
5501   bool ultimate_alloc_comp;
5502   gfc_symbol *sym;
5503   stmtblock_t block;
5504   gfc_ref *ref;
5505
5506   ultimate_ptr_comp = false;
5507   ultimate_alloc_comp = false;
5508   for (ref = expr->ref; ref; ref = ref->next)
5509     {
5510       if (ref->next == NULL)
5511         break;
5512
5513       if (ref->type == REF_COMPONENT)
5514         {
5515           ultimate_ptr_comp = ref->u.c.component->attr.pointer;
5516           ultimate_alloc_comp = ref->u.c.component->attr.allocatable;
5517         }
5518     }
5519
5520   full_array_var = false;
5521   contiguous = false;
5522
5523   if (expr->expr_type == EXPR_VARIABLE && ref && !ultimate_ptr_comp)
5524     full_array_var = gfc_full_array_ref_p (ref, &contiguous);
5525
5526   sym = full_array_var ? expr->symtree->n.sym : NULL;
5527
5528   /* The symbol should have an array specification.  */
5529   gcc_assert (!sym || sym->as || ref->u.ar.as);
5530
5531   if (expr->expr_type == EXPR_ARRAY && expr->ts.type == BT_CHARACTER)
5532     {
5533       get_array_ctor_strlen (&se->pre, expr->value.constructor, &tmp);
5534       expr->ts.u.cl->backend_decl = tmp;
5535       se->string_length = tmp;
5536     }
5537
5538   /* Is this the result of the enclosing procedure?  */
5539   this_array_result = (full_array_var && sym->attr.flavor == FL_PROCEDURE);
5540   if (this_array_result
5541         && (sym->backend_decl != current_function_decl)
5542         && (sym->backend_decl != parent))
5543     this_array_result = false;
5544
5545   /* Passing address of the array if it is not pointer or assumed-shape.  */
5546   if (full_array_var && g77 && !this_array_result)
5547     {
5548       tmp = gfc_get_symbol_decl (sym);
5549
5550       if (sym->ts.type == BT_CHARACTER)
5551         se->string_length = sym->ts.u.cl->backend_decl;
5552
5553       if (sym->ts.type == BT_DERIVED)
5554         {
5555           gfc_conv_expr_descriptor (se, expr, ss);
5556           se->expr = gfc_conv_array_data (se->expr);
5557           return;
5558         }
5559
5560       if (!sym->attr.pointer
5561             && sym->as
5562             && sym->as->type != AS_ASSUMED_SHAPE 
5563             && !sym->attr.allocatable)
5564         {
5565           /* Some variables are declared directly, others are declared as
5566              pointers and allocated on the heap.  */
5567           if (sym->attr.dummy || POINTER_TYPE_P (TREE_TYPE (tmp)))
5568             se->expr = tmp;
5569           else
5570             se->expr = gfc_build_addr_expr (NULL_TREE, tmp);
5571           if (size)
5572             array_parameter_size (tmp, expr, size);
5573           return;
5574         }
5575
5576       if (sym->attr.allocatable)
5577         {
5578           if (sym->attr.dummy || sym->attr.result)
5579             {
5580               gfc_conv_expr_descriptor (se, expr, ss);
5581               tmp = se->expr;
5582             }
5583           if (size)
5584             array_parameter_size (tmp, expr, size);
5585           se->expr = gfc_conv_array_data (tmp);
5586           return;
5587         }
5588     }
5589
5590   /* A convenient reduction in scope.  */
5591   contiguous = g77 && !this_array_result && contiguous;
5592
5593   /* There is no need to pack and unpack the array, if it is contiguous
5594      and not deferred or assumed shape.  */
5595   no_pack = ((sym && sym->as
5596                   && !sym->attr.pointer
5597                   && sym->as->type != AS_DEFERRED
5598                   && sym->as->type != AS_ASSUMED_SHAPE)
5599                       ||
5600              (ref && ref->u.ar.as
5601                   && ref->u.ar.as->type != AS_DEFERRED
5602                   && ref->u.ar.as->type != AS_ASSUMED_SHAPE));
5603
5604   no_pack = contiguous && no_pack;
5605
5606   /* Array constructors are always contiguous and do not need packing.  */
5607   array_constructor = g77 && !this_array_result && expr->expr_type == EXPR_ARRAY;
5608
5609   /* Same is true of contiguous sections from allocatable variables.  */
5610   good_allocatable = contiguous
5611                        && expr->symtree
5612                        && expr->symtree->n.sym->attr.allocatable;
5613
5614   /* Or ultimate allocatable components.  */
5615   ultimate_alloc_comp = contiguous && ultimate_alloc_comp; 
5616
5617   if (no_pack || array_constructor || good_allocatable || ultimate_alloc_comp)
5618     {
5619       gfc_conv_expr_descriptor (se, expr, ss);
5620       if (expr->ts.type == BT_CHARACTER)
5621         se->string_length = expr->ts.u.cl->backend_decl;
5622       if (size)
5623         array_parameter_size (se->expr, expr, size);
5624       se->expr = gfc_conv_array_data (se->expr);
5625       return;
5626     }
5627
5628   if (this_array_result)
5629     {
5630       /* Result of the enclosing function.  */
5631       gfc_conv_expr_descriptor (se, expr, ss);
5632       if (size)
5633         array_parameter_size (se->expr, expr, size);
5634       se->expr = gfc_build_addr_expr (NULL_TREE, se->expr);
5635
5636       if (g77 && TREE_TYPE (TREE_TYPE (se->expr)) != NULL_TREE
5637               && GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (TREE_TYPE (se->expr))))
5638         se->expr = gfc_conv_array_data (build_fold_indirect_ref_loc (input_location,
5639                                                                  se->expr));
5640
5641       return;
5642     }
5643   else
5644     {
5645       /* Every other type of array.  */
5646       se->want_pointer = 1;
5647       gfc_conv_expr_descriptor (se, expr, ss);
5648       if (size)
5649         array_parameter_size (build_fold_indirect_ref_loc (input_location,
5650                                                        se->expr),
5651                                   expr, size);
5652     }
5653
5654   /* Deallocate the allocatable components of structures that are
5655      not variable.  */
5656   if (expr->ts.type == BT_DERIVED
5657         && expr->ts.u.derived->attr.alloc_comp
5658         && expr->expr_type != EXPR_VARIABLE)
5659     {
5660       tmp = build_fold_indirect_ref_loc (input_location,
5661                                      se->expr);
5662       tmp = gfc_deallocate_alloc_comp (expr->ts.u.derived, tmp, expr->rank);
5663       gfc_add_expr_to_block (&se->post, tmp);
5664     }
5665
5666   if (g77)
5667     {
5668       desc = se->expr;
5669       /* Repack the array.  */
5670       if (gfc_option.warn_array_temp)
5671         {
5672           if (fsym)
5673             gfc_warning ("Creating array temporary at %L for argument '%s'",
5674                          &expr->where, fsym->name);
5675           else
5676             gfc_warning ("Creating array temporary at %L", &expr->where);
5677         }
5678
5679       ptr = build_call_expr_loc (input_location,
5680                              gfor_fndecl_in_pack, 1, desc);
5681
5682       if (fsym && fsym->attr.optional && sym && sym->attr.optional)
5683         {
5684           tmp = gfc_conv_expr_present (sym);
5685           ptr = build3 (COND_EXPR, TREE_TYPE (se->expr), tmp,
5686                         fold_convert (TREE_TYPE (se->expr), ptr),
5687                         fold_convert (TREE_TYPE (se->expr), null_pointer_node));
5688         }
5689
5690       ptr = gfc_evaluate_now (ptr, &se->pre);
5691
5692       se->expr = ptr;
5693
5694       if (gfc_option.rtcheck & GFC_RTCHECK_ARRAY_TEMPS)
5695         {
5696           char * msg;
5697
5698           if (fsym && proc_name)
5699             asprintf (&msg, "An array temporary was created for argument "
5700                       "'%s' of procedure '%s'", fsym->name, proc_name);
5701           else
5702             asprintf (&msg, "An array temporary was created");
5703
5704           tmp = build_fold_indirect_ref_loc (input_location,
5705                                          desc);
5706           tmp = gfc_conv_array_data (tmp);
5707           tmp = fold_build2 (NE_EXPR, boolean_type_node,
5708                              fold_convert (TREE_TYPE (tmp), ptr), tmp);
5709
5710           if (fsym && fsym->attr.optional && sym && sym->attr.optional)
5711             tmp = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
5712                                gfc_conv_expr_present (sym), tmp);
5713
5714           gfc_trans_runtime_check (false, true, tmp, &se->pre,
5715                                    &expr->where, msg);
5716           gfc_free (msg);
5717         }
5718
5719       gfc_start_block (&block);
5720
5721       /* Copy the data back.  */
5722       if (fsym == NULL || fsym->attr.intent != INTENT_IN)
5723         {
5724           tmp = build_call_expr_loc (input_location,
5725                                  gfor_fndecl_in_unpack, 2, desc, ptr);
5726           gfc_add_expr_to_block (&block, tmp);
5727         }
5728
5729       /* Free the temporary.  */
5730       tmp = gfc_call_free (convert (pvoid_type_node, ptr));
5731       gfc_add_expr_to_block (&block, tmp);
5732
5733       stmt = gfc_finish_block (&block);
5734
5735       gfc_init_block (&block);
5736       /* Only if it was repacked.  This code needs to be executed before the
5737          loop cleanup code.  */
5738       tmp = build_fold_indirect_ref_loc (input_location,
5739                                      desc);
5740       tmp = gfc_conv_array_data (tmp);
5741       tmp = fold_build2 (NE_EXPR, boolean_type_node,
5742                          fold_convert (TREE_TYPE (tmp), ptr), tmp);
5743
5744       if (fsym && fsym->attr.optional && sym && sym->attr.optional)
5745         tmp = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
5746                            gfc_conv_expr_present (sym), tmp);
5747
5748       tmp = build3_v (COND_EXPR, tmp, stmt, build_empty_stmt (input_location));
5749
5750       gfc_add_expr_to_block (&block, tmp);
5751       gfc_add_block_to_block (&block, &se->post);
5752
5753       gfc_init_block (&se->post);
5754       gfc_add_block_to_block (&se->post, &block);
5755     }
5756 }
5757
5758
5759 /* Generate code to deallocate an array, if it is allocated.  */
5760
5761 tree
5762 gfc_trans_dealloc_allocated (tree descriptor)
5763
5764   tree tmp;
5765   tree var;
5766   stmtblock_t block;
5767
5768   gfc_start_block (&block);
5769
5770   var = gfc_conv_descriptor_data_get (descriptor);
5771   STRIP_NOPS (var);
5772
5773   /* Call array_deallocate with an int * present in the second argument.
5774      Although it is ignored here, it's presence ensures that arrays that
5775      are already deallocated are ignored.  */
5776   tmp = gfc_deallocate_with_status (var, NULL_TREE, true, NULL);
5777   gfc_add_expr_to_block (&block, tmp);
5778
5779   /* Zero the data pointer.  */
5780   tmp = fold_build2 (MODIFY_EXPR, void_type_node,
5781                      var, build_int_cst (TREE_TYPE (var), 0));
5782   gfc_add_expr_to_block (&block, tmp);
5783
5784   return gfc_finish_block (&block);
5785 }
5786
5787
5788 /* This helper function calculates the size in words of a full array.  */
5789
5790 static tree
5791 get_full_array_size (stmtblock_t *block, tree decl, int rank)
5792 {
5793   tree idx;
5794   tree nelems;
5795   tree tmp;
5796   idx = gfc_rank_cst[rank - 1];
5797   nelems = gfc_conv_descriptor_ubound_get (decl, idx);
5798   tmp = gfc_conv_descriptor_lbound_get (decl, idx);
5799   tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type, nelems, tmp);
5800   tmp = fold_build2 (PLUS_EXPR, gfc_array_index_type,
5801                      tmp, gfc_index_one_node);
5802   tmp = gfc_evaluate_now (tmp, block);
5803
5804   nelems = gfc_conv_descriptor_stride_get (decl, idx);
5805   tmp = fold_build2 (MULT_EXPR, gfc_array_index_type, nelems, tmp);
5806   return gfc_evaluate_now (tmp, block);
5807 }
5808
5809
5810 /* Allocate dest to the same size as src, and copy src -> dest.
5811    If no_malloc is set, only the copy is done.  */
5812
5813 static tree
5814 duplicate_allocatable(tree dest, tree src, tree type, int rank,
5815                       bool no_malloc)
5816 {
5817   tree tmp;
5818   tree size;
5819   tree nelems;
5820   tree null_cond;
5821   tree null_data;
5822   stmtblock_t block;
5823
5824   /* If the source is null, set the destination to null.  Then,
5825      allocate memory to the destination.  */
5826   gfc_init_block (&block);
5827
5828   if (rank == 0)
5829     {
5830       tmp = null_pointer_node;
5831       tmp = fold_build2 (MODIFY_EXPR, type, dest, tmp);
5832       gfc_add_expr_to_block (&block, tmp);
5833       null_data = gfc_finish_block (&block);
5834
5835       gfc_init_block (&block);
5836       size = TYPE_SIZE_UNIT (type);
5837       if (!no_malloc)
5838         {
5839           tmp = gfc_call_malloc (&block, type, size);
5840           tmp = fold_build2 (MODIFY_EXPR, void_type_node, dest,
5841                              fold_convert (type, tmp));
5842           gfc_add_expr_to_block (&block, tmp);
5843         }
5844
5845       tmp = built_in_decls[BUILT_IN_MEMCPY];
5846       tmp = build_call_expr_loc (input_location, tmp, 3,
5847                                  dest, src, size);
5848     }
5849   else
5850     {
5851       gfc_conv_descriptor_data_set (&block, dest, null_pointer_node);
5852       null_data = gfc_finish_block (&block);
5853
5854       gfc_init_block (&block);
5855       nelems = get_full_array_size (&block, src, rank);
5856       tmp = fold_convert (gfc_array_index_type,
5857                           TYPE_SIZE_UNIT (gfc_get_element_type (type)));
5858       size = fold_build2 (MULT_EXPR, gfc_array_index_type, nelems, tmp);
5859       if (!no_malloc)
5860         {
5861           tmp = TREE_TYPE (gfc_conv_descriptor_data_get (src));
5862           tmp = gfc_call_malloc (&block, tmp, size);
5863           gfc_conv_descriptor_data_set (&block, dest, tmp);
5864         }
5865
5866       /* We know the temporary and the value will be the same length,
5867          so can use memcpy.  */
5868       tmp = built_in_decls[BUILT_IN_MEMCPY];
5869       tmp = build_call_expr_loc (input_location,
5870                         tmp, 3, gfc_conv_descriptor_data_get (dest),
5871                         gfc_conv_descriptor_data_get (src), size);
5872     }
5873
5874   gfc_add_expr_to_block (&block, tmp);
5875   tmp = gfc_finish_block (&block);
5876
5877   /* Null the destination if the source is null; otherwise do
5878      the allocate and copy.  */
5879   if (rank == 0)
5880     null_cond = src;
5881   else
5882     null_cond = gfc_conv_descriptor_data_get (src);
5883
5884   null_cond = convert (pvoid_type_node, null_cond);
5885   null_cond = fold_build2 (NE_EXPR, boolean_type_node,
5886                            null_cond, null_pointer_node);
5887   return build3_v (COND_EXPR, null_cond, tmp, null_data);
5888 }
5889
5890
5891 /* Allocate dest to the same size as src, and copy data src -> dest.  */
5892
5893 tree
5894 gfc_duplicate_allocatable (tree dest, tree src, tree type, int rank)
5895 {
5896   return duplicate_allocatable(dest, src, type, rank, false);
5897 }
5898
5899
5900 /* Copy data src -> dest.  */
5901
5902 tree
5903 gfc_copy_allocatable_data (tree dest, tree src, tree type, int rank)
5904 {
5905   return duplicate_allocatable(dest, src, type, rank, true);
5906 }
5907
5908
5909 /* Recursively traverse an object of derived type, generating code to
5910    deallocate, nullify or copy allocatable components.  This is the work horse
5911    function for the functions named in this enum.  */
5912
5913 enum {DEALLOCATE_ALLOC_COMP = 1, NULLIFY_ALLOC_COMP, COPY_ALLOC_COMP,
5914       COPY_ONLY_ALLOC_COMP};
5915
5916 static tree
5917 structure_alloc_comps (gfc_symbol * der_type, tree decl,
5918                        tree dest, int rank, int purpose)
5919 {
5920   gfc_component *c;
5921   gfc_loopinfo loop;
5922   stmtblock_t fnblock;
5923   stmtblock_t loopbody;
5924   tree tmp;
5925   tree comp;
5926   tree dcmp;
5927   tree nelems;
5928   tree index;
5929   tree var;
5930   tree cdecl;
5931   tree ctype;
5932   tree vref, dref;
5933   tree null_cond = NULL_TREE;
5934
5935   gfc_init_block (&fnblock);
5936
5937   if (POINTER_TYPE_P (TREE_TYPE (decl)) && rank != 0)
5938     decl = build_fold_indirect_ref_loc (input_location,
5939                                     decl);
5940
5941   /* If this an array of derived types with allocatable components
5942      build a loop and recursively call this function.  */
5943   if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
5944         || GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl)))
5945     {
5946       tmp = gfc_conv_array_data (decl);
5947       var = build_fold_indirect_ref_loc (input_location,
5948                                      tmp);
5949         
5950       /* Get the number of elements - 1 and set the counter.  */
5951       if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (decl)))
5952         {
5953           /* Use the descriptor for an allocatable array.  Since this
5954              is a full array reference, we only need the descriptor
5955              information from dimension = rank.  */
5956           tmp = get_full_array_size (&fnblock, decl, rank);
5957           tmp = fold_build2 (MINUS_EXPR, gfc_array_index_type,
5958                              tmp, gfc_index_one_node);
5959
5960           null_cond = gfc_conv_descriptor_data_get (decl);
5961           null_cond = fold_build2 (NE_EXPR, boolean_type_node, null_cond,
5962                                    build_int_cst (TREE_TYPE (null_cond), 0));
5963         }
5964       else
5965         {
5966           /*  Otherwise use the TYPE_DOMAIN information.  */
5967           tmp =  array_type_nelts (TREE_TYPE (decl));
5968           tmp = fold_convert (gfc_array_index_type, tmp);
5969         }
5970
5971       /* Remember that this is, in fact, the no. of elements - 1.  */
5972       nelems = gfc_evaluate_now (tmp, &fnblock);
5973       index = gfc_create_var (gfc_array_index_type, "S");
5974
5975       /* Build the body of the loop.  */
5976       gfc_init_block (&loopbody);
5977
5978       vref = gfc_build_array_ref (var, index, NULL);
5979
5980       if (purpose == COPY_ALLOC_COMP)
5981         {
5982           if (GFC_DESCRIPTOR_TYPE_P (TREE_TYPE (dest)))
5983             {
5984               tmp = gfc_duplicate_allocatable (dest, decl, TREE_TYPE(decl), rank);
5985               gfc_add_expr_to_block (&fnblock, tmp);
5986             }
5987           tmp = build_fold_indirect_ref_loc (input_location,
5988                                          gfc_conv_array_data (dest));
5989           dref = gfc_build_array_ref (tmp, index, NULL);
5990           tmp = structure_alloc_comps (der_type, vref, dref, rank, purpose);
5991         }
5992       else if (purpose == COPY_ONLY_ALLOC_COMP)
5993         {
5994           tmp = build_fold_indirect_ref_loc (input_location,
5995                                          gfc_conv_array_data (dest));
5996           dref = gfc_build_array_ref (tmp, index, NULL);
5997           tmp = structure_alloc_comps (der_type, vref, dref, rank,
5998                                        COPY_ALLOC_COMP);
5999         }
6000       else
6001         tmp = structure_alloc_comps (der_type, vref, NULL_TREE, rank, purpose);
6002
6003       gfc_add_expr_to_block (&loopbody, tmp);
6004
6005       /* Build the loop and return.  */
6006       gfc_init_loopinfo (&loop);
6007       loop.dimen = 1;
6008       loop.from[0] = gfc_index_zero_node;
6009       loop.loopvar[0] = index;
6010       loop.to[0] = nelems;
6011       gfc_trans_scalarizing_loops (&loop, &loopbody);
6012       gfc_add_block_to_block (&fnblock, &loop.pre);
6013
6014       tmp = gfc_finish_block (&fnblock);
6015       if (null_cond != NULL_TREE)
6016         tmp = build3_v (COND_EXPR, null_cond, tmp,
6017                         build_empty_stmt (input_location));
6018
6019       return tmp;
6020     }
6021
6022   /* Otherwise, act on the components or recursively call self to
6023      act on a chain of components.  */
6024   for (c = der_type->components; c; c = c->next)
6025     {
6026       bool cmp_has_alloc_comps = (c->ts.type == BT_DERIVED)
6027                                     && c->ts.u.derived->attr.alloc_comp;
6028       cdecl = c->backend_decl;
6029       ctype = TREE_TYPE (cdecl);
6030
6031       switch (purpose)
6032         {
6033         case DEALLOCATE_ALLOC_COMP:
6034           /* Do not deallocate the components of ultimate pointer
6035              components.  */
6036           if (cmp_has_alloc_comps && !c->attr.pointer)
6037             {
6038               comp = fold_build3 (COMPONENT_REF, ctype,
6039                                   decl, cdecl, NULL_TREE);
6040               rank = c->as ? c->as->rank : 0;
6041               tmp = structure_alloc_comps (c->ts.u.derived, comp, NULL_TREE,
6042                                            rank, purpose);
6043               gfc_add_expr_to_block (&fnblock, tmp);
6044             }
6045
6046           if (c->attr.allocatable && c->attr.dimension)
6047             {
6048               comp = fold_build3 (COMPONENT_REF, ctype,
6049                                   decl, cdecl, NULL_TREE);
6050               tmp = gfc_trans_dealloc_allocated (comp);
6051               gfc_add_expr_to_block (&fnblock, tmp);
6052             }
6053           else if (c->attr.allocatable)
6054             {
6055               /* Allocatable scalar components.  */
6056               comp = fold_build3 (COMPONENT_REF, ctype, decl, cdecl, NULL_TREE);
6057
6058               tmp = gfc_deallocate_with_status (comp, NULL_TREE, true, NULL);
6059               gfc_add_expr_to_block (&fnblock, tmp);
6060
6061               tmp = fold_build2 (MODIFY_EXPR, void_type_node, comp,
6062                                  build_int_cst (TREE_TYPE (comp), 0));
6063               gfc_add_expr_to_block (&fnblock, tmp);
6064             }
6065           else if (c->ts.type == BT_CLASS
6066                    && c->ts.u.derived->components->attr.allocatable)
6067             {
6068               /* Allocatable scalar CLASS components.  */
6069               comp = fold_build3 (COMPONENT_REF, ctype, decl, cdecl, NULL_TREE);
6070               
6071               /* Add reference to '$data' component.  */
6072               tmp = c->ts.u.derived->components->backend_decl;
6073               comp = fold_build3 (COMPONENT_REF, TREE_TYPE (tmp),
6074                                   comp, tmp, NULL_TREE);
6075
6076               tmp = gfc_deallocate_with_status (comp, NULL_TREE, true, NULL);
6077               gfc_add_expr_to_block (&fnblock, tmp);
6078
6079               tmp = fold_build2 (MODIFY_EXPR, void_type_node, comp,
6080                                  build_int_cst (TREE_TYPE (comp), 0));
6081               gfc_add_expr_to_block (&fnblock, tmp);
6082             }
6083           break;
6084
6085         case NULLIFY_ALLOC_COMP:
6086           if (c->attr.pointer)
6087             continue;
6088           else if (c->attr.allocatable && c->attr.dimension)
6089             {
6090               comp = fold_build3 (COMPONENT_REF, ctype,
6091                                   decl, cdecl, NULL_TREE);
6092               gfc_conv_descriptor_data_set (&fnblock, comp, null_pointer_node);
6093             }
6094           else if (c->attr.allocatable)
6095             {
6096               /* Allocatable scalar components.  */
6097               comp = fold_build3 (COMPONENT_REF, ctype, decl, cdecl, NULL_TREE);
6098               tmp = fold_build2 (MODIFY_EXPR, void_type_node, comp,
6099                                  build_int_cst (TREE_TYPE (comp), 0));
6100               gfc_add_expr_to_block (&fnblock, tmp);
6101             }
6102           else if (c->ts.type == BT_CLASS
6103                    && c->ts.u.derived->components->attr.allocatable)
6104             {
6105               /* Allocatable scalar CLASS components.  */
6106               comp = fold_build3 (COMPONENT_REF, ctype, decl, cdecl, NULL_TREE);
6107               /* Add reference to '$data' component.  */
6108               tmp = c->ts.u.derived->components->backend_decl;
6109               comp = fold_build3 (COMPONENT_REF, TREE_TYPE (tmp),
6110                                   comp, tmp, NULL_TREE);
6111               tmp = fold_build2 (MODIFY_EXPR, void_type_node, comp,
6112                                  build_int_cst (TREE_TYPE (comp), 0));
6113               gfc_add_expr_to_block (&fnblock, tmp);
6114             }
6115           else if (cmp_has_alloc_comps)
6116             {
6117               comp = fold_build3 (COMPONENT_REF, ctype,
6118                                   decl, cdecl, NULL_TREE);
6119               rank = c->as ? c->as->rank : 0;
6120               tmp = structure_alloc_comps (c->ts.u.derived, comp, NULL_TREE,
6121                                            rank, purpose);
6122               gfc_add_expr_to_block (&fnblock, tmp);
6123             }
6124           break;
6125
6126         case COPY_ALLOC_COMP:
6127           if (c->attr.pointer)
6128             continue;
6129
6130           /* We need source and destination components.  */
6131           comp = fold_build3 (COMPONENT_REF, ctype, decl, cdecl, NULL_TREE);
6132           dcmp = fold_build3 (COMPONENT_REF, ctype, dest, cdecl, NULL_TREE);
6133           dcmp = fold_convert (TREE_TYPE (comp), dcmp);
6134
6135           if (c->attr.allocatable && !cmp_has_alloc_comps)
6136             {
6137               rank = c->as ? c->as->rank : 0;
6138               tmp = gfc_duplicate_allocatable(dcmp, comp, ctype, rank);
6139               gfc_add_expr_to_block (&fnblock, tmp);
6140             }
6141
6142           if (cmp_has_alloc_comps)
6143             {
6144               rank = c->as ? c->as->rank : 0;
6145               tmp = fold_convert (TREE_TYPE (dcmp), comp);
6146               gfc_add_modify (&fnblock, dcmp, tmp);
6147               tmp = structure_alloc_comps (c->ts.u.derived, comp, dcmp,
6148                                            rank, purpose);
6149               gfc_add_expr_to_block (&fnblock, tmp);
6150             }
6151           break;
6152
6153         default:
6154           gcc_unreachable ();
6155           break;
6156         }
6157     }
6158
6159   return gfc_finish_block (&fnblock);
6160 }
6161
6162 /* Recursively traverse an object of derived type, generating code to
6163    nullify allocatable components.  */
6164
6165 tree
6166 gfc_nullify_alloc_comp (gfc_symbol * der_type, tree decl, int rank)
6167 {
6168   return structure_alloc_comps (der_type, decl, NULL_TREE, rank,
6169                                 NULLIFY_ALLOC_COMP);
6170 }
6171
6172
6173 /* Recursively traverse an object of derived type, generating code to
6174    deallocate allocatable components.  */
6175
6176 tree
6177 gfc_deallocate_alloc_comp (gfc_symbol * der_type, tree decl, int rank)
6178 {
6179   return structure_alloc_comps (der_type, decl, NULL_TREE, rank,
6180                                 DEALLOCATE_ALLOC_COMP);
6181 }
6182
6183
6184 /* Recursively traverse an object of derived type, generating code to
6185    copy it and its allocatable components.  */
6186
6187 tree
6188 gfc_copy_alloc_comp (gfc_symbol * der_type, tree decl, tree dest, int rank)
6189 {
6190   return structure_alloc_comps (der_type, decl, dest, rank, COPY_ALLOC_COMP);
6191 }
6192
6193
6194 /* Recursively traverse an object of derived type, generating code to
6195    copy only its allocatable components.  */
6196
6197 tree
6198 gfc_copy_only_alloc_comp (gfc_symbol * der_type, tree decl, tree dest, int rank)
6199 {
6200   return structure_alloc_comps (der_type, decl, dest, rank, COPY_ONLY_ALLOC_COMP);
6201 }
6202
6203
6204 /* Check for default initializer; sym->value is not enough as it is also
6205    set for EXPR_NULL of allocatables.  */
6206
6207 static bool
6208 has_default_initializer (gfc_symbol *der)
6209 {
6210   gfc_component *c;
6211
6212   gcc_assert (der->attr.flavor == FL_DERIVED);
6213   for (c = der->components; c; c = c->next)
6214     if ((c->ts.type != BT_DERIVED && c->initializer)
6215         || (c->ts.type == BT_DERIVED
6216             && (!c->attr.pointer && has_default_initializer (c->ts.u.derived))))
6217       break;
6218
6219   return c != NULL;
6220 }
6221
6222
6223 /* NULLIFY an allocatable/pointer array on function entry, free it on exit.
6224    Do likewise, recursively if necessary, with the allocatable components of
6225    derived types.  */
6226
6227 tree
6228 gfc_trans_deferred_array (gfc_symbol * sym, tree body)
6229 {
6230   tree type;
6231   tree tmp;
6232   tree descriptor;
6233   stmtblock_t fnblock;
6234   locus loc;
6235   int rank;
6236   bool sym_has_alloc_comp;
6237
6238   sym_has_alloc_comp = (sym->ts.type == BT_DERIVED)
6239                           && sym->ts.u.derived->attr.alloc_comp;
6240
6241   /* Make sure the frontend gets these right.  */
6242   if (!(sym->attr.pointer || sym->attr.allocatable || sym_has_alloc_comp))
6243     fatal_error ("Possible frontend bug: Deferred array size without pointer, "
6244                  "allocatable attribute or derived type without allocatable "
6245                  "components.");
6246
6247   gfc_init_block (&fnblock);
6248
6249   gcc_assert (TREE_CODE (sym->backend_decl) == VAR_DECL
6250                 || TREE_CODE (sym->backend_decl) == PARM_DECL);
6251
6252   if (sym->ts.type == BT_CHARACTER
6253       && !INTEGER_CST_P (sym->ts.u.cl->backend_decl))
6254     {
6255       gfc_conv_string_length (sym->ts.u.cl, NULL, &fnblock);
6256       gfc_trans_vla_type_sizes (sym, &fnblock);
6257     }
6258
6259   /* Dummy, use associated and result variables don't need anything special.  */
6260   if (sym->attr.dummy || sym->attr.use_assoc || sym->attr.result)
6261     {
6262       gfc_add_expr_to_block (&fnblock, body);
6263
6264       return gfc_finish_block (&fnblock);
6265     }
6266
6267   gfc_get_backend_locus (&loc);
6268   gfc_set_backend_locus (&sym->declared_at);
6269   descriptor = sym->backend_decl;
6270
6271   /* Although static, derived types with default initializers and
6272      allocatable components must not be nulled wholesale; instead they
6273      are treated component by component.  */
6274   if (TREE_STATIC (descriptor) && !sym_has_alloc_comp)
6275     {
6276       /* SAVEd variables are not freed on exit.  */
6277       gfc_trans_static_array_pointer (sym);
6278       return body;
6279     }
6280
6281   /* Get the descriptor type.  */
6282   type = TREE_TYPE (sym->backend_decl);
6283
6284   if (sym_has_alloc_comp && !(sym->attr.pointer || sym->attr.allocatable))
6285     {
6286       if (!sym->attr.save
6287           && !(TREE_STATIC (sym->backend_decl) && sym->attr.is_main_program))
6288         {
6289           if (sym->value == NULL || !has_default_initializer (sym->ts.u.derived))
6290             {
6291               rank = sym->as ? sym->as->rank : 0;
6292               tmp = gfc_nullify_alloc_comp (sym->ts.u.derived, descriptor, rank);
6293               gfc_add_expr_to_block (&fnblock, tmp);
6294             }
6295           else
6296             {
6297               tmp = gfc_init_default_dt (sym, NULL, false);
6298               gfc_add_expr_to_block (&fnblock, tmp);
6299             }
6300         }
6301     }
6302   else if (!GFC_DESCRIPTOR_TYPE_P (type))
6303     {
6304       /* If the backend_decl is not a descriptor, we must have a pointer
6305          to one.  */
6306       descriptor = build_fold_indirect_ref_loc (input_location,
6307                                             sym->backend_decl);
6308       type = TREE_TYPE (descriptor);
6309     }
6310   
6311   /* NULLIFY the data pointer.  */
6312   if (GFC_DESCRIPTOR_TYPE_P (type) && !sym->attr.save)
6313     gfc_conv_descriptor_data_set (&fnblock, descriptor, null_pointer_node);
6314
6315   gfc_add_expr_to_block (&fnblock, body);
6316
6317   gfc_set_backend_locus (&loc);
6318
6319   /* Allocatable arrays need to be freed when they go out of scope.
6320      The allocatable components of pointers must not be touched.  */
6321   if (sym_has_alloc_comp && !(sym->attr.function || sym->attr.result)
6322       && !sym->attr.pointer && !sym->attr.save)
6323     {
6324       int rank;
6325       rank = sym->as ? sym->as->rank : 0;
6326       tmp = gfc_deallocate_alloc_comp (sym->ts.u.derived, descriptor, rank);
6327       gfc_add_expr_to_block (&fnblock, tmp);
6328     }
6329
6330   if (sym->attr.allocatable && sym->attr.dimension
6331       && !sym->attr.save && !sym->attr.result)
6332     {
6333       tmp = gfc_trans_dealloc_allocated (sym->backend_decl);
6334       gfc_add_expr_to_block (&fnblock, tmp);
6335     }
6336
6337   return gfc_finish_block (&fnblock);
6338 }
6339
6340 /************ Expression Walking Functions ******************/
6341
6342 /* Walk a variable reference.
6343
6344    Possible extension - multiple component subscripts.
6345     x(:,:) = foo%a(:)%b(:)
6346    Transforms to
6347     forall (i=..., j=...)
6348       x(i,j) = foo%a(j)%b(i)
6349     end forall
6350    This adds a fair amount of complexity because you need to deal with more
6351    than one ref.  Maybe handle in a similar manner to vector subscripts.
6352    Maybe not worth the effort.  */
6353
6354
6355 static gfc_ss *
6356 gfc_walk_variable_expr (gfc_ss * ss, gfc_expr * expr)
6357 {
6358   gfc_ref *ref;
6359   gfc_array_ref *ar;
6360   gfc_ss *newss;
6361   int n;
6362
6363   for (ref = expr->ref; ref; ref = ref->next)
6364     if (ref->type == REF_ARRAY && ref->u.ar.type != AR_ELEMENT)
6365       break;
6366
6367   for (; ref; ref = ref->next)
6368     {
6369       if (ref->type == REF_SUBSTRING)
6370         {
6371           newss = gfc_get_ss ();
6372           newss->type = GFC_SS_SCALAR;
6373           newss->expr = ref->u.ss.start;
6374           newss->next = ss;
6375           ss = newss;
6376
6377           newss = gfc_get_ss ();
6378           newss->type = GFC_SS_SCALAR;
6379           newss->expr = ref->u.ss.end;
6380           newss->next = ss;
6381           ss = newss;
6382         }
6383
6384       /* We're only interested in array sections from now on.  */
6385       if (ref->type != REF_ARRAY)
6386         continue;
6387
6388       ar = &ref->u.ar;
6389
6390       if (ar->as->rank == 0)
6391         {
6392           /* Scalar coarray.  */
6393           continue;
6394         }
6395
6396       switch (ar->type)
6397         {
6398         case AR_ELEMENT:
6399           for (n = 0; n < ar->dimen; n++)
6400             {
6401               newss = gfc_get_ss ();
6402               newss->type = GFC_SS_SCALAR;
6403               newss->expr = ar->start[n];
6404               newss->next = ss;
6405               ss = newss;
6406             }
6407           break;
6408
6409         case AR_FULL:
6410           newss = gfc_get_ss ();
6411           newss->type = GFC_SS_SECTION;
6412           newss->expr = expr;
6413           newss->next = ss;
6414           newss->data.info.dimen = ar->as->rank;
6415           newss->data.info.ref = ref;
6416
6417           /* Make sure array is the same as array(:,:), this way
6418              we don't need to special case all the time.  */
6419           ar->dimen = ar->as->rank;
6420           for (n = 0; n < ar->dimen; n++)
6421             {
6422               newss->data.info.dim[n] = n;
6423               ar->dimen_type[n] = DIMEN_RANGE;
6424
6425               gcc_assert (ar->start[n] == NULL);
6426               gcc_assert (ar->end[n] == NULL);
6427               gcc_assert (ar->stride[n] == NULL);
6428             }
6429           ss = newss;
6430           break;
6431
6432         case AR_SECTION:
6433           newss = gfc_get_ss ();
6434           newss->type = GFC_SS_SECTION;
6435           newss->expr = expr;
6436           newss->next = ss;
6437           newss->data.info.dimen = 0;
6438           newss->data.info.ref = ref;
6439
6440           /* We add SS chains for all the subscripts in the section.  */
6441           for (n = 0; n < ar->dimen; n++)
6442             {
6443               gfc_ss *indexss;
6444
6445               switch (ar->dimen_type[n])
6446                 {
6447                 case DIMEN_ELEMENT:
6448                   /* Add SS for elemental (scalar) subscripts.  */
6449                   gcc_assert (ar->start[n]);
6450                   indexss = gfc_get_ss ();
6451                   indexss->type = GFC_SS_SCALAR;
6452                   indexss->expr = ar->start[n];
6453                   indexss->next = gfc_ss_terminator;
6454                   indexss->loop_chain = gfc_ss_terminator;
6455                   newss->data.info.subscript[n] = indexss;
6456                   break;
6457
6458                 case DIMEN_RANGE:
6459                   /* We don't add anything for sections, just remember this
6460                      dimension for later.  */
6461                   newss->data.info.dim[newss->data.info.dimen] = n;
6462                   newss->data.info.dimen++;
6463                   break;
6464
6465                 case DIMEN_VECTOR:
6466                   /* Create a GFC_SS_VECTOR index in which we can store
6467                      the vector's descriptor.  */
6468                   indexss = gfc_get_ss ();
6469                   indexss->type = GFC_SS_VECTOR;
6470                   indexss->expr = ar->start[n];
6471                   indexss->next = gfc_ss_terminator;
6472                   indexss->loop_chain = gfc_ss_terminator;
6473                   newss->data.info.subscript[n] = indexss;
6474                   newss->data.info.dim[newss->data.info.dimen] = n;
6475                   newss->data.info.dimen++;
6476                   break;
6477
6478                 default:
6479                   /* We should know what sort of section it is by now.  */
6480                   gcc_unreachable ();
6481                 }
6482             }
6483           /* We should have at least one non-elemental dimension.  */
6484           gcc_assert (newss->data.info.dimen > 0);
6485           ss = newss;
6486           break;
6487
6488         default:
6489           /* We should know what sort of section it is by now.  */
6490           gcc_unreachable ();
6491         }
6492
6493     }
6494   return ss;
6495 }
6496
6497
6498 /* Walk an expression operator. If only one operand of a binary expression is
6499    scalar, we must also add the scalar term to the SS chain.  */
6500
6501 static gfc_ss *
6502 gfc_walk_op_expr (gfc_ss * ss, gfc_expr * expr)
6503 {
6504   gfc_ss *head;
6505   gfc_ss *head2;
6506   gfc_ss *newss;
6507
6508   head = gfc_walk_subexpr (ss, expr->value.op.op1);
6509   if (expr->value.op.op2 == NULL)
6510     head2 = head;
6511   else
6512     head2 = gfc_walk_subexpr (head, expr->value.op.op2);
6513
6514   /* All operands are scalar.  Pass back and let the caller deal with it.  */
6515   if (head2 == ss)
6516     return head2;
6517
6518   /* All operands require scalarization.  */
6519   if (head != ss && (expr->value.op.op2 == NULL || head2 != head))
6520     return head2;
6521
6522   /* One of the operands needs scalarization, the other is scalar.
6523      Create a gfc_ss for the scalar expression.  */
6524   newss = gfc_get_ss ();
6525   newss->type = GFC_SS_SCALAR;
6526   if (head == ss)
6527     {
6528       /* First operand is scalar.  We build the chain in reverse order, so
6529          add the scalar SS after the second operand.  */
6530       head = head2;
6531       while (head && head->next != ss)
6532         head = head->next;
6533       /* Check we haven't somehow broken the chain.  */
6534       gcc_assert (head);
6535       newss->next = ss;
6536       head->next = newss;
6537       newss->expr = expr->value.op.op1;
6538     }
6539   else                          /* head2 == head */
6540     {
6541       gcc_assert (head2 == head);
6542       /* Second operand is scalar.  */
6543       newss->next = head2;
6544       head2 = newss;
6545       newss->expr = expr->value.op.op2;
6546     }
6547
6548   return head2;
6549 }
6550
6551
6552 /* Reverse a SS chain.  */
6553
6554 gfc_ss *
6555 gfc_reverse_ss (gfc_ss * ss)
6556 {
6557   gfc_ss *next;
6558   gfc_ss *head;
6559
6560   gcc_assert (ss != NULL);
6561
6562   head = gfc_ss_terminator;
6563   while (ss != gfc_ss_terminator)
6564     {
6565       next = ss->next;
6566       /* Check we didn't somehow break the chain.  */
6567       gcc_assert (next != NULL);
6568       ss->next = head;
6569       head = ss;
6570       ss = next;
6571     }
6572
6573   return (head);
6574 }
6575
6576
6577 /* Walk the arguments of an elemental function.  */
6578
6579 gfc_ss *
6580 gfc_walk_elemental_function_args (gfc_ss * ss, gfc_actual_arglist *arg,
6581                                   gfc_ss_type type)
6582 {
6583   int scalar;
6584   gfc_ss *head;
6585   gfc_ss *tail;
6586   gfc_ss *newss;
6587
6588   head = gfc_ss_terminator;
6589   tail = NULL;
6590   scalar = 1;
6591   for (; arg; arg = arg->next)
6592     {
6593       if (!arg->expr)
6594         continue;
6595
6596       newss = gfc_walk_subexpr (head, arg->expr);
6597       if (newss == head)
6598         {
6599           /* Scalar argument.  */
6600           newss = gfc_get_ss ();
6601           newss->type = type;
6602           newss->expr = arg->expr;
6603           newss->next = head;
6604         }
6605       else
6606         scalar = 0;
6607
6608       head = newss;
6609       if (!tail)
6610         {
6611           tail = head;
6612           while (tail->next != gfc_ss_terminator)
6613             tail = tail->next;
6614         }
6615     }
6616
6617   if (scalar)
6618     {
6619       /* If all the arguments are scalar we don't need the argument SS.  */
6620       gfc_free_ss_chain (head);
6621       /* Pass it back.  */
6622       return ss;
6623     }
6624
6625   /* Add it onto the existing chain.  */
6626   tail->next = ss;
6627   return head;
6628 }
6629
6630
6631 /* Walk a function call.  Scalar functions are passed back, and taken out of
6632    scalarization loops.  For elemental functions we walk their arguments.
6633    The result of functions returning arrays is stored in a temporary outside
6634    the loop, so that the function is only called once.  Hence we do not need
6635    to walk their arguments.  */
6636
6637 static gfc_ss *
6638 gfc_walk_function_expr (gfc_ss * ss, gfc_expr * expr)
6639 {
6640   gfc_ss *newss;
6641   gfc_intrinsic_sym *isym;
6642   gfc_symbol *sym;
6643   gfc_component *comp = NULL;
6644
6645   isym = expr->value.function.isym;
6646
6647   /* Handle intrinsic functions separately.  */
6648   if (isym)
6649     return gfc_walk_intrinsic_function (ss, expr, isym);
6650
6651   sym = expr->value.function.esym;
6652   if (!sym)
6653       sym = expr->symtree->n.sym;
6654
6655   /* A function that returns arrays.  */
6656   gfc_is_proc_ptr_comp (expr, &comp);
6657   if ((!comp && gfc_return_by_reference (sym) && sym->result->attr.dimension)
6658       || (comp && comp->attr.dimension))
6659     {
6660       newss = gfc_get_ss ();
6661       newss->type = GFC_SS_FUNCTION;
6662       newss->expr = expr;
6663       newss->next = ss;
6664       newss->data.info.dimen = expr->rank;
6665       return newss;
6666     }
6667
6668   /* Walk the parameters of an elemental function.  For now we always pass
6669      by reference.  */
6670   if (sym->attr.elemental)
6671     return gfc_walk_elemental_function_args (ss, expr->value.function.actual,
6672                                              GFC_SS_REFERENCE);
6673
6674   /* Scalar functions are OK as these are evaluated outside the scalarization
6675      loop.  Pass back and let the caller deal with it.  */
6676   return ss;
6677 }
6678
6679
6680 /* An array temporary is constructed for array constructors.  */
6681
6682 static gfc_ss *
6683 gfc_walk_array_constructor (gfc_ss * ss, gfc_expr * expr)
6684 {
6685   gfc_ss *newss;
6686   int n;
6687
6688   newss = gfc_get_ss ();
6689   newss->type = GFC_SS_CONSTRUCTOR;
6690   newss->expr = expr;
6691   newss->next = ss;
6692   newss->data.info.dimen = expr->rank;
6693   for (n = 0; n < expr->rank; n++)
6694     newss->data.info.dim[n] = n;
6695
6696   return newss;
6697 }
6698
6699
6700 /* Walk an expression.  Add walked expressions to the head of the SS chain.
6701    A wholly scalar expression will not be added.  */
6702
6703 static gfc_ss *
6704 gfc_walk_subexpr (gfc_ss * ss, gfc_expr * expr)
6705 {
6706   gfc_ss *head;
6707
6708   switch (expr->expr_type)
6709     {
6710     case EXPR_VARIABLE:
6711       head = gfc_walk_variable_expr (ss, expr);
6712       return head;
6713
6714     case EXPR_OP:
6715       head = gfc_walk_op_expr (ss, expr);
6716       return head;
6717
6718     case EXPR_FUNCTION:
6719       head = gfc_walk_function_expr (ss, expr);
6720       return head;
6721
6722     case EXPR_CONSTANT:
6723     case EXPR_NULL:
6724     case EXPR_STRUCTURE:
6725       /* Pass back and let the caller deal with it.  */
6726       break;
6727
6728     case EXPR_ARRAY:
6729       head = gfc_walk_array_constructor (ss, expr);
6730       return head;
6731
6732     case EXPR_SUBSTRING:
6733       /* Pass back and let the caller deal with it.  */
6734       break;
6735
6736     default:
6737       internal_error ("bad expression type during walk (%d)",
6738                       expr->expr_type);
6739     }
6740   return ss;
6741 }
6742
6743
6744 /* Entry point for expression walking.
6745    A return value equal to the passed chain means this is
6746    a scalar expression.  It is up to the caller to take whatever action is
6747    necessary to translate these.  */
6748
6749 gfc_ss *
6750 gfc_walk_expr (gfc_expr * expr)
6751 {
6752   gfc_ss *res;
6753
6754   res = gfc_walk_subexpr (gfc_ss_terminator, expr);
6755   return gfc_reverse_ss (res);
6756 }