OSDN Git Service

2008-01-22 Paul Thomas <pault@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / fortran / trans-common.c
1 /* Common block and equivalence list handling
2    Copyright (C) 2000, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Canqun Yang <canqun@nudt.edu.cn>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */     
21
22 /* The core algorithm is based on Andy Vaught's g95 tree.  Also the
23    way to build UNION_TYPE is borrowed from Richard Henderson.
24  
25    Transform common blocks.  An integral part of this is processing
26    equivalence variables.  Equivalenced variables that are not in a
27    common block end up in a private block of their own.
28
29    Each common block or local equivalence list is declared as a union.
30    Variables within the block are represented as a field within the
31    block with the proper offset. 
32  
33    So if two variables are equivalenced, they just point to a common
34    area in memory.
35  
36    Mathematically, laying out an equivalence block is equivalent to
37    solving a linear system of equations.  The matrix is usually a
38    sparse matrix in which each row contains all zero elements except
39    for a +1 and a -1, a sort of a generalized Vandermonde matrix.  The
40    matrix is usually block diagonal.  The system can be
41    overdetermined, underdetermined or have a unique solution.  If the
42    system is inconsistent, the program is not standard conforming.
43    The solution vector is integral, since all of the pivots are +1 or -1.
44  
45    How we lay out an equivalence block is a little less complicated.
46    In an equivalence list with n elements, there are n-1 conditions to
47    be satisfied.  The conditions partition the variables into what we
48    will call segments.  If A and B are equivalenced then A and B are
49    in the same segment.  If B and C are equivalenced as well, then A,
50    B and C are in a segment and so on.  Each segment is a block of
51    memory that has one or more variables equivalenced in some way.  A
52    common block is made up of a series of segments that are joined one
53    after the other.  In the linear system, a segment is a block
54    diagonal.
55  
56    To lay out a segment we first start with some variable and
57    determine its length.  The first variable is assumed to start at
58    offset one and extends to however long it is.  We then traverse the
59    list of equivalences to find an unused condition that involves at
60    least one of the variables currently in the segment.
61  
62    Each equivalence condition amounts to the condition B+b=C+c where B
63    and C are the offsets of the B and C variables, and b and c are
64    constants which are nonzero for array elements, substrings or
65    structure components.  So for
66  
67      EQUIVALENCE(B(2), C(3))
68    we have
69      B + 2*size of B's elements = C + 3*size of C's elements.
70  
71    If B and C are known we check to see if the condition already
72    holds.  If B is known we can solve for C.  Since we know the length
73    of C, we can see if the minimum and maximum extents of the segment
74    are affected.  Eventually, we make a full pass through the
75    equivalence list without finding any new conditions and the segment
76    is fully specified.
77  
78    At this point, the segment is added to the current common block.
79    Since we know the minimum extent of the segment, everything in the
80    segment is translated to its position in the common block.  The
81    usual case here is that there are no equivalence statements and the
82    common block is series of segments with one variable each, which is
83    a diagonal matrix in the matrix formulation.
84  
85    Each segment is described by a chain of segment_info structures.  Each
86    segment_info structure describes the extents of a single variable within
87    the segment.  This list is maintained in the order the elements are
88    positioned withing the segment.  If two elements have the same starting
89    offset the smaller will come first.  If they also have the same size their
90    ordering is undefined. 
91    
92    Once all common blocks have been created, the list of equivalences
93    is examined for still-unused equivalence conditions.  We create a
94    block for each merged equivalence list.  */
95
96 #include "config.h"
97 #include "system.h"
98 #include "coretypes.h"
99 #include "target.h"
100 #include "tree.h"
101 #include "toplev.h"
102 #include "tm.h"
103 #include "rtl.h"
104 #include "gfortran.h"
105 #include "trans.h"
106 #include "trans-types.h"
107 #include "trans-const.h"
108 #include "target-memory.h"
109
110
111 /* Holds a single variable in an equivalence set.  */
112 typedef struct segment_info
113 {
114   gfc_symbol *sym;
115   HOST_WIDE_INT offset;
116   HOST_WIDE_INT length;
117   /* This will contain the field type until the field is created.  */
118   tree field;
119   struct segment_info *next;
120 } segment_info;
121
122 static segment_info * current_segment;
123 static gfc_namespace *gfc_common_ns = NULL;
124
125
126 /* Make a segment_info based on a symbol.  */
127
128 static segment_info *
129 get_segment_info (gfc_symbol * sym, HOST_WIDE_INT offset)
130 {
131   segment_info *s;
132
133   /* Make sure we've got the character length.  */
134   if (sym->ts.type == BT_CHARACTER)
135     gfc_conv_const_charlen (sym->ts.cl);
136
137   /* Create the segment_info and fill it in.  */
138   s = (segment_info *) gfc_getmem (sizeof (segment_info));
139   s->sym = sym;
140   /* We will use this type when building the segment aggregate type.  */
141   s->field = gfc_sym_type (sym);
142   s->length = int_size_in_bytes (s->field);
143   s->offset = offset;
144
145   return s;
146 }
147
148
149 /* Add a copy of a segment list to the namespace.  This is specifically for
150    equivalence segments, so that dependency checking can be done on
151    equivalence group members.  */
152
153 static void
154 copy_equiv_list_to_ns (segment_info *c)
155 {
156   segment_info *f;
157   gfc_equiv_info *s;
158   gfc_equiv_list *l;
159
160   l = (gfc_equiv_list *) gfc_getmem (sizeof (gfc_equiv_list));
161
162   l->next = c->sym->ns->equiv_lists;
163   c->sym->ns->equiv_lists = l;
164
165   for (f = c; f; f = f->next)
166     {
167       s = (gfc_equiv_info *) gfc_getmem (sizeof (gfc_equiv_info));
168       s->next = l->equiv;
169       l->equiv = s;
170       s->sym = f->sym;
171       s->offset = f->offset;
172       s->length = f->length;
173     }
174 }
175
176
177 /* Add combine segment V and segment LIST.  */
178
179 static segment_info *
180 add_segments (segment_info *list, segment_info *v)
181 {
182   segment_info *s;
183   segment_info *p;
184   segment_info *next;
185
186   p = NULL;
187   s = list;
188
189   while (v)
190     {
191       /* Find the location of the new element.  */
192       while (s)
193         {
194           if (v->offset < s->offset)
195             break;
196           if (v->offset == s->offset
197               && v->length <= s->length)
198             break;
199
200           p = s;
201           s = s->next;
202         }
203
204       /* Insert the new element in between p and s.  */
205       next = v->next;
206       v->next = s;
207       if (p == NULL)
208         list = v;
209       else
210         p->next = v;
211
212       p = v;
213       v = next;
214     }
215
216   return list;
217 }
218
219
220 /* Construct mangled common block name from symbol name.  */
221
222 /* We need the bind(c) flag to tell us how/if we should mangle the symbol
223    name.  There are few calls to this function, so few places that this
224    would need to be added.  At the moment, there is only one call, in
225    build_common_decl().  We can't attempt to look up the common block
226    because we may be building it for the first time and therefore, it won't
227    be in the common_root.  We also need the binding label, if it's bind(c).
228    Therefore, send in the pointer to the common block, so whatever info we
229    have so far can be used.  All of the necessary info should be available
230    in the gfc_common_head by now, so it should be accurate to test the
231    isBindC flag and use the binding label given if it is bind(c).
232
233    We may NOT know yet if it's bind(c) or not, but we can try at least.
234    Will have to figure out what to do later if it's labeled bind(c)
235    after this is called.  */
236
237 static tree
238 gfc_sym_mangled_common_id (gfc_common_head *com)
239 {
240   int has_underscore;
241   char mangled_name[GFC_MAX_MANGLED_SYMBOL_LEN + 1];
242   char name[GFC_MAX_SYMBOL_LEN + 1];
243
244   /* Get the name out of the common block pointer.  */
245   strcpy (name, com->name);
246
247   /* If we're suppose to do a bind(c).  */
248   if (com->is_bind_c == 1 && com->binding_label[0] != '\0')
249     return get_identifier (com->binding_label);
250
251   if (strcmp (name, BLANK_COMMON_NAME) == 0)
252     return get_identifier (name);
253
254   if (gfc_option.flag_underscoring)
255     {
256       has_underscore = strchr (name, '_') != 0;
257       if (gfc_option.flag_second_underscore && has_underscore)
258         snprintf (mangled_name, sizeof mangled_name, "%s__", name);
259       else
260         snprintf (mangled_name, sizeof mangled_name, "%s_", name);
261
262       return get_identifier (mangled_name);
263     }
264   else
265     return get_identifier (name);
266 }
267
268
269 /* Build a field declaration for a common variable or a local equivalence
270    object.  */
271
272 static void
273 build_field (segment_info *h, tree union_type, record_layout_info rli)
274 {
275   tree field;
276   tree name;
277   HOST_WIDE_INT offset = h->offset;
278   unsigned HOST_WIDE_INT desired_align, known_align;
279
280   name = get_identifier (h->sym->name);
281   field = build_decl (FIELD_DECL, name, h->field);
282   gfc_set_decl_location (field, &h->sym->declared_at);
283   known_align = (offset & -offset) * BITS_PER_UNIT;
284   if (known_align == 0 || known_align > BIGGEST_ALIGNMENT)
285     known_align = BIGGEST_ALIGNMENT;
286
287   desired_align = update_alignment_for_field (rli, field, known_align);
288   if (desired_align > known_align)
289     DECL_PACKED (field) = 1;
290
291   DECL_FIELD_CONTEXT (field) = union_type;
292   DECL_FIELD_OFFSET (field) = size_int (offset);
293   DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
294   SET_DECL_OFFSET_ALIGN (field, known_align);
295
296   rli->offset = size_binop (MAX_EXPR, rli->offset,
297                             size_binop (PLUS_EXPR,
298                                         DECL_FIELD_OFFSET (field),
299                                         DECL_SIZE_UNIT (field)));
300   /* If this field is assigned to a label, we create another two variables.
301      One will hold the address of target label or format label. The other will
302      hold the length of format label string.  */
303   if (h->sym->attr.assign)
304     {
305       tree len;
306       tree addr;
307
308       gfc_allocate_lang_decl (field);
309       GFC_DECL_ASSIGN (field) = 1;
310       len = gfc_create_var_np (gfc_charlen_type_node,h->sym->name);
311       addr = gfc_create_var_np (pvoid_type_node, h->sym->name);
312       TREE_STATIC (len) = 1;
313       TREE_STATIC (addr) = 1;
314       DECL_INITIAL (len) = build_int_cst (NULL_TREE, -2);
315       gfc_set_decl_location (len, &h->sym->declared_at);
316       gfc_set_decl_location (addr, &h->sym->declared_at);
317       GFC_DECL_STRING_LEN (field) = pushdecl_top_level (len);
318       GFC_DECL_ASSIGN_ADDR (field) = pushdecl_top_level (addr);
319     }
320
321   h->field = field;
322 }
323
324
325 /* Get storage for local equivalence.  */
326
327 static tree
328 build_equiv_decl (tree union_type, bool is_init, bool is_saved)
329 {
330   tree decl;
331   char name[15];
332   static int serial = 0;
333
334   if (is_init)
335     {
336       decl = gfc_create_var (union_type, "equiv");
337       TREE_STATIC (decl) = 1;
338       GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
339       return decl;
340     }
341
342   snprintf (name, sizeof (name), "equiv.%d", serial++);
343   decl = build_decl (VAR_DECL, get_identifier (name), union_type);
344   DECL_ARTIFICIAL (decl) = 1;
345   DECL_IGNORED_P (decl) = 1;
346
347   if (!gfc_can_put_var_on_stack (DECL_SIZE_UNIT (decl))
348       || is_saved)
349     TREE_STATIC (decl) = 1;
350
351   TREE_ADDRESSABLE (decl) = 1;
352   TREE_USED (decl) = 1;
353   GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
354
355   /* The source location has been lost, and doesn't really matter.
356      We need to set it to something though.  */
357   gfc_set_decl_location (decl, &gfc_current_locus);
358
359   gfc_add_decl_to_function (decl);
360
361   return decl;
362 }
363
364
365 /* Get storage for common block.  */
366
367 static tree
368 build_common_decl (gfc_common_head *com, tree union_type, bool is_init)
369 {
370   gfc_symbol *common_sym;
371   tree decl;
372
373   /* Create a namespace to store symbols for common blocks.  */
374   if (gfc_common_ns == NULL)
375     gfc_common_ns = gfc_get_namespace (NULL, 0);
376
377   gfc_get_symbol (com->name, gfc_common_ns, &common_sym);
378   decl = common_sym->backend_decl;
379
380   /* Update the size of this common block as needed.  */
381   if (decl != NULL_TREE)
382     {
383       tree size = TYPE_SIZE_UNIT (union_type);
384       if (tree_int_cst_lt (DECL_SIZE_UNIT (decl), size))
385         {
386           /* Named common blocks of the same name shall be of the same size
387              in all scoping units of a program in which they appear, but
388              blank common blocks may be of different sizes.  */
389           if (strcmp (com->name, BLANK_COMMON_NAME))
390             gfc_warning ("Named COMMON block '%s' at %L shall be of the "
391                          "same size", com->name, &com->where);
392           DECL_SIZE_UNIT (decl) = size;
393           TREE_TYPE (decl) = union_type;
394         }
395      }
396
397   /* If this common block has been declared in a previous program unit,
398      and either it is already initialized or there is no new initialization
399      for it, just return.  */
400   if ((decl != NULL_TREE) && (!is_init || DECL_INITIAL (decl)))
401     return decl;
402
403   /* If there is no backend_decl for the common block, build it.  */
404   if (decl == NULL_TREE)
405     {
406       decl = build_decl (VAR_DECL, get_identifier (com->name), union_type);
407       SET_DECL_ASSEMBLER_NAME (decl, gfc_sym_mangled_common_id (com));
408       TREE_PUBLIC (decl) = 1;
409       TREE_STATIC (decl) = 1;
410       if (!com->is_bind_c)
411         DECL_ALIGN (decl) = BIGGEST_ALIGNMENT;
412       else
413         {
414           /* Do not set the alignment for bind(c) common blocks to
415              BIGGEST_ALIGNMENT because that won't match what C does.  Also,
416              for common blocks with one element, the alignment must be
417              that of the field within the common block in order to match
418              what C will do.  */
419           tree field = NULL_TREE;
420           field = TYPE_FIELDS (TREE_TYPE (decl));
421           if (TREE_CHAIN (field) == NULL_TREE)
422             DECL_ALIGN (decl) = TYPE_ALIGN (TREE_TYPE (field));
423         }
424       DECL_USER_ALIGN (decl) = 0;
425       GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
426
427       gfc_set_decl_location (decl, &com->where);
428
429       if (com->threadprivate)
430         DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
431
432       /* Place the back end declaration for this common block in
433          GLOBAL_BINDING_LEVEL.  */
434       common_sym->backend_decl = pushdecl_top_level (decl);
435     }
436
437   /* Has no initial values.  */
438   if (!is_init)
439     {
440       DECL_INITIAL (decl) = NULL_TREE;
441       DECL_COMMON (decl) = 1;
442       DECL_DEFER_OUTPUT (decl) = 1;
443     }
444   else
445     {
446       DECL_INITIAL (decl) = error_mark_node;
447       DECL_COMMON (decl) = 0;
448       DECL_DEFER_OUTPUT (decl) = 0;
449     }
450   return decl;
451 }
452
453
454 /* Return a field that is the size of the union, if an equivalence has
455    overlapping initializers.  Merge the initializers into a single
456    initializer for this new field, then free the old ones.  */ 
457
458 static tree
459 get_init_field (segment_info *head, tree union_type, tree *field_init,
460                 record_layout_info rli)
461 {
462   segment_info *s;
463   HOST_WIDE_INT length = 0;
464   HOST_WIDE_INT offset = 0;
465   unsigned HOST_WIDE_INT known_align, desired_align;
466   bool overlap = false;
467   tree tmp, field;
468   tree init;
469   unsigned char *data, *chk;
470   VEC(constructor_elt,gc) *v = NULL;
471
472   tree type = unsigned_char_type_node;
473   int i;
474
475   /* Obtain the size of the union and check if there are any overlapping
476      initializers.  */
477   for (s = head; s; s = s->next)
478     {
479       HOST_WIDE_INT slen = s->offset + s->length;
480       if (s->sym->value)
481         {
482           if (s->offset < offset)
483             overlap = true;
484           offset = slen;
485         }
486       length = length < slen ? slen : length;
487     }
488
489   if (!overlap)
490     return NULL_TREE;
491
492   /* Now absorb all the initializer data into a single vector,
493      whilst checking for overlapping, unequal values.  */
494   data = (unsigned char*)gfc_getmem ((size_t)length);
495   chk = (unsigned char*)gfc_getmem ((size_t)length);
496
497   /* TODO - change this when default initialization is implemented.  */
498   memset (data, '\0', (size_t)length);
499   memset (chk, '\0', (size_t)length);
500   for (s = head; s; s = s->next)
501     if (s->sym->value)
502       gfc_merge_initializers (s->sym->ts, s->sym->value,
503                               &data[s->offset],
504                               &chk[s->offset],
505                              (size_t)s->length);
506   
507   for (i = 0; i < length; i++)
508     CONSTRUCTOR_APPEND_ELT (v, NULL, build_int_cst (type, data[i]));
509
510   gfc_free (data);
511   gfc_free (chk);
512
513   /* Build a char[length] array to hold the initializers.  Much of what
514      follows is borrowed from build_field, above.  */
515
516   tmp = build_int_cst (gfc_array_index_type, length - 1);
517   tmp = build_range_type (gfc_array_index_type,
518                           gfc_index_zero_node, tmp);
519   tmp = build_array_type (type, tmp);
520   field = build_decl (FIELD_DECL, NULL_TREE, tmp);
521   gfc_set_decl_location (field, &gfc_current_locus);
522
523   known_align = BIGGEST_ALIGNMENT;
524
525   desired_align = update_alignment_for_field (rli, field, known_align);
526   if (desired_align > known_align)
527     DECL_PACKED (field) = 1;
528
529   DECL_FIELD_CONTEXT (field) = union_type;
530   DECL_FIELD_OFFSET (field) = size_int (0);
531   DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
532   SET_DECL_OFFSET_ALIGN (field, known_align);
533
534   rli->offset = size_binop (MAX_EXPR, rli->offset,
535                             size_binop (PLUS_EXPR,
536                                         DECL_FIELD_OFFSET (field),
537                                         DECL_SIZE_UNIT (field)));
538
539   init = build_constructor (TREE_TYPE (field), v);
540   TREE_CONSTANT (init) = 1;
541   TREE_INVARIANT (init) = 1;
542
543   *field_init = init;
544
545   for (s = head; s; s = s->next)
546     {
547       if (s->sym->value == NULL)
548         continue;
549
550       gfc_free_expr (s->sym->value);
551       s->sym->value = NULL;
552     }
553
554   return field;
555 }
556
557
558 /* Declare memory for the common block or local equivalence, and create
559    backend declarations for all of the elements.  */
560
561 static void
562 create_common (gfc_common_head *com, segment_info *head, bool saw_equiv)
563 {
564   segment_info *s, *next_s;
565   tree union_type;
566   tree *field_link;
567   tree field;
568   tree field_init = NULL_TREE;
569   record_layout_info rli;
570   tree decl;
571   bool is_init = false;
572   bool is_saved = false;
573
574   /* Declare the variables inside the common block.
575      If the current common block contains any equivalence object, then
576      make a UNION_TYPE node, otherwise RECORD_TYPE. This will let the
577      alias analyzer work well when there is no address overlapping for
578      common variables in the current common block.  */
579   if (saw_equiv)
580     union_type = make_node (UNION_TYPE);
581   else
582     union_type = make_node (RECORD_TYPE);
583
584   rli = start_record_layout (union_type);
585   field_link = &TYPE_FIELDS (union_type);
586
587   /* Check for overlapping initializers and replace them with a single,
588      artificial field that contains all the data.  */
589   if (saw_equiv)
590     field = get_init_field (head, union_type, &field_init, rli);
591   else
592     field = NULL_TREE;
593
594   if (field != NULL_TREE)
595     {
596       is_init = true;
597       *field_link = field;
598       field_link = &TREE_CHAIN (field);
599     }
600
601   for (s = head; s; s = s->next)
602     {
603       build_field (s, union_type, rli);
604
605       /* Link the field into the type.  */
606       *field_link = s->field;
607       field_link = &TREE_CHAIN (s->field);
608
609       /* Has initial value.  */
610       if (s->sym->value)
611         is_init = true;
612
613       /* Has SAVE attribute.  */
614       if (s->sym->attr.save)
615         is_saved = true;
616     }
617
618   finish_record_layout (rli, true);
619
620   if (com)
621     decl = build_common_decl (com, union_type, is_init);
622   else
623     decl = build_equiv_decl (union_type, is_init, is_saved);
624
625   if (is_init)
626     {
627       tree ctor, tmp;
628       HOST_WIDE_INT offset = 0;
629       VEC(constructor_elt,gc) *v = NULL;
630
631       if (field != NULL_TREE && field_init != NULL_TREE)
632         CONSTRUCTOR_APPEND_ELT (v, field, field_init);
633       else
634         for (s = head; s; s = s->next)
635           {
636             if (s->sym->value)
637               {
638                 /* Add the initializer for this field.  */
639                 tmp = gfc_conv_initializer (s->sym->value, &s->sym->ts,
640                     TREE_TYPE (s->field), s->sym->attr.dimension,
641                     s->sym->attr.pointer || s->sym->attr.allocatable);
642
643                 CONSTRUCTOR_APPEND_ELT (v, s->field, tmp);
644                 offset = s->offset + s->length;
645               }
646           }
647
648       gcc_assert (!VEC_empty (constructor_elt, v));
649       ctor = build_constructor (union_type, v);
650       TREE_CONSTANT (ctor) = 1;
651       TREE_INVARIANT (ctor) = 1;
652       TREE_STATIC (ctor) = 1;
653       DECL_INITIAL (decl) = ctor;
654
655 #ifdef ENABLE_CHECKING
656       {
657         tree field, value;
658         unsigned HOST_WIDE_INT idx;
659         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), idx, field, value)
660           gcc_assert (TREE_CODE (field) == FIELD_DECL);
661       }
662 #endif
663     }
664
665   /* Build component reference for each variable.  */
666   for (s = head; s; s = next_s)
667     {
668       tree var_decl;
669
670       var_decl = build_decl (VAR_DECL, DECL_NAME (s->field),
671                              TREE_TYPE (s->field));
672       gfc_set_decl_location (var_decl, &s->sym->declared_at);
673       TREE_PUBLIC (var_decl) = TREE_PUBLIC (decl);
674       TREE_STATIC (var_decl) = TREE_STATIC (decl);
675       TREE_USED (var_decl) = TREE_USED (decl);
676       if (s->sym->attr.target)
677         TREE_ADDRESSABLE (var_decl) = 1;
678       /* This is a fake variable just for debugging purposes.  */
679       TREE_ASM_WRITTEN (var_decl) = 1;
680
681       if (com)
682         var_decl = pushdecl_top_level (var_decl);
683       else
684         gfc_add_decl_to_function (var_decl);
685
686       SET_DECL_VALUE_EXPR (var_decl,
687                            build3 (COMPONENT_REF, TREE_TYPE (s->field),
688                                    decl, s->field, NULL_TREE));
689       DECL_HAS_VALUE_EXPR_P (var_decl) = 1;
690       GFC_DECL_COMMON_OR_EQUIV (var_decl) = 1;
691
692       if (s->sym->attr.assign)
693         {
694           gfc_allocate_lang_decl (var_decl);
695           GFC_DECL_ASSIGN (var_decl) = 1;
696           GFC_DECL_STRING_LEN (var_decl) = GFC_DECL_STRING_LEN (s->field);
697           GFC_DECL_ASSIGN_ADDR (var_decl) = GFC_DECL_ASSIGN_ADDR (s->field);
698         }
699
700       s->sym->backend_decl = var_decl;
701
702       next_s = s->next;
703       gfc_free (s);
704     }
705 }
706
707
708 /* Given a symbol, find it in the current segment list. Returns NULL if
709    not found.  */
710
711 static segment_info *
712 find_segment_info (gfc_symbol *symbol)
713 {
714   segment_info *n;
715
716   for (n = current_segment; n; n = n->next)
717     {
718       if (n->sym == symbol)
719         return n;
720     }
721
722   return NULL;
723 }
724
725
726 /* Given an expression node, make sure it is a constant integer and return
727    the mpz_t value.  */
728
729 static mpz_t *
730 get_mpz (gfc_expr *e)
731 {
732
733   if (e->expr_type != EXPR_CONSTANT)
734     gfc_internal_error ("get_mpz(): Not an integer constant");
735
736   return &e->value.integer;
737 }
738
739
740 /* Given an array specification and an array reference, figure out the
741    array element number (zero based). Bounds and elements are guaranteed
742    to be constants.  If something goes wrong we generate an error and
743    return zero.  */
744  
745 static HOST_WIDE_INT
746 element_number (gfc_array_ref *ar)
747 {
748   mpz_t multiplier, offset, extent, n;
749   gfc_array_spec *as;
750   HOST_WIDE_INT i, rank;
751
752   as = ar->as;
753   rank = as->rank;
754   mpz_init_set_ui (multiplier, 1);
755   mpz_init_set_ui (offset, 0);
756   mpz_init (extent);
757   mpz_init (n);
758
759   for (i = 0; i < rank; i++)
760     { 
761       if (ar->dimen_type[i] != DIMEN_ELEMENT)
762         gfc_internal_error ("element_number(): Bad dimension type");
763
764       mpz_sub (n, *get_mpz (ar->start[i]), *get_mpz (as->lower[i]));
765  
766       mpz_mul (n, n, multiplier);
767       mpz_add (offset, offset, n);
768  
769       mpz_sub (extent, *get_mpz (as->upper[i]), *get_mpz (as->lower[i]));
770       mpz_add_ui (extent, extent, 1);
771  
772       if (mpz_sgn (extent) < 0)
773         mpz_set_ui (extent, 0);
774  
775       mpz_mul (multiplier, multiplier, extent);
776     } 
777  
778   i = mpz_get_ui (offset);
779  
780   mpz_clear (multiplier);
781   mpz_clear (offset);
782   mpz_clear (extent);
783   mpz_clear (n);
784  
785   return i;
786 }
787
788
789 /* Given a single element of an equivalence list, figure out the offset
790    from the base symbol.  For simple variables or full arrays, this is
791    simply zero.  For an array element we have to calculate the array
792    element number and multiply by the element size. For a substring we
793    have to calculate the further reference.  */
794
795 static HOST_WIDE_INT
796 calculate_offset (gfc_expr *e)
797 {
798   HOST_WIDE_INT n, element_size, offset;
799   gfc_typespec *element_type;
800   gfc_ref *reference;
801
802   offset = 0;
803   element_type = &e->symtree->n.sym->ts;
804
805   for (reference = e->ref; reference; reference = reference->next)
806     switch (reference->type)
807       {
808       case REF_ARRAY:
809         switch (reference->u.ar.type)
810           {
811           case AR_FULL:
812             break;
813
814           case AR_ELEMENT:
815             n = element_number (&reference->u.ar);
816             if (element_type->type == BT_CHARACTER)
817               gfc_conv_const_charlen (element_type->cl);
818             element_size =
819               int_size_in_bytes (gfc_typenode_for_spec (element_type));
820             offset += n * element_size;
821             break;
822
823           default:
824             gfc_error ("Bad array reference at %L", &e->where);
825           }
826         break;
827       case REF_SUBSTRING:
828         if (reference->u.ss.start != NULL)
829           offset += mpz_get_ui (*get_mpz (reference->u.ss.start)) - 1;
830         break;
831       default:
832         gfc_error ("Illegal reference type at %L as EQUIVALENCE object",
833                    &e->where);
834     }
835   return offset;
836 }
837
838
839 /* Add a new segment_info structure to the current segment.  eq1 is already
840    in the list, eq2 is not.  */
841
842 static void
843 new_condition (segment_info *v, gfc_equiv *eq1, gfc_equiv *eq2)
844 {
845   HOST_WIDE_INT offset1, offset2;
846   segment_info *a;
847
848   offset1 = calculate_offset (eq1->expr);
849   offset2 = calculate_offset (eq2->expr);
850
851   a = get_segment_info (eq2->expr->symtree->n.sym,
852                         v->offset + offset1 - offset2);
853  
854   current_segment = add_segments (current_segment, a);
855 }
856
857
858 /* Given two equivalence structures that are both already in the list, make
859    sure that this new condition is not violated, generating an error if it
860    is.  */
861
862 static void
863 confirm_condition (segment_info *s1, gfc_equiv *eq1, segment_info *s2,
864                    gfc_equiv *eq2)
865 {
866   HOST_WIDE_INT offset1, offset2;
867
868   offset1 = calculate_offset (eq1->expr);
869   offset2 = calculate_offset (eq2->expr);
870
871   if (s1->offset + offset1 != s2->offset + offset2)
872     gfc_error ("Inconsistent equivalence rules involving '%s' at %L and "
873                "'%s' at %L", s1->sym->name, &s1->sym->declared_at,
874                s2->sym->name, &s2->sym->declared_at);
875 }
876
877
878 /* Process a new equivalence condition. eq1 is know to be in segment f.
879    If eq2 is also present then confirm that the condition holds.
880    Otherwise add a new variable to the segment list.  */
881
882 static void
883 add_condition (segment_info *f, gfc_equiv *eq1, gfc_equiv *eq2)
884 {
885   segment_info *n;
886
887   n = find_segment_info (eq2->expr->symtree->n.sym);
888
889   if (n == NULL)
890     new_condition (f, eq1, eq2);
891   else
892     confirm_condition (f, eq1, n, eq2);
893 }
894
895
896 /* Given a segment element, search through the equivalence lists for unused
897    conditions that involve the symbol.  Add these rules to the segment.  */
898
899 static bool
900 find_equivalence (segment_info *n)
901 {
902   gfc_equiv *e1, *e2, *eq;
903   bool found;
904
905   found = FALSE;
906
907   for (e1 = n->sym->ns->equiv; e1; e1 = e1->next)
908     {
909       eq = NULL;
910
911       /* Search the equivalence list, including the root (first) element
912          for the symbol that owns the segment.  */
913       for (e2 = e1; e2; e2 = e2->eq)
914         {
915           if (!e2->used && e2->expr->symtree->n.sym == n->sym)
916             {
917               eq = e2;
918               break;
919             }
920         }
921
922       /* Go to the next root element.  */
923       if (eq == NULL)
924         continue;
925
926       eq->used = 1;
927
928       /* Now traverse the equivalence list matching the offsets.  */
929       for (e2 = e1; e2; e2 = e2->eq)
930         {
931           if (!e2->used && e2 != eq)
932             {
933               add_condition (n, eq, e2);
934               e2->used = 1;
935               found = TRUE;
936             }
937         }
938     }
939   return found;
940 }
941
942
943 /* Add all symbols equivalenced within a segment.  We need to scan the
944    segment list multiple times to include indirect equivalences.  Since
945    a new segment_info can inserted at the beginning of the segment list,
946    depending on its offset, we have to force a final pass through the
947    loop by demanding that completion sees a pass with no matches; ie.
948    all symbols with equiv_built set and no new equivalences found.  */
949
950 static void
951 add_equivalences (bool *saw_equiv)
952 {
953   segment_info *f;
954   bool seen_one, more;
955
956   seen_one = false;
957   more = TRUE;
958   while (more)
959     {
960       more = FALSE;
961       for (f = current_segment; f; f = f->next)
962         {
963           if (!f->sym->equiv_built)
964             {
965               f->sym->equiv_built = 1;
966               seen_one = find_equivalence (f);
967               if (seen_one)
968                 {
969                   *saw_equiv = true;
970                   more = true;
971                 }
972             }
973         }
974     }
975
976   /* Add a copy of this segment list to the namespace.  */
977   copy_equiv_list_to_ns (current_segment);
978 }
979
980
981 /* Returns the offset necessary to properly align the current equivalence.
982    Sets *palign to the required alignment.  */
983
984 static HOST_WIDE_INT
985 align_segment (unsigned HOST_WIDE_INT *palign)
986 {
987   segment_info *s;
988   unsigned HOST_WIDE_INT offset;
989   unsigned HOST_WIDE_INT max_align;
990   unsigned HOST_WIDE_INT this_align;
991   unsigned HOST_WIDE_INT this_offset;
992
993   max_align = 1;
994   offset = 0;
995   for (s = current_segment; s; s = s->next)
996     {
997       this_align = TYPE_ALIGN_UNIT (s->field);
998       if (s->offset & (this_align - 1))
999         {
1000           /* Field is misaligned.  */
1001           this_offset = this_align - ((s->offset + offset) & (this_align - 1));
1002           if (this_offset & (max_align - 1))
1003             {
1004               /* Aligning this field would misalign a previous field.  */
1005               gfc_error ("The equivalence set for variable '%s' "
1006                          "declared at %L violates alignment requirements",
1007                          s->sym->name, &s->sym->declared_at);
1008             }
1009           offset += this_offset;
1010         }
1011       max_align = this_align;
1012     }
1013   if (palign)
1014     *palign = max_align;
1015   return offset;
1016 }
1017
1018
1019 /* Adjust segment offsets by the given amount.  */
1020
1021 static void
1022 apply_segment_offset (segment_info *s, HOST_WIDE_INT offset)
1023 {
1024   for (; s; s = s->next)
1025     s->offset += offset;
1026 }
1027
1028
1029 /* Lay out a symbol in a common block.  If the symbol has already been seen
1030    then check the location is consistent.  Otherwise create segments
1031    for that symbol and all the symbols equivalenced with it.  */
1032
1033 /* Translate a single common block.  */
1034
1035 static void
1036 translate_common (gfc_common_head *common, gfc_symbol *var_list)
1037 {
1038   gfc_symbol *sym;
1039   segment_info *s;
1040   segment_info *common_segment;
1041   HOST_WIDE_INT offset;
1042   HOST_WIDE_INT current_offset;
1043   unsigned HOST_WIDE_INT align;
1044   unsigned HOST_WIDE_INT max_align;
1045   bool saw_equiv;
1046
1047   common_segment = NULL;
1048   current_offset = 0;
1049   max_align = 1;
1050   saw_equiv = false;
1051
1052   /* Add symbols to the segment.  */
1053   for (sym = var_list; sym; sym = sym->common_next)
1054     {
1055       current_segment = common_segment;
1056       s = find_segment_info (sym);
1057
1058       /* Symbol has already been added via an equivalence.  Multiple
1059          use associations of the same common block result in equiv_built
1060          being set but no information about the symbol in the segment.  */
1061       if (s && sym->equiv_built)
1062         {
1063           /* Ensure the current location is properly aligned.  */
1064           align = TYPE_ALIGN_UNIT (s->field);
1065           current_offset = (current_offset + align - 1) &~ (align - 1);
1066
1067           /* Verify that it ended up where we expect it.  */
1068           if (s->offset != current_offset)
1069             {
1070               gfc_error ("Equivalence for '%s' does not match ordering of "
1071                          "COMMON '%s' at %L", sym->name,
1072                          common->name, &common->where);
1073             }
1074         }
1075       else
1076         {
1077           /* A symbol we haven't seen before.  */
1078           s = current_segment = get_segment_info (sym, current_offset);
1079
1080           /* Add all objects directly or indirectly equivalenced with this
1081              symbol.  */
1082           add_equivalences (&saw_equiv);
1083
1084           if (current_segment->offset < 0)
1085             gfc_error ("The equivalence set for '%s' cause an invalid "
1086                        "extension to COMMON '%s' at %L", sym->name,
1087                        common->name, &common->where);
1088
1089           offset = align_segment (&align);
1090
1091           if (offset & (max_align - 1))
1092             {
1093               /* The required offset conflicts with previous alignment
1094                  requirements.  Insert padding immediately before this
1095                  segment.  */
1096               gfc_warning ("Padding of %d bytes required before '%s' in "
1097                            "COMMON '%s' at %L", (int)offset, s->sym->name,
1098                            common->name, &common->where);
1099             }
1100           else
1101             {
1102               /* Offset the whole common block.  */
1103               apply_segment_offset (common_segment, offset);
1104             }
1105
1106           /* Apply the offset to the new segments.  */
1107           apply_segment_offset (current_segment, offset);
1108           current_offset += offset;
1109           if (max_align < align)
1110             max_align = align;
1111
1112           /* Add the new segments to the common block.  */
1113           common_segment = add_segments (common_segment, current_segment);
1114         }
1115
1116       /* The offset of the next common variable.  */
1117       current_offset += s->length;
1118     }
1119
1120   if (common_segment == NULL)
1121     {
1122       gfc_error ("COMMON '%s' at %L does not exist",
1123                  common->name, &common->where);
1124       return;
1125     }
1126
1127   if (common_segment->offset != 0)
1128     {
1129       gfc_warning ("COMMON '%s' at %L requires %d bytes of padding at start",
1130                    common->name, &common->where, (int)common_segment->offset);
1131     }
1132
1133   create_common (common, common_segment, saw_equiv);
1134 }
1135
1136
1137 /* Create a new block for each merged equivalence list.  */
1138
1139 static void
1140 finish_equivalences (gfc_namespace *ns)
1141 {
1142   gfc_equiv *z, *y;
1143   gfc_symbol *sym;
1144   gfc_common_head * c;
1145   HOST_WIDE_INT offset;
1146   unsigned HOST_WIDE_INT align;
1147   bool dummy;
1148
1149   for (z = ns->equiv; z; z = z->next)
1150     for (y = z->eq; y; y = y->eq)
1151       {
1152         if (y->used) 
1153           continue;
1154         sym = z->expr->symtree->n.sym;
1155         current_segment = get_segment_info (sym, 0);
1156
1157         /* All objects directly or indirectly equivalenced with this
1158            symbol.  */
1159         add_equivalences (&dummy);
1160
1161         /* Align the block.  */
1162         offset = align_segment (&align);
1163
1164         /* Ensure all offsets are positive.  */
1165         offset -= current_segment->offset & ~(align - 1);
1166
1167         apply_segment_offset (current_segment, offset);
1168
1169         /* Create the decl.  If this is a module equivalence, it has a
1170            unique name, pointed to by z->module.  This is written to a
1171            gfc_common_header to push create_common into using
1172            build_common_decl, so that the equivalence appears as an
1173            external symbol.  Otherwise, a local declaration is built using
1174            build_equiv_decl.  */
1175         if (z->module)
1176           {
1177             c = gfc_get_common_head ();
1178             /* We've lost the real location, so use the location of the
1179                enclosing procedure.  */
1180             c->where = ns->proc_name->declared_at;
1181             strcpy (c->name, z->module);
1182           }
1183         else
1184           c = NULL;
1185
1186         create_common (c, current_segment, true);
1187         break;
1188       }
1189 }
1190
1191
1192 /* Work function for translating a named common block.  */
1193
1194 static void
1195 named_common (gfc_symtree *st)
1196 {
1197   translate_common (st->n.common, st->n.common->head);
1198 }
1199
1200
1201 /* Translate the common blocks in a namespace. Unlike other variables,
1202    these have to be created before code, because the backend_decl depends
1203    on the rest of the common block.  */
1204
1205 void
1206 gfc_trans_common (gfc_namespace *ns)
1207 {
1208   gfc_common_head *c;
1209
1210   /* Translate the blank common block.  */
1211   if (ns->blank_common.head != NULL)
1212     {
1213       c = gfc_get_common_head ();
1214
1215       /* We've lost the real location, so use the location of the
1216          enclosing procedure.  */
1217       if (ns->proc_name != NULL)
1218         c->where = ns->proc_name->declared_at;
1219       else
1220         c->where = ns->blank_common.head->common_head->where;
1221
1222       strcpy (c->name, BLANK_COMMON_NAME);
1223       translate_common (c, ns->blank_common.head);
1224     }
1225
1226   /* Translate all named common blocks.  */
1227   gfc_traverse_symtree (ns->common_root, named_common);
1228
1229   /* Translate local equivalence.  */
1230   finish_equivalences (ns);
1231
1232   /* Commit the newly created symbols for common blocks and module
1233      equivalences.  */
1234   gfc_commit_symbols ();
1235 }