OSDN Git Service

2011-08-02 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch13.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             S E M _ C H 1 3                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, 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
26 with Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Disp; use Exp_Disp;
33 with Exp_Tss;  use Exp_Tss;
34 with Exp_Util; use Exp_Util;
35 with Lib;      use Lib;
36 with Lib.Xref; use Lib.Xref;
37 with Namet;    use Namet;
38 with Nlists;   use Nlists;
39 with Nmake;    use Nmake;
40 with Opt;      use Opt;
41 with Restrict; use Restrict;
42 with Rident;   use Rident;
43 with Rtsfind;  use Rtsfind;
44 with Sem;      use Sem;
45 with Sem_Aux;  use Sem_Aux;
46 with Sem_Ch3;  use Sem_Ch3;
47 with Sem_Ch6;  use Sem_Ch6;
48 with Sem_Ch8;  use Sem_Ch8;
49 with Sem_Eval; use Sem_Eval;
50 with Sem_Res;  use Sem_Res;
51 with Sem_Type; use Sem_Type;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinput;   use Sinput;
55 with Snames;   use Snames;
56 with Stand;    use Stand;
57 with Sinfo;    use Sinfo;
58 with Stringt;  use Stringt;
59 with Targparm; use Targparm;
60 with Ttypes;   use Ttypes;
61 with Tbuild;   use Tbuild;
62 with Urealp;   use Urealp;
63
64 with GNAT.Heap_Sort_G;
65
66 package body Sem_Ch13 is
67
68    SSU : constant Pos := System_Storage_Unit;
69    --  Convenient short hand for commonly used constant
70
71    -----------------------
72    -- Local Subprograms --
73    -----------------------
74
75    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id);
76    --  This routine is called after setting the Esize of type entity Typ.
77    --  The purpose is to deal with the situation where an alignment has been
78    --  inherited from a derived type that is no longer appropriate for the
79    --  new Esize value. In this case, we reset the Alignment to unknown.
80
81    procedure Build_Predicate_Function (Typ : Entity_Id; N : Node_Id);
82    --  If Typ has predicates (indicated by Has_Predicates being set for Typ,
83    --  then either there are pragma Invariant entries on the rep chain for the
84    --  type (note that Predicate aspects are converted to pragma Predicate), or
85    --  there are inherited aspects from a parent type, or ancestor subtypes.
86    --  This procedure builds the spec and body for the Predicate function that
87    --  tests these predicates. N is the freeze node for the type. The spec of
88    --  the function is inserted before the freeze node, and the body of the
89    --  function is inserted after the freeze node.
90
91    procedure Build_Static_Predicate
92      (Typ  : Entity_Id;
93       Expr : Node_Id;
94       Nam  : Name_Id);
95    --  Given a predicated type Typ, where Typ is a discrete static subtype,
96    --  whose predicate expression is Expr, tests if Expr is a static predicate,
97    --  and if so, builds the predicate range list. Nam is the name of the one
98    --  argument to the predicate function. Occurrences of the type name in the
99    --  predicate expression have been replaced by identifier references to this
100    --  name, which is unique, so any identifier with Chars matching Nam must be
101    --  a reference to the type. If the predicate is non-static, this procedure
102    --  returns doing nothing. If the predicate is static, then the predicate
103    --  list is stored in Static_Predicate (Typ), and the Expr is rewritten as
104    --  a canonicalized membership operation.
105
106    function Get_Alignment_Value (Expr : Node_Id) return Uint;
107    --  Given the expression for an alignment value, returns the corresponding
108    --  Uint value. If the value is inappropriate, then error messages are
109    --  posted as required, and a value of No_Uint is returned.
110
111    function Is_Operational_Item (N : Node_Id) return Boolean;
112    --  A specification for a stream attribute is allowed before the full type
113    --  is declared, as explained in AI-00137 and the corrigendum. Attributes
114    --  that do not specify a representation characteristic are operational
115    --  attributes.
116
117    procedure New_Stream_Subprogram
118      (N    : Node_Id;
119       Ent  : Entity_Id;
120       Subp : Entity_Id;
121       Nam  : TSS_Name_Type);
122    --  Create a subprogram renaming of a given stream attribute to the
123    --  designated subprogram and then in the tagged case, provide this as a
124    --  primitive operation, or in the non-tagged case make an appropriate TSS
125    --  entry. This is more properly an expansion activity than just semantics,
126    --  but the presence of user-defined stream functions for limited types is a
127    --  legality check, which is why this takes place here rather than in
128    --  exp_ch13, where it was previously. Nam indicates the name of the TSS
129    --  function to be generated.
130    --
131    --  To avoid elaboration anomalies with freeze nodes, for untagged types
132    --  we generate both a subprogram declaration and a subprogram renaming
133    --  declaration, so that the attribute specification is handled as a
134    --  renaming_as_body. For tagged types, the specification is one of the
135    --  primitive specs.
136
137    generic
138       with procedure Replace_Type_Reference (N : Node_Id);
139    procedure Replace_Type_References_Generic (N : Node_Id; TName : Name_Id);
140    --  This is used to scan an expression for a predicate or invariant aspect
141    --  replacing occurrences of the name TName (the name of the subtype to
142    --  which the aspect applies) with appropriate references to the parameter
143    --  of the predicate function or invariant procedure. The procedure passed
144    --  as a generic parameter does the actual replacement of node N, which is
145    --  either a simple direct reference to TName, or a selected component that
146    --  represents an appropriately qualified occurrence of TName.
147
148    procedure Set_Biased
149      (E      : Entity_Id;
150       N      : Node_Id;
151       Msg    : String;
152       Biased : Boolean := True);
153    --  If Biased is True, sets Has_Biased_Representation flag for E, and
154    --  outputs a warning message at node N if Warn_On_Biased_Representation is
155    --  is True. This warning inserts the string Msg to describe the construct
156    --  causing biasing.
157
158    ----------------------------------------------
159    -- Table for Validate_Unchecked_Conversions --
160    ----------------------------------------------
161
162    --  The following table collects unchecked conversions for validation.
163    --  Entries are made by Validate_Unchecked_Conversion and then the
164    --  call to Validate_Unchecked_Conversions does the actual error
165    --  checking and posting of warnings. The reason for this delayed
166    --  processing is to take advantage of back-annotations of size and
167    --  alignment values performed by the back end.
168
169    --  Note: the reason we store a Source_Ptr value instead of a Node_Id
170    --  is that by the time Validate_Unchecked_Conversions is called, Sprint
171    --  will already have modified all Sloc values if the -gnatD option is set.
172
173    type UC_Entry is record
174       Eloc   : Source_Ptr; -- node used for posting warnings
175       Source : Entity_Id;  -- source type for unchecked conversion
176       Target : Entity_Id;  -- target type for unchecked conversion
177    end record;
178
179    package Unchecked_Conversions is new Table.Table (
180      Table_Component_Type => UC_Entry,
181      Table_Index_Type     => Int,
182      Table_Low_Bound      => 1,
183      Table_Initial        => 50,
184      Table_Increment      => 200,
185      Table_Name           => "Unchecked_Conversions");
186
187    ----------------------------------------
188    -- Table for Validate_Address_Clauses --
189    ----------------------------------------
190
191    --  If an address clause has the form
192
193    --    for X'Address use Expr
194
195    --  where Expr is of the form Y'Address or recursively is a reference
196    --  to a constant of either of these forms, and X and Y are entities of
197    --  objects, then if Y has a smaller alignment than X, that merits a
198    --  warning about possible bad alignment. The following table collects
199    --  address clauses of this kind. We put these in a table so that they
200    --  can be checked after the back end has completed annotation of the
201    --  alignments of objects, since we can catch more cases that way.
202
203    type Address_Clause_Check_Record is record
204       N : Node_Id;
205       --  The address clause
206
207       X : Entity_Id;
208       --  The entity of the object overlaying Y
209
210       Y : Entity_Id;
211       --  The entity of the object being overlaid
212
213       Off : Boolean;
214       --  Whether the address is offset within Y
215    end record;
216
217    package Address_Clause_Checks is new Table.Table (
218      Table_Component_Type => Address_Clause_Check_Record,
219      Table_Index_Type     => Int,
220      Table_Low_Bound      => 1,
221      Table_Initial        => 20,
222      Table_Increment      => 200,
223      Table_Name           => "Address_Clause_Checks");
224
225    -----------------------------------------
226    -- Adjust_Record_For_Reverse_Bit_Order --
227    -----------------------------------------
228
229    procedure Adjust_Record_For_Reverse_Bit_Order (R : Entity_Id) is
230       Comp : Node_Id;
231       CC   : Node_Id;
232
233    begin
234       --  Processing depends on version of Ada
235
236       --  For Ada 95, we just renumber bits within a storage unit. We do the
237       --  same for Ada 83 mode, since we recognize pragma Bit_Order in Ada 83,
238       --  and are free to add this extension.
239
240       if Ada_Version < Ada_2005 then
241          Comp := First_Component_Or_Discriminant (R);
242          while Present (Comp) loop
243             CC := Component_Clause (Comp);
244
245             --  If component clause is present, then deal with the non-default
246             --  bit order case for Ada 95 mode.
247
248             --  We only do this processing for the base type, and in fact that
249             --  is important, since otherwise if there are record subtypes, we
250             --  could reverse the bits once for each subtype, which is wrong.
251
252             if Present (CC)
253               and then Ekind (R) = E_Record_Type
254             then
255                declare
256                   CFB : constant Uint    := Component_Bit_Offset (Comp);
257                   CSZ : constant Uint    := Esize (Comp);
258                   CLC : constant Node_Id := Component_Clause (Comp);
259                   Pos : constant Node_Id := Position (CLC);
260                   FB  : constant Node_Id := First_Bit (CLC);
261
262                   Storage_Unit_Offset : constant Uint :=
263                                           CFB / System_Storage_Unit;
264
265                   Start_Bit : constant Uint :=
266                                 CFB mod System_Storage_Unit;
267
268                begin
269                   --  Cases where field goes over storage unit boundary
270
271                   if Start_Bit + CSZ > System_Storage_Unit then
272
273                      --  Allow multi-byte field but generate warning
274
275                      if Start_Bit mod System_Storage_Unit = 0
276                        and then CSZ mod System_Storage_Unit = 0
277                      then
278                         Error_Msg_N
279                           ("multi-byte field specified with non-standard"
280                            & " Bit_Order?", CLC);
281
282                         if Bytes_Big_Endian then
283                            Error_Msg_N
284                              ("bytes are not reversed "
285                               & "(component is big-endian)?", CLC);
286                         else
287                            Error_Msg_N
288                              ("bytes are not reversed "
289                               & "(component is little-endian)?", CLC);
290                         end if;
291
292                         --  Do not allow non-contiguous field
293
294                      else
295                         Error_Msg_N
296                           ("attempt to specify non-contiguous field "
297                            & "not permitted", CLC);
298                         Error_Msg_N
299                           ("\caused by non-standard Bit_Order "
300                            & "specified", CLC);
301                         Error_Msg_N
302                           ("\consider possibility of using "
303                            & "Ada 2005 mode here", CLC);
304                      end if;
305
306                   --  Case where field fits in one storage unit
307
308                   else
309                      --  Give warning if suspicious component clause
310
311                      if Intval (FB) >= System_Storage_Unit
312                        and then Warn_On_Reverse_Bit_Order
313                      then
314                         Error_Msg_N
315                           ("?Bit_Order clause does not affect " &
316                            "byte ordering", Pos);
317                         Error_Msg_Uint_1 :=
318                           Intval (Pos) + Intval (FB) /
319                           System_Storage_Unit;
320                         Error_Msg_N
321                           ("?position normalized to ^ before bit " &
322                            "order interpreted", Pos);
323                      end if;
324
325                      --  Here is where we fix up the Component_Bit_Offset value
326                      --  to account for the reverse bit order. Some examples of
327                      --  what needs to be done are:
328
329                      --    First_Bit .. Last_Bit     Component_Bit_Offset
330                      --      old          new          old       new
331
332                      --     0 .. 0       7 .. 7         0         7
333                      --     0 .. 1       6 .. 7         0         6
334                      --     0 .. 2       5 .. 7         0         5
335                      --     0 .. 7       0 .. 7         0         4
336
337                      --     1 .. 1       6 .. 6         1         6
338                      --     1 .. 4       3 .. 6         1         3
339                      --     4 .. 7       0 .. 3         4         0
340
341                      --  The rule is that the first bit is is obtained by
342                      --  subtracting the old ending bit from storage_unit - 1.
343
344                      Set_Component_Bit_Offset
345                        (Comp,
346                         (Storage_Unit_Offset * System_Storage_Unit) +
347                           (System_Storage_Unit - 1) -
348                           (Start_Bit + CSZ - 1));
349
350                      Set_Normalized_First_Bit
351                        (Comp,
352                         Component_Bit_Offset (Comp) mod
353                           System_Storage_Unit);
354                   end if;
355                end;
356             end if;
357
358             Next_Component_Or_Discriminant (Comp);
359          end loop;
360
361       --  For Ada 2005, we do machine scalar processing, as fully described In
362       --  AI-133. This involves gathering all components which start at the
363       --  same byte offset and processing them together. Same approach is still
364       --  valid in later versions including Ada 2012.
365
366       else
367          declare
368             Max_Machine_Scalar_Size : constant Uint :=
369                                         UI_From_Int
370                                           (Standard_Long_Long_Integer_Size);
371             --  We use this as the maximum machine scalar size
372
373             Num_CC : Natural;
374             SSU    : constant Uint := UI_From_Int (System_Storage_Unit);
375
376          begin
377             --  This first loop through components does two things. First it
378             --  deals with the case of components with component clauses whose
379             --  length is greater than the maximum machine scalar size (either
380             --  accepting them or rejecting as needed). Second, it counts the
381             --  number of components with component clauses whose length does
382             --  not exceed this maximum for later processing.
383
384             Num_CC := 0;
385             Comp   := First_Component_Or_Discriminant (R);
386             while Present (Comp) loop
387                CC := Component_Clause (Comp);
388
389                if Present (CC) then
390                   declare
391                      Fbit : constant Uint :=
392                               Static_Integer (First_Bit (CC));
393                      Lbit : constant Uint :=
394                               Static_Integer (Last_Bit (CC));
395
396                   begin
397                      --  Case of component with last bit >= max machine scalar
398
399                      if Lbit >= Max_Machine_Scalar_Size then
400
401                         --  This is allowed only if first bit is zero, and
402                         --  last bit + 1 is a multiple of storage unit size.
403
404                         if Fbit = 0 and then (Lbit + 1) mod SSU = 0 then
405
406                            --  This is the case to give a warning if enabled
407
408                            if Warn_On_Reverse_Bit_Order then
409                               Error_Msg_N
410                                 ("multi-byte field specified with "
411                                  & "  non-standard Bit_Order?", CC);
412
413                               if Bytes_Big_Endian then
414                                  Error_Msg_N
415                                    ("\bytes are not reversed "
416                                     & "(component is big-endian)?", CC);
417                               else
418                                  Error_Msg_N
419                                    ("\bytes are not reversed "
420                                     & "(component is little-endian)?", CC);
421                               end if;
422                            end if;
423
424                         --  Give error message for RM 13.4.1(10) violation
425
426                         else
427                            Error_Msg_FE
428                              ("machine scalar rules not followed for&",
429                               First_Bit (CC), Comp);
430
431                            Error_Msg_Uint_1 := Lbit;
432                            Error_Msg_Uint_2 := Max_Machine_Scalar_Size;
433                            Error_Msg_F
434                              ("\last bit (^) exceeds maximum machine "
435                               & "scalar size (^)",
436                               First_Bit (CC));
437
438                            if (Lbit + 1) mod SSU /= 0 then
439                               Error_Msg_Uint_1 := SSU;
440                               Error_Msg_F
441                                 ("\and is not a multiple of Storage_Unit (^) "
442                                  & "('R'M 13.4.1(10))",
443                                  First_Bit (CC));
444
445                            else
446                               Error_Msg_Uint_1 := Fbit;
447                               Error_Msg_F
448                                 ("\and first bit (^) is non-zero "
449                                  & "('R'M 13.4.1(10))",
450                                  First_Bit (CC));
451                            end if;
452                         end if;
453
454                      --  OK case of machine scalar related component clause,
455                      --  For now, just count them.
456
457                      else
458                         Num_CC := Num_CC + 1;
459                      end if;
460                   end;
461                end if;
462
463                Next_Component_Or_Discriminant (Comp);
464             end loop;
465
466             --  We need to sort the component clauses on the basis of the
467             --  Position values in the clause, so we can group clauses with
468             --  the same Position. together to determine the relevant machine
469             --  scalar size.
470
471             Sort_CC : declare
472                Comps : array (0 .. Num_CC) of Entity_Id;
473                --  Array to collect component and discriminant entities. The
474                --  data starts at index 1, the 0'th entry is for the sort
475                --  routine.
476
477                function CP_Lt (Op1, Op2 : Natural) return Boolean;
478                --  Compare routine for Sort
479
480                procedure CP_Move (From : Natural; To : Natural);
481                --  Move routine for Sort
482
483                package Sorting is new GNAT.Heap_Sort_G (CP_Move, CP_Lt);
484
485                Start : Natural;
486                Stop  : Natural;
487                --  Start and stop positions in the component list of the set of
488                --  components with the same starting position (that constitute
489                --  components in a single machine scalar).
490
491                MaxL  : Uint;
492                --  Maximum last bit value of any component in this set
493
494                MSS   : Uint;
495                --  Corresponding machine scalar size
496
497                -----------
498                -- CP_Lt --
499                -----------
500
501                function CP_Lt (Op1, Op2 : Natural) return Boolean is
502                begin
503                   return Position (Component_Clause (Comps (Op1))) <
504                     Position (Component_Clause (Comps (Op2)));
505                end CP_Lt;
506
507                -------------
508                -- CP_Move --
509                -------------
510
511                procedure CP_Move (From : Natural; To : Natural) is
512                begin
513                   Comps (To) := Comps (From);
514                end CP_Move;
515
516                --  Start of processing for Sort_CC
517
518             begin
519                --  Collect the machine scalar relevant component clauses
520
521                Num_CC := 0;
522                Comp   := First_Component_Or_Discriminant (R);
523                while Present (Comp) loop
524                   declare
525                      CC   : constant Node_Id := Component_Clause (Comp);
526
527                   begin
528                      --  Collect only component clauses whose last bit is less
529                      --  than machine scalar size. Any component clause whose
530                      --  last bit exceeds this value does not take part in
531                      --  machine scalar layout considerations. The test for
532                      --  Error_Posted makes sure we exclude component clauses
533                      --  for which we already posted an error.
534
535                      if Present (CC)
536                        and then not Error_Posted (Last_Bit (CC))
537                        and then Static_Integer (Last_Bit (CC)) <
538                                 Max_Machine_Scalar_Size
539                      then
540                         Num_CC := Num_CC + 1;
541                         Comps (Num_CC) := Comp;
542                      end if;
543                   end;
544
545                   Next_Component_Or_Discriminant (Comp);
546                end loop;
547
548                --  Sort by ascending position number
549
550                Sorting.Sort (Num_CC);
551
552                --  We now have all the components whose size does not exceed
553                --  the max machine scalar value, sorted by starting position.
554                --  In this loop we gather groups of clauses starting at the
555                --  same position, to process them in accordance with AI-133.
556
557                Stop := 0;
558                while Stop < Num_CC loop
559                   Start := Stop + 1;
560                   Stop  := Start;
561                   MaxL  :=
562                     Static_Integer
563                       (Last_Bit (Component_Clause (Comps (Start))));
564                   while Stop < Num_CC loop
565                      if Static_Integer
566                           (Position (Component_Clause (Comps (Stop + 1)))) =
567                         Static_Integer
568                           (Position (Component_Clause (Comps (Stop))))
569                      then
570                         Stop := Stop + 1;
571                         MaxL :=
572                           UI_Max
573                             (MaxL,
574                              Static_Integer
575                                (Last_Bit
576                                   (Component_Clause (Comps (Stop)))));
577                      else
578                         exit;
579                      end if;
580                   end loop;
581
582                   --  Now we have a group of component clauses from Start to
583                   --  Stop whose positions are identical, and MaxL is the
584                   --  maximum last bit value of any of these components.
585
586                   --  We need to determine the corresponding machine scalar
587                   --  size. This loop assumes that machine scalar sizes are
588                   --  even, and that each possible machine scalar has twice
589                   --  as many bits as the next smaller one.
590
591                   MSS := Max_Machine_Scalar_Size;
592                   while MSS mod 2 = 0
593                     and then (MSS / 2) >= SSU
594                     and then (MSS / 2) > MaxL
595                   loop
596                      MSS := MSS / 2;
597                   end loop;
598
599                   --  Here is where we fix up the Component_Bit_Offset value
600                   --  to account for the reverse bit order. Some examples of
601                   --  what needs to be done for the case of a machine scalar
602                   --  size of 8 are:
603
604                   --    First_Bit .. Last_Bit     Component_Bit_Offset
605                   --      old          new          old       new
606
607                   --     0 .. 0       7 .. 7         0         7
608                   --     0 .. 1       6 .. 7         0         6
609                   --     0 .. 2       5 .. 7         0         5
610                   --     0 .. 7       0 .. 7         0         4
611
612                   --     1 .. 1       6 .. 6         1         6
613                   --     1 .. 4       3 .. 6         1         3
614                   --     4 .. 7       0 .. 3         4         0
615
616                   --  The rule is that the first bit is obtained by subtracting
617                   --  the old ending bit from machine scalar size - 1.
618
619                   for C in Start .. Stop loop
620                      declare
621                         Comp : constant Entity_Id := Comps (C);
622                         CC   : constant Node_Id   :=
623                                  Component_Clause (Comp);
624                         LB   : constant Uint :=
625                                  Static_Integer (Last_Bit (CC));
626                         NFB  : constant Uint := MSS - Uint_1 - LB;
627                         NLB  : constant Uint := NFB + Esize (Comp) - 1;
628                         Pos  : constant Uint :=
629                                  Static_Integer (Position (CC));
630
631                      begin
632                         if Warn_On_Reverse_Bit_Order then
633                            Error_Msg_Uint_1 := MSS;
634                            Error_Msg_N
635                              ("info: reverse bit order in machine " &
636                               "scalar of length^?", First_Bit (CC));
637                            Error_Msg_Uint_1 := NFB;
638                            Error_Msg_Uint_2 := NLB;
639
640                            if Bytes_Big_Endian then
641                               Error_Msg_NE
642                                 ("?\info: big-endian range for "
643                                  & "component & is ^ .. ^",
644                                  First_Bit (CC), Comp);
645                            else
646                               Error_Msg_NE
647                                 ("?\info: little-endian range "
648                                  & "for component & is ^ .. ^",
649                                  First_Bit (CC), Comp);
650                            end if;
651                         end if;
652
653                         Set_Component_Bit_Offset (Comp, Pos * SSU + NFB);
654                         Set_Normalized_First_Bit (Comp, NFB mod SSU);
655                      end;
656                   end loop;
657                end loop;
658             end Sort_CC;
659          end;
660       end if;
661    end Adjust_Record_For_Reverse_Bit_Order;
662
663    --------------------------------------
664    -- Alignment_Check_For_Esize_Change --
665    --------------------------------------
666
667    procedure Alignment_Check_For_Esize_Change (Typ : Entity_Id) is
668    begin
669       --  If the alignment is known, and not set by a rep clause, and is
670       --  inconsistent with the size being set, then reset it to unknown,
671       --  we assume in this case that the size overrides the inherited
672       --  alignment, and that the alignment must be recomputed.
673
674       if Known_Alignment (Typ)
675         and then not Has_Alignment_Clause (Typ)
676         and then Esize (Typ) mod (Alignment (Typ) * SSU) /= 0
677       then
678          Init_Alignment (Typ);
679       end if;
680    end Alignment_Check_For_Esize_Change;
681
682    -----------------------------------
683    -- Analyze_Aspect_Specifications --
684    -----------------------------------
685
686    procedure Analyze_Aspect_Specifications (N : Node_Id; E : Entity_Id) is
687       Aspect : Node_Id;
688       Aitem  : Node_Id;
689       Ent    : Node_Id;
690
691       L : constant List_Id := Aspect_Specifications (N);
692
693       Ins_Node : Node_Id := N;
694       --  Insert pragmas (except Pre/Post/Invariant/Predicate) after this node
695
696       --  The general processing involves building an attribute definition
697       --  clause or a pragma node that corresponds to the access type. Then
698       --  one of two things happens:
699
700       --  If we are required to delay the evaluation of this aspect to the
701       --  freeze point, we attach the corresponding pragma/attribute definition
702       --  clause to the aspect specification node, which is then placed in the
703       --  Rep Item chain. In this case we mark the entity by setting the flag
704       --  Has_Delayed_Aspects and we evaluate the rep item at the freeze point.
705
706       --  If no delay is required, we just insert the pragma or attribute
707       --  after the declaration, and it will get processed by the normal
708       --  circuit. The From_Aspect_Specification flag is set on the pragma
709       --  or attribute definition node in either case to activate special
710       --  processing (e.g. not traversing the list of homonyms for inline).
711
712       Delay_Required : Boolean;
713       --  Set True if delay is required
714
715    begin
716       pragma Assert (Present (L));
717
718       --  Loop through aspects
719
720       Aspect := First (L);
721       Aspect_Loop : while Present (Aspect) loop
722          declare
723             Loc  : constant Source_Ptr := Sloc (Aspect);
724             Id   : constant Node_Id    := Identifier (Aspect);
725             Expr : constant Node_Id    := Expression (Aspect);
726             Nam  : constant Name_Id    := Chars (Id);
727             A_Id : constant Aspect_Id  := Get_Aspect_Id (Nam);
728             Anod : Node_Id;
729
730             Eloc : Source_Ptr := Sloc (Expr);
731             --  Source location of expression, modified when we split PPC's
732
733             procedure Check_False_Aspect_For_Derived_Type;
734             --  This procedure checks for the case of a false aspect for a
735             --  derived type, which improperly tries to cancel an aspect
736             --  inherited from the parent;
737
738             -----------------------------------------
739             -- Check_False_Aspect_For_Derived_Type --
740             -----------------------------------------
741
742             procedure Check_False_Aspect_For_Derived_Type is
743             begin
744                --  We are only checking derived types
745
746                if not Is_Derived_Type (E) then
747                   return;
748                end if;
749
750                case A_Id is
751                   when Aspect_Atomic | Aspect_Shared =>
752                      if not Is_Atomic (E) then
753                         return;
754                      end if;
755
756                   when Aspect_Atomic_Components =>
757                      if not Has_Atomic_Components (E) then
758                         return;
759                      end if;
760
761                   when Aspect_Discard_Names =>
762                      if not Discard_Names (E) then
763                         return;
764                      end if;
765
766                   when Aspect_Pack =>
767                      if not Is_Packed (E) then
768                         return;
769                      end if;
770
771                   when Aspect_Unchecked_Union =>
772                      if not Is_Unchecked_Union (E) then
773                         return;
774                      end if;
775
776                   when Aspect_Volatile =>
777                      if not Is_Volatile (E) then
778                         return;
779                      end if;
780
781                   when Aspect_Volatile_Components =>
782                      if not Has_Volatile_Components (E) then
783                         return;
784                      end if;
785
786                   when others =>
787                      return;
788                end case;
789
790                --  Fall through means we are canceling an inherited aspect
791
792                Error_Msg_Name_1 := Nam;
793                Error_Msg_NE
794                  ("derived type& inherits aspect%, cannot cancel", Expr, E);
795             end Check_False_Aspect_For_Derived_Type;
796
797          --  Start of processing for Aspect_Loop
798
799          begin
800             --  Skip aspect if already analyzed (not clear if this is needed)
801
802             if Analyzed (Aspect) then
803                goto Continue;
804             end if;
805
806             Set_Analyzed (Aspect);
807             Set_Entity (Aspect, E);
808             Ent := New_Occurrence_Of (E, Sloc (Id));
809
810             --  Check for duplicate aspect. Note that the Comes_From_Source
811             --  test allows duplicate Pre/Post's that we generate internally
812             --  to escape being flagged here.
813
814             Anod := First (L);
815             while Anod /= Aspect loop
816                if Same_Aspect (A_Id, Get_Aspect_Id (Chars (Identifier (Anod))))
817                  and then Comes_From_Source (Aspect)
818                then
819                   Error_Msg_Name_1 := Nam;
820                   Error_Msg_Sloc := Sloc (Anod);
821
822                   --  Case of same aspect specified twice
823
824                   if Class_Present (Anod) = Class_Present (Aspect) then
825                      if not Class_Present (Anod) then
826                         Error_Msg_NE
827                           ("aspect% for & previously given#",
828                            Id, E);
829                      else
830                         Error_Msg_NE
831                           ("aspect `%''Class` for & previously given#",
832                            Id, E);
833                      end if;
834
835                   --  Case of Pre and Pre'Class both specified
836
837                   elsif Nam = Name_Pre then
838                      if Class_Present (Aspect) then
839                         Error_Msg_NE
840                           ("aspect `Pre''Class` for & is not allowed here",
841                            Id, E);
842                         Error_Msg_NE
843                           ("\since aspect `Pre` previously given#",
844                            Id, E);
845
846                      else
847                         Error_Msg_NE
848                           ("aspect `Pre` for & is not allowed here",
849                            Id, E);
850                         Error_Msg_NE
851                           ("\since aspect `Pre''Class` previously given#",
852                            Id, E);
853                      end if;
854                   end if;
855
856                   goto Continue;
857                end if;
858
859                Next (Anod);
860             end loop;
861
862             --  Copy expression for later processing by the procedures
863             --  Check_Aspect_At_[Freeze_Point | End_Of_Declarations]
864
865             Set_Entity (Id, New_Copy_Tree (Expr));
866
867             --  Processing based on specific aspect
868
869             case A_Id is
870
871                --  No_Aspect should be impossible
872
873                when No_Aspect =>
874                   raise Program_Error;
875
876                --  Aspects taking an optional boolean argument. For all of
877                --  these we just create a matching pragma and insert it, if
878                --  the expression is missing or set to True. If the expression
879                --  is False, we can ignore the aspect with the exception that
880                --  in the case of a derived type, we must check for an illegal
881                --  attempt to cancel an inherited aspect.
882
883                when Boolean_Aspects =>
884                   Set_Is_Boolean_Aspect (Aspect);
885
886                   if Present (Expr)
887                     and then Is_False (Static_Boolean (Expr))
888                   then
889                      Check_False_Aspect_For_Derived_Type;
890                      goto Continue;
891                   end if;
892
893                   --  If True, build corresponding pragma node
894
895                   Aitem :=
896                     Make_Pragma (Loc,
897                       Pragma_Argument_Associations => New_List (Ent),
898                       Pragma_Identifier            =>
899                         Make_Identifier (Sloc (Id), Chars (Id)));
900
901                   --  Never need to delay for boolean aspects
902
903                   Delay_Required := False;
904
905                --  Library unit aspects. These are boolean aspects, but we
906                --  have to do special things with the insertion, since the
907                --  pragma belongs inside the declarations of a package.
908
909                when Library_Unit_Aspects =>
910                   if Present (Expr)
911                     and then Is_False (Static_Boolean (Expr))
912                   then
913                      goto Continue;
914                   end if;
915
916                   --  Build corresponding pragma node
917
918                   Aitem :=
919                     Make_Pragma (Loc,
920                       Pragma_Argument_Associations => New_List (Ent),
921                       Pragma_Identifier            =>
922                         Make_Identifier (Sloc (Id), Chars (Id)));
923
924                   --  This requires special handling in the case of a package
925                   --  declaration, the pragma needs to be inserted in the list
926                   --  of declarations for the associated package. There is no
927                   --  issue of visibility delay for these aspects.
928
929                   if Nkind (N) = N_Package_Declaration then
930                      if Nkind (Parent (N)) /= N_Compilation_Unit then
931                         Error_Msg_N
932                           ("incorrect context for library unit aspect&", Id);
933                      else
934                         Prepend
935                           (Aitem, Visible_Declarations (Specification (N)));
936                      end if;
937
938                      goto Continue;
939                   end if;
940
941                   --  If not package declaration, no delay is required
942
943                   Delay_Required := False;
944
945                --  Aspects corresponding to attribute definition clauses
946
947                when Aspect_Address        |
948                     Aspect_Alignment      |
949                     Aspect_Bit_Order      |
950                     Aspect_Component_Size |
951                     Aspect_External_Tag   |
952                     Aspect_Input          |
953                     Aspect_Machine_Radix  |
954                     Aspect_Object_Size    |
955                     Aspect_Output         |
956                     Aspect_Read           |
957                     Aspect_Size           |
958                     Aspect_Storage_Pool   |
959                     Aspect_Storage_Size   |
960                     Aspect_Stream_Size    |
961                     Aspect_Value_Size     |
962                     Aspect_Write          =>
963
964                   --  Construct the attribute definition clause
965
966                   Aitem :=
967                     Make_Attribute_Definition_Clause (Loc,
968                       Name       => Ent,
969                       Chars      => Chars (Id),
970                       Expression => Relocate_Node (Expr));
971
972                   --  A delay is required except in the common case where
973                   --  the expression is a literal, in which case it is fine
974                   --  to take care of it right away.
975
976                   if Nkind_In (Expr, N_Integer_Literal, N_String_Literal) then
977                      Delay_Required := False;
978                   else
979                      Delay_Required := True;
980                      Set_Is_Delayed_Aspect (Aspect);
981                   end if;
982
983                --  Aspects corresponding to pragmas with two arguments, where
984                --  the first argument is a local name referring to the entity,
985                --  and the second argument is the aspect definition expression
986                --  which is an expression which must be delayed and analyzed.
987
988                when Aspect_Default_Component_Value |
989                     Aspect_Default_Value           =>
990
991                   --  Construct the pragma
992
993                   Aitem :=
994                     Make_Pragma (Loc,
995                       Pragma_Argument_Associations => New_List (
996                         New_Occurrence_Of (E, Loc),
997                         Relocate_Node (Expr)),
998                       Pragma_Identifier            =>
999                         Make_Identifier (Sloc (Id), Chars (Id)));
1000
1001                   --  These aspects do require delaying
1002
1003                   Delay_Required := True;
1004                   Set_Is_Delayed_Aspect (Aspect);
1005
1006                --  Aspects corresponding to pragmas with two arguments, where
1007                --  the first argument is a local name referring to the entity,
1008                --  and the second argument is the aspect definition expression
1009                --  which is an expression that does not get analyzed.
1010
1011                when Aspect_Suppress   |
1012                     Aspect_Unsuppress =>
1013
1014                   --  Construct the pragma
1015
1016                   Aitem :=
1017                     Make_Pragma (Loc,
1018                       Pragma_Argument_Associations => New_List (
1019                         New_Occurrence_Of (E, Loc),
1020                         Relocate_Node (Expr)),
1021                       Pragma_Identifier            =>
1022                         Make_Identifier (Sloc (Id), Chars (Id)));
1023
1024                   --  We don't have to play the delay game here, since the only
1025                   --  values are check names which don't get analyzed anyway.
1026
1027                   Delay_Required := False;
1028
1029                --  Aspects corresponding to pragmas with two arguments, where
1030                --  the second argument is a local name referring to the entity,
1031                --  and the first argument is the aspect definition expression.
1032
1033                when Aspect_Warnings =>
1034
1035                   --  Construct the pragma
1036
1037                   Aitem :=
1038                     Make_Pragma (Loc,
1039                       Pragma_Argument_Associations => New_List (
1040                         Relocate_Node (Expr),
1041                         New_Occurrence_Of (E, Loc)),
1042                       Pragma_Identifier            =>
1043                         Make_Identifier (Sloc (Id), Chars (Id)),
1044                       Class_Present                => Class_Present (Aspect));
1045
1046                   --  We don't have to play the delay game here, since the only
1047                   --  values are ON/OFF which don't get analyzed anyway.
1048
1049                   Delay_Required := False;
1050
1051                --  Aspects Pre/Post generate Precondition/Postcondition pragmas
1052                --  with a first argument that is the expression, and a second
1053                --  argument that is an informative message if the test fails.
1054                --  This is inserted right after the declaration, to get the
1055                --  required pragma placement. The processing for the pragmas
1056                --  takes care of the required delay.
1057
1058                when Pre_Post_Aspects => declare
1059                   Pname : Name_Id;
1060
1061                begin
1062                   if A_Id = Aspect_Pre or else A_Id = Aspect_Precondition then
1063                      Pname := Name_Precondition;
1064                   else
1065                      Pname := Name_Postcondition;
1066                   end if;
1067
1068                   --  If the expressions is of the form A and then B, then
1069                   --  we generate separate Pre/Post aspects for the separate
1070                   --  clauses. Since we allow multiple pragmas, there is no
1071                   --  problem in allowing multiple Pre/Post aspects internally.
1072
1073                   --  We do not do this for Pre'Class, since we have to put
1074                   --  these conditions together in a complex OR expression
1075
1076                   if Pname = Name_Postcondition
1077                     or else not Class_Present (Aspect)
1078                   then
1079                      while Nkind (Expr) = N_And_Then loop
1080                         Insert_After (Aspect,
1081                           Make_Aspect_Specification (Sloc (Right_Opnd (Expr)),
1082                             Identifier    => Identifier (Aspect),
1083                             Expression    => Relocate_Node (Right_Opnd (Expr)),
1084                             Class_Present => Class_Present (Aspect),
1085                             Split_PPC     => True));
1086                         Rewrite (Expr, Relocate_Node (Left_Opnd (Expr)));
1087                         Eloc := Sloc (Expr);
1088                      end loop;
1089                   end if;
1090
1091                   --  Build the precondition/postcondition pragma
1092
1093                   Aitem :=
1094                     Make_Pragma (Loc,
1095                       Pragma_Identifier            =>
1096                         Make_Identifier (Sloc (Id), Pname),
1097                       Class_Present                => Class_Present (Aspect),
1098                       Split_PPC                    => Split_PPC (Aspect),
1099                       Pragma_Argument_Associations => New_List (
1100                         Make_Pragma_Argument_Association (Eloc,
1101                           Chars      => Name_Check,
1102                           Expression => Relocate_Node (Expr))));
1103
1104                   --  Add message unless exception messages are suppressed
1105
1106                   if not Opt.Exception_Locations_Suppressed then
1107                      Append_To (Pragma_Argument_Associations (Aitem),
1108                        Make_Pragma_Argument_Association (Eloc,
1109                          Chars     => Name_Message,
1110                          Expression =>
1111                            Make_String_Literal (Eloc,
1112                              Strval => "failed "
1113                                        & Get_Name_String (Pname)
1114                                        & " from "
1115                                        & Build_Location_String (Eloc))));
1116                   end if;
1117
1118                   Set_From_Aspect_Specification (Aitem, True);
1119                   Set_Is_Delayed_Aspect (Aspect);
1120
1121                   --  For Pre/Post cases, insert immediately after the entity
1122                   --  declaration, since that is the required pragma placement.
1123                   --  Note that for these aspects, we do not have to worry
1124                   --  about delay issues, since the pragmas themselves deal
1125                   --  with delay of visibility for the expression analysis.
1126
1127                   --  If the entity is a library-level subprogram, the pre/
1128                   --  postconditions must be treated as late pragmas.
1129
1130                   if Nkind (Parent (N)) = N_Compilation_Unit then
1131                      Add_Global_Declaration (Aitem);
1132                   else
1133                      Insert_After (N, Aitem);
1134                   end if;
1135
1136                   goto Continue;
1137                end;
1138
1139                --  Invariant aspects generate a corresponding pragma with a
1140                --  first argument that is the entity, a second argument that is
1141                --  the expression and a third argument that is an appropriate
1142                --  message. This is inserted right after the declaration, to
1143                --  get the required pragma placement. The pragma processing
1144                --  takes care of the required delay.
1145
1146                when Aspect_Invariant      |
1147                     Aspect_Type_Invariant =>
1148
1149                   --  Construct the pragma
1150
1151                   Aitem :=
1152                     Make_Pragma (Loc,
1153                       Pragma_Argument_Associations =>
1154                         New_List (Ent, Relocate_Node (Expr)),
1155                       Class_Present                => Class_Present (Aspect),
1156                       Pragma_Identifier            =>
1157                         Make_Identifier (Sloc (Id), Name_Invariant));
1158
1159                   --  Add message unless exception messages are suppressed
1160
1161                   if not Opt.Exception_Locations_Suppressed then
1162                      Append_To (Pragma_Argument_Associations (Aitem),
1163                        Make_Pragma_Argument_Association (Eloc,
1164                          Chars      => Name_Message,
1165                          Expression =>
1166                            Make_String_Literal (Eloc,
1167                              Strval => "failed invariant from "
1168                                        & Build_Location_String (Eloc))));
1169                   end if;
1170
1171                   Set_From_Aspect_Specification (Aitem, True);
1172                   Set_Is_Delayed_Aspect (Aspect);
1173
1174                   --  For Invariant case, insert immediately after the entity
1175                   --  declaration. We do not have to worry about delay issues
1176                   --  since the pragma processing takes care of this.
1177
1178                   Insert_After (N, Aitem);
1179                   goto Continue;
1180
1181                --  Predicate aspects generate a corresponding pragma with a
1182                --  first argument that is the entity, and the second argument
1183                --  is the expression.
1184
1185                when Aspect_Dynamic_Predicate |
1186                     Aspect_Predicate         |
1187                     Aspect_Static_Predicate  =>
1188
1189                   --  Construct the pragma (always a pragma Predicate, with
1190                   --  flags recording whether
1191
1192                   Aitem :=
1193                     Make_Pragma (Loc,
1194                       Pragma_Argument_Associations =>
1195                         New_List (Ent, Relocate_Node (Expr)),
1196                       Class_Present                => Class_Present (Aspect),
1197                       Pragma_Identifier            =>
1198                         Make_Identifier (Sloc (Id), Name_Predicate));
1199
1200                   Set_From_Aspect_Specification (Aitem, True);
1201
1202                   --  Set special flags for dynamic/static cases
1203
1204                   if A_Id = Aspect_Dynamic_Predicate then
1205                      Set_From_Dynamic_Predicate (Aitem);
1206                   elsif A_Id = Aspect_Static_Predicate then
1207                      Set_From_Static_Predicate (Aitem);
1208                   end if;
1209
1210                   --  Make sure we have a freeze node (it might otherwise be
1211                   --  missing in cases like subtype X is Y, and we would not
1212                   --  have a place to build the predicate function).
1213
1214                   Set_Has_Predicates (E);
1215                   Ensure_Freeze_Node (E);
1216                   Set_Is_Delayed_Aspect (Aspect);
1217                   Delay_Required := True;
1218             end case;
1219
1220             Set_From_Aspect_Specification (Aitem, True);
1221
1222             --  If a delay is required, we delay the freeze (not much point in
1223             --  delaying the aspect if we don't delay the freeze!). The pragma
1224             --  or clause is then attached to the aspect specification which
1225             --  is placed in the rep item list.
1226
1227             if Delay_Required then
1228                Ensure_Freeze_Node (E);
1229                Set_Is_Delayed_Aspect (Aitem);
1230                Set_Has_Delayed_Aspects (E);
1231                Set_Aspect_Rep_Item (Aspect, Aitem);
1232                Record_Rep_Item (E, Aspect);
1233
1234             --  If no delay required, insert the pragma/clause in the tree
1235
1236             else
1237                --  If this is a compilation unit, we will put the pragma in
1238                --  the Pragmas_After list of the N_Compilation_Unit_Aux node.
1239
1240                if Nkind (Parent (Ins_Node)) = N_Compilation_Unit then
1241                   declare
1242                      Aux : constant Node_Id :=
1243                              Aux_Decls_Node (Parent (Ins_Node));
1244
1245                   begin
1246                      pragma Assert (Nkind (Aux) = N_Compilation_Unit_Aux);
1247
1248                      if No (Pragmas_After (Aux)) then
1249                         Set_Pragmas_After (Aux, Empty_List);
1250                      end if;
1251
1252                      --  For Pre_Post put at start of list, otherwise at end
1253
1254                      if A_Id in Pre_Post_Aspects then
1255                         Prepend (Aitem, Pragmas_After (Aux));
1256                      else
1257                         Append (Aitem, Pragmas_After (Aux));
1258                      end if;
1259                   end;
1260
1261                --  Here if not compilation unit case
1262
1263                else
1264                   --  For Pre/Post cases, insert immediately after the entity
1265                   --  declaration, since that is the required pragma placement.
1266
1267                   if A_Id in Pre_Post_Aspects then
1268                      Insert_After (N, Aitem);
1269
1270                   --  For all other cases, insert in sequence
1271
1272                   else
1273                      Insert_After (Ins_Node, Aitem);
1274                      Ins_Node := Aitem;
1275                   end if;
1276                end if;
1277             end if;
1278          end;
1279
1280          <<Continue>>
1281             Next (Aspect);
1282       end loop Aspect_Loop;
1283    end Analyze_Aspect_Specifications;
1284
1285    -----------------------
1286    -- Analyze_At_Clause --
1287    -----------------------
1288
1289    --  An at clause is replaced by the corresponding Address attribute
1290    --  definition clause that is the preferred approach in Ada 95.
1291
1292    procedure Analyze_At_Clause (N : Node_Id) is
1293       CS : constant Boolean := Comes_From_Source (N);
1294
1295    begin
1296       --  This is an obsolescent feature
1297
1298       Check_Restriction (No_Obsolescent_Features, N);
1299
1300       if Warn_On_Obsolescent_Feature then
1301          Error_Msg_N
1302            ("at clause is an obsolescent feature (RM J.7(2))?", N);
1303          Error_Msg_N
1304            ("\use address attribute definition clause instead?", N);
1305       end if;
1306
1307       --  Rewrite as address clause
1308
1309       Rewrite (N,
1310         Make_Attribute_Definition_Clause (Sloc (N),
1311           Name  => Identifier (N),
1312           Chars => Name_Address,
1313           Expression => Expression (N)));
1314
1315       --  We preserve Comes_From_Source, since logically the clause still
1316       --  comes from the source program even though it is changed in form.
1317
1318       Set_Comes_From_Source (N, CS);
1319
1320       --  Analyze rewritten clause
1321
1322       Analyze_Attribute_Definition_Clause (N);
1323    end Analyze_At_Clause;
1324
1325    -----------------------------------------
1326    -- Analyze_Attribute_Definition_Clause --
1327    -----------------------------------------
1328
1329    procedure Analyze_Attribute_Definition_Clause (N : Node_Id) is
1330       Loc   : constant Source_Ptr   := Sloc (N);
1331       Nam   : constant Node_Id      := Name (N);
1332       Attr  : constant Name_Id      := Chars (N);
1333       Expr  : constant Node_Id      := Expression (N);
1334       Id    : constant Attribute_Id := Get_Attribute_Id (Attr);
1335       Ent   : Entity_Id;
1336       U_Ent : Entity_Id;
1337
1338       FOnly : Boolean := False;
1339       --  Reset to True for subtype specific attribute (Alignment, Size)
1340       --  and for stream attributes, i.e. those cases where in the call
1341       --  to Rep_Item_Too_Late, FOnly is set True so that only the freezing
1342       --  rules are checked. Note that the case of stream attributes is not
1343       --  clear from the RM, but see AI95-00137. Also, the RM seems to
1344       --  disallow Storage_Size for derived task types, but that is also
1345       --  clearly unintentional.
1346
1347       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type);
1348       --  Common processing for 'Read, 'Write, 'Input and 'Output attribute
1349       --  definition clauses.
1350
1351       function Duplicate_Clause return Boolean;
1352       --  This routine checks if the aspect for U_Ent being given by attribute
1353       --  definition clause N is for an aspect that has already been specified,
1354       --  and if so gives an error message. If there is a duplicate, True is
1355       --  returned, otherwise if there is no error, False is returned.
1356
1357       -----------------------------------
1358       -- Analyze_Stream_TSS_Definition --
1359       -----------------------------------
1360
1361       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type) is
1362          Subp : Entity_Id := Empty;
1363          I    : Interp_Index;
1364          It   : Interp;
1365          Pnam : Entity_Id;
1366
1367          Is_Read : constant Boolean := (TSS_Nam = TSS_Stream_Read);
1368
1369          function Has_Good_Profile (Subp : Entity_Id) return Boolean;
1370          --  Return true if the entity is a subprogram with an appropriate
1371          --  profile for the attribute being defined.
1372
1373          ----------------------
1374          -- Has_Good_Profile --
1375          ----------------------
1376
1377          function Has_Good_Profile (Subp : Entity_Id) return Boolean is
1378             F              : Entity_Id;
1379             Is_Function    : constant Boolean := (TSS_Nam = TSS_Stream_Input);
1380             Expected_Ekind : constant array (Boolean) of Entity_Kind :=
1381                                (False => E_Procedure, True => E_Function);
1382             Typ            : Entity_Id;
1383
1384          begin
1385             if Ekind (Subp) /= Expected_Ekind (Is_Function) then
1386                return False;
1387             end if;
1388
1389             F := First_Formal (Subp);
1390
1391             if No (F)
1392               or else Ekind (Etype (F)) /= E_Anonymous_Access_Type
1393               or else Designated_Type (Etype (F)) /=
1394                                Class_Wide_Type (RTE (RE_Root_Stream_Type))
1395             then
1396                return False;
1397             end if;
1398
1399             if not Is_Function then
1400                Next_Formal (F);
1401
1402                declare
1403                   Expected_Mode : constant array (Boolean) of Entity_Kind :=
1404                                     (False => E_In_Parameter,
1405                                      True  => E_Out_Parameter);
1406                begin
1407                   if Parameter_Mode (F) /= Expected_Mode (Is_Read) then
1408                      return False;
1409                   end if;
1410                end;
1411
1412                Typ := Etype (F);
1413
1414             else
1415                Typ := Etype (Subp);
1416             end if;
1417
1418             return Base_Type (Typ) = Base_Type (Ent)
1419               and then No (Next_Formal (F));
1420          end Has_Good_Profile;
1421
1422       --  Start of processing for Analyze_Stream_TSS_Definition
1423
1424       begin
1425          FOnly := True;
1426
1427          if not Is_Type (U_Ent) then
1428             Error_Msg_N ("local name must be a subtype", Nam);
1429             return;
1430          end if;
1431
1432          Pnam := TSS (Base_Type (U_Ent), TSS_Nam);
1433
1434          --  If Pnam is present, it can be either inherited from an ancestor
1435          --  type (in which case it is legal to redefine it for this type), or
1436          --  be a previous definition of the attribute for the same type (in
1437          --  which case it is illegal).
1438
1439          --  In the first case, it will have been analyzed already, and we
1440          --  can check that its profile does not match the expected profile
1441          --  for a stream attribute of U_Ent. In the second case, either Pnam
1442          --  has been analyzed (and has the expected profile), or it has not
1443          --  been analyzed yet (case of a type that has not been frozen yet
1444          --  and for which the stream attribute has been set using Set_TSS).
1445
1446          if Present (Pnam)
1447            and then (No (First_Entity (Pnam)) or else Has_Good_Profile (Pnam))
1448          then
1449             Error_Msg_Sloc := Sloc (Pnam);
1450             Error_Msg_Name_1 := Attr;
1451             Error_Msg_N ("% attribute already defined #", Nam);
1452             return;
1453          end if;
1454
1455          Analyze (Expr);
1456
1457          if Is_Entity_Name (Expr) then
1458             if not Is_Overloaded (Expr) then
1459                if Has_Good_Profile (Entity (Expr)) then
1460                   Subp := Entity (Expr);
1461                end if;
1462
1463             else
1464                Get_First_Interp (Expr, I, It);
1465                while Present (It.Nam) loop
1466                   if Has_Good_Profile (It.Nam) then
1467                      Subp := It.Nam;
1468                      exit;
1469                   end if;
1470
1471                   Get_Next_Interp (I, It);
1472                end loop;
1473             end if;
1474          end if;
1475
1476          if Present (Subp) then
1477             if Is_Abstract_Subprogram (Subp) then
1478                Error_Msg_N ("stream subprogram must not be abstract", Expr);
1479                return;
1480             end if;
1481
1482             Set_Entity (Expr, Subp);
1483             Set_Etype (Expr, Etype (Subp));
1484
1485             New_Stream_Subprogram (N, U_Ent, Subp, TSS_Nam);
1486
1487          else
1488             Error_Msg_Name_1 := Attr;
1489             Error_Msg_N ("incorrect expression for% attribute", Expr);
1490          end if;
1491       end Analyze_Stream_TSS_Definition;
1492
1493       ----------------------
1494       -- Duplicate_Clause --
1495       ----------------------
1496
1497       function Duplicate_Clause return Boolean is
1498          A : Node_Id;
1499
1500       begin
1501          --  Nothing to do if this attribute definition clause comes from
1502          --  an aspect specification, since we could not be duplicating an
1503          --  explicit clause, and we dealt with the case of duplicated aspects
1504          --  in Analyze_Aspect_Specifications.
1505
1506          if From_Aspect_Specification (N) then
1507             return False;
1508          end if;
1509
1510          --  Otherwise current clause may duplicate previous clause or a
1511          --  previously given aspect specification for the same aspect.
1512
1513          A := Get_Rep_Item_For_Entity (U_Ent, Chars (N));
1514
1515          if Present (A) then
1516             if Entity (A) = U_Ent then
1517                Error_Msg_Name_1 := Chars (N);
1518                Error_Msg_Sloc := Sloc (A);
1519                Error_Msg_NE ("aspect% for & previously given#", N, U_Ent);
1520                return True;
1521             end if;
1522          end if;
1523
1524          return False;
1525       end Duplicate_Clause;
1526
1527    --  Start of processing for Analyze_Attribute_Definition_Clause
1528
1529    begin
1530       --  Process Ignore_Rep_Clauses option
1531
1532       if Ignore_Rep_Clauses then
1533          case Id is
1534
1535             --  The following should be ignored. They do not affect legality
1536             --  and may be target dependent. The basic idea of -gnatI is to
1537             --  ignore any rep clauses that may be target dependent but do not
1538             --  affect legality (except possibly to be rejected because they
1539             --  are incompatible with the compilation target).
1540
1541             when Attribute_Alignment      |
1542                  Attribute_Bit_Order      |
1543                  Attribute_Component_Size |
1544                  Attribute_Machine_Radix  |
1545                  Attribute_Object_Size    |
1546                  Attribute_Size           |
1547                  Attribute_Small          |
1548                  Attribute_Stream_Size    |
1549                  Attribute_Value_Size     =>
1550
1551                Rewrite (N, Make_Null_Statement (Sloc (N)));
1552                return;
1553
1554             --  The following should not be ignored, because in the first place
1555             --  they are reasonably portable, and should not cause problems in
1556             --  compiling code from another target, and also they do affect
1557             --  legality, e.g. failing to provide a stream attribute for a
1558             --  type may make a program illegal.
1559
1560             when Attribute_External_Tag   |
1561                  Attribute_Input          |
1562                  Attribute_Output         |
1563                  Attribute_Read           |
1564                  Attribute_Storage_Pool   |
1565                  Attribute_Storage_Size   |
1566                  Attribute_Write          =>
1567                null;
1568
1569             --  Other cases are errors ("attribute& cannot be set with
1570             --  definition clause"), which will be caught below.
1571
1572             when others =>
1573                null;
1574          end case;
1575       end if;
1576
1577       Analyze (Nam);
1578       Ent := Entity (Nam);
1579
1580       if Rep_Item_Too_Early (Ent, N) then
1581          return;
1582       end if;
1583
1584       --  Rep clause applies to full view of incomplete type or private type if
1585       --  we have one (if not, this is a premature use of the type). However,
1586       --  certain semantic checks need to be done on the specified entity (i.e.
1587       --  the private view), so we save it in Ent.
1588
1589       if Is_Private_Type (Ent)
1590         and then Is_Derived_Type (Ent)
1591         and then not Is_Tagged_Type (Ent)
1592         and then No (Full_View (Ent))
1593       then
1594          --  If this is a private type whose completion is a derivation from
1595          --  another private type, there is no full view, and the attribute
1596          --  belongs to the type itself, not its underlying parent.
1597
1598          U_Ent := Ent;
1599
1600       elsif Ekind (Ent) = E_Incomplete_Type then
1601
1602          --  The attribute applies to the full view, set the entity of the
1603          --  attribute definition accordingly.
1604
1605          Ent := Underlying_Type (Ent);
1606          U_Ent := Ent;
1607          Set_Entity (Nam, Ent);
1608
1609       else
1610          U_Ent := Underlying_Type (Ent);
1611       end if;
1612
1613       --  Complete other routine error checks
1614
1615       if Etype (Nam) = Any_Type then
1616          return;
1617
1618       elsif Scope (Ent) /= Current_Scope then
1619          Error_Msg_N ("entity must be declared in this scope", Nam);
1620          return;
1621
1622       elsif No (U_Ent) then
1623          U_Ent := Ent;
1624
1625       elsif Is_Type (U_Ent)
1626         and then not Is_First_Subtype (U_Ent)
1627         and then Id /= Attribute_Object_Size
1628         and then Id /= Attribute_Value_Size
1629         and then not From_At_Mod (N)
1630       then
1631          Error_Msg_N ("cannot specify attribute for subtype", Nam);
1632          return;
1633       end if;
1634
1635       Set_Entity (N, U_Ent);
1636
1637       --  Switch on particular attribute
1638
1639       case Id is
1640
1641          -------------
1642          -- Address --
1643          -------------
1644
1645          --  Address attribute definition clause
1646
1647          when Attribute_Address => Address : begin
1648
1649             --  A little error check, catch for X'Address use X'Address;
1650
1651             if Nkind (Nam) = N_Identifier
1652               and then Nkind (Expr) = N_Attribute_Reference
1653               and then Attribute_Name (Expr) = Name_Address
1654               and then Nkind (Prefix (Expr)) = N_Identifier
1655               and then Chars (Nam) = Chars (Prefix (Expr))
1656             then
1657                Error_Msg_NE
1658                  ("address for & is self-referencing", Prefix (Expr), Ent);
1659                return;
1660             end if;
1661
1662             --  Not that special case, carry on with analysis of expression
1663
1664             Analyze_And_Resolve (Expr, RTE (RE_Address));
1665
1666             --  Even when ignoring rep clauses we need to indicate that the
1667             --  entity has an address clause and thus it is legal to declare
1668             --  it imported.
1669
1670             if Ignore_Rep_Clauses then
1671                if Ekind_In (U_Ent, E_Variable, E_Constant) then
1672                   Record_Rep_Item (U_Ent, N);
1673                end if;
1674
1675                return;
1676             end if;
1677
1678             if Duplicate_Clause then
1679                null;
1680
1681             --  Case of address clause for subprogram
1682
1683             elsif Is_Subprogram (U_Ent) then
1684                if Has_Homonym (U_Ent) then
1685                   Error_Msg_N
1686                     ("address clause cannot be given " &
1687                      "for overloaded subprogram",
1688                      Nam);
1689                   return;
1690                end if;
1691
1692                --  For subprograms, all address clauses are permitted, and we
1693                --  mark the subprogram as having a deferred freeze so that Gigi
1694                --  will not elaborate it too soon.
1695
1696                --  Above needs more comments, what is too soon about???
1697
1698                Set_Has_Delayed_Freeze (U_Ent);
1699
1700             --  Case of address clause for entry
1701
1702             elsif Ekind (U_Ent) = E_Entry then
1703                if Nkind (Parent (N)) = N_Task_Body then
1704                   Error_Msg_N
1705                     ("entry address must be specified in task spec", Nam);
1706                   return;
1707                end if;
1708
1709                --  For entries, we require a constant address
1710
1711                Check_Constant_Address_Clause (Expr, U_Ent);
1712
1713                --  Special checks for task types
1714
1715                if Is_Task_Type (Scope (U_Ent))
1716                  and then Comes_From_Source (Scope (U_Ent))
1717                then
1718                   Error_Msg_N
1719                     ("?entry address declared for entry in task type", N);
1720                   Error_Msg_N
1721                     ("\?only one task can be declared of this type", N);
1722                end if;
1723
1724                --  Entry address clauses are obsolescent
1725
1726                Check_Restriction (No_Obsolescent_Features, N);
1727
1728                if Warn_On_Obsolescent_Feature then
1729                   Error_Msg_N
1730                     ("attaching interrupt to task entry is an " &
1731                      "obsolescent feature (RM J.7.1)?", N);
1732                   Error_Msg_N
1733                     ("\use interrupt procedure instead?", N);
1734                end if;
1735
1736             --  Case of an address clause for a controlled object which we
1737             --  consider to be erroneous.
1738
1739             elsif Is_Controlled (Etype (U_Ent))
1740               or else Has_Controlled_Component (Etype (U_Ent))
1741             then
1742                Error_Msg_NE
1743                  ("?controlled object& must not be overlaid", Nam, U_Ent);
1744                Error_Msg_N
1745                  ("\?Program_Error will be raised at run time", Nam);
1746                Insert_Action (Declaration_Node (U_Ent),
1747                  Make_Raise_Program_Error (Loc,
1748                    Reason => PE_Overlaid_Controlled_Object));
1749                return;
1750
1751             --  Case of address clause for a (non-controlled) object
1752
1753             elsif
1754               Ekind (U_Ent) = E_Variable
1755                 or else
1756               Ekind (U_Ent) = E_Constant
1757             then
1758                declare
1759                   Expr  : constant Node_Id := Expression (N);
1760                   O_Ent : Entity_Id;
1761                   Off   : Boolean;
1762
1763                begin
1764                   --  Exported variables cannot have an address clause, because
1765                   --  this cancels the effect of the pragma Export.
1766
1767                   if Is_Exported (U_Ent) then
1768                      Error_Msg_N
1769                        ("cannot export object with address clause", Nam);
1770                      return;
1771                   end if;
1772
1773                   Find_Overlaid_Entity (N, O_Ent, Off);
1774
1775                   --  Overlaying controlled objects is erroneous
1776
1777                   if Present (O_Ent)
1778                     and then (Has_Controlled_Component (Etype (O_Ent))
1779                                 or else Is_Controlled (Etype (O_Ent)))
1780                   then
1781                      Error_Msg_N
1782                        ("?cannot overlay with controlled object", Expr);
1783                      Error_Msg_N
1784                        ("\?Program_Error will be raised at run time", Expr);
1785                      Insert_Action (Declaration_Node (U_Ent),
1786                        Make_Raise_Program_Error (Loc,
1787                          Reason => PE_Overlaid_Controlled_Object));
1788                      return;
1789
1790                   elsif Present (O_Ent)
1791                     and then Ekind (U_Ent) = E_Constant
1792                     and then not Is_Constant_Object (O_Ent)
1793                   then
1794                      Error_Msg_N ("constant overlays a variable?", Expr);
1795
1796                   elsif Present (Renamed_Object (U_Ent)) then
1797                      Error_Msg_N
1798                        ("address clause not allowed"
1799                           & " for a renaming declaration (RM 13.1(6))", Nam);
1800                      return;
1801
1802                   --  Imported variables can have an address clause, but then
1803                   --  the import is pretty meaningless except to suppress
1804                   --  initializations, so we do not need such variables to
1805                   --  be statically allocated (and in fact it causes trouble
1806                   --  if the address clause is a local value).
1807
1808                   elsif Is_Imported (U_Ent) then
1809                      Set_Is_Statically_Allocated (U_Ent, False);
1810                   end if;
1811
1812                   --  We mark a possible modification of a variable with an
1813                   --  address clause, since it is likely aliasing is occurring.
1814
1815                   Note_Possible_Modification (Nam, Sure => False);
1816
1817                   --  Here we are checking for explicit overlap of one variable
1818                   --  by another, and if we find this then mark the overlapped
1819                   --  variable as also being volatile to prevent unwanted
1820                   --  optimizations. This is a significant pessimization so
1821                   --  avoid it when there is an offset, i.e. when the object
1822                   --  is composite; they cannot be optimized easily anyway.
1823
1824                   if Present (O_Ent)
1825                     and then Is_Object (O_Ent)
1826                     and then not Off
1827                   then
1828                      Set_Treat_As_Volatile (O_Ent);
1829                   end if;
1830
1831                   --  Legality checks on the address clause for initialized
1832                   --  objects is deferred until the freeze point, because
1833                   --  a subsequent pragma might indicate that the object is
1834                   --  imported and thus not initialized.
1835
1836                   Set_Has_Delayed_Freeze (U_Ent);
1837
1838                   --  If an initialization call has been generated for this
1839                   --  object, it needs to be deferred to after the freeze node
1840                   --  we have just now added, otherwise GIGI will see a
1841                   --  reference to the variable (as actual to the IP call)
1842                   --  before its definition.
1843
1844                   declare
1845                      Init_Call : constant Node_Id := Find_Init_Call (U_Ent, N);
1846                   begin
1847                      if Present (Init_Call) then
1848                         Remove (Init_Call);
1849                         Append_Freeze_Action (U_Ent, Init_Call);
1850                      end if;
1851                   end;
1852
1853                   if Is_Exported (U_Ent) then
1854                      Error_Msg_N
1855                        ("& cannot be exported if an address clause is given",
1856                         Nam);
1857                      Error_Msg_N
1858                        ("\define and export a variable " &
1859                         "that holds its address instead",
1860                         Nam);
1861                   end if;
1862
1863                   --  Entity has delayed freeze, so we will generate an
1864                   --  alignment check at the freeze point unless suppressed.
1865
1866                   if not Range_Checks_Suppressed (U_Ent)
1867                     and then not Alignment_Checks_Suppressed (U_Ent)
1868                   then
1869                      Set_Check_Address_Alignment (N);
1870                   end if;
1871
1872                   --  Kill the size check code, since we are not allocating
1873                   --  the variable, it is somewhere else.
1874
1875                   Kill_Size_Check_Code (U_Ent);
1876
1877                   --  If the address clause is of the form:
1878
1879                   --    for Y'Address use X'Address
1880
1881                   --  or
1882
1883                   --    Const : constant Address := X'Address;
1884                   --    ...
1885                   --    for Y'Address use Const;
1886
1887                   --  then we make an entry in the table for checking the size
1888                   --  and alignment of the overlaying variable. We defer this
1889                   --  check till after code generation to take full advantage
1890                   --  of the annotation done by the back end. This entry is
1891                   --  only made if the address clause comes from source.
1892                   --  If the entity has a generic type, the check will be
1893                   --  performed in the instance if the actual type justifies
1894                   --  it, and we do not insert the clause in the table to
1895                   --  prevent spurious warnings.
1896
1897                   if Address_Clause_Overlay_Warnings
1898                     and then Comes_From_Source (N)
1899                     and then Present (O_Ent)
1900                     and then Is_Object (O_Ent)
1901                   then
1902                      if not Is_Generic_Type (Etype (U_Ent)) then
1903                         Address_Clause_Checks.Append ((N, U_Ent, O_Ent, Off));
1904                      end if;
1905
1906                      --  If variable overlays a constant view, and we are
1907                      --  warning on overlays, then mark the variable as
1908                      --  overlaying a constant (we will give warnings later
1909                      --  if this variable is assigned).
1910
1911                      if Is_Constant_Object (O_Ent)
1912                        and then Ekind (U_Ent) = E_Variable
1913                      then
1914                         Set_Overlays_Constant (U_Ent);
1915                      end if;
1916                   end if;
1917                end;
1918
1919             --  Not a valid entity for an address clause
1920
1921             else
1922                Error_Msg_N ("address cannot be given for &", Nam);
1923             end if;
1924          end Address;
1925
1926          ---------------
1927          -- Alignment --
1928          ---------------
1929
1930          --  Alignment attribute definition clause
1931
1932          when Attribute_Alignment => Alignment : declare
1933             Align : constant Uint := Get_Alignment_Value (Expr);
1934
1935          begin
1936             FOnly := True;
1937
1938             if not Is_Type (U_Ent)
1939               and then Ekind (U_Ent) /= E_Variable
1940               and then Ekind (U_Ent) /= E_Constant
1941             then
1942                Error_Msg_N ("alignment cannot be given for &", Nam);
1943
1944             elsif Duplicate_Clause then
1945                null;
1946
1947             elsif Align /= No_Uint then
1948                Set_Has_Alignment_Clause (U_Ent);
1949                Set_Alignment            (U_Ent, Align);
1950
1951                --  For an array type, U_Ent is the first subtype. In that case,
1952                --  also set the alignment of the anonymous base type so that
1953                --  other subtypes (such as the itypes for aggregates of the
1954                --  type) also receive the expected alignment.
1955
1956                if Is_Array_Type (U_Ent) then
1957                   Set_Alignment (Base_Type (U_Ent), Align);
1958                end if;
1959             end if;
1960          end Alignment;
1961
1962          ---------------
1963          -- Bit_Order --
1964          ---------------
1965
1966          --  Bit_Order attribute definition clause
1967
1968          when Attribute_Bit_Order => Bit_Order : declare
1969          begin
1970             if not Is_Record_Type (U_Ent) then
1971                Error_Msg_N
1972                  ("Bit_Order can only be defined for record type", Nam);
1973
1974             elsif Duplicate_Clause then
1975                null;
1976
1977             else
1978                Analyze_And_Resolve (Expr, RTE (RE_Bit_Order));
1979
1980                if Etype (Expr) = Any_Type then
1981                   return;
1982
1983                elsif not Is_Static_Expression (Expr) then
1984                   Flag_Non_Static_Expr
1985                     ("Bit_Order requires static expression!", Expr);
1986
1987                else
1988                   if (Expr_Value (Expr) = 0) /= Bytes_Big_Endian then
1989                      Set_Reverse_Bit_Order (U_Ent, True);
1990                   end if;
1991                end if;
1992             end if;
1993          end Bit_Order;
1994
1995          --------------------
1996          -- Component_Size --
1997          --------------------
1998
1999          --  Component_Size attribute definition clause
2000
2001          when Attribute_Component_Size => Component_Size_Case : declare
2002             Csize    : constant Uint := Static_Integer (Expr);
2003             Ctyp     : Entity_Id;
2004             Btype    : Entity_Id;
2005             Biased   : Boolean;
2006             New_Ctyp : Entity_Id;
2007             Decl     : Node_Id;
2008
2009          begin
2010             if not Is_Array_Type (U_Ent) then
2011                Error_Msg_N ("component size requires array type", Nam);
2012                return;
2013             end if;
2014
2015             Btype := Base_Type (U_Ent);
2016             Ctyp := Component_Type (Btype);
2017
2018             if Duplicate_Clause then
2019                null;
2020
2021             elsif Rep_Item_Too_Early (Btype, N) then
2022                null;
2023
2024             elsif Csize /= No_Uint then
2025                Check_Size (Expr, Ctyp, Csize, Biased);
2026
2027                --  For the biased case, build a declaration for a subtype that
2028                --  will be used to represent the biased subtype that reflects
2029                --  the biased representation of components. We need the subtype
2030                --  to get proper conversions on referencing elements of the
2031                --  array. Note: component size clauses are ignored in VM mode.
2032
2033                if VM_Target = No_VM then
2034                   if Biased then
2035                      New_Ctyp :=
2036                        Make_Defining_Identifier (Loc,
2037                          Chars =>
2038                            New_External_Name (Chars (U_Ent), 'C', 0, 'T'));
2039
2040                      Decl :=
2041                        Make_Subtype_Declaration (Loc,
2042                          Defining_Identifier => New_Ctyp,
2043                          Subtype_Indication  =>
2044                            New_Occurrence_Of (Component_Type (Btype), Loc));
2045
2046                      Set_Parent (Decl, N);
2047                      Analyze (Decl, Suppress => All_Checks);
2048
2049                      Set_Has_Delayed_Freeze        (New_Ctyp, False);
2050                      Set_Esize                     (New_Ctyp, Csize);
2051                      Set_RM_Size                   (New_Ctyp, Csize);
2052                      Init_Alignment                (New_Ctyp);
2053                      Set_Is_Itype                  (New_Ctyp, True);
2054                      Set_Associated_Node_For_Itype (New_Ctyp, U_Ent);
2055
2056                      Set_Component_Type (Btype, New_Ctyp);
2057                      Set_Biased (New_Ctyp, N, "component size clause");
2058                   end if;
2059
2060                   Set_Component_Size (Btype, Csize);
2061
2062                --  For VM case, we ignore component size clauses
2063
2064                else
2065                   --  Give a warning unless we are in GNAT mode, in which case
2066                   --  the warning is suppressed since it is not useful.
2067
2068                   if not GNAT_Mode then
2069                      Error_Msg_N
2070                        ("?component size ignored in this configuration", N);
2071                   end if;
2072                end if;
2073
2074                --  Deal with warning on overridden size
2075
2076                if Warn_On_Overridden_Size
2077                  and then Has_Size_Clause (Ctyp)
2078                  and then RM_Size (Ctyp) /= Csize
2079                then
2080                   Error_Msg_NE
2081                     ("?component size overrides size clause for&",
2082                      N, Ctyp);
2083                end if;
2084
2085                Set_Has_Component_Size_Clause (Btype, True);
2086                Set_Has_Non_Standard_Rep (Btype, True);
2087             end if;
2088          end Component_Size_Case;
2089
2090          ------------------
2091          -- External_Tag --
2092          ------------------
2093
2094          when Attribute_External_Tag => External_Tag :
2095          begin
2096             if not Is_Tagged_Type (U_Ent) then
2097                Error_Msg_N ("should be a tagged type", Nam);
2098             end if;
2099
2100             if Duplicate_Clause then
2101                null;
2102
2103             else
2104                Analyze_And_Resolve (Expr, Standard_String);
2105
2106                if not Is_Static_Expression (Expr) then
2107                   Flag_Non_Static_Expr
2108                     ("static string required for tag name!", Nam);
2109                end if;
2110
2111                if VM_Target = No_VM then
2112                   Set_Has_External_Tag_Rep_Clause (U_Ent);
2113                else
2114                   Error_Msg_Name_1 := Attr;
2115                   Error_Msg_N
2116                     ("% attribute unsupported in this configuration", Nam);
2117                end if;
2118
2119                if not Is_Library_Level_Entity (U_Ent) then
2120                   Error_Msg_NE
2121                     ("?non-unique external tag supplied for &", N, U_Ent);
2122                   Error_Msg_N
2123                     ("?\same external tag applies to all subprogram calls", N);
2124                   Error_Msg_N
2125                     ("?\corresponding internal tag cannot be obtained", N);
2126                end if;
2127             end if;
2128          end External_Tag;
2129
2130          -----------
2131          -- Input --
2132          -----------
2133
2134          when Attribute_Input =>
2135             Analyze_Stream_TSS_Definition (TSS_Stream_Input);
2136             Set_Has_Specified_Stream_Input (Ent);
2137
2138          -------------------
2139          -- Machine_Radix --
2140          -------------------
2141
2142          --  Machine radix attribute definition clause
2143
2144          when Attribute_Machine_Radix => Machine_Radix : declare
2145             Radix : constant Uint := Static_Integer (Expr);
2146
2147          begin
2148             if not Is_Decimal_Fixed_Point_Type (U_Ent) then
2149                Error_Msg_N ("decimal fixed-point type expected for &", Nam);
2150
2151             elsif Duplicate_Clause then
2152                null;
2153
2154             elsif Radix /= No_Uint then
2155                Set_Has_Machine_Radix_Clause (U_Ent);
2156                Set_Has_Non_Standard_Rep (Base_Type (U_Ent));
2157
2158                if Radix = 2 then
2159                   null;
2160                elsif Radix = 10 then
2161                   Set_Machine_Radix_10 (U_Ent);
2162                else
2163                   Error_Msg_N ("machine radix value must be 2 or 10", Expr);
2164                end if;
2165             end if;
2166          end Machine_Radix;
2167
2168          -----------------
2169          -- Object_Size --
2170          -----------------
2171
2172          --  Object_Size attribute definition clause
2173
2174          when Attribute_Object_Size => Object_Size : declare
2175             Size : constant Uint := Static_Integer (Expr);
2176
2177             Biased : Boolean;
2178             pragma Warnings (Off, Biased);
2179
2180          begin
2181             if not Is_Type (U_Ent) then
2182                Error_Msg_N ("Object_Size cannot be given for &", Nam);
2183
2184             elsif Duplicate_Clause then
2185                null;
2186
2187             else
2188                Check_Size (Expr, U_Ent, Size, Biased);
2189
2190                if Size /= 8
2191                     and then
2192                   Size /= 16
2193                     and then
2194                   Size /= 32
2195                     and then
2196                   UI_Mod (Size, 64) /= 0
2197                then
2198                   Error_Msg_N
2199                     ("Object_Size must be 8, 16, 32, or multiple of 64",
2200                      Expr);
2201                end if;
2202
2203                Set_Esize (U_Ent, Size);
2204                Set_Has_Object_Size_Clause (U_Ent);
2205                Alignment_Check_For_Esize_Change (U_Ent);
2206             end if;
2207          end Object_Size;
2208
2209          ------------
2210          -- Output --
2211          ------------
2212
2213          when Attribute_Output =>
2214             Analyze_Stream_TSS_Definition (TSS_Stream_Output);
2215             Set_Has_Specified_Stream_Output (Ent);
2216
2217          ----------
2218          -- Read --
2219          ----------
2220
2221          when Attribute_Read =>
2222             Analyze_Stream_TSS_Definition (TSS_Stream_Read);
2223             Set_Has_Specified_Stream_Read (Ent);
2224
2225          ----------
2226          -- Size --
2227          ----------
2228
2229          --  Size attribute definition clause
2230
2231          when Attribute_Size => Size : declare
2232             Size   : constant Uint := Static_Integer (Expr);
2233             Etyp   : Entity_Id;
2234             Biased : Boolean;
2235
2236          begin
2237             FOnly := True;
2238
2239             if Duplicate_Clause then
2240                null;
2241
2242             elsif not Is_Type (U_Ent)
2243               and then Ekind (U_Ent) /= E_Variable
2244               and then Ekind (U_Ent) /= E_Constant
2245             then
2246                Error_Msg_N ("size cannot be given for &", Nam);
2247
2248             elsif Is_Array_Type (U_Ent)
2249               and then not Is_Constrained (U_Ent)
2250             then
2251                Error_Msg_N
2252                  ("size cannot be given for unconstrained array", Nam);
2253
2254             elsif Size /= No_Uint then
2255
2256                if VM_Target /= No_VM and then not GNAT_Mode then
2257
2258                   --  Size clause is not handled properly on VM targets.
2259                   --  Display a warning unless we are in GNAT mode, in which
2260                   --  case this is useless.
2261
2262                   Error_Msg_N
2263                     ("?size clauses are ignored in this configuration", N);
2264                end if;
2265
2266                if Is_Type (U_Ent) then
2267                   Etyp := U_Ent;
2268                else
2269                   Etyp := Etype (U_Ent);
2270                end if;
2271
2272                --  Check size, note that Gigi is in charge of checking that the
2273                --  size of an array or record type is OK. Also we do not check
2274                --  the size in the ordinary fixed-point case, since it is too
2275                --  early to do so (there may be subsequent small clause that
2276                --  affects the size). We can check the size if a small clause
2277                --  has already been given.
2278
2279                if not Is_Ordinary_Fixed_Point_Type (U_Ent)
2280                  or else Has_Small_Clause (U_Ent)
2281                then
2282                   Check_Size (Expr, Etyp, Size, Biased);
2283                   Set_Biased (U_Ent, N, "size clause", Biased);
2284                end if;
2285
2286                --  For types set RM_Size and Esize if possible
2287
2288                if Is_Type (U_Ent) then
2289                   Set_RM_Size (U_Ent, Size);
2290
2291                   --  For scalar types, increase Object_Size to power of 2, but
2292                   --  not less than a storage unit in any case (i.e., normally
2293                   --  this means it will be byte addressable).
2294
2295                   if Is_Scalar_Type (U_Ent) then
2296                      if Size <= System_Storage_Unit then
2297                         Init_Esize (U_Ent, System_Storage_Unit);
2298                      elsif Size <= 16 then
2299                         Init_Esize (U_Ent, 16);
2300                      elsif Size <= 32 then
2301                         Init_Esize (U_Ent, 32);
2302                      else
2303                         Set_Esize  (U_Ent, (Size + 63) / 64 * 64);
2304                      end if;
2305
2306                   --  For all other types, object size = value size. The
2307                   --  backend will adjust as needed.
2308
2309                   else
2310                      Set_Esize (U_Ent, Size);
2311                   end if;
2312
2313                   Alignment_Check_For_Esize_Change (U_Ent);
2314
2315                --  For objects, set Esize only
2316
2317                else
2318                   if Is_Elementary_Type (Etyp) then
2319                      if Size /= System_Storage_Unit
2320                           and then
2321                         Size /= System_Storage_Unit * 2
2322                           and then
2323                         Size /= System_Storage_Unit * 4
2324                            and then
2325                         Size /= System_Storage_Unit * 8
2326                      then
2327                         Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
2328                         Error_Msg_Uint_2 := Error_Msg_Uint_1 * 8;
2329                         Error_Msg_N
2330                           ("size for primitive object must be a power of 2"
2331                             & " in the range ^-^", N);
2332                      end if;
2333                   end if;
2334
2335                   Set_Esize (U_Ent, Size);
2336                end if;
2337
2338                Set_Has_Size_Clause (U_Ent);
2339             end if;
2340          end Size;
2341
2342          -----------
2343          -- Small --
2344          -----------
2345
2346          --  Small attribute definition clause
2347
2348          when Attribute_Small => Small : declare
2349             Implicit_Base : constant Entity_Id := Base_Type (U_Ent);
2350             Small         : Ureal;
2351
2352          begin
2353             Analyze_And_Resolve (Expr, Any_Real);
2354
2355             if Etype (Expr) = Any_Type then
2356                return;
2357
2358             elsif not Is_Static_Expression (Expr) then
2359                Flag_Non_Static_Expr
2360                  ("small requires static expression!", Expr);
2361                return;
2362
2363             else
2364                Small := Expr_Value_R (Expr);
2365
2366                if Small <= Ureal_0 then
2367                   Error_Msg_N ("small value must be greater than zero", Expr);
2368                   return;
2369                end if;
2370
2371             end if;
2372
2373             if not Is_Ordinary_Fixed_Point_Type (U_Ent) then
2374                Error_Msg_N
2375                  ("small requires an ordinary fixed point type", Nam);
2376
2377             elsif Has_Small_Clause (U_Ent) then
2378                Error_Msg_N ("small already given for &", Nam);
2379
2380             elsif Small > Delta_Value (U_Ent) then
2381                Error_Msg_N
2382                  ("small value must not be greater then delta value", Nam);
2383
2384             else
2385                Set_Small_Value (U_Ent, Small);
2386                Set_Small_Value (Implicit_Base, Small);
2387                Set_Has_Small_Clause (U_Ent);
2388                Set_Has_Small_Clause (Implicit_Base);
2389                Set_Has_Non_Standard_Rep (Implicit_Base);
2390             end if;
2391          end Small;
2392
2393          ------------------
2394          -- Storage_Pool --
2395          ------------------
2396
2397          --  Storage_Pool attribute definition clause
2398
2399          when Attribute_Storage_Pool => Storage_Pool : declare
2400             Pool : Entity_Id;
2401             T    : Entity_Id;
2402
2403          begin
2404             if Ekind (U_Ent) = E_Access_Subprogram_Type then
2405                Error_Msg_N
2406                  ("storage pool cannot be given for access-to-subprogram type",
2407                   Nam);
2408                return;
2409
2410             elsif not
2411               Ekind_In (U_Ent, E_Access_Type, E_General_Access_Type)
2412             then
2413                Error_Msg_N
2414                  ("storage pool can only be given for access types", Nam);
2415                return;
2416
2417             elsif Is_Derived_Type (U_Ent) then
2418                Error_Msg_N
2419                  ("storage pool cannot be given for a derived access type",
2420                   Nam);
2421
2422             elsif Duplicate_Clause then
2423                return;
2424
2425             elsif Present (Associated_Storage_Pool (U_Ent)) then
2426                Error_Msg_N ("storage pool already given for &", Nam);
2427                return;
2428             end if;
2429
2430             Analyze_And_Resolve
2431               (Expr, Class_Wide_Type (RTE (RE_Root_Storage_Pool)));
2432
2433             if not Denotes_Variable (Expr) then
2434                Error_Msg_N ("storage pool must be a variable", Expr);
2435                return;
2436             end if;
2437
2438             if Nkind (Expr) = N_Type_Conversion then
2439                T := Etype (Expression (Expr));
2440             else
2441                T := Etype (Expr);
2442             end if;
2443
2444             --  The Stack_Bounded_Pool is used internally for implementing
2445             --  access types with a Storage_Size. Since it only work
2446             --  properly when used on one specific type, we need to check
2447             --  that it is not hijacked improperly:
2448             --    type T is access Integer;
2449             --    for T'Storage_Size use n;
2450             --    type Q is access Float;
2451             --    for Q'Storage_Size use T'Storage_Size; -- incorrect
2452
2453             if RTE_Available (RE_Stack_Bounded_Pool)
2454               and then Base_Type (T) = RTE (RE_Stack_Bounded_Pool)
2455             then
2456                Error_Msg_N ("non-shareable internal Pool", Expr);
2457                return;
2458             end if;
2459
2460             --  If the argument is a name that is not an entity name, then
2461             --  we construct a renaming operation to define an entity of
2462             --  type storage pool.
2463
2464             if not Is_Entity_Name (Expr)
2465               and then Is_Object_Reference (Expr)
2466             then
2467                Pool := Make_Temporary (Loc, 'P', Expr);
2468
2469                declare
2470                   Rnode : constant Node_Id :=
2471                             Make_Object_Renaming_Declaration (Loc,
2472                               Defining_Identifier => Pool,
2473                               Subtype_Mark        =>
2474                                 New_Occurrence_Of (Etype (Expr), Loc),
2475                               Name                => Expr);
2476
2477                begin
2478                   Insert_Before (N, Rnode);
2479                   Analyze (Rnode);
2480                   Set_Associated_Storage_Pool (U_Ent, Pool);
2481                end;
2482
2483             elsif Is_Entity_Name (Expr) then
2484                Pool := Entity (Expr);
2485
2486                --  If pool is a renamed object, get original one. This can
2487                --  happen with an explicit renaming, and within instances.
2488
2489                while Present (Renamed_Object (Pool))
2490                  and then Is_Entity_Name (Renamed_Object (Pool))
2491                loop
2492                   Pool := Entity (Renamed_Object (Pool));
2493                end loop;
2494
2495                if Present (Renamed_Object (Pool))
2496                  and then Nkind (Renamed_Object (Pool)) = N_Type_Conversion
2497                  and then Is_Entity_Name (Expression (Renamed_Object (Pool)))
2498                then
2499                   Pool := Entity (Expression (Renamed_Object (Pool)));
2500                end if;
2501
2502                Set_Associated_Storage_Pool (U_Ent, Pool);
2503
2504             elsif Nkind (Expr) = N_Type_Conversion
2505               and then Is_Entity_Name (Expression (Expr))
2506               and then Nkind (Original_Node (Expr)) = N_Attribute_Reference
2507             then
2508                Pool := Entity (Expression (Expr));
2509                Set_Associated_Storage_Pool (U_Ent, Pool);
2510
2511             else
2512                Error_Msg_N ("incorrect reference to a Storage Pool", Expr);
2513                return;
2514             end if;
2515          end Storage_Pool;
2516
2517          ------------------
2518          -- Storage_Size --
2519          ------------------
2520
2521          --  Storage_Size attribute definition clause
2522
2523          when Attribute_Storage_Size => Storage_Size : declare
2524             Btype : constant Entity_Id := Base_Type (U_Ent);
2525             Sprag : Node_Id;
2526
2527          begin
2528             if Is_Task_Type (U_Ent) then
2529                Check_Restriction (No_Obsolescent_Features, N);
2530
2531                if Warn_On_Obsolescent_Feature then
2532                   Error_Msg_N
2533                     ("storage size clause for task is an " &
2534                      "obsolescent feature (RM J.9)?", N);
2535                   Error_Msg_N ("\use Storage_Size pragma instead?", N);
2536                end if;
2537
2538                FOnly := True;
2539             end if;
2540
2541             if not Is_Access_Type (U_Ent)
2542               and then Ekind (U_Ent) /= E_Task_Type
2543             then
2544                Error_Msg_N ("storage size cannot be given for &", Nam);
2545
2546             elsif Is_Access_Type (U_Ent) and Is_Derived_Type (U_Ent) then
2547                Error_Msg_N
2548                  ("storage size cannot be given for a derived access type",
2549                   Nam);
2550
2551             elsif Duplicate_Clause then
2552                null;
2553
2554             else
2555                Analyze_And_Resolve (Expr, Any_Integer);
2556
2557                if Is_Access_Type (U_Ent) then
2558                   if Present (Associated_Storage_Pool (U_Ent)) then
2559                      Error_Msg_N ("storage pool already given for &", Nam);
2560                      return;
2561                   end if;
2562
2563                   if Is_OK_Static_Expression (Expr)
2564                     and then Expr_Value (Expr) = 0
2565                   then
2566                      Set_No_Pool_Assigned (Btype);
2567                   end if;
2568
2569                else -- Is_Task_Type (U_Ent)
2570                   Sprag := Get_Rep_Pragma (Btype, Name_Storage_Size);
2571
2572                   if Present (Sprag) then
2573                      Error_Msg_Sloc := Sloc (Sprag);
2574                      Error_Msg_N
2575                        ("Storage_Size already specified#", Nam);
2576                      return;
2577                   end if;
2578                end if;
2579
2580                Set_Has_Storage_Size_Clause (Btype);
2581             end if;
2582          end Storage_Size;
2583
2584          -----------------
2585          -- Stream_Size --
2586          -----------------
2587
2588          when Attribute_Stream_Size => Stream_Size : declare
2589             Size : constant Uint := Static_Integer (Expr);
2590
2591          begin
2592             if Ada_Version <= Ada_95 then
2593                Check_Restriction (No_Implementation_Attributes, N);
2594             end if;
2595
2596             if Duplicate_Clause then
2597                null;
2598
2599             elsif Is_Elementary_Type (U_Ent) then
2600                if Size /= System_Storage_Unit
2601                     and then
2602                   Size /= System_Storage_Unit * 2
2603                     and then
2604                   Size /= System_Storage_Unit * 4
2605                      and then
2606                   Size /= System_Storage_Unit * 8
2607                then
2608                   Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
2609                   Error_Msg_N
2610                     ("stream size for elementary type must be a"
2611                        & " power of 2 and at least ^", N);
2612
2613                elsif RM_Size (U_Ent) > Size then
2614                   Error_Msg_Uint_1 := RM_Size (U_Ent);
2615                   Error_Msg_N
2616                     ("stream size for elementary type must be a"
2617                        & " power of 2 and at least ^", N);
2618                end if;
2619
2620                Set_Has_Stream_Size_Clause (U_Ent);
2621
2622             else
2623                Error_Msg_N ("Stream_Size cannot be given for &", Nam);
2624             end if;
2625          end Stream_Size;
2626
2627          ----------------
2628          -- Value_Size --
2629          ----------------
2630
2631          --  Value_Size attribute definition clause
2632
2633          when Attribute_Value_Size => Value_Size : declare
2634             Size   : constant Uint := Static_Integer (Expr);
2635             Biased : Boolean;
2636
2637          begin
2638             if not Is_Type (U_Ent) then
2639                Error_Msg_N ("Value_Size cannot be given for &", Nam);
2640
2641             elsif Duplicate_Clause then
2642                null;
2643
2644             elsif Is_Array_Type (U_Ent)
2645               and then not Is_Constrained (U_Ent)
2646             then
2647                Error_Msg_N
2648                  ("Value_Size cannot be given for unconstrained array", Nam);
2649
2650             else
2651                if Is_Elementary_Type (U_Ent) then
2652                   Check_Size (Expr, U_Ent, Size, Biased);
2653                   Set_Biased (U_Ent, N, "value size clause", Biased);
2654                end if;
2655
2656                Set_RM_Size (U_Ent, Size);
2657             end if;
2658          end Value_Size;
2659
2660          -----------
2661          -- Write --
2662          -----------
2663
2664          when Attribute_Write =>
2665             Analyze_Stream_TSS_Definition (TSS_Stream_Write);
2666             Set_Has_Specified_Stream_Write (Ent);
2667
2668          --  All other attributes cannot be set
2669
2670          when others =>
2671             Error_Msg_N
2672               ("attribute& cannot be set with definition clause", N);
2673       end case;
2674
2675       --  The test for the type being frozen must be performed after
2676       --  any expression the clause has been analyzed since the expression
2677       --  itself might cause freezing that makes the clause illegal.
2678
2679       if Rep_Item_Too_Late (U_Ent, N, FOnly) then
2680          return;
2681       end if;
2682    end Analyze_Attribute_Definition_Clause;
2683
2684    ----------------------------
2685    -- Analyze_Code_Statement --
2686    ----------------------------
2687
2688    procedure Analyze_Code_Statement (N : Node_Id) is
2689       HSS   : constant Node_Id   := Parent (N);
2690       SBody : constant Node_Id   := Parent (HSS);
2691       Subp  : constant Entity_Id := Current_Scope;
2692       Stmt  : Node_Id;
2693       Decl  : Node_Id;
2694       StmtO : Node_Id;
2695       DeclO : Node_Id;
2696
2697    begin
2698       --  Analyze and check we get right type, note that this implements the
2699       --  requirement (RM 13.8(1)) that Machine_Code be with'ed, since that
2700       --  is the only way that Asm_Insn could possibly be visible.
2701
2702       Analyze_And_Resolve (Expression (N));
2703
2704       if Etype (Expression (N)) = Any_Type then
2705          return;
2706       elsif Etype (Expression (N)) /= RTE (RE_Asm_Insn) then
2707          Error_Msg_N ("incorrect type for code statement", N);
2708          return;
2709       end if;
2710
2711       Check_Code_Statement (N);
2712
2713       --  Make sure we appear in the handled statement sequence of a
2714       --  subprogram (RM 13.8(3)).
2715
2716       if Nkind (HSS) /= N_Handled_Sequence_Of_Statements
2717         or else Nkind (SBody) /= N_Subprogram_Body
2718       then
2719          Error_Msg_N
2720            ("code statement can only appear in body of subprogram", N);
2721          return;
2722       end if;
2723
2724       --  Do remaining checks (RM 13.8(3)) if not already done
2725
2726       if not Is_Machine_Code_Subprogram (Subp) then
2727          Set_Is_Machine_Code_Subprogram (Subp);
2728
2729          --  No exception handlers allowed
2730
2731          if Present (Exception_Handlers (HSS)) then
2732             Error_Msg_N
2733               ("exception handlers not permitted in machine code subprogram",
2734                First (Exception_Handlers (HSS)));
2735          end if;
2736
2737          --  No declarations other than use clauses and pragmas (we allow
2738          --  certain internally generated declarations as well).
2739
2740          Decl := First (Declarations (SBody));
2741          while Present (Decl) loop
2742             DeclO := Original_Node (Decl);
2743             if Comes_From_Source (DeclO)
2744               and not Nkind_In (DeclO, N_Pragma,
2745                                        N_Use_Package_Clause,
2746                                        N_Use_Type_Clause,
2747                                        N_Implicit_Label_Declaration)
2748             then
2749                Error_Msg_N
2750                  ("this declaration not allowed in machine code subprogram",
2751                   DeclO);
2752             end if;
2753
2754             Next (Decl);
2755          end loop;
2756
2757          --  No statements other than code statements, pragmas, and labels.
2758          --  Again we allow certain internally generated statements.
2759
2760          Stmt := First (Statements (HSS));
2761          while Present (Stmt) loop
2762             StmtO := Original_Node (Stmt);
2763             if Comes_From_Source (StmtO)
2764               and then not Nkind_In (StmtO, N_Pragma,
2765                                             N_Label,
2766                                             N_Code_Statement)
2767             then
2768                Error_Msg_N
2769                  ("this statement is not allowed in machine code subprogram",
2770                   StmtO);
2771             end if;
2772
2773             Next (Stmt);
2774          end loop;
2775       end if;
2776    end Analyze_Code_Statement;
2777
2778    -----------------------------------------------
2779    -- Analyze_Enumeration_Representation_Clause --
2780    -----------------------------------------------
2781
2782    procedure Analyze_Enumeration_Representation_Clause (N : Node_Id) is
2783       Ident    : constant Node_Id    := Identifier (N);
2784       Aggr     : constant Node_Id    := Array_Aggregate (N);
2785       Enumtype : Entity_Id;
2786       Elit     : Entity_Id;
2787       Expr     : Node_Id;
2788       Assoc    : Node_Id;
2789       Choice   : Node_Id;
2790       Val      : Uint;
2791       Err      : Boolean := False;
2792
2793       Lo : constant Uint := Expr_Value (Type_Low_Bound (Universal_Integer));
2794       Hi : constant Uint := Expr_Value (Type_High_Bound (Universal_Integer));
2795       --  Allowed range of universal integer (= allowed range of enum lit vals)
2796
2797       Min : Uint;
2798       Max : Uint;
2799       --  Minimum and maximum values of entries
2800
2801       Max_Node : Node_Id;
2802       --  Pointer to node for literal providing max value
2803
2804    begin
2805       if Ignore_Rep_Clauses then
2806          return;
2807       end if;
2808
2809       --  First some basic error checks
2810
2811       Find_Type (Ident);
2812       Enumtype := Entity (Ident);
2813
2814       if Enumtype = Any_Type
2815         or else Rep_Item_Too_Early (Enumtype, N)
2816       then
2817          return;
2818       else
2819          Enumtype := Underlying_Type (Enumtype);
2820       end if;
2821
2822       if not Is_Enumeration_Type (Enumtype) then
2823          Error_Msg_NE
2824            ("enumeration type required, found}",
2825             Ident, First_Subtype (Enumtype));
2826          return;
2827       end if;
2828
2829       --  Ignore rep clause on generic actual type. This will already have
2830       --  been flagged on the template as an error, and this is the safest
2831       --  way to ensure we don't get a junk cascaded message in the instance.
2832
2833       if Is_Generic_Actual_Type (Enumtype) then
2834          return;
2835
2836       --  Type must be in current scope
2837
2838       elsif Scope (Enumtype) /= Current_Scope then
2839          Error_Msg_N ("type must be declared in this scope", Ident);
2840          return;
2841
2842       --  Type must be a first subtype
2843
2844       elsif not Is_First_Subtype (Enumtype) then
2845          Error_Msg_N ("cannot give enumeration rep clause for subtype", N);
2846          return;
2847
2848       --  Ignore duplicate rep clause
2849
2850       elsif Has_Enumeration_Rep_Clause (Enumtype) then
2851          Error_Msg_N ("duplicate enumeration rep clause ignored", N);
2852          return;
2853
2854       --  Don't allow rep clause for standard [wide_[wide_]]character
2855
2856       elsif Is_Standard_Character_Type (Enumtype) then
2857          Error_Msg_N ("enumeration rep clause not allowed for this type", N);
2858          return;
2859
2860       --  Check that the expression is a proper aggregate (no parentheses)
2861
2862       elsif Paren_Count (Aggr) /= 0 then
2863          Error_Msg
2864            ("extra parentheses surrounding aggregate not allowed",
2865             First_Sloc (Aggr));
2866          return;
2867
2868       --  All tests passed, so set rep clause in place
2869
2870       else
2871          Set_Has_Enumeration_Rep_Clause (Enumtype);
2872          Set_Has_Enumeration_Rep_Clause (Base_Type (Enumtype));
2873       end if;
2874
2875       --  Now we process the aggregate. Note that we don't use the normal
2876       --  aggregate code for this purpose, because we don't want any of the
2877       --  normal expansion activities, and a number of special semantic
2878       --  rules apply (including the component type being any integer type)
2879
2880       Elit := First_Literal (Enumtype);
2881
2882       --  First the positional entries if any
2883
2884       if Present (Expressions (Aggr)) then
2885          Expr := First (Expressions (Aggr));
2886          while Present (Expr) loop
2887             if No (Elit) then
2888                Error_Msg_N ("too many entries in aggregate", Expr);
2889                return;
2890             end if;
2891
2892             Val := Static_Integer (Expr);
2893
2894             --  Err signals that we found some incorrect entries processing
2895             --  the list. The final checks for completeness and ordering are
2896             --  skipped in this case.
2897
2898             if Val = No_Uint then
2899                Err := True;
2900             elsif Val < Lo or else Hi < Val then
2901                Error_Msg_N ("value outside permitted range", Expr);
2902                Err := True;
2903             end if;
2904
2905             Set_Enumeration_Rep (Elit, Val);
2906             Set_Enumeration_Rep_Expr (Elit, Expr);
2907             Next (Expr);
2908             Next (Elit);
2909          end loop;
2910       end if;
2911
2912       --  Now process the named entries if present
2913
2914       if Present (Component_Associations (Aggr)) then
2915          Assoc := First (Component_Associations (Aggr));
2916          while Present (Assoc) loop
2917             Choice := First (Choices (Assoc));
2918
2919             if Present (Next (Choice)) then
2920                Error_Msg_N
2921                  ("multiple choice not allowed here", Next (Choice));
2922                Err := True;
2923             end if;
2924
2925             if Nkind (Choice) = N_Others_Choice then
2926                Error_Msg_N ("others choice not allowed here", Choice);
2927                Err := True;
2928
2929             elsif Nkind (Choice) = N_Range then
2930                --  ??? should allow zero/one element range here
2931                Error_Msg_N ("range not allowed here", Choice);
2932                Err := True;
2933
2934             else
2935                Analyze_And_Resolve (Choice, Enumtype);
2936
2937                if Is_Entity_Name (Choice)
2938                  and then Is_Type (Entity (Choice))
2939                then
2940                   Error_Msg_N ("subtype name not allowed here", Choice);
2941                   Err := True;
2942                   --  ??? should allow static subtype with zero/one entry
2943
2944                elsif Etype (Choice) = Base_Type (Enumtype) then
2945                   if not Is_Static_Expression (Choice) then
2946                      Flag_Non_Static_Expr
2947                        ("non-static expression used for choice!", Choice);
2948                      Err := True;
2949
2950                   else
2951                      Elit := Expr_Value_E (Choice);
2952
2953                      if Present (Enumeration_Rep_Expr (Elit)) then
2954                         Error_Msg_Sloc := Sloc (Enumeration_Rep_Expr (Elit));
2955                         Error_Msg_NE
2956                           ("representation for& previously given#",
2957                            Choice, Elit);
2958                         Err := True;
2959                      end if;
2960
2961                      Set_Enumeration_Rep_Expr (Elit, Expression (Assoc));
2962
2963                      Expr := Expression (Assoc);
2964                      Val := Static_Integer (Expr);
2965
2966                      if Val = No_Uint then
2967                         Err := True;
2968
2969                      elsif Val < Lo or else Hi < Val then
2970                         Error_Msg_N ("value outside permitted range", Expr);
2971                         Err := True;
2972                      end if;
2973
2974                      Set_Enumeration_Rep (Elit, Val);
2975                   end if;
2976                end if;
2977             end if;
2978
2979             Next (Assoc);
2980          end loop;
2981       end if;
2982
2983       --  Aggregate is fully processed. Now we check that a full set of
2984       --  representations was given, and that they are in range and in order.
2985       --  These checks are only done if no other errors occurred.
2986
2987       if not Err then
2988          Min  := No_Uint;
2989          Max  := No_Uint;
2990
2991          Elit := First_Literal (Enumtype);
2992          while Present (Elit) loop
2993             if No (Enumeration_Rep_Expr (Elit)) then
2994                Error_Msg_NE ("missing representation for&!", N, Elit);
2995
2996             else
2997                Val := Enumeration_Rep (Elit);
2998
2999                if Min = No_Uint then
3000                   Min := Val;
3001                end if;
3002
3003                if Val /= No_Uint then
3004                   if Max /= No_Uint and then Val <= Max then
3005                      Error_Msg_NE
3006                        ("enumeration value for& not ordered!",
3007                         Enumeration_Rep_Expr (Elit), Elit);
3008                   end if;
3009
3010                   Max_Node := Enumeration_Rep_Expr (Elit);
3011                   Max := Val;
3012                end if;
3013
3014                --  If there is at least one literal whose representation is not
3015                --  equal to the Pos value, then note that this enumeration type
3016                --  has a non-standard representation.
3017
3018                if Val /= Enumeration_Pos (Elit) then
3019                   Set_Has_Non_Standard_Rep (Base_Type (Enumtype));
3020                end if;
3021             end if;
3022
3023             Next (Elit);
3024          end loop;
3025
3026          --  Now set proper size information
3027
3028          declare
3029             Minsize : Uint := UI_From_Int (Minimum_Size (Enumtype));
3030
3031          begin
3032             if Has_Size_Clause (Enumtype) then
3033
3034                --  All OK, if size is OK now
3035
3036                if RM_Size (Enumtype) >= Minsize then
3037                   null;
3038
3039                else
3040                   --  Try if we can get by with biasing
3041
3042                   Minsize :=
3043                     UI_From_Int (Minimum_Size (Enumtype, Biased => True));
3044
3045                   --  Error message if even biasing does not work
3046
3047                   if RM_Size (Enumtype) < Minsize then
3048                      Error_Msg_Uint_1 := RM_Size (Enumtype);
3049                      Error_Msg_Uint_2 := Max;
3050                      Error_Msg_N
3051                        ("previously given size (^) is too small "
3052                         & "for this value (^)", Max_Node);
3053
3054                   --  If biasing worked, indicate that we now have biased rep
3055
3056                   else
3057                      Set_Biased
3058                        (Enumtype, Size_Clause (Enumtype), "size clause");
3059                   end if;
3060                end if;
3061
3062             else
3063                Set_RM_Size    (Enumtype, Minsize);
3064                Set_Enum_Esize (Enumtype);
3065             end if;
3066
3067             Set_RM_Size   (Base_Type (Enumtype), RM_Size   (Enumtype));
3068             Set_Esize     (Base_Type (Enumtype), Esize     (Enumtype));
3069             Set_Alignment (Base_Type (Enumtype), Alignment (Enumtype));
3070          end;
3071       end if;
3072
3073       --  We repeat the too late test in case it froze itself!
3074
3075       if Rep_Item_Too_Late (Enumtype, N) then
3076          null;
3077       end if;
3078    end Analyze_Enumeration_Representation_Clause;
3079
3080    ----------------------------
3081    -- Analyze_Free_Statement --
3082    ----------------------------
3083
3084    procedure Analyze_Free_Statement (N : Node_Id) is
3085    begin
3086       Analyze (Expression (N));
3087    end Analyze_Free_Statement;
3088
3089    ---------------------------
3090    -- Analyze_Freeze_Entity --
3091    ---------------------------
3092
3093    procedure Analyze_Freeze_Entity (N : Node_Id) is
3094       E : constant Entity_Id := Entity (N);
3095
3096    begin
3097       --  Remember that we are processing a freezing entity. Required to
3098       --  ensure correct decoration of internal entities associated with
3099       --  interfaces (see New_Overloaded_Entity).
3100
3101       Inside_Freezing_Actions := Inside_Freezing_Actions + 1;
3102
3103       --  For tagged types covering interfaces add internal entities that link
3104       --  the primitives of the interfaces with the primitives that cover them.
3105       --  Note: These entities were originally generated only when generating
3106       --  code because their main purpose was to provide support to initialize
3107       --  the secondary dispatch tables. They are now generated also when
3108       --  compiling with no code generation to provide ASIS the relationship
3109       --  between interface primitives and tagged type primitives. They are
3110       --  also used to locate primitives covering interfaces when processing
3111       --  generics (see Derive_Subprograms).
3112
3113       if Ada_Version >= Ada_2005
3114         and then Ekind (E) = E_Record_Type
3115         and then Is_Tagged_Type (E)
3116         and then not Is_Interface (E)
3117         and then Has_Interfaces (E)
3118       then
3119          --  This would be a good common place to call the routine that checks
3120          --  overriding of interface primitives (and thus factorize calls to
3121          --  Check_Abstract_Overriding located at different contexts in the
3122          --  compiler). However, this is not possible because it causes
3123          --  spurious errors in case of late overriding.
3124
3125          Add_Internal_Interface_Entities (E);
3126       end if;
3127
3128       --  Check CPP types
3129
3130       if Ekind (E) = E_Record_Type
3131         and then Is_CPP_Class (E)
3132         and then Is_Tagged_Type (E)
3133         and then Tagged_Type_Expansion
3134         and then Expander_Active
3135       then
3136          if CPP_Num_Prims (E) = 0 then
3137
3138             --  If the CPP type has user defined components then it must import
3139             --  primitives from C++. This is required because if the C++ class
3140             --  has no primitives then the C++ compiler does not added the _tag
3141             --  component to the type.
3142
3143             pragma Assert (Chars (First_Entity (E)) = Name_uTag);
3144
3145             if First_Entity (E) /= Last_Entity (E) then
3146                Error_Msg_N
3147                  ("?'C'P'P type must import at least one primitive from C++",
3148                   E);
3149             end if;
3150          end if;
3151
3152          --  Check that all its primitives are abstract or imported from C++.
3153          --  Check also availability of the C++ constructor.
3154
3155          declare
3156             Has_Constructors : constant Boolean := Has_CPP_Constructors (E);
3157             Elmt             : Elmt_Id;
3158             Error_Reported   : Boolean := False;
3159             Prim             : Node_Id;
3160
3161          begin
3162             Elmt := First_Elmt (Primitive_Operations (E));
3163             while Present (Elmt) loop
3164                Prim := Node (Elmt);
3165
3166                if Comes_From_Source (Prim) then
3167                   if Is_Abstract_Subprogram (Prim) then
3168                      null;
3169
3170                   elsif not Is_Imported (Prim)
3171                     or else Convention (Prim) /= Convention_CPP
3172                   then
3173                      Error_Msg_N
3174                        ("?primitives of 'C'P'P types must be imported from C++"
3175                         & " or abstract", Prim);
3176
3177                   elsif not Has_Constructors
3178                      and then not Error_Reported
3179                   then
3180                      Error_Msg_Name_1 := Chars (E);
3181                      Error_Msg_N
3182                        ("?'C'P'P constructor required for type %", Prim);
3183                      Error_Reported := True;
3184                   end if;
3185                end if;
3186
3187                Next_Elmt (Elmt);
3188             end loop;
3189          end;
3190       end if;
3191
3192       Inside_Freezing_Actions := Inside_Freezing_Actions - 1;
3193
3194       --  If we have a type with predicates, build predicate function
3195
3196       if Is_Type (E) and then Has_Predicates (E) then
3197          Build_Predicate_Function (E, N);
3198       end if;
3199
3200       --  If type has delayed aspects, this is where we do the preanalysis
3201       --  at the freeze point, as part of the consistent visibility check.
3202       --  Note that this must be done after calling Build_Predicate_Function,
3203       --  since that call marks occurrences of the subtype name in the saved
3204       --  expression so that they will not cause trouble in the preanalysis.
3205
3206       if Has_Delayed_Aspects (E) then
3207          declare
3208             Ritem : Node_Id;
3209
3210          begin
3211             --  Look for aspect specification entries for this entity
3212
3213             Ritem := First_Rep_Item (E);
3214             while Present (Ritem) loop
3215                if Nkind (Ritem) = N_Aspect_Specification
3216                  and then Entity (Ritem) = E
3217                  and then Is_Delayed_Aspect (Ritem)
3218                then
3219                   Check_Aspect_At_Freeze_Point (Ritem);
3220                end if;
3221
3222                Next_Rep_Item (Ritem);
3223             end loop;
3224          end;
3225       end if;
3226    end Analyze_Freeze_Entity;
3227
3228    ------------------------------------------
3229    -- Analyze_Record_Representation_Clause --
3230    ------------------------------------------
3231
3232    --  Note: we check as much as we can here, but we can't do any checks
3233    --  based on the position values (e.g. overlap checks) until freeze time
3234    --  because especially in Ada 2005 (machine scalar mode), the processing
3235    --  for non-standard bit order can substantially change the positions.
3236    --  See procedure Check_Record_Representation_Clause (called from Freeze)
3237    --  for the remainder of this processing.
3238
3239    procedure Analyze_Record_Representation_Clause (N : Node_Id) is
3240       Ident   : constant Node_Id := Identifier (N);
3241       Biased  : Boolean;
3242       CC      : Node_Id;
3243       Comp    : Entity_Id;
3244       Fbit    : Uint;
3245       Hbit    : Uint := Uint_0;
3246       Lbit    : Uint;
3247       Ocomp   : Entity_Id;
3248       Posit   : Uint;
3249       Rectype : Entity_Id;
3250
3251       CR_Pragma : Node_Id := Empty;
3252       --  Points to N_Pragma node if Complete_Representation pragma present
3253
3254    begin
3255       if Ignore_Rep_Clauses then
3256          return;
3257       end if;
3258
3259       Find_Type (Ident);
3260       Rectype := Entity (Ident);
3261
3262       if Rectype = Any_Type
3263         or else Rep_Item_Too_Early (Rectype, N)
3264       then
3265          return;
3266       else
3267          Rectype := Underlying_Type (Rectype);
3268       end if;
3269
3270       --  First some basic error checks
3271
3272       if not Is_Record_Type (Rectype) then
3273          Error_Msg_NE
3274            ("record type required, found}", Ident, First_Subtype (Rectype));
3275          return;
3276
3277       elsif Scope (Rectype) /= Current_Scope then
3278          Error_Msg_N ("type must be declared in this scope", N);
3279          return;
3280
3281       elsif not Is_First_Subtype (Rectype) then
3282          Error_Msg_N ("cannot give record rep clause for subtype", N);
3283          return;
3284
3285       elsif Has_Record_Rep_Clause (Rectype) then
3286          Error_Msg_N ("duplicate record rep clause ignored", N);
3287          return;
3288
3289       elsif Rep_Item_Too_Late (Rectype, N) then
3290          return;
3291       end if;
3292
3293       if Present (Mod_Clause (N)) then
3294          declare
3295             Loc     : constant Source_Ptr := Sloc (N);
3296             M       : constant Node_Id := Mod_Clause (N);
3297             P       : constant List_Id := Pragmas_Before (M);
3298             AtM_Nod : Node_Id;
3299
3300             Mod_Val : Uint;
3301             pragma Warnings (Off, Mod_Val);
3302
3303          begin
3304             Check_Restriction (No_Obsolescent_Features, Mod_Clause (N));
3305
3306             if Warn_On_Obsolescent_Feature then
3307                Error_Msg_N
3308                  ("mod clause is an obsolescent feature (RM J.8)?", N);
3309                Error_Msg_N
3310                  ("\use alignment attribute definition clause instead?", N);
3311             end if;
3312
3313             if Present (P) then
3314                Analyze_List (P);
3315             end if;
3316
3317             --  In ASIS_Mode mode, expansion is disabled, but we must convert
3318             --  the Mod clause into an alignment clause anyway, so that the
3319             --  back-end can compute and back-annotate properly the size and
3320             --  alignment of types that may include this record.
3321
3322             --  This seems dubious, this destroys the source tree in a manner
3323             --  not detectable by ASIS ???
3324
3325             if Operating_Mode = Check_Semantics
3326               and then ASIS_Mode
3327             then
3328                AtM_Nod :=
3329                  Make_Attribute_Definition_Clause (Loc,
3330                    Name       => New_Reference_To (Base_Type (Rectype), Loc),
3331                    Chars      => Name_Alignment,
3332                    Expression => Relocate_Node (Expression (M)));
3333
3334                Set_From_At_Mod (AtM_Nod);
3335                Insert_After (N, AtM_Nod);
3336                Mod_Val := Get_Alignment_Value (Expression (AtM_Nod));
3337                Set_Mod_Clause (N, Empty);
3338
3339             else
3340                --  Get the alignment value to perform error checking
3341
3342                Mod_Val := Get_Alignment_Value (Expression (M));
3343             end if;
3344          end;
3345       end if;
3346
3347       --  For untagged types, clear any existing component clauses for the
3348       --  type. If the type is derived, this is what allows us to override
3349       --  a rep clause for the parent. For type extensions, the representation
3350       --  of the inherited components is inherited, so we want to keep previous
3351       --  component clauses for completeness.
3352
3353       if not Is_Tagged_Type (Rectype) then
3354          Comp := First_Component_Or_Discriminant (Rectype);
3355          while Present (Comp) loop
3356             Set_Component_Clause (Comp, Empty);
3357             Next_Component_Or_Discriminant (Comp);
3358          end loop;
3359       end if;
3360
3361       --  All done if no component clauses
3362
3363       CC := First (Component_Clauses (N));
3364
3365       if No (CC) then
3366          return;
3367       end if;
3368
3369       --  A representation like this applies to the base type
3370
3371       Set_Has_Record_Rep_Clause (Base_Type (Rectype));
3372       Set_Has_Non_Standard_Rep  (Base_Type (Rectype));
3373       Set_Has_Specified_Layout  (Base_Type (Rectype));
3374
3375       --  Process the component clauses
3376
3377       while Present (CC) loop
3378
3379          --  Pragma
3380
3381          if Nkind (CC) = N_Pragma then
3382             Analyze (CC);
3383
3384             --  The only pragma of interest is Complete_Representation
3385
3386             if Pragma_Name (CC) = Name_Complete_Representation then
3387                CR_Pragma := CC;
3388             end if;
3389
3390          --  Processing for real component clause
3391
3392          else
3393             Posit := Static_Integer (Position  (CC));
3394             Fbit  := Static_Integer (First_Bit (CC));
3395             Lbit  := Static_Integer (Last_Bit  (CC));
3396
3397             if Posit /= No_Uint
3398               and then Fbit /= No_Uint
3399               and then Lbit /= No_Uint
3400             then
3401                if Posit < 0 then
3402                   Error_Msg_N
3403                     ("position cannot be negative", Position (CC));
3404
3405                elsif Fbit < 0 then
3406                   Error_Msg_N
3407                     ("first bit cannot be negative", First_Bit (CC));
3408
3409                --  The Last_Bit specified in a component clause must not be
3410                --  less than the First_Bit minus one (RM-13.5.1(10)).
3411
3412                elsif Lbit < Fbit - 1 then
3413                   Error_Msg_N
3414                     ("last bit cannot be less than first bit minus one",
3415                      Last_Bit (CC));
3416
3417                --  Values look OK, so find the corresponding record component
3418                --  Even though the syntax allows an attribute reference for
3419                --  implementation-defined components, GNAT does not allow the
3420                --  tag to get an explicit position.
3421
3422                elsif Nkind (Component_Name (CC)) = N_Attribute_Reference then
3423                   if Attribute_Name (Component_Name (CC)) = Name_Tag then
3424                      Error_Msg_N ("position of tag cannot be specified", CC);
3425                   else
3426                      Error_Msg_N ("illegal component name", CC);
3427                   end if;
3428
3429                else
3430                   Comp := First_Entity (Rectype);
3431                   while Present (Comp) loop
3432                      exit when Chars (Comp) = Chars (Component_Name (CC));
3433                      Next_Entity (Comp);
3434                   end loop;
3435
3436                   if No (Comp) then
3437
3438                      --  Maybe component of base type that is absent from
3439                      --  statically constrained first subtype.
3440
3441                      Comp := First_Entity (Base_Type (Rectype));
3442                      while Present (Comp) loop
3443                         exit when Chars (Comp) = Chars (Component_Name (CC));
3444                         Next_Entity (Comp);
3445                      end loop;
3446                   end if;
3447
3448                   if No (Comp) then
3449                      Error_Msg_N
3450                        ("component clause is for non-existent field", CC);
3451
3452                   --  Ada 2012 (AI05-0026): Any name that denotes a
3453                   --  discriminant of an object of an unchecked union type
3454                   --  shall not occur within a record_representation_clause.
3455
3456                   --  The general restriction of using record rep clauses on
3457                   --  Unchecked_Union types has now been lifted. Since it is
3458                   --  possible to introduce a record rep clause which mentions
3459                   --  the discriminant of an Unchecked_Union in non-Ada 2012
3460                   --  code, this check is applied to all versions of the
3461                   --  language.
3462
3463                   elsif Ekind (Comp) = E_Discriminant
3464                     and then Is_Unchecked_Union (Rectype)
3465                   then
3466                      Error_Msg_N
3467                        ("cannot reference discriminant of Unchecked_Union",
3468                         Component_Name (CC));
3469
3470                   elsif Present (Component_Clause (Comp)) then
3471
3472                      --  Diagnose duplicate rep clause, or check consistency
3473                      --  if this is an inherited component. In a double fault,
3474                      --  there may be a duplicate inconsistent clause for an
3475                      --  inherited component.
3476
3477                      if Scope (Original_Record_Component (Comp)) = Rectype
3478                        or else Parent (Component_Clause (Comp)) = N
3479                      then
3480                         Error_Msg_Sloc := Sloc (Component_Clause (Comp));
3481                         Error_Msg_N ("component clause previously given#", CC);
3482
3483                      else
3484                         declare
3485                            Rep1 : constant Node_Id := Component_Clause (Comp);
3486                         begin
3487                            if Intval (Position (Rep1)) /=
3488                                                    Intval (Position (CC))
3489                              or else Intval (First_Bit (Rep1)) /=
3490                                                    Intval (First_Bit (CC))
3491                              or else Intval (Last_Bit (Rep1)) /=
3492                                                    Intval (Last_Bit (CC))
3493                            then
3494                               Error_Msg_N ("component clause inconsistent "
3495                                 & "with representation of ancestor", CC);
3496                            elsif Warn_On_Redundant_Constructs then
3497                               Error_Msg_N ("?redundant component clause "
3498                                 & "for inherited component!", CC);
3499                            end if;
3500                         end;
3501                      end if;
3502
3503                   --  Normal case where this is the first component clause we
3504                   --  have seen for this entity, so set it up properly.
3505
3506                   else
3507                      --  Make reference for field in record rep clause and set
3508                      --  appropriate entity field in the field identifier.
3509
3510                      Generate_Reference
3511                        (Comp, Component_Name (CC), Set_Ref => False);
3512                      Set_Entity (Component_Name (CC), Comp);
3513
3514                      --  Update Fbit and Lbit to the actual bit number
3515
3516                      Fbit := Fbit + UI_From_Int (SSU) * Posit;
3517                      Lbit := Lbit + UI_From_Int (SSU) * Posit;
3518
3519                      if Has_Size_Clause (Rectype)
3520                        and then Esize (Rectype) <= Lbit
3521                      then
3522                         Error_Msg_N
3523                           ("bit number out of range of specified size",
3524                            Last_Bit (CC));
3525                      else
3526                         Set_Component_Clause     (Comp, CC);
3527                         Set_Component_Bit_Offset (Comp, Fbit);
3528                         Set_Esize                (Comp, 1 + (Lbit - Fbit));
3529                         Set_Normalized_First_Bit (Comp, Fbit mod SSU);
3530                         Set_Normalized_Position  (Comp, Fbit / SSU);
3531
3532                         if Warn_On_Overridden_Size
3533                           and then Has_Size_Clause (Etype (Comp))
3534                           and then RM_Size (Etype (Comp)) /= Esize (Comp)
3535                         then
3536                            Error_Msg_NE
3537                              ("?component size overrides size clause for&",
3538                               Component_Name (CC), Etype (Comp));
3539                         end if;
3540
3541                         --  This information is also set in the corresponding
3542                         --  component of the base type, found by accessing the
3543                         --  Original_Record_Component link if it is present.
3544
3545                         Ocomp := Original_Record_Component (Comp);
3546
3547                         if Hbit < Lbit then
3548                            Hbit := Lbit;
3549                         end if;
3550
3551                         Check_Size
3552                           (Component_Name (CC),
3553                            Etype (Comp),
3554                            Esize (Comp),
3555                            Biased);
3556
3557                         Set_Biased
3558                           (Comp, First_Node (CC), "component clause", Biased);
3559
3560                         if Present (Ocomp) then
3561                            Set_Component_Clause     (Ocomp, CC);
3562                            Set_Component_Bit_Offset (Ocomp, Fbit);
3563                            Set_Normalized_First_Bit (Ocomp, Fbit mod SSU);
3564                            Set_Normalized_Position  (Ocomp, Fbit / SSU);
3565                            Set_Esize                (Ocomp, 1 + (Lbit - Fbit));
3566
3567                            Set_Normalized_Position_Max
3568                              (Ocomp, Normalized_Position (Ocomp));
3569
3570                            --  Note: we don't use Set_Biased here, because we
3571                            --  already gave a warning above if needed, and we
3572                            --  would get a duplicate for the same name here.
3573
3574                            Set_Has_Biased_Representation
3575                              (Ocomp, Has_Biased_Representation (Comp));
3576                         end if;
3577
3578                         if Esize (Comp) < 0 then
3579                            Error_Msg_N ("component size is negative", CC);
3580                         end if;
3581                      end if;
3582                   end if;
3583                end if;
3584             end if;
3585          end if;
3586
3587          Next (CC);
3588       end loop;
3589
3590       --  Check missing components if Complete_Representation pragma appeared
3591
3592       if Present (CR_Pragma) then
3593          Comp := First_Component_Or_Discriminant (Rectype);
3594          while Present (Comp) loop
3595             if No (Component_Clause (Comp)) then
3596                Error_Msg_NE
3597                  ("missing component clause for &", CR_Pragma, Comp);
3598             end if;
3599
3600             Next_Component_Or_Discriminant (Comp);
3601          end loop;
3602
3603          --  If no Complete_Representation pragma, warn if missing components
3604
3605       elsif Warn_On_Unrepped_Components then
3606          declare
3607             Num_Repped_Components   : Nat := 0;
3608             Num_Unrepped_Components : Nat := 0;
3609
3610          begin
3611             --  First count number of repped and unrepped components
3612
3613             Comp := First_Component_Or_Discriminant (Rectype);
3614             while Present (Comp) loop
3615                if Present (Component_Clause (Comp)) then
3616                   Num_Repped_Components := Num_Repped_Components + 1;
3617                else
3618                   Num_Unrepped_Components := Num_Unrepped_Components + 1;
3619                end if;
3620
3621                Next_Component_Or_Discriminant (Comp);
3622             end loop;
3623
3624             --  We are only interested in the case where there is at least one
3625             --  unrepped component, and at least half the components have rep
3626             --  clauses. We figure that if less than half have them, then the
3627             --  partial rep clause is really intentional. If the component
3628             --  type has no underlying type set at this point (as for a generic
3629             --  formal type), we don't know enough to give a warning on the
3630             --  component.
3631
3632             if Num_Unrepped_Components > 0
3633               and then Num_Unrepped_Components < Num_Repped_Components
3634             then
3635                Comp := First_Component_Or_Discriminant (Rectype);
3636                while Present (Comp) loop
3637                   if No (Component_Clause (Comp))
3638                     and then Comes_From_Source (Comp)
3639                     and then Present (Underlying_Type (Etype (Comp)))
3640                     and then (Is_Scalar_Type (Underlying_Type (Etype (Comp)))
3641                                or else Size_Known_At_Compile_Time
3642                                          (Underlying_Type (Etype (Comp))))
3643                     and then not Has_Warnings_Off (Rectype)
3644                   then
3645                      Error_Msg_Sloc := Sloc (Comp);
3646                      Error_Msg_NE
3647                        ("?no component clause given for & declared #",
3648                         N, Comp);
3649                   end if;
3650
3651                   Next_Component_Or_Discriminant (Comp);
3652                end loop;
3653             end if;
3654          end;
3655       end if;
3656    end Analyze_Record_Representation_Clause;
3657
3658    -------------------------------
3659    -- Build_Invariant_Procedure --
3660    -------------------------------
3661
3662    --  The procedure that is constructed here has the form
3663
3664    --  procedure typInvariant (Ixxx : typ) is
3665    --  begin
3666    --     pragma Check (Invariant, exp, "failed invariant from xxx");
3667    --     pragma Check (Invariant, exp, "failed invariant from xxx");
3668    --     ...
3669    --     pragma Check (Invariant, exp, "failed inherited invariant from xxx");
3670    --     ...
3671    --  end typInvariant;
3672
3673    procedure Build_Invariant_Procedure (Typ : Entity_Id; N : Node_Id) is
3674       Loc   : constant Source_Ptr := Sloc (Typ);
3675       Stmts : List_Id;
3676       Spec  : Node_Id;
3677       SId   : Entity_Id;
3678       PDecl : Node_Id;
3679       PBody : Node_Id;
3680
3681       Visible_Decls : constant List_Id := Visible_Declarations (N);
3682       Private_Decls : constant List_Id := Private_Declarations (N);
3683
3684       procedure Add_Invariants (T : Entity_Id; Inherit : Boolean);
3685       --  Appends statements to Stmts for any invariants in the rep item chain
3686       --  of the given type. If Inherit is False, then we only process entries
3687       --  on the chain for the type Typ. If Inherit is True, then we ignore any
3688       --  Invariant aspects, but we process all Invariant'Class aspects, adding
3689       --  "inherited" to the exception message and generating an informational
3690       --  message about the inheritance of an invariant.
3691
3692       Object_Name : constant Name_Id := New_Internal_Name ('I');
3693       --  Name for argument of invariant procedure
3694
3695       Object_Entity : constant Node_Id :=
3696                         Make_Defining_Identifier (Loc, Object_Name);
3697       --  The procedure declaration entity for the argument
3698
3699       --------------------
3700       -- Add_Invariants --
3701       --------------------
3702
3703       procedure Add_Invariants (T : Entity_Id; Inherit : Boolean) is
3704          Ritem : Node_Id;
3705          Arg1  : Node_Id;
3706          Arg2  : Node_Id;
3707          Arg3  : Node_Id;
3708          Exp   : Node_Id;
3709          Loc   : Source_Ptr;
3710          Assoc : List_Id;
3711          Str   : String_Id;
3712
3713          procedure Replace_Type_Reference (N : Node_Id);
3714          --  Replace a single occurrence N of the subtype name with a reference
3715          --  to the formal of the predicate function. N can be an identifier
3716          --  referencing the subtype, or a selected component, representing an
3717          --  appropriately qualified occurrence of the subtype name.
3718
3719          procedure Replace_Type_References is
3720            new Replace_Type_References_Generic (Replace_Type_Reference);
3721          --  Traverse an expression replacing all occurrences of the subtype
3722          --  name with appropriate references to the object that is the formal
3723          --  parameter of the predicate function. Note that we must ensure
3724          --  that the type and entity information is properly set in the
3725          --  replacement node, since we will do a Preanalyze call of this
3726          --  expression without proper visibility of the procedure argument.
3727
3728          ----------------------------
3729          -- Replace_Type_Reference --
3730          ----------------------------
3731
3732          procedure Replace_Type_Reference (N : Node_Id) is
3733          begin
3734             --  Invariant'Class, replace with T'Class (obj)
3735
3736             if Class_Present (Ritem) then
3737                Rewrite (N,
3738                  Make_Type_Conversion (Loc,
3739                    Subtype_Mark =>
3740                      Make_Attribute_Reference (Loc,
3741                        Prefix         => New_Occurrence_Of (T, Loc),
3742                        Attribute_Name => Name_Class),
3743                    Expression   => Make_Identifier (Loc, Object_Name)));
3744
3745                Set_Entity (Expression (N), Object_Entity);
3746                Set_Etype  (Expression (N), Typ);
3747
3748             --  Invariant, replace with obj
3749
3750             else
3751                Rewrite (N, Make_Identifier (Loc, Object_Name));
3752                Set_Entity (N, Object_Entity);
3753                Set_Etype  (N, Typ);
3754             end if;
3755          end Replace_Type_Reference;
3756
3757       --  Start of processing for Add_Invariants
3758
3759       begin
3760          Ritem := First_Rep_Item (T);
3761          while Present (Ritem) loop
3762             if Nkind (Ritem) = N_Pragma
3763               and then Pragma_Name (Ritem) = Name_Invariant
3764             then
3765                Arg1 := First (Pragma_Argument_Associations (Ritem));
3766                Arg2 := Next (Arg1);
3767                Arg3 := Next (Arg2);
3768
3769                Arg1 := Get_Pragma_Arg (Arg1);
3770                Arg2 := Get_Pragma_Arg (Arg2);
3771
3772                --  For Inherit case, ignore Invariant, process only Class case
3773
3774                if Inherit then
3775                   if not Class_Present (Ritem) then
3776                      goto Continue;
3777                   end if;
3778
3779                --  For Inherit false, process only item for right type
3780
3781                else
3782                   if Entity (Arg1) /= Typ then
3783                      goto Continue;
3784                   end if;
3785                end if;
3786
3787                if No (Stmts) then
3788                   Stmts := Empty_List;
3789                end if;
3790
3791                Exp := New_Copy_Tree (Arg2);
3792                Loc := Sloc (Exp);
3793
3794                --  We need to replace any occurrences of the name of the type
3795                --  with references to the object, converted to type'Class in
3796                --  the case of Invariant'Class aspects.
3797
3798                Replace_Type_References (Exp, Chars (T));
3799
3800                --  If this invariant comes from an aspect, find the aspect
3801                --  specification, and replace the saved expression because
3802                --  we need the subtype references replaced for the calls to
3803                --  Preanalyze_Spec_Expressin in Check_Aspect_At_Freeze_Point
3804                --  and Check_Aspect_At_End_Of_Declarations.
3805
3806                if From_Aspect_Specification (Ritem) then
3807                   declare
3808                      Aitem : Node_Id;
3809
3810                   begin
3811                      --  Loop to find corresponding aspect, note that this
3812                      --  must be present given the pragma is marked delayed.
3813
3814                      Aitem := Next_Rep_Item (Ritem);
3815                      while Present (Aitem) loop
3816                         if Nkind (Aitem) = N_Aspect_Specification
3817                           and then Aspect_Rep_Item (Aitem) = Ritem
3818                         then
3819                            Set_Entity
3820                              (Identifier (Aitem), New_Copy_Tree (Exp));
3821                            exit;
3822                         end if;
3823
3824                         Aitem := Next_Rep_Item (Aitem);
3825                      end loop;
3826                   end;
3827                end if;
3828
3829                --  Now we need to preanalyze the expression to properly capture
3830                --  the visibility in the visible part. The expression will not
3831                --  be analyzed for real until the body is analyzed, but that is
3832                --  at the end of the private part and has the wrong visibility.
3833
3834                Set_Parent (Exp, N);
3835                Preanalyze_Spec_Expression (Exp, Standard_Boolean);
3836
3837                --  Build first two arguments for Check pragma
3838
3839                Assoc := New_List (
3840                  Make_Pragma_Argument_Association (Loc,
3841                    Expression => Make_Identifier (Loc, Name_Invariant)),
3842                  Make_Pragma_Argument_Association (Loc, Expression => Exp));
3843
3844                --  Add message if present in Invariant pragma
3845
3846                if Present (Arg3) then
3847                   Str := Strval (Get_Pragma_Arg (Arg3));
3848
3849                   --  If inherited case, and message starts "failed invariant",
3850                   --  change it to be "failed inherited invariant".
3851
3852                   if Inherit then
3853                      String_To_Name_Buffer (Str);
3854
3855                      if Name_Buffer (1 .. 16) = "failed invariant" then
3856                         Insert_Str_In_Name_Buffer ("inherited ", 8);
3857                         Str := String_From_Name_Buffer;
3858                      end if;
3859                   end if;
3860
3861                   Append_To (Assoc,
3862                     Make_Pragma_Argument_Association (Loc,
3863                       Expression => Make_String_Literal (Loc, Str)));
3864                end if;
3865
3866                --  Add Check pragma to list of statements
3867
3868                Append_To (Stmts,
3869                  Make_Pragma (Loc,
3870                    Pragma_Identifier            =>
3871                      Make_Identifier (Loc, Name_Check),
3872                    Pragma_Argument_Associations => Assoc));
3873
3874                --  If Inherited case and option enabled, output info msg. Note
3875                --  that we know this is a case of Invariant'Class.
3876
3877                if Inherit and Opt.List_Inherited_Aspects then
3878                   Error_Msg_Sloc := Sloc (Ritem);
3879                   Error_Msg_N
3880                     ("?info: & inherits `Invariant''Class` aspect from #",
3881                      Typ);
3882                end if;
3883             end if;
3884
3885          <<Continue>>
3886             Next_Rep_Item (Ritem);
3887          end loop;
3888       end Add_Invariants;
3889
3890    --  Start of processing for Build_Invariant_Procedure
3891
3892    begin
3893       Stmts := No_List;
3894       PDecl := Empty;
3895       PBody := Empty;
3896       Set_Etype (Object_Entity, Typ);
3897
3898       --  Add invariants for the current type
3899
3900       Add_Invariants (Typ, Inherit => False);
3901
3902       --  Add invariants for parent types
3903
3904       declare
3905          Current_Typ : Entity_Id;
3906          Parent_Typ  : Entity_Id;
3907
3908       begin
3909          Current_Typ := Typ;
3910          loop
3911             Parent_Typ := Etype (Current_Typ);
3912
3913             if Is_Private_Type (Parent_Typ)
3914               and then Present (Full_View (Base_Type (Parent_Typ)))
3915             then
3916                Parent_Typ := Full_View (Base_Type (Parent_Typ));
3917             end if;
3918
3919             exit when Parent_Typ = Current_Typ;
3920
3921             Current_Typ := Parent_Typ;
3922             Add_Invariants (Current_Typ, Inherit => True);
3923          end loop;
3924       end;
3925
3926       --  Build the procedure if we generated at least one Check pragma
3927
3928       if Stmts /= No_List then
3929
3930          --  Build procedure declaration
3931
3932          SId :=
3933            Make_Defining_Identifier (Loc,
3934              Chars => New_External_Name (Chars (Typ), "Invariant"));
3935          Set_Has_Invariants (SId);
3936          Set_Invariant_Procedure (Typ, SId);
3937
3938          Spec :=
3939            Make_Procedure_Specification (Loc,
3940              Defining_Unit_Name       => SId,
3941              Parameter_Specifications => New_List (
3942                Make_Parameter_Specification (Loc,
3943                  Defining_Identifier => Object_Entity,
3944                  Parameter_Type      => New_Occurrence_Of (Typ, Loc))));
3945
3946          PDecl := Make_Subprogram_Declaration (Loc, Specification => Spec);
3947
3948          --  Build procedure body
3949
3950          SId :=
3951            Make_Defining_Identifier (Loc,
3952              Chars => New_External_Name (Chars (Typ), "Invariant"));
3953
3954          Spec :=
3955            Make_Procedure_Specification (Loc,
3956              Defining_Unit_Name       => SId,
3957              Parameter_Specifications => New_List (
3958                Make_Parameter_Specification (Loc,
3959                  Defining_Identifier =>
3960                    Make_Defining_Identifier (Loc, Object_Name),
3961                  Parameter_Type => New_Occurrence_Of (Typ, Loc))));
3962
3963          PBody :=
3964            Make_Subprogram_Body (Loc,
3965              Specification              => Spec,
3966              Declarations               => Empty_List,
3967              Handled_Statement_Sequence =>
3968                Make_Handled_Sequence_Of_Statements (Loc,
3969                  Statements => Stmts));
3970
3971          --  Insert procedure declaration and spec at the appropriate points.
3972          --  Skip this if there are no private declarations (that's an error
3973          --  that will be diagnosed elsewhere, and there is no point in having
3974          --  an invariant procedure set if the full declaration is missing).
3975
3976          if Present (Private_Decls) then
3977
3978             --  The spec goes at the end of visible declarations, but they have
3979             --  already been analyzed, so we need to explicitly do the analyze.
3980
3981             Append_To (Visible_Decls, PDecl);
3982             Analyze (PDecl);
3983
3984             --  The body goes at the end of the private declarations, which we
3985             --  have not analyzed yet, so we do not need to perform an explicit
3986             --  analyze call. We skip this if there are no private declarations
3987             --  (this is an error that will be caught elsewhere);
3988
3989             Append_To (Private_Decls, PBody);
3990          end if;
3991       end if;
3992    end Build_Invariant_Procedure;
3993
3994    ------------------------------
3995    -- Build_Predicate_Function --
3996    ------------------------------
3997
3998    --  The procedure that is constructed here has the form
3999
4000    --  function typPredicate (Ixxx : typ) return Boolean is
4001    --  begin
4002    --     return
4003    --        exp1 and then exp2 and then ...
4004    --        and then typ1Predicate (typ1 (Ixxx))
4005    --        and then typ2Predicate (typ2 (Ixxx))
4006    --        and then ...;
4007    --  end typPredicate;
4008
4009    --  Here exp1, and exp2 are expressions from Predicate pragmas. Note that
4010    --  this is the point at which these expressions get analyzed, providing the
4011    --  required delay, and typ1, typ2, are entities from which predicates are
4012    --  inherited. Note that we do NOT generate Check pragmas, that's because we
4013    --  use this function even if checks are off, e.g. for membership tests.
4014
4015    procedure Build_Predicate_Function (Typ : Entity_Id; N : Node_Id) is
4016       Loc  : constant Source_Ptr := Sloc (Typ);
4017       Spec : Node_Id;
4018       SId  : Entity_Id;
4019       FDecl : Node_Id;
4020       FBody : Node_Id;
4021
4022       Expr : Node_Id;
4023       --  This is the expression for the return statement in the function. It
4024       --  is build by connecting the component predicates with AND THEN.
4025
4026       procedure Add_Call (T : Entity_Id);
4027       --  Includes a call to the predicate function for type T in Expr if T
4028       --  has predicates and Predicate_Function (T) is non-empty.
4029
4030       procedure Add_Predicates;
4031       --  Appends expressions for any Predicate pragmas in the rep item chain
4032       --  Typ to Expr. Note that we look only at items for this exact entity.
4033       --  Inheritance of predicates for the parent type is done by calling the
4034       --  Predicate_Function of the parent type, using Add_Call above.
4035
4036       Object_Name : constant Name_Id := New_Internal_Name ('I');
4037       --  Name for argument of Predicate procedure
4038
4039       Object_Entity : constant Entity_Id :=
4040                         Make_Defining_Identifier (Loc, Object_Name);
4041       --  The entity for the spec entity for the argument
4042
4043       Dynamic_Predicate_Present : Boolean := False;
4044       --  Set True if a dynamic predicate is present, results in the entire
4045       --  predicate being considered dynamic even if it looks static
4046
4047       Static_Predicate_Present : Node_Id := Empty;
4048       --  Set to N_Pragma node for a static predicate if one is encountered.
4049
4050       --------------
4051       -- Add_Call --
4052       --------------
4053
4054       procedure Add_Call (T : Entity_Id) is
4055          Exp : Node_Id;
4056
4057       begin
4058          if Present (T) and then Present (Predicate_Function (T)) then
4059             Set_Has_Predicates (Typ);
4060
4061             --  Build the call to the predicate function of T
4062
4063             Exp :=
4064               Make_Predicate_Call
4065                 (T, Convert_To (T, Make_Identifier (Loc, Object_Name)));
4066
4067             --  Add call to evolving expression, using AND THEN if needed
4068
4069             if No (Expr) then
4070                Expr := Exp;
4071             else
4072                Expr :=
4073                  Make_And_Then (Loc,
4074                    Left_Opnd  => Relocate_Node (Expr),
4075                    Right_Opnd => Exp);
4076             end if;
4077
4078             --  Output info message on inheritance if required. Note we do not
4079             --  give this information for generic actual types, since it is
4080             --  unwelcome noise in that case in instantiations. We also
4081             --  generally suppress the message in instantiations, and also
4082             --  if it involves internal names.
4083
4084             if Opt.List_Inherited_Aspects
4085               and then not Is_Generic_Actual_Type (Typ)
4086               and then Instantiation_Depth (Sloc (Typ)) = 0
4087               and then not Is_Internal_Name (Chars (T))
4088               and then not Is_Internal_Name (Chars (Typ))
4089             then
4090                Error_Msg_Sloc := Sloc (Predicate_Function (T));
4091                Error_Msg_Node_2 := T;
4092                Error_Msg_N ("?info: & inherits predicate from & #", Typ);
4093             end if;
4094          end if;
4095       end Add_Call;
4096
4097       --------------------
4098       -- Add_Predicates --
4099       --------------------
4100
4101       procedure Add_Predicates is
4102          Ritem : Node_Id;
4103          Arg1  : Node_Id;
4104          Arg2  : Node_Id;
4105
4106          procedure Replace_Type_Reference (N : Node_Id);
4107          --  Replace a single occurrence N of the subtype name with a reference
4108          --  to the formal of the predicate function. N can be an identifier
4109          --  referencing the subtype, or a selected component, representing an
4110          --  appropriately qualified occurrence of the subtype name.
4111
4112          procedure Replace_Type_References is
4113            new Replace_Type_References_Generic (Replace_Type_Reference);
4114          --  Traverse an expression changing every occurrence of an identifier
4115          --  whose name matches the name of the subtype with a reference to
4116          --  the formal parameter of the predicate function.
4117
4118          ----------------------------
4119          -- Replace_Type_Reference --
4120          ----------------------------
4121
4122          procedure Replace_Type_Reference (N : Node_Id) is
4123          begin
4124             Rewrite (N, Make_Identifier (Loc, Object_Name));
4125             Set_Entity (N, Object_Entity);
4126             Set_Etype (N, Typ);
4127          end Replace_Type_Reference;
4128
4129       --  Start of processing for Add_Predicates
4130
4131       begin
4132          Ritem := First_Rep_Item (Typ);
4133          while Present (Ritem) loop
4134             if Nkind (Ritem) = N_Pragma
4135               and then Pragma_Name (Ritem) = Name_Predicate
4136             then
4137                if From_Dynamic_Predicate (Ritem) then
4138                   Dynamic_Predicate_Present := True;
4139                elsif From_Static_Predicate (Ritem) then
4140                   Static_Predicate_Present := Ritem;
4141                end if;
4142
4143                --  Acquire arguments
4144
4145                Arg1 := First (Pragma_Argument_Associations (Ritem));
4146                Arg2 := Next (Arg1);
4147
4148                Arg1 := Get_Pragma_Arg (Arg1);
4149                Arg2 := Get_Pragma_Arg (Arg2);
4150
4151                --  See if this predicate pragma is for the current type
4152
4153                if Entity (Arg1) = Typ then
4154
4155                   --  We have a match, this entry is for our subtype
4156
4157                   --  We need to replace any occurrences of the name of the
4158                   --  type with references to the object.
4159
4160                   Replace_Type_References (Arg2, Chars (Typ));
4161
4162                   --  If this predicate comes from an aspect, find the aspect
4163                   --  specification, and replace the saved expression because
4164                   --  we need the subtype references replaced for the calls to
4165                   --  Preanalyze_Spec_Expressin in Check_Aspect_At_Freeze_Point
4166                   --  and Check_Aspect_At_End_Of_Declarations.
4167
4168                   if From_Aspect_Specification (Ritem) then
4169                      declare
4170                         Aitem : Node_Id;
4171
4172                      begin
4173                         --  Loop to find corresponding aspect, note that this
4174                         --  must be present given the pragma is marked delayed.
4175
4176                         Aitem := Next_Rep_Item (Ritem);
4177                         loop
4178                            if Nkind (Aitem) = N_Aspect_Specification
4179                              and then Aspect_Rep_Item (Aitem) = Ritem
4180                            then
4181                               Set_Entity
4182                                 (Identifier (Aitem), New_Copy_Tree (Arg2));
4183                               exit;
4184                            end if;
4185
4186                            Aitem := Next_Rep_Item (Aitem);
4187                         end loop;
4188                      end;
4189                   end if;
4190
4191                   --  Now we can add the expression
4192
4193                   if No (Expr) then
4194                      Expr := Relocate_Node (Arg2);
4195
4196                   --  There already was a predicate, so add to it
4197
4198                   else
4199                      Expr :=
4200                        Make_And_Then (Loc,
4201                          Left_Opnd  => Relocate_Node (Expr),
4202                          Right_Opnd => Relocate_Node (Arg2));
4203                   end if;
4204                end if;
4205             end if;
4206
4207             Next_Rep_Item (Ritem);
4208          end loop;
4209       end Add_Predicates;
4210
4211    --  Start of processing for Build_Predicate_Function
4212
4213    begin
4214       --  Initialize for construction of statement list
4215
4216       Expr := Empty;
4217
4218       --  Return if already built or if type does not have predicates
4219
4220       if not Has_Predicates (Typ)
4221         or else Present (Predicate_Function (Typ))
4222       then
4223          return;
4224       end if;
4225
4226       --  Add Predicates for the current type
4227
4228       Add_Predicates;
4229
4230       --  Add predicates for ancestor if present
4231
4232       declare
4233          Atyp : constant Entity_Id := Nearest_Ancestor (Typ);
4234       begin
4235          if Present (Atyp) then
4236             Add_Call (Atyp);
4237          end if;
4238       end;
4239
4240       --  If we have predicates, build the function
4241
4242       if Present (Expr) then
4243
4244          --  Build function declaration
4245
4246          pragma Assert (Has_Predicates (Typ));
4247          SId :=
4248            Make_Defining_Identifier (Loc,
4249              Chars => New_External_Name (Chars (Typ), "Predicate"));
4250          Set_Has_Predicates (SId);
4251          Set_Predicate_Function (Typ, SId);
4252
4253          Spec :=
4254            Make_Function_Specification (Loc,
4255              Defining_Unit_Name       => SId,
4256              Parameter_Specifications => New_List (
4257                Make_Parameter_Specification (Loc,
4258                  Defining_Identifier => Object_Entity,
4259                  Parameter_Type      => New_Occurrence_Of (Typ, Loc))),
4260              Result_Definition        =>
4261                New_Occurrence_Of (Standard_Boolean, Loc));
4262
4263          FDecl := Make_Subprogram_Declaration (Loc, Specification => Spec);
4264
4265          --  Build function body
4266
4267          SId :=
4268            Make_Defining_Identifier (Loc,
4269              Chars => New_External_Name (Chars (Typ), "Predicate"));
4270
4271          Spec :=
4272            Make_Function_Specification (Loc,
4273              Defining_Unit_Name       => SId,
4274              Parameter_Specifications => New_List (
4275                Make_Parameter_Specification (Loc,
4276                  Defining_Identifier =>
4277                    Make_Defining_Identifier (Loc, Object_Name),
4278                  Parameter_Type =>
4279                    New_Occurrence_Of (Typ, Loc))),
4280              Result_Definition        =>
4281                New_Occurrence_Of (Standard_Boolean, Loc));
4282
4283          FBody :=
4284            Make_Subprogram_Body (Loc,
4285              Specification              => Spec,
4286              Declarations               => Empty_List,
4287              Handled_Statement_Sequence =>
4288                Make_Handled_Sequence_Of_Statements (Loc,
4289                  Statements => New_List (
4290                    Make_Simple_Return_Statement (Loc,
4291                      Expression => Expr))));
4292
4293          --  Insert declaration before freeze node and body after
4294
4295          Insert_Before_And_Analyze (N, FDecl);
4296          Insert_After_And_Analyze  (N, FBody);
4297
4298          --  Deal with static predicate case
4299
4300          if Ekind_In (Typ, E_Enumeration_Subtype,
4301                            E_Modular_Integer_Subtype,
4302                            E_Signed_Integer_Subtype)
4303            and then Is_Static_Subtype (Typ)
4304            and then not Dynamic_Predicate_Present
4305          then
4306             Build_Static_Predicate (Typ, Expr, Object_Name);
4307
4308             if Present (Static_Predicate_Present)
4309               and No (Static_Predicate (Typ))
4310             then
4311                Error_Msg_F
4312                  ("expression does not have required form for "
4313                   & "static predicate",
4314                   Next (First (Pragma_Argument_Associations
4315                                 (Static_Predicate_Present))));
4316             end if;
4317          end if;
4318       end if;
4319    end Build_Predicate_Function;
4320
4321    ----------------------------
4322    -- Build_Static_Predicate --
4323    ----------------------------
4324
4325    procedure Build_Static_Predicate
4326      (Typ  : Entity_Id;
4327       Expr : Node_Id;
4328       Nam  : Name_Id)
4329    is
4330       Loc : constant Source_Ptr := Sloc (Expr);
4331
4332       Non_Static : exception;
4333       --  Raised if something non-static is found
4334
4335       Btyp : constant Entity_Id := Base_Type (Typ);
4336
4337       BLo : constant Uint := Expr_Value (Type_Low_Bound  (Btyp));
4338       BHi : constant Uint := Expr_Value (Type_High_Bound (Btyp));
4339       --  Low bound and high bound value of base type of Typ
4340
4341       TLo : constant Uint := Expr_Value (Type_Low_Bound  (Typ));
4342       THi : constant Uint := Expr_Value (Type_High_Bound (Typ));
4343       --  Low bound and high bound values of static subtype Typ
4344
4345       type REnt is record
4346          Lo, Hi : Uint;
4347       end record;
4348       --  One entry in a Rlist value, a single REnt (range entry) value
4349       --  denotes one range from Lo to Hi. To represent a single value
4350       --  range Lo = Hi = value.
4351
4352       type RList is array (Nat range <>) of REnt;
4353       --  A list of ranges. The ranges are sorted in increasing order,
4354       --  and are disjoint (there is a gap of at least one value between
4355       --  each range in the table). A value is in the set of ranges in
4356       --  Rlist if it lies within one of these ranges
4357
4358       False_Range : constant RList :=
4359                       RList'(1 .. 0 => REnt'(No_Uint, No_Uint));
4360       --  An empty set of ranges represents a range list that can never be
4361       --  satisfied, since there are no ranges in which the value could lie,
4362       --  so it does not lie in any of them. False_Range is a canonical value
4363       --  for this empty set, but general processing should test for an Rlist
4364       --  with length zero (see Is_False predicate), since other null ranges
4365       --  may appear which must be treated as False.
4366
4367       True_Range : constant RList := RList'(1 => REnt'(BLo, BHi));
4368       --  Range representing True, value must be in the base range
4369
4370       function "and" (Left, Right : RList) return RList;
4371       --  And's together two range lists, returning a range list. This is
4372       --  a set intersection operation.
4373
4374       function "or" (Left, Right : RList) return RList;
4375       --  Or's together two range lists, returning a range list. This is a
4376       --  set union operation.
4377
4378       function "not" (Right : RList) return RList;
4379       --  Returns complement of a given range list, i.e. a range list
4380       --  representing all the values in TLo .. THi that are not in the
4381       --  input operand Right.
4382
4383       function Build_Val (V : Uint) return Node_Id;
4384       --  Return an analyzed N_Identifier node referencing this value, suitable
4385       --  for use as an entry in the Static_Predicate list. This node is typed
4386       --  with the base type.
4387
4388       function Build_Range (Lo, Hi : Uint) return Node_Id;
4389       --  Return an analyzed N_Range node referencing this range, suitable
4390       --  for use as an entry in the Static_Predicate list. This node is typed
4391       --  with the base type.
4392
4393       function Get_RList (Exp : Node_Id) return RList;
4394       --  This is a recursive routine that converts the given expression into
4395       --  a list of ranges, suitable for use in building the static predicate.
4396
4397       function Is_False (R : RList) return Boolean;
4398       pragma Inline (Is_False);
4399       --  Returns True if the given range list is empty, and thus represents
4400       --  a False list of ranges that can never be satisfied.
4401
4402       function Is_True (R : RList) return Boolean;
4403       --  Returns True if R trivially represents the True predicate by having
4404       --  a single range from BLo to BHi.
4405
4406       function Is_Type_Ref (N : Node_Id) return Boolean;
4407       pragma Inline (Is_Type_Ref);
4408       --  Returns if True if N is a reference to the type for the predicate in
4409       --  the expression (i.e. if it is an identifier whose Chars field matches
4410       --  the Nam given in the call).
4411
4412       function Lo_Val (N : Node_Id) return Uint;
4413       --  Given static expression or static range from a Static_Predicate list,
4414       --  gets expression value or low bound of range.
4415
4416       function Hi_Val (N : Node_Id) return Uint;
4417       --  Given static expression or static range from a Static_Predicate list,
4418       --  gets expression value of high bound of range.
4419
4420       function Membership_Entry (N : Node_Id) return RList;
4421       --  Given a single membership entry (range, value, or subtype), returns
4422       --  the corresponding range list. Raises Static_Error if not static.
4423
4424       function Membership_Entries (N : Node_Id) return RList;
4425       --  Given an element on an alternatives list of a membership operation,
4426       --  returns the range list corresponding to this entry and all following
4427       --  entries (i.e. returns the "or" of this list of values).
4428
4429       function Stat_Pred (Typ : Entity_Id) return RList;
4430       --  Given a type, if it has a static predicate, then return the predicate
4431       --  as a range list, otherwise raise Non_Static.
4432
4433       -----------
4434       -- "and" --
4435       -----------
4436
4437       function "and" (Left, Right : RList) return RList is
4438          FEnt : REnt;
4439          --  First range of result
4440
4441          SLeft : Nat := Left'First;
4442          --  Start of rest of left entries
4443
4444          SRight : Nat := Right'First;
4445          --  Start of rest of right entries
4446
4447       begin
4448          --  If either range is True, return the other
4449
4450          if Is_True (Left) then
4451             return Right;
4452          elsif Is_True (Right) then
4453             return Left;
4454          end if;
4455
4456          --  If either range is False, return False
4457
4458          if Is_False (Left) or else Is_False (Right) then
4459             return False_Range;
4460          end if;
4461
4462          --  Loop to remove entries at start that are disjoint, and thus
4463          --  just get discarded from the result entirely.
4464
4465          loop
4466             --  If no operands left in either operand, result is false
4467
4468             if SLeft > Left'Last or else SRight > Right'Last then
4469                return False_Range;
4470
4471             --  Discard first left operand entry if disjoint with right
4472
4473             elsif Left (SLeft).Hi < Right (SRight).Lo then
4474                SLeft := SLeft + 1;
4475
4476             --  Discard first right operand entry if disjoint with left
4477
4478             elsif Right (SRight).Hi < Left (SLeft).Lo then
4479                SRight := SRight + 1;
4480
4481             --  Otherwise we have an overlapping entry
4482
4483             else
4484                exit;
4485             end if;
4486          end loop;
4487
4488          --  Now we have two non-null operands, and first entries overlap.
4489          --  The first entry in the result will be the overlapping part of
4490          --  these two entries.
4491
4492          FEnt := REnt'(Lo => UI_Max (Left (SLeft).Lo, Right (SRight).Lo),
4493                        Hi => UI_Min (Left (SLeft).Hi, Right (SRight).Hi));
4494
4495          --  Now we can remove the entry that ended at a lower value, since
4496          --  its contribution is entirely contained in Fent.
4497
4498          if Left (SLeft).Hi <= Right (SRight).Hi then
4499             SLeft := SLeft + 1;
4500          else
4501             SRight := SRight + 1;
4502          end if;
4503
4504          --  Compute result by concatenating this first entry with the "and"
4505          --  of the remaining parts of the left and right operands. Note that
4506          --  if either of these is empty, "and" will yield empty, so that we
4507          --  will end up with just Fent, which is what we want in that case.
4508
4509          return
4510            FEnt & (Left (SLeft .. Left'Last) and Right (SRight .. Right'Last));
4511       end "and";
4512
4513       -----------
4514       -- "not" --
4515       -----------
4516
4517       function "not" (Right : RList) return RList is
4518       begin
4519          --  Return True if False range
4520
4521          if Is_False (Right) then
4522             return True_Range;
4523          end if;
4524
4525          --  Return False if True range
4526
4527          if Is_True (Right) then
4528             return False_Range;
4529          end if;
4530
4531          --  Here if not trivial case
4532
4533          declare
4534             Result : RList (1 .. Right'Length + 1);
4535             --  May need one more entry for gap at beginning and end
4536
4537             Count : Nat := 0;
4538             --  Number of entries stored in Result
4539
4540          begin
4541             --  Gap at start
4542
4543             if Right (Right'First).Lo > TLo then
4544                Count := Count + 1;
4545                Result (Count) := REnt'(TLo, Right (Right'First).Lo - 1);
4546             end if;
4547
4548             --  Gaps between ranges
4549
4550             for J in Right'First .. Right'Last - 1 loop
4551                Count := Count + 1;
4552                Result (Count) :=
4553                  REnt'(Right (J).Hi + 1, Right (J + 1).Lo - 1);
4554             end loop;
4555
4556             --  Gap at end
4557
4558             if Right (Right'Last).Hi < THi then
4559                Count := Count + 1;
4560                Result (Count) := REnt'(Right (Right'Last).Hi + 1, THi);
4561             end if;
4562
4563             return Result (1 .. Count);
4564          end;
4565       end "not";
4566
4567       ----------
4568       -- "or" --
4569       ----------
4570
4571       function "or" (Left, Right : RList) return RList is
4572          FEnt : REnt;
4573          --  First range of result
4574
4575          SLeft : Nat := Left'First;
4576          --  Start of rest of left entries
4577
4578          SRight : Nat := Right'First;
4579          --  Start of rest of right entries
4580
4581       begin
4582          --  If either range is True, return True
4583
4584          if Is_True (Left) or else Is_True (Right) then
4585             return True_Range;
4586          end if;
4587
4588          --  If either range is False (empty), return the other
4589
4590          if Is_False (Left) then
4591             return Right;
4592          elsif Is_False (Right) then
4593             return Left;
4594          end if;
4595
4596          --  Initialize result first entry from left or right operand
4597          --  depending on which starts with the lower range.
4598
4599          if Left (SLeft).Lo < Right (SRight).Lo then
4600             FEnt := Left (SLeft);
4601             SLeft := SLeft + 1;
4602          else
4603             FEnt := Right (SRight);
4604             SRight := SRight + 1;
4605          end if;
4606
4607          --  This loop eats ranges from left and right operands that
4608          --  are contiguous with the first range we are gathering.
4609
4610          loop
4611             --  Eat first entry in left operand if contiguous or
4612             --  overlapped by gathered first operand of result.
4613
4614             if SLeft <= Left'Last
4615               and then Left (SLeft).Lo <= FEnt.Hi + 1
4616             then
4617                FEnt.Hi := UI_Max (FEnt.Hi, Left (SLeft).Hi);
4618                SLeft := SLeft + 1;
4619
4620                --  Eat first entry in right operand if contiguous or
4621                --  overlapped by gathered right operand of result.
4622
4623             elsif SRight <= Right'Last
4624               and then Right (SRight).Lo <= FEnt.Hi + 1
4625             then
4626                FEnt.Hi := UI_Max (FEnt.Hi, Right (SRight).Hi);
4627                SRight := SRight + 1;
4628
4629                --  All done if no more entries to eat!
4630
4631             else
4632                exit;
4633             end if;
4634          end loop;
4635
4636          --  Obtain result as the first entry we just computed, concatenated
4637          --  to the "or" of the remaining results (if one operand is empty,
4638          --  this will just concatenate with the other
4639
4640          return
4641            FEnt & (Left (SLeft .. Left'Last) or Right (SRight .. Right'Last));
4642       end "or";
4643
4644       -----------------
4645       -- Build_Range --
4646       -----------------
4647
4648       function Build_Range (Lo, Hi : Uint) return Node_Id is
4649          Result : Node_Id;
4650       begin
4651          if Lo = Hi then
4652             return Build_Val (Hi);
4653          else
4654             Result :=
4655               Make_Range (Loc,
4656                 Low_Bound  => Build_Val (Lo),
4657                 High_Bound => Build_Val (Hi));
4658             Set_Etype (Result, Btyp);
4659             Set_Analyzed (Result);
4660             return Result;
4661          end if;
4662       end Build_Range;
4663
4664       ---------------
4665       -- Build_Val --
4666       ---------------
4667
4668       function Build_Val (V : Uint) return Node_Id is
4669          Result : Node_Id;
4670
4671       begin
4672          if Is_Enumeration_Type (Typ) then
4673             Result := Get_Enum_Lit_From_Pos (Typ, V, Loc);
4674          else
4675             Result := Make_Integer_Literal (Loc, V);
4676          end if;
4677
4678          Set_Etype (Result, Btyp);
4679          Set_Is_Static_Expression (Result);
4680          Set_Analyzed (Result);
4681          return Result;
4682       end Build_Val;
4683
4684       ---------------
4685       -- Get_RList --
4686       ---------------
4687
4688       function Get_RList (Exp : Node_Id) return RList is
4689          Op  : Node_Kind;
4690          Val : Uint;
4691
4692       begin
4693          --  Static expression can only be true or false
4694
4695          if Is_OK_Static_Expression (Exp) then
4696
4697             --  For False
4698
4699             if Expr_Value (Exp) = 0 then
4700                return False_Range;
4701             else
4702                return True_Range;
4703             end if;
4704          end if;
4705
4706          --  Otherwise test node type
4707
4708          Op := Nkind (Exp);
4709
4710          case Op is
4711
4712             --  And
4713
4714             when N_Op_And | N_And_Then =>
4715                return Get_RList (Left_Opnd (Exp))
4716                         and
4717                       Get_RList (Right_Opnd (Exp));
4718
4719             --  Or
4720
4721             when N_Op_Or | N_Or_Else =>
4722                return Get_RList (Left_Opnd (Exp))
4723                         or
4724                       Get_RList (Right_Opnd (Exp));
4725
4726             --  Not
4727
4728             when N_Op_Not =>
4729                return not Get_RList (Right_Opnd (Exp));
4730
4731             --  Comparisons of type with static value
4732
4733             when N_Op_Compare =>
4734                --  Type is left operand
4735
4736                if Is_Type_Ref (Left_Opnd (Exp))
4737                  and then Is_OK_Static_Expression (Right_Opnd (Exp))
4738                then
4739                   Val := Expr_Value (Right_Opnd (Exp));
4740
4741                   --  Typ is right operand
4742
4743                elsif Is_Type_Ref (Right_Opnd (Exp))
4744                  and then Is_OK_Static_Expression (Left_Opnd (Exp))
4745                then
4746                   Val := Expr_Value (Left_Opnd (Exp));
4747
4748                   --  Invert sense of comparison
4749
4750                   case Op is
4751                      when N_Op_Gt => Op := N_Op_Lt;
4752                      when N_Op_Lt => Op := N_Op_Gt;
4753                      when N_Op_Ge => Op := N_Op_Le;
4754                      when N_Op_Le => Op := N_Op_Ge;
4755                      when others  => null;
4756                   end case;
4757
4758                   --  Other cases are non-static
4759
4760                else
4761                   raise Non_Static;
4762                end if;
4763
4764                --  Construct range according to comparison operation
4765
4766                case Op is
4767                   when N_Op_Eq =>
4768                      return RList'(1 => REnt'(Val, Val));
4769
4770                   when N_Op_Ge =>
4771                      return RList'(1 => REnt'(Val, BHi));
4772
4773                   when N_Op_Gt =>
4774                      return RList'(1 => REnt'(Val + 1, BHi));
4775
4776                   when N_Op_Le =>
4777                      return RList'(1 => REnt'(BLo, Val));
4778
4779                   when N_Op_Lt =>
4780                      return RList'(1 => REnt'(BLo, Val - 1));
4781
4782                   when N_Op_Ne =>
4783                      return RList'(REnt'(BLo, Val - 1),
4784                                    REnt'(Val + 1, BHi));
4785
4786                   when others  =>
4787                      raise Program_Error;
4788                end case;
4789
4790             --  Membership (IN)
4791
4792             when N_In =>
4793                if not Is_Type_Ref (Left_Opnd (Exp)) then
4794                   raise Non_Static;
4795                end if;
4796
4797                if Present (Right_Opnd (Exp)) then
4798                   return Membership_Entry (Right_Opnd (Exp));
4799                else
4800                   return Membership_Entries (First (Alternatives (Exp)));
4801                end if;
4802
4803             --  Negative membership (NOT IN)
4804
4805             when N_Not_In =>
4806                if not Is_Type_Ref (Left_Opnd (Exp)) then
4807                   raise Non_Static;
4808                end if;
4809
4810                if Present (Right_Opnd (Exp)) then
4811                   return not Membership_Entry (Right_Opnd (Exp));
4812                else
4813                   return not Membership_Entries (First (Alternatives (Exp)));
4814                end if;
4815
4816             --  Function call, may be call to static predicate
4817
4818             when N_Function_Call =>
4819                if Is_Entity_Name (Name (Exp)) then
4820                   declare
4821                      Ent : constant Entity_Id := Entity (Name (Exp));
4822                   begin
4823                      if Has_Predicates (Ent) then
4824                         return Stat_Pred (Etype (First_Formal (Ent)));
4825                      end if;
4826                   end;
4827                end if;
4828
4829                --  Other function call cases are non-static
4830
4831                raise Non_Static;
4832
4833             --  Qualified expression, dig out the expression
4834
4835             when N_Qualified_Expression =>
4836                return Get_RList (Expression (Exp));
4837
4838             --  Xor operator
4839
4840             when N_Op_Xor =>
4841                return (Get_RList (Left_Opnd (Exp))
4842                         and not Get_RList (Right_Opnd (Exp)))
4843                  or   (Get_RList (Right_Opnd (Exp))
4844                         and not Get_RList (Left_Opnd (Exp)));
4845
4846             --  Any other node type is non-static
4847
4848             when others =>
4849                raise Non_Static;
4850          end case;
4851       end Get_RList;
4852
4853       ------------
4854       -- Hi_Val --
4855       ------------
4856
4857       function Hi_Val (N : Node_Id) return Uint is
4858       begin
4859          if Is_Static_Expression (N) then
4860             return Expr_Value (N);
4861          else
4862             pragma Assert (Nkind (N) = N_Range);
4863             return Expr_Value (High_Bound (N));
4864          end if;
4865       end Hi_Val;
4866
4867       --------------
4868       -- Is_False --
4869       --------------
4870
4871       function Is_False (R : RList) return Boolean is
4872       begin
4873          return R'Length = 0;
4874       end Is_False;
4875
4876       -------------
4877       -- Is_True --
4878       -------------
4879
4880       function Is_True (R : RList) return Boolean is
4881       begin
4882          return R'Length = 1
4883            and then R (R'First).Lo = BLo
4884            and then R (R'First).Hi = BHi;
4885       end Is_True;
4886
4887       -----------------
4888       -- Is_Type_Ref --
4889       -----------------
4890
4891       function Is_Type_Ref (N : Node_Id) return Boolean is
4892       begin
4893          return Nkind (N) = N_Identifier and then Chars (N) = Nam;
4894       end Is_Type_Ref;
4895
4896       ------------
4897       -- Lo_Val --
4898       ------------
4899
4900       function Lo_Val (N : Node_Id) return Uint is
4901       begin
4902          if Is_Static_Expression (N) then
4903             return Expr_Value (N);
4904          else
4905             pragma Assert (Nkind (N) = N_Range);
4906             return Expr_Value (Low_Bound (N));
4907          end if;
4908       end Lo_Val;
4909
4910       ------------------------
4911       -- Membership_Entries --
4912       ------------------------
4913
4914       function Membership_Entries (N : Node_Id) return RList is
4915       begin
4916          if No (Next (N)) then
4917             return Membership_Entry (N);
4918          else
4919             return Membership_Entry (N) or Membership_Entries (Next (N));
4920          end if;
4921       end Membership_Entries;
4922
4923       ----------------------
4924       -- Membership_Entry --
4925       ----------------------
4926
4927       function Membership_Entry (N : Node_Id) return RList is
4928          Val : Uint;
4929          SLo : Uint;
4930          SHi : Uint;
4931
4932       begin
4933          --  Range case
4934
4935          if Nkind (N) = N_Range then
4936             if not Is_Static_Expression (Low_Bound (N))
4937                  or else
4938                not Is_Static_Expression (High_Bound (N))
4939             then
4940                raise Non_Static;
4941             else
4942                SLo := Expr_Value (Low_Bound  (N));
4943                SHi := Expr_Value (High_Bound (N));
4944                return RList'(1 => REnt'(SLo, SHi));
4945             end if;
4946
4947          --  Static expression case
4948
4949          elsif Is_Static_Expression (N) then
4950             Val := Expr_Value (N);
4951             return RList'(1 => REnt'(Val, Val));
4952
4953          --  Identifier (other than static expression) case
4954
4955          else pragma Assert (Nkind (N) = N_Identifier);
4956
4957             --  Type case
4958
4959             if Is_Type (Entity (N)) then
4960
4961                --  If type has predicates, process them
4962
4963                if Has_Predicates (Entity (N)) then
4964                   return Stat_Pred (Entity (N));
4965
4966                --  For static subtype without predicates, get range
4967
4968                elsif Is_Static_Subtype (Entity (N)) then
4969                   SLo := Expr_Value (Type_Low_Bound  (Entity (N)));
4970                   SHi := Expr_Value (Type_High_Bound (Entity (N)));
4971                   return RList'(1 => REnt'(SLo, SHi));
4972
4973                --  Any other type makes us non-static
4974
4975                else
4976                   raise Non_Static;
4977                end if;
4978
4979             --  Any other kind of identifier in predicate (e.g. a non-static
4980             --  expression value) means this is not a static predicate.
4981
4982             else
4983                raise Non_Static;
4984             end if;
4985          end if;
4986       end Membership_Entry;
4987
4988       ---------------
4989       -- Stat_Pred --
4990       ---------------
4991
4992       function Stat_Pred (Typ : Entity_Id) return RList is
4993       begin
4994          --  Not static if type does not have static predicates
4995
4996          if not Has_Predicates (Typ)
4997            or else No (Static_Predicate (Typ))
4998          then
4999             raise Non_Static;
5000          end if;
5001
5002          --  Otherwise we convert the predicate list to a range list
5003
5004          declare
5005             Result : RList (1 .. List_Length (Static_Predicate (Typ)));
5006             P      : Node_Id;
5007
5008          begin
5009             P := First (Static_Predicate (Typ));
5010             for J in Result'Range loop
5011                Result (J) := REnt'(Lo_Val (P), Hi_Val (P));
5012                Next (P);
5013             end loop;
5014
5015             return Result;
5016          end;
5017       end Stat_Pred;
5018
5019    --  Start of processing for Build_Static_Predicate
5020
5021    begin
5022       --  Now analyze the expression to see if it is a static predicate
5023
5024       declare
5025          Ranges : constant RList := Get_RList (Expr);
5026          --  Range list from expression if it is static
5027
5028          Plist : List_Id;
5029
5030       begin
5031          --  Convert range list into a form for the static predicate. In the
5032          --  Ranges array, we just have raw ranges, these must be converted
5033          --  to properly typed and analyzed static expressions or range nodes.
5034
5035          --  Note: here we limit ranges to the ranges of the subtype, so that
5036          --  a predicate is always false for values outside the subtype. That
5037          --  seems fine, such values are invalid anyway, and considering them
5038          --  to fail the predicate seems allowed and friendly, and furthermore
5039          --  simplifies processing for case statements and loops.
5040
5041          Plist := New_List;
5042
5043          for J in Ranges'Range loop
5044             declare
5045                Lo : Uint := Ranges (J).Lo;
5046                Hi : Uint := Ranges (J).Hi;
5047
5048             begin
5049                --  Ignore completely out of range entry
5050
5051                if Hi < TLo or else Lo > THi then
5052                   null;
5053
5054                   --  Otherwise process entry
5055
5056                else
5057                   --  Adjust out of range value to subtype range
5058
5059                   if Lo < TLo then
5060                      Lo := TLo;
5061                   end if;
5062
5063                   if Hi > THi then
5064                      Hi := THi;
5065                   end if;
5066
5067                   --  Convert range into required form
5068
5069                   if Lo = Hi then
5070                      Append_To (Plist, Build_Val (Lo));
5071                   else
5072                      Append_To (Plist, Build_Range (Lo, Hi));
5073                   end if;
5074                end if;
5075             end;
5076          end loop;
5077
5078          --  Processing was successful and all entries were static, so now we
5079          --  can store the result as the predicate list.
5080
5081          Set_Static_Predicate (Typ, Plist);
5082
5083          --  The processing for static predicates put the expression into
5084          --  canonical form as a series of ranges. It also eliminated
5085          --  duplicates and collapsed and combined ranges. We might as well
5086          --  replace the alternatives list of the right operand of the
5087          --  membership test with the static predicate list, which will
5088          --  usually be more efficient.
5089
5090          declare
5091             New_Alts : constant List_Id := New_List;
5092             Old_Node : Node_Id;
5093             New_Node : Node_Id;
5094
5095          begin
5096             Old_Node := First (Plist);
5097             while Present (Old_Node) loop
5098                New_Node := New_Copy (Old_Node);
5099
5100                if Nkind (New_Node) = N_Range then
5101                   Set_Low_Bound  (New_Node, New_Copy (Low_Bound  (Old_Node)));
5102                   Set_High_Bound (New_Node, New_Copy (High_Bound (Old_Node)));
5103                end if;
5104
5105                Append_To (New_Alts, New_Node);
5106                Next (Old_Node);
5107             end loop;
5108
5109             --  If empty list, replace by False
5110
5111             if Is_Empty_List (New_Alts) then
5112                Rewrite (Expr, New_Occurrence_Of (Standard_False, Loc));
5113
5114             --  Else replace by set membership test
5115
5116             else
5117                Rewrite (Expr,
5118                  Make_In (Loc,
5119                    Left_Opnd    => Make_Identifier (Loc, Nam),
5120                    Right_Opnd   => Empty,
5121                    Alternatives => New_Alts));
5122
5123                --  Resolve new expression in function context
5124
5125                Install_Formals (Predicate_Function (Typ));
5126                Push_Scope (Predicate_Function (Typ));
5127                Analyze_And_Resolve (Expr, Standard_Boolean);
5128                Pop_Scope;
5129             end if;
5130          end;
5131       end;
5132
5133    --  If non-static, return doing nothing
5134
5135    exception
5136       when Non_Static =>
5137          return;
5138    end Build_Static_Predicate;
5139
5140    -----------------------------------------
5141    -- Check_Aspect_At_End_Of_Declarations --
5142    -----------------------------------------
5143
5144    procedure Check_Aspect_At_End_Of_Declarations (ASN : Node_Id) is
5145       Ent   : constant Entity_Id := Entity     (ASN);
5146       Ident : constant Node_Id   := Identifier (ASN);
5147
5148       Freeze_Expr : constant Node_Id := Expression (ASN);
5149       --  Preanalyzed expression from call to Check_Aspect_At_Freeze_Point
5150
5151       End_Decl_Expr : constant Node_Id := Entity (Ident);
5152       --  Expression to be analyzed at end of declarations
5153
5154       T : constant Entity_Id := Etype (Freeze_Expr);
5155       --  Type required for preanalyze call
5156
5157       A_Id : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
5158
5159       Err : Boolean;
5160       --  Set False if error
5161
5162       --  On entry to this procedure, Entity (Ident) contains a copy of the
5163       --  original expression from the aspect, saved for this purpose, and
5164       --  but Expression (Ident) is a preanalyzed copy of the expression,
5165       --  preanalyzed just after the freeze point.
5166
5167    begin
5168       --  Case of stream attributes, just have to compare entities
5169
5170       if A_Id = Aspect_Input  or else
5171          A_Id = Aspect_Output or else
5172          A_Id = Aspect_Read   or else
5173          A_Id = Aspect_Write
5174       then
5175          Analyze (End_Decl_Expr);
5176          Err := Entity (End_Decl_Expr) /= Entity (Freeze_Expr);
5177
5178       --  All other cases
5179
5180       else
5181          Preanalyze_Spec_Expression (End_Decl_Expr, T);
5182          Err := not Fully_Conformant_Expressions (End_Decl_Expr, Freeze_Expr);
5183       end if;
5184
5185       --  Output error message if error
5186
5187       if Err then
5188          Error_Msg_NE
5189            ("visibility of aspect for& changes after freeze point",
5190             ASN, Ent);
5191          Error_Msg_NE
5192            ("?info: & is frozen here, aspects evaluated at this point",
5193             Freeze_Node (Ent), Ent);
5194       end if;
5195    end Check_Aspect_At_End_Of_Declarations;
5196
5197    ----------------------------------
5198    -- Check_Aspect_At_Freeze_Point --
5199    ----------------------------------
5200
5201    procedure Check_Aspect_At_Freeze_Point (ASN : Node_Id) is
5202       Ident : constant Node_Id := Identifier (ASN);
5203       --  Identifier (use Entity field to save expression)
5204
5205       T : Entity_Id;
5206       --  Type required for preanalyze call
5207
5208       A_Id : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
5209
5210    begin
5211       --  On entry to this procedure, Entity (Ident) contains a copy of the
5212       --  original expression from the aspect, saved for this purpose.
5213
5214       --  On exit from this procedure Entity (Ident) is unchanged, still
5215       --  containing that copy, but Expression (Ident) is a preanalyzed copy
5216       --  of the expression, preanalyzed just after the freeze point.
5217
5218       --  Make a copy of the expression to be preanalyed
5219
5220       Set_Expression (ASN, New_Copy_Tree (Entity (Ident)));
5221
5222       --  Find type for preanalyze call
5223
5224       case A_Id is
5225
5226          --  No_Aspect should be impossible
5227
5228          when No_Aspect =>
5229             raise Program_Error;
5230
5231          --  Library unit aspects should be impossible (never delayed)
5232
5233          when Library_Unit_Aspects =>
5234             raise Program_Error;
5235
5236          --  Aspects taking an optional boolean argument. Should be impossible
5237          --  since these are never delayed.
5238
5239          when Boolean_Aspects =>
5240             raise Program_Error;
5241
5242          --  Default_Value is resolved with the type entity in question
5243
5244          when Aspect_Default_Value =>
5245             T := Entity (ASN);
5246
5247          --  Default_Component_Value is resolved with the component type
5248
5249          when Aspect_Default_Component_Value =>
5250             T := Component_Type (Entity (ASN));
5251
5252          --  Aspects corresponding to attribute definition clauses
5253
5254          when Aspect_Address =>
5255             T := RTE (RE_Address);
5256
5257          when Aspect_Bit_Order =>
5258             T := RTE (RE_Bit_Order);
5259
5260          when Aspect_External_Tag =>
5261             T := Standard_String;
5262
5263          when Aspect_Storage_Pool =>
5264             T := Class_Wide_Type (RTE (RE_Root_Storage_Pool));
5265
5266          when
5267               Aspect_Alignment      |
5268               Aspect_Component_Size |
5269               Aspect_Machine_Radix  |
5270               Aspect_Object_Size    |
5271               Aspect_Size           |
5272               Aspect_Storage_Size   |
5273               Aspect_Stream_Size    |
5274               Aspect_Value_Size     =>
5275             T := Any_Integer;
5276
5277          --  Stream attribute. Special case, the expression is just an entity
5278          --  that does not need any resolution, so just analyze.
5279
5280          when Aspect_Input  |
5281               Aspect_Output |
5282               Aspect_Read   |
5283               Aspect_Write  =>
5284             Analyze (Expression (ASN));
5285             return;
5286
5287          --  Suppress/Unsupress/Warnings should never be delayed
5288
5289          when Aspect_Suppress   |
5290               Aspect_Unsuppress |
5291               Aspect_Warnings   =>
5292             raise Program_Error;
5293
5294          --  Pre/Post/Invariant/Predicate take boolean expressions
5295
5296          when Aspect_Dynamic_Predicate |
5297               Aspect_Invariant         |
5298               Aspect_Pre               |
5299               Aspect_Precondition      |
5300               Aspect_Post              |
5301               Aspect_Postcondition     |
5302               Aspect_Predicate         |
5303               Aspect_Static_Predicate  |
5304               Aspect_Type_Invariant    =>
5305             T := Standard_Boolean;
5306       end case;
5307
5308       --  Do the preanalyze call
5309
5310       Preanalyze_Spec_Expression (Expression (ASN), T);
5311    end Check_Aspect_At_Freeze_Point;
5312
5313    -----------------------------------
5314    -- Check_Constant_Address_Clause --
5315    -----------------------------------
5316
5317    procedure Check_Constant_Address_Clause
5318      (Expr  : Node_Id;
5319       U_Ent : Entity_Id)
5320    is
5321       procedure Check_At_Constant_Address (Nod : Node_Id);
5322       --  Checks that the given node N represents a name whose 'Address is
5323       --  constant (in the same sense as OK_Constant_Address_Clause, i.e. the
5324       --  address value is the same at the point of declaration of U_Ent and at
5325       --  the time of elaboration of the address clause.
5326
5327       procedure Check_Expr_Constants (Nod : Node_Id);
5328       --  Checks that Nod meets the requirements for a constant address clause
5329       --  in the sense of the enclosing procedure.
5330
5331       procedure Check_List_Constants (Lst : List_Id);
5332       --  Check that all elements of list Lst meet the requirements for a
5333       --  constant address clause in the sense of the enclosing procedure.
5334
5335       -------------------------------
5336       -- Check_At_Constant_Address --
5337       -------------------------------
5338
5339       procedure Check_At_Constant_Address (Nod : Node_Id) is
5340       begin
5341          if Is_Entity_Name (Nod) then
5342             if Present (Address_Clause (Entity ((Nod)))) then
5343                Error_Msg_NE
5344                  ("invalid address clause for initialized object &!",
5345                            Nod, U_Ent);
5346                Error_Msg_NE
5347                  ("address for& cannot" &
5348                     " depend on another address clause! (RM 13.1(22))!",
5349                   Nod, U_Ent);
5350
5351             elsif In_Same_Source_Unit (Entity (Nod), U_Ent)
5352               and then Sloc (U_Ent) < Sloc (Entity (Nod))
5353             then
5354                Error_Msg_NE
5355                  ("invalid address clause for initialized object &!",
5356                   Nod, U_Ent);
5357                Error_Msg_Node_2 := U_Ent;
5358                Error_Msg_NE
5359                  ("\& must be defined before & (RM 13.1(22))!",
5360                   Nod, Entity (Nod));
5361             end if;
5362
5363          elsif Nkind (Nod) = N_Selected_Component then
5364             declare
5365                T : constant Entity_Id := Etype (Prefix (Nod));
5366
5367             begin
5368                if (Is_Record_Type (T)
5369                     and then Has_Discriminants (T))
5370                  or else
5371                   (Is_Access_Type (T)
5372                      and then Is_Record_Type (Designated_Type (T))
5373                      and then Has_Discriminants (Designated_Type (T)))
5374                then
5375                   Error_Msg_NE
5376                     ("invalid address clause for initialized object &!",
5377                      Nod, U_Ent);
5378                   Error_Msg_N
5379                     ("\address cannot depend on component" &
5380                      " of discriminated record (RM 13.1(22))!",
5381                      Nod);
5382                else
5383                   Check_At_Constant_Address (Prefix (Nod));
5384                end if;
5385             end;
5386
5387          elsif Nkind (Nod) = N_Indexed_Component then
5388             Check_At_Constant_Address (Prefix (Nod));
5389             Check_List_Constants (Expressions (Nod));
5390
5391          else
5392             Check_Expr_Constants (Nod);
5393          end if;
5394       end Check_At_Constant_Address;
5395
5396       --------------------------
5397       -- Check_Expr_Constants --
5398       --------------------------
5399
5400       procedure Check_Expr_Constants (Nod : Node_Id) is
5401          Loc_U_Ent : constant Source_Ptr := Sloc (U_Ent);
5402          Ent       : Entity_Id           := Empty;
5403
5404       begin
5405          if Nkind (Nod) in N_Has_Etype
5406            and then Etype (Nod) = Any_Type
5407          then
5408             return;
5409          end if;
5410
5411          case Nkind (Nod) is
5412             when N_Empty | N_Error =>
5413                return;
5414
5415             when N_Identifier | N_Expanded_Name =>
5416                Ent := Entity (Nod);
5417
5418                --  We need to look at the original node if it is different
5419                --  from the node, since we may have rewritten things and
5420                --  substituted an identifier representing the rewrite.
5421
5422                if Original_Node (Nod) /= Nod then
5423                   Check_Expr_Constants (Original_Node (Nod));
5424
5425                   --  If the node is an object declaration without initial
5426                   --  value, some code has been expanded, and the expression
5427                   --  is not constant, even if the constituents might be
5428                   --  acceptable, as in A'Address + offset.
5429
5430                   if Ekind (Ent) = E_Variable
5431                     and then
5432                       Nkind (Declaration_Node (Ent)) = N_Object_Declaration
5433                     and then
5434                       No (Expression (Declaration_Node (Ent)))
5435                   then
5436                      Error_Msg_NE
5437                        ("invalid address clause for initialized object &!",
5438                         Nod, U_Ent);
5439
5440                   --  If entity is constant, it may be the result of expanding
5441                   --  a check. We must verify that its declaration appears
5442                   --  before the object in question, else we also reject the
5443                   --  address clause.
5444
5445                   elsif Ekind (Ent) = E_Constant
5446                     and then In_Same_Source_Unit (Ent, U_Ent)
5447                     and then Sloc (Ent) > Loc_U_Ent
5448                   then
5449                      Error_Msg_NE
5450                        ("invalid address clause for initialized object &!",
5451                         Nod, U_Ent);
5452                   end if;
5453
5454                   return;
5455                end if;
5456
5457                --  Otherwise look at the identifier and see if it is OK
5458
5459                if Ekind_In (Ent, E_Named_Integer, E_Named_Real)
5460                  or else Is_Type (Ent)
5461                then
5462                   return;
5463
5464                elsif
5465                   Ekind (Ent) = E_Constant
5466                     or else
5467                   Ekind (Ent) = E_In_Parameter
5468                then
5469                   --  This is the case where we must have Ent defined before
5470                   --  U_Ent. Clearly if they are in different units this
5471                   --  requirement is met since the unit containing Ent is
5472                   --  already processed.
5473
5474                   if not In_Same_Source_Unit (Ent, U_Ent) then
5475                      return;
5476
5477                   --  Otherwise location of Ent must be before the location
5478                   --  of U_Ent, that's what prior defined means.
5479
5480                   elsif Sloc (Ent) < Loc_U_Ent then
5481                      return;
5482
5483                   else
5484                      Error_Msg_NE
5485                        ("invalid address clause for initialized object &!",
5486                         Nod, U_Ent);
5487                      Error_Msg_Node_2 := U_Ent;
5488                      Error_Msg_NE
5489                        ("\& must be defined before & (RM 13.1(22))!",
5490                         Nod, Ent);
5491                   end if;
5492
5493                elsif Nkind (Original_Node (Nod)) = N_Function_Call then
5494                   Check_Expr_Constants (Original_Node (Nod));
5495
5496                else
5497                   Error_Msg_NE
5498                     ("invalid address clause for initialized object &!",
5499                      Nod, U_Ent);
5500
5501                   if Comes_From_Source (Ent) then
5502                      Error_Msg_NE
5503                        ("\reference to variable& not allowed"
5504                           & " (RM 13.1(22))!", Nod, Ent);
5505                   else
5506                      Error_Msg_N
5507                        ("non-static expression not allowed"
5508                           & " (RM 13.1(22))!", Nod);
5509                   end if;
5510                end if;
5511
5512             when N_Integer_Literal   =>
5513
5514                --  If this is a rewritten unchecked conversion, in a system
5515                --  where Address is an integer type, always use the base type
5516                --  for a literal value. This is user-friendly and prevents
5517                --  order-of-elaboration issues with instances of unchecked
5518                --  conversion.
5519
5520                if Nkind (Original_Node (Nod)) = N_Function_Call then
5521                   Set_Etype (Nod, Base_Type (Etype (Nod)));
5522                end if;
5523
5524             when N_Real_Literal      |
5525                  N_String_Literal    |
5526                  N_Character_Literal =>
5527                return;
5528
5529             when N_Range =>
5530                Check_Expr_Constants (Low_Bound (Nod));
5531                Check_Expr_Constants (High_Bound (Nod));
5532
5533             when N_Explicit_Dereference =>
5534                Check_Expr_Constants (Prefix (Nod));
5535
5536             when N_Indexed_Component =>
5537                Check_Expr_Constants (Prefix (Nod));
5538                Check_List_Constants (Expressions (Nod));
5539
5540             when N_Slice =>
5541                Check_Expr_Constants (Prefix (Nod));
5542                Check_Expr_Constants (Discrete_Range (Nod));
5543
5544             when N_Selected_Component =>
5545                Check_Expr_Constants (Prefix (Nod));
5546
5547             when N_Attribute_Reference =>
5548                if Attribute_Name (Nod) = Name_Address
5549                    or else
5550                   Attribute_Name (Nod) = Name_Access
5551                     or else
5552                   Attribute_Name (Nod) = Name_Unchecked_Access
5553                     or else
5554                   Attribute_Name (Nod) = Name_Unrestricted_Access
5555                then
5556                   Check_At_Constant_Address (Prefix (Nod));
5557
5558                else
5559                   Check_Expr_Constants (Prefix (Nod));
5560                   Check_List_Constants (Expressions (Nod));
5561                end if;
5562
5563             when N_Aggregate =>
5564                Check_List_Constants (Component_Associations (Nod));
5565                Check_List_Constants (Expressions (Nod));
5566
5567             when N_Component_Association =>
5568                Check_Expr_Constants (Expression (Nod));
5569
5570             when N_Extension_Aggregate =>
5571                Check_Expr_Constants (Ancestor_Part (Nod));
5572                Check_List_Constants (Component_Associations (Nod));
5573                Check_List_Constants (Expressions (Nod));
5574
5575             when N_Null =>
5576                return;
5577
5578             when N_Binary_Op | N_Short_Circuit | N_Membership_Test =>
5579                Check_Expr_Constants (Left_Opnd (Nod));
5580                Check_Expr_Constants (Right_Opnd (Nod));
5581
5582             when N_Unary_Op =>
5583                Check_Expr_Constants (Right_Opnd (Nod));
5584
5585             when N_Type_Conversion           |
5586                  N_Qualified_Expression      |
5587                  N_Allocator                 =>
5588                Check_Expr_Constants (Expression (Nod));
5589
5590             when N_Unchecked_Type_Conversion =>
5591                Check_Expr_Constants (Expression (Nod));
5592
5593                --  If this is a rewritten unchecked conversion, subtypes in
5594                --  this node are those created within the instance. To avoid
5595                --  order of elaboration issues, replace them with their base
5596                --  types. Note that address clauses can cause order of
5597                --  elaboration problems because they are elaborated by the
5598                --  back-end at the point of definition, and may mention
5599                --  entities declared in between (as long as everything is
5600                --  static). It is user-friendly to allow unchecked conversions
5601                --  in this context.
5602
5603                if Nkind (Original_Node (Nod)) = N_Function_Call then
5604                   Set_Etype (Expression (Nod),
5605                     Base_Type (Etype (Expression (Nod))));
5606                   Set_Etype (Nod, Base_Type (Etype (Nod)));
5607                end if;
5608
5609             when N_Function_Call =>
5610                if not Is_Pure (Entity (Name (Nod))) then
5611                   Error_Msg_NE
5612                     ("invalid address clause for initialized object &!",
5613                      Nod, U_Ent);
5614
5615                   Error_Msg_NE
5616                     ("\function & is not pure (RM 13.1(22))!",
5617                      Nod, Entity (Name (Nod)));
5618
5619                else
5620                   Check_List_Constants (Parameter_Associations (Nod));
5621                end if;
5622
5623             when N_Parameter_Association =>
5624                Check_Expr_Constants (Explicit_Actual_Parameter (Nod));
5625
5626             when others =>
5627                Error_Msg_NE
5628                  ("invalid address clause for initialized object &!",
5629                   Nod, U_Ent);
5630                Error_Msg_NE
5631                  ("\must be constant defined before& (RM 13.1(22))!",
5632                   Nod, U_Ent);
5633          end case;
5634       end Check_Expr_Constants;
5635
5636       --------------------------
5637       -- Check_List_Constants --
5638       --------------------------
5639
5640       procedure Check_List_Constants (Lst : List_Id) is
5641          Nod1 : Node_Id;
5642
5643       begin
5644          if Present (Lst) then
5645             Nod1 := First (Lst);
5646             while Present (Nod1) loop
5647                Check_Expr_Constants (Nod1);
5648                Next (Nod1);
5649             end loop;
5650          end if;
5651       end Check_List_Constants;
5652
5653    --  Start of processing for Check_Constant_Address_Clause
5654
5655    begin
5656       --  If rep_clauses are to be ignored, no need for legality checks. In
5657       --  particular, no need to pester user about rep clauses that violate
5658       --  the rule on constant addresses, given that these clauses will be
5659       --  removed by Freeze before they reach the back end.
5660
5661       if not Ignore_Rep_Clauses then
5662          Check_Expr_Constants (Expr);
5663       end if;
5664    end Check_Constant_Address_Clause;
5665
5666    ----------------------------------------
5667    -- Check_Record_Representation_Clause --
5668    ----------------------------------------
5669
5670    procedure Check_Record_Representation_Clause (N : Node_Id) is
5671       Loc     : constant Source_Ptr := Sloc (N);
5672       Ident   : constant Node_Id    := Identifier (N);
5673       Rectype : Entity_Id;
5674       Fent    : Entity_Id;
5675       CC      : Node_Id;
5676       Fbit    : Uint;
5677       Lbit    : Uint;
5678       Hbit    : Uint := Uint_0;
5679       Comp    : Entity_Id;
5680       Pcomp   : Entity_Id;
5681
5682       Max_Bit_So_Far : Uint;
5683       --  Records the maximum bit position so far. If all field positions
5684       --  are monotonically increasing, then we can skip the circuit for
5685       --  checking for overlap, since no overlap is possible.
5686
5687       Tagged_Parent : Entity_Id := Empty;
5688       --  This is set in the case of a derived tagged type for which we have
5689       --  Is_Fully_Repped_Tagged_Type True (indicating that all components are
5690       --  positioned by record representation clauses). In this case we must
5691       --  check for overlap between components of this tagged type, and the
5692       --  components of its parent. Tagged_Parent will point to this parent
5693       --  type. For all other cases Tagged_Parent is left set to Empty.
5694
5695       Parent_Last_Bit : Uint;
5696       --  Relevant only if Tagged_Parent is set, Parent_Last_Bit indicates the
5697       --  last bit position for any field in the parent type. We only need to
5698       --  check overlap for fields starting below this point.
5699
5700       Overlap_Check_Required : Boolean;
5701       --  Used to keep track of whether or not an overlap check is required
5702
5703       Overlap_Detected : Boolean := False;
5704       --  Set True if an overlap is detected
5705
5706       Ccount : Natural := 0;
5707       --  Number of component clauses in record rep clause
5708
5709       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id);
5710       --  Given two entities for record components or discriminants, checks
5711       --  if they have overlapping component clauses and issues errors if so.
5712
5713       procedure Find_Component;
5714       --  Finds component entity corresponding to current component clause (in
5715       --  CC), and sets Comp to the entity, and Fbit/Lbit to the zero origin
5716       --  start/stop bits for the field. If there is no matching component or
5717       --  if the matching component does not have a component clause, then
5718       --  that's an error and Comp is set to Empty, but no error message is
5719       --  issued, since the message was already given. Comp is also set to
5720       --  Empty if the current "component clause" is in fact a pragma.
5721
5722       -----------------------------
5723       -- Check_Component_Overlap --
5724       -----------------------------
5725
5726       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id) is
5727          CC1 : constant Node_Id := Component_Clause (C1_Ent);
5728          CC2 : constant Node_Id := Component_Clause (C2_Ent);
5729
5730       begin
5731          if Present (CC1) and then Present (CC2) then
5732
5733             --  Exclude odd case where we have two tag fields in the same
5734             --  record, both at location zero. This seems a bit strange, but
5735             --  it seems to happen in some circumstances, perhaps on an error.
5736
5737             if Chars (C1_Ent) = Name_uTag
5738                  and then
5739                Chars (C2_Ent) = Name_uTag
5740             then
5741                return;
5742             end if;
5743
5744             --  Here we check if the two fields overlap
5745
5746             declare
5747                S1 : constant Uint := Component_Bit_Offset (C1_Ent);
5748                S2 : constant Uint := Component_Bit_Offset (C2_Ent);
5749                E1 : constant Uint := S1 + Esize (C1_Ent);
5750                E2 : constant Uint := S2 + Esize (C2_Ent);
5751
5752             begin
5753                if E2 <= S1 or else E1 <= S2 then
5754                   null;
5755                else
5756                   Error_Msg_Node_2 := Component_Name (CC2);
5757                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
5758                   Error_Msg_Node_1 := Component_Name (CC1);
5759                   Error_Msg_N
5760                     ("component& overlaps & #", Component_Name (CC1));
5761                   Overlap_Detected := True;
5762                end if;
5763             end;
5764          end if;
5765       end Check_Component_Overlap;
5766
5767       --------------------
5768       -- Find_Component --
5769       --------------------
5770
5771       procedure Find_Component is
5772
5773          procedure Search_Component (R : Entity_Id);
5774          --  Search components of R for a match. If found, Comp is set.
5775
5776          ----------------------
5777          -- Search_Component --
5778          ----------------------
5779
5780          procedure Search_Component (R : Entity_Id) is
5781          begin
5782             Comp := First_Component_Or_Discriminant (R);
5783             while Present (Comp) loop
5784
5785                --  Ignore error of attribute name for component name (we
5786                --  already gave an error message for this, so no need to
5787                --  complain here)
5788
5789                if Nkind (Component_Name (CC)) = N_Attribute_Reference then
5790                   null;
5791                else
5792                   exit when Chars (Comp) = Chars (Component_Name (CC));
5793                end if;
5794
5795                Next_Component_Or_Discriminant (Comp);
5796             end loop;
5797          end Search_Component;
5798
5799       --  Start of processing for Find_Component
5800
5801       begin
5802          --  Return with Comp set to Empty if we have a pragma
5803
5804          if Nkind (CC) = N_Pragma then
5805             Comp := Empty;
5806             return;
5807          end if;
5808
5809          --  Search current record for matching component
5810
5811          Search_Component (Rectype);
5812
5813          --  If not found, maybe component of base type that is absent from
5814          --  statically constrained first subtype.
5815
5816          if No (Comp) then
5817             Search_Component (Base_Type (Rectype));
5818          end if;
5819
5820          --  If no component, or the component does not reference the component
5821          --  clause in question, then there was some previous error for which
5822          --  we already gave a message, so just return with Comp Empty.
5823
5824          if No (Comp)
5825            or else Component_Clause (Comp) /= CC
5826          then
5827             Comp := Empty;
5828
5829          --  Normal case where we have a component clause
5830
5831          else
5832             Fbit := Component_Bit_Offset (Comp);
5833             Lbit := Fbit + Esize (Comp) - 1;
5834          end if;
5835       end Find_Component;
5836
5837    --  Start of processing for Check_Record_Representation_Clause
5838
5839    begin
5840       Find_Type (Ident);
5841       Rectype := Entity (Ident);
5842
5843       if Rectype = Any_Type then
5844          return;
5845       else
5846          Rectype := Underlying_Type (Rectype);
5847       end if;
5848
5849       --  See if we have a fully repped derived tagged type
5850
5851       declare
5852          PS : constant Entity_Id := Parent_Subtype (Rectype);
5853
5854       begin
5855          if Present (PS) and then Is_Fully_Repped_Tagged_Type (PS) then
5856             Tagged_Parent := PS;
5857
5858             --  Find maximum bit of any component of the parent type
5859
5860             Parent_Last_Bit := UI_From_Int (System_Address_Size - 1);
5861             Pcomp := First_Entity (Tagged_Parent);
5862             while Present (Pcomp) loop
5863                if Ekind_In (Pcomp, E_Discriminant, E_Component) then
5864                   if Component_Bit_Offset (Pcomp) /= No_Uint
5865                     and then Known_Static_Esize (Pcomp)
5866                   then
5867                      Parent_Last_Bit :=
5868                        UI_Max
5869                          (Parent_Last_Bit,
5870                           Component_Bit_Offset (Pcomp) + Esize (Pcomp) - 1);
5871                   end if;
5872
5873                   Next_Entity (Pcomp);
5874                end if;
5875             end loop;
5876          end if;
5877       end;
5878
5879       --  All done if no component clauses
5880
5881       CC := First (Component_Clauses (N));
5882
5883       if No (CC) then
5884          return;
5885       end if;
5886
5887       --  If a tag is present, then create a component clause that places it
5888       --  at the start of the record (otherwise gigi may place it after other
5889       --  fields that have rep clauses).
5890
5891       Fent := First_Entity (Rectype);
5892
5893       if Nkind (Fent) = N_Defining_Identifier
5894         and then Chars (Fent) = Name_uTag
5895       then
5896          Set_Component_Bit_Offset    (Fent, Uint_0);
5897          Set_Normalized_Position     (Fent, Uint_0);
5898          Set_Normalized_First_Bit    (Fent, Uint_0);
5899          Set_Normalized_Position_Max (Fent, Uint_0);
5900          Init_Esize                  (Fent, System_Address_Size);
5901
5902          Set_Component_Clause (Fent,
5903            Make_Component_Clause (Loc,
5904              Component_Name => Make_Identifier (Loc, Name_uTag),
5905
5906              Position  => Make_Integer_Literal (Loc, Uint_0),
5907              First_Bit => Make_Integer_Literal (Loc, Uint_0),
5908              Last_Bit  =>
5909                Make_Integer_Literal (Loc,
5910                  UI_From_Int (System_Address_Size))));
5911
5912          Ccount := Ccount + 1;
5913       end if;
5914
5915       Max_Bit_So_Far := Uint_Minus_1;
5916       Overlap_Check_Required := False;
5917
5918       --  Process the component clauses
5919
5920       while Present (CC) loop
5921          Find_Component;
5922
5923          if Present (Comp) then
5924             Ccount := Ccount + 1;
5925
5926             --  We need a full overlap check if record positions non-monotonic
5927
5928             if Fbit <= Max_Bit_So_Far then
5929                Overlap_Check_Required := True;
5930             end if;
5931
5932             Max_Bit_So_Far := Lbit;
5933
5934             --  Check bit position out of range of specified size
5935
5936             if Has_Size_Clause (Rectype)
5937               and then Esize (Rectype) <= Lbit
5938             then
5939                Error_Msg_N
5940                  ("bit number out of range of specified size",
5941                   Last_Bit (CC));
5942
5943                --  Check for overlap with tag field
5944
5945             else
5946                if Is_Tagged_Type (Rectype)
5947                  and then Fbit < System_Address_Size
5948                then
5949                   Error_Msg_NE
5950                     ("component overlaps tag field of&",
5951                      Component_Name (CC), Rectype);
5952                   Overlap_Detected := True;
5953                end if;
5954
5955                if Hbit < Lbit then
5956                   Hbit := Lbit;
5957                end if;
5958             end if;
5959
5960             --  Check parent overlap if component might overlap parent field
5961
5962             if Present (Tagged_Parent)
5963               and then Fbit <= Parent_Last_Bit
5964             then
5965                Pcomp := First_Component_Or_Discriminant (Tagged_Parent);
5966                while Present (Pcomp) loop
5967                   if not Is_Tag (Pcomp)
5968                     and then Chars (Pcomp) /= Name_uParent
5969                   then
5970                      Check_Component_Overlap (Comp, Pcomp);
5971                   end if;
5972
5973                   Next_Component_Or_Discriminant (Pcomp);
5974                end loop;
5975             end if;
5976          end if;
5977
5978          Next (CC);
5979       end loop;
5980
5981       --  Now that we have processed all the component clauses, check for
5982       --  overlap. We have to leave this till last, since the components can
5983       --  appear in any arbitrary order in the representation clause.
5984
5985       --  We do not need this check if all specified ranges were monotonic,
5986       --  as recorded by Overlap_Check_Required being False at this stage.
5987
5988       --  This first section checks if there are any overlapping entries at
5989       --  all. It does this by sorting all entries and then seeing if there are
5990       --  any overlaps. If there are none, then that is decisive, but if there
5991       --  are overlaps, they may still be OK (they may result from fields in
5992       --  different variants).
5993
5994       if Overlap_Check_Required then
5995          Overlap_Check1 : declare
5996
5997             OC_Fbit : array (0 .. Ccount) of Uint;
5998             --  First-bit values for component clauses, the value is the offset
5999             --  of the first bit of the field from start of record. The zero
6000             --  entry is for use in sorting.
6001
6002             OC_Lbit : array (0 .. Ccount) of Uint;
6003             --  Last-bit values for component clauses, the value is the offset
6004             --  of the last bit of the field from start of record. The zero
6005             --  entry is for use in sorting.
6006
6007             OC_Count : Natural := 0;
6008             --  Count of entries in OC_Fbit and OC_Lbit
6009
6010             function OC_Lt (Op1, Op2 : Natural) return Boolean;
6011             --  Compare routine for Sort
6012
6013             procedure OC_Move (From : Natural; To : Natural);
6014             --  Move routine for Sort
6015
6016             package Sorting is new GNAT.Heap_Sort_G (OC_Move, OC_Lt);
6017
6018             -----------
6019             -- OC_Lt --
6020             -----------
6021
6022             function OC_Lt (Op1, Op2 : Natural) return Boolean is
6023             begin
6024                return OC_Fbit (Op1) < OC_Fbit (Op2);
6025             end OC_Lt;
6026
6027             -------------
6028             -- OC_Move --
6029             -------------
6030
6031             procedure OC_Move (From : Natural; To : Natural) is
6032             begin
6033                OC_Fbit (To) := OC_Fbit (From);
6034                OC_Lbit (To) := OC_Lbit (From);
6035             end OC_Move;
6036
6037             --  Start of processing for Overlap_Check
6038
6039          begin
6040             CC := First (Component_Clauses (N));
6041             while Present (CC) loop
6042
6043                --  Exclude component clause already marked in error
6044
6045                if not Error_Posted (CC) then
6046                   Find_Component;
6047
6048                   if Present (Comp) then
6049                      OC_Count := OC_Count + 1;
6050                      OC_Fbit (OC_Count) := Fbit;
6051                      OC_Lbit (OC_Count) := Lbit;
6052                   end if;
6053                end if;
6054
6055                Next (CC);
6056             end loop;
6057
6058             Sorting.Sort (OC_Count);
6059
6060             Overlap_Check_Required := False;
6061             for J in 1 .. OC_Count - 1 loop
6062                if OC_Lbit (J) >= OC_Fbit (J + 1) then
6063                   Overlap_Check_Required := True;
6064                   exit;
6065                end if;
6066             end loop;
6067          end Overlap_Check1;
6068       end if;
6069
6070       --  If Overlap_Check_Required is still True, then we have to do the full
6071       --  scale overlap check, since we have at least two fields that do
6072       --  overlap, and we need to know if that is OK since they are in
6073       --  different variant, or whether we have a definite problem.
6074
6075       if Overlap_Check_Required then
6076          Overlap_Check2 : declare
6077             C1_Ent, C2_Ent : Entity_Id;
6078             --  Entities of components being checked for overlap
6079
6080             Clist : Node_Id;
6081             --  Component_List node whose Component_Items are being checked
6082
6083             Citem : Node_Id;
6084             --  Component declaration for component being checked
6085
6086          begin
6087             C1_Ent := First_Entity (Base_Type (Rectype));
6088
6089             --  Loop through all components in record. For each component check
6090             --  for overlap with any of the preceding elements on the component
6091             --  list containing the component and also, if the component is in
6092             --  a variant, check against components outside the case structure.
6093             --  This latter test is repeated recursively up the variant tree.
6094
6095             Main_Component_Loop : while Present (C1_Ent) loop
6096                if not Ekind_In (C1_Ent, E_Component, E_Discriminant) then
6097                   goto Continue_Main_Component_Loop;
6098                end if;
6099
6100                --  Skip overlap check if entity has no declaration node. This
6101                --  happens with discriminants in constrained derived types.
6102                --  Possibly we are missing some checks as a result, but that
6103                --  does not seem terribly serious.
6104
6105                if No (Declaration_Node (C1_Ent)) then
6106                   goto Continue_Main_Component_Loop;
6107                end if;
6108
6109                Clist := Parent (List_Containing (Declaration_Node (C1_Ent)));
6110
6111                --  Loop through component lists that need checking. Check the
6112                --  current component list and all lists in variants above us.
6113
6114                Component_List_Loop : loop
6115
6116                   --  If derived type definition, go to full declaration
6117                   --  If at outer level, check discriminants if there are any.
6118
6119                   if Nkind (Clist) = N_Derived_Type_Definition then
6120                      Clist := Parent (Clist);
6121                   end if;
6122
6123                   --  Outer level of record definition, check discriminants
6124
6125                   if Nkind_In (Clist, N_Full_Type_Declaration,
6126                                N_Private_Type_Declaration)
6127                   then
6128                      if Has_Discriminants (Defining_Identifier (Clist)) then
6129                         C2_Ent :=
6130                           First_Discriminant (Defining_Identifier (Clist));
6131                         while Present (C2_Ent) loop
6132                            exit when C1_Ent = C2_Ent;
6133                            Check_Component_Overlap (C1_Ent, C2_Ent);
6134                            Next_Discriminant (C2_Ent);
6135                         end loop;
6136                      end if;
6137
6138                      --  Record extension case
6139
6140                   elsif Nkind (Clist) = N_Derived_Type_Definition then
6141                      Clist := Empty;
6142
6143                      --  Otherwise check one component list
6144
6145                   else
6146                      Citem := First (Component_Items (Clist));
6147                      while Present (Citem) loop
6148                         if Nkind (Citem) = N_Component_Declaration then
6149                            C2_Ent := Defining_Identifier (Citem);
6150                            exit when C1_Ent = C2_Ent;
6151                            Check_Component_Overlap (C1_Ent, C2_Ent);
6152                         end if;
6153
6154                         Next (Citem);
6155                      end loop;
6156                   end if;
6157
6158                   --  Check for variants above us (the parent of the Clist can
6159                   --  be a variant, in which case its parent is a variant part,
6160                   --  and the parent of the variant part is a component list
6161                   --  whose components must all be checked against the current
6162                   --  component for overlap).
6163
6164                   if Nkind (Parent (Clist)) = N_Variant then
6165                      Clist := Parent (Parent (Parent (Clist)));
6166
6167                      --  Check for possible discriminant part in record, this
6168                      --  is treated essentially as another level in the
6169                      --  recursion. For this case the parent of the component
6170                      --  list is the record definition, and its parent is the
6171                      --  full type declaration containing the discriminant
6172                      --  specifications.
6173
6174                   elsif Nkind (Parent (Clist)) = N_Record_Definition then
6175                      Clist := Parent (Parent ((Clist)));
6176
6177                      --  If neither of these two cases, we are at the top of
6178                      --  the tree.
6179
6180                   else
6181                      exit Component_List_Loop;
6182                   end if;
6183                end loop Component_List_Loop;
6184
6185                <<Continue_Main_Component_Loop>>
6186                Next_Entity (C1_Ent);
6187
6188             end loop Main_Component_Loop;
6189          end Overlap_Check2;
6190       end if;
6191
6192       --  The following circuit deals with warning on record holes (gaps). We
6193       --  skip this check if overlap was detected, since it makes sense for the
6194       --  programmer to fix this illegality before worrying about warnings.
6195
6196       if not Overlap_Detected and Warn_On_Record_Holes then
6197          Record_Hole_Check : declare
6198             Decl : constant Node_Id := Declaration_Node (Base_Type (Rectype));
6199             --  Full declaration of record type
6200
6201             procedure Check_Component_List
6202               (CL   : Node_Id;
6203                Sbit : Uint;
6204                DS   : List_Id);
6205             --  Check component list CL for holes. The starting bit should be
6206             --  Sbit. which is zero for the main record component list and set
6207             --  appropriately for recursive calls for variants. DS is set to
6208             --  a list of discriminant specifications to be included in the
6209             --  consideration of components. It is No_List if none to consider.
6210
6211             --------------------------
6212             -- Check_Component_List --
6213             --------------------------
6214
6215             procedure Check_Component_List
6216               (CL   : Node_Id;
6217                Sbit : Uint;
6218                DS   : List_Id)
6219             is
6220                Compl : Integer;
6221
6222             begin
6223                Compl := Integer (List_Length (Component_Items (CL)));
6224
6225                if DS /= No_List then
6226                   Compl := Compl + Integer (List_Length (DS));
6227                end if;
6228
6229                declare
6230                   Comps : array (Natural range 0 .. Compl) of Entity_Id;
6231                   --  Gather components (zero entry is for sort routine)
6232
6233                   Ncomps : Natural := 0;
6234                   --  Number of entries stored in Comps (starting at Comps (1))
6235
6236                   Citem : Node_Id;
6237                   --  One component item or discriminant specification
6238
6239                   Nbit  : Uint;
6240                   --  Starting bit for next component
6241
6242                   CEnt  : Entity_Id;
6243                   --  Component entity
6244
6245                   Variant : Node_Id;
6246                   --  One variant
6247
6248                   function Lt (Op1, Op2 : Natural) return Boolean;
6249                   --  Compare routine for Sort
6250
6251                   procedure Move (From : Natural; To : Natural);
6252                   --  Move routine for Sort
6253
6254                   package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
6255
6256                   --------
6257                   -- Lt --
6258                   --------
6259
6260                   function Lt (Op1, Op2 : Natural) return Boolean is
6261                   begin
6262                      return Component_Bit_Offset (Comps (Op1))
6263                        <
6264                        Component_Bit_Offset (Comps (Op2));
6265                   end Lt;
6266
6267                   ----------
6268                   -- Move --
6269                   ----------
6270
6271                   procedure Move (From : Natural; To : Natural) is
6272                   begin
6273                      Comps (To) := Comps (From);
6274                   end Move;
6275
6276                begin
6277                   --  Gather discriminants into Comp
6278
6279                   if DS /= No_List then
6280                      Citem := First (DS);
6281                      while Present (Citem) loop
6282                         if Nkind (Citem) = N_Discriminant_Specification then
6283                            declare
6284                               Ent : constant Entity_Id :=
6285                                       Defining_Identifier (Citem);
6286                            begin
6287                               if Ekind (Ent) = E_Discriminant then
6288                                  Ncomps := Ncomps + 1;
6289                                  Comps (Ncomps) := Ent;
6290                               end if;
6291                            end;
6292                         end if;
6293
6294                         Next (Citem);
6295                      end loop;
6296                   end if;
6297
6298                   --  Gather component entities into Comp
6299
6300                   Citem := First (Component_Items (CL));
6301                   while Present (Citem) loop
6302                      if Nkind (Citem) = N_Component_Declaration then
6303                         Ncomps := Ncomps + 1;
6304                         Comps (Ncomps) := Defining_Identifier (Citem);
6305                      end if;
6306
6307                      Next (Citem);
6308                   end loop;
6309
6310                   --  Now sort the component entities based on the first bit.
6311                   --  Note we already know there are no overlapping components.
6312
6313                   Sorting.Sort (Ncomps);
6314
6315                   --  Loop through entries checking for holes
6316
6317                   Nbit := Sbit;
6318                   for J in 1 .. Ncomps loop
6319                      CEnt := Comps (J);
6320                      Error_Msg_Uint_1 := Component_Bit_Offset (CEnt) - Nbit;
6321
6322                      if Error_Msg_Uint_1 > 0 then
6323                         Error_Msg_NE
6324                           ("?^-bit gap before component&",
6325                            Component_Name (Component_Clause (CEnt)), CEnt);
6326                      end if;
6327
6328                      Nbit := Component_Bit_Offset (CEnt) + Esize (CEnt);
6329                   end loop;
6330
6331                   --  Process variant parts recursively if present
6332
6333                   if Present (Variant_Part (CL)) then
6334                      Variant := First (Variants (Variant_Part (CL)));
6335                      while Present (Variant) loop
6336                         Check_Component_List
6337                           (Component_List (Variant), Nbit, No_List);
6338                         Next (Variant);
6339                      end loop;
6340                   end if;
6341                end;
6342             end Check_Component_List;
6343
6344          --  Start of processing for Record_Hole_Check
6345
6346          begin
6347             declare
6348                Sbit : Uint;
6349
6350             begin
6351                if Is_Tagged_Type (Rectype) then
6352                   Sbit := UI_From_Int (System_Address_Size);
6353                else
6354                   Sbit := Uint_0;
6355                end if;
6356
6357                if Nkind (Decl) = N_Full_Type_Declaration
6358                  and then Nkind (Type_Definition (Decl)) = N_Record_Definition
6359                then
6360                   Check_Component_List
6361                     (Component_List (Type_Definition (Decl)),
6362                      Sbit,
6363                      Discriminant_Specifications (Decl));
6364                end if;
6365             end;
6366          end Record_Hole_Check;
6367       end if;
6368
6369       --  For records that have component clauses for all components, and whose
6370       --  size is less than or equal to 32, we need to know the size in the
6371       --  front end to activate possible packed array processing where the
6372       --  component type is a record.
6373
6374       --  At this stage Hbit + 1 represents the first unused bit from all the
6375       --  component clauses processed, so if the component clauses are
6376       --  complete, then this is the length of the record.
6377
6378       --  For records longer than System.Storage_Unit, and for those where not
6379       --  all components have component clauses, the back end determines the
6380       --  length (it may for example be appropriate to round up the size
6381       --  to some convenient boundary, based on alignment considerations, etc).
6382
6383       if Unknown_RM_Size (Rectype) and then Hbit + 1 <= 32 then
6384
6385          --  Nothing to do if at least one component has no component clause
6386
6387          Comp := First_Component_Or_Discriminant (Rectype);
6388          while Present (Comp) loop
6389             exit when No (Component_Clause (Comp));
6390             Next_Component_Or_Discriminant (Comp);
6391          end loop;
6392
6393          --  If we fall out of loop, all components have component clauses
6394          --  and so we can set the size to the maximum value.
6395
6396          if No (Comp) then
6397             Set_RM_Size (Rectype, Hbit + 1);
6398          end if;
6399       end if;
6400    end Check_Record_Representation_Clause;
6401
6402    ----------------
6403    -- Check_Size --
6404    ----------------
6405
6406    procedure Check_Size
6407      (N      : Node_Id;
6408       T      : Entity_Id;
6409       Siz    : Uint;
6410       Biased : out Boolean)
6411    is
6412       UT : constant Entity_Id := Underlying_Type (T);
6413       M  : Uint;
6414
6415    begin
6416       Biased := False;
6417
6418       --  Dismiss cases for generic types or types with previous errors
6419
6420       if No (UT)
6421         or else UT = Any_Type
6422         or else Is_Generic_Type (UT)
6423         or else Is_Generic_Type (Root_Type (UT))
6424       then
6425          return;
6426
6427       --  Check case of bit packed array
6428
6429       elsif Is_Array_Type (UT)
6430         and then Known_Static_Component_Size (UT)
6431         and then Is_Bit_Packed_Array (UT)
6432       then
6433          declare
6434             Asiz : Uint;
6435             Indx : Node_Id;
6436             Ityp : Entity_Id;
6437
6438          begin
6439             Asiz := Component_Size (UT);
6440             Indx := First_Index (UT);
6441             loop
6442                Ityp := Etype (Indx);
6443
6444                --  If non-static bound, then we are not in the business of
6445                --  trying to check the length, and indeed an error will be
6446                --  issued elsewhere, since sizes of non-static array types
6447                --  cannot be set implicitly or explicitly.
6448
6449                if not Is_Static_Subtype (Ityp) then
6450                   return;
6451                end if;
6452
6453                --  Otherwise accumulate next dimension
6454
6455                Asiz := Asiz * (Expr_Value (Type_High_Bound (Ityp)) -
6456                                Expr_Value (Type_Low_Bound  (Ityp)) +
6457                                Uint_1);
6458
6459                Next_Index (Indx);
6460                exit when No (Indx);
6461             end loop;
6462
6463             if Asiz <= Siz then
6464                return;
6465             else
6466                Error_Msg_Uint_1 := Asiz;
6467                Error_Msg_NE
6468                  ("size for& too small, minimum allowed is ^", N, T);
6469                Set_Esize   (T, Asiz);
6470                Set_RM_Size (T, Asiz);
6471             end if;
6472          end;
6473
6474       --  All other composite types are ignored
6475
6476       elsif Is_Composite_Type (UT) then
6477          return;
6478
6479       --  For fixed-point types, don't check minimum if type is not frozen,
6480       --  since we don't know all the characteristics of the type that can
6481       --  affect the size (e.g. a specified small) till freeze time.
6482
6483       elsif Is_Fixed_Point_Type (UT)
6484         and then not Is_Frozen (UT)
6485       then
6486          null;
6487
6488       --  Cases for which a minimum check is required
6489
6490       else
6491          --  Ignore if specified size is correct for the type
6492
6493          if Known_Esize (UT) and then Siz = Esize (UT) then
6494             return;
6495          end if;
6496
6497          --  Otherwise get minimum size
6498
6499          M := UI_From_Int (Minimum_Size (UT));
6500
6501          if Siz < M then
6502
6503             --  Size is less than minimum size, but one possibility remains
6504             --  that we can manage with the new size if we bias the type.
6505
6506             M := UI_From_Int (Minimum_Size (UT, Biased => True));
6507
6508             if Siz < M then
6509                Error_Msg_Uint_1 := M;
6510                Error_Msg_NE
6511                  ("size for& too small, minimum allowed is ^", N, T);
6512                Set_Esize (T, M);
6513                Set_RM_Size (T, M);
6514             else
6515                Biased := True;
6516             end if;
6517          end if;
6518       end if;
6519    end Check_Size;
6520
6521    -------------------------
6522    -- Get_Alignment_Value --
6523    -------------------------
6524
6525    function Get_Alignment_Value (Expr : Node_Id) return Uint is
6526       Align : constant Uint := Static_Integer (Expr);
6527
6528    begin
6529       if Align = No_Uint then
6530          return No_Uint;
6531
6532       elsif Align <= 0 then
6533          Error_Msg_N ("alignment value must be positive", Expr);
6534          return No_Uint;
6535
6536       else
6537          for J in Int range 0 .. 64 loop
6538             declare
6539                M : constant Uint := Uint_2 ** J;
6540
6541             begin
6542                exit when M = Align;
6543
6544                if M > Align then
6545                   Error_Msg_N
6546                     ("alignment value must be power of 2", Expr);
6547                   return No_Uint;
6548                end if;
6549             end;
6550          end loop;
6551
6552          return Align;
6553       end if;
6554    end Get_Alignment_Value;
6555
6556    ----------------
6557    -- Initialize --
6558    ----------------
6559
6560    procedure Initialize is
6561    begin
6562       Address_Clause_Checks.Init;
6563       Independence_Checks.Init;
6564       Unchecked_Conversions.Init;
6565    end Initialize;
6566
6567    -------------------------
6568    -- Is_Operational_Item --
6569    -------------------------
6570
6571    function Is_Operational_Item (N : Node_Id) return Boolean is
6572    begin
6573       if Nkind (N) /= N_Attribute_Definition_Clause then
6574          return False;
6575       else
6576          declare
6577             Id    : constant Attribute_Id := Get_Attribute_Id (Chars (N));
6578          begin
6579             return   Id = Attribute_Input
6580               or else Id = Attribute_Output
6581               or else Id = Attribute_Read
6582               or else Id = Attribute_Write
6583               or else Id = Attribute_External_Tag;
6584          end;
6585       end if;
6586    end Is_Operational_Item;
6587
6588    ------------------
6589    -- Minimum_Size --
6590    ------------------
6591
6592    function Minimum_Size
6593      (T      : Entity_Id;
6594       Biased : Boolean := False) return Nat
6595    is
6596       Lo     : Uint    := No_Uint;
6597       Hi     : Uint    := No_Uint;
6598       LoR    : Ureal   := No_Ureal;
6599       HiR    : Ureal   := No_Ureal;
6600       LoSet  : Boolean := False;
6601       HiSet  : Boolean := False;
6602       B      : Uint;
6603       S      : Nat;
6604       Ancest : Entity_Id;
6605       R_Typ  : constant Entity_Id := Root_Type (T);
6606
6607    begin
6608       --  If bad type, return 0
6609
6610       if T = Any_Type then
6611          return 0;
6612
6613       --  For generic types, just return zero. There cannot be any legitimate
6614       --  need to know such a size, but this routine may be called with a
6615       --  generic type as part of normal processing.
6616
6617       elsif Is_Generic_Type (R_Typ)
6618         or else R_Typ = Any_Type
6619       then
6620          return 0;
6621
6622          --  Access types. Normally an access type cannot have a size smaller
6623          --  than the size of System.Address. The exception is on VMS, where
6624          --  we have short and long addresses, and it is possible for an access
6625          --  type to have a short address size (and thus be less than the size
6626          --  of System.Address itself). We simply skip the check for VMS, and
6627          --  leave it to the back end to do the check.
6628
6629       elsif Is_Access_Type (T) then
6630          if OpenVMS_On_Target then
6631             return 0;
6632          else
6633             return System_Address_Size;
6634          end if;
6635
6636       --  Floating-point types
6637
6638       elsif Is_Floating_Point_Type (T) then
6639          return UI_To_Int (Esize (R_Typ));
6640
6641       --  Discrete types
6642
6643       elsif Is_Discrete_Type (T) then
6644
6645          --  The following loop is looking for the nearest compile time known
6646          --  bounds following the ancestor subtype chain. The idea is to find
6647          --  the most restrictive known bounds information.
6648
6649          Ancest := T;
6650          loop
6651             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
6652                return 0;
6653             end if;
6654
6655             if not LoSet then
6656                if Compile_Time_Known_Value (Type_Low_Bound (Ancest)) then
6657                   Lo := Expr_Rep_Value (Type_Low_Bound (Ancest));
6658                   LoSet := True;
6659                   exit when HiSet;
6660                end if;
6661             end if;
6662
6663             if not HiSet then
6664                if Compile_Time_Known_Value (Type_High_Bound (Ancest)) then
6665                   Hi := Expr_Rep_Value (Type_High_Bound (Ancest));
6666                   HiSet := True;
6667                   exit when LoSet;
6668                end if;
6669             end if;
6670
6671             Ancest := Ancestor_Subtype (Ancest);
6672
6673             if No (Ancest) then
6674                Ancest := Base_Type (T);
6675
6676                if Is_Generic_Type (Ancest) then
6677                   return 0;
6678                end if;
6679             end if;
6680          end loop;
6681
6682       --  Fixed-point types. We can't simply use Expr_Value to get the
6683       --  Corresponding_Integer_Value values of the bounds, since these do not
6684       --  get set till the type is frozen, and this routine can be called
6685       --  before the type is frozen. Similarly the test for bounds being static
6686       --  needs to include the case where we have unanalyzed real literals for
6687       --  the same reason.
6688
6689       elsif Is_Fixed_Point_Type (T) then
6690
6691          --  The following loop is looking for the nearest compile time known
6692          --  bounds following the ancestor subtype chain. The idea is to find
6693          --  the most restrictive known bounds information.
6694
6695          Ancest := T;
6696          loop
6697             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
6698                return 0;
6699             end if;
6700
6701             --  Note: In the following two tests for LoSet and HiSet, it may
6702             --  seem redundant to test for N_Real_Literal here since normally
6703             --  one would assume that the test for the value being known at
6704             --  compile time includes this case. However, there is a glitch.
6705             --  If the real literal comes from folding a non-static expression,
6706             --  then we don't consider any non- static expression to be known
6707             --  at compile time if we are in configurable run time mode (needed
6708             --  in some cases to give a clearer definition of what is and what
6709             --  is not accepted). So the test is indeed needed. Without it, we
6710             --  would set neither Lo_Set nor Hi_Set and get an infinite loop.
6711
6712             if not LoSet then
6713                if Nkind (Type_Low_Bound (Ancest)) = N_Real_Literal
6714                  or else Compile_Time_Known_Value (Type_Low_Bound (Ancest))
6715                then
6716                   LoR := Expr_Value_R (Type_Low_Bound (Ancest));
6717                   LoSet := True;
6718                   exit when HiSet;
6719                end if;
6720             end if;
6721
6722             if not HiSet then
6723                if Nkind (Type_High_Bound (Ancest)) = N_Real_Literal
6724                  or else Compile_Time_Known_Value (Type_High_Bound (Ancest))
6725                then
6726                   HiR := Expr_Value_R (Type_High_Bound (Ancest));
6727                   HiSet := True;
6728                   exit when LoSet;
6729                end if;
6730             end if;
6731
6732             Ancest := Ancestor_Subtype (Ancest);
6733
6734             if No (Ancest) then
6735                Ancest := Base_Type (T);
6736
6737                if Is_Generic_Type (Ancest) then
6738                   return 0;
6739                end if;
6740             end if;
6741          end loop;
6742
6743          Lo := UR_To_Uint (LoR / Small_Value (T));
6744          Hi := UR_To_Uint (HiR / Small_Value (T));
6745
6746       --  No other types allowed
6747
6748       else
6749          raise Program_Error;
6750       end if;
6751
6752       --  Fall through with Hi and Lo set. Deal with biased case
6753
6754       if (Biased
6755            and then not Is_Fixed_Point_Type (T)
6756            and then not (Is_Enumeration_Type (T)
6757                           and then Has_Non_Standard_Rep (T)))
6758         or else Has_Biased_Representation (T)
6759       then
6760          Hi := Hi - Lo;
6761          Lo := Uint_0;
6762       end if;
6763
6764       --  Signed case. Note that we consider types like range 1 .. -1 to be
6765       --  signed for the purpose of computing the size, since the bounds have
6766       --  to be accommodated in the base type.
6767
6768       if Lo < 0 or else Hi < 0 then
6769          S := 1;
6770          B := Uint_1;
6771
6772          --  S = size, B = 2 ** (size - 1) (can accommodate -B .. +(B - 1))
6773          --  Note that we accommodate the case where the bounds cross. This
6774          --  can happen either because of the way the bounds are declared
6775          --  or because of the algorithm in Freeze_Fixed_Point_Type.
6776
6777          while Lo < -B
6778            or else Hi < -B
6779            or else Lo >= B
6780            or else Hi >= B
6781          loop
6782             B := Uint_2 ** S;
6783             S := S + 1;
6784          end loop;
6785
6786       --  Unsigned case
6787
6788       else
6789          --  If both bounds are positive, make sure that both are represen-
6790          --  table in the case where the bounds are crossed. This can happen
6791          --  either because of the way the bounds are declared, or because of
6792          --  the algorithm in Freeze_Fixed_Point_Type.
6793
6794          if Lo > Hi then
6795             Hi := Lo;
6796          end if;
6797
6798          --  S = size, (can accommodate 0 .. (2**size - 1))
6799
6800          S := 0;
6801          while Hi >= Uint_2 ** S loop
6802             S := S + 1;
6803          end loop;
6804       end if;
6805
6806       return S;
6807    end Minimum_Size;
6808
6809    ---------------------------
6810    -- New_Stream_Subprogram --
6811    ---------------------------
6812
6813    procedure New_Stream_Subprogram
6814      (N     : Node_Id;
6815       Ent   : Entity_Id;
6816       Subp  : Entity_Id;
6817       Nam   : TSS_Name_Type)
6818    is
6819       Loc       : constant Source_Ptr := Sloc (N);
6820       Sname     : constant Name_Id    := Make_TSS_Name (Base_Type (Ent), Nam);
6821       Subp_Id   : Entity_Id;
6822       Subp_Decl : Node_Id;
6823       F         : Entity_Id;
6824       Etyp      : Entity_Id;
6825
6826       Defer_Declaration : constant Boolean :=
6827                             Is_Tagged_Type (Ent) or else Is_Private_Type (Ent);
6828       --  For a tagged type, there is a declaration for each stream attribute
6829       --  at the freeze point, and we must generate only a completion of this
6830       --  declaration. We do the same for private types, because the full view
6831       --  might be tagged. Otherwise we generate a declaration at the point of
6832       --  the attribute definition clause.
6833
6834       function Build_Spec return Node_Id;
6835       --  Used for declaration and renaming declaration, so that this is
6836       --  treated as a renaming_as_body.
6837
6838       ----------------
6839       -- Build_Spec --
6840       ----------------
6841
6842       function Build_Spec return Node_Id is
6843          Out_P   : constant Boolean := (Nam = TSS_Stream_Read);
6844          Formals : List_Id;
6845          Spec    : Node_Id;
6846          T_Ref   : constant Node_Id := New_Reference_To (Etyp, Loc);
6847
6848       begin
6849          Subp_Id := Make_Defining_Identifier (Loc, Sname);
6850
6851          --  S : access Root_Stream_Type'Class
6852
6853          Formals := New_List (
6854                       Make_Parameter_Specification (Loc,
6855                         Defining_Identifier =>
6856                           Make_Defining_Identifier (Loc, Name_S),
6857                         Parameter_Type =>
6858                           Make_Access_Definition (Loc,
6859                             Subtype_Mark =>
6860                               New_Reference_To (
6861                                 Designated_Type (Etype (F)), Loc))));
6862
6863          if Nam = TSS_Stream_Input then
6864             Spec := Make_Function_Specification (Loc,
6865                       Defining_Unit_Name       => Subp_Id,
6866                       Parameter_Specifications => Formals,
6867                       Result_Definition        => T_Ref);
6868          else
6869             --  V : [out] T
6870
6871             Append_To (Formals,
6872               Make_Parameter_Specification (Loc,
6873                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
6874                 Out_Present         => Out_P,
6875                 Parameter_Type      => T_Ref));
6876
6877             Spec :=
6878               Make_Procedure_Specification (Loc,
6879                 Defining_Unit_Name       => Subp_Id,
6880                 Parameter_Specifications => Formals);
6881          end if;
6882
6883          return Spec;
6884       end Build_Spec;
6885
6886    --  Start of processing for New_Stream_Subprogram
6887
6888    begin
6889       F := First_Formal (Subp);
6890
6891       if Ekind (Subp) = E_Procedure then
6892          Etyp := Etype (Next_Formal (F));
6893       else
6894          Etyp := Etype (Subp);
6895       end if;
6896
6897       --  Prepare subprogram declaration and insert it as an action on the
6898       --  clause node. The visibility for this entity is used to test for
6899       --  visibility of the attribute definition clause (in the sense of
6900       --  8.3(23) as amended by AI-195).
6901
6902       if not Defer_Declaration then
6903          Subp_Decl :=
6904            Make_Subprogram_Declaration (Loc,
6905              Specification => Build_Spec);
6906
6907       --  For a tagged type, there is always a visible declaration for each
6908       --  stream TSS (it is a predefined primitive operation), and the
6909       --  completion of this declaration occurs at the freeze point, which is
6910       --  not always visible at places where the attribute definition clause is
6911       --  visible. So, we create a dummy entity here for the purpose of
6912       --  tracking the visibility of the attribute definition clause itself.
6913
6914       else
6915          Subp_Id :=
6916            Make_Defining_Identifier (Loc, New_External_Name (Sname, 'V'));
6917          Subp_Decl :=
6918            Make_Object_Declaration (Loc,
6919              Defining_Identifier => Subp_Id,
6920              Object_Definition   => New_Occurrence_Of (Standard_Boolean, Loc));
6921       end if;
6922
6923       Insert_Action (N, Subp_Decl);
6924       Set_Entity (N, Subp_Id);
6925
6926       Subp_Decl :=
6927         Make_Subprogram_Renaming_Declaration (Loc,
6928           Specification => Build_Spec,
6929           Name => New_Reference_To (Subp, Loc));
6930
6931       if Defer_Declaration then
6932          Set_TSS (Base_Type (Ent), Subp_Id);
6933       else
6934          Insert_Action (N, Subp_Decl);
6935          Copy_TSS (Subp_Id, Base_Type (Ent));
6936       end if;
6937    end New_Stream_Subprogram;
6938
6939    ------------------------
6940    -- Rep_Item_Too_Early --
6941    ------------------------
6942
6943    function Rep_Item_Too_Early (T : Entity_Id; N : Node_Id) return Boolean is
6944    begin
6945       --  Cannot apply non-operational rep items to generic types
6946
6947       if Is_Operational_Item (N) then
6948          return False;
6949
6950       elsif Is_Type (T)
6951         and then Is_Generic_Type (Root_Type (T))
6952       then
6953          Error_Msg_N ("representation item not allowed for generic type", N);
6954          return True;
6955       end if;
6956
6957       --  Otherwise check for incomplete type
6958
6959       if Is_Incomplete_Or_Private_Type (T)
6960         and then No (Underlying_Type (T))
6961       then
6962          Error_Msg_N
6963            ("representation item must be after full type declaration", N);
6964          return True;
6965
6966       --  If the type has incomplete components, a representation clause is
6967       --  illegal but stream attributes and Convention pragmas are correct.
6968
6969       elsif Has_Private_Component (T) then
6970          if Nkind (N) = N_Pragma then
6971             return False;
6972          else
6973             Error_Msg_N
6974               ("representation item must appear after type is fully defined",
6975                 N);
6976             return True;
6977          end if;
6978       else
6979          return False;
6980       end if;
6981    end Rep_Item_Too_Early;
6982
6983    -----------------------
6984    -- Rep_Item_Too_Late --
6985    -----------------------
6986
6987    function Rep_Item_Too_Late
6988      (T     : Entity_Id;
6989       N     : Node_Id;
6990       FOnly : Boolean := False) return Boolean
6991    is
6992       S           : Entity_Id;
6993       Parent_Type : Entity_Id;
6994
6995       procedure Too_Late;
6996       --  Output the too late message. Note that this is not considered a
6997       --  serious error, since the effect is simply that we ignore the
6998       --  representation clause in this case.
6999
7000       --------------
7001       -- Too_Late --
7002       --------------
7003
7004       procedure Too_Late is
7005       begin
7006          Error_Msg_N ("|representation item appears too late!", N);
7007       end Too_Late;
7008
7009    --  Start of processing for Rep_Item_Too_Late
7010
7011    begin
7012       --  First make sure entity is not frozen (RM 13.1(9)). Exclude imported
7013       --  types, which may be frozen if they appear in a representation clause
7014       --  for a local type.
7015
7016       if Is_Frozen (T)
7017         and then not From_With_Type (T)
7018       then
7019          Too_Late;
7020          S := First_Subtype (T);
7021
7022          if Present (Freeze_Node (S)) then
7023             Error_Msg_NE
7024               ("?no more representation items for }", Freeze_Node (S), S);
7025          end if;
7026
7027          return True;
7028
7029       --  Check for case of non-tagged derived type whose parent either has
7030       --  primitive operations, or is a by reference type (RM 13.1(10)).
7031
7032       elsif Is_Type (T)
7033         and then not FOnly
7034         and then Is_Derived_Type (T)
7035         and then not Is_Tagged_Type (T)
7036       then
7037          Parent_Type := Etype (Base_Type (T));
7038
7039          if Has_Primitive_Operations (Parent_Type) then
7040             Too_Late;
7041             Error_Msg_NE
7042               ("primitive operations already defined for&!", N, Parent_Type);
7043             return True;
7044
7045          elsif Is_By_Reference_Type (Parent_Type) then
7046             Too_Late;
7047             Error_Msg_NE
7048               ("parent type & is a by reference type!", N, Parent_Type);
7049             return True;
7050          end if;
7051       end if;
7052
7053       --  No error, link item into head of chain of rep items for the entity,
7054       --  but avoid chaining if we have an overloadable entity, and the pragma
7055       --  is one that can apply to multiple overloaded entities.
7056
7057       if Is_Overloadable (T)
7058         and then Nkind (N) = N_Pragma
7059       then
7060          declare
7061             Pname : constant Name_Id := Pragma_Name (N);
7062          begin
7063             if Pname = Name_Convention or else
7064                Pname = Name_Import     or else
7065                Pname = Name_Export     or else
7066                Pname = Name_External   or else
7067                Pname = Name_Interface
7068             then
7069                return False;
7070             end if;
7071          end;
7072       end if;
7073
7074       Record_Rep_Item (T, N);
7075       return False;
7076    end Rep_Item_Too_Late;
7077
7078    -------------------------------------
7079    -- Replace_Type_References_Generic --
7080    -------------------------------------
7081
7082    procedure Replace_Type_References_Generic (N : Node_Id; TName : Name_Id) is
7083
7084       function Replace_Node (N : Node_Id) return Traverse_Result;
7085       --  Processes a single node in the traversal procedure below, checking
7086       --  if node N should be replaced, and if so, doing the replacement.
7087
7088       procedure Replace_Type_Refs is new Traverse_Proc (Replace_Node);
7089       --  This instantiation provides the body of Replace_Type_References
7090
7091       ------------------
7092       -- Replace_Node --
7093       ------------------
7094
7095       function Replace_Node (N : Node_Id) return Traverse_Result is
7096          S : Entity_Id;
7097          P : Node_Id;
7098
7099       begin
7100          --  Case of identifier
7101
7102          if Nkind (N) = N_Identifier then
7103
7104             --  If not the type name, all done with this node
7105
7106             if Chars (N) /= TName then
7107                return Skip;
7108
7109             --  Otherwise do the replacement and we are done with this node
7110
7111             else
7112                Replace_Type_Reference (N);
7113                return Skip;
7114             end if;
7115
7116          --  Case of selected component (which is what a qualification
7117          --  looks like in the unanalyzed tree, which is what we have.
7118
7119          elsif Nkind (N) = N_Selected_Component then
7120
7121             --  If selector name is not our type, keeping going (we might
7122             --  still have an occurrence of the type in the prefix).
7123
7124             if Nkind (Selector_Name (N)) /= N_Identifier
7125               or else Chars (Selector_Name (N)) /= TName
7126             then
7127                return OK;
7128
7129             --  Selector name is our type, check qualification
7130
7131             else
7132                --  Loop through scopes and prefixes, doing comparison
7133
7134                S := Current_Scope;
7135                P := Prefix (N);
7136                loop
7137                   --  Continue if no more scopes or scope with no name
7138
7139                   if No (S) or else Nkind (S) not in N_Has_Chars then
7140                      return OK;
7141                   end if;
7142
7143                   --  Do replace if prefix is an identifier matching the
7144                   --  scope that we are currently looking at.
7145
7146                   if Nkind (P) = N_Identifier
7147                     and then Chars (P) = Chars (S)
7148                   then
7149                      Replace_Type_Reference (N);
7150                      return Skip;
7151                   end if;
7152
7153                   --  Go check scope above us if prefix is itself of the
7154                   --  form of a selected component, whose selector matches
7155                   --  the scope we are currently looking at.
7156
7157                   if Nkind (P) = N_Selected_Component
7158                     and then Nkind (Selector_Name (P)) = N_Identifier
7159                     and then Chars (Selector_Name (P)) = Chars (S)
7160                   then
7161                      S := Scope (S);
7162                      P := Prefix (P);
7163
7164                   --  For anything else, we don't have a match, so keep on
7165                   --  going, there are still some weird cases where we may
7166                   --  still have a replacement within the prefix.
7167
7168                   else
7169                      return OK;
7170                   end if;
7171                end loop;
7172             end if;
7173
7174             --  Continue for any other node kind
7175
7176          else
7177             return OK;
7178          end if;
7179       end Replace_Node;
7180
7181    begin
7182       Replace_Type_Refs (N);
7183    end Replace_Type_References_Generic;
7184
7185    -------------------------
7186    -- Same_Representation --
7187    -------------------------
7188
7189    function Same_Representation (Typ1, Typ2 : Entity_Id) return Boolean is
7190       T1 : constant Entity_Id := Underlying_Type (Typ1);
7191       T2 : constant Entity_Id := Underlying_Type (Typ2);
7192
7193    begin
7194       --  A quick check, if base types are the same, then we definitely have
7195       --  the same representation, because the subtype specific representation
7196       --  attributes (Size and Alignment) do not affect representation from
7197       --  the point of view of this test.
7198
7199       if Base_Type (T1) = Base_Type (T2) then
7200          return True;
7201
7202       elsif Is_Private_Type (Base_Type (T2))
7203         and then Base_Type (T1) = Full_View (Base_Type (T2))
7204       then
7205          return True;
7206       end if;
7207
7208       --  Tagged types never have differing representations
7209
7210       if Is_Tagged_Type (T1) then
7211          return True;
7212       end if;
7213
7214       --  Representations are definitely different if conventions differ
7215
7216       if Convention (T1) /= Convention (T2) then
7217          return False;
7218       end if;
7219
7220       --  Representations are different if component alignments differ
7221
7222       if (Is_Record_Type (T1) or else Is_Array_Type (T1))
7223         and then
7224          (Is_Record_Type (T2) or else Is_Array_Type (T2))
7225         and then Component_Alignment (T1) /= Component_Alignment (T2)
7226       then
7227          return False;
7228       end if;
7229
7230       --  For arrays, the only real issue is component size. If we know the
7231       --  component size for both arrays, and it is the same, then that's
7232       --  good enough to know we don't have a change of representation.
7233
7234       if Is_Array_Type (T1) then
7235          if Known_Component_Size (T1)
7236            and then Known_Component_Size (T2)
7237            and then Component_Size (T1) = Component_Size (T2)
7238          then
7239             return True;
7240          end if;
7241       end if;
7242
7243       --  Types definitely have same representation if neither has non-standard
7244       --  representation since default representations are always consistent.
7245       --  If only one has non-standard representation, and the other does not,
7246       --  then we consider that they do not have the same representation. They
7247       --  might, but there is no way of telling early enough.
7248
7249       if Has_Non_Standard_Rep (T1) then
7250          if not Has_Non_Standard_Rep (T2) then
7251             return False;
7252          end if;
7253       else
7254          return not Has_Non_Standard_Rep (T2);
7255       end if;
7256
7257       --  Here the two types both have non-standard representation, and we need
7258       --  to determine if they have the same non-standard representation.
7259
7260       --  For arrays, we simply need to test if the component sizes are the
7261       --  same. Pragma Pack is reflected in modified component sizes, so this
7262       --  check also deals with pragma Pack.
7263
7264       if Is_Array_Type (T1) then
7265          return Component_Size (T1) = Component_Size (T2);
7266
7267       --  Tagged types always have the same representation, because it is not
7268       --  possible to specify different representations for common fields.
7269
7270       elsif Is_Tagged_Type (T1) then
7271          return True;
7272
7273       --  Case of record types
7274
7275       elsif Is_Record_Type (T1) then
7276
7277          --  Packed status must conform
7278
7279          if Is_Packed (T1) /= Is_Packed (T2) then
7280             return False;
7281
7282          --  Otherwise we must check components. Typ2 maybe a constrained
7283          --  subtype with fewer components, so we compare the components
7284          --  of the base types.
7285
7286          else
7287             Record_Case : declare
7288                CD1, CD2 : Entity_Id;
7289
7290                function Same_Rep return Boolean;
7291                --  CD1 and CD2 are either components or discriminants. This
7292                --  function tests whether the two have the same representation
7293
7294                --------------
7295                -- Same_Rep --
7296                --------------
7297
7298                function Same_Rep return Boolean is
7299                begin
7300                   if No (Component_Clause (CD1)) then
7301                      return No (Component_Clause (CD2));
7302
7303                   else
7304                      return
7305                         Present (Component_Clause (CD2))
7306                           and then
7307                         Component_Bit_Offset (CD1) = Component_Bit_Offset (CD2)
7308                           and then
7309                         Esize (CD1) = Esize (CD2);
7310                   end if;
7311                end Same_Rep;
7312
7313             --  Start of processing for Record_Case
7314
7315             begin
7316                if Has_Discriminants (T1) then
7317                   CD1 := First_Discriminant (T1);
7318                   CD2 := First_Discriminant (T2);
7319
7320                   --  The number of discriminants may be different if the
7321                   --  derived type has fewer (constrained by values). The
7322                   --  invisible discriminants retain the representation of
7323                   --  the original, so the discrepancy does not per se
7324                   --  indicate a different representation.
7325
7326                   while Present (CD1)
7327                     and then Present (CD2)
7328                   loop
7329                      if not Same_Rep then
7330                         return False;
7331                      else
7332                         Next_Discriminant (CD1);
7333                         Next_Discriminant (CD2);
7334                      end if;
7335                   end loop;
7336                end if;
7337
7338                CD1 := First_Component (Underlying_Type (Base_Type (T1)));
7339                CD2 := First_Component (Underlying_Type (Base_Type (T2)));
7340
7341                while Present (CD1) loop
7342                   if not Same_Rep then
7343                      return False;
7344                   else
7345                      Next_Component (CD1);
7346                      Next_Component (CD2);
7347                   end if;
7348                end loop;
7349
7350                return True;
7351             end Record_Case;
7352          end if;
7353
7354       --  For enumeration types, we must check each literal to see if the
7355       --  representation is the same. Note that we do not permit enumeration
7356       --  representation clauses for Character and Wide_Character, so these
7357       --  cases were already dealt with.
7358
7359       elsif Is_Enumeration_Type (T1) then
7360          Enumeration_Case : declare
7361             L1, L2 : Entity_Id;
7362
7363          begin
7364             L1 := First_Literal (T1);
7365             L2 := First_Literal (T2);
7366
7367             while Present (L1) loop
7368                if Enumeration_Rep (L1) /= Enumeration_Rep (L2) then
7369                   return False;
7370                else
7371                   Next_Literal (L1);
7372                   Next_Literal (L2);
7373                end if;
7374             end loop;
7375
7376             return True;
7377
7378          end Enumeration_Case;
7379
7380       --  Any other types have the same representation for these purposes
7381
7382       else
7383          return True;
7384       end if;
7385    end Same_Representation;
7386
7387    ----------------
7388    -- Set_Biased --
7389    ----------------
7390
7391    procedure Set_Biased
7392      (E      : Entity_Id;
7393       N      : Node_Id;
7394       Msg    : String;
7395       Biased : Boolean := True)
7396    is
7397    begin
7398       if Biased then
7399          Set_Has_Biased_Representation (E);
7400
7401          if Warn_On_Biased_Representation then
7402             Error_Msg_NE
7403               ("?" & Msg & " forces biased representation for&", N, E);
7404          end if;
7405       end if;
7406    end Set_Biased;
7407
7408    --------------------
7409    -- Set_Enum_Esize --
7410    --------------------
7411
7412    procedure Set_Enum_Esize (T : Entity_Id) is
7413       Lo : Uint;
7414       Hi : Uint;
7415       Sz : Nat;
7416
7417    begin
7418       Init_Alignment (T);
7419
7420       --  Find the minimum standard size (8,16,32,64) that fits
7421
7422       Lo := Enumeration_Rep (Entity (Type_Low_Bound (T)));
7423       Hi := Enumeration_Rep (Entity (Type_High_Bound (T)));
7424
7425       if Lo < 0 then
7426          if Lo >= -Uint_2**07 and then Hi < Uint_2**07 then
7427             Sz := Standard_Character_Size;  -- May be > 8 on some targets
7428
7429          elsif Lo >= -Uint_2**15 and then Hi < Uint_2**15 then
7430             Sz := 16;
7431
7432          elsif Lo >= -Uint_2**31 and then Hi < Uint_2**31 then
7433             Sz := 32;
7434
7435          else pragma Assert (Lo >= -Uint_2**63 and then Hi < Uint_2**63);
7436             Sz := 64;
7437          end if;
7438
7439       else
7440          if Hi < Uint_2**08 then
7441             Sz := Standard_Character_Size;  -- May be > 8 on some targets
7442
7443          elsif Hi < Uint_2**16 then
7444             Sz := 16;
7445
7446          elsif Hi < Uint_2**32 then
7447             Sz := 32;
7448
7449          else pragma Assert (Hi < Uint_2**63);
7450             Sz := 64;
7451          end if;
7452       end if;
7453
7454       --  That minimum is the proper size unless we have a foreign convention
7455       --  and the size required is 32 or less, in which case we bump the size
7456       --  up to 32. This is required for C and C++ and seems reasonable for
7457       --  all other foreign conventions.
7458
7459       if Has_Foreign_Convention (T)
7460         and then Esize (T) < Standard_Integer_Size
7461       then
7462          Init_Esize (T, Standard_Integer_Size);
7463       else
7464          Init_Esize (T, Sz);
7465       end if;
7466    end Set_Enum_Esize;
7467
7468    ------------------------------
7469    -- Validate_Address_Clauses --
7470    ------------------------------
7471
7472    procedure Validate_Address_Clauses is
7473    begin
7474       for J in Address_Clause_Checks.First .. Address_Clause_Checks.Last loop
7475          declare
7476             ACCR : Address_Clause_Check_Record
7477                      renames Address_Clause_Checks.Table (J);
7478
7479             Expr : Node_Id;
7480
7481             X_Alignment : Uint;
7482             Y_Alignment : Uint;
7483
7484             X_Size : Uint;
7485             Y_Size : Uint;
7486
7487          begin
7488             --  Skip processing of this entry if warning already posted
7489
7490             if not Address_Warning_Posted (ACCR.N) then
7491
7492                Expr := Original_Node (Expression (ACCR.N));
7493
7494                --  Get alignments
7495
7496                X_Alignment := Alignment (ACCR.X);
7497                Y_Alignment := Alignment (ACCR.Y);
7498
7499                --  Similarly obtain sizes
7500
7501                X_Size := Esize (ACCR.X);
7502                Y_Size := Esize (ACCR.Y);
7503
7504                --  Check for large object overlaying smaller one
7505
7506                if Y_Size > Uint_0
7507                  and then X_Size > Uint_0
7508                  and then X_Size > Y_Size
7509                then
7510                   Error_Msg_NE
7511                     ("?& overlays smaller object", ACCR.N, ACCR.X);
7512                   Error_Msg_N
7513                     ("\?program execution may be erroneous", ACCR.N);
7514                   Error_Msg_Uint_1 := X_Size;
7515                   Error_Msg_NE
7516                     ("\?size of & is ^", ACCR.N, ACCR.X);
7517                   Error_Msg_Uint_1 := Y_Size;
7518                   Error_Msg_NE
7519                     ("\?size of & is ^", ACCR.N, ACCR.Y);
7520
7521                --  Check for inadequate alignment, both of the base object
7522                --  and of the offset, if any.
7523
7524                --  Note: we do not check the alignment if we gave a size
7525                --  warning, since it would likely be redundant.
7526
7527                elsif Y_Alignment /= Uint_0
7528                  and then (Y_Alignment < X_Alignment
7529                              or else (ACCR.Off
7530                                         and then
7531                                           Nkind (Expr) = N_Attribute_Reference
7532                                         and then
7533                                           Attribute_Name (Expr) = Name_Address
7534                                         and then
7535                                           Has_Compatible_Alignment
7536                                             (ACCR.X, Prefix (Expr))
7537                                              /= Known_Compatible))
7538                then
7539                   Error_Msg_NE
7540                     ("?specified address for& may be inconsistent "
7541                        & "with alignment",
7542                      ACCR.N, ACCR.X);
7543                   Error_Msg_N
7544                     ("\?program execution may be erroneous (RM 13.3(27))",
7545                      ACCR.N);
7546                   Error_Msg_Uint_1 := X_Alignment;
7547                   Error_Msg_NE
7548                     ("\?alignment of & is ^",
7549                      ACCR.N, ACCR.X);
7550                   Error_Msg_Uint_1 := Y_Alignment;
7551                   Error_Msg_NE
7552                     ("\?alignment of & is ^",
7553                      ACCR.N, ACCR.Y);
7554                   if Y_Alignment >= X_Alignment then
7555                      Error_Msg_N
7556                       ("\?but offset is not multiple of alignment",
7557                        ACCR.N);
7558                   end if;
7559                end if;
7560             end if;
7561          end;
7562       end loop;
7563    end Validate_Address_Clauses;
7564
7565    ---------------------------
7566    -- Validate_Independence --
7567    ---------------------------
7568
7569    procedure Validate_Independence is
7570       SU   : constant Uint := UI_From_Int (System_Storage_Unit);
7571       N    : Node_Id;
7572       E    : Entity_Id;
7573       IC   : Boolean;
7574       Comp : Entity_Id;
7575       Addr : Node_Id;
7576       P    : Node_Id;
7577
7578       procedure Check_Array_Type (Atyp : Entity_Id);
7579       --  Checks if the array type Atyp has independent components, and
7580       --  if not, outputs an appropriate set of error messages.
7581
7582       procedure No_Independence;
7583       --  Output message that independence cannot be guaranteed
7584
7585       function OK_Component (C : Entity_Id) return Boolean;
7586       --  Checks one component to see if it is independently accessible, and
7587       --  if so yields True, otherwise yields False if independent access
7588       --  cannot be guaranteed. This is a conservative routine, it only
7589       --  returns True if it knows for sure, it returns False if it knows
7590       --  there is a problem, or it cannot be sure there is no problem.
7591
7592       procedure Reason_Bad_Component (C : Entity_Id);
7593       --  Outputs continuation message if a reason can be determined for
7594       --  the component C being bad.
7595
7596       ----------------------
7597       -- Check_Array_Type --
7598       ----------------------
7599
7600       procedure Check_Array_Type (Atyp : Entity_Id) is
7601          Ctyp : constant Entity_Id := Component_Type (Atyp);
7602
7603       begin
7604          --  OK if no alignment clause, no pack, and no component size
7605
7606          if not Has_Component_Size_Clause (Atyp)
7607            and then not Has_Alignment_Clause (Atyp)
7608            and then not Is_Packed (Atyp)
7609          then
7610             return;
7611          end if;
7612
7613          --  Check actual component size
7614
7615          if not Known_Component_Size (Atyp)
7616            or else not (Addressable (Component_Size (Atyp))
7617                           and then Component_Size (Atyp) < 64)
7618            or else Component_Size (Atyp) mod Esize (Ctyp) /= 0
7619          then
7620             No_Independence;
7621
7622             --  Bad component size, check reason
7623
7624             if Has_Component_Size_Clause (Atyp) then
7625                P :=
7626                  Get_Attribute_Definition_Clause
7627                    (Atyp, Attribute_Component_Size);
7628
7629                if Present (P) then
7630                   Error_Msg_Sloc := Sloc (P);
7631                   Error_Msg_N ("\because of Component_Size clause#", N);
7632                   return;
7633                end if;
7634             end if;
7635
7636             if Is_Packed (Atyp) then
7637                P := Get_Rep_Pragma (Atyp, Name_Pack);
7638
7639                if Present (P) then
7640                   Error_Msg_Sloc := Sloc (P);
7641                   Error_Msg_N ("\because of pragma Pack#", N);
7642                   return;
7643                end if;
7644             end if;
7645
7646             --  No reason found, just return
7647
7648             return;
7649          end if;
7650
7651          --  Array type is OK independence-wise
7652
7653          return;
7654       end Check_Array_Type;
7655
7656       ---------------------
7657       -- No_Independence --
7658       ---------------------
7659
7660       procedure No_Independence is
7661       begin
7662          if Pragma_Name (N) = Name_Independent then
7663             Error_Msg_NE
7664               ("independence cannot be guaranteed for&", N, E);
7665          else
7666             Error_Msg_NE
7667               ("independent components cannot be guaranteed for&", N, E);
7668          end if;
7669       end No_Independence;
7670
7671       ------------------
7672       -- OK_Component --
7673       ------------------
7674
7675       function OK_Component (C : Entity_Id) return Boolean is
7676          Rec  : constant Entity_Id := Scope (C);
7677          Ctyp : constant Entity_Id := Etype (C);
7678
7679       begin
7680          --  OK if no component clause, no Pack, and no alignment clause
7681
7682          if No (Component_Clause (C))
7683            and then not Is_Packed (Rec)
7684            and then not Has_Alignment_Clause (Rec)
7685          then
7686             return True;
7687          end if;
7688
7689          --  Here we look at the actual component layout. A component is
7690          --  addressable if its size is a multiple of the Esize of the
7691          --  component type, and its starting position in the record has
7692          --  appropriate alignment, and the record itself has appropriate
7693          --  alignment to guarantee the component alignment.
7694
7695          --  Make sure sizes are static, always assume the worst for any
7696          --  cases where we cannot check static values.
7697
7698          if not (Known_Static_Esize (C)
7699                   and then Known_Static_Esize (Ctyp))
7700          then
7701             return False;
7702          end if;
7703
7704          --  Size of component must be addressable or greater than 64 bits
7705          --  and a multiple of bytes.
7706
7707          if not Addressable (Esize (C))
7708            and then Esize (C) < Uint_64
7709          then
7710             return False;
7711          end if;
7712
7713          --  Check size is proper multiple
7714
7715          if Esize (C) mod Esize (Ctyp) /= 0 then
7716             return False;
7717          end if;
7718
7719          --  Check alignment of component is OK
7720
7721          if not Known_Component_Bit_Offset (C)
7722            or else Component_Bit_Offset (C) < Uint_0
7723            or else Component_Bit_Offset (C) mod Esize (Ctyp) /= 0
7724          then
7725             return False;
7726          end if;
7727
7728          --  Check alignment of record type is OK
7729
7730          if not Known_Alignment (Rec)
7731            or else (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
7732          then
7733             return False;
7734          end if;
7735
7736          --  All tests passed, component is addressable
7737
7738          return True;
7739       end OK_Component;
7740
7741       --------------------------
7742       -- Reason_Bad_Component --
7743       --------------------------
7744
7745       procedure Reason_Bad_Component (C : Entity_Id) is
7746          Rec  : constant Entity_Id := Scope (C);
7747          Ctyp : constant Entity_Id := Etype (C);
7748
7749       begin
7750          --  If component clause present assume that's the problem
7751
7752          if Present (Component_Clause (C)) then
7753             Error_Msg_Sloc := Sloc (Component_Clause (C));
7754             Error_Msg_N ("\because of Component_Clause#", N);
7755             return;
7756          end if;
7757
7758          --  If pragma Pack clause present, assume that's the problem
7759
7760          if Is_Packed (Rec) then
7761             P := Get_Rep_Pragma (Rec, Name_Pack);
7762
7763             if Present (P) then
7764                Error_Msg_Sloc := Sloc (P);
7765                Error_Msg_N ("\because of pragma Pack#", N);
7766                return;
7767             end if;
7768          end if;
7769
7770          --  See if record has bad alignment clause
7771
7772          if Has_Alignment_Clause (Rec)
7773            and then Known_Alignment (Rec)
7774            and then (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
7775          then
7776             P := Get_Attribute_Definition_Clause (Rec, Attribute_Alignment);
7777
7778             if Present (P) then
7779                Error_Msg_Sloc := Sloc (P);
7780                Error_Msg_N ("\because of Alignment clause#", N);
7781             end if;
7782          end if;
7783
7784          --  Couldn't find a reason, so return without a message
7785
7786          return;
7787       end Reason_Bad_Component;
7788
7789    --  Start of processing for Validate_Independence
7790
7791    begin
7792       for J in Independence_Checks.First .. Independence_Checks.Last loop
7793          N  := Independence_Checks.Table (J).N;
7794          E  := Independence_Checks.Table (J).E;
7795          IC := Pragma_Name (N) = Name_Independent_Components;
7796
7797          --  Deal with component case
7798
7799          if Ekind (E) = E_Discriminant or else Ekind (E) = E_Component then
7800             if not OK_Component (E) then
7801                No_Independence;
7802                Reason_Bad_Component (E);
7803                goto Continue;
7804             end if;
7805          end if;
7806
7807          --  Deal with record with Independent_Components
7808
7809          if IC and then Is_Record_Type (E) then
7810             Comp := First_Component_Or_Discriminant (E);
7811             while Present (Comp) loop
7812                if not OK_Component (Comp) then
7813                   No_Independence;
7814                   Reason_Bad_Component (Comp);
7815                   goto Continue;
7816                end if;
7817
7818                Next_Component_Or_Discriminant (Comp);
7819             end loop;
7820          end if;
7821
7822          --  Deal with address clause case
7823
7824          if Is_Object (E) then
7825             Addr := Address_Clause (E);
7826
7827             if Present (Addr) then
7828                No_Independence;
7829                Error_Msg_Sloc := Sloc (Addr);
7830                Error_Msg_N ("\because of Address clause#", N);
7831                goto Continue;
7832             end if;
7833          end if;
7834
7835          --  Deal with independent components for array type
7836
7837          if IC and then Is_Array_Type (E) then
7838             Check_Array_Type (E);
7839          end if;
7840
7841          --  Deal with independent components for array object
7842
7843          if IC and then Is_Object (E) and then Is_Array_Type (Etype (E)) then
7844             Check_Array_Type (Etype (E));
7845          end if;
7846
7847       <<Continue>> null;
7848       end loop;
7849    end Validate_Independence;
7850
7851    -----------------------------------
7852    -- Validate_Unchecked_Conversion --
7853    -----------------------------------
7854
7855    procedure Validate_Unchecked_Conversion
7856      (N        : Node_Id;
7857       Act_Unit : Entity_Id)
7858    is
7859       Source : Entity_Id;
7860       Target : Entity_Id;
7861       Vnode  : Node_Id;
7862
7863    begin
7864       --  Obtain source and target types. Note that we call Ancestor_Subtype
7865       --  here because the processing for generic instantiation always makes
7866       --  subtypes, and we want the original frozen actual types.
7867
7868       --  If we are dealing with private types, then do the check on their
7869       --  fully declared counterparts if the full declarations have been
7870       --  encountered (they don't have to be visible, but they must exist!)
7871
7872       Source := Ancestor_Subtype (Etype (First_Formal (Act_Unit)));
7873
7874       if Is_Private_Type (Source)
7875         and then Present (Underlying_Type (Source))
7876       then
7877          Source := Underlying_Type (Source);
7878       end if;
7879
7880       Target := Ancestor_Subtype (Etype (Act_Unit));
7881
7882       --  If either type is generic, the instantiation happens within a generic
7883       --  unit, and there is nothing to check. The proper check
7884       --  will happen when the enclosing generic is instantiated.
7885
7886       if Is_Generic_Type (Source) or else Is_Generic_Type (Target) then
7887          return;
7888       end if;
7889
7890       if Is_Private_Type (Target)
7891         and then Present (Underlying_Type (Target))
7892       then
7893          Target := Underlying_Type (Target);
7894       end if;
7895
7896       --  Source may be unconstrained array, but not target
7897
7898       if Is_Array_Type (Target)
7899         and then not Is_Constrained (Target)
7900       then
7901          Error_Msg_N
7902            ("unchecked conversion to unconstrained array not allowed", N);
7903          return;
7904       end if;
7905
7906       --  Warn if conversion between two different convention pointers
7907
7908       if Is_Access_Type (Target)
7909         and then Is_Access_Type (Source)
7910         and then Convention (Target) /= Convention (Source)
7911         and then Warn_On_Unchecked_Conversion
7912       then
7913          --  Give warnings for subprogram pointers only on most targets. The
7914          --  exception is VMS, where data pointers can have different lengths
7915          --  depending on the pointer convention.
7916
7917          if Is_Access_Subprogram_Type (Target)
7918            or else Is_Access_Subprogram_Type (Source)
7919            or else OpenVMS_On_Target
7920          then
7921             Error_Msg_N
7922               ("?conversion between pointers with different conventions!", N);
7923          end if;
7924       end if;
7925
7926       --  Warn if one of the operands is Ada.Calendar.Time. Do not emit a
7927       --  warning when compiling GNAT-related sources.
7928
7929       if Warn_On_Unchecked_Conversion
7930         and then not In_Predefined_Unit (N)
7931         and then RTU_Loaded (Ada_Calendar)
7932         and then
7933           (Chars (Source) = Name_Time
7934              or else
7935            Chars (Target) = Name_Time)
7936       then
7937          --  If Ada.Calendar is loaded and the name of one of the operands is
7938          --  Time, there is a good chance that this is Ada.Calendar.Time.
7939
7940          declare
7941             Calendar_Time : constant Entity_Id :=
7942                               Full_View (RTE (RO_CA_Time));
7943          begin
7944             pragma Assert (Present (Calendar_Time));
7945
7946             if Source = Calendar_Time
7947               or else Target = Calendar_Time
7948             then
7949                Error_Msg_N
7950                  ("?representation of 'Time values may change between " &
7951                   "'G'N'A'T versions", N);
7952             end if;
7953          end;
7954       end if;
7955
7956       --  Make entry in unchecked conversion table for later processing by
7957       --  Validate_Unchecked_Conversions, which will check sizes and alignments
7958       --  (using values set by the back-end where possible). This is only done
7959       --  if the appropriate warning is active.
7960
7961       if Warn_On_Unchecked_Conversion then
7962          Unchecked_Conversions.Append
7963            (New_Val => UC_Entry'
7964               (Eloc   => Sloc (N),
7965                Source => Source,
7966                Target => Target));
7967
7968          --  If both sizes are known statically now, then back end annotation
7969          --  is not required to do a proper check but if either size is not
7970          --  known statically, then we need the annotation.
7971
7972          if Known_Static_RM_Size (Source)
7973            and then Known_Static_RM_Size (Target)
7974          then
7975             null;
7976          else
7977             Back_Annotate_Rep_Info := True;
7978          end if;
7979       end if;
7980
7981       --  If unchecked conversion to access type, and access type is declared
7982       --  in the same unit as the unchecked conversion, then set the
7983       --  No_Strict_Aliasing flag (no strict aliasing is implicit in this
7984       --  situation).
7985
7986       if Is_Access_Type (Target) and then
7987         In_Same_Source_Unit (Target, N)
7988       then
7989          Set_No_Strict_Aliasing (Implementation_Base_Type (Target));
7990       end if;
7991
7992       --  Generate N_Validate_Unchecked_Conversion node for back end in
7993       --  case the back end needs to perform special validation checks.
7994
7995       --  Shouldn't this be in Exp_Ch13, since the check only gets done
7996       --  if we have full expansion and the back end is called ???
7997
7998       Vnode :=
7999         Make_Validate_Unchecked_Conversion (Sloc (N));
8000       Set_Source_Type (Vnode, Source);
8001       Set_Target_Type (Vnode, Target);
8002
8003       --  If the unchecked conversion node is in a list, just insert before it.
8004       --  If not we have some strange case, not worth bothering about.
8005
8006       if Is_List_Member (N) then
8007          Insert_After (N, Vnode);
8008       end if;
8009    end Validate_Unchecked_Conversion;
8010
8011    ------------------------------------
8012    -- Validate_Unchecked_Conversions --
8013    ------------------------------------
8014
8015    procedure Validate_Unchecked_Conversions is
8016    begin
8017       for N in Unchecked_Conversions.First .. Unchecked_Conversions.Last loop
8018          declare
8019             T : UC_Entry renames Unchecked_Conversions.Table (N);
8020
8021             Eloc   : constant Source_Ptr := T.Eloc;
8022             Source : constant Entity_Id  := T.Source;
8023             Target : constant Entity_Id  := T.Target;
8024
8025             Source_Siz    : Uint;
8026             Target_Siz    : Uint;
8027
8028          begin
8029             --  This validation check, which warns if we have unequal sizes for
8030             --  unchecked conversion, and thus potentially implementation
8031             --  dependent semantics, is one of the few occasions on which we
8032             --  use the official RM size instead of Esize. See description in
8033             --  Einfo "Handling of Type'Size Values" for details.
8034
8035             if Serious_Errors_Detected = 0
8036               and then Known_Static_RM_Size (Source)
8037               and then Known_Static_RM_Size (Target)
8038
8039               --  Don't do the check if warnings off for either type, note the
8040               --  deliberate use of OR here instead of OR ELSE to get the flag
8041               --  Warnings_Off_Used set for both types if appropriate.
8042
8043               and then not (Has_Warnings_Off (Source)
8044                               or
8045                             Has_Warnings_Off (Target))
8046             then
8047                Source_Siz := RM_Size (Source);
8048                Target_Siz := RM_Size (Target);
8049
8050                if Source_Siz /= Target_Siz then
8051                   Error_Msg
8052                     ("?types for unchecked conversion have different sizes!",
8053                      Eloc);
8054
8055                   if All_Errors_Mode then
8056                      Error_Msg_Name_1 := Chars (Source);
8057                      Error_Msg_Uint_1 := Source_Siz;
8058                      Error_Msg_Name_2 := Chars (Target);
8059                      Error_Msg_Uint_2 := Target_Siz;
8060                      Error_Msg ("\size of % is ^, size of % is ^?", Eloc);
8061
8062                      Error_Msg_Uint_1 := UI_Abs (Source_Siz - Target_Siz);
8063
8064                      if Is_Discrete_Type (Source)
8065                        and then Is_Discrete_Type (Target)
8066                      then
8067                         if Source_Siz > Target_Siz then
8068                            Error_Msg
8069                              ("\?^ high order bits of source will be ignored!",
8070                               Eloc);
8071
8072                         elsif Is_Unsigned_Type (Source) then
8073                            Error_Msg
8074                              ("\?source will be extended with ^ high order " &
8075                               "zero bits?!", Eloc);
8076
8077                         else
8078                            Error_Msg
8079                              ("\?source will be extended with ^ high order " &
8080                               "sign bits!",
8081                               Eloc);
8082                         end if;
8083
8084                      elsif Source_Siz < Target_Siz then
8085                         if Is_Discrete_Type (Target) then
8086                            if Bytes_Big_Endian then
8087                               Error_Msg
8088                                 ("\?target value will include ^ undefined " &
8089                                  "low order bits!",
8090                                  Eloc);
8091                            else
8092                               Error_Msg
8093                                 ("\?target value will include ^ undefined " &
8094                                  "high order bits!",
8095                                  Eloc);
8096                            end if;
8097
8098                         else
8099                            Error_Msg
8100                              ("\?^ trailing bits of target value will be " &
8101                               "undefined!", Eloc);
8102                         end if;
8103
8104                      else pragma Assert (Source_Siz > Target_Siz);
8105                         Error_Msg
8106                           ("\?^ trailing bits of source will be ignored!",
8107                            Eloc);
8108                      end if;
8109                   end if;
8110                end if;
8111             end if;
8112
8113             --  If both types are access types, we need to check the alignment.
8114             --  If the alignment of both is specified, we can do it here.
8115
8116             if Serious_Errors_Detected = 0
8117               and then Ekind (Source) in Access_Kind
8118               and then Ekind (Target) in Access_Kind
8119               and then Target_Strict_Alignment
8120               and then Present (Designated_Type (Source))
8121               and then Present (Designated_Type (Target))
8122             then
8123                declare
8124                   D_Source : constant Entity_Id := Designated_Type (Source);
8125                   D_Target : constant Entity_Id := Designated_Type (Target);
8126
8127                begin
8128                   if Known_Alignment (D_Source)
8129                     and then Known_Alignment (D_Target)
8130                   then
8131                      declare
8132                         Source_Align : constant Uint := Alignment (D_Source);
8133                         Target_Align : constant Uint := Alignment (D_Target);
8134
8135                      begin
8136                         if Source_Align < Target_Align
8137                           and then not Is_Tagged_Type (D_Source)
8138
8139                           --  Suppress warning if warnings suppressed on either
8140                           --  type or either designated type. Note the use of
8141                           --  OR here instead of OR ELSE. That is intentional,
8142                           --  we would like to set flag Warnings_Off_Used in
8143                           --  all types for which warnings are suppressed.
8144
8145                           and then not (Has_Warnings_Off (D_Source)
8146                                           or
8147                                         Has_Warnings_Off (D_Target)
8148                                           or
8149                                         Has_Warnings_Off (Source)
8150                                           or
8151                                         Has_Warnings_Off (Target))
8152                         then
8153                            Error_Msg_Uint_1 := Target_Align;
8154                            Error_Msg_Uint_2 := Source_Align;
8155                            Error_Msg_Node_1 := D_Target;
8156                            Error_Msg_Node_2 := D_Source;
8157                            Error_Msg
8158                              ("?alignment of & (^) is stricter than " &
8159                               "alignment of & (^)!", Eloc);
8160                            Error_Msg
8161                              ("\?resulting access value may have invalid " &
8162                               "alignment!", Eloc);
8163                         end if;
8164                      end;
8165                   end if;
8166                end;
8167             end if;
8168          end;
8169       end loop;
8170    end Validate_Unchecked_Conversions;
8171
8172 end Sem_Ch13;