OSDN Git Service

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