* gnat_rm.texi, gnat_ugn.texi, doc: Documentation updates and clean ups
[official-gcc.git] / gcc / ada / doc / gnat_rm / representation_clauses_and_pragmas.rst
blob8d28d24fe60a417b6152872bd488101120dcce46
1 .. _Representation_Clauses_and_Pragmas:
3 **********************************
4 Representation Clauses and Pragmas
5 **********************************
7 .. index:: Representation Clauses
9 .. index:: Representation Clause
11 .. index:: Representation Pragma
13 .. index:: Pragma, representation
15 This section describes the representation clauses accepted by GNAT, and
16 their effect on the representation of corresponding data objects.
18 GNAT fully implements Annex C (Systems Programming).  This means that all
19 the implementation advice sections in chapter 13 are fully implemented.
20 However, these sections only require a minimal level of support for
21 representation clauses.  GNAT provides much more extensive capabilities,
22 and this section describes the additional capabilities provided.
24 .. _Alignment_Clauses:
26 Alignment Clauses
27 =================
29 .. index:: Alignment Clause
31 GNAT requires that all alignment clauses specify a power of 2, and all
32 default alignments are always a power of 2.  The default alignment
33 values are as follows:
35 * *Primitive Types*.
37   For primitive types, the alignment is the minimum of the actual size of
38   objects of the type divided by `Storage_Unit`,
39   and the maximum alignment supported by the target.
40   (This maximum alignment is given by the GNAT-specific attribute
41   `Standard'Maximum_Alignment`; see :ref:`Attribute_Maximum_Alignment`.)
43   .. index:: Maximum_Alignment attribute
45   For example, for type `Long_Float`, the object size is 8 bytes, and the
46   default alignment will be 8 on any target that supports alignments
47   this large, but on some targets, the maximum alignment may be smaller
48   than 8, in which case objects of type `Long_Float` will be maximally
49   aligned.
51 * *Arrays*.
53   For arrays, the alignment is equal to the alignment of the component type
54   for the normal case where no packing or component size is given.  If the
55   array is packed, and the packing is effective (see separate section on
56   packed arrays), then the alignment will be one for long packed arrays,
57   or arrays whose length is not known at compile time.  For short packed
58   arrays, which are handled internally as modular types, the alignment
59   will be as described for primitive types, e.g., a packed array of length
60   31 bits will have an object size of four bytes, and an alignment of 4.
62 * *Records*.
64   For the normal non-packed case, the alignment of a record is equal to
65   the maximum alignment of any of its components.  For tagged records, this
66   includes the implicit access type used for the tag.  If a pragma `Pack`
67   is used and all components are packable (see separate section on pragma
68   `Pack`), then the resulting alignment is 1, unless the layout of the
69   record makes it profitable to increase it.
71   A special case is when:
73   * the size of the record is given explicitly, or a
74     full record representation clause is given, and
76   * the size of the record is 2, 4, or 8 bytes.
78   In this case, an alignment is chosen to match the
79   size of the record. For example, if we have:
81   .. code-block:: ada
83        type Small is record
84           A, B : Character;
85        end record;
86        for Small'Size use 16;
88   then the default alignment of the record type `Small` is 2, not 1. This
89   leads to more efficient code when the record is treated as a unit, and also
90   allows the type to specified as `Atomic` on architectures requiring
91   strict alignment.
93 An alignment clause may specify a larger alignment than the default value
94 up to some maximum value dependent on the target (obtainable by using the
95 attribute reference `Standard'Maximum_Alignment`). It may also specify
96 a smaller alignment than the default value for enumeration, integer and
97 fixed point types, as well as for record types, for example
99 .. code-block:: ada
101     type V is record
102        A : Integer;
103     end record;
105     for V'alignment use 1;
107 .. index:: Alignment, default
109 The default alignment for the type `V` is 4, as a result of the
110 Integer field in the record, but it is permissible, as shown, to
111 override the default alignment of the record with a smaller value.
113 .. index:: Alignment, subtypes
115 Note that according to the Ada standard, an alignment clause applies only
116 to the first named subtype. If additional subtypes are declared, then the
117 compiler is allowed to choose any alignment it likes, and there is no way
118 to control this choice. Consider:
120 .. code-block:: ada
122      type R is range 1 .. 10_000;
123      for R'Alignment use 1;
124      subtype RS is R range 1 .. 1000;
126 The alignment clause specifies an alignment of 1 for the first named subtype
127 `R` but this does not necessarily apply to `RS`. When writing
128 portable Ada code, you should avoid writing code that explicitly or
129 implicitly relies on the alignment of such subtypes.
131 For the GNAT compiler, if an explicit alignment clause is given, this
132 value is also used for any subsequent subtypes. So for GNAT, in the
133 above example, you can count on the alignment of `RS` being 1. But this
134 assumption is non-portable, and other compilers may choose different
135 alignments for the subtype `RS`.
137 .. _Size_Clauses:
139 Size Clauses
140 ============
142 .. index:: Size Clause
144 The default size for a type `T` is obtainable through the
145 language-defined attribute `T'Size` and also through the
146 equivalent GNAT-defined attribute `T'Value_Size`.
147 For objects of type `T`, GNAT will generally increase the type size
148 so that the object size (obtainable through the GNAT-defined attribute
149 `T'Object_Size`)
150 is a multiple of `T'Alignment * Storage_Unit`.
152 For example:
154 .. code-block:: ada
156      type Smallint is range 1 .. 6;
158      type Rec is record
159         Y1 : integer;
160         Y2 : boolean;
161      end record;
163 In this example, `Smallint'Size` = `Smallint'Value_Size` = 3,
164 as specified by the RM rules,
165 but objects of this type will have a size of 8
166 (`Smallint'Object_Size` = 8),
167 since objects by default occupy an integral number
168 of storage units.  On some targets, notably older
169 versions of the Digital Alpha, the size of stand
170 alone objects of this type may be 32, reflecting
171 the inability of the hardware to do byte load/stores.
173 Similarly, the size of type `Rec` is 40 bits
174 (`Rec'Size` = `Rec'Value_Size` = 40), but
175 the alignment is 4, so objects of this type will have
176 their size increased to 64 bits so that it is a multiple
177 of the alignment (in bits).  This decision is
178 in accordance with the specific Implementation Advice in RM 13.3(43):
180    "A `Size` clause should be supported for an object if the specified
181    `Size` is at least as large as its subtype's `Size`, and corresponds
182    to a size in storage elements that is a multiple of the object's
183    `Alignment` (if the `Alignment` is nonzero)."
185 An explicit size clause may be used to override the default size by
186 increasing it.  For example, if we have:
188 .. code-block:: ada
190      type My_Boolean is new Boolean;
191      for My_Boolean'Size use 32;
193 then values of this type will always be 32 bits long.  In the case of
194 discrete types, the size can be increased up to 64 bits, with the effect
195 that the entire specified field is used to hold the value, sign- or
196 zero-extended as appropriate.  If more than 64 bits is specified, then
197 padding space is allocated after the value, and a warning is issued that
198 there are unused bits.
200 Similarly the size of records and arrays may be increased, and the effect
201 is to add padding bits after the value.  This also causes a warning message
202 to be generated.
204 The largest Size value permitted in GNAT is 2**31-1.  Since this is a
205 Size in bits, this corresponds to an object of size 256 megabytes (minus
206 one).  This limitation is true on all targets.  The reason for this
207 limitation is that it improves the quality of the code in many cases
208 if it is known that a Size value can be accommodated in an object of
209 type Integer.
212 .. _Storage_Size_Clauses:
214 Storage_Size Clauses
215 ====================
217 .. index:: Storage_Size Clause
219 For tasks, the `Storage_Size` clause specifies the amount of space
220 to be allocated for the task stack.  This cannot be extended, and if the
221 stack is exhausted, then `Storage_Error` will be raised (if stack
222 checking is enabled).  Use a `Storage_Size` attribute definition clause,
223 or a `Storage_Size` pragma in the task definition to set the
224 appropriate required size.  A useful technique is to include in every
225 task definition a pragma of the form:
227 .. code-block:: ada
229      pragma Storage_Size (Default_Stack_Size);
231 Then `Default_Stack_Size` can be defined in a global package, and
232 modified as required. Any tasks requiring stack sizes different from the
233 default can have an appropriate alternative reference in the pragma.
235 You can also use the *-d* binder switch to modify the default stack
236 size.
238 For access types, the `Storage_Size` clause specifies the maximum
239 space available for allocation of objects of the type.  If this space is
240 exceeded then `Storage_Error` will be raised by an allocation attempt.
241 In the case where the access type is declared local to a subprogram, the
242 use of a `Storage_Size` clause triggers automatic use of a special
243 predefined storage pool (`System.Pool_Size`) that ensures that all
244 space for the pool is automatically reclaimed on exit from the scope in
245 which the type is declared.
247 A special case recognized by the compiler is the specification of a
248 `Storage_Size` of zero for an access type.  This means that no
249 items can be allocated from the pool, and this is recognized at compile
250 time, and all the overhead normally associated with maintaining a fixed
251 size storage pool is eliminated.  Consider the following example:
253 .. code-block:: ada
255      procedure p is
256         type R is array (Natural) of Character;
257         type P is access all R;
258         for P'Storage_Size use 0;
259         --  Above access type intended only for interfacing purposes
261         y : P;
263         procedure g (m : P);
264         pragma Import (C, g);
266         --  ...
268      begin
269         --  ...
270         y := new R;
271      end;
273 As indicated in this example, these dummy storage pools are often useful in
274 connection with interfacing where no object will ever be allocated.  If you
275 compile the above example, you get the warning:
279      p.adb:16:09: warning: allocation from empty storage pool
280      p.adb:16:09: warning: Storage_Error will be raised at run time
283 Of course in practice, there will not be any explicit allocators in the
284 case of such an access declaration.
286 .. _Size_of_Variant_Record_Objects:
288 Size of Variant Record Objects
289 ==============================
291 .. index:: Size, variant record objects
293 .. index:: Variant record objects, size
295 In the case of variant record objects, there is a question whether Size gives
296 information about a particular variant, or the maximum size required
297 for any variant.  Consider the following program
299 .. code-block:: ada
301   with Text_IO; use Text_IO;
302   procedure q is
303      type R1 (A : Boolean := False) is record
304        case A is
305          when True  => X : Character;
306          when False => null;
307        end case;
308      end record;
310      V1 : R1 (False);
311      V2 : R1;
313   begin
314      Put_Line (Integer'Image (V1'Size));
315      Put_Line (Integer'Image (V2'Size));
316   end q;
318 Here we are dealing with a variant record, where the True variant
319 requires 16 bits, and the False variant requires 8 bits.
320 In the above example, both V1 and V2 contain the False variant,
321 which is only 8 bits long.  However, the result of running the
322 program is:
326   8
327   16
329 The reason for the difference here is that the discriminant value of
330 V1 is fixed, and will always be False.  It is not possible to assign
331 a True variant value to V1, therefore 8 bits is sufficient.  On the
332 other hand, in the case of V2, the initial discriminant value is
333 False (from the default), but it is possible to assign a True
334 variant value to V2, therefore 16 bits must be allocated for V2
335 in the general case, even fewer bits may be needed at any particular
336 point during the program execution.
338 As can be seen from the output of this program, the `'Size`
339 attribute applied to such an object in GNAT gives the actual allocated
340 size of the variable, which is the largest size of any of the variants.
341 The Ada Reference Manual is not completely clear on what choice should
342 be made here, but the GNAT behavior seems most consistent with the
343 language in the RM.
345 In some cases, it may be desirable to obtain the size of the current
346 variant, rather than the size of the largest variant.  This can be
347 achieved in GNAT by making use of the fact that in the case of a
348 subprogram parameter, GNAT does indeed return the size of the current
349 variant (because a subprogram has no way of knowing how much space
350 is actually allocated for the actual).
352 Consider the following modified version of the above program:
354 .. code-block:: ada
356   with Text_IO; use Text_IO;
357   procedure q is
358      type R1 (A : Boolean := False) is record
359        case A is
360          when True  => X : Character;
361          when False => null;
362        end case;
363      end record;
365      V2 : R1;
367      function Size (V : R1) return Integer is
368      begin
369         return V'Size;
370      end Size;
372   begin
373      Put_Line (Integer'Image (V2'Size));
374      Put_Line (Integer'Image (Size (V2)));
375      V2 := (True, 'x');
376      Put_Line (Integer'Image (V2'Size));
377      Put_Line (Integer'Image (Size (V2)));
378   end q;
380 The output from this program is
384   16
385   8
386   16
387   16
389 Here we see that while the `'Size` attribute always returns
390 the maximum size, regardless of the current variant value, the
391 `Size` function does indeed return the size of the current
392 variant value.
395 .. _Biased_Representation:
397 Biased Representation
398 =====================
400 .. index:: Size for biased representation
402 .. index:: Biased representation
404 In the case of scalars with a range starting at other than zero, it is
405 possible in some cases to specify a size smaller than the default minimum
406 value, and in such cases, GNAT uses an unsigned biased representation,
407 in which zero is used to represent the lower bound, and successive values
408 represent successive values of the type.
410 For example, suppose we have the declaration:
412 .. code-block:: ada
414      type Small is range -7 .. -4;
415      for Small'Size use 2;
417 Although the default size of type `Small` is 4, the `Size`
418 clause is accepted by GNAT and results in the following representation
419 scheme:
423     -7 is represented as 2#00#
424     -6 is represented as 2#01#
425     -5 is represented as 2#10#
426     -4 is represented as 2#11#
428 Biased representation is only used if the specified `Size` clause
429 cannot be accepted in any other manner.  These reduced sizes that force
430 biased representation can be used for all discrete types except for
431 enumeration types for which a representation clause is given.
434 .. _Value_Size_and_Object_Size_Clauses:
436 Value_Size and Object_Size Clauses
437 ==================================
439 .. index:: Value_Size
440 .. index:: Object_Size
441 .. index:: Size, of objects
443 In Ada 95 and Ada 2005, `T'Size` for a type `T` is the minimum
444 number of bits required to hold values of type `T`.
445 Although this interpretation was allowed in Ada 83, it was not required,
446 and this requirement in practice can cause some significant difficulties.
447 For example, in most Ada 83 compilers, `Natural'Size` was 32.
448 However, in Ada 95 and Ada 2005,
449 `Natural'Size` is
450 typically 31.  This means that code may change in behavior when moving
451 from Ada 83 to Ada 95 or Ada 2005.  For example, consider:
453 .. code-block:: ada
455      type Rec is record;
456         A : Natural;
457         B : Natural;
458      end record;
460      for Rec use record
461         at 0  range 0 .. Natural'Size - 1;
462         at 0  range Natural'Size .. 2 * Natural'Size - 1;
463      end record;
465 In the above code, since the typical size of `Natural` objects
466 is 32 bits and `Natural'Size` is 31, the above code can cause
467 unexpected inefficient packing in Ada 95 and Ada 2005, and in general
468 there are cases where the fact that the object size can exceed the
469 size of the type causes surprises.
471 To help get around this problem GNAT provides two implementation
472 defined attributes, `Value_Size` and `Object_Size`.  When
473 applied to a type, these attributes yield the size of the type
474 (corresponding to the RM defined size attribute), and the size of
475 objects of the type respectively.
477 The `Object_Size` is used for determining the default size of
478 objects and components.  This size value can be referred to using the
479 `Object_Size` attribute.  The phrase 'is used' here means that it is
480 the basis of the determination of the size.  The backend is free to
481 pad this up if necessary for efficiency, e.g., an 8-bit stand-alone
482 character might be stored in 32 bits on a machine with no efficient
483 byte access instructions such as the Alpha.
485 The default rules for the value of `Object_Size` for
486 discrete types are as follows:
489   The `Object_Size` for base subtypes reflect the natural hardware
490   size in bits (run the compiler with *-gnatS* to find those values
491   for numeric types). Enumeration types and fixed-point base subtypes have
492   8, 16, 32 or 64 bits for this size, depending on the range of values
493   to be stored.
496   The `Object_Size` of a subtype is the same as the
497   `Object_Size` of
498   the type from which it is obtained.
501   The `Object_Size` of a derived base type is copied from the parent
502   base type, and the `Object_Size` of a derived first subtype is copied
503   from the parent first subtype.
505 The `Value_Size` attribute
506 is the (minimum) number of bits required to store a value
507 of the type.
508 This value is used to determine how tightly to pack
509 records or arrays with components of this type, and also affects
510 the semantics of unchecked conversion (unchecked conversions where
511 the `Value_Size` values differ generate a warning, and are potentially
512 target dependent).
514 The default rules for the value of `Value_Size` are as follows:
517   The `Value_Size` for a base subtype is the minimum number of bits
518   required to store all values of the type (including the sign bit
519   only if negative values are possible).
522   If a subtype statically matches the first subtype of a given type, then it has
523   by default the same `Value_Size` as the first subtype.  This is a
524   consequence of RM 13.1(14): "if two subtypes statically match,
525   then their subtype-specific aspects are the same".)
528   All other subtypes have a `Value_Size` corresponding to the minimum
529   number of bits required to store all values of the subtype.  For
530   dynamic bounds, it is assumed that the value can range down or up
531   to the corresponding bound of the ancestor
533 The RM defined attribute `Size` corresponds to the
534 `Value_Size` attribute.
536 The `Size` attribute may be defined for a first-named subtype.  This sets
537 the `Value_Size` of
538 the first-named subtype to the given value, and the
539 `Object_Size` of this first-named subtype to the given value padded up
540 to an appropriate boundary.  It is a consequence of the default rules
541 above that this `Object_Size` will apply to all further subtypes.  On the
542 other hand, `Value_Size` is affected only for the first subtype, any
543 dynamic subtypes obtained from it directly, and any statically matching
544 subtypes.  The `Value_Size` of any other static subtypes is not affected.
546 `Value_Size` and
547 `Object_Size` may be explicitly set for any subtype using
548 an attribute definition clause.  Note that the use of these attributes
549 can cause the RM 13.1(14) rule to be violated.  If two access types
550 reference aliased objects whose subtypes have differing `Object_Size`
551 values as a result of explicit attribute definition clauses, then it
552 is illegal to convert from one access subtype to the other. For a more
553 complete description of this additional legality rule, see the
554 description of the `Object_Size` attribute.
556 To get a feel for the difference, consider the following examples (note
557 that in each case the base is `Short_Short_Integer` with a size of 8):
559 +---------------------------------------------+-------------+-------------+
560 |Type or subtype declaration                  | Object_Size |   Value_Size|
561 +=============================================+=============+=============+
562 |``type x1 is range 0 .. 5;``                 |  8          |    3        |
563 +---------------------------------------------+-------------+-------------+
564 |``type x2 is range 0 .. 5;``                 | 16          |   12        |
565 |``for x2'size use 12;``                      |             |             |
566 +---------------------------------------------+-------------+-------------+
567 |``subtype x3 is x2 range 0 .. 3;``           | 16          |    2        |
568 +---------------------------------------------+-------------+-------------+
569 |``subtype x4 is x2'base range 0 .. 10;``     |  8          |    4        |
570 +---------------------------------------------+-------------+-------------+
571 |``dynamic : x2'Base range -64 .. +63;``      |             |             |
572 +---------------------------------------------+-------------+-------------+
573 |``subtype x5 is x2 range 0 .. dynamic;``     | 16          |    3*       |
574 +---------------------------------------------+-------------+-------------+
575 |``subtype x6 is x2'base range 0 .. dynamic;``|  8          |    7*       |
576 +---------------------------------------------+-------------+-------------+
578 Note: the entries marked '*' are not actually specified by the Ada
579 Reference Manual, which has nothing to say about size in the dynamic
580 case. What GNAT does is to allocate sufficient bits to accomodate any
581 possible dynamic values for the bounds at run-time.
583 So far, so good, but GNAT has to obey the RM rules, so the question is
584 under what conditions must the RM `Size` be used.
585 The following is a list
586 of the occasions on which the RM `Size` must be used:
589   Component size for packed arrays or records
592   Value of the attribute `Size` for a type
595   Warning about sizes not matching for unchecked conversion
597 For record types, the `Object_Size` is always a multiple of the
598 alignment of the type (this is true for all types). In some cases the
599 `Value_Size` can be smaller. Consider:
602 .. code-block:: ada
604      type R is record
605        X : Integer;
606        Y : Character;
607      end record;
610 On a typical 32-bit architecture, the X component will be four bytes, and
611 require four-byte alignment, and the Y component will be one byte. In this
612 case `R'Value_Size` will be 40 (bits) since this is the minimum size
613 required to store a value of this type, and for example, it is permissible
614 to have a component of type R in an outer array whose component size is
615 specified to be 48 bits. However, `R'Object_Size` will be 64 (bits),
616 since it must be rounded up so that this value is a multiple of the
617 alignment (4 bytes = 32 bits).
619 For all other types, the `Object_Size`
620 and `Value_Size` are the same (and equivalent to the RM attribute `Size`).
621 Only `Size` may be specified for such types.
623 Note that `Value_Size` can be used to force biased representation
624 for a particular subtype. Consider this example:
627 .. code-block:: ada
629      type R is (A, B, C, D, E, F);
630      subtype RAB is R range A .. B;
631      subtype REF is R range E .. F;
634 By default, `RAB`
635 has a size of 1 (sufficient to accommodate the representation
636 of `A` and `B`, 0 and 1), and `REF`
637 has a size of 3 (sufficient to accommodate the representation
638 of `E` and `F`, 4 and 5). But if we add the
639 following `Value_Size` attribute definition clause:
642 .. code-block:: ada
644      for REF'Value_Size use 1;
647 then biased representation is forced for `REF`,
648 and 0 will represent `E` and 1 will represent `F`.
649 A warning is issued when a `Value_Size` attribute
650 definition clause forces biased representation. This
651 warning can be turned off using `-gnatw.B`.
653 .. _Component_Size_Clauses:
655 Component_Size Clauses
656 ======================
658 .. index:: Component_Size Clause
660 Normally, the value specified in a component size clause must be consistent
661 with the subtype of the array component with regard to size and alignment.
662 In other words, the value specified must be at least equal to the size
663 of this subtype, and must be a multiple of the alignment value.
665 In addition, component size clauses are allowed which cause the array
666 to be packed, by specifying a smaller value.  A first case is for
667 component size values in the range 1 through 63.  The value specified
668 must not be smaller than the Size of the subtype.  GNAT will accurately
669 honor all packing requests in this range.  For example, if we have:
672 .. code-block:: ada
674   type r is array (1 .. 8) of Natural;
675   for r'Component_Size use 31;
678 then the resulting array has a length of 31 bytes (248 bits = 8 * 31).
679 Of course access to the components of such an array is considerably
680 less efficient than if the natural component size of 32 is used.
681 A second case is when the subtype of the component is a record type
682 padded because of its default alignment.  For example, if we have:
685 .. code-block:: ada
687   type r is record
688     i : Integer;
689     j : Integer;
690     b : Boolean;
691   end record;
693   type a is array (1 .. 8) of r;
694   for a'Component_Size use 72;
697 then the resulting array has a length of 72 bytes, instead of 96 bytes
698 if the alignment of the record (4) was obeyed.
700 Note that there is no point in giving both a component size clause
701 and a pragma Pack for the same array type. if such duplicate
702 clauses are given, the pragma Pack will be ignored.
704 .. _Bit_Order_Clauses:
706 Bit_Order Clauses
707 =================
709 .. index:: Bit_Order Clause
711 .. index:: bit ordering
713 .. index:: ordering, of bits
715 For record subtypes, GNAT permits the specification of the `Bit_Order`
716 attribute.  The specification may either correspond to the default bit
717 order for the target, in which case the specification has no effect and
718 places no additional restrictions, or it may be for the non-standard
719 setting (that is the opposite of the default).
721 In the case where the non-standard value is specified, the effect is
722 to renumber bits within each byte, but the ordering of bytes is not
723 affected.  There are certain
724 restrictions placed on component clauses as follows:
727 * Components fitting within a single storage unit.
729   These are unrestricted, and the effect is merely to renumber bits.  For
730   example if we are on a little-endian machine with `Low_Order_First`
731   being the default, then the following two declarations have exactly
732   the same effect:
735   ::
737        type R1 is record
738           A : Boolean;
739           B : Integer range 1 .. 120;
740        end record;
742        for R1 use record
743           A at 0 range 0 .. 0;
744           B at 0 range 1 .. 7;
745        end record;
747        type R2 is record
748           A : Boolean;
749           B : Integer range 1 .. 120;
750        end record;
752        for R2'Bit_Order use High_Order_First;
754        for R2 use record
755           A at 0 range 7 .. 7;
756           B at 0 range 0 .. 6;
757        end record;
760   The useful application here is to write the second declaration with the
761   `Bit_Order` attribute definition clause, and know that it will be treated
762   the same, regardless of whether the target is little-endian or big-endian.
764 * Components occupying an integral number of bytes.
766   These are components that exactly fit in two or more bytes.  Such component
767   declarations are allowed, but have no effect, since it is important to realize
768   that the `Bit_Order` specification does not affect the ordering of bytes.
769   In particular, the following attempt at getting an endian-independent integer
770   does not work:
773   ::
775        type R2 is record
776           A : Integer;
777        end record;
779        for R2'Bit_Order use High_Order_First;
781        for R2 use record
782           A at 0 range 0 .. 31;
783        end record;
786   This declaration will result in a little-endian integer on a
787   little-endian machine, and a big-endian integer on a big-endian machine.
788   If byte flipping is required for interoperability between big- and
789   little-endian machines, this must be explicitly programmed.  This capability
790   is not provided by `Bit_Order`.
792 * Components that are positioned across byte boundaries
794   but do not occupy an integral number of bytes.  Given that bytes are not
795   reordered, such fields would occupy a non-contiguous sequence of bits
796   in memory, requiring non-trivial code to reassemble.  They are for this
797   reason not permitted, and any component clause specifying such a layout
798   will be flagged as illegal by GNAT.
801 Since the misconception that Bit_Order automatically deals with all
802 endian-related incompatibilities is a common one, the specification of
803 a component field that is an integral number of bytes will always
804 generate a warning.  This warning may be suppressed using `pragma Warnings (Off)`
805 if desired.  The following section contains additional
806 details regarding the issue of byte ordering.
808 .. _Effect_of_Bit_Order_on_Byte_Ordering:
810 Effect of Bit_Order on Byte Ordering
811 ====================================
813 .. index:: byte ordering
815 .. index:: ordering, of bytes
817 In this section we will review the effect of the `Bit_Order` attribute
818 definition clause on byte ordering.  Briefly, it has no effect at all, but
819 a detailed example will be helpful.  Before giving this
820 example, let us review the precise
821 definition of the effect of defining `Bit_Order`.  The effect of a
822 non-standard bit order is described in section 13.5.3 of the Ada
823 Reference Manual:
825    "2   A bit ordering is a method of interpreting the meaning of
826    the storage place attributes."
828 To understand the precise definition of storage place attributes in
829 this context, we visit section 13.5.1 of the manual:
831    "13   A record_representation_clause (without the mod_clause)
832    specifies the layout.  The storage place attributes (see 13.5.2)
833    are taken from the values of the position, first_bit, and last_bit
834    expressions after normalizing those values so that first_bit is
835    less than Storage_Unit."
837 The critical point here is that storage places are taken from
838 the values after normalization, not before.  So the `Bit_Order`
839 interpretation applies to normalized values.  The interpretation
840 is described in the later part of the 13.5.3 paragraph:
842    "2   A bit ordering is a method of interpreting the meaning of
843    the storage place attributes.  High_Order_First (known in the
844    vernacular as 'big endian') means that the first bit of a
845    storage element (bit 0) is the most significant bit (interpreting
846    the sequence of bits that represent a component as an unsigned
847    integer value).  Low_Order_First (known in the vernacular as
848    'little endian') means the opposite: the first bit is the
849    least significant."
851 Note that the numbering is with respect to the bits of a storage
852 unit.  In other words, the specification affects only the numbering
853 of bits within a single storage unit.
855 We can make the effect clearer by giving an example.
857 Suppose that we have an external device which presents two bytes, the first
858 byte presented, which is the first (low addressed byte) of the two byte
859 record is called Master, and the second byte is called Slave.
861 The left most (most significant bit is called Control for each byte, and
862 the remaining 7 bits are called V1, V2, ... V7, where V7 is the rightmost
863 (least significant) bit.
865 On a big-endian machine, we can write the following representation clause
868 .. code-block:: ada
870      type Data is record
871         Master_Control : Bit;
872         Master_V1      : Bit;
873         Master_V2      : Bit;
874         Master_V3      : Bit;
875         Master_V4      : Bit;
876         Master_V5      : Bit;
877         Master_V6      : Bit;
878         Master_V7      : Bit;
879         Slave_Control  : Bit;
880         Slave_V1       : Bit;
881         Slave_V2       : Bit;
882         Slave_V3       : Bit;
883         Slave_V4       : Bit;
884         Slave_V5       : Bit;
885         Slave_V6       : Bit;
886         Slave_V7       : Bit;
887      end record;
889      for Data use record
890         Master_Control at 0 range 0 .. 0;
891         Master_V1      at 0 range 1 .. 1;
892         Master_V2      at 0 range 2 .. 2;
893         Master_V3      at 0 range 3 .. 3;
894         Master_V4      at 0 range 4 .. 4;
895         Master_V5      at 0 range 5 .. 5;
896         Master_V6      at 0 range 6 .. 6;
897         Master_V7      at 0 range 7 .. 7;
898         Slave_Control  at 1 range 0 .. 0;
899         Slave_V1       at 1 range 1 .. 1;
900         Slave_V2       at 1 range 2 .. 2;
901         Slave_V3       at 1 range 3 .. 3;
902         Slave_V4       at 1 range 4 .. 4;
903         Slave_V5       at 1 range 5 .. 5;
904         Slave_V6       at 1 range 6 .. 6;
905         Slave_V7       at 1 range 7 .. 7;
906      end record;
909 Now if we move this to a little endian machine, then the bit ordering within
910 the byte is backwards, so we have to rewrite the record rep clause as:
913 .. code-block:: ada
915      for Data use record
916         Master_Control at 0 range 7 .. 7;
917         Master_V1      at 0 range 6 .. 6;
918         Master_V2      at 0 range 5 .. 5;
919         Master_V3      at 0 range 4 .. 4;
920         Master_V4      at 0 range 3 .. 3;
921         Master_V5      at 0 range 2 .. 2;
922         Master_V6      at 0 range 1 .. 1;
923         Master_V7      at 0 range 0 .. 0;
924         Slave_Control  at 1 range 7 .. 7;
925         Slave_V1       at 1 range 6 .. 6;
926         Slave_V2       at 1 range 5 .. 5;
927         Slave_V3       at 1 range 4 .. 4;
928         Slave_V4       at 1 range 3 .. 3;
929         Slave_V5       at 1 range 2 .. 2;
930         Slave_V6       at 1 range 1 .. 1;
931         Slave_V7       at 1 range 0 .. 0;
932      end record;
935 It is a nuisance to have to rewrite the clause, especially if
936 the code has to be maintained on both machines.  However,
937 this is a case that we can handle with the
938 `Bit_Order` attribute if it is implemented.
939 Note that the implementation is not required on byte addressed
940 machines, but it is indeed implemented in GNAT.
941 This means that we can simply use the
942 first record clause, together with the declaration
945 .. code-block:: ada
947      for Data'Bit_Order use High_Order_First;
950 and the effect is what is desired, namely the layout is exactly the same,
951 independent of whether the code is compiled on a big-endian or little-endian
952 machine.
954 The important point to understand is that byte ordering is not affected.
955 A `Bit_Order` attribute definition never affects which byte a field
956 ends up in, only where it ends up in that byte.
957 To make this clear, let us rewrite the record rep clause of the previous
958 example as:
961 .. code-block:: ada
963      for Data'Bit_Order use High_Order_First;
964      for Data use record
965         Master_Control at 0 range  0 .. 0;
966         Master_V1      at 0 range  1 .. 1;
967         Master_V2      at 0 range  2 .. 2;
968         Master_V3      at 0 range  3 .. 3;
969         Master_V4      at 0 range  4 .. 4;
970         Master_V5      at 0 range  5 .. 5;
971         Master_V6      at 0 range  6 .. 6;
972         Master_V7      at 0 range  7 .. 7;
973         Slave_Control  at 0 range  8 .. 8;
974         Slave_V1       at 0 range  9 .. 9;
975         Slave_V2       at 0 range 10 .. 10;
976         Slave_V3       at 0 range 11 .. 11;
977         Slave_V4       at 0 range 12 .. 12;
978         Slave_V5       at 0 range 13 .. 13;
979         Slave_V6       at 0 range 14 .. 14;
980         Slave_V7       at 0 range 15 .. 15;
981      end record;
984 This is exactly equivalent to saying (a repeat of the first example):
987 .. code-block:: ada
989      for Data'Bit_Order use High_Order_First;
990      for Data use record
991         Master_Control at 0 range 0 .. 0;
992         Master_V1      at 0 range 1 .. 1;
993         Master_V2      at 0 range 2 .. 2;
994         Master_V3      at 0 range 3 .. 3;
995         Master_V4      at 0 range 4 .. 4;
996         Master_V5      at 0 range 5 .. 5;
997         Master_V6      at 0 range 6 .. 6;
998         Master_V7      at 0 range 7 .. 7;
999         Slave_Control  at 1 range 0 .. 0;
1000         Slave_V1       at 1 range 1 .. 1;
1001         Slave_V2       at 1 range 2 .. 2;
1002         Slave_V3       at 1 range 3 .. 3;
1003         Slave_V4       at 1 range 4 .. 4;
1004         Slave_V5       at 1 range 5 .. 5;
1005         Slave_V6       at 1 range 6 .. 6;
1006         Slave_V7       at 1 range 7 .. 7;
1007      end record;
1010 Why are they equivalent? Well take a specific field, the `Slave_V2`
1011 field.  The storage place attributes are obtained by normalizing the
1012 values given so that the `First_Bit` value is less than 8.  After
1013 normalizing the values (0,10,10) we get (1,2,2) which is exactly what
1014 we specified in the other case.
1016 Now one might expect that the `Bit_Order` attribute might affect
1017 bit numbering within the entire record component (two bytes in this
1018 case, thus affecting which byte fields end up in), but that is not
1019 the way this feature is defined, it only affects numbering of bits,
1020 not which byte they end up in.
1022 Consequently it never makes sense to specify a starting bit number
1023 greater than 7 (for a byte addressable field) if an attribute
1024 definition for `Bit_Order` has been given, and indeed it
1025 may be actively confusing to specify such a value, so the compiler
1026 generates a warning for such usage.
1028 If you do need to control byte ordering then appropriate conditional
1029 values must be used.  If in our example, the slave byte came first on
1030 some machines we might write:
1032 .. code-block:: ada
1034      Master_Byte_First constant Boolean := ...;
1036      Master_Byte : constant Natural :=
1037                      1 - Boolean'Pos (Master_Byte_First);
1038      Slave_Byte  : constant Natural :=
1039                      Boolean'Pos (Master_Byte_First);
1041      for Data'Bit_Order use High_Order_First;
1042      for Data use record
1043         Master_Control at Master_Byte range 0 .. 0;
1044         Master_V1      at Master_Byte range 1 .. 1;
1045         Master_V2      at Master_Byte range 2 .. 2;
1046         Master_V3      at Master_Byte range 3 .. 3;
1047         Master_V4      at Master_Byte range 4 .. 4;
1048         Master_V5      at Master_Byte range 5 .. 5;
1049         Master_V6      at Master_Byte range 6 .. 6;
1050         Master_V7      at Master_Byte range 7 .. 7;
1051         Slave_Control  at Slave_Byte  range 0 .. 0;
1052         Slave_V1       at Slave_Byte  range 1 .. 1;
1053         Slave_V2       at Slave_Byte  range 2 .. 2;
1054         Slave_V3       at Slave_Byte  range 3 .. 3;
1055         Slave_V4       at Slave_Byte  range 4 .. 4;
1056         Slave_V5       at Slave_Byte  range 5 .. 5;
1057         Slave_V6       at Slave_Byte  range 6 .. 6;
1058         Slave_V7       at Slave_Byte  range 7 .. 7;
1059      end record;
1061 Now to switch between machines, all that is necessary is
1062 to set the boolean constant `Master_Byte_First` in
1063 an appropriate manner.
1065 .. _Pragma_Pack_for_Arrays:
1067 Pragma Pack for Arrays
1068 ======================
1070 .. index:: Pragma Pack (for arrays)
1072 Pragma `Pack` applied to an array has no effect unless the component type
1073 is packable.  For a component type to be packable, it must be one of the
1074 following cases:
1077   Any scalar type
1079   Any type whose size is specified with a size clause
1081   Any packed array type with a static size
1083   Any record type padded because of its default alignment
1085 For all these cases, if the component subtype size is in the range
1086 1 through 63, then the effect of the pragma `Pack` is exactly as though a
1087 component size were specified giving the component subtype size.
1088 For example if we have:
1090 .. code-block:: ada
1092      type r is range 0 .. 17;
1094      type ar is array (1 .. 8) of r;
1095      pragma Pack (ar);
1097 Then the component size of `ar` will be set to 5 (i.e., to `r'size`,
1098 and the size of the array `ar` will be exactly 40 bits.
1100 Note that in some cases this rather fierce approach to packing can produce
1101 unexpected effects.  For example, in Ada 95 and Ada 2005,
1102 subtype `Natural` typically has a size of 31, meaning that if you
1103 pack an array of `Natural`, you get 31-bit
1104 close packing, which saves a few bits, but results in far less efficient
1105 access.  Since many other Ada compilers will ignore such a packing request,
1106 GNAT will generate a warning on some uses of pragma `Pack` that it guesses
1107 might not be what is intended.  You can easily remove this warning by
1108 using an explicit `Component_Size` setting instead, which never generates
1109 a warning, since the intention of the programmer is clear in this case.
1111 GNAT treats packed arrays in one of two ways.  If the size of the array is
1112 known at compile time and is less than 64 bits, then internally the array
1113 is represented as a single modular type, of exactly the appropriate number
1114 of bits.  If the length is greater than 63 bits, or is not known at compile
1115 time, then the packed array is represented as an array of bytes, and the
1116 length is always a multiple of 8 bits.
1118 Note that to represent a packed array as a modular type, the alignment must
1119 be suitable for the modular type involved. For example, on typical machines
1120 a 32-bit packed array will be represented by a 32-bit modular integer with
1121 an alignment of four bytes. If you explicitly override the default alignment
1122 with an alignment clause that is too small, the modular representation
1123 cannot be used. For example, consider the following set of declarations:
1125 .. code-block:: ada
1127      type R is range 1 .. 3;
1128      type S is array (1 .. 31) of R;
1129      for S'Component_Size use 2;
1130      for S'Size use 62;
1131      for S'Alignment use 1;
1133 If the alignment clause were not present, then a 62-bit modular
1134 representation would be chosen (typically with an alignment of 4 or 8
1135 bytes depending on the target). But the default alignment is overridden
1136 with the explicit alignment clause. This means that the modular
1137 representation cannot be used, and instead the array of bytes
1138 representation must be used, meaning that the length must be a multiple
1139 of 8. Thus the above set of declarations will result in a diagnostic
1140 rejecting the size clause and noting that the minimum size allowed is 64.
1142 .. index:: Pragma Pack (for type Natural)
1144 .. index:: Pragma Pack warning
1146 One special case that is worth noting occurs when the base type of the
1147 component size is 8/16/32 and the subtype is one bit less. Notably this
1148 occurs with subtype `Natural`. Consider:
1150 .. code-block:: ada
1152      type Arr is array (1 .. 32) of Natural;
1153      pragma Pack (Arr);
1155 In all commonly used Ada 83 compilers, this pragma Pack would be ignored,
1156 since typically `Natural'Size` is 32 in Ada 83, and in any case most
1157 Ada 83 compilers did not attempt 31 bit packing.
1159 In Ada 95 and Ada 2005, `Natural'Size` is required to be 31. Furthermore,
1160 GNAT really does pack 31-bit subtype to 31 bits. This may result in a
1161 substantial unintended performance penalty when porting legacy Ada 83 code.
1162 To help prevent this, GNAT generates a warning in such cases. If you really
1163 want 31 bit packing in a case like this, you can set the component size
1164 explicitly:
1166 .. code-block:: ada
1168      type Arr is array (1 .. 32) of Natural;
1169      for Arr'Component_Size use 31;
1171 Here 31-bit packing is achieved as required, and no warning is generated,
1172 since in this case the programmer intention is clear.
1174 .. _Pragma_Pack_for_Records:
1176 Pragma Pack for Records
1177 =======================
1179 .. index:: Pragma Pack (for records)
1181 Pragma `Pack` applied to a record will pack the components to reduce
1182 wasted space from alignment gaps and by reducing the amount of space
1183 taken by components.  We distinguish between *packable* components and
1184 *non-packable* components.
1185 Components of the following types are considered packable:
1188   Components of a primitive type are packable unless they are aliased
1189   or of an atomic type.
1192   Small packed arrays, whose size does not exceed 64 bits, and where the
1193   size is statically known at compile time, are represented internally
1194   as modular integers, and so they are also packable.
1197 All packable components occupy the exact number of bits corresponding to
1198 their `Size` value, and are packed with no padding bits, i.e., they
1199 can start on an arbitrary bit boundary.
1201 All other types are non-packable, they occupy an integral number of
1202 storage units, and
1203 are placed at a boundary corresponding to their alignment requirements.
1205 For example, consider the record
1207 .. code-block:: ada
1209      type Rb1 is array (1 .. 13) of Boolean;
1210      pragma Pack (Rb1);
1212      type Rb2 is array (1 .. 65) of Boolean;
1213      pragma Pack (Rb2);
1215      type AF is new Float with Atomic;
1217      type X2 is record
1218         L1 : Boolean;
1219         L2 : Duration;
1220         L3 : AF;
1221         L4 : Boolean;
1222         L5 : Rb1;
1223         L6 : Rb2;
1224      end record;
1225      pragma Pack (X2);
1227 The representation for the record X2 is as follows:
1229 .. code-block:: ada
1231   for X2'Size use 224;
1232   for X2 use record
1233      L1 at  0 range  0 .. 0;
1234      L2 at  0 range  1 .. 64;
1235      L3 at 12 range  0 .. 31;
1236      L4 at 16 range  0 .. 0;
1237      L5 at 16 range  1 .. 13;
1238      L6 at 18 range  0 .. 71;
1239   end record;
1241 Studying this example, we see that the packable fields `L1`
1242 and `L2` are
1243 of length equal to their sizes, and placed at specific bit boundaries (and
1244 not byte boundaries) to
1245 eliminate padding.  But `L3` is of a non-packable float type (because
1246 it is aliased), so it is on the next appropriate alignment boundary.
1248 The next two fields are fully packable, so `L4` and `L5` are
1249 minimally packed with no gaps.  However, type `Rb2` is a packed
1250 array that is longer than 64 bits, so it is itself non-packable.  Thus
1251 the `L6` field is aligned to the next byte boundary, and takes an
1252 integral number of bytes, i.e., 72 bits.
1254 .. _Record_Representation_Clauses:
1256 Record Representation Clauses
1257 =============================
1259 .. index:: Record Representation Clause
1261 Record representation clauses may be given for all record types, including
1262 types obtained by record extension.  Component clauses are allowed for any
1263 static component.  The restrictions on component clauses depend on the type
1264 of the component.
1266 .. index:: Component Clause
1268 For all components of an elementary type, the only restriction on component
1269 clauses is that the size must be at least the 'Size value of the type
1270 (actually the Value_Size).  There are no restrictions due to alignment,
1271 and such components may freely cross storage boundaries.
1273 Packed arrays with a size up to and including 64 bits are represented
1274 internally using a modular type with the appropriate number of bits, and
1275 thus the same lack of restriction applies.  For example, if you declare:
1277 .. code-block:: ada
1279      type R is array (1 .. 49) of Boolean;
1280      pragma Pack (R);
1281      for R'Size use 49;
1283 then a component clause for a component of type R may start on any
1284 specified bit boundary, and may specify a value of 49 bits or greater.
1286 For packed bit arrays that are longer than 64 bits, there are two
1287 cases. If the component size is a power of 2 (1,2,4,8,16,32 bits),
1288 including the important case of single bits or boolean values, then
1289 there are no limitations on placement of such components, and they
1290 may start and end at arbitrary bit boundaries.
1292 If the component size is not a power of 2 (e.g., 3 or 5), then
1293 an array of this type longer than 64 bits must always be placed on
1294 on a storage unit (byte) boundary and occupy an integral number
1295 of storage units (bytes). Any component clause that does not
1296 meet this requirement will be rejected.
1298 Any aliased component, or component of an aliased type, must
1299 have its normal alignment and size. A component clause that
1300 does not meet this requirement will be rejected.
1302 The tag field of a tagged type always occupies an address sized field at
1303 the start of the record.  No component clause may attempt to overlay this
1304 tag. When a tagged type appears as a component, the tag field must have
1305 proper alignment
1307 In the case of a record extension T1, of a type T, no component clause applied
1308 to the type T1 can specify a storage location that would overlap the first
1309 T'Size bytes of the record.
1311 For all other component types, including non-bit-packed arrays,
1312 the component can be placed at an arbitrary bit boundary,
1313 so for example, the following is permitted:
1315 .. code-block:: ada
1317      type R is array (1 .. 10) of Boolean;
1318      for R'Size use 80;
1320      type Q is record
1321         G, H : Boolean;
1322         L, M : R;
1323      end record;
1325      for Q use record
1326         G at 0 range  0 ..   0;
1327         H at 0 range  1 ..   1;
1328         L at 0 range  2 ..  81;
1329         R at 0 range 82 .. 161;
1330      end record;
1332 Note: the above rules apply to recent releases of GNAT 5.
1333 In GNAT 3, there are more severe restrictions on larger components.
1334 For non-primitive types, including packed arrays with a size greater than
1335 64 bits, component clauses must respect the alignment requirement of the
1336 type, in particular, always starting on a byte boundary, and the length
1337 must be a multiple of the storage unit.
1339 .. _Handling_of_Records_with_Holes:
1341 Handling of Records with Holes
1342 ==============================
1344 .. index:: Handling of Records with Holes
1346 As a result of alignment considerations, records may contain "holes"
1347 or gaps
1348 which do not correspond to the data bits of any of the components.
1349 Record representation clauses can also result in holes in records.
1351 GNAT does not attempt to clear these holes, so in record objects,
1352 they should be considered to hold undefined rubbish. The generated
1353 equality routine just tests components so does not access these
1354 undefined bits, and assignment and copy operations may or may not
1355 preserve the contents of these holes (for assignments, the holes
1356 in the target will in practice contain either the bits that are
1357 present in the holes in the source, or the bits that were present
1358 in the target before the assignment).
1360 If it is necessary to ensure that holes in records have all zero
1361 bits, then record objects for which this initialization is desired
1362 should be explicitly set to all zero values using Unchecked_Conversion
1363 or address overlays. For example
1365 .. code-block:: ada
1367   type HRec is record
1368      C : Character;
1369      I : Integer;
1370   end record;
1372 On typical machines, integers need to be aligned on a four-byte
1373 boundary, resulting in three bytes of undefined rubbish following
1374 the 8-bit field for C. To ensure that the hole in a variable of
1375 type HRec is set to all zero bits,
1376 you could for example do:
1378 .. code-block:: ada
1380   type Base is record
1381      Dummy1, Dummy2 : Integer := 0;
1382   end record;
1384   BaseVar : Base;
1385   RealVar : Hrec;
1386   for RealVar'Address use BaseVar'Address;
1389 Now the 8-bytes of the value of RealVar start out containing all zero
1390 bits. A safer approach is to just define dummy fields, avoiding the
1391 holes, as in:
1393 .. code-block:: ada
1395   type HRec is record
1396      C      : Character;
1397      Dummy1 : Short_Short_Integer := 0;
1398      Dummy2 : Short_Short_Integer := 0;
1399      Dummy3 : Short_Short_Integer := 0;
1400      I      : Integer;
1401   end record;
1403 And to make absolutely sure that the intent of this is followed, you
1404 can use representation clauses:
1406 .. code-block:: ada
1408   for Hrec use record
1409      C      at 0 range 0 .. 7;
1410      Dummy1 at 1 range 0 .. 7;
1411      Dummy2 at 2 range 0 .. 7;
1412      Dummy3 at 3 range 0 .. 7;
1413      I      at 4 range 0 .. 31;
1414   end record;
1415   for Hrec'Size use 64;
1418 .. _Enumeration_Clauses:
1420 Enumeration Clauses
1421 ===================
1423 The only restriction on enumeration clauses is that the range of values
1424 must be representable.  For the signed case, if one or more of the
1425 representation values are negative, all values must be in the range:
1427 .. code-block:: ada
1429      System.Min_Int .. System.Max_Int
1431 For the unsigned case, where all values are nonnegative, the values must
1432 be in the range:
1434 .. code-block:: ada
1436      0 .. System.Max_Binary_Modulus;
1439 A *confirming* representation clause is one in which the values range
1440 from 0 in sequence, i.e., a clause that confirms the default representation
1441 for an enumeration type.
1442 Such a confirming representation
1443 is permitted by these rules, and is specially recognized by the compiler so
1444 that no extra overhead results from the use of such a clause.
1446 If an array has an index type which is an enumeration type to which an
1447 enumeration clause has been applied, then the array is stored in a compact
1448 manner.  Consider the declarations:
1450 .. code-block:: ada
1452      type r is (A, B, C);
1453      for r use (A => 1, B => 5, C => 10);
1454      type t is array (r) of Character;
1456 The array type t corresponds to a vector with exactly three elements and
1457 has a default size equal to `3*Character'Size`.  This ensures efficient
1458 use of space, but means that accesses to elements of the array will incur
1459 the overhead of converting representation values to the corresponding
1460 positional values, (i.e., the value delivered by the `Pos` attribute).
1463 .. _Address_Clauses:
1465 Address Clauses
1466 ===============
1467 .. index:: Address Clause
1469 The reference manual allows a general restriction on representation clauses,
1470 as found in RM 13.1(22):
1472    "An implementation need not support representation
1473    items containing nonstatic expressions, except that
1474    an implementation should support a representation item
1475    for a given entity if each nonstatic expression in the
1476    representation item is a name that statically denotes
1477    a constant declared before the entity."
1479 In practice this is applicable only to address clauses, since this is the
1480 only case in which a non-static expression is permitted by the syntax.  As
1481 the AARM notes in sections 13.1 (22.a-22.h):
1483    22.a   Reason: This is to avoid the following sort of thing:
1485    22.b        X : Integer := F(...);
1486    Y : Address := G(...);
1487    for X'Address use Y;
1489    22.c   In the above, we have to evaluate the
1490    initialization expression for X before we
1491    know where to put the result.  This seems
1492    like an unreasonable implementation burden.
1494    22.d   The above code should instead be written
1495    like this:
1497    22.e        Y : constant Address := G(...);
1498    X : Integer := F(...);
1499    for X'Address use Y;
1501    22.f   This allows the expression 'Y' to be safely
1502    evaluated before X is created.
1504    22.g   The constant could be a formal parameter of mode in.
1506    22.h   An implementation can support other nonstatic
1507    expressions if it wants to.  Expressions of type
1508    Address are hardly ever static, but their value
1509    might be known at compile time anyway in many
1510    cases.
1512 GNAT does indeed permit many additional cases of non-static expressions.  In
1513 particular, if the type involved is elementary there are no restrictions
1514 (since in this case, holding a temporary copy of the initialization value,
1515 if one is present, is inexpensive).  In addition, if there is no implicit or
1516 explicit initialization, then there are no restrictions.  GNAT will reject
1517 only the case where all three of these conditions hold:
1520   The type of the item is non-elementary (e.g., a record or array).
1523   There is explicit or implicit initialization required for the object.
1524   Note that access values are always implicitly initialized.
1527   The address value is non-static.  Here GNAT is more permissive than the
1528   RM, and allows the address value to be the address of a previously declared
1529   stand-alone variable, as long as it does not itself have an address clause.
1531   ::
1533                Anchor  : Some_Initialized_Type;
1534                Overlay : Some_Initialized_Type;
1535                for Overlay'Address use Anchor'Address;
1537   However, the prefix of the address clause cannot be an array component, or
1538   a component of a discriminated record.
1540 As noted above in section 22.h, address values are typically non-static.  In
1541 particular the To_Address function, even if applied to a literal value, is
1542 a non-static function call.  To avoid this minor annoyance, GNAT provides
1543 the implementation defined attribute 'To_Address.  The following two
1544 expressions have identical values:
1546 .. index:: Attribute
1547 .. index:: To_Address
1549 .. code-block:: ada
1551      To_Address (16#1234_0000#)
1552      System'To_Address (16#1234_0000#);
1554 except that the second form is considered to be a static expression, and
1555 thus when used as an address clause value is always permitted.
1557 Additionally, GNAT treats as static an address clause that is an
1558 unchecked_conversion of a static integer value.  This simplifies the porting
1559 of legacy code, and provides a portable equivalent to the GNAT attribute
1560 `To_Address`.
1562 Another issue with address clauses is the interaction with alignment
1563 requirements.  When an address clause is given for an object, the address
1564 value must be consistent with the alignment of the object (which is usually
1565 the same as the alignment of the type of the object).  If an address clause
1566 is given that specifies an inappropriately aligned address value, then the
1567 program execution is erroneous.
1569 Since this source of erroneous behavior can have unfortunate effects on
1570 machines with strict alignment requirements, GNAT
1571 checks (at compile time if possible, generating a warning, or at execution
1572 time with a run-time check) that the alignment is appropriate.  If the
1573 run-time check fails, then `Program_Error` is raised.  This run-time
1574 check is suppressed if range checks are suppressed, or if the special GNAT
1575 check Alignment_Check is suppressed, or if
1576 `pragma Restrictions (No_Elaboration_Code)` is in effect. It is also
1577 suppressed by default on non-strict alignment machines (such as the x86).
1579 Finally, GNAT does not permit overlaying of objects of controlled types or
1580 composite types containing a controlled component. In most cases, the compiler
1581 can detect an attempt at such overlays and will generate a warning at compile
1582 time and a Program_Error exception at run time.
1584 .. index:: Export
1586 An address clause cannot be given for an exported object.  More
1587 understandably the real restriction is that objects with an address
1588 clause cannot be exported.  This is because such variables are not
1589 defined by the Ada program, so there is no external object to export.
1591 .. index:: Import
1593 It is permissible to give an address clause and a pragma Import for the
1594 same object.  In this case, the variable is not really defined by the
1595 Ada program, so there is no external symbol to be linked.  The link name
1596 and the external name are ignored in this case.  The reason that we allow this
1597 combination is that it provides a useful idiom to avoid unwanted
1598 initializations on objects with address clauses.
1600 When an address clause is given for an object that has implicit or
1601 explicit initialization, then by default initialization takes place.  This
1602 means that the effect of the object declaration is to overwrite the
1603 memory at the specified address.  This is almost always not what the
1604 programmer wants, so GNAT will output a warning:
1608     with System;
1609     package G is
1610        type R is record
1611           M : Integer := 0;
1612        end record;
1614        Ext : R;
1615        for Ext'Address use System'To_Address (16#1234_1234#);
1616            |
1617     >>> warning: implicit initialization of "Ext" may
1618         modify overlaid storage
1619     >>> warning: use pragma Import for "Ext" to suppress
1620         initialization (RM B(24))
1622     end G;
1624 As indicated by the warning message, the solution is to use a (dummy) pragma
1625 Import to suppress this initialization.  The pragma tell the compiler that the
1626 object is declared and initialized elsewhere.  The following package compiles
1627 without warnings (and the initialization is suppressed):
1629 .. code-block:: ada
1631      with System;
1632      package G is
1633         type R is record
1634            M : Integer := 0;
1635         end record;
1637         Ext : R;
1638         for Ext'Address use System'To_Address (16#1234_1234#);
1639         pragma Import (Ada, Ext);
1640      end G;
1643 A final issue with address clauses involves their use for overlaying
1644 variables, as in the following example:
1646 .. index:: Overlaying of objects
1648 .. code-block:: ada
1650     A : Integer;
1651     B : Integer;
1652     for B'Address use A'Address;
1655 or alternatively, using the form recommended by the RM:
1657 .. code-block:: ada
1659     A    : Integer;
1660     Addr : constant Address := A'Address;
1661     B    : Integer;
1662     for B'Address use Addr;
1665 In both of these cases, `A`
1666 and `B` become aliased to one another via the
1667 address clause. This use of address clauses to overlay
1668 variables, achieving an effect similar to unchecked
1669 conversion was erroneous in Ada 83, but in Ada 95 and Ada 2005
1670 the effect is implementation defined. Furthermore, the
1671 Ada RM specifically recommends that in a situation
1672 like this, `B` should be subject to the following
1673 implementation advice (RM 13.3(19)):
1675    "19  If the Address of an object is specified, or it is imported
1676    or exported, then the implementation should not perform
1677    optimizations based on assumptions of no aliases."
1679 GNAT follows this recommendation, and goes further by also applying
1680 this recommendation to the overlaid variable (`A`
1681 in the above example) in this case. This means that the overlay
1682 works "as expected", in that a modification to one of the variables
1683 will affect the value of the other.
1685 Note that when address clause overlays are used in this way, there is an
1686 issue of unintentional initialization, as shown by this example:
1690   package Overwrite_Record is
1691      type R is record
1692         A : Character := 'C';
1693         B : Character := 'A';
1694      end record;
1695      X : Short_Integer := 3;
1696      Y : R;
1697      for Y'Address use X'Address;
1698          |
1699   >>> warning: default initialization of "Y" may
1700       modify "X", use pragma Import for "Y" to
1701       suppress initialization (RM B.1(24))
1703   end Overwrite_Record;
1705 Here the default initialization of `Y` will clobber the value
1706 of `X`, which justifies the warning. The warning notes that
1707 this effect can be eliminated by adding a `pragma Import`
1708 which suppresses the initialization:
1710 .. code-block:: ada
1712   package Overwrite_Record is
1713      type R is record
1714         A : Character := 'C';
1715         B : Character := 'A';
1716      end record;
1717      X : Short_Integer := 3;
1718      Y : R;
1719      for Y'Address use X'Address;
1720      pragma Import (Ada, Y);
1721   end Overwrite_Record;
1724 Note that the use of `pragma Initialize_Scalars` may cause variables to
1725 be initialized when they would not otherwise have been in the absence
1726 of the use of this pragma. This may cause an overlay to have this
1727 unintended clobbering effect. The compiler avoids this for scalar
1728 types, but not for composite objects (where in general the effect
1729 of `Initialize_Scalars` is part of the initialization routine
1730 for the composite object:
1734   pragma Initialize_Scalars;
1735   with Ada.Text_IO;  use Ada.Text_IO;
1736   procedure Overwrite_Array is
1737      type Arr is array (1 .. 5) of Integer;
1738      X : Arr := (others => 1);
1739      A : Arr;
1740      for A'Address use X'Address;
1741          |
1742   >>> warning: default initialization of "A" may
1743       modify "X", use pragma Import for "A" to
1744       suppress initialization (RM B.1(24))
1746   begin
1747      if X /= Arr'(others => 1) then
1748         Put_Line ("X was clobbered");
1749      else
1750         Put_Line ("X was not clobbered");
1751      end if;
1752   end Overwrite_Array;
1754 The above program generates the warning as shown, and at execution
1755 time, prints `X was clobbered`. If the `pragma Import` is
1756 added as suggested:
1758 .. code-block:: ada
1760   pragma Initialize_Scalars;
1761   with Ada.Text_IO;  use Ada.Text_IO;
1762   procedure Overwrite_Array is
1763      type Arr is array (1 .. 5) of Integer;
1764      X : Arr := (others => 1);
1765      A : Arr;
1766      for A'Address use X'Address;
1767      pragma Import (Ada, A);
1768   begin
1769      if X /= Arr'(others => 1) then
1770         Put_Line ("X was clobbered");
1771      else
1772         Put_Line ("X was not clobbered");
1773      end if;
1774   end Overwrite_Array;
1776 then the program compiles without the warning and when run will generate
1777 the output `X was not clobbered`.
1780 .. _Use_of_Address_Clauses_for_Memory-Mapped_I/O:
1782 Use of Address Clauses for Memory-Mapped I/O
1783 ============================================
1785 .. index:: Memory-mapped I/O
1787 A common pattern is to use an address clause to map an atomic variable to
1788 a location in memory that corresponds to a memory-mapped I/O operation or
1789 operations, for example:
1791 .. code-block:: ada
1793       type Mem_Word is record
1794          A,B,C,D : Byte;
1795       end record;
1796       pragma Atomic (Mem_Word);
1797       for Mem_Word_Size use 32;
1799       Mem : Mem_Word;
1800       for Mem'Address use some-address;
1801       ...
1802       Temp := Mem;
1803       Temp.A := 32;
1804       Mem := Temp;
1806 For a full access (reference or modification) of the variable (Mem) in
1807 this case, as in the above examples, GNAT guarantees that the entire atomic
1808 word will be accessed. It is not clear whether the RM requires this. For
1809 example in the above, can the compiler reference only the Mem.A field as
1810 an optimization? Whatever the answer to this question is, GNAT makes the
1811 guarantee that for such a reference, the entire word is read or written.
1813 A problem arises with a component access such as:
1815 .. code-block:: ada
1817       Mem.A := 32;
1819 Note that the component A is not declared as atomic. This means that it is
1820 not clear what this assignment means. It could correspond to full word read
1821 and write as given in the first example, or on architectures that supported
1822 such an operation it might be a single byte store instruction. The RM does
1823 not have anything to say in this situation, and GNAT does not make any
1824 guarantee. The code generated may vary from target to target. GNAT will issue
1825 a warning in such a case:
1829       Mem.A := 32;
1830       |
1831       >>> warning: access to non-atomic component of atomic array,
1832           may cause unexpected accesses to atomic object
1834 It is best to be explicit in this situation, by either declaring the
1835 components to be atomic if you want the byte store, or explicitly writing
1836 the full word access sequence if that is what the hardware requires.
1839 .. _Effect_of_Convention_on_Representation:
1841 Effect of Convention on Representation
1842 ======================================
1844 .. index:: Convention, effect on representation
1846 Normally the specification of a foreign language convention for a type or
1847 an object has no effect on the chosen representation.  In particular, the
1848 representation chosen for data in GNAT generally meets the standard system
1849 conventions, and for example records are laid out in a manner that is
1850 consistent with C.  This means that specifying convention C (for example)
1851 has no effect.
1853 There are four exceptions to this general rule:
1855 * *Convention Fortran and array subtypes*.
1857   If pragma Convention Fortran is specified for an array subtype, then in
1858   accordance with the implementation advice in section 3.6.2(11) of the
1859   Ada Reference Manual, the array will be stored in a Fortran-compatible
1860   column-major manner, instead of the normal default row-major order.
1862 * *Convention C and enumeration types*
1864   GNAT normally stores enumeration types in 8, 16, or 32 bits as required
1865   to accommodate all values of the type.  For example, for the enumeration
1866   type declared by:
1868   ::
1870        type Color is (Red, Green, Blue);
1872   8 bits is sufficient to store all values of the type, so by default, objects
1873   of type `Color` will be represented using 8 bits.  However, normal C
1874   convention is to use 32 bits for all enum values in C, since enum values
1875   are essentially of type int.  If pragma `Convention C` is specified for an
1876   Ada enumeration type, then the size is modified as necessary (usually to
1877   32 bits) to be consistent with the C convention for enum values.
1879   Note that this treatment applies only to types. If Convention C is given for
1880   an enumeration object, where the enumeration type is not Convention C, then
1881   Object_Size bits are allocated. For example, for a normal enumeration type,
1882   with less than 256 elements, only 8 bits will be allocated for the object.
1883   Since this may be a surprise in terms of what C expects, GNAT will issue a
1884   warning in this situation. The warning can be suppressed by giving an explicit
1885   size clause specifying the desired size.
1887 * *Convention C/Fortran and Boolean types*
1889   In C, the usual convention for boolean values, that is values used for
1890   conditions, is that zero represents false, and nonzero values represent
1891   true.  In Ada, the normal convention is that two specific values, typically
1892   0/1, are used to represent false/true respectively.
1894   Fortran has a similar convention for `LOGICAL` values (any nonzero
1895   value represents true).
1897   To accommodate the Fortran and C conventions, if a pragma Convention specifies
1898   C or Fortran convention for a derived Boolean, as in the following example:
1900   ::
1902        type C_Switch is new Boolean;
1903        pragma Convention (C, C_Switch);
1906   then the GNAT generated code will treat any nonzero value as true.  For truth
1907   values generated by GNAT, the conventional value 1 will be used for True, but
1908   when one of these values is read, any nonzero value is treated as True.
1911 .. _Conventions_and_Anonymous_Access_Types:
1913 Conventions and Anonymous Access Types
1914 ======================================
1916 .. index:: Anonymous access types
1918 .. index:: Convention for anonymous access types
1920 The RM is not entirely clear on convention handling in a number of cases,
1921 and in particular, it is not clear on the convention to be given to
1922 anonymous access types in general, and in particular what is to be
1923 done for the case of anonymous access-to-subprogram.
1925 In GNAT, we decide that if an explicit Convention is applied
1926 to an object or component, and its type is such an anonymous type,
1927 then the convention will apply to this anonymous type as well. This
1928 seems to make sense since it is anomolous in any case to have a
1929 different convention for an object and its type, and there is clearly
1930 no way to explicitly specify a convention for an anonymous type, since
1931 it doesn't have a name to specify!
1933 Furthermore, we decide that if a convention is applied to a record type,
1934 then this convention is inherited by any of its components that are of an
1935 anonymous access type which do not have an explicitly specified convention.
1937 The following program shows these conventions in action:
1941   package ConvComp is
1942      type Foo is range 1 .. 10;
1943      type T1 is record
1944         A : access function (X : Foo) return Integer;
1945         B : Integer;
1946      end record;
1947      pragma Convention (C, T1);
1949      type T2 is record
1950         A : access function (X : Foo) return Integer;
1951         pragma Convention  (C, A);
1952         B : Integer;
1953      end record;
1954      pragma Convention (COBOL, T2);
1956      type T3 is record
1957         A : access function (X : Foo) return Integer;
1958         pragma Convention  (COBOL, A);
1959         B : Integer;
1960      end record;
1961      pragma Convention (C, T3);
1963      type T4 is record
1964         A : access function (X : Foo) return Integer;
1965         B : Integer;
1966      end record;
1967      pragma Convention (COBOL, T4);
1969      function F (X : Foo) return Integer;
1970      pragma Convention (C, F);
1972      function F (X : Foo) return Integer is (13);
1974      TV1 : T1 := (F'Access, 12);  -- OK
1975      TV2 : T2 := (F'Access, 13);  -- OK
1977      TV3 : T3 := (F'Access, 13);  -- ERROR
1978                   |
1979   >>> subprogram "F" has wrong convention
1980   >>> does not match access to subprogram declared at line 17
1981        38.    TV4 : T4 := (F'Access, 13);  -- ERROR
1982                   |
1983   >>> subprogram "F" has wrong convention
1984   >>> does not match access to subprogram declared at line 24
1985        39. end ConvComp;
1988 .. _Determining_the_Representations_chosen_by_GNAT:
1990 Determining the Representations chosen by GNAT
1991 ==============================================
1993 .. index:: Representation, determination of
1995 .. index:: -gnatR (gcc)
1997 Although the descriptions in this section are intended to be complete, it is
1998 often easier to simply experiment to see what GNAT accepts and what the
1999 effect is on the layout of types and objects.
2001 As required by the Ada RM, if a representation clause is not accepted, then
2002 it must be rejected as illegal by the compiler.  However, when a
2003 representation clause or pragma is accepted, there can still be questions
2004 of what the compiler actually does.  For example, if a partial record
2005 representation clause specifies the location of some components and not
2006 others, then where are the non-specified components placed? Or if pragma
2007 `Pack` is used on a record, then exactly where are the resulting
2008 fields placed? The section on pragma `Pack` in this chapter can be
2009 used to answer the second question, but it is often easier to just see
2010 what the compiler does.
2012 For this purpose, GNAT provides the option *-gnatR*.  If you compile
2013 with this option, then the compiler will output information on the actual
2014 representations chosen, in a format similar to source representation
2015 clauses.  For example, if we compile the package:
2017 .. code-block:: ada
2019   package q is
2020      type r (x : boolean) is tagged record
2021         case x is
2022            when True => S : String (1 .. 100);
2023            when False => null;
2024         end case;
2025      end record;
2027      type r2 is new r (false) with record
2028         y2 : integer;
2029      end record;
2031      for r2 use record
2032         y2 at 16 range 0 .. 31;
2033      end record;
2035      type x is record
2036         y : character;
2037      end record;
2039      type x1 is array (1 .. 10) of x;
2040      for x1'component_size use 11;
2042      type ia is access integer;
2044      type Rb1 is array (1 .. 13) of Boolean;
2045      pragma Pack (rb1);
2047      type Rb2 is array (1 .. 65) of Boolean;
2048      pragma Pack (rb2);
2050      type x2 is record
2051         l1 : Boolean;
2052         l2 : Duration;
2053         l3 : Float;
2054         l4 : Boolean;
2055         l5 : Rb1;
2056         l6 : Rb2;
2057      end record;
2058      pragma Pack (x2);
2059   end q;
2061 using the switch *-gnatR* we obtain the following output:
2063 .. code-block:: ada
2065   Representation information for unit q
2066   -------------------------------------
2068   for r'Size use ??;
2069   for r'Alignment use 4;
2070   for r use record
2071      x    at 4 range  0 .. 7;
2072      _tag at 0 range  0 .. 31;
2073      s    at 5 range  0 .. 799;
2074   end record;
2076   for r2'Size use 160;
2077   for r2'Alignment use 4;
2078   for r2 use record
2079      x       at  4 range  0 .. 7;
2080      _tag    at  0 range  0 .. 31;
2081      _parent at  0 range  0 .. 63;
2082      y2      at 16 range  0 .. 31;
2083   end record;
2085   for x'Size use 8;
2086   for x'Alignment use 1;
2087   for x use record
2088      y at 0 range  0 .. 7;
2089   end record;
2091   for x1'Size use 112;
2092   for x1'Alignment use 1;
2093   for x1'Component_Size use 11;
2095   for rb1'Size use 13;
2096   for rb1'Alignment use 2;
2097   for rb1'Component_Size use 1;
2099   for rb2'Size use 72;
2100   for rb2'Alignment use 1;
2101   for rb2'Component_Size use 1;
2103   for x2'Size use 224;
2104   for x2'Alignment use 4;
2105   for x2 use record
2106      l1 at  0 range  0 .. 0;
2107      l2 at  0 range  1 .. 64;
2108      l3 at 12 range  0 .. 31;
2109      l4 at 16 range  0 .. 0;
2110      l5 at 16 range  1 .. 13;
2111      l6 at 18 range  0 .. 71;
2112   end record;
2114 The Size values are actually the Object_Size, i.e., the default size that
2115 will be allocated for objects of the type.
2116 The ``??`` size for type r indicates that we have a variant record, and the
2117 actual size of objects will depend on the discriminant value.
2119 The Alignment values show the actual alignment chosen by the compiler
2120 for each record or array type.
2122 The record representation clause for type r shows where all fields
2123 are placed, including the compiler generated tag field (whose location
2124 cannot be controlled by the programmer).
2126 The record representation clause for the type extension r2 shows all the
2127 fields present, including the parent field, which is a copy of the fields
2128 of the parent type of r2, i.e., r1.
2130 The component size and size clauses for types rb1 and rb2 show
2131 the exact effect of pragma `Pack` on these arrays, and the record
2132 representation clause for type x2 shows how pragma `Pack` affects
2133 this record type.
2135 In some cases, it may be useful to cut and paste the representation clauses
2136 generated by the compiler into the original source to fix and guarantee
2137 the actual representation to be used.