1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             E X P _ P A K D                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2014, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26with Atree;    use Atree;
27with Checks;   use Checks;
28with Einfo;    use Einfo;
29with Errout;   use Errout;
30with Exp_Dbug; use Exp_Dbug;
31with Exp_Util; use Exp_Util;
32with Layout;   use Layout;
33with Lib.Xref; use Lib.Xref;
34with Namet;    use Namet;
35with Nlists;   use Nlists;
36with Nmake;    use Nmake;
37with Opt;      use Opt;
38with Sem;      use Sem;
39with Sem_Aux;  use Sem_Aux;
40with Sem_Ch3;  use Sem_Ch3;
41with Sem_Ch8;  use Sem_Ch8;
42with Sem_Ch13; use Sem_Ch13;
43with Sem_Eval; use Sem_Eval;
44with Sem_Res;  use Sem_Res;
45with Sem_Util; use Sem_Util;
46with Sinfo;    use Sinfo;
47with Snames;   use Snames;
48with Stand;    use Stand;
49with Targparm; use Targparm;
50with Tbuild;   use Tbuild;
51with Ttypes;   use Ttypes;
52with Uintp;    use Uintp;
53
54package body Exp_Pakd is
55
56   ---------------------------
57   -- Endian Considerations --
58   ---------------------------
59
60   --  As described in the specification, bit numbering in a packed array
61   --  is consistent with bit numbering in a record representation clause,
62   --  and hence dependent on the endianness of the machine:
63
64   --    For little-endian machines, element zero is at the right hand end
65   --    (low order end) of a bit field.
66
67   --    For big-endian machines, element zero is at the left hand end
68   --    (high order end) of a bit field.
69
70   --  The shifts that are used to right justify a field therefore differ in
71   --  the two cases. For the little-endian case, we can simply use the bit
72   --  number (i.e. the element number * element size) as the count for a right
73   --  shift. For the big-endian case, we have to subtract the shift count from
74   --  an appropriate constant to use in the right shift. We use rotates
75   --  instead of shifts (which is necessary in the store case to preserve
76   --  other fields), and we expect that the backend will be able to change the
77   --  right rotate into a left rotate, avoiding the subtract, if the machine
78   --  architecture provides such an instruction.
79
80   -----------------------
81   -- Local Subprograms --
82   -----------------------
83
84   procedure Compute_Linear_Subscript
85     (Atyp   : Entity_Id;
86      N      : Node_Id;
87      Subscr : out Node_Id);
88   --  Given a constrained array type Atyp, and an indexed component node N
89   --  referencing an array object of this type, build an expression of type
90   --  Standard.Integer representing the zero-based linear subscript value.
91   --  This expression includes any required range checks.
92
93   procedure Convert_To_PAT_Type (Aexp : Node_Id);
94   --  Given an expression of a packed array type, builds a corresponding
95   --  expression whose type is the implementation type used to represent
96   --  the packed array. Aexp is analyzed and resolved on entry and on exit.
97
98   procedure Get_Base_And_Bit_Offset
99     (N      : Node_Id;
100      Base   : out Node_Id;
101      Offset : out Node_Id);
102   --  Given a node N for a name which involves a packed array reference,
103   --  return the base object of the reference and build an expression of
104   --  type Standard.Integer representing the zero-based offset in bits
105   --  from Base'Address to the first bit of the reference.
106
107   function Known_Aligned_Enough (Obj : Node_Id; Csiz : Nat) return Boolean;
108   --  There are two versions of the Set routines, the ones used when the
109   --  object is known to be sufficiently well aligned given the number of
110   --  bits, and the ones used when the object is not known to be aligned.
111   --  This routine is used to determine which set to use. Obj is a reference
112   --  to the object, and Csiz is the component size of the packed array.
113   --  True is returned if the alignment of object is known to be sufficient,
114   --  defined as 1 for odd bit sizes, 4 for bit sizes divisible by 4, and
115   --  2 otherwise.
116
117   function Make_Shift_Left (N : Node_Id; S : Node_Id) return Node_Id;
118   --  Build a left shift node, checking for the case of a shift count of zero
119
120   function Make_Shift_Right (N : Node_Id; S : Node_Id) return Node_Id;
121   --  Build a right shift node, checking for the case of a shift count of zero
122
123   function RJ_Unchecked_Convert_To
124     (Typ  : Entity_Id;
125      Expr : Node_Id) return Node_Id;
126   --  The packed array code does unchecked conversions which in some cases
127   --  may involve non-discrete types with differing sizes. The semantics of
128   --  such conversions is potentially endianness dependent, and the effect
129   --  we want here for such a conversion is to do the conversion in size as
130   --  though numeric items are involved, and we extend or truncate on the
131   --  left side. This happens naturally in the little-endian case, but in
132   --  the big endian case we can get left justification, when what we want
133   --  is right justification. This routine does the unchecked conversion in
134   --  a stepwise manner to ensure that it gives the expected result. Hence
135   --  the name (RJ = Right justified). The parameters Typ and Expr are as
136   --  for the case of a normal Unchecked_Convert_To call.
137
138   procedure Setup_Enumeration_Packed_Array_Reference (N : Node_Id);
139   --  This routine is called in the Get and Set case for arrays that are
140   --  packed but not bit-packed, meaning that they have at least one
141   --  subscript that is of an enumeration type with a non-standard
142   --  representation. This routine modifies the given node to properly
143   --  reference the corresponding packed array type.
144
145   procedure Setup_Inline_Packed_Array_Reference
146     (N      : Node_Id;
147      Atyp   : Entity_Id;
148      Obj    : in out Node_Id;
149      Cmask  : out Uint;
150      Shift  : out Node_Id);
151   --  This procedure performs common processing on the N_Indexed_Component
152   --  parameter given as N, whose prefix is a reference to a packed array.
153   --  This is used for the get and set when the component size is 1, 2, 4,
154   --  or for other component sizes when the packed array type is a modular
155   --  type (i.e. the cases that are handled with inline code).
156   --
157   --  On entry:
158   --
159   --    N is the N_Indexed_Component node for the packed array reference
160   --
161   --    Atyp is the constrained array type (the actual subtype has been
162   --    computed if necessary to obtain the constraints, but this is still
163   --    the original array type, not the Packed_Array_Impl_Type value).
164   --
165   --    Obj is the object which is to be indexed. It is always of type Atyp.
166   --
167   --  On return:
168   --
169   --    Obj is the object containing the desired bit field. It is of type
170   --    Unsigned, Long_Unsigned, or Long_Long_Unsigned, and is either the
171   --    entire value, for the small static case, or the proper selected byte
172   --    from the array in the large or dynamic case. This node is analyzed
173   --    and resolved on return.
174   --
175   --    Shift is a node representing the shift count to be used in the
176   --    rotate right instruction that positions the field for access.
177   --    This node is analyzed and resolved on return.
178   --
179   --    Cmask is a mask corresponding to the width of the component field.
180   --    Its value is 2 ** Csize - 1 (e.g. 2#1111# for component size of 4).
181   --
182   --  Note: in some cases the call to this routine may generate actions
183   --  (for handling multi-use references and the generation of the packed
184   --  array type on the fly). Such actions are inserted into the tree
185   --  directly using Insert_Action.
186
187   function Revert_Storage_Order (N : Node_Id) return Node_Id;
188   --  Perform appropriate justification and byte ordering adjustments for N,
189   --  an element of a packed array type, when both the component type and
190   --  the enclosing packed array type have reverse scalar storage order.
191   --  On little-endian targets, the value is left justified before byte
192   --  swapping. The Etype of the returned expression is an integer type of
193   --  an appropriate power-of-2 size.
194
195   --------------------------
196   -- Revert_Storage_Order --
197   --------------------------
198
199   function Revert_Storage_Order (N : Node_Id) return Node_Id is
200      Loc     : constant Source_Ptr := Sloc (N);
201      T       : constant Entity_Id := Etype (N);
202      T_Size  : constant Uint := RM_Size (T);
203
204      Swap_RE : RE_Id;
205      Swap_F  : Entity_Id;
206      Swap_T  : Entity_Id;
207      --  Swapping function
208
209      Arg      : Node_Id;
210      Adjusted : Node_Id;
211      Shift    : Uint;
212
213   begin
214      if T_Size <= 8 then
215
216         --  Array component size is less than a byte: no swapping needed
217
218         Swap_F := Empty;
219         Swap_T := RTE (RE_Unsigned_8);
220
221      else
222         --  Select byte swapping function depending on array component size
223
224         if T_Size <= 16 then
225            Swap_RE := RE_Bswap_16;
226
227         elsif T_Size <= 32 then
228            Swap_RE := RE_Bswap_32;
229
230         else pragma Assert (T_Size <= 64);
231            Swap_RE := RE_Bswap_64;
232         end if;
233
234         Swap_F := RTE (Swap_RE);
235         Swap_T := Etype (Swap_F);
236
237      end if;
238
239      Shift := Esize (Swap_T) - T_Size;
240
241      Arg := RJ_Unchecked_Convert_To (Swap_T, N);
242
243      if not Bytes_Big_Endian and then Shift > Uint_0 then
244         Arg :=
245           Make_Op_Shift_Left (Loc,
246             Left_Opnd  => Arg,
247             Right_Opnd => Make_Integer_Literal (Loc, Shift));
248      end if;
249
250      if Present (Swap_F) then
251         Adjusted :=
252           Make_Function_Call (Loc,
253             Name                   => New_Occurrence_Of (Swap_F, Loc),
254             Parameter_Associations => New_List (Arg));
255      else
256         Adjusted := Arg;
257      end if;
258
259      Set_Etype (Adjusted, Swap_T);
260      return Adjusted;
261   end Revert_Storage_Order;
262
263   ------------------------------
264   -- Compute_Linear_Subscript --
265   ------------------------------
266
267   procedure Compute_Linear_Subscript
268     (Atyp   : Entity_Id;
269      N      : Node_Id;
270      Subscr : out Node_Id)
271   is
272      Loc    : constant Source_Ptr := Sloc (N);
273      Oldsub : Node_Id;
274      Newsub : Node_Id;
275      Indx   : Node_Id;
276      Styp   : Entity_Id;
277
278   begin
279      Subscr := Empty;
280
281      --  Loop through dimensions
282
283      Indx   := First_Index (Atyp);
284      Oldsub := First (Expressions (N));
285
286      while Present (Indx) loop
287         Styp := Etype (Indx);
288         Newsub := Relocate_Node (Oldsub);
289
290         --  Get expression for the subscript value. First, if Do_Range_Check
291         --  is set on a subscript, then we must do a range check against the
292         --  original bounds (not the bounds of the packed array type). We do
293         --  this by introducing a subtype conversion.
294
295         if Do_Range_Check (Newsub)
296           and then Etype (Newsub) /= Styp
297         then
298            Newsub := Convert_To (Styp, Newsub);
299         end if;
300
301         --  Now evolve the expression for the subscript. First convert
302         --  the subscript to be zero based and of an integer type.
303
304         --  Case of integer type, where we just subtract to get lower bound
305
306         if Is_Integer_Type (Styp) then
307
308            --  If length of integer type is smaller than standard integer,
309            --  then we convert to integer first, then do the subtract
310
311            --  Integer (subscript) - Integer (Styp'First)
312
313            if Esize (Styp) < Esize (Standard_Integer) then
314               Newsub :=
315                 Make_Op_Subtract (Loc,
316                   Left_Opnd => Convert_To (Standard_Integer, Newsub),
317                 Right_Opnd =>
318                   Convert_To (Standard_Integer,
319                     Make_Attribute_Reference (Loc,
320                       Prefix         => New_Occurrence_Of (Styp, Loc),
321                       Attribute_Name => Name_First)));
322
323            --  For larger integer types, subtract first, then convert to
324            --  integer, this deals with strange long long integer bounds.
325
326            --    Integer (subscript - Styp'First)
327
328            else
329               Newsub :=
330                 Convert_To (Standard_Integer,
331                   Make_Op_Subtract (Loc,
332                     Left_Opnd => Newsub,
333                   Right_Opnd =>
334                     Make_Attribute_Reference (Loc,
335                       Prefix         => New_Occurrence_Of (Styp, Loc),
336                       Attribute_Name => Name_First)));
337            end if;
338
339         --  For the enumeration case, we have to use 'Pos to get the value
340         --  to work with before subtracting the lower bound.
341
342         --    Integer (Styp'Pos (subscr)) - Integer (Styp'Pos (Styp'First));
343
344         --  This is not quite right for bizarre cases where the size of the
345         --  enumeration type is > Integer'Size bits due to rep clause ???
346
347         else
348            pragma Assert (Is_Enumeration_Type (Styp));
349
350            Newsub :=
351              Make_Op_Subtract (Loc,
352                Left_Opnd => Convert_To (Standard_Integer,
353                  Make_Attribute_Reference (Loc,
354                    Prefix         => New_Occurrence_Of (Styp, Loc),
355                    Attribute_Name => Name_Pos,
356                    Expressions    => New_List (Newsub))),
357
358                Right_Opnd =>
359                  Convert_To (Standard_Integer,
360                    Make_Attribute_Reference (Loc,
361                      Prefix         => New_Occurrence_Of (Styp, Loc),
362                      Attribute_Name => Name_Pos,
363                      Expressions    => New_List (
364                        Make_Attribute_Reference (Loc,
365                          Prefix         => New_Occurrence_Of (Styp, Loc),
366                          Attribute_Name => Name_First)))));
367         end if;
368
369         Set_Paren_Count (Newsub, 1);
370
371         --  For the first subscript, we just copy that subscript value
372
373         if No (Subscr) then
374            Subscr := Newsub;
375
376         --  Otherwise, we must multiply what we already have by the current
377         --  stride and then add in the new value to the evolving subscript.
378
379         else
380            Subscr :=
381              Make_Op_Add (Loc,
382                Left_Opnd =>
383                  Make_Op_Multiply (Loc,
384                    Left_Opnd  => Subscr,
385                    Right_Opnd =>
386                      Make_Attribute_Reference (Loc,
387                        Attribute_Name => Name_Range_Length,
388                        Prefix         => New_Occurrence_Of (Styp, Loc))),
389                Right_Opnd => Newsub);
390         end if;
391
392         --  Move to next subscript
393
394         Next_Index (Indx);
395         Next (Oldsub);
396      end loop;
397   end Compute_Linear_Subscript;
398
399   -------------------------
400   -- Convert_To_PAT_Type --
401   -------------------------
402
403   --  The PAT is always obtained from the actual subtype
404
405   procedure Convert_To_PAT_Type (Aexp : Node_Id) is
406      Act_ST : Entity_Id;
407
408   begin
409      Convert_To_Actual_Subtype (Aexp);
410      Act_ST := Underlying_Type (Etype (Aexp));
411      Create_Packed_Array_Impl_Type (Act_ST);
412
413      --  Just replace the etype with the packed array type. This works because
414      --  the expression will not be further analyzed, and Gigi considers the
415      --  two types equivalent in any case.
416
417      --  This is not strictly the case ??? If the reference is an actual in
418      --  call, the expansion of the prefix is delayed, and must be reanalyzed,
419      --  see Reset_Packed_Prefix. On the other hand, if the prefix is a simple
420      --  array reference, reanalysis can produce spurious type errors when the
421      --  PAT type is replaced again with the original type of the array. Same
422      --  for the case of a dereference. Ditto for function calls: expansion
423      --  may introduce additional actuals which will trigger errors if call is
424      --  reanalyzed. The following is correct and minimal, but the handling of
425      --  more complex packed expressions in actuals is confused. Probably the
426      --  problem only remains for actuals in calls.
427
428      Set_Etype (Aexp, Packed_Array_Impl_Type (Act_ST));
429
430      if Is_Entity_Name (Aexp)
431        or else
432           (Nkind (Aexp) = N_Indexed_Component
433             and then Is_Entity_Name (Prefix (Aexp)))
434        or else Nkind_In (Aexp, N_Explicit_Dereference, N_Function_Call)
435      then
436         Set_Analyzed (Aexp);
437      end if;
438   end Convert_To_PAT_Type;
439
440   -----------------------------------
441   -- Create_Packed_Array_Impl_Type --
442   -----------------------------------
443
444   procedure Create_Packed_Array_Impl_Type (Typ : Entity_Id) is
445      Loc      : constant Source_Ptr := Sloc (Typ);
446      Ctyp     : constant Entity_Id  := Component_Type (Typ);
447      Csize    : constant Uint       := Component_Size (Typ);
448
449      Ancest   : Entity_Id;
450      PB_Type  : Entity_Id;
451      PASize   : Uint;
452      Decl     : Node_Id;
453      PAT      : Entity_Id;
454      Len_Dim  : Node_Id;
455      Len_Expr : Node_Id;
456      Len_Bits : Uint;
457      Bits_U1  : Node_Id;
458      PAT_High : Node_Id;
459      Btyp     : Entity_Id;
460      Lit      : Node_Id;
461
462      procedure Install_PAT;
463      --  This procedure is called with Decl set to the declaration for the
464      --  packed array type. It creates the type and installs it as required.
465
466      procedure Set_PB_Type;
467      --  Sets PB_Type to Packed_Bytes{1,2,4} as required by the alignment
468      --  requirements (see documentation in the spec of this package).
469
470      -----------------
471      -- Install_PAT --
472      -----------------
473
474      procedure Install_PAT is
475         Pushed_Scope : Boolean := False;
476
477      begin
478         --  We do not want to put the declaration we have created in the tree
479         --  since it is often hard, and sometimes impossible to find a proper
480         --  place for it (the impossible case arises for a packed array type
481         --  with bounds depending on the discriminant, a declaration cannot
482         --  be put inside the record, and the reference to the discriminant
483         --  cannot be outside the record).
484
485         --  The solution is to analyze the declaration while temporarily
486         --  attached to the tree at an appropriate point, and then we install
487         --  the resulting type as an Itype in the packed array type field of
488         --  the original type, so that no explicit declaration is required.
489
490         --  Note: the packed type is created in the scope of its parent type.
491         --  There are at least some cases where the current scope is deeper,
492         --  and so when this is the case, we temporarily reset the scope
493         --  for the definition. This is clearly safe, since the first use
494         --  of the packed array type will be the implicit reference from
495         --  the corresponding unpacked type when it is elaborated.
496
497         if Is_Itype (Typ) then
498            Set_Parent (Decl, Associated_Node_For_Itype (Typ));
499         else
500            Set_Parent (Decl, Declaration_Node (Typ));
501         end if;
502
503         if Scope (Typ) /= Current_Scope then
504            Push_Scope (Scope (Typ));
505            Pushed_Scope := True;
506         end if;
507
508         Set_Is_Itype (PAT, True);
509         Set_Packed_Array_Impl_Type (Typ, PAT);
510         Analyze (Decl, Suppress => All_Checks);
511
512         if Pushed_Scope then
513            Pop_Scope;
514         end if;
515
516         --  Set Esize and RM_Size to the actual size of the packed object
517         --  Do not reset RM_Size if already set, as happens in the case of
518         --  a modular type.
519
520         if Unknown_Esize (PAT) then
521            Set_Esize (PAT, PASize);
522         end if;
523
524         if Unknown_RM_Size (PAT) then
525            Set_RM_Size (PAT, PASize);
526         end if;
527
528         Adjust_Esize_Alignment (PAT);
529
530         --  Set remaining fields of packed array type
531
532         Init_Alignment                (PAT);
533         Set_Parent                    (PAT, Empty);
534         Set_Associated_Node_For_Itype (PAT, Typ);
535         Set_Is_Packed_Array_Impl_Type      (PAT, True);
536         Set_Original_Array_Type       (PAT, Typ);
537
538         --  For a non-bit-packed array, propagate reverse storage order
539         --  flag from original base type to packed array base type.
540
541         if not Is_Bit_Packed_Array (Typ) then
542            Set_Reverse_Storage_Order
543              (Etype (PAT), Reverse_Storage_Order (Base_Type (Typ)));
544         end if;
545
546         --  We definitely do not want to delay freezing for packed array
547         --  types. This is of particular importance for the itypes that are
548         --  generated for record components depending on discriminants where
549         --  there is no place to put the freeze node.
550
551         Set_Has_Delayed_Freeze (PAT, False);
552         Set_Has_Delayed_Freeze (Etype (PAT), False);
553
554         --  If we did allocate a freeze node, then clear out the reference
555         --  since it is obsolete (should we delete the freeze node???)
556
557         Set_Freeze_Node (PAT, Empty);
558         Set_Freeze_Node (Etype (PAT), Empty);
559      end Install_PAT;
560
561      -----------------
562      -- Set_PB_Type --
563      -----------------
564
565      procedure Set_PB_Type is
566      begin
567         --  If the user has specified an explicit alignment for the
568         --  type or component, take it into account.
569
570         if Csize <= 2 or else Csize = 4 or else Csize mod 2 /= 0
571           or else Alignment (Typ) = 1
572           or else Component_Alignment (Typ) = Calign_Storage_Unit
573         then
574            PB_Type := RTE (RE_Packed_Bytes1);
575
576         elsif Csize mod 4 /= 0
577           or else Alignment (Typ) = 2
578         then
579            PB_Type := RTE (RE_Packed_Bytes2);
580
581         else
582            PB_Type := RTE (RE_Packed_Bytes4);
583         end if;
584      end Set_PB_Type;
585
586   --  Start of processing for Create_Packed_Array_Impl_Type
587
588   begin
589      --  If we already have a packed array type, nothing to do
590
591      if Present (Packed_Array_Impl_Type (Typ)) then
592         return;
593      end if;
594
595      --  If our immediate ancestor subtype is constrained, and it already
596      --  has a packed array type, then just share the same type, since the
597      --  bounds must be the same. If the ancestor is not an array type but
598      --  a private type, as can happen with multiple instantiations, create
599      --  a new packed type, to avoid privacy issues.
600
601      if Ekind (Typ) = E_Array_Subtype then
602         Ancest := Ancestor_Subtype (Typ);
603
604         if Present (Ancest)
605           and then Is_Array_Type (Ancest)
606           and then Is_Constrained (Ancest)
607           and then Present (Packed_Array_Impl_Type (Ancest))
608         then
609            Set_Packed_Array_Impl_Type (Typ, Packed_Array_Impl_Type (Ancest));
610            return;
611         end if;
612      end if;
613
614      --  We preset the result type size from the size of the original array
615      --  type, since this size clearly belongs to the packed array type. The
616      --  size of the conceptual unpacked type is always set to unknown.
617
618      PASize := RM_Size (Typ);
619
620      --  Case of an array where at least one index is of an enumeration
621      --  type with a non-standard representation, but the component size
622      --  is not appropriate for bit packing. This is the case where we
623      --  have Is_Packed set (we would never be in this unit otherwise),
624      --  but Is_Bit_Packed_Array is false.
625
626      --  Note that if the component size is appropriate for bit packing,
627      --  then the circuit for the computation of the subscript properly
628      --  deals with the non-standard enumeration type case by taking the
629      --  Pos anyway.
630
631      if not Is_Bit_Packed_Array (Typ) then
632
633         --  Here we build a declaration:
634
635         --    type tttP is array (index1, index2, ...) of component_type
636
637         --  where index1, index2, are the index types. These are the same
638         --  as the index types of the original array, except for the non-
639         --  standard representation enumeration type case, where we have
640         --  two subcases.
641
642         --  For the unconstrained array case, we use
643
644         --    Natural range <>
645
646         --  For the constrained case, we use
647
648         --    Natural range Enum_Type'Pos (Enum_Type'First) ..
649         --                  Enum_Type'Pos (Enum_Type'Last);
650
651         --  Note that tttP is created even if no index subtype is a non
652         --  standard enumeration, because we still need to remove padding
653         --  normally inserted for component alignment.
654
655         PAT :=
656           Make_Defining_Identifier (Loc,
657             Chars => New_External_Name (Chars (Typ), 'P'));
658
659         Set_Packed_Array_Impl_Type (Typ, PAT);
660
661         declare
662            Indexes   : constant List_Id := New_List;
663            Indx      : Node_Id;
664            Indx_Typ  : Entity_Id;
665            Enum_Case : Boolean;
666            Typedef   : Node_Id;
667
668         begin
669            Indx := First_Index (Typ);
670
671            while Present (Indx) loop
672               Indx_Typ := Etype (Indx);
673
674               Enum_Case := Is_Enumeration_Type (Indx_Typ)
675                              and then Has_Non_Standard_Rep (Indx_Typ);
676
677               --  Unconstrained case
678
679               if not Is_Constrained (Typ) then
680                  if Enum_Case then
681                     Indx_Typ := Standard_Natural;
682                  end if;
683
684                  Append_To (Indexes, New_Occurrence_Of (Indx_Typ, Loc));
685
686               --  Constrained case
687
688               else
689                  if not Enum_Case then
690                     Append_To (Indexes, New_Occurrence_Of (Indx_Typ, Loc));
691
692                  else
693                     Append_To (Indexes,
694                       Make_Subtype_Indication (Loc,
695                         Subtype_Mark =>
696                           New_Occurrence_Of (Standard_Natural, Loc),
697                         Constraint =>
698                           Make_Range_Constraint (Loc,
699                             Range_Expression =>
700                               Make_Range (Loc,
701                                 Low_Bound =>
702                                   Make_Attribute_Reference (Loc,
703                                     Prefix         =>
704                                       New_Occurrence_Of (Indx_Typ, Loc),
705                                     Attribute_Name => Name_Pos,
706                                     Expressions    => New_List (
707                                       Make_Attribute_Reference (Loc,
708                                         Prefix         =>
709                                           New_Occurrence_Of (Indx_Typ, Loc),
710                                         Attribute_Name => Name_First))),
711
712                                 High_Bound =>
713                                   Make_Attribute_Reference (Loc,
714                                     Prefix         =>
715                                       New_Occurrence_Of (Indx_Typ, Loc),
716                                     Attribute_Name => Name_Pos,
717                                     Expressions    => New_List (
718                                       Make_Attribute_Reference (Loc,
719                                         Prefix         =>
720                                           New_Occurrence_Of (Indx_Typ, Loc),
721                                         Attribute_Name => Name_Last)))))));
722
723                  end if;
724               end if;
725
726               Next_Index (Indx);
727            end loop;
728
729            if not Is_Constrained (Typ) then
730               Typedef :=
731                 Make_Unconstrained_Array_Definition (Loc,
732                   Subtype_Marks => Indexes,
733                   Component_Definition =>
734                     Make_Component_Definition (Loc,
735                       Aliased_Present    => False,
736                       Subtype_Indication =>
737                          New_Occurrence_Of (Ctyp, Loc)));
738
739            else
740               Typedef :=
741                  Make_Constrained_Array_Definition (Loc,
742                    Discrete_Subtype_Definitions => Indexes,
743                    Component_Definition =>
744                      Make_Component_Definition (Loc,
745                        Aliased_Present    => False,
746                        Subtype_Indication =>
747                          New_Occurrence_Of (Ctyp, Loc)));
748            end if;
749
750            Decl :=
751              Make_Full_Type_Declaration (Loc,
752                Defining_Identifier => PAT,
753                Type_Definition     => Typedef);
754         end;
755
756         --  Set type as packed array type and install it
757
758         Set_Is_Packed_Array_Impl_Type (PAT);
759         Install_PAT;
760         return;
761
762      --  Case of bit-packing required for unconstrained array. We create
763      --  a subtype that is equivalent to use Packed_Bytes{1,2,4} as needed.
764
765      elsif not Is_Constrained (Typ) then
766
767         --  When generating standard DWARF, the ___XP suffix will be stripped
768         --  by the back-end but generate it anyway to ease compiler debugging.
769         --  This will help to distinguish implementation types from original
770         --  packed arrays.
771
772         PAT :=
773           Make_Defining_Identifier (Loc,
774             Chars => Make_Packed_Array_Impl_Type_Name (Typ, Csize));
775
776         Set_Packed_Array_Impl_Type (Typ, PAT);
777         Set_PB_Type;
778
779         Decl :=
780           Make_Subtype_Declaration (Loc,
781             Defining_Identifier => PAT,
782               Subtype_Indication => New_Occurrence_Of (PB_Type, Loc));
783         Install_PAT;
784         return;
785
786      --  Remaining code is for the case of bit-packing for constrained array
787
788      --  The name of the packed array subtype is
789
790      --    ttt___XPsss
791
792      --  where sss is the component size in bits and ttt is the name of
793      --  the parent packed type.
794
795      else
796         PAT :=
797           Make_Defining_Identifier (Loc,
798             Chars => Make_Packed_Array_Impl_Type_Name (Typ, Csize));
799
800         Set_Packed_Array_Impl_Type (Typ, PAT);
801
802         --  Build an expression for the length of the array in bits.
803         --  This is the product of the length of each of the dimensions
804
805         declare
806            J : Nat := 1;
807
808         begin
809            Len_Expr := Empty; -- suppress junk warning
810
811            loop
812               Len_Dim :=
813                 Make_Attribute_Reference (Loc,
814                   Attribute_Name => Name_Length,
815                   Prefix         => New_Occurrence_Of (Typ, Loc),
816                   Expressions    => New_List (
817                     Make_Integer_Literal (Loc, J)));
818
819               if J = 1 then
820                  Len_Expr := Len_Dim;
821
822               else
823                  Len_Expr :=
824                    Make_Op_Multiply (Loc,
825                      Left_Opnd  => Len_Expr,
826                      Right_Opnd => Len_Dim);
827               end if;
828
829               J := J + 1;
830               exit when J > Number_Dimensions (Typ);
831            end loop;
832         end;
833
834         --  Temporarily attach the length expression to the tree and analyze
835         --  and resolve it, so that we can test its value. We assume that the
836         --  total length fits in type Integer. This expression may involve
837         --  discriminants, so we treat it as a default/per-object expression.
838
839         Set_Parent (Len_Expr, Typ);
840         Preanalyze_Spec_Expression (Len_Expr, Standard_Long_Long_Integer);
841
842         --  Use a modular type if possible. We can do this if we have
843         --  static bounds, and the length is small enough, and the length
844         --  is not zero. We exclude the zero length case because the size
845         --  of things is always at least one, and the zero length object
846         --  would have an anomalous size.
847
848         if Compile_Time_Known_Value (Len_Expr) then
849            Len_Bits := Expr_Value (Len_Expr) * Csize;
850
851            --  Check for size known to be too large
852
853            if Len_Bits >
854              Uint_2 ** (Standard_Integer_Size - 1) * System_Storage_Unit
855            then
856               if System_Storage_Unit = 8 then
857                  Error_Msg_N
858                    ("packed array size cannot exceed " &
859                     "Integer''Last bytes", Typ);
860               else
861                  Error_Msg_N
862                    ("packed array size cannot exceed " &
863                     "Integer''Last storage units", Typ);
864               end if;
865
866               --  Reset length to arbitrary not too high value to continue
867
868               Len_Expr := Make_Integer_Literal (Loc, 65535);
869               Analyze_And_Resolve (Len_Expr, Standard_Long_Long_Integer);
870            end if;
871
872            --  We normally consider small enough to mean no larger than the
873            --  value of System_Max_Binary_Modulus_Power, checking that in the
874            --  case of values longer than word size, we have long shifts.
875
876            if Len_Bits > 0
877              and then
878                (Len_Bits <= System_Word_Size
879                   or else (Len_Bits <= System_Max_Binary_Modulus_Power
880                              and then Support_Long_Shifts_On_Target))
881            then
882               --  We can use the modular type, it has the form:
883
884               --    subtype tttPn is btyp
885               --      range 0 .. 2 ** ((Typ'Length (1)
886               --                * ... * Typ'Length (n)) * Csize) - 1;
887
888               --  The bounds are statically known, and btyp is one of the
889               --  unsigned types, depending on the length.
890
891               if Len_Bits <= Standard_Short_Short_Integer_Size then
892                  Btyp := RTE (RE_Short_Short_Unsigned);
893
894               elsif Len_Bits <= Standard_Short_Integer_Size then
895                  Btyp := RTE (RE_Short_Unsigned);
896
897               elsif Len_Bits <= Standard_Integer_Size then
898                  Btyp := RTE (RE_Unsigned);
899
900               elsif Len_Bits <= Standard_Long_Integer_Size then
901                  Btyp := RTE (RE_Long_Unsigned);
902
903               else
904                  Btyp := RTE (RE_Long_Long_Unsigned);
905               end if;
906
907               Lit := Make_Integer_Literal (Loc, 2 ** Len_Bits - 1);
908               Set_Print_In_Hex (Lit);
909
910               Decl :=
911                 Make_Subtype_Declaration (Loc,
912                   Defining_Identifier => PAT,
913                     Subtype_Indication =>
914                       Make_Subtype_Indication (Loc,
915                         Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
916
917                         Constraint =>
918                           Make_Range_Constraint (Loc,
919                             Range_Expression =>
920                               Make_Range (Loc,
921                                 Low_Bound =>
922                                   Make_Integer_Literal (Loc, 0),
923                                 High_Bound => Lit))));
924
925               if PASize = Uint_0 then
926                  PASize := Len_Bits;
927               end if;
928
929               Install_PAT;
930
931               --  Propagate a given alignment to the modular type. This can
932               --  cause it to be under-aligned, but that's OK.
933
934               if Present (Alignment_Clause (Typ)) then
935                  Set_Alignment (PAT, Alignment (Typ));
936               end if;
937
938               return;
939            end if;
940         end if;
941
942         --  Could not use a modular type, for all other cases, we build
943         --  a packed array subtype:
944
945         --    subtype tttPn is
946         --      System.Packed_Bytes{1,2,4} (0 .. (Bits + 7) / 8 - 1);
947
948         --  Bits is the length of the array in bits
949
950         Set_PB_Type;
951
952         Bits_U1 :=
953           Make_Op_Add (Loc,
954             Left_Opnd =>
955               Make_Op_Multiply (Loc,
956                 Left_Opnd  =>
957                   Make_Integer_Literal (Loc, Csize),
958                 Right_Opnd => Len_Expr),
959
960             Right_Opnd =>
961               Make_Integer_Literal (Loc, 7));
962
963         Set_Paren_Count (Bits_U1, 1);
964
965         PAT_High :=
966           Make_Op_Subtract (Loc,
967             Left_Opnd =>
968               Make_Op_Divide (Loc,
969                 Left_Opnd => Bits_U1,
970                 Right_Opnd => Make_Integer_Literal (Loc, 8)),
971             Right_Opnd => Make_Integer_Literal (Loc, 1));
972
973         Decl :=
974           Make_Subtype_Declaration (Loc,
975             Defining_Identifier => PAT,
976               Subtype_Indication =>
977                 Make_Subtype_Indication (Loc,
978                   Subtype_Mark => New_Occurrence_Of (PB_Type, Loc),
979                   Constraint =>
980                     Make_Index_Or_Discriminant_Constraint (Loc,
981                       Constraints => New_List (
982                         Make_Range (Loc,
983                           Low_Bound =>
984                             Make_Integer_Literal (Loc, 0),
985                           High_Bound =>
986                             Convert_To (Standard_Integer, PAT_High))))));
987
988         Install_PAT;
989
990         --  Currently the code in this unit requires that packed arrays
991         --  represented by non-modular arrays of bytes be on a byte
992         --  boundary for bit sizes handled by System.Pack_nn units.
993         --  That's because these units assume the array being accessed
994         --  starts on a byte boundary.
995
996         if Get_Id (UI_To_Int (Csize)) /= RE_Null then
997            Set_Must_Be_On_Byte_Boundary (Typ);
998         end if;
999      end if;
1000   end Create_Packed_Array_Impl_Type;
1001
1002   -----------------------------------
1003   -- Expand_Bit_Packed_Element_Set --
1004   -----------------------------------
1005
1006   procedure Expand_Bit_Packed_Element_Set (N : Node_Id) is
1007      Loc : constant Source_Ptr := Sloc (N);
1008      Lhs : constant Node_Id    := Name (N);
1009
1010      Ass_OK : constant Boolean := Assignment_OK (Lhs);
1011      --  Used to preserve assignment OK status when assignment is rewritten
1012
1013      Rhs : Node_Id := Expression (N);
1014      --  Initially Rhs is the right hand side value, it will be replaced
1015      --  later by an appropriate unchecked conversion for the assignment.
1016
1017      Obj   : Node_Id;
1018      Atyp  : Entity_Id;
1019      PAT   : Entity_Id;
1020      Ctyp  : Entity_Id;
1021      Csiz  : Int;
1022      Cmask : Uint;
1023
1024      Shift : Node_Id;
1025      --  The expression for the shift value that is required
1026
1027      Shift_Used : Boolean := False;
1028      --  Set True if Shift has been used in the generated code at least once,
1029      --  so that it must be duplicated if used again.
1030
1031      New_Lhs : Node_Id;
1032      New_Rhs : Node_Id;
1033
1034      Rhs_Val_Known : Boolean;
1035      Rhs_Val       : Uint;
1036      --  If the value of the right hand side as an integer constant is
1037      --  known at compile time, Rhs_Val_Known is set True, and Rhs_Val
1038      --  contains the value. Otherwise Rhs_Val_Known is set False, and
1039      --  the Rhs_Val is undefined.
1040
1041      function Get_Shift return Node_Id;
1042      --  Function used to get the value of Shift, making sure that it
1043      --  gets duplicated if the function is called more than once.
1044
1045      ---------------
1046      -- Get_Shift --
1047      ---------------
1048
1049      function Get_Shift return Node_Id is
1050      begin
1051         --  If we used the shift value already, then duplicate it. We
1052         --  set a temporary parent in case actions have to be inserted.
1053
1054         if Shift_Used then
1055            Set_Parent (Shift, N);
1056            return Duplicate_Subexpr_No_Checks (Shift);
1057
1058         --  If first time, use Shift unchanged, and set flag for first use
1059
1060         else
1061            Shift_Used := True;
1062            return Shift;
1063         end if;
1064      end Get_Shift;
1065
1066   --  Start of processing for Expand_Bit_Packed_Element_Set
1067
1068   begin
1069      pragma Assert (Is_Bit_Packed_Array (Etype (Prefix (Lhs))));
1070
1071      Obj := Relocate_Node (Prefix (Lhs));
1072      Convert_To_Actual_Subtype (Obj);
1073      Atyp := Etype (Obj);
1074      PAT  := Packed_Array_Impl_Type (Atyp);
1075      Ctyp := Component_Type (Atyp);
1076      Csiz := UI_To_Int (Component_Size (Atyp));
1077
1078      --  We remove side effects, in case the rhs modifies the lhs, because we
1079      --  are about to transform the rhs into an expression that first READS
1080      --  the lhs, so we can do the necessary shifting and masking. Example:
1081      --  "X(2) := F(...);" where F modifies X(3). Otherwise, the side effect
1082      --  will be lost.
1083
1084      Remove_Side_Effects (Rhs);
1085
1086      --  We convert the right hand side to the proper subtype to ensure
1087      --  that an appropriate range check is made (since the normal range
1088      --  check from assignment will be lost in the transformations). This
1089      --  conversion is analyzed immediately so that subsequent processing
1090      --  can work with an analyzed Rhs (and e.g. look at its Etype)
1091
1092      --  If the right-hand side is a string literal, create a temporary for
1093      --  it, constant-folding is not ready to wrap the bit representation
1094      --  of a string literal.
1095
1096      if Nkind (Rhs) = N_String_Literal then
1097         declare
1098            Decl : Node_Id;
1099         begin
1100            Decl :=
1101              Make_Object_Declaration (Loc,
1102                Defining_Identifier => Make_Temporary (Loc, 'T', Rhs),
1103                Object_Definition   => New_Occurrence_Of (Ctyp, Loc),
1104                Expression          => New_Copy_Tree (Rhs));
1105
1106            Insert_Actions (N, New_List (Decl));
1107            Rhs := New_Occurrence_Of (Defining_Identifier (Decl), Loc);
1108         end;
1109      end if;
1110
1111      Rhs := Convert_To (Ctyp, Rhs);
1112      Set_Parent (Rhs, N);
1113
1114      --  If we are building the initialization procedure for a packed array,
1115      --  and Initialize_Scalars is enabled, each component assignment is an
1116      --  out-of-range value by design.  Compile this value without checks,
1117      --  because a call to the array init_proc must not raise an exception.
1118
1119      --  Condition is not consistent with description above, Within_Init_Proc
1120      --  is True also when we are building the IP for a record or protected
1121      --  type that has a packed array component???
1122
1123      if Within_Init_Proc
1124        and then Initialize_Scalars
1125      then
1126         Analyze_And_Resolve (Rhs, Ctyp, Suppress => All_Checks);
1127      else
1128         Analyze_And_Resolve (Rhs, Ctyp);
1129      end if;
1130
1131      --  For the AAMP target, indexing of certain packed array is passed
1132      --  through to the back end without expansion, because the expansion
1133      --  results in very inefficient code on that target. This allows the
1134      --  GNAAMP back end to generate specialized macros that support more
1135      --  efficient indexing of packed arrays with components having sizes
1136      --  that are small powers of two.
1137
1138      if AAMP_On_Target
1139        and then (Csiz = 1 or else Csiz = 2 or else Csiz = 4)
1140      then
1141         return;
1142      end if;
1143
1144      --  Case of component size 1,2,4 or any component size for the modular
1145      --  case. These are the cases for which we can inline the code.
1146
1147      if Csiz = 1 or else Csiz = 2 or else Csiz = 4
1148        or else (Present (PAT) and then Is_Modular_Integer_Type (PAT))
1149      then
1150         Setup_Inline_Packed_Array_Reference (Lhs, Atyp, Obj, Cmask, Shift);
1151
1152         --  The statement to be generated is:
1153
1154         --    Obj := atyp!((Obj and Mask1) or (shift_left (rhs, Shift)))
1155
1156         --  or in the case of a freestanding Reverse_Storage_Order object,
1157
1158         --    Obj := Swap (atyp!((Swap (Obj) and Mask1)
1159         --                         or (shift_left (rhs, Shift))))
1160
1161         --      where Mask1 is obtained by shifting Cmask left Shift bits
1162         --      and then complementing the result.
1163
1164         --      the "and Mask1" is omitted if rhs is constant and all 1 bits
1165
1166         --      the "or ..." is omitted if rhs is constant and all 0 bits
1167
1168         --      rhs is converted to the appropriate type
1169
1170         --      The result is converted back to the array type, since
1171         --      otherwise we lose knowledge of the packed nature.
1172
1173         --  Determine if right side is all 0 bits or all 1 bits
1174
1175         if Compile_Time_Known_Value (Rhs) then
1176            Rhs_Val       := Expr_Rep_Value (Rhs);
1177            Rhs_Val_Known := True;
1178
1179         --  The following test catches the case of an unchecked conversion of
1180         --  an integer literal. This results from optimizing aggregates of
1181         --  packed types.
1182
1183         elsif Nkind (Rhs) = N_Unchecked_Type_Conversion
1184           and then Compile_Time_Known_Value (Expression (Rhs))
1185         then
1186            Rhs_Val       := Expr_Rep_Value (Expression (Rhs));
1187            Rhs_Val_Known := True;
1188
1189         else
1190            Rhs_Val       := No_Uint;
1191            Rhs_Val_Known := False;
1192         end if;
1193
1194         --  Some special checks for the case where the right hand value is
1195         --  known at compile time. Basically we have to take care of the
1196         --  implicit conversion to the subtype of the component object.
1197
1198         if Rhs_Val_Known then
1199
1200            --  If we have a biased component type then we must manually do the
1201            --  biasing, since we are taking responsibility in this case for
1202            --  constructing the exact bit pattern to be used.
1203
1204            if Has_Biased_Representation (Ctyp) then
1205               Rhs_Val := Rhs_Val - Expr_Rep_Value (Type_Low_Bound (Ctyp));
1206            end if;
1207
1208            --  For a negative value, we manually convert the two's complement
1209            --  value to a corresponding unsigned value, so that the proper
1210            --  field width is maintained. If we did not do this, we would
1211            --  get too many leading sign bits later on.
1212
1213            if Rhs_Val < 0 then
1214               Rhs_Val := 2 ** UI_From_Int (Csiz) + Rhs_Val;
1215            end if;
1216         end if;
1217
1218         --  Now create copies removing side effects. Note that in some complex
1219         --  cases, this may cause the fact that we have already set a packed
1220         --  array type on Obj to get lost. So we save the type of Obj, and
1221         --  make sure it is reset properly.
1222
1223         New_Lhs := Duplicate_Subexpr (Obj, Name_Req => True);
1224         New_Rhs := Duplicate_Subexpr_No_Checks (Obj);
1225
1226         --  First we deal with the "and"
1227
1228         if not Rhs_Val_Known or else Rhs_Val /= Cmask then
1229            declare
1230               Mask1 : Node_Id;
1231               Lit   : Node_Id;
1232
1233            begin
1234               if Compile_Time_Known_Value (Shift) then
1235                  Mask1 :=
1236                    Make_Integer_Literal (Loc,
1237                      Modulus (Etype (Obj)) - 1 -
1238                                 (Cmask * (2 ** Expr_Value (Get_Shift))));
1239                  Set_Print_In_Hex (Mask1);
1240
1241               else
1242                  Lit := Make_Integer_Literal (Loc, Cmask);
1243                  Set_Print_In_Hex (Lit);
1244                  Mask1 :=
1245                    Make_Op_Not (Loc,
1246                      Right_Opnd => Make_Shift_Left (Lit, Get_Shift));
1247               end if;
1248
1249               New_Rhs :=
1250                 Make_Op_And (Loc,
1251                   Left_Opnd  => New_Rhs,
1252                   Right_Opnd => Mask1);
1253            end;
1254         end if;
1255
1256         --  Then deal with the "or"
1257
1258         if not Rhs_Val_Known or else Rhs_Val /= 0 then
1259            declare
1260               Or_Rhs : Node_Id;
1261
1262               procedure Fixup_Rhs;
1263               --  Adjust Rhs by bias if biased representation for components
1264               --  or remove extraneous high order sign bits if signed.
1265
1266               procedure Fixup_Rhs is
1267                  Etyp : constant Entity_Id := Etype (Rhs);
1268
1269               begin
1270                  --  For biased case, do the required biasing by simply
1271                  --  converting to the biased subtype (the conversion
1272                  --  will generate the required bias).
1273
1274                  if Has_Biased_Representation (Ctyp) then
1275                     Rhs := Convert_To (Ctyp, Rhs);
1276
1277                  --  For a signed integer type that is not biased, generate
1278                  --  a conversion to unsigned to strip high order sign bits.
1279
1280                  elsif Is_Signed_Integer_Type (Ctyp) then
1281                     Rhs := Unchecked_Convert_To (RTE (Bits_Id (Csiz)), Rhs);
1282                  end if;
1283
1284                  --  Set Etype, since it can be referenced before the node is
1285                  --  completely analyzed.
1286
1287                  Set_Etype (Rhs, Etyp);
1288
1289                  --  We now need to do an unchecked conversion of the
1290                  --  result to the target type, but it is important that
1291                  --  this conversion be a right justified conversion and
1292                  --  not a left justified conversion.
1293
1294                  Rhs := RJ_Unchecked_Convert_To (Etype (Obj), Rhs);
1295               end Fixup_Rhs;
1296
1297            begin
1298               if Rhs_Val_Known
1299                 and then Compile_Time_Known_Value (Get_Shift)
1300               then
1301                  Or_Rhs :=
1302                    Make_Integer_Literal (Loc,
1303                      Rhs_Val * (2 ** Expr_Value (Get_Shift)));
1304                  Set_Print_In_Hex (Or_Rhs);
1305
1306               else
1307                  --  We have to convert the right hand side to Etype (Obj).
1308                  --  A special case arises if what we have now is a Val
1309                  --  attribute reference whose expression type is Etype (Obj).
1310                  --  This happens for assignments of fields from the same
1311                  --  array. In this case we get the required right hand side
1312                  --  by simply removing the inner attribute reference.
1313
1314                  if Nkind (Rhs) = N_Attribute_Reference
1315                    and then Attribute_Name (Rhs) = Name_Val
1316                    and then Etype (First (Expressions (Rhs))) = Etype (Obj)
1317                  then
1318                     Rhs := Relocate_Node (First (Expressions (Rhs)));
1319                     Fixup_Rhs;
1320
1321                  --  If the value of the right hand side is a known integer
1322                  --  value, then just replace it by an untyped constant,
1323                  --  which will be properly retyped when we analyze and
1324                  --  resolve the expression.
1325
1326                  elsif Rhs_Val_Known then
1327
1328                     --  Note that Rhs_Val has already been normalized to
1329                     --  be an unsigned value with the proper number of bits.
1330
1331                     Rhs := Make_Integer_Literal (Loc, Rhs_Val);
1332
1333                  --  Otherwise we need an unchecked conversion
1334
1335                  else
1336                     Fixup_Rhs;
1337                  end if;
1338
1339                  Or_Rhs := Make_Shift_Left (Rhs, Get_Shift);
1340               end if;
1341
1342               if Nkind (New_Rhs) = N_Op_And then
1343                  Set_Paren_Count (New_Rhs, 1);
1344                  Set_Etype (New_Rhs, Etype (Left_Opnd (New_Rhs)));
1345               end if;
1346
1347               New_Rhs :=
1348                 Make_Op_Or (Loc,
1349                   Left_Opnd  => New_Rhs,
1350                   Right_Opnd => Or_Rhs);
1351            end;
1352         end if;
1353
1354         --  Now do the rewrite
1355
1356         Rewrite (N,
1357           Make_Assignment_Statement (Loc,
1358             Name       => New_Lhs,
1359             Expression =>
1360               Unchecked_Convert_To (Etype (New_Lhs), New_Rhs)));
1361         Set_Assignment_OK (Name (N), Ass_OK);
1362
1363      --  All other component sizes for non-modular case
1364
1365      else
1366         --  We generate
1367
1368         --    Set_nn (Arr'address, Subscr, Bits_nn!(Rhs))
1369
1370         --  where Subscr is the computed linear subscript
1371
1372         declare
1373            Bits_nn : constant Entity_Id := RTE (Bits_Id (Csiz));
1374            Set_nn  : Entity_Id;
1375            Subscr  : Node_Id;
1376            Atyp    : Entity_Id;
1377            Rev_SSO : Node_Id;
1378
1379         begin
1380            if No (Bits_nn) then
1381
1382               --  Error, most likely High_Integrity_Mode restriction
1383
1384               return;
1385            end if;
1386
1387            --  Acquire proper Set entity. We use the aligned or unaligned
1388            --  case as appropriate.
1389
1390            if Known_Aligned_Enough (Obj, Csiz) then
1391               Set_nn := RTE (Set_Id (Csiz));
1392            else
1393               Set_nn := RTE (SetU_Id (Csiz));
1394            end if;
1395
1396            --  Now generate the set reference
1397
1398            Obj := Relocate_Node (Prefix (Lhs));
1399            Convert_To_Actual_Subtype (Obj);
1400            Atyp := Etype (Obj);
1401            Compute_Linear_Subscript (Atyp, Lhs, Subscr);
1402
1403            --  Set indication of whether the packed array has reverse SSO
1404
1405            Rev_SSO :=
1406              New_Occurrence_Of
1407                (Boolean_Literals (Reverse_Storage_Order (Atyp)), Loc);
1408
1409            --  Below we must make the assumption that Obj is
1410            --  at least byte aligned, since otherwise its address
1411            --  cannot be taken. The assumption holds since the
1412            --  only arrays that can be misaligned are small packed
1413            --  arrays which are implemented as a modular type, and
1414            --  that is not the case here.
1415
1416            Rewrite (N,
1417              Make_Procedure_Call_Statement (Loc,
1418                  Name => New_Occurrence_Of (Set_nn, Loc),
1419                  Parameter_Associations => New_List (
1420                    Make_Attribute_Reference (Loc,
1421                      Prefix         => Obj,
1422                      Attribute_Name => Name_Address),
1423                    Subscr,
1424                    Unchecked_Convert_To (Bits_nn, Convert_To (Ctyp, Rhs)),
1425                    Rev_SSO)));
1426
1427         end;
1428      end if;
1429
1430      Analyze (N, Suppress => All_Checks);
1431   end Expand_Bit_Packed_Element_Set;
1432
1433   -------------------------------------
1434   -- Expand_Packed_Address_Reference --
1435   -------------------------------------
1436
1437   procedure Expand_Packed_Address_Reference (N : Node_Id) is
1438      Loc    : constant Source_Ptr := Sloc (N);
1439      Base   : Node_Id;
1440      Offset : Node_Id;
1441
1442   begin
1443      --  We build an expression that has the form
1444
1445      --    outer_object'Address
1446      --      + (linear-subscript * component_size  for each array reference
1447      --      +  field'Bit_Position                 for each record field
1448      --      +  ...
1449      --      +  ...) / Storage_Unit;
1450
1451      Get_Base_And_Bit_Offset (Prefix (N), Base, Offset);
1452
1453      Rewrite (N,
1454        Unchecked_Convert_To (RTE (RE_Address),
1455          Make_Op_Add (Loc,
1456            Left_Opnd =>
1457              Unchecked_Convert_To (RTE (RE_Integer_Address),
1458                Make_Attribute_Reference (Loc,
1459                  Prefix         => Base,
1460                  Attribute_Name => Name_Address)),
1461
1462            Right_Opnd =>
1463              Unchecked_Convert_To (RTE (RE_Integer_Address),
1464                Make_Op_Divide (Loc,
1465                  Left_Opnd => Offset,
1466                  Right_Opnd =>
1467                    Make_Integer_Literal (Loc, System_Storage_Unit))))));
1468
1469      Analyze_And_Resolve (N, RTE (RE_Address));
1470   end Expand_Packed_Address_Reference;
1471
1472   ---------------------------------
1473   -- Expand_Packed_Bit_Reference --
1474   ---------------------------------
1475
1476   procedure Expand_Packed_Bit_Reference (N : Node_Id) is
1477      Loc    : constant Source_Ptr := Sloc (N);
1478      Base   : Node_Id;
1479      Offset : Node_Id;
1480
1481   begin
1482      --  We build an expression that has the form
1483
1484      --    (linear-subscript * component_size      for each array reference
1485      --      +  field'Bit_Position                 for each record field
1486      --      +  ...
1487      --      +  ...) mod Storage_Unit;
1488
1489      Get_Base_And_Bit_Offset (Prefix (N), Base, Offset);
1490
1491      Rewrite (N,
1492        Unchecked_Convert_To (Universal_Integer,
1493          Make_Op_Mod (Loc,
1494            Left_Opnd => Offset,
1495            Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
1496
1497      Analyze_And_Resolve (N, Universal_Integer);
1498   end Expand_Packed_Bit_Reference;
1499
1500   ------------------------------------
1501   -- Expand_Packed_Boolean_Operator --
1502   ------------------------------------
1503
1504   --  This routine expands "a op b" for the packed cases
1505
1506   procedure Expand_Packed_Boolean_Operator (N : Node_Id) is
1507      Loc : constant Source_Ptr := Sloc (N);
1508      Typ : constant Entity_Id  := Etype (N);
1509      L   : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
1510      R   : constant Node_Id    := Relocate_Node (Right_Opnd (N));
1511
1512      Ltyp : Entity_Id;
1513      Rtyp : Entity_Id;
1514      PAT  : Entity_Id;
1515
1516   begin
1517      Convert_To_Actual_Subtype (L);
1518      Convert_To_Actual_Subtype (R);
1519
1520      Ensure_Defined (Etype (L), N);
1521      Ensure_Defined (Etype (R), N);
1522
1523      Apply_Length_Check (R, Etype (L));
1524
1525      Ltyp := Etype (L);
1526      Rtyp := Etype (R);
1527
1528      --  Deal with silly case of XOR where the subcomponent has a range
1529      --  True .. True where an exception must be raised.
1530
1531      if Nkind (N) = N_Op_Xor then
1532         Silly_Boolean_Array_Xor_Test (N, Rtyp);
1533      end if;
1534
1535      --  Now that that silliness is taken care of, get packed array type
1536
1537      Convert_To_PAT_Type (L);
1538      Convert_To_PAT_Type (R);
1539
1540      PAT := Etype (L);
1541
1542      --  For the modular case, we expand a op b into
1543
1544      --    rtyp!(pat!(a) op pat!(b))
1545
1546      --  where rtyp is the Etype of the left operand. Note that we do not
1547      --  convert to the base type, since this would be unconstrained, and
1548      --  hence not have a corresponding packed array type set.
1549
1550      --  Note that both operands must be modular for this code to be used
1551
1552      if Is_Modular_Integer_Type (PAT)
1553           and then
1554         Is_Modular_Integer_Type (Etype (R))
1555      then
1556         declare
1557            P : Node_Id;
1558
1559         begin
1560            if Nkind (N) = N_Op_And then
1561               P := Make_Op_And (Loc, L, R);
1562
1563            elsif Nkind (N) = N_Op_Or then
1564               P := Make_Op_Or  (Loc, L, R);
1565
1566            else -- Nkind (N) = N_Op_Xor
1567               P := Make_Op_Xor (Loc, L, R);
1568            end if;
1569
1570            Rewrite (N, Unchecked_Convert_To (Ltyp, P));
1571         end;
1572
1573      --  For the array case, we insert the actions
1574
1575      --    Result : Ltype;
1576
1577      --    System.Bit_Ops.Bit_And/Or/Xor
1578      --     (Left'Address,
1579      --      Ltype'Length * Ltype'Component_Size;
1580      --      Right'Address,
1581      --      Rtype'Length * Rtype'Component_Size
1582      --      Result'Address);
1583
1584      --  where Left and Right are the Packed_Bytes{1,2,4} operands and
1585      --  the second argument and fourth arguments are the lengths of the
1586      --  operands in bits. Then we replace the expression by a reference
1587      --  to Result.
1588
1589      --  Note that if we are mixing a modular and array operand, everything
1590      --  works fine, since we ensure that the modular representation has the
1591      --  same physical layout as the array representation (that's what the
1592      --  left justified modular stuff in the big-endian case is about).
1593
1594      else
1595         declare
1596            Result_Ent : constant Entity_Id := Make_Temporary (Loc, 'T');
1597            E_Id       : RE_Id;
1598
1599         begin
1600            if Nkind (N) = N_Op_And then
1601               E_Id := RE_Bit_And;
1602
1603            elsif Nkind (N) = N_Op_Or then
1604               E_Id := RE_Bit_Or;
1605
1606            else -- Nkind (N) = N_Op_Xor
1607               E_Id := RE_Bit_Xor;
1608            end if;
1609
1610            Insert_Actions (N, New_List (
1611
1612              Make_Object_Declaration (Loc,
1613                Defining_Identifier => Result_Ent,
1614                Object_Definition => New_Occurrence_Of (Ltyp, Loc)),
1615
1616              Make_Procedure_Call_Statement (Loc,
1617                Name => New_Occurrence_Of (RTE (E_Id), Loc),
1618                  Parameter_Associations => New_List (
1619
1620                    Make_Byte_Aligned_Attribute_Reference (Loc,
1621                      Prefix         => L,
1622                      Attribute_Name => Name_Address),
1623
1624                    Make_Op_Multiply (Loc,
1625                      Left_Opnd =>
1626                        Make_Attribute_Reference (Loc,
1627                          Prefix         =>
1628                            New_Occurrence_Of
1629                              (Etype (First_Index (Ltyp)), Loc),
1630                          Attribute_Name => Name_Range_Length),
1631
1632                      Right_Opnd =>
1633                        Make_Integer_Literal (Loc, Component_Size (Ltyp))),
1634
1635                    Make_Byte_Aligned_Attribute_Reference (Loc,
1636                      Prefix         => R,
1637                      Attribute_Name => Name_Address),
1638
1639                    Make_Op_Multiply (Loc,
1640                      Left_Opnd =>
1641                        Make_Attribute_Reference (Loc,
1642                          Prefix         =>
1643                            New_Occurrence_Of
1644                              (Etype (First_Index (Rtyp)), Loc),
1645                          Attribute_Name => Name_Range_Length),
1646
1647                      Right_Opnd =>
1648                        Make_Integer_Literal (Loc, Component_Size (Rtyp))),
1649
1650                    Make_Byte_Aligned_Attribute_Reference (Loc,
1651                      Prefix => New_Occurrence_Of (Result_Ent, Loc),
1652                      Attribute_Name => Name_Address)))));
1653
1654            Rewrite (N,
1655              New_Occurrence_Of (Result_Ent, Loc));
1656         end;
1657      end if;
1658
1659      Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
1660   end Expand_Packed_Boolean_Operator;
1661
1662   -------------------------------------
1663   -- Expand_Packed_Element_Reference --
1664   -------------------------------------
1665
1666   procedure Expand_Packed_Element_Reference (N : Node_Id) is
1667      Loc   : constant Source_Ptr := Sloc (N);
1668      Obj   : Node_Id;
1669      Atyp  : Entity_Id;
1670      PAT   : Entity_Id;
1671      Ctyp  : Entity_Id;
1672      Csiz  : Int;
1673      Shift : Node_Id;
1674      Cmask : Uint;
1675      Lit   : Node_Id;
1676      Arg   : Node_Id;
1677
1678   begin
1679      --  If the node is an actual in a call, the prefix has not been fully
1680      --  expanded, to account for the additional expansion for in-out actuals
1681      --  (see expand_actuals for details). If the prefix itself is a packed
1682      --  reference as well, we have to recurse to complete the transformation
1683      --  of the prefix.
1684
1685      if Nkind (Prefix (N)) = N_Indexed_Component
1686        and then not Analyzed (Prefix (N))
1687        and then Is_Bit_Packed_Array (Etype (Prefix (Prefix (N))))
1688      then
1689         Expand_Packed_Element_Reference (Prefix (N));
1690      end if;
1691
1692      --  The prefix may be rewritten below as a conversion. If it is a source
1693      --  entity generate reference to it now, to prevent spurious warnings
1694      --  about unused entities.
1695
1696      if Is_Entity_Name (Prefix (N))
1697        and then Comes_From_Source (Prefix (N))
1698      then
1699         Generate_Reference (Entity (Prefix (N)), Prefix (N), 'r');
1700      end if;
1701
1702      --  If not bit packed, we have the enumeration case, which is easily
1703      --  dealt with (just adjust the subscripts of the indexed component)
1704
1705      --  Note: this leaves the result as an indexed component, which is
1706      --  still a variable, so can be used in the assignment case, as is
1707      --  required in the enumeration case.
1708
1709      if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
1710         Setup_Enumeration_Packed_Array_Reference (N);
1711         return;
1712      end if;
1713
1714      --  Remaining processing is for the bit-packed case
1715
1716      Obj := Relocate_Node (Prefix (N));
1717      Convert_To_Actual_Subtype (Obj);
1718      Atyp := Etype (Obj);
1719      PAT  := Packed_Array_Impl_Type (Atyp);
1720      Ctyp := Component_Type (Atyp);
1721      Csiz := UI_To_Int (Component_Size (Atyp));
1722
1723      --  For the AAMP target, indexing of certain packed array is passed
1724      --  through to the back end without expansion, because the expansion
1725      --  results in very inefficient code on that target. This allows the
1726      --  GNAAMP back end to generate specialized macros that support more
1727      --  efficient indexing of packed arrays with components having sizes
1728      --  that are small powers of two.
1729
1730      if AAMP_On_Target
1731        and then (Csiz = 1 or else Csiz = 2 or else Csiz = 4)
1732      then
1733         return;
1734      end if;
1735
1736      --  Case of component size 1,2,4 or any component size for the modular
1737      --  case. These are the cases for which we can inline the code.
1738
1739      if Csiz = 1 or else Csiz = 2 or else Csiz = 4
1740        or else (Present (PAT) and then Is_Modular_Integer_Type (PAT))
1741      then
1742         Setup_Inline_Packed_Array_Reference (N, Atyp, Obj, Cmask, Shift);
1743         Lit := Make_Integer_Literal (Loc, Cmask);
1744         Set_Print_In_Hex (Lit);
1745
1746         --  We generate a shift right to position the field, followed by a
1747         --  masking operation to extract the bit field, and we finally do an
1748         --  unchecked conversion to convert the result to the required target.
1749
1750         --  Note that the unchecked conversion automatically deals with the
1751         --  bias if we are dealing with a biased representation. What will
1752         --  happen is that we temporarily generate the biased representation,
1753         --  but almost immediately that will be converted to the original
1754         --  unbiased component type, and the bias will disappear.
1755
1756         Arg :=
1757           Make_Op_And (Loc,
1758             Left_Opnd  => Make_Shift_Right (Obj, Shift),
1759             Right_Opnd => Lit);
1760         Set_Etype (Arg, Ctyp);
1761
1762         --  Component extraction is performed on a native endianness scalar
1763         --  value: if Atyp has reverse storage order, then it has been byte
1764         --  swapped, and if the component being extracted is itself of a
1765         --  composite type with reverse storage order, then we need to swap
1766         --  it back to its expected endianness after extraction.
1767
1768         if Reverse_Storage_Order (Atyp)
1769           and then (Is_Record_Type (Ctyp) or else Is_Array_Type (Ctyp))
1770           and then Reverse_Storage_Order (Ctyp)
1771         then
1772            Arg := Revert_Storage_Order (Arg);
1773         end if;
1774
1775         --  We needed to analyze this before we do the unchecked convert
1776         --  below, but we need it temporarily attached to the tree for
1777         --  this analysis (hence the temporary Set_Parent call).
1778
1779         Set_Parent (Arg, Parent (N));
1780         Analyze_And_Resolve (Arg);
1781
1782         Rewrite (N, RJ_Unchecked_Convert_To (Ctyp, Arg));
1783
1784      --  All other component sizes for non-modular case
1785
1786      else
1787         --  We generate
1788
1789         --    Component_Type!(Get_nn (Arr'address, Subscr))
1790
1791         --  where Subscr is the computed linear subscript
1792
1793         declare
1794            Get_nn  : Entity_Id;
1795            Subscr  : Node_Id;
1796            Rev_SSO : constant Node_Id :=
1797              New_Occurrence_Of
1798                (Boolean_Literals (Reverse_Storage_Order (Atyp)), Loc);
1799
1800         begin
1801            --  Acquire proper Get entity. We use the aligned or unaligned
1802            --  case as appropriate.
1803
1804            if Known_Aligned_Enough (Obj, Csiz) then
1805               Get_nn := RTE (Get_Id (Csiz));
1806            else
1807               Get_nn := RTE (GetU_Id (Csiz));
1808            end if;
1809
1810            --  Now generate the get reference
1811
1812            Compute_Linear_Subscript (Atyp, N, Subscr);
1813
1814            --  Below we make the assumption that Obj is at least byte
1815            --  aligned, since otherwise its address cannot be taken.
1816            --  The assumption holds since the only arrays that can be
1817            --  misaligned are small packed arrays which are implemented
1818            --  as a modular type, and that is not the case here.
1819
1820            Rewrite (N,
1821              Unchecked_Convert_To (Ctyp,
1822                Make_Function_Call (Loc,
1823                  Name => New_Occurrence_Of (Get_nn, Loc),
1824                  Parameter_Associations => New_List (
1825                    Make_Attribute_Reference (Loc,
1826                      Prefix         => Obj,
1827                      Attribute_Name => Name_Address),
1828                    Subscr,
1829                    Rev_SSO))));
1830         end;
1831      end if;
1832
1833      Analyze_And_Resolve (N, Ctyp, Suppress => All_Checks);
1834   end Expand_Packed_Element_Reference;
1835
1836   ----------------------
1837   -- Expand_Packed_Eq --
1838   ----------------------
1839
1840   --  Handles expansion of "=" on packed array types
1841
1842   procedure Expand_Packed_Eq (N : Node_Id) is
1843      Loc : constant Source_Ptr := Sloc (N);
1844      L   : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
1845      R   : constant Node_Id    := Relocate_Node (Right_Opnd (N));
1846
1847      LLexpr : Node_Id;
1848      RLexpr : Node_Id;
1849
1850      Ltyp : Entity_Id;
1851      Rtyp : Entity_Id;
1852      PAT  : Entity_Id;
1853
1854   begin
1855      Convert_To_Actual_Subtype (L);
1856      Convert_To_Actual_Subtype (R);
1857      Ltyp := Underlying_Type (Etype (L));
1858      Rtyp := Underlying_Type (Etype (R));
1859
1860      Convert_To_PAT_Type (L);
1861      Convert_To_PAT_Type (R);
1862      PAT := Etype (L);
1863
1864      LLexpr :=
1865        Make_Op_Multiply (Loc,
1866          Left_Opnd =>
1867            Make_Attribute_Reference (Loc,
1868              Prefix         => New_Occurrence_Of (Ltyp, Loc),
1869              Attribute_Name => Name_Length),
1870          Right_Opnd =>
1871            Make_Integer_Literal (Loc, Component_Size (Ltyp)));
1872
1873      RLexpr :=
1874        Make_Op_Multiply (Loc,
1875          Left_Opnd =>
1876            Make_Attribute_Reference (Loc,
1877              Prefix         => New_Occurrence_Of (Rtyp, Loc),
1878              Attribute_Name => Name_Length),
1879          Right_Opnd =>
1880            Make_Integer_Literal (Loc, Component_Size (Rtyp)));
1881
1882      --  For the modular case, we transform the comparison to:
1883
1884      --    Ltyp'Length = Rtyp'Length and then PAT!(L) = PAT!(R)
1885
1886      --  where PAT is the packed array type. This works fine, since in the
1887      --  modular case we guarantee that the unused bits are always zeroes.
1888      --  We do have to compare the lengths because we could be comparing
1889      --  two different subtypes of the same base type.
1890
1891      if Is_Modular_Integer_Type (PAT) then
1892         Rewrite (N,
1893           Make_And_Then (Loc,
1894             Left_Opnd =>
1895               Make_Op_Eq (Loc,
1896                 Left_Opnd  => LLexpr,
1897                 Right_Opnd => RLexpr),
1898
1899             Right_Opnd =>
1900               Make_Op_Eq (Loc,
1901                 Left_Opnd => L,
1902                 Right_Opnd => R)));
1903
1904      --  For the non-modular case, we call a runtime routine
1905
1906      --    System.Bit_Ops.Bit_Eq
1907      --      (L'Address, L_Length, R'Address, R_Length)
1908
1909      --  where PAT is the packed array type, and the lengths are the lengths
1910      --  in bits of the original packed arrays. This routine takes care of
1911      --  not comparing the unused bits in the last byte.
1912
1913      else
1914         Rewrite (N,
1915           Make_Function_Call (Loc,
1916             Name => New_Occurrence_Of (RTE (RE_Bit_Eq), Loc),
1917             Parameter_Associations => New_List (
1918               Make_Byte_Aligned_Attribute_Reference (Loc,
1919                 Prefix         => L,
1920                 Attribute_Name => Name_Address),
1921
1922               LLexpr,
1923
1924               Make_Byte_Aligned_Attribute_Reference (Loc,
1925                 Prefix         => R,
1926                 Attribute_Name => Name_Address),
1927
1928               RLexpr)));
1929      end if;
1930
1931      Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
1932   end Expand_Packed_Eq;
1933
1934   -----------------------
1935   -- Expand_Packed_Not --
1936   -----------------------
1937
1938   --  Handles expansion of "not" on packed array types
1939
1940   procedure Expand_Packed_Not (N : Node_Id) is
1941      Loc  : constant Source_Ptr := Sloc (N);
1942      Typ  : constant Entity_Id  := Etype (N);
1943      Opnd : constant Node_Id    := Relocate_Node (Right_Opnd (N));
1944
1945      Rtyp : Entity_Id;
1946      PAT  : Entity_Id;
1947      Lit  : Node_Id;
1948
1949   begin
1950      Convert_To_Actual_Subtype (Opnd);
1951      Rtyp := Etype (Opnd);
1952
1953      --  Deal with silly False..False and True..True subtype case
1954
1955      Silly_Boolean_Array_Not_Test (N, Rtyp);
1956
1957      --  Now that the silliness is taken care of, get packed array type
1958
1959      Convert_To_PAT_Type (Opnd);
1960      PAT := Etype (Opnd);
1961
1962      --  For the case where the packed array type is a modular type, "not A"
1963      --  expands simply into:
1964
1965      --     Rtyp!(PAT!(A) xor Mask)
1966
1967      --  where PAT is the packed array type, Mask is a mask of all 1 bits of
1968      --  length equal to the size of this packed type, and Rtyp is the actual
1969      --  actual subtype of the operand.
1970
1971      Lit := Make_Integer_Literal (Loc, 2 ** RM_Size (PAT) - 1);
1972      Set_Print_In_Hex (Lit);
1973
1974      if not Is_Array_Type (PAT) then
1975         Rewrite (N,
1976           Unchecked_Convert_To (Rtyp,
1977             Make_Op_Xor (Loc,
1978               Left_Opnd  => Opnd,
1979               Right_Opnd => Lit)));
1980
1981      --  For the array case, we insert the actions
1982
1983      --    Result : Typ;
1984
1985      --    System.Bit_Ops.Bit_Not
1986      --     (Opnd'Address,
1987      --      Typ'Length * Typ'Component_Size,
1988      --      Result'Address);
1989
1990      --  where Opnd is the Packed_Bytes{1,2,4} operand and the second argument
1991      --  is the length of the operand in bits. We then replace the expression
1992      --  with a reference to Result.
1993
1994      else
1995         declare
1996            Result_Ent : constant Entity_Id := Make_Temporary (Loc, 'T');
1997
1998         begin
1999            Insert_Actions (N, New_List (
2000              Make_Object_Declaration (Loc,
2001                Defining_Identifier => Result_Ent,
2002                Object_Definition   => New_Occurrence_Of (Rtyp, Loc)),
2003
2004              Make_Procedure_Call_Statement (Loc,
2005                Name => New_Occurrence_Of (RTE (RE_Bit_Not), Loc),
2006                  Parameter_Associations => New_List (
2007                    Make_Byte_Aligned_Attribute_Reference (Loc,
2008                      Prefix         => Opnd,
2009                      Attribute_Name => Name_Address),
2010
2011                    Make_Op_Multiply (Loc,
2012                      Left_Opnd =>
2013                        Make_Attribute_Reference (Loc,
2014                          Prefix         =>
2015                            New_Occurrence_Of
2016                              (Etype (First_Index (Rtyp)), Loc),
2017                          Attribute_Name => Name_Range_Length),
2018
2019                      Right_Opnd =>
2020                        Make_Integer_Literal (Loc, Component_Size (Rtyp))),
2021
2022                    Make_Byte_Aligned_Attribute_Reference (Loc,
2023                      Prefix         => New_Occurrence_Of (Result_Ent, Loc),
2024                      Attribute_Name => Name_Address)))));
2025
2026            Rewrite (N, New_Occurrence_Of (Result_Ent, Loc));
2027         end;
2028      end if;
2029
2030      Analyze_And_Resolve (N, Typ, Suppress => All_Checks);
2031   end Expand_Packed_Not;
2032
2033   -----------------------------
2034   -- Get_Base_And_Bit_Offset --
2035   -----------------------------
2036
2037   procedure Get_Base_And_Bit_Offset
2038     (N      : Node_Id;
2039      Base   : out Node_Id;
2040      Offset : out Node_Id)
2041   is
2042      Loc    : Source_Ptr;
2043      Term   : Node_Id;
2044      Atyp   : Entity_Id;
2045      Subscr : Node_Id;
2046
2047   begin
2048      Base   := N;
2049      Offset := Empty;
2050
2051      --  We build up an expression serially that has the form
2052
2053      --    linear-subscript * component_size       for each array reference
2054      --      +  field'Bit_Position                 for each record field
2055      --      +  ...
2056
2057      loop
2058         Loc := Sloc (Base);
2059
2060         if Nkind (Base) = N_Indexed_Component then
2061            Convert_To_Actual_Subtype (Prefix (Base));
2062            Atyp := Etype (Prefix (Base));
2063            Compute_Linear_Subscript (Atyp, Base, Subscr);
2064
2065            Term :=
2066              Make_Op_Multiply (Loc,
2067                Left_Opnd => Subscr,
2068                Right_Opnd =>
2069                 Make_Attribute_Reference (Loc,
2070                   Prefix         => New_Occurrence_Of (Atyp, Loc),
2071                   Attribute_Name => Name_Component_Size));
2072
2073         elsif Nkind (Base) = N_Selected_Component then
2074            Term :=
2075              Make_Attribute_Reference (Loc,
2076                Prefix         => Selector_Name (Base),
2077                Attribute_Name => Name_Bit_Position);
2078
2079         else
2080            return;
2081         end if;
2082
2083         if No (Offset) then
2084            Offset := Term;
2085
2086         else
2087            Offset :=
2088              Make_Op_Add (Loc,
2089                Left_Opnd  => Offset,
2090                Right_Opnd => Term);
2091         end if;
2092
2093         Base := Prefix (Base);
2094      end loop;
2095   end Get_Base_And_Bit_Offset;
2096
2097   -------------------------------------
2098   -- Involves_Packed_Array_Reference --
2099   -------------------------------------
2100
2101   function Involves_Packed_Array_Reference (N : Node_Id) return Boolean is
2102   begin
2103      if Nkind (N) = N_Indexed_Component
2104        and then Is_Bit_Packed_Array (Etype (Prefix (N)))
2105      then
2106         return True;
2107
2108      elsif Nkind (N) = N_Selected_Component then
2109         return Involves_Packed_Array_Reference (Prefix (N));
2110
2111      else
2112         return False;
2113      end if;
2114   end Involves_Packed_Array_Reference;
2115
2116   --------------------------
2117   -- Known_Aligned_Enough --
2118   --------------------------
2119
2120   function Known_Aligned_Enough (Obj : Node_Id; Csiz : Nat) return Boolean is
2121      Typ : constant Entity_Id := Etype (Obj);
2122
2123      function In_Partially_Packed_Record (Comp : Entity_Id) return Boolean;
2124      --  If the component is in a record that contains previous packed
2125      --  components, consider it unaligned because the back-end might
2126      --  choose to pack the rest of the record. Lead to less efficient code,
2127      --  but safer vis-a-vis of back-end choices.
2128
2129      --------------------------------
2130      -- In_Partially_Packed_Record --
2131      --------------------------------
2132
2133      function In_Partially_Packed_Record (Comp : Entity_Id) return Boolean is
2134         Rec_Type  : constant Entity_Id := Scope (Comp);
2135         Prev_Comp : Entity_Id;
2136
2137      begin
2138         Prev_Comp := First_Entity (Rec_Type);
2139         while Present (Prev_Comp) loop
2140            if Is_Packed (Etype (Prev_Comp)) then
2141               return True;
2142
2143            elsif Prev_Comp = Comp then
2144               return False;
2145            end if;
2146
2147            Next_Entity (Prev_Comp);
2148         end loop;
2149
2150         return False;
2151      end  In_Partially_Packed_Record;
2152
2153   --  Start of processing for Known_Aligned_Enough
2154
2155   begin
2156      --  Odd bit sizes don't need alignment anyway
2157
2158      if Csiz mod 2 = 1 then
2159         return True;
2160
2161      --  If we have a specified alignment, see if it is sufficient, if not
2162      --  then we can't possibly be aligned enough in any case.
2163
2164      elsif Known_Alignment (Etype (Obj)) then
2165         --  Alignment required is 4 if size is a multiple of 4, and
2166         --  2 otherwise (e.g. 12 bits requires 4, 10 bits requires 2)
2167
2168         if Alignment (Etype (Obj)) < 4 - (Csiz mod 4) then
2169            return False;
2170         end if;
2171      end if;
2172
2173      --  OK, alignment should be sufficient, if object is aligned
2174
2175      --  If object is strictly aligned, then it is definitely aligned
2176
2177      if Strict_Alignment (Typ) then
2178         return True;
2179
2180      --  Case of subscripted array reference
2181
2182      elsif Nkind (Obj) = N_Indexed_Component then
2183
2184         --  If we have a pointer to an array, then this is definitely
2185         --  aligned, because pointers always point to aligned versions.
2186
2187         if Is_Access_Type (Etype (Prefix (Obj))) then
2188            return True;
2189
2190         --  Otherwise, go look at the prefix
2191
2192         else
2193            return Known_Aligned_Enough (Prefix (Obj), Csiz);
2194         end if;
2195
2196      --  Case of record field
2197
2198      elsif Nkind (Obj) = N_Selected_Component then
2199
2200         --  What is significant here is whether the record type is packed
2201
2202         if Is_Record_Type (Etype (Prefix (Obj)))
2203           and then Is_Packed (Etype (Prefix (Obj)))
2204         then
2205            return False;
2206
2207         --  Or the component has a component clause which might cause
2208         --  the component to become unaligned (we can't tell if the
2209         --  backend is doing alignment computations).
2210
2211         elsif Present (Component_Clause (Entity (Selector_Name (Obj)))) then
2212            return False;
2213
2214         elsif In_Partially_Packed_Record (Entity (Selector_Name (Obj))) then
2215            return False;
2216
2217         --  In all other cases, go look at prefix
2218
2219         else
2220            return Known_Aligned_Enough (Prefix (Obj), Csiz);
2221         end if;
2222
2223      elsif Nkind (Obj) = N_Type_Conversion then
2224         return Known_Aligned_Enough (Expression (Obj), Csiz);
2225
2226      --  For a formal parameter, it is safer to assume that it is not
2227      --  aligned, because the formal may be unconstrained while the actual
2228      --  is constrained. In this situation, a small constrained packed
2229      --  array, represented in modular form, may be unaligned.
2230
2231      elsif Is_Entity_Name (Obj) then
2232         return not Is_Formal (Entity (Obj));
2233      else
2234
2235      --  If none of the above, must be aligned
2236         return True;
2237      end if;
2238   end Known_Aligned_Enough;
2239
2240   ---------------------
2241   -- Make_Shift_Left --
2242   ---------------------
2243
2244   function Make_Shift_Left (N : Node_Id; S : Node_Id) return Node_Id is
2245      Nod : Node_Id;
2246
2247   begin
2248      if Compile_Time_Known_Value (S) and then Expr_Value (S) = 0 then
2249         return N;
2250      else
2251         Nod :=
2252           Make_Op_Shift_Left (Sloc (N),
2253             Left_Opnd  => N,
2254             Right_Opnd => S);
2255         Set_Shift_Count_OK (Nod, True);
2256         return Nod;
2257      end if;
2258   end Make_Shift_Left;
2259
2260   ----------------------
2261   -- Make_Shift_Right --
2262   ----------------------
2263
2264   function Make_Shift_Right (N : Node_Id; S : Node_Id) return Node_Id is
2265      Nod : Node_Id;
2266
2267   begin
2268      if Compile_Time_Known_Value (S) and then Expr_Value (S) = 0 then
2269         return N;
2270      else
2271         Nod :=
2272           Make_Op_Shift_Right (Sloc (N),
2273             Left_Opnd  => N,
2274             Right_Opnd => S);
2275         Set_Shift_Count_OK (Nod, True);
2276         return Nod;
2277      end if;
2278   end Make_Shift_Right;
2279
2280   -----------------------------
2281   -- RJ_Unchecked_Convert_To --
2282   -----------------------------
2283
2284   function RJ_Unchecked_Convert_To
2285     (Typ  : Entity_Id;
2286      Expr : Node_Id) return Node_Id
2287   is
2288      Source_Typ : constant Entity_Id := Etype (Expr);
2289      Target_Typ : constant Entity_Id := Typ;
2290
2291      Src : Node_Id := Expr;
2292
2293      Source_Siz : Nat;
2294      Target_Siz : Nat;
2295
2296   begin
2297      Source_Siz := UI_To_Int (RM_Size (Source_Typ));
2298      Target_Siz := UI_To_Int (RM_Size (Target_Typ));
2299
2300      --  For a little-endian target type stored byte-swapped on a
2301      --  big-endian machine, do not mask to Target_Siz bits.
2302
2303      if Bytes_Big_Endian
2304           and then (Is_Record_Type (Target_Typ)
2305                       or else
2306                     Is_Array_Type (Target_Typ))
2307           and then Reverse_Storage_Order (Target_Typ)
2308      then
2309         Source_Siz := Target_Siz;
2310      end if;
2311
2312      --  First step, if the source type is not a discrete type, then we first
2313      --  convert to a modular type of the source length, since otherwise, on
2314      --  a big-endian machine, we get left-justification. We do it for little-
2315      --  endian machines as well, because there might be junk bits that are
2316      --  not cleared if the type is not numeric.
2317
2318      if Source_Siz /= Target_Siz
2319        and then not Is_Discrete_Type (Source_Typ)
2320      then
2321         Src := Unchecked_Convert_To (RTE (Bits_Id (Source_Siz)), Src);
2322      end if;
2323
2324      --  In the big endian case, if the lengths of the two types differ, then
2325      --  we must worry about possible left justification in the conversion,
2326      --  and avoiding that is what this is all about.
2327
2328      if Bytes_Big_Endian and then Source_Siz /= Target_Siz then
2329
2330         --  Next step. If the target is not a discrete type, then we first
2331         --  convert to a modular type of the target length, since otherwise,
2332         --  on a big-endian machine, we get left-justification.
2333
2334         if not Is_Discrete_Type (Target_Typ) then
2335            Src := Unchecked_Convert_To (RTE (Bits_Id (Target_Siz)), Src);
2336         end if;
2337      end if;
2338
2339      --  And now we can do the final conversion to the target type
2340
2341      return Unchecked_Convert_To (Target_Typ, Src);
2342   end RJ_Unchecked_Convert_To;
2343
2344   ----------------------------------------------
2345   -- Setup_Enumeration_Packed_Array_Reference --
2346   ----------------------------------------------
2347
2348   --  All we have to do here is to find the subscripts that correspond to the
2349   --  index positions that have non-standard enumeration types and insert a
2350   --  Pos attribute to get the proper subscript value.
2351
2352   --  Finally the prefix must be uncheck-converted to the corresponding packed
2353   --  array type.
2354
2355   --  Note that the component type is unchanged, so we do not need to fiddle
2356   --  with the types (Gigi always automatically takes the packed array type if
2357   --  it is set, as it will be in this case).
2358
2359   procedure Setup_Enumeration_Packed_Array_Reference (N : Node_Id) is
2360      Pfx   : constant Node_Id   := Prefix (N);
2361      Typ   : constant Entity_Id := Etype (N);
2362      Exprs : constant List_Id   := Expressions (N);
2363      Expr  : Node_Id;
2364
2365   begin
2366      --  If the array is unconstrained, then we replace the array reference
2367      --  with its actual subtype. This actual subtype will have a packed array
2368      --  type with appropriate bounds.
2369
2370      if not Is_Constrained (Packed_Array_Impl_Type (Etype (Pfx))) then
2371         Convert_To_Actual_Subtype (Pfx);
2372      end if;
2373
2374      Expr := First (Exprs);
2375      while Present (Expr) loop
2376         declare
2377            Loc      : constant Source_Ptr := Sloc (Expr);
2378            Expr_Typ : constant Entity_Id := Etype (Expr);
2379
2380         begin
2381            if Is_Enumeration_Type (Expr_Typ)
2382              and then Has_Non_Standard_Rep (Expr_Typ)
2383            then
2384               Rewrite (Expr,
2385                 Make_Attribute_Reference (Loc,
2386                   Prefix         => New_Occurrence_Of (Expr_Typ, Loc),
2387                   Attribute_Name => Name_Pos,
2388                   Expressions    => New_List (Relocate_Node (Expr))));
2389               Analyze_And_Resolve (Expr, Standard_Natural);
2390            end if;
2391         end;
2392
2393         Next (Expr);
2394      end loop;
2395
2396      Rewrite (N,
2397        Make_Indexed_Component (Sloc (N),
2398          Prefix      =>
2399            Unchecked_Convert_To (Packed_Array_Impl_Type (Etype (Pfx)), Pfx),
2400          Expressions => Exprs));
2401
2402      Analyze_And_Resolve (N, Typ);
2403   end Setup_Enumeration_Packed_Array_Reference;
2404
2405   -----------------------------------------
2406   -- Setup_Inline_Packed_Array_Reference --
2407   -----------------------------------------
2408
2409   procedure Setup_Inline_Packed_Array_Reference
2410     (N      : Node_Id;
2411      Atyp   : Entity_Id;
2412      Obj    : in out Node_Id;
2413      Cmask  : out Uint;
2414      Shift  : out Node_Id)
2415   is
2416      Loc  : constant Source_Ptr := Sloc (N);
2417      PAT  : Entity_Id;
2418      Otyp : Entity_Id;
2419      Csiz : Uint;
2420      Osiz : Uint;
2421
2422   begin
2423      Csiz := Component_Size (Atyp);
2424
2425      Convert_To_PAT_Type (Obj);
2426      PAT := Etype (Obj);
2427
2428      Cmask := 2 ** Csiz - 1;
2429
2430      if Is_Array_Type (PAT) then
2431         Otyp := Component_Type (PAT);
2432         Osiz := Component_Size (PAT);
2433
2434      else
2435         Otyp := PAT;
2436
2437         --  In the case where the PAT is a modular type, we want the actual
2438         --  size in bits of the modular value we use. This is neither the
2439         --  Object_Size nor the Value_Size, either of which may have been
2440         --  reset to strange values, but rather the minimum size. Note that
2441         --  since this is a modular type with full range, the issue of
2442         --  biased representation does not arise.
2443
2444         Osiz := UI_From_Int (Minimum_Size (Otyp));
2445      end if;
2446
2447      Compute_Linear_Subscript (Atyp, N, Shift);
2448
2449      --  If the component size is not 1, then the subscript must be multiplied
2450      --  by the component size to get the shift count.
2451
2452      if Csiz /= 1 then
2453         Shift :=
2454           Make_Op_Multiply (Loc,
2455             Left_Opnd  => Make_Integer_Literal (Loc, Csiz),
2456             Right_Opnd => Shift);
2457      end if;
2458
2459      --  If we have the array case, then this shift count must be broken down
2460      --  into a byte subscript, and a shift within the byte.
2461
2462      if Is_Array_Type (PAT) then
2463
2464         declare
2465            New_Shift : Node_Id;
2466
2467         begin
2468            --  We must analyze shift, since we will duplicate it
2469
2470            Set_Parent (Shift, N);
2471            Analyze_And_Resolve
2472              (Shift, Standard_Integer, Suppress => All_Checks);
2473
2474            --  The shift count within the word is
2475            --    shift mod Osiz
2476
2477            New_Shift :=
2478              Make_Op_Mod (Loc,
2479                Left_Opnd  => Duplicate_Subexpr (Shift),
2480                Right_Opnd => Make_Integer_Literal (Loc, Osiz));
2481
2482            --  The subscript to be used on the PAT array is
2483            --    shift / Osiz
2484
2485            Obj :=
2486              Make_Indexed_Component (Loc,
2487                Prefix => Obj,
2488                Expressions => New_List (
2489                  Make_Op_Divide (Loc,
2490                    Left_Opnd  => Duplicate_Subexpr (Shift),
2491                    Right_Opnd => Make_Integer_Literal (Loc, Osiz))));
2492
2493            Shift := New_Shift;
2494         end;
2495
2496      --  For the modular integer case, the object to be manipulated is the
2497      --  entire array, so Obj is unchanged. Note that we will reset its type
2498      --  to PAT before returning to the caller.
2499
2500      else
2501         null;
2502      end if;
2503
2504      --  The one remaining step is to modify the shift count for the
2505      --  big-endian case. Consider the following example in a byte:
2506
2507      --     xxxxxxxx  bits of byte
2508      --     vvvvvvvv  bits of value
2509      --     33221100  little-endian numbering
2510      --     00112233  big-endian numbering
2511
2512      --  Here we have the case of 2-bit fields
2513
2514      --  For the little-endian case, we already have the proper shift count
2515      --  set, e.g. for element 2, the shift count is 2*2 = 4.
2516
2517      --  For the big endian case, we have to adjust the shift count, computing
2518      --  it as (N - F) - Shift, where N is the number of bits in an element of
2519      --  the array used to implement the packed array, F is the number of bits
2520      --  in a source array element, and Shift is the count so far computed.
2521
2522      --  We also have to adjust if the storage order is reversed
2523
2524      if Bytes_Big_Endian xor Reverse_Storage_Order (Base_Type (Atyp)) then
2525         Shift :=
2526           Make_Op_Subtract (Loc,
2527             Left_Opnd  => Make_Integer_Literal (Loc, Osiz - Csiz),
2528             Right_Opnd => Shift);
2529      end if;
2530
2531      Set_Parent (Shift, N);
2532      Set_Parent (Obj, N);
2533      Analyze_And_Resolve (Obj,   Otyp,             Suppress => All_Checks);
2534      Analyze_And_Resolve (Shift, Standard_Integer, Suppress => All_Checks);
2535
2536      --  Make sure final type of object is the appropriate packed type
2537
2538      Set_Etype (Obj, Otyp);
2539
2540   end Setup_Inline_Packed_Array_Reference;
2541
2542end Exp_Pakd;
2543