OSDN Git Service

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