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