2ff16651c61c8dd17f09b5069e26c593d7aaec7c
[platform/upstream/gcc.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-2016, 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 Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Elists;   use Elists;
32 with Errout;   use Errout;
33 with Expander; use Expander;
34 with Exp_Disp; use Exp_Disp;
35 with Exp_Tss;  use Exp_Tss;
36 with Exp_Util; use Exp_Util;
37 with Freeze;   use Freeze;
38 with Ghost;    use Ghost;
39 with Lib;      use Lib;
40 with Lib.Xref; use Lib.Xref;
41 with Namet;    use Namet;
42 with Nlists;   use Nlists;
43 with Nmake;    use Nmake;
44 with Opt;      use Opt;
45 with Restrict; use Restrict;
46 with Rident;   use Rident;
47 with Rtsfind;  use Rtsfind;
48 with Sem;      use Sem;
49 with Sem_Aux;  use Sem_Aux;
50 with Sem_Case; use Sem_Case;
51 with Sem_Ch3;  use Sem_Ch3;
52 with Sem_Ch6;  use Sem_Ch6;
53 with Sem_Ch8;  use Sem_Ch8;
54 with Sem_Dim;  use Sem_Dim;
55 with Sem_Disp; use Sem_Disp;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Prag; use Sem_Prag;
58 with Sem_Res;  use Sem_Res;
59 with Sem_Type; use Sem_Type;
60 with Sem_Util; use Sem_Util;
61 with Sem_Warn; use Sem_Warn;
62 with Sinput;   use Sinput;
63 with Snames;   use Snames;
64 with Stand;    use Stand;
65 with Sinfo;    use Sinfo;
66 with Targparm; use Targparm;
67 with Ttypes;   use Ttypes;
68 with Tbuild;   use Tbuild;
69 with Urealp;   use Urealp;
70 with Warnsw;   use Warnsw;
71
72 with GNAT.Heap_Sort_G;
73
74 package body Sem_Ch13 is
75
76    SSU : constant Pos := System_Storage_Unit;
77    --  Convenient short hand for commonly used constant
78
79    -----------------------
80    -- Local Subprograms --
81    -----------------------
82
83    procedure Alignment_Check_For_Size_Change (Typ : Entity_Id; Size : Uint);
84    --  This routine is called after setting one of the sizes of type entity
85    --  Typ to Size. The purpose is to deal with the situation of a derived
86    --  type whose inherited alignment is no longer appropriate for the new
87    --  size value. In this case, we reset the Alignment to unknown.
88
89    procedure Build_Discrete_Static_Predicate
90      (Typ  : Entity_Id;
91       Expr : Node_Id;
92       Nam  : Name_Id);
93    --  Given a predicated type Typ, where Typ is a discrete static subtype,
94    --  whose predicate expression is Expr, tests if Expr is a static predicate,
95    --  and if so, builds the predicate range list. Nam is the name of the one
96    --  argument to the predicate function. Occurrences of the type name in the
97    --  predicate expression have been replaced by identifier references to this
98    --  name, which is unique, so any identifier with Chars matching Nam must be
99    --  a reference to the type. If the predicate is non-static, this procedure
100    --  returns doing nothing. If the predicate is static, then the predicate
101    --  list is stored in Static_Discrete_Predicate (Typ), and the Expr is
102    --  rewritten as a canonicalized membership operation.
103
104    function Build_Export_Import_Pragma
105      (Asp : Node_Id;
106       Id  : Entity_Id) return Node_Id;
107    --  Create the corresponding pragma for aspect Export or Import denoted by
108    --  Asp. Id is the related entity subject to the aspect. Return Empty when
109    --  the expression of aspect Asp evaluates to False or is erroneous.
110
111    function Build_Predicate_Function_Declaration
112       (Typ : Entity_Id) return Node_Id;
113    --  Build the declaration for a predicate function. The declaration is built
114    --  at the end of the declarative part containing the type definition, which
115    --  may be before the freeze point of the type. The predicate expression is
116    --  pre-analyzed at this point, to catch visibility errors.
117
118    procedure Build_Predicate_Functions (Typ : Entity_Id; N : Node_Id);
119    --  If Typ has predicates (indicated by Has_Predicates being set for Typ),
120    --  then either there are pragma Predicate entries on the rep chain for the
121    --  type (note that Predicate aspects are converted to pragma Predicate), or
122    --  there are inherited aspects from a parent type, or ancestor subtypes.
123    --  This procedure builds body for the Predicate function that tests these
124    --  predicates. N is the freeze node for the type. The spec of the function
125    --  is inserted before the freeze node, and the body of the function is
126    --  inserted after the freeze node. If the predicate expression has a least
127    --  one Raise_Expression, then this procedure also builds the M version of
128    --  the predicate function for use in membership tests.
129
130    procedure Check_Pool_Size_Clash (Ent : Entity_Id; SP, SS : Node_Id);
131    --  Called if both Storage_Pool and Storage_Size attribute definition
132    --  clauses (SP and SS) are present for entity Ent. Issue error message.
133
134    procedure Freeze_Entity_Checks (N : Node_Id);
135    --  Called from Analyze_Freeze_Entity and Analyze_Generic_Freeze Entity
136    --  to generate appropriate semantic checks that are delayed until this
137    --  point (they had to be delayed this long for cases of delayed aspects,
138    --  e.g. analysis of statically predicated subtypes in choices, for which
139    --  we have to be sure the subtypes in question are frozen before checking).
140
141    function Get_Alignment_Value (Expr : Node_Id) return Uint;
142    --  Given the expression for an alignment value, returns the corresponding
143    --  Uint value. If the value is inappropriate, then error messages are
144    --  posted as required, and a value of No_Uint is returned.
145
146    procedure Get_Interfacing_Aspects
147      (Iface_Asp : Node_Id;
148       Conv_Asp  : out Node_Id;
149       EN_Asp    : out Node_Id;
150       Expo_Asp  : out Node_Id;
151       Imp_Asp   : out Node_Id;
152       LN_Asp    : out Node_Id;
153       Do_Checks : Boolean := False);
154    --  Given a single interfacing aspect Iface_Asp, retrieve other interfacing
155    --  aspects that apply to the same related entity. The aspects considered by
156    --  this routine are as follows:
157    --
158    --    Conv_Asp - aspect Convention
159    --    EN_Asp   - aspect External_Name
160    --    Expo_Asp - aspect Export
161    --    Imp_Asp  - aspect Import
162    --    LN_Asp   - aspect Link_Name
163    --
164    --  When flag Do_Checks is set, this routine will flag duplicate uses of
165    --  aspects.
166
167    function Is_Operational_Item (N : Node_Id) return Boolean;
168    --  A specification for a stream attribute is allowed before the full type
169    --  is declared, as explained in AI-00137 and the corrigendum. Attributes
170    --  that do not specify a representation characteristic are operational
171    --  attributes.
172
173    function Is_Predicate_Static
174      (Expr : Node_Id;
175       Nam  : Name_Id) return Boolean;
176    --  Given predicate expression Expr, tests if Expr is predicate-static in
177    --  the sense of the rules in (RM 3.2.4 (15-24)). Occurrences of the type
178    --  name in the predicate expression have been replaced by references to
179    --  an identifier whose Chars field is Nam. This name is unique, so any
180    --  identifier with Chars matching Nam must be a reference to the type.
181    --  Returns True if the expression is predicate-static and False otherwise,
182    --  but is not in the business of setting flags or issuing error messages.
183    --
184    --  Only scalar types can have static predicates, so False is always
185    --  returned for non-scalar types.
186    --
187    --  Note: the RM seems to suggest that string types can also have static
188    --  predicates. But that really makes lttle sense as very few useful
189    --  predicates can be constructed for strings. Remember that:
190    --
191    --     "ABC" < "DEF"
192    --
193    --  is not a static expression. So even though the clearly faulty RM wording
194    --  allows the following:
195    --
196    --     subtype S is String with Static_Predicate => S < "DEF"
197    --
198    --  We can't allow this, otherwise we have predicate-static applying to a
199    --  larger class than static expressions, which was never intended.
200
201    procedure New_Stream_Subprogram
202      (N    : Node_Id;
203       Ent  : Entity_Id;
204       Subp : Entity_Id;
205       Nam  : TSS_Name_Type);
206    --  Create a subprogram renaming of a given stream attribute to the
207    --  designated subprogram and then in the tagged case, provide this as a
208    --  primitive operation, or in the untagged case make an appropriate TSS
209    --  entry. This is more properly an expansion activity than just semantics,
210    --  but the presence of user-defined stream functions for limited types
211    --  is a legality check, which is why this takes place here rather than in
212    --  exp_ch13, where it was previously. Nam indicates the name of the TSS
213    --  function to be generated.
214    --
215    --  To avoid elaboration anomalies with freeze nodes, for untagged types
216    --  we generate both a subprogram declaration and a subprogram renaming
217    --  declaration, so that the attribute specification is handled as a
218    --  renaming_as_body. For tagged types, the specification is one of the
219    --  primitive specs.
220
221    procedure Resolve_Iterable_Operation
222      (N      : Node_Id;
223       Cursor : Entity_Id;
224       Typ    : Entity_Id;
225       Nam    : Name_Id);
226    --  If the name of a primitive operation for an Iterable aspect is
227    --  overloaded, resolve according to required signature.
228
229    procedure Set_Biased
230      (E      : Entity_Id;
231       N      : Node_Id;
232       Msg    : String;
233       Biased : Boolean := True);
234    --  If Biased is True, sets Has_Biased_Representation flag for E, and
235    --  outputs a warning message at node N if Warn_On_Biased_Representation is
236    --  is True. This warning inserts the string Msg to describe the construct
237    --  causing biasing.
238
239    ---------------------------------------------------
240    -- Table for Validate_Compile_Time_Warning_Error --
241    ---------------------------------------------------
242
243    --  The following table collects pragmas Compile_Time_Error and Compile_
244    --  Time_Warning for validation. Entries are made by calls to subprogram
245    --  Validate_Compile_Time_Warning_Error, and the call to the procedure
246    --  Validate_Compile_Time_Warning_Errors does the actual error checking
247    --  and posting of warning and error messages. The reason for this delayed
248    --  processing is to take advantage of back-annotations of attributes size
249    --  and alignment values performed by the back end.
250
251    --  Note: the reason we store a Source_Ptr value instead of a Node_Id is
252    --  that by the time Validate_Unchecked_Conversions is called, Sprint will
253    --  already have modified all Sloc values if the -gnatD option is set.
254
255    type CTWE_Entry is record
256       Eloc  : Source_Ptr;
257       --  Source location used in warnings and error messages
258
259       Prag  : Node_Id;
260       --  Pragma Compile_Time_Error or Compile_Time_Warning
261
262       Scope : Node_Id;
263       --  The scope which encloses the pragma
264    end record;
265
266    package Compile_Time_Warnings_Errors is new Table.Table (
267      Table_Component_Type => CTWE_Entry,
268      Table_Index_Type     => Int,
269      Table_Low_Bound      => 1,
270      Table_Initial        => 50,
271      Table_Increment      => 200,
272      Table_Name           => "Compile_Time_Warnings_Errors");
273
274    ----------------------------------------------
275    -- Table for Validate_Unchecked_Conversions --
276    ----------------------------------------------
277
278    --  The following table collects unchecked conversions for validation.
279    --  Entries are made by Validate_Unchecked_Conversion and then the call
280    --  to Validate_Unchecked_Conversions does the actual error checking and
281    --  posting of warnings. The reason for this delayed processing is to take
282    --  advantage of back-annotations of size and alignment values performed by
283    --  the back end.
284
285    --  Note: the reason we store a Source_Ptr value instead of a Node_Id is
286    --  that by the time Validate_Unchecked_Conversions is called, Sprint will
287    --  already have modified all Sloc values if the -gnatD option is set.
288
289    type UC_Entry is record
290       Eloc     : Source_Ptr; -- node used for posting warnings
291       Source   : Entity_Id;  -- source type for unchecked conversion
292       Target   : Entity_Id;  -- target type for unchecked conversion
293       Act_Unit : Entity_Id;  -- actual function instantiated
294    end record;
295
296    package Unchecked_Conversions is new Table.Table (
297      Table_Component_Type => UC_Entry,
298      Table_Index_Type     => Int,
299      Table_Low_Bound      => 1,
300      Table_Initial        => 50,
301      Table_Increment      => 200,
302      Table_Name           => "Unchecked_Conversions");
303
304    ----------------------------------------
305    -- Table for Validate_Address_Clauses --
306    ----------------------------------------
307
308    --  If an address clause has the form
309
310    --    for X'Address use Expr
311
312    --  where Expr has a value known at compile time or is of the form Y'Address
313    --  or recursively is a reference to a constant initialized with either of
314    --  these forms, and the value of Expr is not a multiple of X's alignment,
315    --  or if Y has a smaller alignment than X, then that merits a warning about
316    --  possible bad alignment. The following table collects address clauses of
317    --  this kind. We put these in a table so that they can be checked after the
318    --  back end has completed annotation of the alignments of objects, since we
319    --  can catch more cases that way.
320
321    type Address_Clause_Check_Record is record
322       N : Node_Id;
323       --  The address clause
324
325       X : Entity_Id;
326       --  The entity of the object subject to the address clause
327
328       A : Uint;
329       --  The value of the address in the first case
330
331       Y : Entity_Id;
332       --  The entity of the object being overlaid in the second case
333
334       Off : Boolean;
335       --  Whether the address is offset within Y in the second case
336    end record;
337
338    package Address_Clause_Checks is new Table.Table (
339      Table_Component_Type => Address_Clause_Check_Record,
340      Table_Index_Type     => Int,
341      Table_Low_Bound      => 1,
342      Table_Initial        => 20,
343      Table_Increment      => 200,
344      Table_Name           => "Address_Clause_Checks");
345
346    -----------------------------------------
347    -- Adjust_Record_For_Reverse_Bit_Order --
348    -----------------------------------------
349
350    procedure Adjust_Record_For_Reverse_Bit_Order (R : Entity_Id) is
351       Comp : Node_Id;
352       CC   : Node_Id;
353
354    begin
355       --  Processing depends on version of Ada
356
357       --  For Ada 95, we just renumber bits within a storage unit. We do the
358       --  same for Ada 83 mode, since we recognize the Bit_Order attribute in
359       --  Ada 83, and are free to add this extension.
360
361       if Ada_Version < Ada_2005 then
362          Comp := First_Component_Or_Discriminant (R);
363          while Present (Comp) loop
364             CC := Component_Clause (Comp);
365
366             --  If component clause is present, then deal with the non-default
367             --  bit order case for Ada 95 mode.
368
369             --  We only do this processing for the base type, and in fact that
370             --  is important, since otherwise if there are record subtypes, we
371             --  could reverse the bits once for each subtype, which is wrong.
372
373             if Present (CC) and then Ekind (R) = E_Record_Type then
374                declare
375                   CFB : constant Uint    := Component_Bit_Offset (Comp);
376                   CSZ : constant Uint    := Esize (Comp);
377                   CLC : constant Node_Id := Component_Clause (Comp);
378                   Pos : constant Node_Id := Position (CLC);
379                   FB  : constant Node_Id := First_Bit (CLC);
380
381                   Storage_Unit_Offset : constant Uint :=
382                                           CFB / System_Storage_Unit;
383
384                   Start_Bit : constant Uint :=
385                                 CFB mod System_Storage_Unit;
386
387                begin
388                   --  Cases where field goes over storage unit boundary
389
390                   if Start_Bit + CSZ > System_Storage_Unit then
391
392                      --  Allow multi-byte field but generate warning
393
394                      if Start_Bit mod System_Storage_Unit = 0
395                        and then CSZ mod System_Storage_Unit = 0
396                      then
397                         Error_Msg_N
398                           ("info: multi-byte field specified with "
399                            & "non-standard Bit_Order?V?", CLC);
400
401                         if Bytes_Big_Endian then
402                            Error_Msg_N
403                              ("\bytes are not reversed "
404                               & "(component is big-endian)?V?", CLC);
405                         else
406                            Error_Msg_N
407                              ("\bytes are not reversed "
408                               & "(component is little-endian)?V?", CLC);
409                         end if;
410
411                      --  Do not allow non-contiguous field
412
413                      else
414                         Error_Msg_N
415                           ("attempt to specify non-contiguous field "
416                            & "not permitted", CLC);
417                         Error_Msg_N
418                           ("\caused by non-standard Bit_Order "
419                            & "specified", CLC);
420                         Error_Msg_N
421                           ("\consider possibility of using "
422                            & "Ada 2005 mode here", CLC);
423                      end if;
424
425                   --  Case where field fits in one storage unit
426
427                   else
428                      --  Give warning if suspicious component clause
429
430                      if Intval (FB) >= System_Storage_Unit
431                        and then Warn_On_Reverse_Bit_Order
432                      then
433                         Error_Msg_N
434                           ("info: Bit_Order clause does not affect " &
435                            "byte ordering?V?", Pos);
436                         Error_Msg_Uint_1 :=
437                           Intval (Pos) + Intval (FB) /
438                           System_Storage_Unit;
439                         Error_Msg_N
440                           ("info: position normalized to ^ before bit " &
441                            "order interpreted?V?", Pos);
442                      end if;
443
444                      --  Here is where we fix up the Component_Bit_Offset value
445                      --  to account for the reverse bit order. Some examples of
446                      --  what needs to be done are:
447
448                      --    First_Bit .. Last_Bit     Component_Bit_Offset
449                      --      old          new          old       new
450
451                      --     0 .. 0       7 .. 7         0         7
452                      --     0 .. 1       6 .. 7         0         6
453                      --     0 .. 2       5 .. 7         0         5
454                      --     0 .. 7       0 .. 7         0         4
455
456                      --     1 .. 1       6 .. 6         1         6
457                      --     1 .. 4       3 .. 6         1         3
458                      --     4 .. 7       0 .. 3         4         0
459
460                      --  The rule is that the first bit is is obtained by
461                      --  subtracting the old ending bit from storage_unit - 1.
462
463                      Set_Component_Bit_Offset
464                        (Comp,
465                         (Storage_Unit_Offset * System_Storage_Unit) +
466                           (System_Storage_Unit - 1) -
467                           (Start_Bit + CSZ - 1));
468
469                      Set_Normalized_First_Bit
470                        (Comp,
471                         Component_Bit_Offset (Comp) mod
472                           System_Storage_Unit);
473                   end if;
474                end;
475             end if;
476
477             Next_Component_Or_Discriminant (Comp);
478          end loop;
479
480       --  For Ada 2005, we do machine scalar processing, as fully described In
481       --  AI-133. This involves gathering all components which start at the
482       --  same byte offset and processing them together. Same approach is still
483       --  valid in later versions including Ada 2012.
484
485       else
486          declare
487             Max_Machine_Scalar_Size : constant Uint :=
488                                         UI_From_Int
489                                           (Standard_Long_Long_Integer_Size);
490             --  We use this as the maximum machine scalar size
491
492             Num_CC : Natural;
493             SSU    : constant Uint := UI_From_Int (System_Storage_Unit);
494
495          begin
496             --  This first loop through components does two things. First it
497             --  deals with the case of components with component clauses whose
498             --  length is greater than the maximum machine scalar size (either
499             --  accepting them or rejecting as needed). Second, it counts the
500             --  number of components with component clauses whose length does
501             --  not exceed this maximum for later processing.
502
503             Num_CC := 0;
504             Comp   := First_Component_Or_Discriminant (R);
505             while Present (Comp) loop
506                CC := Component_Clause (Comp);
507
508                if Present (CC) then
509                   declare
510                      Fbit : constant Uint := Static_Integer (First_Bit (CC));
511                      Lbit : constant Uint := Static_Integer (Last_Bit (CC));
512
513                   begin
514                      --  Case of component with last bit >= max machine scalar
515
516                      if Lbit >= Max_Machine_Scalar_Size then
517
518                         --  This is allowed only if first bit is zero, and
519                         --  last bit + 1 is a multiple of storage unit size.
520
521                         if Fbit = 0 and then (Lbit + 1) mod SSU = 0 then
522
523                            --  This is the case to give a warning if enabled
524
525                            if Warn_On_Reverse_Bit_Order then
526                               Error_Msg_N
527                                 ("info: multi-byte field specified with "
528                                  & "non-standard Bit_Order?V?", CC);
529
530                               if Bytes_Big_Endian then
531                                  Error_Msg_N
532                                    ("\bytes are not reversed "
533                                     & "(component is big-endian)?V?", CC);
534                               else
535                                  Error_Msg_N
536                                    ("\bytes are not reversed "
537                                     & "(component is little-endian)?V?", CC);
538                               end if;
539                            end if;
540
541                         --  Give error message for RM 13.5.1(10) violation
542
543                         else
544                            Error_Msg_FE
545                              ("machine scalar rules not followed for&",
546                               First_Bit (CC), Comp);
547
548                            Error_Msg_Uint_1 := Lbit + 1;
549                            Error_Msg_Uint_2 := Max_Machine_Scalar_Size;
550                            Error_Msg_F
551                              ("\last bit + 1 (^) exceeds maximum machine "
552                               & "scalar size (^)",
553                               First_Bit (CC));
554
555                            if (Lbit + 1) mod SSU /= 0 then
556                               Error_Msg_Uint_1 := SSU;
557                               Error_Msg_F
558                                 ("\and is not a multiple of Storage_Unit (^) "
559                                  & "(RM 13.5.1(10))",
560                                  First_Bit (CC));
561
562                            else
563                               Error_Msg_Uint_1 := Fbit;
564                               Error_Msg_F
565                                 ("\and first bit (^) is non-zero "
566                                  & "(RM 13.4.1(10))",
567                                  First_Bit (CC));
568                            end if;
569                         end if;
570
571                      --  OK case of machine scalar related component clause,
572                      --  For now, just count them.
573
574                      else
575                         Num_CC := Num_CC + 1;
576                      end if;
577                   end;
578                end if;
579
580                Next_Component_Or_Discriminant (Comp);
581             end loop;
582
583             --  We need to sort the component clauses on the basis of the
584             --  Position values in the clause, so we can group clauses with
585             --  the same Position together to determine the relevant machine
586             --  scalar size.
587
588             Sort_CC : declare
589                Comps : array (0 .. Num_CC) of Entity_Id;
590                --  Array to collect component and discriminant entities. The
591                --  data starts at index 1, the 0'th entry is for the sort
592                --  routine.
593
594                function CP_Lt (Op1, Op2 : Natural) return Boolean;
595                --  Compare routine for Sort
596
597                procedure CP_Move (From : Natural; To : Natural);
598                --  Move routine for Sort
599
600                package Sorting is new GNAT.Heap_Sort_G (CP_Move, CP_Lt);
601
602                Start : Natural;
603                Stop  : Natural;
604                --  Start and stop positions in the component list of the set of
605                --  components with the same starting position (that constitute
606                --  components in a single machine scalar).
607
608                MaxL  : Uint;
609                --  Maximum last bit value of any component in this set
610
611                MSS   : Uint;
612                --  Corresponding machine scalar size
613
614                -----------
615                -- CP_Lt --
616                -----------
617
618                function CP_Lt (Op1, Op2 : Natural) return Boolean is
619                begin
620                   return Position (Component_Clause (Comps (Op1))) <
621                     Position (Component_Clause (Comps (Op2)));
622                end CP_Lt;
623
624                -------------
625                -- CP_Move --
626                -------------
627
628                procedure CP_Move (From : Natural; To : Natural) is
629                begin
630                   Comps (To) := Comps (From);
631                end CP_Move;
632
633             --  Start of processing for Sort_CC
634
635             begin
636                --  Collect the machine scalar relevant component clauses
637
638                Num_CC := 0;
639                Comp   := First_Component_Or_Discriminant (R);
640                while Present (Comp) loop
641                   declare
642                      CC   : constant Node_Id := Component_Clause (Comp);
643
644                   begin
645                      --  Collect only component clauses whose last bit is less
646                      --  than machine scalar size. Any component clause whose
647                      --  last bit exceeds this value does not take part in
648                      --  machine scalar layout considerations. The test for
649                      --  Error_Posted makes sure we exclude component clauses
650                      --  for which we already posted an error.
651
652                      if Present (CC)
653                        and then not Error_Posted (Last_Bit (CC))
654                        and then Static_Integer (Last_Bit (CC)) <
655                                                     Max_Machine_Scalar_Size
656                      then
657                         Num_CC := Num_CC + 1;
658                         Comps (Num_CC) := Comp;
659                      end if;
660                   end;
661
662                   Next_Component_Or_Discriminant (Comp);
663                end loop;
664
665                --  Sort by ascending position number
666
667                Sorting.Sort (Num_CC);
668
669                --  We now have all the components whose size does not exceed
670                --  the max machine scalar value, sorted by starting position.
671                --  In this loop we gather groups of clauses starting at the
672                --  same position, to process them in accordance with AI-133.
673
674                Stop := 0;
675                while Stop < Num_CC loop
676                   Start := Stop + 1;
677                   Stop  := Start;
678                   MaxL  :=
679                     Static_Integer
680                       (Last_Bit (Component_Clause (Comps (Start))));
681                   while Stop < Num_CC loop
682                      if Static_Integer
683                           (Position (Component_Clause (Comps (Stop + 1)))) =
684                         Static_Integer
685                           (Position (Component_Clause (Comps (Stop))))
686                      then
687                         Stop := Stop + 1;
688                         MaxL :=
689                           UI_Max
690                             (MaxL,
691                              Static_Integer
692                                (Last_Bit
693                                   (Component_Clause (Comps (Stop)))));
694                      else
695                         exit;
696                      end if;
697                   end loop;
698
699                   --  Now we have a group of component clauses from Start to
700                   --  Stop whose positions are identical, and MaxL is the
701                   --  maximum last bit value of any of these components.
702
703                   --  We need to determine the corresponding machine scalar
704                   --  size. This loop assumes that machine scalar sizes are
705                   --  even, and that each possible machine scalar has twice
706                   --  as many bits as the next smaller one.
707
708                   MSS := Max_Machine_Scalar_Size;
709                   while MSS mod 2 = 0
710                     and then (MSS / 2) >= SSU
711                     and then (MSS / 2) > MaxL
712                   loop
713                      MSS := MSS / 2;
714                   end loop;
715
716                   --  Here is where we fix up the Component_Bit_Offset value
717                   --  to account for the reverse bit order. Some examples of
718                   --  what needs to be done for the case of a machine scalar
719                   --  size of 8 are:
720
721                   --    First_Bit .. Last_Bit     Component_Bit_Offset
722                   --      old          new          old       new
723
724                   --     0 .. 0       7 .. 7         0         7
725                   --     0 .. 1       6 .. 7         0         6
726                   --     0 .. 2       5 .. 7         0         5
727                   --     0 .. 7       0 .. 7         0         4
728
729                   --     1 .. 1       6 .. 6         1         6
730                   --     1 .. 4       3 .. 6         1         3
731                   --     4 .. 7       0 .. 3         4         0
732
733                   --  The rule is that the first bit is obtained by subtracting
734                   --  the old ending bit from machine scalar size - 1.
735
736                   for C in Start .. Stop loop
737                      declare
738                         Comp : constant Entity_Id := Comps (C);
739                         CC   : constant Node_Id   := Component_Clause (Comp);
740
741                         LB   : constant Uint := Static_Integer (Last_Bit (CC));
742                         NFB  : constant Uint := MSS - Uint_1 - LB;
743                         NLB  : constant Uint := NFB + Esize (Comp) - 1;
744                         Pos  : constant Uint := Static_Integer (Position (CC));
745
746                      begin
747                         if Warn_On_Reverse_Bit_Order then
748                            Error_Msg_Uint_1 := MSS;
749                            Error_Msg_N
750                              ("info: reverse bit order in machine " &
751                               "scalar of length^?V?", First_Bit (CC));
752                            Error_Msg_Uint_1 := NFB;
753                            Error_Msg_Uint_2 := NLB;
754
755                            if Bytes_Big_Endian then
756                               Error_Msg_NE
757                                 ("\big-endian range for component "
758                                  & "& is ^ .. ^?V?", First_Bit (CC), Comp);
759                            else
760                               Error_Msg_NE
761                                 ("\little-endian range for component"
762                                  & "& is ^ .. ^?V?", First_Bit (CC), Comp);
763                            end if;
764                         end if;
765
766                         Set_Component_Bit_Offset (Comp, Pos * SSU + NFB);
767                         Set_Normalized_First_Bit (Comp, NFB mod SSU);
768                      end;
769                   end loop;
770                end loop;
771             end Sort_CC;
772          end;
773       end if;
774    end Adjust_Record_For_Reverse_Bit_Order;
775
776    -------------------------------------
777    -- Alignment_Check_For_Size_Change --
778    -------------------------------------
779
780    procedure Alignment_Check_For_Size_Change (Typ : Entity_Id; Size : Uint) is
781    begin
782       --  If the alignment is known, and not set by a rep clause, and is
783       --  inconsistent with the size being set, then reset it to unknown,
784       --  we assume in this case that the size overrides the inherited
785       --  alignment, and that the alignment must be recomputed.
786
787       if Known_Alignment (Typ)
788         and then not Has_Alignment_Clause (Typ)
789         and then Size mod (Alignment (Typ) * SSU) /= 0
790       then
791          Init_Alignment (Typ);
792       end if;
793    end Alignment_Check_For_Size_Change;
794
795    -------------------------------------
796    -- Analyze_Aspects_At_Freeze_Point --
797    -------------------------------------
798
799    procedure Analyze_Aspects_At_Freeze_Point (E : Entity_Id) is
800       procedure Analyze_Aspect_Default_Value (ASN : Node_Id);
801       --  This routine analyzes an Aspect_Default_[Component_]Value denoted by
802       --  the aspect specification node ASN.
803
804       procedure Inherit_Delayed_Rep_Aspects (ASN : Node_Id);
805       --  As discussed in the spec of Aspects (see Aspect_Delay declaration),
806       --  a derived type can inherit aspects from its parent which have been
807       --  specified at the time of the derivation using an aspect, as in:
808       --
809       --    type A is range 1 .. 10
810       --      with Size => Not_Defined_Yet;
811       --    ..
812       --    type B is new A;
813       --    ..
814       --    Not_Defined_Yet : constant := 64;
815       --
816       --  In this example, the Size of A is considered to be specified prior
817       --  to the derivation, and thus inherited, even though the value is not
818       --  known at the time of derivation. To deal with this, we use two entity
819       --  flags. The flag Has_Derived_Rep_Aspects is set in the parent type (A
820       --  here), and then the flag May_Inherit_Delayed_Rep_Aspects is set in
821       --  the derived type (B here). If this flag is set when the derived type
822       --  is frozen, then this procedure is called to ensure proper inheritance
823       --  of all delayed aspects from the parent type. The derived type is E,
824       --  the argument to Analyze_Aspects_At_Freeze_Point. ASN is the first
825       --  aspect specification node in the Rep_Item chain for the parent type.
826
827       procedure Make_Pragma_From_Boolean_Aspect (ASN : Node_Id);
828       --  Given an aspect specification node ASN whose expression is an
829       --  optional Boolean, this routines creates the corresponding pragma
830       --  at the freezing point.
831
832       ----------------------------------
833       -- Analyze_Aspect_Default_Value --
834       ----------------------------------
835
836       procedure Analyze_Aspect_Default_Value (ASN : Node_Id) is
837          A_Id : constant Aspect_Id := Get_Aspect_Id (ASN);
838          Ent  : constant Entity_Id := Entity (ASN);
839          Expr : constant Node_Id   := Expression (ASN);
840          Id   : constant Node_Id   := Identifier (ASN);
841
842       begin
843          Error_Msg_Name_1 := Chars (Id);
844
845          if not Is_Type (Ent) then
846             Error_Msg_N ("aspect% can only apply to a type", Id);
847             return;
848
849          elsif not Is_First_Subtype (Ent) then
850             Error_Msg_N ("aspect% cannot apply to subtype", Id);
851             return;
852
853          elsif A_Id = Aspect_Default_Value
854            and then not Is_Scalar_Type (Ent)
855          then
856             Error_Msg_N ("aspect% can only be applied to scalar type", Id);
857             return;
858
859          elsif A_Id = Aspect_Default_Component_Value then
860             if not Is_Array_Type (Ent) then
861                Error_Msg_N ("aspect% can only be applied to array type", Id);
862                return;
863
864             elsif not Is_Scalar_Type (Component_Type (Ent)) then
865                Error_Msg_N ("aspect% requires scalar components", Id);
866                return;
867             end if;
868          end if;
869
870          Set_Has_Default_Aspect (Base_Type (Ent));
871
872          if Is_Scalar_Type (Ent) then
873             Set_Default_Aspect_Value (Base_Type (Ent), Expr);
874          else
875             Set_Default_Aspect_Component_Value (Base_Type (Ent), Expr);
876          end if;
877       end Analyze_Aspect_Default_Value;
878
879       ---------------------------------
880       -- Inherit_Delayed_Rep_Aspects --
881       ---------------------------------
882
883       procedure Inherit_Delayed_Rep_Aspects (ASN : Node_Id) is
884          A_Id : constant Aspect_Id := Get_Aspect_Id (ASN);
885          P    : constant Entity_Id := Entity (ASN);
886          --  Entithy for parent type
887
888          N : Node_Id;
889          --  Item from Rep_Item chain
890
891          A : Aspect_Id;
892
893       begin
894          --  Loop through delayed aspects for the parent type
895
896          N := ASN;
897          while Present (N) loop
898             if Nkind (N) = N_Aspect_Specification then
899                exit when Entity (N) /= P;
900
901                if Is_Delayed_Aspect (N) then
902                   A := Get_Aspect_Id (Chars (Identifier (N)));
903
904                   --  Process delayed rep aspect. For Boolean attributes it is
905                   --  not possible to cancel an attribute once set (the attempt
906                   --  to use an aspect with xxx => False is an error) for a
907                   --  derived type. So for those cases, we do not have to check
908                   --  if a clause has been given for the derived type, since it
909                   --  is harmless to set it again if it is already set.
910
911                   case A is
912
913                      --  Alignment
914
915                      when Aspect_Alignment =>
916                         if not Has_Alignment_Clause (E) then
917                            Set_Alignment (E, Alignment (P));
918                         end if;
919
920                      --  Atomic
921
922                      when Aspect_Atomic =>
923                         if Is_Atomic (P) then
924                            Set_Is_Atomic (E);
925                         end if;
926
927                      --  Atomic_Components
928
929                      when Aspect_Atomic_Components =>
930                         if Has_Atomic_Components (P) then
931                            Set_Has_Atomic_Components (Base_Type (E));
932                         end if;
933
934                      --  Bit_Order
935
936                      when Aspect_Bit_Order =>
937                         if Is_Record_Type (E)
938                           and then No (Get_Attribute_Definition_Clause
939                                          (E, Attribute_Bit_Order))
940                           and then Reverse_Bit_Order (P)
941                         then
942                            Set_Reverse_Bit_Order (Base_Type (E));
943                         end if;
944
945                      --  Component_Size
946
947                      when Aspect_Component_Size =>
948                         if Is_Array_Type (E)
949                           and then not Has_Component_Size_Clause (E)
950                         then
951                            Set_Component_Size
952                              (Base_Type (E), Component_Size (P));
953                         end if;
954
955                      --  Machine_Radix
956
957                      when Aspect_Machine_Radix =>
958                         if Is_Decimal_Fixed_Point_Type (E)
959                           and then not Has_Machine_Radix_Clause (E)
960                         then
961                            Set_Machine_Radix_10 (E, Machine_Radix_10 (P));
962                         end if;
963
964                      --  Object_Size (also Size which also sets Object_Size)
965
966                      when Aspect_Object_Size | Aspect_Size =>
967                         if not Has_Size_Clause (E)
968                           and then
969                             No (Get_Attribute_Definition_Clause
970                                   (E, Attribute_Object_Size))
971                         then
972                            Set_Esize (E, Esize (P));
973                         end if;
974
975                      --  Pack
976
977                      when Aspect_Pack =>
978                         if not Is_Packed (E) then
979                            Set_Is_Packed (Base_Type (E));
980
981                            if Is_Bit_Packed_Array (P) then
982                               Set_Is_Bit_Packed_Array (Base_Type (E));
983                               Set_Packed_Array_Impl_Type
984                                 (E, Packed_Array_Impl_Type (P));
985                            end if;
986                         end if;
987
988                      --  Scalar_Storage_Order
989
990                      when Aspect_Scalar_Storage_Order =>
991                         if (Is_Record_Type (E) or else Is_Array_Type (E))
992                           and then No (Get_Attribute_Definition_Clause
993                                          (E, Attribute_Scalar_Storage_Order))
994                           and then Reverse_Storage_Order (P)
995                         then
996                            Set_Reverse_Storage_Order (Base_Type (E));
997
998                            --  Clear default SSO indications, since the aspect
999                            --  overrides the default.
1000
1001                            Set_SSO_Set_Low_By_Default  (Base_Type (E), False);
1002                            Set_SSO_Set_High_By_Default (Base_Type (E), False);
1003                         end if;
1004
1005                      --  Small
1006
1007                      when Aspect_Small =>
1008                         if Is_Fixed_Point_Type (E)
1009                           and then not Has_Small_Clause (E)
1010                         then
1011                            Set_Small_Value (E, Small_Value (P));
1012                         end if;
1013
1014                      --  Storage_Size
1015
1016                      when Aspect_Storage_Size =>
1017                         if (Is_Access_Type (E) or else Is_Task_Type (E))
1018                           and then not Has_Storage_Size_Clause (E)
1019                         then
1020                            Set_Storage_Size_Variable
1021                              (Base_Type (E), Storage_Size_Variable (P));
1022                         end if;
1023
1024                      --  Value_Size
1025
1026                      when Aspect_Value_Size =>
1027
1028                         --  Value_Size is never inherited, it is either set by
1029                         --  default, or it is explicitly set for the derived
1030                         --  type. So nothing to do here.
1031
1032                         null;
1033
1034                      --  Volatile
1035
1036                      when Aspect_Volatile =>
1037                         if Is_Volatile (P) then
1038                            Set_Is_Volatile (E);
1039                         end if;
1040
1041                      --  Volatile_Full_Access
1042
1043                      when Aspect_Volatile_Full_Access =>
1044                         if Is_Volatile_Full_Access (P) then
1045                            Set_Is_Volatile_Full_Access (E);
1046                         end if;
1047
1048                      --  Volatile_Components
1049
1050                      when Aspect_Volatile_Components =>
1051                         if Has_Volatile_Components (P) then
1052                            Set_Has_Volatile_Components (Base_Type (E));
1053                         end if;
1054
1055                      --  That should be all the Rep Aspects
1056
1057                      when others =>
1058                         pragma Assert (Aspect_Delay (A_Id) /= Rep_Aspect);
1059                         null;
1060
1061                   end case;
1062                end if;
1063             end if;
1064
1065             N := Next_Rep_Item (N);
1066          end loop;
1067       end Inherit_Delayed_Rep_Aspects;
1068
1069       -------------------------------------
1070       -- Make_Pragma_From_Boolean_Aspect --
1071       -------------------------------------
1072
1073       procedure Make_Pragma_From_Boolean_Aspect (ASN : Node_Id) is
1074          Ident  : constant Node_Id    := Identifier (ASN);
1075          A_Name : constant Name_Id    := Chars (Ident);
1076          A_Id   : constant Aspect_Id  := Get_Aspect_Id (A_Name);
1077          Ent    : constant Entity_Id  := Entity (ASN);
1078          Expr   : constant Node_Id    := Expression (ASN);
1079          Loc    : constant Source_Ptr := Sloc (ASN);
1080
1081          procedure Check_False_Aspect_For_Derived_Type;
1082          --  This procedure checks for the case of a false aspect for a derived
1083          --  type, which improperly tries to cancel an aspect inherited from
1084          --  the parent.
1085
1086          -----------------------------------------
1087          -- Check_False_Aspect_For_Derived_Type --
1088          -----------------------------------------
1089
1090          procedure Check_False_Aspect_For_Derived_Type is
1091             Par : Node_Id;
1092
1093          begin
1094             --  We are only checking derived types
1095
1096             if not Is_Derived_Type (E) then
1097                return;
1098             end if;
1099
1100             Par := Nearest_Ancestor (E);
1101
1102             case A_Id is
1103                when Aspect_Atomic | Aspect_Shared =>
1104                   if not Is_Atomic (Par) then
1105                      return;
1106                   end if;
1107
1108                when Aspect_Atomic_Components =>
1109                   if not Has_Atomic_Components (Par) then
1110                      return;
1111                   end if;
1112
1113                when Aspect_Discard_Names =>
1114                   if not Discard_Names (Par) then
1115                      return;
1116                   end if;
1117
1118                when Aspect_Pack =>
1119                   if not Is_Packed (Par) then
1120                      return;
1121                   end if;
1122
1123                when Aspect_Unchecked_Union =>
1124                   if not Is_Unchecked_Union (Par) then
1125                      return;
1126                   end if;
1127
1128                when Aspect_Volatile =>
1129                   if not Is_Volatile (Par) then
1130                      return;
1131                   end if;
1132
1133                when Aspect_Volatile_Components =>
1134                   if not Has_Volatile_Components (Par) then
1135                      return;
1136                   end if;
1137
1138                when Aspect_Volatile_Full_Access =>
1139                   if not Is_Volatile_Full_Access (Par) then
1140                      return;
1141                   end if;
1142
1143                when others =>
1144                   return;
1145             end case;
1146
1147             --  Fall through means we are canceling an inherited aspect
1148
1149             Error_Msg_Name_1 := A_Name;
1150             Error_Msg_NE
1151               ("derived type& inherits aspect%, cannot cancel", Expr, E);
1152          end Check_False_Aspect_For_Derived_Type;
1153
1154          --  Local variables
1155
1156          Prag : Node_Id;
1157
1158       --  Start of processing for Make_Pragma_From_Boolean_Aspect
1159
1160       begin
1161          --  Note that we know Expr is present, because for a missing Expr
1162          --  argument, we knew it was True and did not need to delay the
1163          --  evaluation to the freeze point.
1164
1165          if Is_False (Static_Boolean (Expr)) then
1166             Check_False_Aspect_For_Derived_Type;
1167
1168          else
1169             Prag :=
1170               Make_Pragma (Loc,
1171                 Pragma_Identifier            =>
1172                   Make_Identifier (Sloc (Ident), Chars (Ident)),
1173                 Pragma_Argument_Associations => New_List (
1174                   Make_Pragma_Argument_Association (Sloc (Ident),
1175                     Expression => New_Occurrence_Of (Ent, Sloc (Ident)))));
1176
1177             Set_From_Aspect_Specification (Prag, True);
1178             Set_Corresponding_Aspect (Prag, ASN);
1179             Set_Aspect_Rep_Item (ASN, Prag);
1180             Set_Is_Delayed_Aspect (Prag);
1181             Set_Parent (Prag, ASN);
1182          end if;
1183       end Make_Pragma_From_Boolean_Aspect;
1184
1185       --  Local variables
1186
1187       A_Id  : Aspect_Id;
1188       ASN   : Node_Id;
1189       Ritem : Node_Id;
1190
1191    --  Start of processing for Analyze_Aspects_At_Freeze_Point
1192
1193    begin
1194       --  Must be visible in current scope
1195
1196       if not Scope_Within_Or_Same (Current_Scope, Scope (E)) then
1197          return;
1198       end if;
1199
1200       --  Look for aspect specification entries for this entity
1201
1202       ASN := First_Rep_Item (E);
1203       while Present (ASN) loop
1204          if Nkind (ASN) = N_Aspect_Specification then
1205             exit when Entity (ASN) /= E;
1206
1207             if Is_Delayed_Aspect (ASN) then
1208                A_Id := Get_Aspect_Id (ASN);
1209
1210                case A_Id is
1211
1212                   --  For aspects whose expression is an optional Boolean, make
1213                   --  the corresponding pragma at the freeze point.
1214
1215                   when Boolean_Aspects      |
1216                        Library_Unit_Aspects =>
1217
1218                      --  Aspects Export and Import require special handling.
1219                      --  Both are by definition Boolean and may benefit from
1220                      --  forward references, however their expressions are
1221                      --  treated as static. In addition, the syntax of their
1222                      --  corresponding pragmas requires extra "pieces" which
1223                      --  may also contain forward references. To account for
1224                      --  all of this, the corresponding pragma is created by
1225                      --  Analyze_Aspect_Export_Import, but is not analyzed as
1226                      --  the complete analysis must happen now.
1227
1228                      if A_Id = Aspect_Export or else A_Id = Aspect_Import then
1229                         null;
1230
1231                      --  Otherwise create a corresponding pragma
1232
1233                      else
1234                         Make_Pragma_From_Boolean_Aspect (ASN);
1235                      end if;
1236
1237                   --  Special handling for aspects that don't correspond to
1238                   --  pragmas/attributes.
1239
1240                   when Aspect_Default_Value           |
1241                        Aspect_Default_Component_Value =>
1242
1243                      --  Do not inherit aspect for anonymous base type of a
1244                      --  scalar or array type, because they apply to the first
1245                      --  subtype of the type, and will be processed when that
1246                      --  first subtype is frozen.
1247
1248                      if Is_Derived_Type (E)
1249                        and then not Comes_From_Source (E)
1250                        and then E /= First_Subtype (E)
1251                      then
1252                         null;
1253                      else
1254                         Analyze_Aspect_Default_Value (ASN);
1255                      end if;
1256
1257                   --  Ditto for iterator aspects, because the corresponding
1258                   --  attributes may not have been analyzed yet.
1259
1260                   when Aspect_Constant_Indexing |
1261                        Aspect_Variable_Indexing |
1262                        Aspect_Default_Iterator  |
1263                        Aspect_Iterator_Element  =>
1264                      Analyze (Expression (ASN));
1265
1266                      if Etype (Expression (ASN)) = Any_Type then
1267                         Error_Msg_NE
1268                           ("\aspect must be fully defined before & is frozen",
1269                            ASN, E);
1270                      end if;
1271
1272                   when Aspect_Iterable =>
1273                      Validate_Iterable_Aspect (E, ASN);
1274
1275                   when others =>
1276                      null;
1277                end case;
1278
1279                Ritem := Aspect_Rep_Item (ASN);
1280
1281                if Present (Ritem) then
1282                   Analyze (Ritem);
1283                end if;
1284             end if;
1285          end if;
1286
1287          Next_Rep_Item (ASN);
1288       end loop;
1289
1290       --  This is where we inherit delayed rep aspects from our parent. Note
1291       --  that if we fell out of the above loop with ASN non-empty, it means
1292       --  we hit an aspect for an entity other than E, and it must be the
1293       --  type from which we were derived.
1294
1295       if May_Inherit_Delayed_Rep_Aspects (E) then
1296          Inherit_Delayed_Rep_Aspects (ASN);
1297       end if;
1298    end Analyze_Aspects_At_Freeze_Point;
1299
1300    -----------------------------------
1301    -- Analyze_Aspect_Specifications --
1302    -----------------------------------
1303
1304    procedure Analyze_Aspect_Specifications (N : Node_Id; E : Entity_Id) is
1305       procedure Decorate (Asp : Node_Id; Prag : Node_Id);
1306       --  Establish linkages between an aspect and its corresponding pragma
1307
1308       procedure Insert_Pragma
1309         (Prag        : Node_Id;
1310          Is_Instance : Boolean := False);
1311       --  Subsidiary to the analysis of aspects
1312       --    Abstract_State
1313       --    Attach_Handler
1314       --    Contract_Cases
1315       --    Depends
1316       --    Ghost
1317       --    Global
1318       --    Initial_Condition
1319       --    Initializes
1320       --    Post
1321       --    Pre
1322       --    Refined_Depends
1323       --    Refined_Global
1324       --    Refined_State
1325       --    SPARK_Mode
1326       --    Warnings
1327       --  Insert pragma Prag such that it mimics the placement of a source
1328       --  pragma of the same kind. Flag Is_Generic should be set when the
1329       --  context denotes a generic instance.
1330
1331       --------------
1332       -- Decorate --
1333       --------------
1334
1335       procedure Decorate (Asp : Node_Id; Prag : Node_Id) is
1336       begin
1337          Set_Aspect_Rep_Item           (Asp, Prag);
1338          Set_Corresponding_Aspect      (Prag, Asp);
1339          Set_From_Aspect_Specification (Prag);
1340          Set_Parent                    (Prag, Asp);
1341       end Decorate;
1342
1343       -------------------
1344       -- Insert_Pragma --
1345       -------------------
1346
1347       procedure Insert_Pragma
1348         (Prag        : Node_Id;
1349          Is_Instance : Boolean := False)
1350       is
1351          Aux      : Node_Id;
1352          Decl     : Node_Id;
1353          Decls    : List_Id;
1354          Def      : Node_Id;
1355          Inserted : Boolean := False;
1356
1357       begin
1358          --  When the aspect appears on an entry, package, protected unit,
1359          --  subprogram, or task unit body, insert the generated pragma at the
1360          --  top of the body declarations to emulate the behavior of a source
1361          --  pragma.
1362
1363          --    package body Pack with Aspect is
1364
1365          --    package body Pack is
1366          --       pragma Prag;
1367
1368          if Nkind_In (N, N_Entry_Body,
1369                          N_Package_Body,
1370                          N_Protected_Body,
1371                          N_Subprogram_Body,
1372                          N_Task_Body)
1373          then
1374             Decls := Declarations (N);
1375
1376             if No (Decls) then
1377                Decls := New_List;
1378                Set_Declarations (N, Decls);
1379             end if;
1380
1381             Prepend_To (Decls, Prag);
1382
1383          --  When the aspect is associated with a [generic] package declaration
1384          --  insert the generated pragma at the top of the visible declarations
1385          --  to emulate the behavior of a source pragma.
1386
1387          --    package Pack with Aspect is
1388
1389          --    package Pack is
1390          --       pragma Prag;
1391
1392          elsif Nkind_In (N, N_Generic_Package_Declaration,
1393                             N_Package_Declaration)
1394          then
1395             Decls := Visible_Declarations (Specification (N));
1396
1397             if No (Decls) then
1398                Decls := New_List;
1399                Set_Visible_Declarations (Specification (N), Decls);
1400             end if;
1401
1402             --  The visible declarations of a generic instance have the
1403             --  following structure:
1404
1405             --    <renamings of generic formals>
1406             --    <renamings of internally-generated spec and body>
1407             --    <first source declaration>
1408
1409             --  Insert the pragma before the first source declaration by
1410             --  skipping the instance "header" to ensure proper visibility of
1411             --  all formals.
1412
1413             if Is_Instance then
1414                Decl := First (Decls);
1415                while Present (Decl) loop
1416                   if Comes_From_Source (Decl) then
1417                      Insert_Before (Decl, Prag);
1418                      Inserted := True;
1419                      exit;
1420                   else
1421                      Next (Decl);
1422                   end if;
1423                end loop;
1424
1425                --  The pragma is placed after the instance "header"
1426
1427                if not Inserted then
1428                   Append_To (Decls, Prag);
1429                end if;
1430
1431             --  Otherwise this is not a generic instance
1432
1433             else
1434                Prepend_To (Decls, Prag);
1435             end if;
1436
1437          --  When the aspect is associated with a protected unit declaration,
1438          --  insert the generated pragma at the top of the visible declarations
1439          --  the emulate the behavior of a source pragma.
1440
1441          --    protected [type] Prot with Aspect is
1442
1443          --    protected [type] Prot is
1444          --       pragma Prag;
1445
1446          elsif Nkind (N) = N_Protected_Type_Declaration then
1447             Def := Protected_Definition (N);
1448
1449             if No (Def) then
1450                Def :=
1451                  Make_Protected_Definition (Sloc (N),
1452                    Visible_Declarations => New_List,
1453                    End_Label            => Empty);
1454
1455                Set_Protected_Definition (N, Def);
1456             end if;
1457
1458             Decls := Visible_Declarations (Def);
1459
1460             if No (Decls) then
1461                Decls := New_List;
1462                Set_Visible_Declarations (Def, Decls);
1463             end if;
1464
1465             Prepend_To (Decls, Prag);
1466
1467          --  When the aspect is associated with a task unit declaration, insert
1468          --  insert the generated pragma at the top of the visible declarations
1469          --  the emulate the behavior of a source pragma.
1470
1471          --    task [type] Prot with Aspect is
1472
1473          --    task [type] Prot is
1474          --       pragma Prag;
1475
1476          elsif Nkind (N) = N_Task_Type_Declaration then
1477             Def := Task_Definition (N);
1478
1479             if No (Def) then
1480                Def :=
1481                  Make_Task_Definition (Sloc (N),
1482                    Visible_Declarations => New_List,
1483                    End_Label            => Empty);
1484
1485                Set_Task_Definition (N, Def);
1486             end if;
1487
1488             Decls := Visible_Declarations (Def);
1489
1490             if No (Decls) then
1491                Decls := New_List;
1492                Set_Visible_Declarations (Def, Decls);
1493             end if;
1494
1495             Prepend_To (Decls, Prag);
1496
1497          --  When the context is a library unit, the pragma is added to the
1498          --  Pragmas_After list.
1499
1500          elsif Nkind (Parent (N)) = N_Compilation_Unit then
1501             Aux := Aux_Decls_Node (Parent (N));
1502
1503             if No (Pragmas_After (Aux)) then
1504                Set_Pragmas_After (Aux, New_List);
1505             end if;
1506
1507             Prepend (Prag, Pragmas_After (Aux));
1508
1509          --  Default, the pragma is inserted after the context
1510
1511          else
1512             Insert_After (N, Prag);
1513          end if;
1514       end Insert_Pragma;
1515
1516       --  Local variables
1517
1518       Aspect : Node_Id;
1519       Aitem  : Node_Id;
1520       Ent    : Node_Id;
1521
1522       L : constant List_Id := Aspect_Specifications (N);
1523
1524       Ins_Node : Node_Id := N;
1525       --  Insert pragmas/attribute definition clause after this node when no
1526       --  delayed analysis is required.
1527
1528    --  Start of processing for Analyze_Aspect_Specifications
1529
1530    begin
1531       --  The general processing involves building an attribute definition
1532       --  clause or a pragma node that corresponds to the aspect. Then in order
1533       --  to delay the evaluation of this aspect to the freeze point, we attach
1534       --  the corresponding pragma/attribute definition clause to the aspect
1535       --  specification node, which is then placed in the Rep Item chain. In
1536       --  this case we mark the entity by setting the flag Has_Delayed_Aspects
1537       --  and we evaluate the rep item at the freeze point. When the aspect
1538       --  doesn't have a corresponding pragma/attribute definition clause, then
1539       --  its analysis is simply delayed at the freeze point.
1540
1541       --  Some special cases don't require delay analysis, thus the aspect is
1542       --  analyzed right now.
1543
1544       --  Note that there is a special handling for Pre, Post, Test_Case,
1545       --  Contract_Cases aspects. In these cases, we do not have to worry
1546       --  about delay issues, since the pragmas themselves deal with delay
1547       --  of visibility for the expression analysis. Thus, we just insert
1548       --  the pragma after the node N.
1549
1550       pragma Assert (Present (L));
1551
1552       --  Loop through aspects
1553
1554       Aspect := First (L);
1555       Aspect_Loop : while Present (Aspect) loop
1556          Analyze_One_Aspect : declare
1557             Expr : constant Node_Id    := Expression (Aspect);
1558             Id   : constant Node_Id    := Identifier (Aspect);
1559             Loc  : constant Source_Ptr := Sloc (Aspect);
1560             Nam  : constant Name_Id    := Chars (Id);
1561             A_Id : constant Aspect_Id  := Get_Aspect_Id (Nam);
1562             Anod : Node_Id;
1563
1564             Delay_Required : Boolean;
1565             --  Set False if delay is not required
1566
1567             Eloc : Source_Ptr := No_Location;
1568             --  Source location of expression, modified when we split PPC's. It
1569             --  is set below when Expr is present.
1570
1571             procedure Analyze_Aspect_Convention;
1572             --  Perform analysis of aspect Convention
1573
1574             procedure Analyze_Aspect_Export_Import;
1575             --  Perform analysis of aspects Export or Import
1576
1577             procedure Analyze_Aspect_External_Link_Name;
1578             --  Perform analysis of aspects External_Name or Link_Name
1579
1580             procedure Analyze_Aspect_Implicit_Dereference;
1581             --  Perform analysis of the Implicit_Dereference aspects
1582
1583             procedure Make_Aitem_Pragma
1584               (Pragma_Argument_Associations : List_Id;
1585                Pragma_Name                  : Name_Id);
1586             --  This is a wrapper for Make_Pragma used for converting aspects
1587             --  to pragmas. It takes care of Sloc (set from Loc) and building
1588             --  the pragma identifier from the given name. In addition the
1589             --  flags Class_Present and Split_PPC are set from the aspect
1590             --  node, as well as Is_Ignored. This routine also sets the
1591             --  From_Aspect_Specification in the resulting pragma node to
1592             --  True, and sets Corresponding_Aspect to point to the aspect.
1593             --  The resulting pragma is assigned to Aitem.
1594
1595             -------------------------------
1596             -- Analyze_Aspect_Convention --
1597             -------------------------------
1598
1599             procedure Analyze_Aspect_Convention is
1600                Conv    : Node_Id;
1601                Dummy_1 : Node_Id;
1602                Dummy_2 : Node_Id;
1603                Dummy_3 : Node_Id;
1604                Expo    : Node_Id;
1605                Imp     : Node_Id;
1606
1607             begin
1608                --  Obtain all interfacing aspects that apply to the related
1609                --  entity.
1610
1611                Get_Interfacing_Aspects
1612                  (Iface_Asp => Aspect,
1613                   Conv_Asp  => Dummy_1,
1614                   EN_Asp    => Dummy_2,
1615                   Expo_Asp  => Expo,
1616                   Imp_Asp   => Imp,
1617                   LN_Asp    => Dummy_3,
1618                   Do_Checks => True);
1619
1620                --  The related entity is subject to aspect Export or Import.
1621                --  Do not process Convention now because it must be analysed
1622                --  as part of Export or Import.
1623
1624                if Present (Expo) or else Present (Imp) then
1625                   return;
1626
1627                --  Otherwise Convention appears by itself
1628
1629                else
1630                   --  The aspect specifies a particular convention
1631
1632                   if Present (Expr) then
1633                      Conv := New_Copy_Tree (Expr);
1634
1635                   --  Otherwise assume convention Ada
1636
1637                   else
1638                      Conv := Make_Identifier (Loc, Name_Ada);
1639                   end if;
1640
1641                   --  Generate:
1642                   --    pragma Convention (<Conv>, <E>);
1643
1644                   Make_Aitem_Pragma
1645                     (Pragma_Name => Name_Convention,
1646                      Pragma_Argument_Associations => New_List (
1647                        Make_Pragma_Argument_Association (Loc,
1648                          Expression => Conv),
1649                        Make_Pragma_Argument_Association (Loc,
1650                          Expression => New_Occurrence_Of (E, Loc))));
1651
1652                   Decorate (Aspect, Aitem);
1653                   Insert_Pragma (Aitem);
1654                end if;
1655             end Analyze_Aspect_Convention;
1656
1657             ----------------------------------
1658             -- Analyze_Aspect_Export_Import --
1659             ----------------------------------
1660
1661             procedure Analyze_Aspect_Export_Import is
1662                Dummy_1 : Node_Id;
1663                Dummy_2 : Node_Id;
1664                Dummy_3 : Node_Id;
1665                Expo    : Node_Id;
1666                Imp     : Node_Id;
1667
1668             begin
1669                --  Obtain all interfacing aspects that apply to the related
1670                --  entity.
1671
1672                Get_Interfacing_Aspects
1673                  (Iface_Asp => Aspect,
1674                   Conv_Asp  => Dummy_1,
1675                   EN_Asp    => Dummy_2,
1676                   Expo_Asp  => Expo,
1677                   Imp_Asp   => Imp,
1678                   LN_Asp    => Dummy_3,
1679                   Do_Checks => True);
1680
1681                --  The related entity cannot be subject to both aspects Export
1682                --  and Import.
1683
1684                if Present (Expo) and then Present (Imp) then
1685                   Error_Msg_N
1686                     ("incompatible interfacing aspects given for &", E);
1687                   Error_Msg_Sloc := Sloc (Expo);
1688                   Error_Msg_N ("\aspect `Export` #", E);
1689                   Error_Msg_Sloc := Sloc (Imp);
1690                   Error_Msg_N ("\aspect `Import` #", E);
1691                end if;
1692
1693                --  A variable is most likely modified from the outside. Take
1694                --  Take the optimistic approach to avoid spurious errors.
1695
1696                if Ekind (E) = E_Variable then
1697                   Set_Never_Set_In_Source (E, False);
1698                end if;
1699
1700                --  Resolve the expression of an Import or Export here, and
1701                --  require it to be of type Boolean and static. This is not
1702                --  quite right, because in general this should be delayed,
1703                --  but that seems tricky for these, because normally Boolean
1704                --  aspects are replaced with pragmas at the freeze point in
1705                --  Make_Pragma_From_Boolean_Aspect.
1706
1707                if not Present (Expr)
1708                  or else Is_True (Static_Boolean (Expr))
1709                then
1710                   if A_Id = Aspect_Import then
1711                      Set_Has_Completion (E);
1712                      Set_Is_Imported (E);
1713
1714                      --  An imported object cannot be explicitly initialized
1715
1716                      if Nkind (N) = N_Object_Declaration
1717                        and then Present (Expression (N))
1718                      then
1719                         Error_Msg_N
1720                           ("imported entities cannot be initialized "
1721                            & "(RM B.1(24))", Expression (N));
1722                      end if;
1723
1724                   else
1725                      pragma Assert (A_Id = Aspect_Export);
1726                      Set_Is_Exported (E);
1727                   end if;
1728
1729                   --  Create the proper form of pragma Export or Import taking
1730                   --  into account Conversion, External_Name, and Link_Name.
1731
1732                   Aitem := Build_Export_Import_Pragma (Aspect, E);
1733
1734                --  Otherwise the expression is either False or erroneous. There
1735                --  is no corresponding pragma.
1736
1737                else
1738                   Aitem := Empty;
1739                end if;
1740             end Analyze_Aspect_Export_Import;
1741
1742             ---------------------------------------
1743             -- Analyze_Aspect_External_Link_Name --
1744             ---------------------------------------
1745
1746             procedure Analyze_Aspect_External_Link_Name is
1747                Dummy_1 : Node_Id;
1748                Dummy_2 : Node_Id;
1749                Dummy_3 : Node_Id;
1750                Expo    : Node_Id;
1751                Imp     : Node_Id;
1752
1753             begin
1754                --  Obtain all interfacing aspects that apply to the related
1755                --  entity.
1756
1757                Get_Interfacing_Aspects
1758                  (Iface_Asp => Aspect,
1759                   Conv_Asp  => Dummy_1,
1760                   EN_Asp    => Dummy_2,
1761                   Expo_Asp  => Expo,
1762                   Imp_Asp   => Imp,
1763                   LN_Asp    => Dummy_3,
1764                   Do_Checks => True);
1765
1766                --  Ensure that aspect External_Name applies to aspect Export or
1767                --  Import.
1768
1769                if A_Id = Aspect_External_Name then
1770                   if No (Expo) and then No (Imp) then
1771                      Error_Msg_N
1772                        ("aspect `External_Name` requires aspect `Import` or "
1773                         & "`Export`", Aspect);
1774                   end if;
1775
1776                --  Otherwise ensure that aspect Link_Name applies to aspect
1777                --  Export or Import.
1778
1779                else
1780                   pragma Assert (A_Id = Aspect_Link_Name);
1781                   if No (Expo) and then No (Imp) then
1782                      Error_Msg_N
1783                        ("aspect `Link_Name` requires aspect `Import` or "
1784                         & "`Export`", Aspect);
1785                   end if;
1786                end if;
1787             end Analyze_Aspect_External_Link_Name;
1788
1789             -----------------------------------------
1790             -- Analyze_Aspect_Implicit_Dereference --
1791             -----------------------------------------
1792
1793             procedure Analyze_Aspect_Implicit_Dereference is
1794                Disc        : Entity_Id;
1795                Parent_Disc : Entity_Id;
1796
1797             begin
1798                if not Is_Type (E) or else not Has_Discriminants (E) then
1799                   Error_Msg_N
1800                     ("aspect must apply to a type with discriminants", Expr);
1801
1802                elsif not Is_Entity_Name (Expr) then
1803                   Error_Msg_N
1804                     ("aspect must name a discriminant of current type", Expr);
1805
1806                else
1807                   Disc := First_Discriminant (E);
1808                   while Present (Disc) loop
1809                      if Chars (Expr) = Chars (Disc)
1810                        and then Ekind (Etype (Disc)) =
1811                                   E_Anonymous_Access_Type
1812                      then
1813                         Set_Has_Implicit_Dereference (E);
1814                         Set_Has_Implicit_Dereference (Disc);
1815                         exit;
1816                      end if;
1817
1818                      Next_Discriminant (Disc);
1819                   end loop;
1820
1821                   --  Error if no proper access discriminant
1822
1823                   if No (Disc) then
1824                      Error_Msg_NE ("not an access discriminant of&", Expr, E);
1825                      return;
1826                   end if;
1827                end if;
1828
1829                --  For a type extension, check whether parent has a
1830                --  reference discriminant, to verify that use is proper.
1831
1832                if Is_Derived_Type (E)
1833                  and then Has_Discriminants (Etype (E))
1834                then
1835                   Parent_Disc := Get_Reference_Discriminant (Etype (E));
1836
1837                   if Present (Parent_Disc)
1838                     and then Corresponding_Discriminant (Disc) /= Parent_Disc
1839                   then
1840                      Error_Msg_N
1841                        ("reference discriminant does not match discriminant "
1842                         & "of parent type", Expr);
1843                   end if;
1844                end if;
1845             end Analyze_Aspect_Implicit_Dereference;
1846
1847             -----------------------
1848             -- Make_Aitem_Pragma --
1849             -----------------------
1850
1851             procedure Make_Aitem_Pragma
1852               (Pragma_Argument_Associations : List_Id;
1853                Pragma_Name                  : Name_Id)
1854             is
1855                Args : List_Id := Pragma_Argument_Associations;
1856
1857             begin
1858                --  We should never get here if aspect was disabled
1859
1860                pragma Assert (not Is_Disabled (Aspect));
1861
1862                --  Certain aspects allow for an optional name or expression. Do
1863                --  not generate a pragma with empty argument association list.
1864
1865                if No (Args) or else No (Expression (First (Args))) then
1866                   Args := No_List;
1867                end if;
1868
1869                --  Build the pragma
1870
1871                Aitem :=
1872                  Make_Pragma (Loc,
1873                    Pragma_Argument_Associations => Args,
1874                    Pragma_Identifier =>
1875                      Make_Identifier (Sloc (Id), Pragma_Name),
1876                    Class_Present     => Class_Present (Aspect),
1877                    Split_PPC         => Split_PPC (Aspect));
1878
1879                --  Set additional semantic fields
1880
1881                if Is_Ignored (Aspect) then
1882                   Set_Is_Ignored (Aitem);
1883                elsif Is_Checked (Aspect) then
1884                   Set_Is_Checked (Aitem);
1885                end if;
1886
1887                Set_Corresponding_Aspect (Aitem, Aspect);
1888                Set_From_Aspect_Specification (Aitem);
1889             end Make_Aitem_Pragma;
1890
1891          --  Start of processing for Analyze_Aspect_Specifications
1892
1893          begin
1894             --  Skip aspect if already analyzed, to avoid looping in some cases
1895
1896             if Analyzed (Aspect) then
1897                goto Continue;
1898             end if;
1899
1900             --  Skip looking at aspect if it is totally disabled. Just mark it
1901             --  as such for later reference in the tree. This also sets the
1902             --  Is_Ignored and Is_Checked flags appropriately.
1903
1904             Check_Applicable_Policy (Aspect);
1905
1906             if Is_Disabled (Aspect) then
1907                goto Continue;
1908             end if;
1909
1910             --  Set the source location of expression, used in the case of
1911             --  a failed precondition/postcondition or invariant. Note that
1912             --  the source location of the expression is not usually the best
1913             --  choice here. For example, it gets located on the last AND
1914             --  keyword in a chain of boolean expressiond AND'ed together.
1915             --  It is best to put the message on the first character of the
1916             --  assertion, which is the effect of the First_Node call here.
1917
1918             if Present (Expr) then
1919                Eloc := Sloc (First_Node (Expr));
1920             end if;
1921
1922             --  Check restriction No_Implementation_Aspect_Specifications
1923
1924             if Implementation_Defined_Aspect (A_Id) then
1925                Check_Restriction
1926                  (No_Implementation_Aspect_Specifications, Aspect);
1927             end if;
1928
1929             --  Check restriction No_Specification_Of_Aspect
1930
1931             Check_Restriction_No_Specification_Of_Aspect (Aspect);
1932
1933             --  Mark aspect analyzed (actual analysis is delayed till later)
1934
1935             Set_Analyzed (Aspect);
1936             Set_Entity (Aspect, E);
1937             Ent := New_Occurrence_Of (E, Sloc (Id));
1938
1939             --  Check for duplicate aspect. Note that the Comes_From_Source
1940             --  test allows duplicate Pre/Post's that we generate internally
1941             --  to escape being flagged here.
1942
1943             if No_Duplicates_Allowed (A_Id) then
1944                Anod := First (L);
1945                while Anod /= Aspect loop
1946                   if Comes_From_Source (Aspect)
1947                     and then Same_Aspect (A_Id, Get_Aspect_Id (Anod))
1948                   then
1949                      Error_Msg_Name_1 := Nam;
1950                      Error_Msg_Sloc := Sloc (Anod);
1951
1952                      --  Case of same aspect specified twice
1953
1954                      if Class_Present (Anod) = Class_Present (Aspect) then
1955                         if not Class_Present (Anod) then
1956                            Error_Msg_NE
1957                              ("aspect% for & previously given#",
1958                               Id, E);
1959                         else
1960                            Error_Msg_NE
1961                              ("aspect `%''Class` for & previously given#",
1962                               Id, E);
1963                         end if;
1964                      end if;
1965                   end if;
1966
1967                   Next (Anod);
1968                end loop;
1969             end if;
1970
1971             --  Check some general restrictions on language defined aspects
1972
1973             if not Implementation_Defined_Aspect (A_Id) then
1974                Error_Msg_Name_1 := Nam;
1975
1976                --  Not allowed for renaming declarations. Examine the original
1977                --  node because a subprogram renaming may have been rewritten
1978                --  as a body.
1979
1980                if Nkind (Original_Node (N)) in N_Renaming_Declaration then
1981                   Error_Msg_N
1982                     ("aspect % not allowed for renaming declaration",
1983                      Aspect);
1984                end if;
1985
1986                --  Not allowed for formal type declarations
1987
1988                if Nkind (N) = N_Formal_Type_Declaration then
1989                   Error_Msg_N
1990                     ("aspect % not allowed for formal type declaration",
1991                      Aspect);
1992                end if;
1993             end if;
1994
1995             --  Copy expression for later processing by the procedures
1996             --  Check_Aspect_At_[Freeze_Point | End_Of_Declarations]
1997
1998             Set_Entity (Id, New_Copy_Tree (Expr));
1999
2000             --  Set Delay_Required as appropriate to aspect
2001
2002             case Aspect_Delay (A_Id) is
2003                when Always_Delay =>
2004                   Delay_Required := True;
2005
2006                when Never_Delay =>
2007                   Delay_Required := False;
2008
2009                when Rep_Aspect =>
2010
2011                   --  If expression has the form of an integer literal, then
2012                   --  do not delay, since we know the value cannot change.
2013                   --  This optimization catches most rep clause cases.
2014
2015                   --  For Boolean aspects, don't delay if no expression
2016
2017                   if A_Id in Boolean_Aspects and then No (Expr) then
2018                      Delay_Required := False;
2019
2020                   --  For non-Boolean aspects, don't delay if integer literal
2021
2022                   elsif A_Id not in Boolean_Aspects
2023                     and then Present (Expr)
2024                     and then Nkind (Expr) = N_Integer_Literal
2025                   then
2026                      Delay_Required := False;
2027
2028                   --  All other cases are delayed
2029
2030                   else
2031                      Delay_Required := True;
2032                      Set_Has_Delayed_Rep_Aspects (E);
2033                   end if;
2034             end case;
2035
2036             --  Processing based on specific aspect
2037
2038             case A_Id is
2039                when Aspect_Unimplemented =>
2040                   null; -- ??? temp for now
2041
2042                --  No_Aspect should be impossible
2043
2044                when No_Aspect =>
2045                   raise Program_Error;
2046
2047                --  Case 1: Aspects corresponding to attribute definition
2048                --  clauses.
2049
2050                when Aspect_Address              |
2051                     Aspect_Alignment            |
2052                     Aspect_Bit_Order            |
2053                     Aspect_Component_Size       |
2054                     Aspect_Constant_Indexing    |
2055                     Aspect_Default_Iterator     |
2056                     Aspect_Dispatching_Domain   |
2057                     Aspect_External_Tag         |
2058                     Aspect_Input                |
2059                     Aspect_Iterable             |
2060                     Aspect_Iterator_Element     |
2061                     Aspect_Machine_Radix        |
2062                     Aspect_Object_Size          |
2063                     Aspect_Output               |
2064                     Aspect_Read                 |
2065                     Aspect_Scalar_Storage_Order |
2066                     Aspect_Size                 |
2067                     Aspect_Small                |
2068                     Aspect_Secondary_Stack_Size |
2069                     Aspect_Simple_Storage_Pool  |
2070                     Aspect_Storage_Pool         |
2071                     Aspect_Stream_Size          |
2072                     Aspect_Value_Size           |
2073                     Aspect_Variable_Indexing    |
2074                     Aspect_Write                =>
2075
2076                   --  Indexing aspects apply only to tagged type
2077
2078                   if (A_Id = Aspect_Constant_Indexing
2079                         or else
2080                       A_Id = Aspect_Variable_Indexing)
2081                     and then not (Is_Type (E)
2082                                    and then Is_Tagged_Type (E))
2083                   then
2084                      Error_Msg_N
2085                        ("indexing aspect can only apply to a tagged type",
2086                         Aspect);
2087                      goto Continue;
2088                   end if;
2089
2090                   --  For the case of aspect Address, we don't consider that we
2091                   --  know the entity is never set in the source, since it is
2092                   --  is likely aliasing is occurring.
2093
2094                   --  Note: one might think that the analysis of the resulting
2095                   --  attribute definition clause would take care of that, but
2096                   --  that's not the case since it won't be from source.
2097
2098                   if A_Id = Aspect_Address then
2099                      Set_Never_Set_In_Source (E, False);
2100                   end if;
2101
2102                   --  Correctness of the profile of a stream operation is
2103                   --  verified at the freeze point, but we must detect the
2104                   --  illegal specification of this aspect for a subtype now,
2105                   --  to prevent malformed rep_item chains.
2106
2107                   if A_Id = Aspect_Input  or else
2108                      A_Id = Aspect_Output or else
2109                      A_Id = Aspect_Read   or else
2110                      A_Id = Aspect_Write
2111                   then
2112                      if not Is_First_Subtype (E) then
2113                         Error_Msg_N
2114                           ("local name must be a first subtype", Aspect);
2115                         goto Continue;
2116
2117                      --  If stream aspect applies to the class-wide type,
2118                      --  the generated attribute definition applies to the
2119                      --  class-wide type as well.
2120
2121                      elsif Class_Present (Aspect) then
2122                         Ent :=
2123                           Make_Attribute_Reference (Loc,
2124                             Prefix         => Ent,
2125                             Attribute_Name => Name_Class);
2126                      end if;
2127                   end if;
2128
2129                   --  Construct the attribute definition clause
2130
2131                   Aitem :=
2132                     Make_Attribute_Definition_Clause (Loc,
2133                       Name       => Ent,
2134                       Chars      => Chars (Id),
2135                       Expression => Relocate_Node (Expr));
2136
2137                   --  If the address is specified, then we treat the entity as
2138                   --  referenced, to avoid spurious warnings. This is analogous
2139                   --  to what is done with an attribute definition clause, but
2140                   --  here we don't want to generate a reference because this
2141                   --  is the point of definition of the entity.
2142
2143                   if A_Id = Aspect_Address then
2144                      Set_Referenced (E);
2145                   end if;
2146
2147                --  Case 2: Aspects corresponding to pragmas
2148
2149                --  Case 2a: Aspects corresponding to pragmas with two
2150                --  arguments, where the first argument is a local name
2151                --  referring to the entity, and the second argument is the
2152                --  aspect definition expression.
2153
2154                --  Linker_Section/Suppress/Unsuppress
2155
2156                when Aspect_Linker_Section |
2157                     Aspect_Suppress       |
2158                     Aspect_Unsuppress     =>
2159
2160                   Make_Aitem_Pragma
2161                     (Pragma_Argument_Associations => New_List (
2162                        Make_Pragma_Argument_Association (Loc,
2163                          Expression => New_Occurrence_Of (E, Loc)),
2164                        Make_Pragma_Argument_Association (Sloc (Expr),
2165                          Expression => Relocate_Node (Expr))),
2166                      Pragma_Name                  => Chars (Id));
2167
2168                --  Synchronization
2169
2170                --  Corresponds to pragma Implemented, construct the pragma
2171
2172                when Aspect_Synchronization =>
2173                   Make_Aitem_Pragma
2174                     (Pragma_Argument_Associations => New_List (
2175                        Make_Pragma_Argument_Association (Loc,
2176                          Expression => New_Occurrence_Of (E, Loc)),
2177                        Make_Pragma_Argument_Association (Sloc (Expr),
2178                          Expression => Relocate_Node (Expr))),
2179                      Pragma_Name                  => Name_Implemented);
2180
2181                --  Attach_Handler
2182
2183                when Aspect_Attach_Handler =>
2184                   Make_Aitem_Pragma
2185                     (Pragma_Argument_Associations => New_List (
2186                        Make_Pragma_Argument_Association (Sloc (Ent),
2187                          Expression => Ent),
2188                        Make_Pragma_Argument_Association (Sloc (Expr),
2189                          Expression => Relocate_Node (Expr))),
2190                      Pragma_Name                  => Name_Attach_Handler);
2191
2192                   --  We need to insert this pragma into the tree to get proper
2193                   --  processing and to look valid from a placement viewpoint.
2194
2195                   Insert_Pragma (Aitem);
2196                   goto Continue;
2197
2198                --  Dynamic_Predicate, Predicate, Static_Predicate
2199
2200                when Aspect_Dynamic_Predicate |
2201                     Aspect_Predicate         |
2202                     Aspect_Static_Predicate  =>
2203
2204                   --  These aspects apply only to subtypes
2205
2206                   if not Is_Type (E) then
2207                      Error_Msg_N
2208                        ("predicate can only be specified for a subtype",
2209                         Aspect);
2210                      goto Continue;
2211
2212                   elsif Is_Incomplete_Type (E) then
2213                      Error_Msg_N
2214                        ("predicate cannot apply to incomplete view", Aspect);
2215                      goto Continue;
2216                   end if;
2217
2218                   --  Construct the pragma (always a pragma Predicate, with
2219                   --  flags recording whether it is static/dynamic). We also
2220                   --  set flags recording this in the type itself.
2221
2222                   Make_Aitem_Pragma
2223                     (Pragma_Argument_Associations => New_List (
2224                        Make_Pragma_Argument_Association (Sloc (Ent),
2225                          Expression => Ent),
2226                        Make_Pragma_Argument_Association (Sloc (Expr),
2227                          Expression => Relocate_Node (Expr))),
2228                      Pragma_Name => Name_Predicate);
2229
2230                   --  Mark type has predicates, and remember what kind of
2231                   --  aspect lead to this predicate (we need this to access
2232                   --  the right set of check policies later on).
2233
2234                   Set_Has_Predicates (E);
2235
2236                   if A_Id = Aspect_Dynamic_Predicate then
2237                      Set_Has_Dynamic_Predicate_Aspect (E);
2238                   elsif A_Id = Aspect_Static_Predicate then
2239                      Set_Has_Static_Predicate_Aspect (E);
2240                   end if;
2241
2242                   --  If the type is private, indicate that its completion
2243                   --  has a freeze node, because that is the one that will
2244                   --  be visible at freeze time.
2245
2246                   if Is_Private_Type (E) and then Present (Full_View (E)) then
2247                      Set_Has_Predicates (Full_View (E));
2248
2249                      if A_Id = Aspect_Dynamic_Predicate then
2250                         Set_Has_Dynamic_Predicate_Aspect (Full_View (E));
2251                      elsif A_Id = Aspect_Static_Predicate then
2252                         Set_Has_Static_Predicate_Aspect (Full_View (E));
2253                      end if;
2254
2255                      Set_Has_Delayed_Aspects (Full_View (E));
2256                      Ensure_Freeze_Node (Full_View (E));
2257                   end if;
2258
2259                --  Predicate_Failure
2260
2261                when Aspect_Predicate_Failure =>
2262
2263                   --  This aspect applies only to subtypes
2264
2265                   if not Is_Type (E) then
2266                      Error_Msg_N
2267                        ("predicate can only be specified for a subtype",
2268                         Aspect);
2269                      goto Continue;
2270
2271                   elsif Is_Incomplete_Type (E) then
2272                      Error_Msg_N
2273                        ("predicate cannot apply to incomplete view", Aspect);
2274                      goto Continue;
2275                   end if;
2276
2277                   --  Construct the pragma
2278
2279                   Make_Aitem_Pragma
2280                     (Pragma_Argument_Associations => New_List (
2281                        Make_Pragma_Argument_Association (Sloc (Ent),
2282                          Expression => Ent),
2283                        Make_Pragma_Argument_Association (Sloc (Expr),
2284                          Expression => Relocate_Node (Expr))),
2285                      Pragma_Name => Name_Predicate_Failure);
2286
2287                   Set_Has_Predicates (E);
2288
2289                   --  If the type is private, indicate that its completion
2290                   --  has a freeze node, because that is the one that will
2291                   --  be visible at freeze time.
2292
2293                   if Is_Private_Type (E) and then Present (Full_View (E)) then
2294                      Set_Has_Predicates (Full_View (E));
2295                      Set_Has_Delayed_Aspects (Full_View (E));
2296                      Ensure_Freeze_Node (Full_View (E));
2297                   end if;
2298
2299                --  Case 2b: Aspects corresponding to pragmas with two
2300                --  arguments, where the second argument is a local name
2301                --  referring to the entity, and the first argument is the
2302                --  aspect definition expression.
2303
2304                --  Convention
2305
2306                when Aspect_Convention =>
2307                   Analyze_Aspect_Convention;
2308                   goto Continue;
2309
2310                --  External_Name, Link_Name
2311
2312                when Aspect_External_Name |
2313                     Aspect_Link_Name     =>
2314                   Analyze_Aspect_External_Link_Name;
2315                   goto Continue;
2316
2317                --  CPU, Interrupt_Priority, Priority
2318
2319                --  These three aspects can be specified for a subprogram spec
2320                --  or body, in which case we analyze the expression and export
2321                --  the value of the aspect.
2322
2323                --  Previously, we generated an equivalent pragma for bodies
2324                --  (note that the specs cannot contain these pragmas). The
2325                --  pragma was inserted ahead of local declarations, rather than
2326                --  after the body. This leads to a certain duplication between
2327                --  the processing performed for the aspect and the pragma, but
2328                --  given the straightforward handling required it is simpler
2329                --  to duplicate than to translate the aspect in the spec into
2330                --  a pragma in the declarative part of the body.
2331
2332                when Aspect_CPU                |
2333                     Aspect_Interrupt_Priority |
2334                     Aspect_Priority           =>
2335
2336                   if Nkind_In (N, N_Subprogram_Body,
2337                                   N_Subprogram_Declaration)
2338                   then
2339                      --  Analyze the aspect expression
2340
2341                      Analyze_And_Resolve (Expr, Standard_Integer);
2342
2343                      --  Interrupt_Priority aspect not allowed for main
2344                      --  subprograms. RM D.1 does not forbid this explicitly,
2345                      --  but RM J.15.11(6/3) does not permit pragma
2346                      --  Interrupt_Priority for subprograms.
2347
2348                      if A_Id = Aspect_Interrupt_Priority then
2349                         Error_Msg_N
2350                           ("Interrupt_Priority aspect cannot apply to "
2351                            & "subprogram", Expr);
2352
2353                      --  The expression must be static
2354
2355                      elsif not Is_OK_Static_Expression (Expr) then
2356                         Flag_Non_Static_Expr
2357                           ("aspect requires static expression!", Expr);
2358
2359                      --  Check whether this is the main subprogram. Issue a
2360                      --  warning only if it is obviously not a main program
2361                      --  (when it has parameters or when the subprogram is
2362                      --  within a package).
2363
2364                      elsif Present (Parameter_Specifications
2365                                       (Specification (N)))
2366                        or else not Is_Compilation_Unit (Defining_Entity (N))
2367                      then
2368                         --  See RM D.1(14/3) and D.16(12/3)
2369
2370                         Error_Msg_N
2371                           ("aspect applied to subprogram other than the "
2372                            & "main subprogram has no effect??", Expr);
2373
2374                      --  Otherwise check in range and export the value
2375
2376                      --  For the CPU aspect
2377
2378                      elsif A_Id = Aspect_CPU then
2379                         if Is_In_Range (Expr, RTE (RE_CPU_Range)) then
2380
2381                            --  Value is correct so we export the value to make
2382                            --  it available at execution time.
2383
2384                            Set_Main_CPU
2385                              (Main_Unit, UI_To_Int (Expr_Value (Expr)));
2386
2387                         else
2388                            Error_Msg_N
2389                              ("main subprogram CPU is out of range", Expr);
2390                         end if;
2391
2392                      --  For the Priority aspect
2393
2394                      elsif A_Id = Aspect_Priority then
2395                         if Is_In_Range (Expr, RTE (RE_Priority)) then
2396
2397                            --  Value is correct so we export the value to make
2398                            --  it available at execution time.
2399
2400                            Set_Main_Priority
2401                              (Main_Unit, UI_To_Int (Expr_Value (Expr)));
2402
2403                         --  Ignore pragma if Relaxed_RM_Semantics to support
2404                         --  other targets/non GNAT compilers.
2405
2406                         elsif not Relaxed_RM_Semantics then
2407                            Error_Msg_N
2408                              ("main subprogram priority is out of range",
2409                               Expr);
2410                         end if;
2411                      end if;
2412
2413                      --  Load an arbitrary entity from System.Tasking.Stages
2414                      --  or System.Tasking.Restricted.Stages (depending on
2415                      --  the supported profile) to make sure that one of these
2416                      --  packages is implicitly with'ed, since we need to have
2417                      --  the tasking run time active for the pragma Priority to
2418                      --  have any effect. Previously we with'ed the package
2419                      --  System.Tasking, but this package does not trigger the
2420                      --  required initialization of the run-time library.
2421
2422                      declare
2423                         Discard : Entity_Id;
2424                      begin
2425                         if Restricted_Profile then
2426                            Discard := RTE (RE_Activate_Restricted_Tasks);
2427                         else
2428                            Discard := RTE (RE_Activate_Tasks);
2429                         end if;
2430                      end;
2431
2432                      --  Handling for these aspects in subprograms is complete
2433
2434                      goto Continue;
2435
2436                   --  For tasks pass the aspect as an attribute
2437
2438                   else
2439                      Aitem :=
2440                        Make_Attribute_Definition_Clause (Loc,
2441                          Name       => Ent,
2442                          Chars      => Chars (Id),
2443                          Expression => Relocate_Node (Expr));
2444                   end if;
2445
2446                --  Warnings
2447
2448                when Aspect_Warnings =>
2449                   Make_Aitem_Pragma
2450                     (Pragma_Argument_Associations => New_List (
2451                        Make_Pragma_Argument_Association (Sloc (Expr),
2452                          Expression => Relocate_Node (Expr)),
2453                        Make_Pragma_Argument_Association (Loc,
2454                          Expression => New_Occurrence_Of (E, Loc))),
2455                      Pragma_Name                  => Chars (Id));
2456
2457                   Decorate (Aspect, Aitem);
2458                   Insert_Pragma (Aitem);
2459                   goto Continue;
2460
2461                --  Case 2c: Aspects corresponding to pragmas with three
2462                --  arguments.
2463
2464                --  Invariant aspects have a first argument that references the
2465                --  entity, a second argument that is the expression and a third
2466                --  argument that is an appropriate message.
2467
2468                --  Invariant, Type_Invariant
2469
2470                when Aspect_Invariant      |
2471                     Aspect_Type_Invariant =>
2472
2473                   --  Analysis of the pragma will verify placement legality:
2474                   --  an invariant must apply to a private type, or appear in
2475                   --  the private part of a spec and apply to a completion.
2476
2477                   Make_Aitem_Pragma
2478                     (Pragma_Argument_Associations => New_List (
2479                        Make_Pragma_Argument_Association (Sloc (Ent),
2480                          Expression => Ent),
2481                        Make_Pragma_Argument_Association (Sloc (Expr),
2482                          Expression => Relocate_Node (Expr))),
2483                      Pragma_Name                  => Name_Invariant);
2484
2485                   --  Add message unless exception messages are suppressed
2486
2487                   if not Opt.Exception_Locations_Suppressed then
2488                      Append_To (Pragma_Argument_Associations (Aitem),
2489                        Make_Pragma_Argument_Association (Eloc,
2490                          Chars      => Name_Message,
2491                          Expression =>
2492                            Make_String_Literal (Eloc,
2493                              Strval => "failed invariant from "
2494                                        & Build_Location_String (Eloc))));
2495                   end if;
2496
2497                   --  For Invariant case, insert immediately after the entity
2498                   --  declaration. We do not have to worry about delay issues
2499                   --  since the pragma processing takes care of this.
2500
2501                   Delay_Required := False;
2502
2503                --  Case 2d : Aspects that correspond to a pragma with one
2504                --  argument.
2505
2506                --  Abstract_State
2507
2508                --  Aspect Abstract_State introduces implicit declarations for
2509                --  all state abstraction entities it defines. To emulate this
2510                --  behavior, insert the pragma at the beginning of the visible
2511                --  declarations of the related package so that it is analyzed
2512                --  immediately.
2513
2514                when Aspect_Abstract_State => Abstract_State : declare
2515                   Context : Node_Id := N;
2516
2517                begin
2518                   --  When aspect Abstract_State appears on a generic package,
2519                   --  it is propageted to the package instance. The context in
2520                   --  this case is the instance spec.
2521
2522                   if Nkind (Context) = N_Package_Instantiation then
2523                      Context := Instance_Spec (Context);
2524                   end if;
2525
2526                   if Nkind_In (Context, N_Generic_Package_Declaration,
2527                                         N_Package_Declaration)
2528                   then
2529                      Make_Aitem_Pragma
2530                        (Pragma_Argument_Associations => New_List (
2531                           Make_Pragma_Argument_Association (Loc,
2532                             Expression => Relocate_Node (Expr))),
2533                         Pragma_Name                  => Name_Abstract_State);
2534
2535                      Decorate (Aspect, Aitem);
2536                      Insert_Pragma
2537                        (Prag        => Aitem,
2538                         Is_Instance =>
2539                           Is_Generic_Instance (Defining_Entity (Context)));
2540
2541                   else
2542                      Error_Msg_NE
2543                        ("aspect & must apply to a package declaration",
2544                         Aspect, Id);
2545                   end if;
2546
2547                   goto Continue;
2548                end Abstract_State;
2549
2550                --  Aspect Async_Readers is never delayed because it is
2551                --  equivalent to a source pragma which appears after the
2552                --  related object declaration.
2553
2554                when Aspect_Async_Readers =>
2555                   Make_Aitem_Pragma
2556                     (Pragma_Argument_Associations => New_List (
2557                        Make_Pragma_Argument_Association (Loc,
2558                          Expression => Relocate_Node (Expr))),
2559                      Pragma_Name                  => Name_Async_Readers);
2560
2561                   Decorate (Aspect, Aitem);
2562                   Insert_Pragma (Aitem);
2563                   goto Continue;
2564
2565                --  Aspect Async_Writers is never delayed because it is
2566                --  equivalent to a source pragma which appears after the
2567                --  related object declaration.
2568
2569                when Aspect_Async_Writers =>
2570                   Make_Aitem_Pragma
2571                     (Pragma_Argument_Associations => New_List (
2572                        Make_Pragma_Argument_Association (Loc,
2573                          Expression => Relocate_Node (Expr))),
2574                      Pragma_Name                  => Name_Async_Writers);
2575
2576                   Decorate (Aspect, Aitem);
2577                   Insert_Pragma (Aitem);
2578                   goto Continue;
2579
2580                --  Aspect Constant_After_Elaboration is never delayed because
2581                --  it is equivalent to a source pragma which appears after the
2582                --  related object declaration.
2583
2584                when Aspect_Constant_After_Elaboration =>
2585                   Make_Aitem_Pragma
2586                     (Pragma_Argument_Associations => New_List (
2587                        Make_Pragma_Argument_Association (Loc,
2588                          Expression => Relocate_Node (Expr))),
2589                      Pragma_Name                  =>
2590                        Name_Constant_After_Elaboration);
2591
2592                   Decorate (Aspect, Aitem);
2593                   Insert_Pragma (Aitem);
2594                   goto Continue;
2595
2596                --  Aspect Default_Internal_Condition is never delayed because
2597                --  it is equivalent to a source pragma which appears after the
2598                --  related private type. To deal with forward references, the
2599                --  generated pragma is stored in the rep chain of the related
2600                --  private type as types do not carry contracts. The pragma is
2601                --  wrapped inside of a procedure at the freeze point of the
2602                --  private type's full view.
2603
2604                when Aspect_Default_Initial_Condition =>
2605                   Make_Aitem_Pragma
2606                     (Pragma_Argument_Associations => New_List (
2607                        Make_Pragma_Argument_Association (Loc,
2608                          Expression => Relocate_Node (Expr))),
2609                      Pragma_Name                  =>
2610                        Name_Default_Initial_Condition);
2611
2612                   Decorate (Aspect, Aitem);
2613                   Insert_Pragma (Aitem);
2614                   goto Continue;
2615
2616                --  Default_Storage_Pool
2617
2618                when Aspect_Default_Storage_Pool =>
2619                   Make_Aitem_Pragma
2620                     (Pragma_Argument_Associations => New_List (
2621                        Make_Pragma_Argument_Association (Loc,
2622                          Expression => Relocate_Node (Expr))),
2623                      Pragma_Name                  =>
2624                        Name_Default_Storage_Pool);
2625
2626                   Decorate (Aspect, Aitem);
2627                   Insert_Pragma (Aitem);
2628                   goto Continue;
2629
2630                --  Depends
2631
2632                --  Aspect Depends is never delayed because it is equivalent to
2633                --  a source pragma which appears after the related subprogram.
2634                --  To deal with forward references, the generated pragma is
2635                --  stored in the contract of the related subprogram and later
2636                --  analyzed at the end of the declarative region. See routine
2637                --  Analyze_Depends_In_Decl_Part for details.
2638
2639                when Aspect_Depends =>
2640                   Make_Aitem_Pragma
2641                     (Pragma_Argument_Associations => New_List (
2642                        Make_Pragma_Argument_Association (Loc,
2643                          Expression => Relocate_Node (Expr))),
2644                      Pragma_Name                  => Name_Depends);
2645
2646                   Decorate (Aspect, Aitem);
2647                   Insert_Pragma (Aitem);
2648                   goto Continue;
2649
2650                --  Aspect Effecitve_Reads is never delayed because it is
2651                --  equivalent to a source pragma which appears after the
2652                --  related object declaration.
2653
2654                when Aspect_Effective_Reads =>
2655                   Make_Aitem_Pragma
2656                     (Pragma_Argument_Associations => New_List (
2657                        Make_Pragma_Argument_Association (Loc,
2658                          Expression => Relocate_Node (Expr))),
2659                      Pragma_Name                  => Name_Effective_Reads);
2660
2661                   Decorate (Aspect, Aitem);
2662                   Insert_Pragma (Aitem);
2663                   goto Continue;
2664
2665                --  Aspect Effective_Writes is never delayed because it is
2666                --  equivalent to a source pragma which appears after the
2667                --  related object declaration.
2668
2669                when Aspect_Effective_Writes =>
2670                   Make_Aitem_Pragma
2671                     (Pragma_Argument_Associations => New_List (
2672                        Make_Pragma_Argument_Association (Loc,
2673                          Expression => Relocate_Node (Expr))),
2674                      Pragma_Name                  => Name_Effective_Writes);
2675
2676                   Decorate (Aspect, Aitem);
2677                   Insert_Pragma (Aitem);
2678                   goto Continue;
2679
2680                --  Aspect Extensions_Visible is never delayed because it is
2681                --  equivalent to a source pragma which appears after the
2682                --  related subprogram.
2683
2684                when Aspect_Extensions_Visible =>
2685                   Make_Aitem_Pragma
2686                     (Pragma_Argument_Associations => New_List (
2687                        Make_Pragma_Argument_Association (Loc,
2688                          Expression => Relocate_Node (Expr))),
2689                      Pragma_Name                  => Name_Extensions_Visible);
2690
2691                   Decorate (Aspect, Aitem);
2692                   Insert_Pragma (Aitem);
2693                   goto Continue;
2694
2695                --  Aspect Ghost is never delayed because it is equivalent to a
2696                --  source pragma which appears at the top of [generic] package
2697                --  declarations or after an object, a [generic] subprogram, or
2698                --  a type declaration.
2699
2700                when Aspect_Ghost =>
2701                   Make_Aitem_Pragma
2702                     (Pragma_Argument_Associations => New_List (
2703                        Make_Pragma_Argument_Association (Loc,
2704                          Expression => Relocate_Node (Expr))),
2705                      Pragma_Name                  => Name_Ghost);
2706
2707                   Decorate (Aspect, Aitem);
2708                   Insert_Pragma (Aitem);
2709                   goto Continue;
2710
2711                --  Global
2712
2713                --  Aspect Global is never delayed because it is equivalent to
2714                --  a source pragma which appears after the related subprogram.
2715                --  To deal with forward references, the generated pragma is
2716                --  stored in the contract of the related subprogram and later
2717                --  analyzed at the end of the declarative region. See routine
2718                --  Analyze_Global_In_Decl_Part for details.
2719
2720                when Aspect_Global =>
2721                   Make_Aitem_Pragma
2722                     (Pragma_Argument_Associations => New_List (
2723                        Make_Pragma_Argument_Association (Loc,
2724                          Expression => Relocate_Node (Expr))),
2725                      Pragma_Name                  => Name_Global);
2726
2727                   Decorate (Aspect, Aitem);
2728                   Insert_Pragma (Aitem);
2729                   goto Continue;
2730
2731                --  Initial_Condition
2732
2733                --  Aspect Initial_Condition is never delayed because it is
2734                --  equivalent to a source pragma which appears after the
2735                --  related package. To deal with forward references, the
2736                --  generated pragma is stored in the contract of the related
2737                --  package and later analyzed at the end of the declarative
2738                --  region. See routine Analyze_Initial_Condition_In_Decl_Part
2739                --  for details.
2740
2741                when Aspect_Initial_Condition => Initial_Condition : declare
2742                   Context : Node_Id := N;
2743
2744                begin
2745                   --  When aspect Initial_Condition appears on a generic
2746                   --  package, it is propageted to the package instance. The
2747                   --  context in this case is the instance spec.
2748
2749                   if Nkind (Context) = N_Package_Instantiation then
2750                      Context := Instance_Spec (Context);
2751                   end if;
2752
2753                   if Nkind_In (Context, N_Generic_Package_Declaration,
2754                                         N_Package_Declaration)
2755                   then
2756                      Make_Aitem_Pragma
2757                        (Pragma_Argument_Associations => New_List (
2758                           Make_Pragma_Argument_Association (Loc,
2759                             Expression => Relocate_Node (Expr))),
2760                         Pragma_Name                  =>
2761                           Name_Initial_Condition);
2762
2763                      Decorate (Aspect, Aitem);
2764                      Insert_Pragma
2765                        (Prag        => Aitem,
2766                         Is_Instance =>
2767                           Is_Generic_Instance (Defining_Entity (Context)));
2768
2769                   --  Otherwise the context is illegal
2770
2771                   else
2772                      Error_Msg_NE
2773                        ("aspect & must apply to a package declaration",
2774                         Aspect, Id);
2775                   end if;
2776
2777                   goto Continue;
2778                end Initial_Condition;
2779
2780                --  Initializes
2781
2782                --  Aspect Initializes is never delayed because it is equivalent
2783                --  to a source pragma appearing after the related package. To
2784                --  deal with forward references, the generated pragma is stored
2785                --  in the contract of the related package and later analyzed at
2786                --  the end of the declarative region. For details, see routine
2787                --  Analyze_Initializes_In_Decl_Part.
2788
2789                when Aspect_Initializes => Initializes : declare
2790                   Context : Node_Id := N;
2791
2792                begin
2793                   --  When aspect Initializes appears on a generic package,
2794                   --  it is propageted to the package instance. The context
2795                   --  in this case is the instance spec.
2796
2797                   if Nkind (Context) = N_Package_Instantiation then
2798                      Context := Instance_Spec (Context);
2799                   end if;
2800
2801                   if Nkind_In (Context, N_Generic_Package_Declaration,
2802                                         N_Package_Declaration)
2803                   then
2804                      Make_Aitem_Pragma
2805                        (Pragma_Argument_Associations => New_List (
2806                           Make_Pragma_Argument_Association (Loc,
2807                             Expression => Relocate_Node (Expr))),
2808                         Pragma_Name                  => Name_Initializes);
2809
2810                      Decorate (Aspect, Aitem);
2811                      Insert_Pragma
2812                        (Prag        => Aitem,
2813                         Is_Instance =>
2814                           Is_Generic_Instance (Defining_Entity (Context)));
2815
2816                   --  Otherwise the context is illegal
2817
2818                   else
2819                      Error_Msg_NE
2820                        ("aspect & must apply to a package declaration",
2821                         Aspect, Id);
2822                   end if;
2823
2824                   goto Continue;
2825                end Initializes;
2826
2827                --  Max_Queue_Length
2828
2829                when Aspect_Max_Queue_Length =>
2830                   Make_Aitem_Pragma
2831                     (Pragma_Argument_Associations => New_List (
2832                        Make_Pragma_Argument_Association (Loc,
2833                          Expression => Relocate_Node (Expr))),
2834                      Pragma_Name                  => Name_Max_Queue_Length);
2835
2836                   Decorate (Aspect, Aitem);
2837                   Insert_Pragma (Aitem);
2838                   goto Continue;
2839
2840                --  Obsolescent
2841
2842                when Aspect_Obsolescent => declare
2843                   Args : List_Id;
2844
2845                begin
2846                   if No (Expr) then
2847                      Args := No_List;
2848                   else
2849                      Args := New_List (
2850                        Make_Pragma_Argument_Association (Sloc (Expr),
2851                          Expression => Relocate_Node (Expr)));
2852                   end if;
2853
2854                   Make_Aitem_Pragma
2855                     (Pragma_Argument_Associations => Args,
2856                      Pragma_Name                  => Chars (Id));
2857                end;
2858
2859                --  Part_Of
2860
2861                when Aspect_Part_Of =>
2862                   if Nkind_In (N, N_Object_Declaration,
2863                                   N_Package_Instantiation)
2864                     or else Is_Single_Concurrent_Type_Declaration (N)
2865                   then
2866                      Make_Aitem_Pragma
2867                        (Pragma_Argument_Associations => New_List (
2868                           Make_Pragma_Argument_Association (Loc,
2869                             Expression => Relocate_Node (Expr))),
2870                         Pragma_Name                  => Name_Part_Of);
2871
2872                      Decorate (Aspect, Aitem);
2873                      Insert_Pragma (Aitem);
2874
2875                   else
2876                      Error_Msg_NE
2877                        ("aspect & must apply to package instantiation, "
2878                         & "object, single protected type or single task type",
2879                         Aspect, Id);
2880                   end if;
2881
2882                   goto Continue;
2883
2884                --  SPARK_Mode
2885
2886                when Aspect_SPARK_Mode =>
2887                   Make_Aitem_Pragma
2888                     (Pragma_Argument_Associations => New_List (
2889                        Make_Pragma_Argument_Association (Loc,
2890                          Expression => Relocate_Node (Expr))),
2891                      Pragma_Name                  => Name_SPARK_Mode);
2892
2893                   Decorate (Aspect, Aitem);
2894                   Insert_Pragma (Aitem);
2895                   goto Continue;
2896
2897                --  Refined_Depends
2898
2899                --  Aspect Refined_Depends is never delayed because it is
2900                --  equivalent to a source pragma which appears in the
2901                --  declarations of the related subprogram body. To deal with
2902                --  forward references, the generated pragma is stored in the
2903                --  contract of the related subprogram body and later analyzed
2904                --  at the end of the declarative region. For details, see
2905                --  routine Analyze_Refined_Depends_In_Decl_Part.
2906
2907                when Aspect_Refined_Depends =>
2908                   Make_Aitem_Pragma
2909                     (Pragma_Argument_Associations => New_List (
2910                        Make_Pragma_Argument_Association (Loc,
2911                          Expression => Relocate_Node (Expr))),
2912                      Pragma_Name                  => Name_Refined_Depends);
2913
2914                   Decorate (Aspect, Aitem);
2915                   Insert_Pragma (Aitem);
2916                   goto Continue;
2917
2918                --  Refined_Global
2919
2920                --  Aspect Refined_Global is never delayed because it is
2921                --  equivalent to a source pragma which appears in the
2922                --  declarations of the related subprogram body. To deal with
2923                --  forward references, the generated pragma is stored in the
2924                --  contract of the related subprogram body and later analyzed
2925                --  at the end of the declarative region. For details, see
2926                --  routine Analyze_Refined_Global_In_Decl_Part.
2927
2928                when Aspect_Refined_Global =>
2929                   Make_Aitem_Pragma
2930                     (Pragma_Argument_Associations => New_List (
2931                        Make_Pragma_Argument_Association (Loc,
2932                          Expression => Relocate_Node (Expr))),
2933                      Pragma_Name                  => Name_Refined_Global);
2934
2935                   Decorate (Aspect, Aitem);
2936                   Insert_Pragma (Aitem);
2937                   goto Continue;
2938
2939                --  Refined_Post
2940
2941                when Aspect_Refined_Post =>
2942                   Make_Aitem_Pragma
2943                     (Pragma_Argument_Associations => New_List (
2944                        Make_Pragma_Argument_Association (Loc,
2945                          Expression => Relocate_Node (Expr))),
2946                      Pragma_Name                  => Name_Refined_Post);
2947
2948                   Decorate (Aspect, Aitem);
2949                   Insert_Pragma (Aitem);
2950                   goto Continue;
2951
2952                --  Refined_State
2953
2954                when Aspect_Refined_State =>
2955
2956                   --  The corresponding pragma for Refined_State is inserted in
2957                   --  the declarations of the related package body. This action
2958                   --  synchronizes both the source and from-aspect versions of
2959                   --  the pragma.
2960
2961                   if Nkind (N) = N_Package_Body then
2962                      Make_Aitem_Pragma
2963                        (Pragma_Argument_Associations => New_List (
2964                           Make_Pragma_Argument_Association (Loc,
2965                             Expression => Relocate_Node (Expr))),
2966                         Pragma_Name                  => Name_Refined_State);
2967
2968                      Decorate (Aspect, Aitem);
2969                      Insert_Pragma (Aitem);
2970
2971                   --  Otherwise the context is illegal
2972
2973                   else
2974                      Error_Msg_NE
2975                        ("aspect & must apply to a package body", Aspect, Id);
2976                   end if;
2977
2978                   goto Continue;
2979
2980                --  Relative_Deadline
2981
2982                when Aspect_Relative_Deadline =>
2983                   Make_Aitem_Pragma
2984                     (Pragma_Argument_Associations => New_List (
2985                        Make_Pragma_Argument_Association (Loc,
2986                          Expression => Relocate_Node (Expr))),
2987                       Pragma_Name                 => Name_Relative_Deadline);
2988
2989                   --  If the aspect applies to a task, the corresponding pragma
2990                   --  must appear within its declarations, not after.
2991
2992                   if Nkind (N) = N_Task_Type_Declaration then
2993                      declare
2994                         Def : Node_Id;
2995                         V   : List_Id;
2996
2997                      begin
2998                         if No (Task_Definition (N)) then
2999                            Set_Task_Definition (N,
3000                              Make_Task_Definition (Loc,
3001                                 Visible_Declarations => New_List,
3002                                 End_Label => Empty));
3003                         end if;
3004
3005                         Def := Task_Definition (N);
3006                         V  := Visible_Declarations (Def);
3007                         if not Is_Empty_List (V) then
3008                            Insert_Before (First (V), Aitem);
3009
3010                         else
3011                            Set_Visible_Declarations (Def, New_List (Aitem));
3012                         end if;
3013
3014                         goto Continue;
3015                      end;
3016                   end if;
3017
3018                --  Aspect Volatile_Function is never delayed because it is
3019                --  equivalent to a source pragma which appears after the
3020                --  related subprogram.
3021
3022                when Aspect_Volatile_Function =>
3023                   Make_Aitem_Pragma
3024                     (Pragma_Argument_Associations => New_List (
3025                        Make_Pragma_Argument_Association (Loc,
3026                          Expression => Relocate_Node (Expr))),
3027                      Pragma_Name                  => Name_Volatile_Function);
3028
3029                   Decorate (Aspect, Aitem);
3030                   Insert_Pragma (Aitem);
3031                   goto Continue;
3032
3033                --  Case 2e: Annotate aspect
3034
3035                when Aspect_Annotate =>
3036                   declare
3037                      Args  : List_Id;
3038                      Pargs : List_Id;
3039                      Arg   : Node_Id;
3040
3041                   begin
3042                      --  The argument can be a single identifier
3043
3044                      if Nkind (Expr) = N_Identifier then
3045
3046                         --  One level of parens is allowed
3047
3048                         if Paren_Count (Expr) > 1 then
3049                            Error_Msg_F ("extra parentheses ignored", Expr);
3050                         end if;
3051
3052                         Set_Paren_Count (Expr, 0);
3053
3054                         --  Add the single item to the list
3055
3056                         Args := New_List (Expr);
3057
3058                      --  Otherwise we must have an aggregate
3059
3060                      elsif Nkind (Expr) = N_Aggregate then
3061
3062                         --  Must be positional
3063
3064                         if Present (Component_Associations (Expr)) then
3065                            Error_Msg_F
3066                              ("purely positional aggregate required", Expr);
3067                            goto Continue;
3068                         end if;
3069
3070                         --  Must not be parenthesized
3071
3072                         if Paren_Count (Expr) /= 0 then
3073                            Error_Msg_F ("extra parentheses ignored", Expr);
3074                         end if;
3075
3076                         --  List of arguments is list of aggregate expressions
3077
3078                         Args := Expressions (Expr);
3079
3080                      --  Anything else is illegal
3081
3082                      else
3083                         Error_Msg_F ("wrong form for Annotate aspect", Expr);
3084                         goto Continue;
3085                      end if;
3086
3087                      --  Prepare pragma arguments
3088
3089                      Pargs := New_List;
3090                      Arg := First (Args);
3091                      while Present (Arg) loop
3092                         Append_To (Pargs,
3093                           Make_Pragma_Argument_Association (Sloc (Arg),
3094                             Expression => Relocate_Node (Arg)));
3095                         Next (Arg);
3096                      end loop;
3097
3098                      Append_To (Pargs,
3099                        Make_Pragma_Argument_Association (Sloc (Ent),
3100                          Chars      => Name_Entity,
3101                          Expression => Ent));
3102
3103                      Make_Aitem_Pragma
3104                        (Pragma_Argument_Associations => Pargs,
3105                         Pragma_Name                  => Name_Annotate);
3106                   end;
3107
3108                --  Case 3 : Aspects that don't correspond to pragma/attribute
3109                --  definition clause.
3110
3111                --  Case 3a: The aspects listed below don't correspond to
3112                --  pragmas/attributes but do require delayed analysis.
3113
3114                --  Default_Value can only apply to a scalar type
3115
3116                when Aspect_Default_Value =>
3117                   if not Is_Scalar_Type (E) then
3118                      Error_Msg_N
3119                        ("aspect Default_Value must apply to a scalar type", N);
3120                   end if;
3121
3122                   Aitem := Empty;
3123
3124                --  Default_Component_Value can only apply to an array type
3125                --  with scalar components.
3126
3127                when Aspect_Default_Component_Value =>
3128                   if not (Is_Array_Type (E)
3129                            and then Is_Scalar_Type (Component_Type (E)))
3130                   then
3131                      Error_Msg_N
3132                        ("aspect Default_Component_Value can only apply to an "
3133                         & "array of scalar components", N);
3134                   end if;
3135
3136                   Aitem := Empty;
3137
3138                --  Case 3b: The aspects listed below don't correspond to
3139                --  pragmas/attributes and don't need delayed analysis.
3140
3141                --  Implicit_Dereference
3142
3143                --  For Implicit_Dereference, External_Name and Link_Name, only
3144                --  the legality checks are done during the analysis, thus no
3145                --  delay is required.
3146
3147                when Aspect_Implicit_Dereference =>
3148                   Analyze_Aspect_Implicit_Dereference;
3149                   goto Continue;
3150
3151                --  Dimension
3152
3153                when Aspect_Dimension =>
3154                   Analyze_Aspect_Dimension (N, Id, Expr);
3155                   goto Continue;
3156
3157                --  Dimension_System
3158
3159                when Aspect_Dimension_System =>
3160                   Analyze_Aspect_Dimension_System (N, Id, Expr);
3161                   goto Continue;
3162
3163                --  Case 4: Aspects requiring special handling
3164
3165                --  Pre/Post/Test_Case/Contract_Cases whose corresponding
3166                --  pragmas take care of the delay.
3167
3168                --  Pre/Post
3169
3170                --  Aspects Pre/Post generate Precondition/Postcondition pragmas
3171                --  with a first argument that is the expression, and a second
3172                --  argument that is an informative message if the test fails.
3173                --  This is inserted right after the declaration, to get the
3174                --  required pragma placement. The processing for the pragmas
3175                --  takes care of the required delay.
3176
3177                when Pre_Post_Aspects => Pre_Post : declare
3178                   Pname : Name_Id;
3179
3180                begin
3181                   if A_Id = Aspect_Pre or else A_Id = Aspect_Precondition then
3182                      Pname := Name_Precondition;
3183                   else
3184                      Pname := Name_Postcondition;
3185                   end if;
3186
3187                   --  Check that the class-wide predicate cannot be applied to
3188                   --  an operation of a synchronized type that is not a tagged
3189                   --  type. Other legality checks are performed when analyzing
3190                   --  the contract of the operation.
3191
3192                   if Class_Present (Aspect)
3193                     and then Is_Concurrent_Type (Current_Scope)
3194                     and then not Is_Tagged_Type (Current_Scope)
3195                     and then Ekind_In (E, E_Entry, E_Function, E_Procedure)
3196                   then
3197                      Error_Msg_Name_1 := Original_Aspect_Pragma_Name (Aspect);
3198                      Error_Msg_N
3199                        ("aspect % can only be specified for a primitive "
3200                         & "operation of a tagged type", Aspect);
3201
3202                      goto Continue;
3203                   end if;
3204
3205                   --  If the expressions is of the form A and then B, then
3206                   --  we generate separate Pre/Post aspects for the separate
3207                   --  clauses. Since we allow multiple pragmas, there is no
3208                   --  problem in allowing multiple Pre/Post aspects internally.
3209                   --  These should be treated in reverse order (B first and
3210                   --  A second) since they are later inserted just after N in
3211                   --  the order they are treated. This way, the pragma for A
3212                   --  ends up preceding the pragma for B, which may have an
3213                   --  importance for the error raised (either constraint error
3214                   --  or precondition error).
3215
3216                   --  We do not do this for Pre'Class, since we have to put
3217                   --  these conditions together in a complex OR expression.
3218
3219                   --  We do not do this in ASIS mode, as ASIS relies on the
3220                   --  original node representing the complete expression, when
3221                   --  retrieving it through the source aspect table.
3222
3223                   if not ASIS_Mode
3224                     and then (Pname = Name_Postcondition
3225                                or else not Class_Present (Aspect))
3226                   then
3227                      while Nkind (Expr) = N_And_Then loop
3228                         Insert_After (Aspect,
3229                           Make_Aspect_Specification (Sloc (Left_Opnd (Expr)),
3230                             Identifier    => Identifier (Aspect),
3231                             Expression    => Relocate_Node (Left_Opnd (Expr)),
3232                             Class_Present => Class_Present (Aspect),
3233                             Split_PPC     => True));
3234                         Rewrite (Expr, Relocate_Node (Right_Opnd (Expr)));
3235                         Eloc := Sloc (Expr);
3236                      end loop;
3237                   end if;
3238
3239                   --  Build the precondition/postcondition pragma
3240
3241                   --  Add note about why we do NOT need Copy_Tree here???
3242
3243                   Make_Aitem_Pragma
3244                     (Pragma_Argument_Associations => New_List (
3245                        Make_Pragma_Argument_Association (Eloc,
3246                          Chars      => Name_Check,
3247                          Expression => Relocate_Node (Expr))),
3248                        Pragma_Name                => Pname);
3249
3250                   --  Add message unless exception messages are suppressed
3251
3252                   if not Opt.Exception_Locations_Suppressed then
3253                      Append_To (Pragma_Argument_Associations (Aitem),
3254                        Make_Pragma_Argument_Association (Eloc,
3255                          Chars      => Name_Message,
3256                          Expression =>
3257                            Make_String_Literal (Eloc,
3258                              Strval => "failed "
3259                                        & Get_Name_String (Pname)
3260                                        & " from "
3261                                        & Build_Location_String (Eloc))));
3262                   end if;
3263
3264                   Set_Is_Delayed_Aspect (Aspect);
3265
3266                   --  For Pre/Post cases, insert immediately after the entity
3267                   --  declaration, since that is the required pragma placement.
3268                   --  Note that for these aspects, we do not have to worry
3269                   --  about delay issues, since the pragmas themselves deal
3270                   --  with delay of visibility for the expression analysis.
3271
3272                   Insert_Pragma (Aitem);
3273
3274                   goto Continue;
3275                end Pre_Post;
3276
3277                --  Test_Case
3278
3279                when Aspect_Test_Case => Test_Case : declare
3280                   Args      : List_Id;
3281                   Comp_Expr : Node_Id;
3282                   Comp_Assn : Node_Id;
3283                   New_Expr  : Node_Id;
3284
3285                begin
3286                   Args := New_List;
3287
3288                   if Nkind (Parent (N)) = N_Compilation_Unit then
3289                      Error_Msg_Name_1 := Nam;
3290                      Error_Msg_N ("incorrect placement of aspect `%`", E);
3291                      goto Continue;
3292                   end if;
3293
3294                   if Nkind (Expr) /= N_Aggregate then
3295                      Error_Msg_Name_1 := Nam;
3296                      Error_Msg_NE
3297                        ("wrong syntax for aspect `%` for &", Id, E);
3298                      goto Continue;
3299                   end if;
3300
3301                   --  Make pragma expressions refer to the original aspect
3302                   --  expressions through the Original_Node link. This is used
3303                   --  in semantic analysis for ASIS mode, so that the original
3304                   --  expression also gets analyzed.
3305
3306                   Comp_Expr := First (Expressions (Expr));
3307                   while Present (Comp_Expr) loop
3308                      New_Expr := Relocate_Node (Comp_Expr);
3309                      Append_To (Args,
3310                        Make_Pragma_Argument_Association (Sloc (Comp_Expr),
3311                          Expression => New_Expr));
3312                      Next (Comp_Expr);
3313                   end loop;
3314
3315                   Comp_Assn := First (Component_Associations (Expr));
3316                   while Present (Comp_Assn) loop
3317                      if List_Length (Choices (Comp_Assn)) /= 1
3318                        or else
3319                          Nkind (First (Choices (Comp_Assn))) /= N_Identifier
3320                      then
3321                         Error_Msg_Name_1 := Nam;
3322                         Error_Msg_NE
3323                           ("wrong syntax for aspect `%` for &", Id, E);
3324                         goto Continue;
3325                      end if;
3326
3327                      Append_To (Args,
3328                        Make_Pragma_Argument_Association (Sloc (Comp_Assn),
3329                          Chars      => Chars (First (Choices (Comp_Assn))),
3330                          Expression =>
3331                            Relocate_Node (Expression (Comp_Assn))));
3332                      Next (Comp_Assn);
3333                   end loop;
3334
3335                   --  Build the test-case pragma
3336
3337                   Make_Aitem_Pragma
3338                     (Pragma_Argument_Associations => Args,
3339                      Pragma_Name                  => Nam);
3340                end Test_Case;
3341
3342                --  Contract_Cases
3343
3344                when Aspect_Contract_Cases =>
3345                   Make_Aitem_Pragma
3346                     (Pragma_Argument_Associations => New_List (
3347                        Make_Pragma_Argument_Association (Loc,
3348                          Expression => Relocate_Node (Expr))),
3349                      Pragma_Name                  => Nam);
3350
3351                   Decorate (Aspect, Aitem);
3352                   Insert_Pragma (Aitem);
3353                   goto Continue;
3354
3355                --  Case 5: Special handling for aspects with an optional
3356                --  boolean argument.
3357
3358                --  In the delayed case, the corresponding pragma cannot be
3359                --  generated yet because the evaluation of the boolean needs
3360                --  to be delayed till the freeze point.
3361
3362                when Boolean_Aspects      |
3363                     Library_Unit_Aspects =>
3364
3365                   Set_Is_Boolean_Aspect (Aspect);
3366
3367                   --  Lock_Free aspect only apply to protected objects
3368
3369                   if A_Id = Aspect_Lock_Free then
3370                      if Ekind (E) /= E_Protected_Type then
3371                         Error_Msg_Name_1 := Nam;
3372                         Error_Msg_N
3373                           ("aspect % only applies to a protected object",
3374                            Aspect);
3375
3376                      else
3377                         --  Set the Uses_Lock_Free flag to True if there is no
3378                         --  expression or if the expression is True. The
3379                         --  evaluation of this aspect should be delayed to the
3380                         --  freeze point (why???)
3381
3382                         if No (Expr)
3383                           or else Is_True (Static_Boolean (Expr))
3384                         then
3385                            Set_Uses_Lock_Free (E);
3386                         end if;
3387
3388                         Record_Rep_Item (E, Aspect);
3389                      end if;
3390
3391                      goto Continue;
3392
3393                   elsif A_Id = Aspect_Export or else A_Id = Aspect_Import then
3394                      Analyze_Aspect_Export_Import;
3395
3396                   --  Disable_Controlled
3397
3398                   elsif A_Id = Aspect_Disable_Controlled then
3399                      if Ekind (E) /= E_Record_Type
3400                        or else not Is_Controlled (E)
3401                      then
3402                         Error_Msg_N
3403                           ("aspect % requires controlled record type", Aspect);
3404                         goto Continue;
3405                      end if;
3406
3407                      --  If we're in a generic template, we don't want to try
3408                      --  to disable controlled types, because typical usage is
3409                      --  "Disable_Controlled => not <some_check>'Enabled", and
3410                      --  the value of Enabled is not known until we see a
3411                      --  particular instance. In such a context, we just need
3412                      --  to preanalyze the expression for legality.
3413
3414                      if Expander_Active then
3415                         Analyze_And_Resolve (Expr, Standard_Boolean);
3416
3417                         if not Present (Expr)
3418                           or else Is_True (Static_Boolean (Expr))
3419                         then
3420                            Set_Disable_Controlled (E);
3421                         end if;
3422
3423                      elsif Serious_Errors_Detected = 0 then
3424                         Preanalyze_And_Resolve (Expr, Standard_Boolean);
3425                      end if;
3426
3427                      goto Continue;
3428                   end if;
3429
3430                   --  Library unit aspects require special handling in the case
3431                   --  of a package declaration, the pragma needs to be inserted
3432                   --  in the list of declarations for the associated package.
3433                   --  There is no issue of visibility delay for these aspects.
3434
3435                   if A_Id in Library_Unit_Aspects
3436                     and then
3437                       Nkind_In (N, N_Package_Declaration,
3438                                    N_Generic_Package_Declaration)
3439                     and then Nkind (Parent (N)) /= N_Compilation_Unit
3440
3441                     --  Aspect is legal on a local instantiation of a library-
3442                     --  level generic unit.
3443
3444                     and then not Is_Generic_Instance (Defining_Entity (N))
3445                   then
3446                      Error_Msg_N
3447                        ("incorrect context for library unit aspect&", Id);
3448                      goto Continue;
3449                   end if;
3450
3451                   --  Cases where we do not delay, includes all cases where the
3452                   --  expression is missing other than the above cases.
3453
3454                   if not Delay_Required or else No (Expr) then
3455
3456                      --  Exclude aspects Export and Import because their pragma
3457                      --  syntax does not map directly to a Boolean aspect.
3458
3459                      if A_Id /= Aspect_Export
3460                        and then A_Id /= Aspect_Import
3461                      then
3462                         Make_Aitem_Pragma
3463                           (Pragma_Argument_Associations => New_List (
3464                              Make_Pragma_Argument_Association (Sloc (Ent),
3465                                Expression => Ent)),
3466                            Pragma_Name                  => Chars (Id));
3467                      end if;
3468
3469                      Delay_Required := False;
3470
3471                   --  In general cases, the corresponding pragma/attribute
3472                   --  definition clause will be inserted later at the freezing
3473                   --  point, and we do not need to build it now.
3474
3475                   else
3476                      Aitem := Empty;
3477                   end if;
3478
3479                --  Storage_Size
3480
3481                --  This is special because for access types we need to generate
3482                --  an attribute definition clause. This also works for single
3483                --  task declarations, but it does not work for task type
3484                --  declarations, because we have the case where the expression
3485                --  references a discriminant of the task type. That can't use
3486                --  an attribute definition clause because we would not have
3487                --  visibility on the discriminant. For that case we must
3488                --  generate a pragma in the task definition.
3489
3490                when Aspect_Storage_Size =>
3491
3492                   --  Task type case
3493
3494                   if Ekind (E) = E_Task_Type then
3495                      declare
3496                         Decl : constant Node_Id := Declaration_Node (E);
3497
3498                      begin
3499                         pragma Assert (Nkind (Decl) = N_Task_Type_Declaration);
3500
3501                         --  If no task definition, create one
3502
3503                         if No (Task_Definition (Decl)) then
3504                            Set_Task_Definition (Decl,
3505                              Make_Task_Definition (Loc,
3506                                Visible_Declarations => Empty_List,
3507                                End_Label            => Empty));
3508                         end if;
3509
3510                         --  Create a pragma and put it at the start of the task
3511                         --  definition for the task type declaration.
3512
3513                         Make_Aitem_Pragma
3514                           (Pragma_Argument_Associations => New_List (
3515                              Make_Pragma_Argument_Association (Loc,
3516                                Expression => Relocate_Node (Expr))),
3517                            Pragma_Name                  => Name_Storage_Size);
3518
3519                         Prepend
3520                           (Aitem,
3521                            Visible_Declarations (Task_Definition (Decl)));
3522                         goto Continue;
3523                      end;
3524
3525                   --  All other cases, generate attribute definition
3526
3527                   else
3528                      Aitem :=
3529                        Make_Attribute_Definition_Clause (Loc,
3530                          Name       => Ent,
3531                          Chars      => Chars (Id),
3532                          Expression => Relocate_Node (Expr));
3533                   end if;
3534             end case;
3535
3536             --  Attach the corresponding pragma/attribute definition clause to
3537             --  the aspect specification node.
3538
3539             if Present (Aitem) then
3540                Set_From_Aspect_Specification (Aitem);
3541             end if;
3542
3543             --  In the context of a compilation unit, we directly put the
3544             --  pragma in the Pragmas_After list of the N_Compilation_Unit_Aux
3545             --  node (no delay is required here) except for aspects on a
3546             --  subprogram body (see below) and a generic package, for which we
3547             --  need to introduce the pragma before building the generic copy
3548             --  (see sem_ch12), and for package instantiations, where the
3549             --  library unit pragmas are better handled early.
3550
3551             if Nkind (Parent (N)) = N_Compilation_Unit
3552               and then (Present (Aitem) or else Is_Boolean_Aspect (Aspect))
3553             then
3554                declare
3555                   Aux : constant Node_Id := Aux_Decls_Node (Parent (N));
3556
3557                begin
3558                   pragma Assert (Nkind (Aux) = N_Compilation_Unit_Aux);
3559
3560                   --  For a Boolean aspect, create the corresponding pragma if
3561                   --  no expression or if the value is True.
3562
3563                   if Is_Boolean_Aspect (Aspect) and then No (Aitem) then
3564                      if Is_True (Static_Boolean (Expr)) then
3565                         Make_Aitem_Pragma
3566                           (Pragma_Argument_Associations => New_List (
3567                              Make_Pragma_Argument_Association (Sloc (Ent),
3568                                Expression => Ent)),
3569                            Pragma_Name                  => Chars (Id));
3570
3571                         Set_From_Aspect_Specification (Aitem, True);
3572                         Set_Corresponding_Aspect (Aitem, Aspect);
3573
3574                      else
3575                         goto Continue;
3576                      end if;
3577                   end if;
3578
3579                   --  If the aspect is on a subprogram body (relevant aspect
3580                   --  is Inline), add the pragma in front of the declarations.
3581
3582                   if Nkind (N) = N_Subprogram_Body then
3583                      if No (Declarations (N)) then
3584                         Set_Declarations (N, New_List);
3585                      end if;
3586
3587                      Prepend (Aitem, Declarations (N));
3588
3589                   elsif Nkind (N) = N_Generic_Package_Declaration then
3590                      if No (Visible_Declarations (Specification (N))) then
3591                         Set_Visible_Declarations (Specification (N), New_List);
3592                      end if;
3593
3594                      Prepend (Aitem,
3595                        Visible_Declarations (Specification (N)));
3596
3597                   elsif Nkind (N) = N_Package_Instantiation then
3598                      declare
3599                         Spec : constant Node_Id :=
3600                                  Specification (Instance_Spec (N));
3601                      begin
3602                         if No (Visible_Declarations (Spec)) then
3603                            Set_Visible_Declarations (Spec, New_List);
3604                         end if;
3605
3606                         Prepend (Aitem, Visible_Declarations (Spec));
3607                      end;
3608
3609                   else
3610                      if No (Pragmas_After (Aux)) then
3611                         Set_Pragmas_After (Aux, New_List);
3612                      end if;
3613
3614                      Append (Aitem, Pragmas_After (Aux));
3615                   end if;
3616
3617                   goto Continue;
3618                end;
3619             end if;
3620
3621             --  The evaluation of the aspect is delayed to the freezing point.
3622             --  The pragma or attribute clause if there is one is then attached
3623             --  to the aspect specification which is put in the rep item list.
3624
3625             if Delay_Required then
3626                if Present (Aitem) then
3627                   Set_Is_Delayed_Aspect (Aitem);
3628                   Set_Aspect_Rep_Item (Aspect, Aitem);
3629                   Set_Parent (Aitem, Aspect);
3630                end if;
3631
3632                Set_Is_Delayed_Aspect (Aspect);
3633
3634                --  In the case of Default_Value, link the aspect to base type
3635                --  as well, even though it appears on a first subtype. This is
3636                --  mandated by the semantics of the aspect. Do not establish
3637                --  the link when processing the base type itself as this leads
3638                --  to a rep item circularity. Verify that we are dealing with
3639                --  a scalar type to prevent cascaded errors.
3640
3641                if A_Id = Aspect_Default_Value
3642                  and then Is_Scalar_Type (E)
3643                  and then Base_Type (E) /= E
3644                then
3645                   Set_Has_Delayed_Aspects (Base_Type (E));
3646                   Record_Rep_Item (Base_Type (E), Aspect);
3647                end if;
3648
3649                Set_Has_Delayed_Aspects (E);
3650                Record_Rep_Item (E, Aspect);
3651
3652             --  When delay is not required and the context is a package or a
3653             --  subprogram body, insert the pragma in the body declarations.
3654
3655             elsif Nkind_In (N, N_Package_Body, N_Subprogram_Body) then
3656                if No (Declarations (N)) then
3657                   Set_Declarations (N, New_List);
3658                end if;
3659
3660                --  The pragma is added before source declarations
3661
3662                Prepend_To (Declarations (N), Aitem);
3663
3664             --  When delay is not required and the context is not a compilation
3665             --  unit, we simply insert the pragma/attribute definition clause
3666             --  in sequence.
3667
3668             elsif Present (Aitem) then
3669                Insert_After (Ins_Node, Aitem);
3670                Ins_Node := Aitem;
3671             end if;
3672          end Analyze_One_Aspect;
3673
3674       <<Continue>>
3675          Next (Aspect);
3676       end loop Aspect_Loop;
3677
3678       if Has_Delayed_Aspects (E) then
3679          Ensure_Freeze_Node (E);
3680       end if;
3681    end Analyze_Aspect_Specifications;
3682
3683    ---------------------------------------------------
3684    -- Analyze_Aspect_Specifications_On_Body_Or_Stub --
3685    ---------------------------------------------------
3686
3687    procedure Analyze_Aspect_Specifications_On_Body_Or_Stub (N : Node_Id) is
3688       Body_Id : constant Entity_Id := Defining_Entity (N);
3689
3690       procedure Diagnose_Misplaced_Aspects (Spec_Id : Entity_Id);
3691       --  Body [stub] N has aspects, but they are not properly placed. Emit an
3692       --  error message depending on the aspects involved. Spec_Id denotes the
3693       --  entity of the corresponding spec.
3694
3695       --------------------------------
3696       -- Diagnose_Misplaced_Aspects --
3697       --------------------------------
3698
3699       procedure Diagnose_Misplaced_Aspects (Spec_Id : Entity_Id) is
3700          procedure Misplaced_Aspect_Error
3701            (Asp     : Node_Id;
3702             Ref_Nam : Name_Id);
3703          --  Emit an error message concerning misplaced aspect Asp. Ref_Nam is
3704          --  the name of the refined version of the aspect.
3705
3706          ----------------------------
3707          -- Misplaced_Aspect_Error --
3708          ----------------------------
3709
3710          procedure Misplaced_Aspect_Error
3711            (Asp     : Node_Id;
3712             Ref_Nam : Name_Id)
3713          is
3714             Asp_Nam : constant Name_Id   := Chars (Identifier (Asp));
3715             Asp_Id  : constant Aspect_Id := Get_Aspect_Id (Asp_Nam);
3716
3717          begin
3718             --  The corresponding spec already contains the aspect in question
3719             --  and the one appearing on the body must be the refined form:
3720
3721             --    procedure P with Global ...;
3722             --    procedure P with Global ... is ... end P;
3723             --                     ^
3724             --                     Refined_Global
3725
3726             if Has_Aspect (Spec_Id, Asp_Id) then
3727                Error_Msg_Name_1 := Asp_Nam;
3728
3729                --  Subunits cannot carry aspects that apply to a subprogram
3730                --  declaration.
3731
3732                if Nkind (Parent (N)) = N_Subunit then
3733                   Error_Msg_N ("aspect % cannot apply to a subunit", Asp);
3734
3735                --  Otherwise suggest the refined form
3736
3737                else
3738                   Error_Msg_Name_2 := Ref_Nam;
3739                   Error_Msg_N ("aspect % should be %", Asp);
3740                end if;
3741
3742             --  Otherwise the aspect must appear on the spec, not on the body
3743
3744             --    procedure P;
3745             --    procedure P with Global ... is ... end P;
3746
3747             else
3748                Error_Msg_N
3749                  ("aspect specification must appear on initial declaration",
3750                   Asp);
3751             end if;
3752          end Misplaced_Aspect_Error;
3753
3754          --  Local variables
3755
3756          Asp     : Node_Id;
3757          Asp_Nam : Name_Id;
3758
3759       --  Start of processing for Diagnose_Misplaced_Aspects
3760
3761       begin
3762          --  Iterate over the aspect specifications and emit specific errors
3763          --  where applicable.
3764
3765          Asp := First (Aspect_Specifications (N));
3766          while Present (Asp) loop
3767             Asp_Nam := Chars (Identifier (Asp));
3768
3769             --  Do not emit errors on aspects that can appear on a subprogram
3770             --  body. This scenario occurs when the aspect specification list
3771             --  contains both misplaced and properly placed aspects.
3772
3773             if Aspect_On_Body_Or_Stub_OK (Get_Aspect_Id (Asp_Nam)) then
3774                null;
3775
3776             --  Special diagnostics for SPARK aspects
3777
3778             elsif Asp_Nam = Name_Depends then
3779                Misplaced_Aspect_Error (Asp, Name_Refined_Depends);
3780
3781             elsif Asp_Nam = Name_Global then
3782                Misplaced_Aspect_Error (Asp, Name_Refined_Global);
3783
3784             elsif Asp_Nam = Name_Post then
3785                Misplaced_Aspect_Error (Asp, Name_Refined_Post);
3786
3787             --  Otherwise a language-defined aspect is misplaced
3788
3789             else
3790                Error_Msg_N
3791                  ("aspect specification must appear on initial declaration",
3792                   Asp);
3793             end if;
3794
3795             Next (Asp);
3796          end loop;
3797       end Diagnose_Misplaced_Aspects;
3798
3799       --  Local variables
3800
3801       Spec_Id : constant Entity_Id := Unique_Defining_Entity (N);
3802
3803    --  Start of processing for Analyze_Aspects_On_Body_Or_Stub
3804
3805    begin
3806       --  Language-defined aspects cannot be associated with a subprogram body
3807       --  [stub] if the subprogram has a spec. Certain implementation defined
3808       --  aspects are allowed to break this rule (for all applicable cases, see
3809       --  table Aspects.Aspect_On_Body_Or_Stub_OK).
3810
3811       if Spec_Id /= Body_Id and then not Aspects_On_Body_Or_Stub_OK (N) then
3812          Diagnose_Misplaced_Aspects (Spec_Id);
3813       else
3814          Analyze_Aspect_Specifications (N, Body_Id);
3815       end if;
3816    end Analyze_Aspect_Specifications_On_Body_Or_Stub;
3817
3818    -----------------------
3819    -- Analyze_At_Clause --
3820    -----------------------
3821
3822    --  An at clause is replaced by the corresponding Address attribute
3823    --  definition clause that is the preferred approach in Ada 95.
3824
3825    procedure Analyze_At_Clause (N : Node_Id) is
3826       CS : constant Boolean := Comes_From_Source (N);
3827
3828    begin
3829       --  This is an obsolescent feature
3830
3831       Check_Restriction (No_Obsolescent_Features, N);
3832
3833       if Warn_On_Obsolescent_Feature then
3834          Error_Msg_N
3835            ("?j?at clause is an obsolescent feature (RM J.7(2))", N);
3836          Error_Msg_N
3837            ("\?j?use address attribute definition clause instead", N);
3838       end if;
3839
3840       --  Rewrite as address clause
3841
3842       Rewrite (N,
3843         Make_Attribute_Definition_Clause (Sloc (N),
3844           Name       => Identifier (N),
3845           Chars      => Name_Address,
3846           Expression => Expression (N)));
3847
3848       --  We preserve Comes_From_Source, since logically the clause still comes
3849       --  from the source program even though it is changed in form.
3850
3851       Set_Comes_From_Source (N, CS);
3852
3853       --  Analyze rewritten clause
3854
3855       Analyze_Attribute_Definition_Clause (N);
3856    end Analyze_At_Clause;
3857
3858    -----------------------------------------
3859    -- Analyze_Attribute_Definition_Clause --
3860    -----------------------------------------
3861
3862    procedure Analyze_Attribute_Definition_Clause (N : Node_Id) is
3863       Loc   : constant Source_Ptr   := Sloc (N);
3864       Nam   : constant Node_Id      := Name (N);
3865       Attr  : constant Name_Id      := Chars (N);
3866       Expr  : constant Node_Id      := Expression (N);
3867       Id    : constant Attribute_Id := Get_Attribute_Id (Attr);
3868
3869       Ent : Entity_Id;
3870       --  The entity of Nam after it is analyzed. In the case of an incomplete
3871       --  type, this is the underlying type.
3872
3873       U_Ent : Entity_Id;
3874       --  The underlying entity to which the attribute applies. Generally this
3875       --  is the Underlying_Type of Ent, except in the case where the clause
3876       --  applies to the full view of an incomplete or private type, in which
3877       --  case U_Ent is just a copy of Ent.
3878
3879       FOnly : Boolean := False;
3880       --  Reset to True for subtype specific attribute (Alignment, Size)
3881       --  and for stream attributes, i.e. those cases where in the call to
3882       --  Rep_Item_Too_Late, FOnly is set True so that only the freezing rules
3883       --  are checked. Note that the case of stream attributes is not clear
3884       --  from the RM, but see AI95-00137. Also, the RM seems to disallow
3885       --  Storage_Size for derived task types, but that is also clearly
3886       --  unintentional.
3887
3888       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type);
3889       --  Common processing for 'Read, 'Write, 'Input and 'Output attribute
3890       --  definition clauses.
3891
3892       function Duplicate_Clause return Boolean;
3893       --  This routine checks if the aspect for U_Ent being given by attribute
3894       --  definition clause N is for an aspect that has already been specified,
3895       --  and if so gives an error message. If there is a duplicate, True is
3896       --  returned, otherwise if there is no error, False is returned.
3897
3898       procedure Check_Indexing_Functions;
3899       --  Check that the function in Constant_Indexing or Variable_Indexing
3900       --  attribute has the proper type structure. If the name is overloaded,
3901       --  check that some interpretation is legal.
3902
3903       procedure Check_Iterator_Functions;
3904       --  Check that there is a single function in Default_Iterator attribute
3905       --  has the proper type structure.
3906
3907       function Check_Primitive_Function (Subp : Entity_Id) return Boolean;
3908       --  Common legality check for the previous two
3909
3910       -----------------------------------
3911       -- Analyze_Stream_TSS_Definition --
3912       -----------------------------------
3913
3914       procedure Analyze_Stream_TSS_Definition (TSS_Nam : TSS_Name_Type) is
3915          Subp : Entity_Id := Empty;
3916          I    : Interp_Index;
3917          It   : Interp;
3918          Pnam : Entity_Id;
3919
3920          Is_Read : constant Boolean := (TSS_Nam = TSS_Stream_Read);
3921          --  True for Read attribute, False for other attributes
3922
3923          function Has_Good_Profile
3924            (Subp   : Entity_Id;
3925             Report : Boolean := False) return Boolean;
3926          --  Return true if the entity is a subprogram with an appropriate
3927          --  profile for the attribute being defined. If result is False and
3928          --  Report is True, function emits appropriate error.
3929
3930          ----------------------
3931          -- Has_Good_Profile --
3932          ----------------------
3933
3934          function Has_Good_Profile
3935            (Subp   : Entity_Id;
3936             Report : Boolean := False) return Boolean
3937          is
3938             Expected_Ekind : constant array (Boolean) of Entity_Kind :=
3939                                (False => E_Procedure, True => E_Function);
3940             Is_Function    : constant Boolean := (TSS_Nam = TSS_Stream_Input);
3941             F              : Entity_Id;
3942             Typ            : Entity_Id;
3943
3944          begin
3945             if Ekind (Subp) /= Expected_Ekind (Is_Function) then
3946                return False;
3947             end if;
3948
3949             F := First_Formal (Subp);
3950
3951             if No (F)
3952               or else Ekind (Etype (F)) /= E_Anonymous_Access_Type
3953               or else Designated_Type (Etype (F)) /=
3954                         Class_Wide_Type (RTE (RE_Root_Stream_Type))
3955             then
3956                return False;
3957             end if;
3958
3959             if not Is_Function then
3960                Next_Formal (F);
3961
3962                declare
3963                   Expected_Mode : constant array (Boolean) of Entity_Kind :=
3964                                     (False => E_In_Parameter,
3965                                      True  => E_Out_Parameter);
3966                begin
3967                   if Parameter_Mode (F) /= Expected_Mode (Is_Read) then
3968                      return False;
3969                   end if;
3970                end;
3971
3972                Typ := Etype (F);
3973
3974                --  If the attribute specification comes from an aspect
3975                --  specification for a class-wide stream, the parameter must be
3976                --  a class-wide type of the entity to which the aspect applies.
3977
3978                if From_Aspect_Specification (N)
3979                  and then Class_Present (Parent (N))
3980                  and then Is_Class_Wide_Type (Typ)
3981                then
3982                   Typ := Etype (Typ);
3983                end if;
3984
3985             else
3986                Typ := Etype (Subp);
3987             end if;
3988
3989             --  Verify that the prefix of the attribute and the local name for
3990             --  the type of the formal match, or one is the class-wide of the
3991             --  other, in the case of a class-wide stream operation.
3992
3993             if Base_Type (Typ) = Base_Type (Ent)
3994               or else (Is_Class_Wide_Type (Typ)
3995                         and then Typ = Class_Wide_Type (Base_Type (Ent)))
3996               or else (Is_Class_Wide_Type (Ent)
3997                         and then Ent = Class_Wide_Type (Base_Type (Typ)))
3998             then
3999                null;
4000             else
4001                return False;
4002             end if;
4003
4004             if Present (Next_Formal (F)) then
4005                return False;
4006
4007             elsif not Is_Scalar_Type (Typ)
4008               and then not Is_First_Subtype (Typ)
4009               and then not Is_Class_Wide_Type (Typ)
4010             then
4011                if Report and not Is_First_Subtype (Typ) then
4012                   Error_Msg_N
4013                     ("subtype of formal in stream operation must be a first "
4014                      & "subtype", Parameter_Type (Parent (F)));
4015                end if;
4016
4017                return False;
4018
4019             else
4020                return True;
4021             end if;
4022          end Has_Good_Profile;
4023
4024       --  Start of processing for Analyze_Stream_TSS_Definition
4025
4026       begin
4027          FOnly := True;
4028
4029          if not Is_Type (U_Ent) then
4030             Error_Msg_N ("local name must be a subtype", Nam);
4031             return;
4032
4033          elsif not Is_First_Subtype (U_Ent) then
4034             Error_Msg_N ("local name must be a first subtype", Nam);
4035             return;
4036          end if;
4037
4038          Pnam := TSS (Base_Type (U_Ent), TSS_Nam);
4039
4040          --  If Pnam is present, it can be either inherited from an ancestor
4041          --  type (in which case it is legal to redefine it for this type), or
4042          --  be a previous definition of the attribute for the same type (in
4043          --  which case it is illegal).
4044
4045          --  In the first case, it will have been analyzed already, and we
4046          --  can check that its profile does not match the expected profile
4047          --  for a stream attribute of U_Ent. In the second case, either Pnam
4048          --  has been analyzed (and has the expected profile), or it has not
4049          --  been analyzed yet (case of a type that has not been frozen yet
4050          --  and for which the stream attribute has been set using Set_TSS).
4051
4052          if Present (Pnam)
4053            and then (No (First_Entity (Pnam)) or else Has_Good_Profile (Pnam))
4054          then
4055             Error_Msg_Sloc := Sloc (Pnam);
4056             Error_Msg_Name_1 := Attr;
4057             Error_Msg_N ("% attribute already defined #", Nam);
4058             return;
4059          end if;
4060
4061          Analyze (Expr);
4062
4063          if Is_Entity_Name (Expr) then
4064             if not Is_Overloaded (Expr) then
4065                if Has_Good_Profile (Entity (Expr), Report => True) then
4066                   Subp := Entity (Expr);
4067                end if;
4068
4069             else
4070                Get_First_Interp (Expr, I, It);
4071                while Present (It.Nam) loop
4072                   if Has_Good_Profile (It.Nam) then
4073                      Subp := It.Nam;
4074                      exit;
4075                   end if;
4076
4077                   Get_Next_Interp (I, It);
4078                end loop;
4079             end if;
4080          end if;
4081
4082          if Present (Subp) then
4083             if Is_Abstract_Subprogram (Subp) then
4084                Error_Msg_N ("stream subprogram must not be abstract", Expr);
4085                return;
4086
4087             --  A stream subprogram for an interface type must be a null
4088             --  procedure (RM 13.13.2 (38/3)). Note that the class-wide type
4089             --  of an interface is not an interface type (3.9.4 (6.b/2)).
4090
4091             elsif Is_Interface (U_Ent)
4092               and then not Is_Class_Wide_Type (U_Ent)
4093               and then not Inside_A_Generic
4094               and then
4095                 (Ekind (Subp) = E_Function
4096                   or else
4097                     not Null_Present
4098                           (Specification
4099                              (Unit_Declaration_Node (Ultimate_Alias (Subp)))))
4100             then
4101                Error_Msg_N
4102                  ("stream subprogram for interface type must be null "
4103                   & "procedure", Expr);
4104             end if;
4105
4106             Set_Entity (Expr, Subp);
4107             Set_Etype (Expr, Etype (Subp));
4108
4109             New_Stream_Subprogram (N, U_Ent, Subp, TSS_Nam);
4110
4111          else
4112             Error_Msg_Name_1 := Attr;
4113             Error_Msg_N ("incorrect expression for% attribute", Expr);
4114          end if;
4115       end Analyze_Stream_TSS_Definition;
4116
4117       ------------------------------
4118       -- Check_Indexing_Functions --
4119       ------------------------------
4120
4121       procedure Check_Indexing_Functions is
4122          Indexing_Found : Boolean := False;
4123
4124          procedure Check_Inherited_Indexing;
4125          --  For a derived type, check that no indexing aspect is specified
4126          --  for the type if it is also inherited
4127
4128          procedure Check_One_Function (Subp : Entity_Id);
4129          --  Check one possible interpretation. Sets Indexing_Found True if a
4130          --  legal indexing function is found.
4131
4132          procedure Illegal_Indexing (Msg : String);
4133          --  Diagnose illegal indexing function if not overloaded. In the
4134          --  overloaded case indicate that no legal interpretation  exists.
4135
4136          ------------------------------
4137          -- Check_Inherited_Indexing --
4138          ------------------------------
4139
4140          procedure Check_Inherited_Indexing is
4141             Inherited : Node_Id;
4142
4143          begin
4144             if Attr = Name_Constant_Indexing then
4145                Inherited :=
4146                  Find_Aspect (Etype (Ent), Aspect_Constant_Indexing);
4147             else pragma Assert (Attr = Name_Variable_Indexing);
4148                Inherited :=
4149                   Find_Aspect (Etype (Ent), Aspect_Variable_Indexing);
4150             end if;
4151
4152             if Present (Inherited) then
4153                if Debug_Flag_Dot_XX then
4154                   null;
4155
4156                --  OK if current attribute_definition_clause is expansion of
4157                --  inherited aspect.
4158
4159                elsif Aspect_Rep_Item (Inherited) = N then
4160                   null;
4161
4162                --  Indicate the operation that must be overridden, rather than
4163                --  redefining the indexing aspect.
4164
4165                else
4166                   Illegal_Indexing
4167                     ("indexing function already inherited from parent type");
4168                   Error_Msg_NE
4169                     ("!override & instead",
4170                      N, Entity (Expression (Inherited)));
4171                end if;
4172             end if;
4173          end Check_Inherited_Indexing;
4174
4175          ------------------------
4176          -- Check_One_Function --
4177          ------------------------
4178
4179          procedure Check_One_Function (Subp : Entity_Id) is
4180             Default_Element : Node_Id;
4181             Ret_Type        : constant Entity_Id := Etype (Subp);
4182
4183          begin
4184             if not Is_Overloadable (Subp) then
4185                Illegal_Indexing ("illegal indexing function for type&");
4186                return;
4187
4188             elsif Scope (Subp) /= Scope (Ent) then
4189                if Nkind (Expr) = N_Expanded_Name then
4190
4191                   --  Indexing function can't be declared elsewhere
4192
4193                   Illegal_Indexing
4194                     ("indexing function must be declared in scope of type&");
4195                end if;
4196
4197                return;
4198
4199             elsif No (First_Formal (Subp)) then
4200                Illegal_Indexing
4201                  ("Indexing requires a function that applies to type&");
4202                return;
4203
4204             elsif No (Next_Formal (First_Formal (Subp))) then
4205                Illegal_Indexing
4206                  ("indexing function must have at least two parameters");
4207                return;
4208
4209             elsif Is_Derived_Type (Ent) then
4210                Check_Inherited_Indexing;
4211             end if;
4212
4213             if not Check_Primitive_Function (Subp) then
4214                Illegal_Indexing
4215                  ("Indexing aspect requires a function that applies to type&");
4216                return;
4217             end if;
4218
4219             --  If partial declaration exists, verify that it is not tagged.
4220
4221             if Ekind (Current_Scope) = E_Package
4222               and then Has_Private_Declaration (Ent)
4223               and then From_Aspect_Specification (N)
4224               and then
4225                 List_Containing (Parent (Ent)) =
4226                   Private_Declarations
4227                     (Specification (Unit_Declaration_Node (Current_Scope)))
4228               and then Nkind (N) = N_Attribute_Definition_Clause
4229             then
4230                declare
4231                   Decl : Node_Id;
4232
4233                begin
4234                   Decl :=
4235                      First (Visible_Declarations
4236                               (Specification
4237                                  (Unit_Declaration_Node (Current_Scope))));
4238
4239                   while Present (Decl) loop
4240                      if Nkind (Decl) = N_Private_Type_Declaration
4241                        and then Ent = Full_View (Defining_Identifier (Decl))
4242                        and then Tagged_Present (Decl)
4243                        and then No (Aspect_Specifications (Decl))
4244                      then
4245                         Illegal_Indexing
4246                           ("Indexing aspect cannot be specified on full view "
4247                            & "if partial view is tagged");
4248                         return;
4249                      end if;
4250
4251                      Next (Decl);
4252                   end loop;
4253                end;
4254             end if;
4255
4256             --  An indexing function must return either the default element of
4257             --  the container, or a reference type. For variable indexing it
4258             --  must be the latter.
4259
4260             Default_Element :=
4261               Find_Value_Of_Aspect
4262                (Etype (First_Formal (Subp)), Aspect_Iterator_Element);
4263
4264             if Present (Default_Element) then
4265                Analyze (Default_Element);
4266
4267                if Is_Entity_Name (Default_Element)
4268                  and then not Covers (Entity (Default_Element), Ret_Type)
4269                  and then False
4270                then
4271                   Illegal_Indexing
4272                     ("wrong return type for indexing function");
4273                   return;
4274                end if;
4275             end if;
4276
4277             --  For variable_indexing the return type must be a reference type
4278
4279             if Attr = Name_Variable_Indexing then
4280                if not Has_Implicit_Dereference (Ret_Type) then
4281                   Illegal_Indexing
4282                      ("variable indexing must return a reference type");
4283                   return;
4284
4285                elsif Is_Access_Constant
4286                        (Etype (First_Discriminant (Ret_Type)))
4287                then
4288                   Illegal_Indexing
4289                     ("variable indexing must return an access to variable");
4290                   return;
4291                end if;
4292
4293             else
4294                if  Has_Implicit_Dereference (Ret_Type)
4295                  and then not
4296                    Is_Access_Constant (Etype (First_Discriminant (Ret_Type)))
4297                then
4298                   Illegal_Indexing
4299                     ("constant indexing must return an access to constant");
4300                   return;
4301
4302                elsif Is_Access_Type (Etype (First_Formal (Subp)))
4303                  and then not Is_Access_Constant (Etype (First_Formal (Subp)))
4304                then
4305                   Illegal_Indexing
4306                     ("constant indexing must apply to an access to constant");
4307                   return;
4308                end if;
4309             end if;
4310
4311             --  All checks succeeded.
4312
4313             Indexing_Found := True;
4314          end Check_One_Function;
4315
4316          -----------------------
4317          --  Illegal_Indexing --
4318          -----------------------
4319
4320          procedure Illegal_Indexing (Msg : String) is
4321          begin
4322             Error_Msg_NE (Msg, N, Ent);
4323          end Illegal_Indexing;
4324
4325       --  Start of processing for Check_Indexing_Functions
4326
4327       begin
4328          if In_Instance then
4329             Check_Inherited_Indexing;
4330          end if;
4331
4332          Analyze (Expr);
4333
4334          if not Is_Overloaded (Expr) then
4335             Check_One_Function (Entity (Expr));
4336
4337          else
4338             declare
4339                I  : Interp_Index;
4340                It : Interp;
4341
4342             begin
4343                Indexing_Found := False;
4344                Get_First_Interp (Expr, I, It);
4345                while Present (It.Nam) loop
4346
4347                   --  Note that analysis will have added the interpretation
4348                   --  that corresponds to the dereference. We only check the
4349                   --  subprogram itself.
4350
4351                   if Is_Overloadable (It.Nam) then
4352                      Check_One_Function (It.Nam);
4353                   end if;
4354
4355                   Get_Next_Interp (I, It);
4356                end loop;
4357             end;
4358          end if;
4359
4360          if not Indexing_Found and then not Error_Posted (N) then
4361             Error_Msg_NE
4362               ("aspect Indexing requires a local function that "
4363                & "applies to type&", Expr, Ent);
4364          end if;
4365       end Check_Indexing_Functions;
4366
4367       ------------------------------
4368       -- Check_Iterator_Functions --
4369       ------------------------------
4370
4371       procedure Check_Iterator_Functions is
4372          function Valid_Default_Iterator (Subp : Entity_Id) return Boolean;
4373          --  Check one possible interpretation for validity
4374
4375          ----------------------------
4376          -- Valid_Default_Iterator --
4377          ----------------------------
4378
4379          function Valid_Default_Iterator (Subp : Entity_Id) return Boolean is
4380             Root_T : constant Entity_Id := Root_Type (Etype (Etype (Subp)));
4381             Formal : Entity_Id;
4382
4383          begin
4384             if not Check_Primitive_Function (Subp) then
4385                return False;
4386
4387             --  The return type must be derived from a type in an instance
4388             --  of Iterator.Interfaces, and thus its root type must have a
4389             --  predefined name.
4390
4391             elsif Chars (Root_T) /= Name_Forward_Iterator
4392              and then Chars (Root_T) /= Name_Reversible_Iterator
4393             then
4394                return False;
4395
4396             else
4397                Formal := First_Formal (Subp);
4398             end if;
4399
4400             --  False if any subsequent formal has no default expression
4401
4402             Formal := Next_Formal (Formal);
4403             while Present (Formal) loop
4404                if No (Expression (Parent (Formal))) then
4405                   return False;
4406                end if;
4407
4408                Next_Formal (Formal);
4409             end loop;
4410
4411             --  True if all subsequent formals have default expressions
4412
4413             return True;
4414          end Valid_Default_Iterator;
4415
4416       --  Start of processing for Check_Iterator_Functions
4417
4418       begin
4419          Analyze (Expr);
4420
4421          if not Is_Entity_Name (Expr) then
4422             Error_Msg_N ("aspect Iterator must be a function name", Expr);
4423          end if;
4424
4425          if not Is_Overloaded (Expr) then
4426             if not Check_Primitive_Function (Entity (Expr)) then
4427                Error_Msg_NE
4428                  ("aspect Indexing requires a function that applies to type&",
4429                    Entity (Expr), Ent);
4430             end if;
4431
4432             --  Flag the default_iterator as well as the denoted function.
4433
4434             if not Valid_Default_Iterator (Entity (Expr)) then
4435                Error_Msg_N ("improper function for default iterator!", Expr);
4436             end if;
4437
4438          else
4439             declare
4440                Default : Entity_Id := Empty;
4441                I       : Interp_Index;
4442                It      : Interp;
4443
4444             begin
4445                Get_First_Interp (Expr, I, It);
4446                while Present (It.Nam) loop
4447                   if not Check_Primitive_Function (It.Nam)
4448                     or else not Valid_Default_Iterator (It.Nam)
4449                   then
4450                      Remove_Interp (I);
4451
4452                   elsif Present (Default) then
4453
4454                      --  An explicit one should override an implicit one
4455
4456                      if Comes_From_Source (Default) =
4457                           Comes_From_Source (It.Nam)
4458                      then
4459                         Error_Msg_N ("default iterator must be unique", Expr);
4460                         Error_Msg_Sloc := Sloc (Default);
4461                         Error_Msg_N ("\\possible interpretation#", Expr);
4462                         Error_Msg_Sloc := Sloc (It.Nam);
4463                         Error_Msg_N ("\\possible interpretation#", Expr);
4464
4465                      elsif Comes_From_Source (It.Nam) then
4466                         Default := It.Nam;
4467                      end if;
4468                   else
4469                      Default := It.Nam;
4470                   end if;
4471
4472                   Get_Next_Interp (I, It);
4473                end loop;
4474
4475                if Present (Default) then
4476                   Set_Entity (Expr, Default);
4477                   Set_Is_Overloaded (Expr, False);
4478                else
4479                   Error_Msg_N
4480                     ("no interpretation is a valid default iterator!", Expr);
4481                end if;
4482             end;
4483          end if;
4484       end Check_Iterator_Functions;
4485
4486       -------------------------------
4487       -- Check_Primitive_Function  --
4488       -------------------------------
4489
4490       function Check_Primitive_Function (Subp : Entity_Id) return Boolean is
4491          Ctrl : Entity_Id;
4492
4493       begin
4494          if Ekind (Subp) /= E_Function then
4495             return False;
4496          end if;
4497
4498          if No (First_Formal (Subp)) then
4499             return False;
4500          else
4501             Ctrl := Etype (First_Formal (Subp));
4502          end if;
4503
4504          --  To be a primitive operation subprogram has to be in same scope.
4505
4506          if Scope (Ctrl) /= Scope (Subp) then
4507             return False;
4508          end if;
4509
4510          --  Type of formal may be the class-wide type, an access to such,
4511          --  or an incomplete view.
4512
4513          if Ctrl = Ent
4514            or else Ctrl = Class_Wide_Type (Ent)
4515            or else
4516              (Ekind (Ctrl) = E_Anonymous_Access_Type
4517                and then (Designated_Type (Ctrl) = Ent
4518                            or else
4519                          Designated_Type (Ctrl) = Class_Wide_Type (Ent)))
4520            or else
4521              (Ekind (Ctrl) = E_Incomplete_Type
4522                and then Full_View (Ctrl) = Ent)
4523          then
4524             null;
4525          else
4526             return False;
4527          end if;
4528
4529          return True;
4530       end Check_Primitive_Function;
4531
4532       ----------------------
4533       -- Duplicate_Clause --
4534       ----------------------
4535
4536       function Duplicate_Clause return Boolean is
4537          A : Node_Id;
4538
4539       begin
4540          --  Nothing to do if this attribute definition clause comes from
4541          --  an aspect specification, since we could not be duplicating an
4542          --  explicit clause, and we dealt with the case of duplicated aspects
4543          --  in Analyze_Aspect_Specifications.
4544
4545          if From_Aspect_Specification (N) then
4546             return False;
4547          end if;
4548
4549          --  Otherwise current clause may duplicate previous clause, or a
4550          --  previously given pragma or aspect specification for the same
4551          --  aspect.
4552
4553          A := Get_Rep_Item (U_Ent, Chars (N), Check_Parents => False);
4554
4555          if Present (A) then
4556             Error_Msg_Name_1 := Chars (N);
4557             Error_Msg_Sloc := Sloc (A);
4558
4559             Error_Msg_NE ("aspect% for & previously given#", N, U_Ent);
4560             return True;
4561          end if;
4562
4563          return False;
4564       end Duplicate_Clause;
4565
4566    --  Start of processing for Analyze_Attribute_Definition_Clause
4567
4568    begin
4569       --  The following code is a defense against recursion. Not clear that
4570       --  this can happen legitimately, but perhaps some error situations can
4571       --  cause it, and we did see this recursion during testing.
4572
4573       if Analyzed (N) then
4574          return;
4575       else
4576          Set_Analyzed (N, True);
4577       end if;
4578
4579       Check_Restriction_No_Use_Of_Attribute (N);
4580
4581       --  Ignore some selected attributes in CodePeer mode since they are not
4582       --  relevant in this context.
4583
4584       if CodePeer_Mode then
4585          case Id is
4586
4587             --  Ignore Component_Size in CodePeer mode, to avoid changing the
4588             --  internal representation of types by implicitly packing them.
4589
4590             when Attribute_Component_Size =>
4591                Rewrite (N, Make_Null_Statement (Sloc (N)));
4592                return;
4593
4594             when others =>
4595                null;
4596          end case;
4597       end if;
4598
4599       --  Process Ignore_Rep_Clauses option
4600
4601       if Ignore_Rep_Clauses then
4602          case Id is
4603
4604             --  The following should be ignored. They do not affect legality
4605             --  and may be target dependent. The basic idea of -gnatI is to
4606             --  ignore any rep clauses that may be target dependent but do not
4607             --  affect legality (except possibly to be rejected because they
4608             --  are incompatible with the compilation target).
4609
4610             when Attribute_Alignment      |
4611                  Attribute_Bit_Order      |
4612                  Attribute_Component_Size |
4613                  Attribute_Machine_Radix  |
4614                  Attribute_Object_Size    |
4615                  Attribute_Size           |
4616                  Attribute_Small          |
4617                  Attribute_Stream_Size    |
4618                  Attribute_Value_Size     =>
4619                Kill_Rep_Clause (N);
4620                return;
4621
4622             --  The following should not be ignored, because in the first place
4623             --  they are reasonably portable, and should not cause problems
4624             --  in compiling code from another target, and also they do affect
4625             --  legality, e.g. failing to provide a stream attribute for a type
4626             --  may make a program illegal.
4627
4628             when Attribute_External_Tag        |
4629                  Attribute_Input               |
4630                  Attribute_Output              |
4631                  Attribute_Read                |
4632                  Attribute_Simple_Storage_Pool |
4633                  Attribute_Storage_Pool        |
4634                  Attribute_Storage_Size        |
4635                  Attribute_Write               =>
4636                null;
4637
4638             --  We do not do anything here with address clauses, they will be
4639             --  removed by Freeze later on, but for now, it works better to
4640             --  keep then in the tree.
4641
4642             when Attribute_Address =>
4643                null;
4644
4645             --  Other cases are errors ("attribute& cannot be set with
4646             --  definition clause"), which will be caught below.
4647
4648             when others =>
4649                null;
4650          end case;
4651       end if;
4652
4653       Analyze (Nam);
4654       Ent := Entity (Nam);
4655
4656       if Rep_Item_Too_Early (Ent, N) then
4657          return;
4658       end if;
4659
4660       --  Rep clause applies to full view of incomplete type or private type if
4661       --  we have one (if not, this is a premature use of the type). However,
4662       --  certain semantic checks need to be done on the specified entity (i.e.
4663       --  the private view), so we save it in Ent.
4664
4665       if Is_Private_Type (Ent)
4666         and then Is_Derived_Type (Ent)
4667         and then not Is_Tagged_Type (Ent)
4668         and then No (Full_View (Ent))
4669       then
4670          --  If this is a private type whose completion is a derivation from
4671          --  another private type, there is no full view, and the attribute
4672          --  belongs to the type itself, not its underlying parent.
4673
4674          U_Ent := Ent;
4675
4676       elsif Ekind (Ent) = E_Incomplete_Type then
4677
4678          --  The attribute applies to the full view, set the entity of the
4679          --  attribute definition accordingly.
4680
4681          Ent := Underlying_Type (Ent);
4682          U_Ent := Ent;
4683          Set_Entity (Nam, Ent);
4684
4685       else
4686          U_Ent := Underlying_Type (Ent);
4687       end if;
4688
4689       --  Avoid cascaded error
4690
4691       if Etype (Nam) = Any_Type then
4692          return;
4693
4694       --  Must be declared in current scope or in case of an aspect
4695       --  specification, must be visible in current scope.
4696
4697       elsif Scope (Ent) /= Current_Scope
4698         and then
4699           not (From_Aspect_Specification (N)
4700                 and then Scope_Within_Or_Same (Current_Scope, Scope (Ent)))
4701       then
4702          Error_Msg_N ("entity must be declared in this scope", Nam);
4703          return;
4704
4705       --  Must not be a source renaming (we do have some cases where the
4706       --  expander generates a renaming, and those cases are OK, in such
4707       --  cases any attribute applies to the renamed object as well).
4708
4709       elsif Is_Object (Ent)
4710         and then Present (Renamed_Object (Ent))
4711       then
4712          --  Case of renamed object from source, this is an error
4713
4714          if Comes_From_Source (Renamed_Object (Ent)) then
4715             Get_Name_String (Chars (N));
4716             Error_Msg_Strlen := Name_Len;
4717             Error_Msg_String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len);
4718             Error_Msg_N
4719               ("~ clause not allowed for a renaming declaration "
4720                & "(RM 13.1(6))", Nam);
4721             return;
4722
4723          --  For the case of a compiler generated renaming, the attribute
4724          --  definition clause applies to the renamed object created by the
4725          --  expander. The easiest general way to handle this is to create a
4726          --  copy of the attribute definition clause for this object.
4727
4728          elsif Is_Entity_Name (Renamed_Object (Ent)) then
4729             Insert_Action (N,
4730               Make_Attribute_Definition_Clause (Loc,
4731                 Name       =>
4732                   New_Occurrence_Of (Entity (Renamed_Object (Ent)), Loc),
4733                 Chars      => Chars (N),
4734                 Expression => Duplicate_Subexpr (Expression (N))));
4735
4736          --  If the renamed object is not an entity, it must be a dereference
4737          --  of an unconstrained function call, and we must introduce a new
4738          --  declaration to capture the expression. This is needed in the case
4739          --  of 'Alignment, where the original declaration must be rewritten.
4740
4741          else
4742             pragma Assert
4743               (Nkind (Renamed_Object (Ent)) = N_Explicit_Dereference);
4744             null;
4745          end if;
4746
4747       --  If no underlying entity, use entity itself, applies to some
4748       --  previously detected error cases ???
4749
4750       elsif No (U_Ent) then
4751          U_Ent := Ent;
4752
4753       --  Cannot specify for a subtype (exception Object/Value_Size)
4754
4755       elsif Is_Type (U_Ent)
4756         and then not Is_First_Subtype (U_Ent)
4757         and then Id /= Attribute_Object_Size
4758         and then Id /= Attribute_Value_Size
4759         and then not From_At_Mod (N)
4760       then
4761          Error_Msg_N ("cannot specify attribute for subtype", Nam);
4762          return;
4763       end if;
4764
4765       Set_Entity (N, U_Ent);
4766
4767       --  Switch on particular attribute
4768
4769       case Id is
4770
4771          -------------
4772          -- Address --
4773          -------------
4774
4775          --  Address attribute definition clause
4776
4777          when Attribute_Address => Address : begin
4778
4779             --  A little error check, catch for X'Address use X'Address;
4780
4781             if Nkind (Nam) = N_Identifier
4782               and then Nkind (Expr) = N_Attribute_Reference
4783               and then Attribute_Name (Expr) = Name_Address
4784               and then Nkind (Prefix (Expr)) = N_Identifier
4785               and then Chars (Nam) = Chars (Prefix (Expr))
4786             then
4787                Error_Msg_NE
4788                  ("address for & is self-referencing", Prefix (Expr), Ent);
4789                return;
4790             end if;
4791
4792             --  Not that special case, carry on with analysis of expression
4793
4794             Analyze_And_Resolve (Expr, RTE (RE_Address));
4795
4796             --  Even when ignoring rep clauses we need to indicate that the
4797             --  entity has an address clause and thus it is legal to declare
4798             --  it imported. Freeze will get rid of the address clause later.
4799
4800             if Ignore_Rep_Clauses then
4801                if Ekind_In (U_Ent, E_Variable, E_Constant) then
4802                   Record_Rep_Item (U_Ent, N);
4803                end if;
4804
4805                return;
4806             end if;
4807
4808             if Duplicate_Clause then
4809                null;
4810
4811             --  Case of address clause for subprogram
4812
4813             elsif Is_Subprogram (U_Ent) then
4814                if Has_Homonym (U_Ent) then
4815                   Error_Msg_N
4816                     ("address clause cannot be given for overloaded "
4817                      & "subprogram", Nam);
4818                   return;
4819                end if;
4820
4821                --  For subprograms, all address clauses are permitted, and we
4822                --  mark the subprogram as having a deferred freeze so that Gigi
4823                --  will not elaborate it too soon.
4824
4825                --  Above needs more comments, what is too soon about???
4826
4827                Set_Has_Delayed_Freeze (U_Ent);
4828
4829             --  Case of address clause for entry
4830
4831             elsif Ekind (U_Ent) = E_Entry then
4832                if Nkind (Parent (N)) = N_Task_Body then
4833                   Error_Msg_N
4834                     ("entry address must be specified in task spec", Nam);
4835                   return;
4836                end if;
4837
4838                --  For entries, we require a constant address
4839
4840                Check_Constant_Address_Clause (Expr, U_Ent);
4841
4842                --  Special checks for task types
4843
4844                if Is_Task_Type (Scope (U_Ent))
4845                  and then Comes_From_Source (Scope (U_Ent))
4846                then
4847                   Error_Msg_N
4848                     ("??entry address declared for entry in task type", N);
4849                   Error_Msg_N
4850                     ("\??only one task can be declared of this type", N);
4851                end if;
4852
4853                --  Entry address clauses are obsolescent
4854
4855                Check_Restriction (No_Obsolescent_Features, N);
4856
4857                if Warn_On_Obsolescent_Feature then
4858                   Error_Msg_N
4859                     ("?j?attaching interrupt to task entry is an obsolescent "
4860                      & "feature (RM J.7.1)", N);
4861                   Error_Msg_N
4862                     ("\?j?use interrupt procedure instead", N);
4863                end if;
4864
4865             --  Case of an address clause for a controlled object which we
4866             --  consider to be erroneous.
4867
4868             elsif Is_Controlled (Etype (U_Ent))
4869               or else Has_Controlled_Component (Etype (U_Ent))
4870             then
4871                Error_Msg_NE
4872                  ("??controlled object& must not be overlaid", Nam, U_Ent);
4873                Error_Msg_N
4874                  ("\??Program_Error will be raised at run time", Nam);
4875                Insert_Action (Declaration_Node (U_Ent),
4876                  Make_Raise_Program_Error (Loc,
4877                    Reason => PE_Overlaid_Controlled_Object));
4878                return;
4879
4880             --  Case of address clause for a (non-controlled) object
4881
4882             elsif Ekind_In (U_Ent, E_Variable, E_Constant) then
4883                declare
4884                   Expr  : constant Node_Id := Expression (N);
4885                   O_Ent : Entity_Id;
4886                   Off   : Boolean;
4887
4888                begin
4889                   --  Exported variables cannot have an address clause, because
4890                   --  this cancels the effect of the pragma Export.
4891
4892                   if Is_Exported (U_Ent) then
4893                      Error_Msg_N
4894                        ("cannot export object with address clause", Nam);
4895                      return;
4896                   end if;
4897
4898                   Find_Overlaid_Entity (N, O_Ent, Off);
4899
4900                   if Present (O_Ent) then
4901
4902                      --  If the object overlays a constant object, mark it so
4903
4904                      if Is_Constant_Object (O_Ent) then
4905                         Set_Overlays_Constant (U_Ent);
4906                      end if;
4907
4908                      --  If the address clause is of the form:
4909
4910                      --    for X'Address use Y'Address;
4911
4912                      --  or
4913
4914                      --    C : constant Address := Y'Address;
4915                      --    ...
4916                      --    for X'Address use C;
4917
4918                      --  then we make an entry in the table to check the size
4919                      --  and alignment of the overlaying variable. But we defer
4920                      --  this check till after code generation to take full
4921                      --  advantage of the annotation done by the back end.
4922
4923                      --  If the entity has a generic type, the check will be
4924                      --  performed in the instance if the actual type justifies
4925                      --  it, and we do not insert the clause in the table to
4926                      --  prevent spurious warnings.
4927
4928                      --  Note: we used to test Comes_From_Source and only give
4929                      --  this warning for source entities, but we have removed
4930                      --  this test. It really seems bogus to generate overlays
4931                      --  that would trigger this warning in generated code.
4932                      --  Furthermore, by removing the test, we handle the
4933                      --  aspect case properly.
4934
4935                      if Is_Object (O_Ent)
4936                        and then not Is_Generic_Type (Etype (U_Ent))
4937                        and then Address_Clause_Overlay_Warnings
4938                      then
4939                         Address_Clause_Checks.Append
4940                           ((N, U_Ent, No_Uint, O_Ent, Off));
4941                      end if;
4942                   else
4943                      --  If this is not an overlay, mark a variable as being
4944                      --  volatile to prevent unwanted optimizations. It's a
4945                      --  conservative interpretation of RM 13.3(19) for the
4946                      --  cases where the compiler cannot detect potential
4947                      --  aliasing issues easily and it also covers the case
4948                      --  of an absolute address where the volatile aspect is
4949                      --  kind of implicit.
4950
4951                      if Ekind (U_Ent) = E_Variable then
4952                         Set_Treat_As_Volatile (U_Ent);
4953                      end if;
4954
4955                      --  Make an entry in the table for an absolute address as
4956                      --  above to check that the value is compatible with the
4957                      --  alignment of the object.
4958
4959                      declare
4960                         Addr : constant Node_Id := Address_Value (Expr);
4961                      begin
4962                         if Compile_Time_Known_Value (Addr)
4963                           and then Address_Clause_Overlay_Warnings
4964                         then
4965                            Address_Clause_Checks.Append
4966                              ((N, U_Ent, Expr_Value (Addr), Empty, False));
4967                         end if;
4968                      end;
4969                   end if;
4970
4971                   --  Overlaying controlled objects is erroneous. Emit warning
4972                   --  but continue analysis because program is itself legal,
4973                   --  and back end must see address clause.
4974
4975                   if Present (O_Ent)
4976                     and then (Has_Controlled_Component (Etype (O_Ent))
4977                                or else Is_Controlled (Etype (O_Ent)))
4978                     and then not Inside_A_Generic
4979                   then
4980                      Error_Msg_N
4981                        ("??cannot use overlays with controlled objects", Expr);
4982                      Error_Msg_N
4983                        ("\??Program_Error will be raised at run time", Expr);
4984                      Insert_Action (Declaration_Node (U_Ent),
4985                        Make_Raise_Program_Error (Loc,
4986                          Reason => PE_Overlaid_Controlled_Object));
4987
4988                   --  Issue an unconditional warning for a constant overlaying
4989                   --  a variable. For the reverse case, we will issue it only
4990                   --  if the variable is modified.
4991
4992                   elsif Ekind (U_Ent) = E_Constant
4993                     and then Present (O_Ent)
4994                     and then not Overlays_Constant (U_Ent)
4995                     and then Address_Clause_Overlay_Warnings
4996                   then
4997                      Error_Msg_N ("??constant overlays a variable", Expr);
4998
4999                   --  Imported variables can have an address clause, but then
5000                   --  the import is pretty meaningless except to suppress
5001                   --  initializations, so we do not need such variables to
5002                   --  be statically allocated (and in fact it causes trouble
5003                   --  if the address clause is a local value).
5004
5005                   elsif Is_Imported (U_Ent) then
5006                      Set_Is_Statically_Allocated (U_Ent, False);
5007                   end if;
5008
5009                   --  We mark a possible modification of a variable with an
5010                   --  address clause, since it is likely aliasing is occurring.
5011
5012                   Note_Possible_Modification (Nam, Sure => False);
5013
5014                   --  Legality checks on the address clause for initialized
5015                   --  objects is deferred until the freeze point, because
5016                   --  a subsequent pragma might indicate that the object
5017                   --  is imported and thus not initialized. Also, the address
5018                   --  clause might involve entities that have yet to be
5019                   --  elaborated.
5020
5021                   Set_Has_Delayed_Freeze (U_Ent);
5022
5023                   --  If an initialization call has been generated for this
5024                   --  object, it needs to be deferred to after the freeze node
5025                   --  we have just now added, otherwise GIGI will see a
5026                   --  reference to the variable (as actual to the IP call)
5027                   --  before its definition.
5028
5029                   declare
5030                      Init_Call : constant Node_Id :=
5031                                    Remove_Init_Call (U_Ent, N);
5032
5033                   begin
5034                      if Present (Init_Call) then
5035                         Append_Freeze_Action (U_Ent, Init_Call);
5036
5037                         --  Reset Initialization_Statements pointer so that
5038                         --  if there is a pragma Import further down, it can
5039                         --  clear any default initialization.
5040
5041                         Set_Initialization_Statements (U_Ent, Init_Call);
5042                      end if;
5043                   end;
5044
5045                   --  Entity has delayed freeze, so we will generate an
5046                   --  alignment check at the freeze point unless suppressed.
5047
5048                   if not Range_Checks_Suppressed (U_Ent)
5049                     and then not Alignment_Checks_Suppressed (U_Ent)
5050                   then
5051                      Set_Check_Address_Alignment (N);
5052                   end if;
5053
5054                   --  Kill the size check code, since we are not allocating
5055                   --  the variable, it is somewhere else.
5056
5057                   Kill_Size_Check_Code (U_Ent);
5058                end;
5059
5060             --  Not a valid entity for an address clause
5061
5062             else
5063                Error_Msg_N ("address cannot be given for &", Nam);
5064             end if;
5065          end Address;
5066
5067          ---------------
5068          -- Alignment --
5069          ---------------
5070
5071          --  Alignment attribute definition clause
5072
5073          when Attribute_Alignment => Alignment : declare
5074             Align     : constant Uint := Get_Alignment_Value (Expr);
5075             Max_Align : constant Uint := UI_From_Int (Maximum_Alignment);
5076
5077          begin
5078             FOnly := True;
5079
5080             if not Is_Type (U_Ent)
5081               and then Ekind (U_Ent) /= E_Variable
5082               and then Ekind (U_Ent) /= E_Constant
5083             then
5084                Error_Msg_N ("alignment cannot be given for &", Nam);
5085
5086             elsif Duplicate_Clause then
5087                null;
5088
5089             elsif Align /= No_Uint then
5090                Set_Has_Alignment_Clause (U_Ent);
5091
5092                --  Tagged type case, check for attempt to set alignment to a
5093                --  value greater than Max_Align, and reset if so. This error
5094                --  is suppressed in ASIS mode to allow for different ASIS
5095                --  back ends or ASIS-based tools to query the illegal clause.
5096
5097                if Is_Tagged_Type (U_Ent)
5098                  and then Align > Max_Align
5099                  and then not ASIS_Mode
5100                then
5101                   Error_Msg_N
5102                     ("alignment for & set to Maximum_Aligment??", Nam);
5103                   Set_Alignment (U_Ent, Max_Align);
5104
5105                --  All other cases
5106
5107                else
5108                   Set_Alignment (U_Ent, Align);
5109                end if;
5110
5111                --  For an array type, U_Ent is the first subtype. In that case,
5112                --  also set the alignment of the anonymous base type so that
5113                --  other subtypes (such as the itypes for aggregates of the
5114                --  type) also receive the expected alignment.
5115
5116                if Is_Array_Type (U_Ent) then
5117                   Set_Alignment (Base_Type (U_Ent), Align);
5118                end if;
5119             end if;
5120          end Alignment;
5121
5122          ---------------
5123          -- Bit_Order --
5124          ---------------
5125
5126          --  Bit_Order attribute definition clause
5127
5128          when Attribute_Bit_Order => Bit_Order : declare
5129          begin
5130             if not Is_Record_Type (U_Ent) then
5131                Error_Msg_N
5132                  ("Bit_Order can only be defined for record type", Nam);
5133
5134             elsif Duplicate_Clause then
5135                null;
5136
5137             else
5138                Analyze_And_Resolve (Expr, RTE (RE_Bit_Order));
5139
5140                if Etype (Expr) = Any_Type then
5141                   return;
5142
5143                elsif not Is_OK_Static_Expression (Expr) then
5144                   Flag_Non_Static_Expr
5145                     ("Bit_Order requires static expression!", Expr);
5146
5147                else
5148                   if (Expr_Value (Expr) = 0) /= Bytes_Big_Endian then
5149                      Set_Reverse_Bit_Order (Base_Type (U_Ent), True);
5150                   end if;
5151                end if;
5152             end if;
5153          end Bit_Order;
5154
5155          --------------------
5156          -- Component_Size --
5157          --------------------
5158
5159          --  Component_Size attribute definition clause
5160
5161          when Attribute_Component_Size => Component_Size_Case : declare
5162             Csize    : constant Uint := Static_Integer (Expr);
5163             Ctyp     : Entity_Id;
5164             Btype    : Entity_Id;
5165             Biased   : Boolean;
5166             New_Ctyp : Entity_Id;
5167             Decl     : Node_Id;
5168
5169          begin
5170             if not Is_Array_Type (U_Ent) then
5171                Error_Msg_N ("component size requires array type", Nam);
5172                return;
5173             end if;
5174
5175             Btype := Base_Type (U_Ent);
5176             Ctyp  := Component_Type (Btype);
5177
5178             if Duplicate_Clause then
5179                null;
5180
5181             elsif Rep_Item_Too_Early (Btype, N) then
5182                null;
5183
5184             elsif Csize /= No_Uint then
5185                Check_Size (Expr, Ctyp, Csize, Biased);
5186
5187                --  For the biased case, build a declaration for a subtype that
5188                --  will be used to represent the biased subtype that reflects
5189                --  the biased representation of components. We need the subtype
5190                --  to get proper conversions on referencing elements of the
5191                --  array.
5192
5193                if Biased then
5194                   New_Ctyp :=
5195                     Make_Defining_Identifier (Loc,
5196                       Chars =>
5197                         New_External_Name (Chars (U_Ent), 'C', 0, 'T'));
5198
5199                   Decl :=
5200                     Make_Subtype_Declaration (Loc,
5201                       Defining_Identifier => New_Ctyp,
5202                       Subtype_Indication  =>
5203                         New_Occurrence_Of (Component_Type (Btype), Loc));
5204
5205                   Set_Parent (Decl, N);
5206                   Analyze (Decl, Suppress => All_Checks);
5207
5208                   Set_Has_Delayed_Freeze        (New_Ctyp, False);
5209                   Set_Esize                     (New_Ctyp, Csize);
5210                   Set_RM_Size                   (New_Ctyp, Csize);
5211                   Init_Alignment                (New_Ctyp);
5212                   Set_Is_Itype                  (New_Ctyp, True);
5213                   Set_Associated_Node_For_Itype (New_Ctyp, U_Ent);
5214
5215                   Set_Component_Type (Btype, New_Ctyp);
5216                   Set_Biased (New_Ctyp, N, "component size clause");
5217                end if;
5218
5219                Set_Component_Size (Btype, Csize);
5220
5221                --  Deal with warning on overridden size
5222
5223                if Warn_On_Overridden_Size
5224                  and then Has_Size_Clause (Ctyp)
5225                  and then RM_Size (Ctyp) /= Csize
5226                then
5227                   Error_Msg_NE
5228                     ("component size overrides size clause for&?S?", N, Ctyp);
5229                end if;
5230
5231                Set_Has_Component_Size_Clause (Btype, True);
5232                Set_Has_Non_Standard_Rep (Btype, True);
5233             end if;
5234          end Component_Size_Case;
5235
5236          -----------------------
5237          -- Constant_Indexing --
5238          -----------------------
5239
5240          when Attribute_Constant_Indexing =>
5241             Check_Indexing_Functions;
5242
5243          ---------
5244          -- CPU --
5245          ---------
5246
5247          when Attribute_CPU => CPU :
5248          begin
5249             --  CPU attribute definition clause not allowed except from aspect
5250             --  specification.
5251
5252             if From_Aspect_Specification (N) then
5253                if not Is_Task_Type (U_Ent) then
5254                   Error_Msg_N ("CPU can only be defined for task", Nam);
5255
5256                elsif Duplicate_Clause then
5257                   null;
5258
5259                else
5260                   --  The expression must be analyzed in the special manner
5261                   --  described in "Handling of Default and Per-Object
5262                   --  Expressions" in sem.ads.
5263
5264                   --  The visibility to the discriminants must be restored
5265
5266                   Push_Scope_And_Install_Discriminants (U_Ent);
5267                   Preanalyze_Spec_Expression (Expr, RTE (RE_CPU_Range));
5268                   Uninstall_Discriminants_And_Pop_Scope (U_Ent);
5269
5270                   if not Is_OK_Static_Expression (Expr) then
5271                      Check_Restriction (Static_Priorities, Expr);
5272                   end if;
5273                end if;
5274
5275             else
5276                Error_Msg_N
5277                  ("attribute& cannot be set with definition clause", N);
5278             end if;
5279          end CPU;
5280
5281          ----------------------
5282          -- Default_Iterator --
5283          ----------------------
5284
5285          when Attribute_Default_Iterator =>  Default_Iterator : declare
5286             Func : Entity_Id;
5287             Typ  : Entity_Id;
5288
5289          begin
5290             --  If target type is untagged, further checks are irrelevant
5291
5292             if not Is_Tagged_Type (U_Ent) then
5293                Error_Msg_N
5294                  ("aspect Default_Iterator applies to tagged type", Nam);
5295                return;
5296             end if;
5297
5298             Check_Iterator_Functions;
5299
5300             Analyze (Expr);
5301
5302             if not Is_Entity_Name (Expr)
5303               or else Ekind (Entity (Expr)) /= E_Function
5304             then
5305                Error_Msg_N ("aspect Iterator must be a function", Expr);
5306                return;
5307             else
5308                Func := Entity (Expr);
5309             end if;
5310
5311             --  The type of the first parameter must be T, T'class, or a
5312             --  corresponding access type (5.5.1 (8/3). If function is
5313             --  parameterless label type accordingly.
5314
5315             if No (First_Formal (Func)) then
5316                Typ := Any_Type;
5317             else
5318                Typ := Etype (First_Formal (Func));
5319             end if;
5320
5321             if Typ = U_Ent
5322               or else Typ = Class_Wide_Type (U_Ent)
5323               or else (Is_Access_Type (Typ)
5324                         and then Designated_Type (Typ) = U_Ent)
5325               or else (Is_Access_Type (Typ)
5326                         and then Designated_Type (Typ) =
5327                                           Class_Wide_Type (U_Ent))
5328             then
5329                null;
5330
5331             else
5332                Error_Msg_NE
5333                  ("Default Iterator must be a primitive of&", Func, U_Ent);
5334             end if;
5335          end Default_Iterator;
5336
5337          ------------------------
5338          -- Dispatching_Domain --
5339          ------------------------
5340
5341          when Attribute_Dispatching_Domain => Dispatching_Domain :
5342          begin
5343             --  Dispatching_Domain attribute definition clause not allowed
5344             --  except from aspect specification.
5345
5346             if From_Aspect_Specification (N) then
5347                if not Is_Task_Type (U_Ent) then
5348                   Error_Msg_N
5349                     ("Dispatching_Domain can only be defined for task", Nam);
5350
5351                elsif Duplicate_Clause then
5352                   null;
5353
5354                else
5355                   --  The expression must be analyzed in the special manner
5356                   --  described in "Handling of Default and Per-Object
5357                   --  Expressions" in sem.ads.
5358
5359                   --  The visibility to the discriminants must be restored
5360
5361                   Push_Scope_And_Install_Discriminants (U_Ent);
5362
5363                   Preanalyze_Spec_Expression
5364                     (Expr, RTE (RE_Dispatching_Domain));
5365
5366                   Uninstall_Discriminants_And_Pop_Scope (U_Ent);
5367                end if;
5368
5369             else
5370                Error_Msg_N
5371                  ("attribute& cannot be set with definition clause", N);
5372             end if;
5373          end Dispatching_Domain;
5374
5375          ------------------
5376          -- External_Tag --
5377          ------------------
5378
5379          when Attribute_External_Tag => External_Tag :
5380          begin
5381             if not Is_Tagged_Type (U_Ent) then
5382                Error_Msg_N ("should be a tagged type", Nam);
5383             end if;
5384
5385             if Duplicate_Clause then
5386                null;
5387
5388             else
5389                Analyze_And_Resolve (Expr, Standard_String);
5390
5391                if not Is_OK_Static_Expression (Expr) then
5392                   Flag_Non_Static_Expr
5393                     ("static string required for tag name!", Nam);
5394                end if;
5395
5396                if not Is_Library_Level_Entity (U_Ent) then
5397                   Error_Msg_NE
5398                     ("??non-unique external tag supplied for &", N, U_Ent);
5399                   Error_Msg_N
5400                     ("\??same external tag applies to all subprogram calls",
5401                      N);
5402                   Error_Msg_N
5403                     ("\??corresponding internal tag cannot be obtained", N);
5404                end if;
5405             end if;
5406          end External_Tag;
5407
5408          --------------------------
5409          -- Implicit_Dereference --
5410          --------------------------
5411
5412          when Attribute_Implicit_Dereference =>
5413
5414             --  Legality checks already performed at the point of the type
5415             --  declaration, aspect is not delayed.
5416
5417             null;
5418
5419          -----------
5420          -- Input --
5421          -----------
5422
5423          when Attribute_Input =>
5424             Analyze_Stream_TSS_Definition (TSS_Stream_Input);
5425             Set_Has_Specified_Stream_Input (Ent);
5426
5427          ------------------------
5428          -- Interrupt_Priority --
5429          ------------------------
5430
5431          when Attribute_Interrupt_Priority => Interrupt_Priority :
5432          begin
5433             --  Interrupt_Priority attribute definition clause not allowed
5434             --  except from aspect specification.
5435
5436             if From_Aspect_Specification (N) then
5437                if not Is_Concurrent_Type (U_Ent) then
5438                   Error_Msg_N
5439                     ("Interrupt_Priority can only be defined for task and "
5440                      & "protected object", Nam);
5441
5442                elsif Duplicate_Clause then
5443                   null;
5444
5445                else
5446                   --  The expression must be analyzed in the special manner
5447                   --  described in "Handling of Default and Per-Object
5448                   --  Expressions" in sem.ads.
5449
5450                   --  The visibility to the discriminants must be restored
5451
5452                   Push_Scope_And_Install_Discriminants (U_Ent);
5453
5454                   Preanalyze_Spec_Expression
5455                     (Expr, RTE (RE_Interrupt_Priority));
5456
5457                   Uninstall_Discriminants_And_Pop_Scope (U_Ent);
5458
5459                   --  Check the No_Task_At_Interrupt_Priority restriction
5460
5461                   if Is_Task_Type (U_Ent) then
5462                      Check_Restriction (No_Task_At_Interrupt_Priority, N);
5463                   end if;
5464                end if;
5465
5466             else
5467                Error_Msg_N
5468                  ("attribute& cannot be set with definition clause", N);
5469             end if;
5470          end Interrupt_Priority;
5471
5472          --------------
5473          -- Iterable --
5474          --------------
5475
5476          when Attribute_Iterable =>
5477             Analyze (Expr);
5478
5479             if Nkind (Expr) /= N_Aggregate then
5480                Error_Msg_N ("aspect Iterable must be an aggregate", Expr);
5481             end if;
5482
5483             declare
5484                Assoc : Node_Id;
5485
5486             begin
5487                Assoc := First (Component_Associations (Expr));
5488                while Present (Assoc) loop
5489                   if not Is_Entity_Name (Expression (Assoc)) then
5490                      Error_Msg_N ("value must be a function", Assoc);
5491                   end if;
5492
5493                   Next (Assoc);
5494                end loop;
5495             end;
5496
5497          ----------------------
5498          -- Iterator_Element --
5499          ----------------------
5500
5501          when Attribute_Iterator_Element =>
5502             Analyze (Expr);
5503
5504             if not Is_Entity_Name (Expr)
5505               or else not Is_Type (Entity (Expr))
5506             then
5507                Error_Msg_N ("aspect Iterator_Element must be a type", Expr);
5508             end if;
5509
5510          -------------------
5511          -- Machine_Radix --
5512          -------------------
5513
5514          --  Machine radix attribute definition clause
5515
5516          when Attribute_Machine_Radix => Machine_Radix : declare
5517             Radix : constant Uint := Static_Integer (Expr);
5518
5519          begin
5520             if not Is_Decimal_Fixed_Point_Type (U_Ent) then
5521                Error_Msg_N ("decimal fixed-point type expected for &", Nam);
5522
5523             elsif Duplicate_Clause then
5524                null;
5525
5526             elsif Radix /= No_Uint then
5527                Set_Has_Machine_Radix_Clause (U_Ent);
5528                Set_Has_Non_Standard_Rep (Base_Type (U_Ent));
5529
5530                if Radix = 2 then
5531                   null;
5532
5533                elsif Radix = 10 then
5534                   Set_Machine_Radix_10 (U_Ent);
5535
5536                --  The following error is suppressed in ASIS mode to allow for
5537                --  different ASIS back ends or ASIS-based tools to query the
5538                --  illegal clause.
5539
5540                elsif not ASIS_Mode then
5541                   Error_Msg_N ("machine radix value must be 2 or 10", Expr);
5542                end if;
5543             end if;
5544          end Machine_Radix;
5545
5546          -----------------
5547          -- Object_Size --
5548          -----------------
5549
5550          --  Object_Size attribute definition clause
5551
5552          when Attribute_Object_Size => Object_Size : declare
5553             Size : constant Uint := Static_Integer (Expr);
5554
5555             Biased : Boolean;
5556             pragma Warnings (Off, Biased);
5557
5558          begin
5559             if not Is_Type (U_Ent) then
5560                Error_Msg_N ("Object_Size cannot be given for &", Nam);
5561
5562             elsif Duplicate_Clause then
5563                null;
5564
5565             else
5566                Check_Size (Expr, U_Ent, Size, Biased);
5567
5568                --  The following errors are suppressed in ASIS mode to allow
5569                --  for different ASIS back ends or ASIS-based tools to query
5570                --  the illegal clause.
5571
5572                if ASIS_Mode then
5573                   null;
5574
5575                elsif Is_Scalar_Type (U_Ent) then
5576                   if Size /= 8 and then Size /= 16 and then Size /= 32
5577                     and then UI_Mod (Size, 64) /= 0
5578                   then
5579                      Error_Msg_N
5580                        ("Object_Size must be 8, 16, 32, or multiple of 64",
5581                         Expr);
5582                   end if;
5583
5584                elsif Size mod 8 /= 0 then
5585                   Error_Msg_N ("Object_Size must be a multiple of 8", Expr);
5586                end if;
5587
5588                Set_Esize (U_Ent, Size);
5589                Set_Has_Object_Size_Clause (U_Ent);
5590                Alignment_Check_For_Size_Change (U_Ent, Size);
5591             end if;
5592          end Object_Size;
5593
5594          ------------
5595          -- Output --
5596          ------------
5597
5598          when Attribute_Output =>
5599             Analyze_Stream_TSS_Definition (TSS_Stream_Output);
5600             Set_Has_Specified_Stream_Output (Ent);
5601
5602          --------------
5603          -- Priority --
5604          --------------
5605
5606          when Attribute_Priority => Priority :
5607          begin
5608             --  Priority attribute definition clause not allowed except from
5609             --  aspect specification.
5610
5611             if From_Aspect_Specification (N) then
5612                if not (Is_Concurrent_Type (U_Ent)
5613                         or else Ekind (U_Ent) = E_Procedure)
5614                then
5615                   Error_Msg_N
5616                     ("Priority can only be defined for task and protected "
5617                      & "object", Nam);
5618
5619                elsif Duplicate_Clause then
5620                   null;
5621
5622                else
5623                   --  The expression must be analyzed in the special manner
5624                   --  described in "Handling of Default and Per-Object
5625                   --  Expressions" in sem.ads.
5626
5627                   --  The visibility to the discriminants must be restored
5628
5629                   Push_Scope_And_Install_Discriminants (U_Ent);
5630                   Preanalyze_Spec_Expression (Expr, Standard_Integer);
5631                   Uninstall_Discriminants_And_Pop_Scope (U_Ent);
5632
5633                   if not Is_OK_Static_Expression (Expr) then
5634                      Check_Restriction (Static_Priorities, Expr);
5635                   end if;
5636                end if;
5637
5638             else
5639                Error_Msg_N
5640                  ("attribute& cannot be set with definition clause", N);
5641             end if;
5642          end Priority;
5643
5644          ----------
5645          -- Read --
5646          ----------
5647
5648          when Attribute_Read =>
5649             Analyze_Stream_TSS_Definition (TSS_Stream_Read);
5650             Set_Has_Specified_Stream_Read (Ent);
5651
5652          --------------------------
5653          -- Scalar_Storage_Order --
5654          --------------------------
5655
5656          --  Scalar_Storage_Order attribute definition clause
5657
5658          when Attribute_Scalar_Storage_Order => Scalar_Storage_Order : declare
5659          begin
5660             if not (Is_Record_Type (U_Ent) or else Is_Array_Type (U_Ent)) then
5661                Error_Msg_N
5662                  ("Scalar_Storage_Order can only be defined for record or "
5663                   & "array type", Nam);
5664
5665             elsif Duplicate_Clause then
5666                null;
5667
5668             else
5669                Analyze_And_Resolve (Expr, RTE (RE_Bit_Order));
5670
5671                if Etype (Expr) = Any_Type then
5672                   return;
5673
5674                elsif not Is_OK_Static_Expression (Expr) then
5675                   Flag_Non_Static_Expr
5676                     ("Scalar_Storage_Order requires static expression!", Expr);
5677
5678                elsif (Expr_Value (Expr) = 0) /= Bytes_Big_Endian then
5679
5680                   --  Here for the case of a non-default (i.e. non-confirming)
5681                   --  Scalar_Storage_Order attribute definition.
5682
5683                   if Support_Nondefault_SSO_On_Target then
5684                      Set_Reverse_Storage_Order (Base_Type (U_Ent), True);
5685                   else
5686                      Error_Msg_N
5687                        ("non-default Scalar_Storage_Order not supported on "
5688                         & "target", Expr);
5689                   end if;
5690                end if;
5691
5692                --  Clear SSO default indications since explicit setting of the
5693                --  order overrides the defaults.
5694
5695                Set_SSO_Set_Low_By_Default  (Base_Type (U_Ent), False);
5696                Set_SSO_Set_High_By_Default (Base_Type (U_Ent), False);
5697             end if;
5698          end Scalar_Storage_Order;
5699
5700          --------------------------
5701          -- Secondary_Stack_Size --
5702          --------------------------
5703
5704          when Attribute_Secondary_Stack_Size => Secondary_Stack_Size :
5705          begin
5706             --  Secondary_Stack_Size attribute definition clause not allowed
5707             --  except from aspect specification.
5708
5709             if From_Aspect_Specification (N) then
5710                if not Is_Task_Type (U_Ent) then
5711                   Error_Msg_N ("Secondary Stack Size can only be " &
5712                                "defined for task", Nam);
5713
5714                elsif Duplicate_Clause then
5715                   null;
5716
5717                else
5718                   Check_Restriction (No_Secondary_Stack, Expr);
5719
5720                   --  The expression must be analyzed in the special manner
5721                   --  described in "Handling of Default and Per-Object
5722                   --  Expressions" in sem.ads.
5723
5724                   --  The visibility to the discriminants must be restored
5725
5726                   Push_Scope_And_Install_Discriminants (U_Ent);
5727                   Preanalyze_Spec_Expression (Expr, Any_Integer);
5728                   Uninstall_Discriminants_And_Pop_Scope (U_Ent);
5729
5730                   if not Is_OK_Static_Expression (Expr) then
5731                      Check_Restriction (Static_Storage_Size, Expr);
5732                   end if;
5733                end if;
5734
5735             else
5736                Error_Msg_N
5737                  ("attribute& cannot be set with definition clause", N);
5738             end if;
5739          end Secondary_Stack_Size;
5740
5741          ----------
5742          -- Size --
5743          ----------
5744
5745          --  Size attribute definition clause
5746
5747          when Attribute_Size => Size : declare
5748             Size   : constant Uint := Static_Integer (Expr);
5749             Etyp   : Entity_Id;
5750             Biased : Boolean;
5751
5752          begin
5753             FOnly := True;
5754
5755             if Duplicate_Clause then
5756                null;
5757
5758             elsif not Is_Type (U_Ent)
5759               and then Ekind (U_Ent) /= E_Variable
5760               and then Ekind (U_Ent) /= E_Constant
5761             then
5762                Error_Msg_N ("size cannot be given for &", Nam);
5763
5764             elsif Is_Array_Type (U_Ent)
5765               and then not Is_Constrained (U_Ent)
5766             then
5767                Error_Msg_N
5768                  ("size cannot be given for unconstrained array", Nam);
5769
5770             elsif Size /= No_Uint then
5771                if Is_Type (U_Ent) then
5772                   Etyp := U_Ent;
5773                else
5774                   Etyp := Etype (U_Ent);
5775                end if;
5776
5777                --  Check size, note that Gigi is in charge of checking that the
5778                --  size of an array or record type is OK. Also we do not check
5779                --  the size in the ordinary fixed-point case, since it is too
5780                --  early to do so (there may be subsequent small clause that
5781                --  affects the size). We can check the size if a small clause
5782                --  has already been given.
5783
5784                if not Is_Ordinary_Fixed_Point_Type (U_Ent)
5785                  or else Has_Small_Clause (U_Ent)
5786                then
5787                   Check_Size (Expr, Etyp, Size, Biased);
5788                   Set_Biased (U_Ent, N, "size clause", Biased);
5789                end if;
5790
5791                --  For types set RM_Size and Esize if possible
5792
5793                if Is_Type (U_Ent) then
5794                   Set_RM_Size (U_Ent, Size);
5795
5796                   --  For elementary types, increase Object_Size to power of 2,
5797                   --  but not less than a storage unit in any case (normally
5798                   --  this means it will be byte addressable).
5799
5800                   --  For all other types, nothing else to do, we leave Esize
5801                   --  (object size) unset, the back end will set it from the
5802                   --  size and alignment in an appropriate manner.
5803
5804                   --  In both cases, we check whether the alignment must be
5805                   --  reset in the wake of the size change.
5806
5807                   if Is_Elementary_Type (U_Ent) then
5808                      if Size <= System_Storage_Unit then
5809                         Init_Esize (U_Ent, System_Storage_Unit);
5810                      elsif Size <= 16 then
5811                         Init_Esize (U_Ent, 16);
5812                      elsif Size <= 32 then
5813                         Init_Esize (U_Ent, 32);
5814                      else
5815                         Set_Esize  (U_Ent, (Size + 63) / 64 * 64);
5816                      end if;
5817
5818                      Alignment_Check_For_Size_Change (U_Ent, Esize (U_Ent));
5819                   else
5820                      Alignment_Check_For_Size_Change (U_Ent, Size);
5821                   end if;
5822
5823                --  For objects, set Esize only
5824
5825                else
5826                   --  The following error is suppressed in ASIS mode to allow
5827                   --  for different ASIS back ends or ASIS-based tools to query
5828                   --  the illegal clause.
5829
5830                   if Is_Elementary_Type (Etyp)
5831                     and then Size /= System_Storage_Unit
5832                     and then Size /= System_Storage_Unit * 2
5833                     and then Size /= System_Storage_Unit * 4
5834                     and then Size /= System_Storage_Unit * 8
5835                     and then not ASIS_Mode
5836                   then
5837                      Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
5838                      Error_Msg_Uint_2 := Error_Msg_Uint_1 * 8;
5839                      Error_Msg_N
5840                        ("size for primitive object must be a power of 2 in "
5841                         & "the range ^-^", N);
5842                   end if;
5843
5844                   Set_Esize (U_Ent, Size);
5845                end if;
5846
5847                Set_Has_Size_Clause (U_Ent);
5848             end if;
5849          end Size;
5850
5851          -----------
5852          -- Small --
5853          -----------
5854
5855          --  Small attribute definition clause
5856
5857          when Attribute_Small => Small : declare
5858             Implicit_Base : constant Entity_Id := Base_Type (U_Ent);
5859             Small         : Ureal;
5860
5861          begin
5862             Analyze_And_Resolve (Expr, Any_Real);
5863
5864             if Etype (Expr) = Any_Type then
5865                return;
5866
5867             elsif not Is_OK_Static_Expression (Expr) then
5868                Flag_Non_Static_Expr
5869                  ("small requires static expression!", Expr);
5870                return;
5871
5872             else
5873                Small := Expr_Value_R (Expr);
5874
5875                if Small <= Ureal_0 then
5876                   Error_Msg_N ("small value must be greater than zero", Expr);
5877                   return;
5878                end if;
5879
5880             end if;
5881
5882             if not Is_Ordinary_Fixed_Point_Type (U_Ent) then
5883                Error_Msg_N
5884                  ("small requires an ordinary fixed point type", Nam);
5885
5886             elsif Has_Small_Clause (U_Ent) then
5887                Error_Msg_N ("small already given for &", Nam);
5888
5889             elsif Small > Delta_Value (U_Ent) then
5890                Error_Msg_N
5891                  ("small value must not be greater than delta value", Nam);
5892
5893             else
5894                Set_Small_Value (U_Ent, Small);
5895                Set_Small_Value (Implicit_Base, Small);
5896                Set_Has_Small_Clause (U_Ent);
5897                Set_Has_Small_Clause (Implicit_Base);
5898                Set_Has_Non_Standard_Rep (Implicit_Base);
5899             end if;
5900          end Small;
5901
5902          ------------------
5903          -- Storage_Pool --
5904          ------------------
5905
5906          --  Storage_Pool attribute definition clause
5907
5908          when Attribute_Storage_Pool | Attribute_Simple_Storage_Pool => declare
5909             Pool : Entity_Id;
5910             T    : Entity_Id;
5911
5912          begin
5913             if Ekind (U_Ent) = E_Access_Subprogram_Type then
5914                Error_Msg_N
5915                  ("storage pool cannot be given for access-to-subprogram type",
5916                   Nam);
5917                return;
5918
5919             elsif not
5920               Ekind_In (U_Ent, E_Access_Type, E_General_Access_Type)
5921             then
5922                Error_Msg_N
5923                  ("storage pool can only be given for access types", Nam);
5924                return;
5925
5926             elsif Is_Derived_Type (U_Ent) then
5927                Error_Msg_N
5928                  ("storage pool cannot be given for a derived access type",
5929                   Nam);
5930
5931             elsif Duplicate_Clause then
5932                return;
5933
5934             elsif Present (Associated_Storage_Pool (U_Ent)) then
5935                Error_Msg_N ("storage pool already given for &", Nam);
5936                return;
5937             end if;
5938
5939             --  Check for Storage_Size previously given
5940
5941             declare
5942                SS : constant Node_Id :=
5943                       Get_Attribute_Definition_Clause
5944                         (U_Ent, Attribute_Storage_Size);
5945             begin
5946                if Present (SS) then
5947                   Check_Pool_Size_Clash (U_Ent, N, SS);
5948                end if;
5949             end;
5950
5951             --  Storage_Pool case
5952
5953             if Id = Attribute_Storage_Pool then
5954                Analyze_And_Resolve
5955                  (Expr, Class_Wide_Type (RTE (RE_Root_Storage_Pool)));
5956
5957             --  In the Simple_Storage_Pool case, we allow a variable of any
5958             --  simple storage pool type, so we Resolve without imposing an
5959             --  expected type.
5960
5961             else
5962                Analyze_And_Resolve (Expr);
5963
5964                if not Present (Get_Rep_Pragma
5965                                  (Etype (Expr), Name_Simple_Storage_Pool_Type))
5966                then
5967                   Error_Msg_N
5968                     ("expression must be of a simple storage pool type", Expr);
5969                end if;
5970             end if;
5971
5972             if not Denotes_Variable (Expr) then
5973                Error_Msg_N ("storage pool must be a variable", Expr);
5974                return;
5975             end if;
5976
5977             if Nkind (Expr) = N_Type_Conversion then
5978                T := Etype (Expression (Expr));
5979             else
5980                T := Etype (Expr);
5981             end if;
5982
5983             --  The Stack_Bounded_Pool is used internally for implementing
5984             --  access types with a Storage_Size. Since it only work properly
5985             --  when used on one specific type, we need to check that it is not
5986             --  hijacked improperly:
5987
5988             --    type T is access Integer;
5989             --    for T'Storage_Size use n;
5990             --    type Q is access Float;
5991             --    for Q'Storage_Size use T'Storage_Size; -- incorrect
5992
5993             if RTE_Available (RE_Stack_Bounded_Pool)
5994               and then Base_Type (T) = RTE (RE_Stack_Bounded_Pool)
5995             then
5996                Error_Msg_N ("non-shareable internal Pool", Expr);
5997                return;
5998             end if;
5999
6000             --  If the argument is a name that is not an entity name, then
6001             --  we construct a renaming operation to define an entity of
6002             --  type storage pool.
6003
6004             if not Is_Entity_Name (Expr)
6005               and then Is_Object_Reference (Expr)
6006             then
6007                Pool := Make_Temporary (Loc, 'P', Expr);
6008
6009                declare
6010                   Rnode : constant Node_Id :=
6011                             Make_Object_Renaming_Declaration (Loc,
6012                               Defining_Identifier => Pool,
6013                               Subtype_Mark        =>
6014                                 New_Occurrence_Of (Etype (Expr), Loc),
6015                               Name                => Expr);
6016
6017                begin
6018                   --  If the attribute definition clause comes from an aspect
6019                   --  clause, then insert the renaming before the associated
6020                   --  entity's declaration, since the attribute clause has
6021                   --  not yet been appended to the declaration list.
6022
6023                   if From_Aspect_Specification (N) then
6024                      Insert_Before (Parent (Entity (N)), Rnode);
6025                   else
6026                      Insert_Before (N, Rnode);
6027                   end if;
6028
6029                   Analyze (Rnode);
6030                   Set_Associated_Storage_Pool (U_Ent, Pool);
6031                end;
6032
6033             elsif Is_Entity_Name (Expr) then
6034                Pool := Entity (Expr);
6035
6036                --  If pool is a renamed object, get original one. This can
6037                --  happen with an explicit renaming, and within instances.
6038
6039                while Present (Renamed_Object (Pool))
6040                  and then Is_Entity_Name (Renamed_Object (Pool))
6041                loop
6042                   Pool := Entity (Renamed_Object (Pool));
6043                end loop;
6044
6045                if Present (Renamed_Object (Pool))
6046                  and then Nkind (Renamed_Object (Pool)) = N_Type_Conversion
6047                  and then Is_Entity_Name (Expression (Renamed_Object (Pool)))
6048                then
6049                   Pool := Entity (Expression (Renamed_Object (Pool)));
6050                end if;
6051
6052                Set_Associated_Storage_Pool (U_Ent, Pool);
6053
6054             elsif Nkind (Expr) = N_Type_Conversion
6055               and then Is_Entity_Name (Expression (Expr))
6056               and then Nkind (Original_Node (Expr)) = N_Attribute_Reference
6057             then
6058                Pool := Entity (Expression (Expr));
6059                Set_Associated_Storage_Pool (U_Ent, Pool);
6060
6061             else
6062                Error_Msg_N ("incorrect reference to a Storage Pool", Expr);
6063                return;
6064             end if;
6065          end;
6066
6067          ------------------
6068          -- Storage_Size --
6069          ------------------
6070
6071          --  Storage_Size attribute definition clause
6072
6073          when Attribute_Storage_Size => Storage_Size : declare
6074             Btype : constant Entity_Id := Base_Type (U_Ent);
6075
6076          begin
6077             if Is_Task_Type (U_Ent) then
6078
6079                --  Check obsolescent (but never obsolescent if from aspect)
6080
6081                if not From_Aspect_Specification (N) then
6082                   Check_Restriction (No_Obsolescent_Features, N);
6083
6084                   if Warn_On_Obsolescent_Feature then
6085                      Error_Msg_N
6086                        ("?j?storage size clause for task is an obsolescent "
6087                         & "feature (RM J.9)", N);
6088                      Error_Msg_N ("\?j?use Storage_Size pragma instead", N);
6089                   end if;
6090                end if;
6091
6092                FOnly := True;
6093             end if;
6094
6095             if not Is_Access_Type (U_Ent)
6096               and then Ekind (U_Ent) /= E_Task_Type
6097             then
6098                Error_Msg_N ("storage size cannot be given for &", Nam);
6099
6100             elsif Is_Access_Type (U_Ent) and Is_Derived_Type (U_Ent) then
6101                Error_Msg_N
6102                  ("storage size cannot be given for a derived access type",
6103                   Nam);
6104
6105             elsif Duplicate_Clause then
6106                null;
6107
6108             else
6109                Analyze_And_Resolve (Expr, Any_Integer);
6110
6111                if Is_Access_Type (U_Ent) then
6112
6113                   --  Check for Storage_Pool previously given
6114
6115                   declare
6116                      SP : constant Node_Id :=
6117                             Get_Attribute_Definition_Clause
6118                               (U_Ent, Attribute_Storage_Pool);
6119
6120                   begin
6121                      if Present (SP) then
6122                         Check_Pool_Size_Clash (U_Ent, SP, N);
6123                      end if;
6124                   end;
6125
6126                   --  Special case of for x'Storage_Size use 0
6127
6128                   if Is_OK_Static_Expression (Expr)
6129                     and then Expr_Value (Expr) = 0
6130                   then
6131                      Set_No_Pool_Assigned (Btype);
6132                   end if;
6133                end if;
6134
6135                Set_Has_Storage_Size_Clause (Btype);
6136             end if;
6137          end Storage_Size;
6138
6139          -----------------
6140          -- Stream_Size --
6141          -----------------
6142
6143          when Attribute_Stream_Size => Stream_Size : declare
6144             Size : constant Uint := Static_Integer (Expr);
6145
6146          begin
6147             if Ada_Version <= Ada_95 then
6148                Check_Restriction (No_Implementation_Attributes, N);
6149             end if;
6150
6151             if Duplicate_Clause then
6152                null;
6153
6154             elsif Is_Elementary_Type (U_Ent) then
6155
6156                --  The following errors are suppressed in ASIS mode to allow
6157                --  for different ASIS back ends or ASIS-based tools to query
6158                --  the illegal clause.
6159
6160                if ASIS_Mode then
6161                   null;
6162
6163                elsif Size /= System_Storage_Unit
6164                  and then Size /= System_Storage_Unit * 2
6165                  and then Size /= System_Storage_Unit * 4
6166                  and then Size /= System_Storage_Unit * 8
6167                then
6168                   Error_Msg_Uint_1 := UI_From_Int (System_Storage_Unit);
6169                   Error_Msg_N
6170                     ("stream size for elementary type must be a power of 2 "
6171                      & "and at least ^", N);
6172
6173                elsif RM_Size (U_Ent) > Size then
6174                   Error_Msg_Uint_1 := RM_Size (U_Ent);
6175                   Error_Msg_N
6176                     ("stream size for elementary type must be a power of 2 "
6177                      & "and at least ^", N);
6178                end if;
6179
6180                Set_Has_Stream_Size_Clause (U_Ent);
6181
6182             else
6183                Error_Msg_N ("Stream_Size cannot be given for &", Nam);
6184             end if;
6185          end Stream_Size;
6186
6187          ----------------
6188          -- Value_Size --
6189          ----------------
6190
6191          --  Value_Size attribute definition clause
6192
6193          when Attribute_Value_Size => Value_Size : declare
6194             Size   : constant Uint := Static_Integer (Expr);
6195             Biased : Boolean;
6196
6197          begin
6198             if not Is_Type (U_Ent) then
6199                Error_Msg_N ("Value_Size cannot be given for &", Nam);
6200
6201             elsif Duplicate_Clause then
6202                null;
6203
6204             elsif Is_Array_Type (U_Ent)
6205               and then not Is_Constrained (U_Ent)
6206             then
6207                Error_Msg_N
6208                  ("Value_Size cannot be given for unconstrained array", Nam);
6209
6210             else
6211                if Is_Elementary_Type (U_Ent) then
6212                   Check_Size (Expr, U_Ent, Size, Biased);
6213                   Set_Biased (U_Ent, N, "value size clause", Biased);
6214                end if;
6215
6216                Set_RM_Size (U_Ent, Size);
6217             end if;
6218          end Value_Size;
6219
6220          -----------------------
6221          -- Variable_Indexing --
6222          -----------------------
6223
6224          when Attribute_Variable_Indexing =>
6225             Check_Indexing_Functions;
6226
6227          -----------
6228          -- Write --
6229          -----------
6230
6231          when Attribute_Write =>
6232             Analyze_Stream_TSS_Definition (TSS_Stream_Write);
6233             Set_Has_Specified_Stream_Write (Ent);
6234
6235          --  All other attributes cannot be set
6236
6237          when others =>
6238             Error_Msg_N
6239               ("attribute& cannot be set with definition clause", N);
6240       end case;
6241
6242       --  The test for the type being frozen must be performed after any
6243       --  expression the clause has been analyzed since the expression itself
6244       --  might cause freezing that makes the clause illegal.
6245
6246       if Rep_Item_Too_Late (U_Ent, N, FOnly) then
6247          return;
6248       end if;
6249    end Analyze_Attribute_Definition_Clause;
6250
6251    ----------------------------
6252    -- Analyze_Code_Statement --
6253    ----------------------------
6254
6255    procedure Analyze_Code_Statement (N : Node_Id) is
6256       HSS   : constant Node_Id   := Parent (N);
6257       SBody : constant Node_Id   := Parent (HSS);
6258       Subp  : constant Entity_Id := Current_Scope;
6259       Stmt  : Node_Id;
6260       Decl  : Node_Id;
6261       StmtO : Node_Id;
6262       DeclO : Node_Id;
6263
6264    begin
6265       --  Accept foreign code statements for CodePeer. The analysis is skipped
6266       --  to avoid rejecting unrecognized constructs.
6267
6268       if CodePeer_Mode then
6269          Set_Analyzed (N);
6270          return;
6271       end if;
6272
6273       --  Analyze and check we get right type, note that this implements the
6274       --  requirement (RM 13.8(1)) that Machine_Code be with'ed, since that is
6275       --  the only way that Asm_Insn could possibly be visible.
6276
6277       Analyze_And_Resolve (Expression (N));
6278
6279       if Etype (Expression (N)) = Any_Type then
6280          return;
6281       elsif Etype (Expression (N)) /= RTE (RE_Asm_Insn) then
6282          Error_Msg_N ("incorrect type for code statement", N);
6283          return;
6284       end if;
6285
6286       Check_Code_Statement (N);
6287
6288       --  Make sure we appear in the handled statement sequence of a subprogram
6289       --  (RM 13.8(3)).
6290
6291       if Nkind (HSS) /= N_Handled_Sequence_Of_Statements
6292         or else Nkind (SBody) /= N_Subprogram_Body
6293       then
6294          Error_Msg_N
6295            ("code statement can only appear in body of subprogram", N);
6296          return;
6297       end if;
6298
6299       --  Do remaining checks (RM 13.8(3)) if not already done
6300
6301       if not Is_Machine_Code_Subprogram (Subp) then
6302          Set_Is_Machine_Code_Subprogram (Subp);
6303
6304          --  No exception handlers allowed
6305
6306          if Present (Exception_Handlers (HSS)) then
6307             Error_Msg_N
6308               ("exception handlers not permitted in machine code subprogram",
6309                First (Exception_Handlers (HSS)));
6310          end if;
6311
6312          --  No declarations other than use clauses and pragmas (we allow
6313          --  certain internally generated declarations as well).
6314
6315          Decl := First (Declarations (SBody));
6316          while Present (Decl) loop
6317             DeclO := Original_Node (Decl);
6318             if Comes_From_Source (DeclO)
6319               and not Nkind_In (DeclO, N_Pragma,
6320                                        N_Use_Package_Clause,
6321                                        N_Use_Type_Clause,
6322                                        N_Implicit_Label_Declaration)
6323             then
6324                Error_Msg_N
6325                  ("this declaration not allowed in machine code subprogram",
6326                   DeclO);
6327             end if;
6328
6329             Next (Decl);
6330          end loop;
6331
6332          --  No statements other than code statements, pragmas, and labels.
6333          --  Again we allow certain internally generated statements.
6334
6335          --  In Ada 2012, qualified expressions are names, and the code
6336          --  statement is initially parsed as a procedure call.
6337
6338          Stmt := First (Statements (HSS));
6339          while Present (Stmt) loop
6340             StmtO := Original_Node (Stmt);
6341
6342             --  A procedure call transformed into a code statement is OK
6343
6344             if Ada_Version >= Ada_2012
6345               and then Nkind (StmtO) = N_Procedure_Call_Statement
6346               and then Nkind (Name (StmtO)) = N_Qualified_Expression
6347             then
6348                null;
6349
6350             elsif Comes_From_Source (StmtO)
6351               and then not Nkind_In (StmtO, N_Pragma,
6352                                             N_Label,
6353                                             N_Code_Statement)
6354             then
6355                Error_Msg_N
6356                  ("this statement is not allowed in machine code subprogram",
6357                   StmtO);
6358             end if;
6359
6360             Next (Stmt);
6361          end loop;
6362       end if;
6363    end Analyze_Code_Statement;
6364
6365    -----------------------------------------------
6366    -- Analyze_Enumeration_Representation_Clause --
6367    -----------------------------------------------
6368
6369    procedure Analyze_Enumeration_Representation_Clause (N : Node_Id) is
6370       Ident    : constant Node_Id := Identifier (N);
6371       Aggr     : constant Node_Id := Array_Aggregate (N);
6372       Enumtype : Entity_Id;
6373       Elit     : Entity_Id;
6374       Expr     : Node_Id;
6375       Assoc    : Node_Id;
6376       Choice   : Node_Id;
6377       Val      : Uint;
6378
6379       Err : Boolean := False;
6380       --  Set True to avoid cascade errors and crashes on incorrect source code
6381
6382       Lo : constant Uint := Expr_Value (Type_Low_Bound (Universal_Integer));
6383       Hi : constant Uint := Expr_Value (Type_High_Bound (Universal_Integer));
6384       --  Allowed range of universal integer (= allowed range of enum lit vals)
6385
6386       Min : Uint;
6387       Max : Uint;
6388       --  Minimum and maximum values of entries
6389
6390       Max_Node : Node_Id;
6391       --  Pointer to node for literal providing max value
6392
6393    begin
6394       if Ignore_Rep_Clauses then
6395          Kill_Rep_Clause (N);
6396          return;
6397       end if;
6398
6399       --  Ignore enumeration rep clauses by default in CodePeer mode,
6400       --  unless -gnatd.I is specified, as a work around for potential false
6401       --  positive messages.
6402
6403       if CodePeer_Mode and not Debug_Flag_Dot_II then
6404          return;
6405       end if;
6406
6407       --  First some basic error checks
6408
6409       Find_Type (Ident);
6410       Enumtype := Entity (Ident);
6411
6412       if Enumtype = Any_Type
6413         or else Rep_Item_Too_Early (Enumtype, N)
6414       then
6415          return;
6416       else
6417          Enumtype := Underlying_Type (Enumtype);
6418       end if;
6419
6420       if not Is_Enumeration_Type (Enumtype) then
6421          Error_Msg_NE
6422            ("enumeration type required, found}",
6423             Ident, First_Subtype (Enumtype));
6424          return;
6425       end if;
6426
6427       --  Ignore rep clause on generic actual type. This will already have
6428       --  been flagged on the template as an error, and this is the safest
6429       --  way to ensure we don't get a junk cascaded message in the instance.
6430
6431       if Is_Generic_Actual_Type (Enumtype) then
6432          return;
6433
6434       --  Type must be in current scope
6435
6436       elsif Scope (Enumtype) /= Current_Scope then
6437          Error_Msg_N ("type must be declared in this scope", Ident);
6438          return;
6439
6440       --  Type must be a first subtype
6441
6442       elsif not Is_First_Subtype (Enumtype) then
6443          Error_Msg_N ("cannot give enumeration rep clause for subtype", N);
6444          return;
6445
6446       --  Ignore duplicate rep clause
6447
6448       elsif Has_Enumeration_Rep_Clause (Enumtype) then
6449          Error_Msg_N ("duplicate enumeration rep clause ignored", N);
6450          return;
6451
6452       --  Don't allow rep clause for standard [wide_[wide_]]character
6453
6454       elsif Is_Standard_Character_Type (Enumtype) then
6455          Error_Msg_N ("enumeration rep clause not allowed for this type", N);
6456          return;
6457
6458       --  Check that the expression is a proper aggregate (no parentheses)
6459
6460       elsif Paren_Count (Aggr) /= 0 then
6461          Error_Msg
6462            ("extra parentheses surrounding aggregate not allowed",
6463             First_Sloc (Aggr));
6464          return;
6465
6466       --  All tests passed, so set rep clause in place
6467
6468       else
6469          Set_Has_Enumeration_Rep_Clause (Enumtype);
6470          Set_Has_Enumeration_Rep_Clause (Base_Type (Enumtype));
6471       end if;
6472
6473       --  Now we process the aggregate. Note that we don't use the normal
6474       --  aggregate code for this purpose, because we don't want any of the
6475       --  normal expansion activities, and a number of special semantic
6476       --  rules apply (including the component type being any integer type)
6477
6478       Elit := First_Literal (Enumtype);
6479
6480       --  First the positional entries if any
6481
6482       if Present (Expressions (Aggr)) then
6483          Expr := First (Expressions (Aggr));
6484          while Present (Expr) loop
6485             if No (Elit) then
6486                Error_Msg_N ("too many entries in aggregate", Expr);
6487                return;
6488             end if;
6489
6490             Val := Static_Integer (Expr);
6491
6492             --  Err signals that we found some incorrect entries processing
6493             --  the list. The final checks for completeness and ordering are
6494             --  skipped in this case.
6495
6496             if Val = No_Uint then
6497                Err := True;
6498
6499             elsif Val < Lo or else Hi < Val then
6500                Error_Msg_N ("value outside permitted range", Expr);
6501                Err := True;
6502             end if;
6503
6504             Set_Enumeration_Rep (Elit, Val);
6505             Set_Enumeration_Rep_Expr (Elit, Expr);
6506             Next (Expr);
6507             Next (Elit);
6508          end loop;
6509       end if;
6510
6511       --  Now process the named entries if present
6512
6513       if Present (Component_Associations (Aggr)) then
6514          Assoc := First (Component_Associations (Aggr));
6515          while Present (Assoc) loop
6516             Choice := First (Choices (Assoc));
6517
6518             if Present (Next (Choice)) then
6519                Error_Msg_N
6520                  ("multiple choice not allowed here", Next (Choice));
6521                Err := True;
6522             end if;
6523
6524             if Nkind (Choice) = N_Others_Choice then
6525                Error_Msg_N ("others choice not allowed here", Choice);
6526                Err := True;
6527
6528             elsif Nkind (Choice) = N_Range then
6529
6530                --  ??? should allow zero/one element range here
6531
6532                Error_Msg_N ("range not allowed here", Choice);
6533                Err := True;
6534
6535             else
6536                Analyze_And_Resolve (Choice, Enumtype);
6537
6538                if Error_Posted (Choice) then
6539                   Err := True;
6540                end if;
6541
6542                if not Err then
6543                   if Is_Entity_Name (Choice)
6544                     and then Is_Type (Entity (Choice))
6545                   then
6546                      Error_Msg_N ("subtype name not allowed here", Choice);
6547                      Err := True;
6548
6549                      --  ??? should allow static subtype with zero/one entry
6550
6551                   elsif Etype (Choice) = Base_Type (Enumtype) then
6552                      if not Is_OK_Static_Expression (Choice) then
6553                         Flag_Non_Static_Expr
6554                           ("non-static expression used for choice!", Choice);
6555                         Err := True;
6556
6557                      else
6558                         Elit := Expr_Value_E (Choice);
6559
6560                         if Present (Enumeration_Rep_Expr (Elit)) then
6561                            Error_Msg_Sloc :=
6562                              Sloc (Enumeration_Rep_Expr (Elit));
6563                            Error_Msg_NE
6564                              ("representation for& previously given#",
6565                               Choice, Elit);
6566                            Err := True;
6567                         end if;
6568
6569                         Set_Enumeration_Rep_Expr (Elit, Expression (Assoc));
6570
6571                         Expr := Expression (Assoc);
6572                         Val := Static_Integer (Expr);
6573
6574                         if Val = No_Uint then
6575                            Err := True;
6576
6577                         elsif Val < Lo or else Hi < Val then
6578                            Error_Msg_N ("value outside permitted range", Expr);
6579                            Err := True;
6580                         end if;
6581
6582                         Set_Enumeration_Rep (Elit, Val);
6583                      end if;
6584                   end if;
6585                end if;
6586             end if;
6587
6588             Next (Assoc);
6589          end loop;
6590       end if;
6591
6592       --  Aggregate is fully processed. Now we check that a full set of
6593       --  representations was given, and that they are in range and in order.
6594       --  These checks are only done if no other errors occurred.
6595
6596       if not Err then
6597          Min  := No_Uint;
6598          Max  := No_Uint;
6599
6600          Elit := First_Literal (Enumtype);
6601          while Present (Elit) loop
6602             if No (Enumeration_Rep_Expr (Elit)) then
6603                Error_Msg_NE ("missing representation for&!", N, Elit);
6604
6605             else
6606                Val := Enumeration_Rep (Elit);
6607
6608                if Min = No_Uint then
6609                   Min := Val;
6610                end if;
6611
6612                if Val /= No_Uint then
6613                   if Max /= No_Uint and then Val <= Max then
6614                      Error_Msg_NE
6615                        ("enumeration value for& not ordered!",
6616                         Enumeration_Rep_Expr (Elit), Elit);
6617                   end if;
6618
6619                   Max_Node := Enumeration_Rep_Expr (Elit);
6620                   Max := Val;
6621                end if;
6622
6623                --  If there is at least one literal whose representation is not
6624                --  equal to the Pos value, then note that this enumeration type
6625                --  has a non-standard representation.
6626
6627                if Val /= Enumeration_Pos (Elit) then
6628                   Set_Has_Non_Standard_Rep (Base_Type (Enumtype));
6629                end if;
6630             end if;
6631
6632             Next (Elit);
6633          end loop;
6634
6635          --  Now set proper size information
6636
6637          declare
6638             Minsize : Uint := UI_From_Int (Minimum_Size (Enumtype));
6639
6640          begin
6641             if Has_Size_Clause (Enumtype) then
6642
6643                --  All OK, if size is OK now
6644
6645                if RM_Size (Enumtype) >= Minsize then
6646                   null;
6647
6648                else
6649                   --  Try if we can get by with biasing
6650
6651                   Minsize :=
6652                     UI_From_Int (Minimum_Size (Enumtype, Biased => True));
6653
6654                   --  Error message if even biasing does not work
6655
6656                   if RM_Size (Enumtype) < Minsize then
6657                      Error_Msg_Uint_1 := RM_Size (Enumtype);
6658                      Error_Msg_Uint_2 := Max;
6659                      Error_Msg_N
6660                        ("previously given size (^) is too small "
6661                         & "for this value (^)", Max_Node);
6662
6663                   --  If biasing worked, indicate that we now have biased rep
6664
6665                   else
6666                      Set_Biased
6667                        (Enumtype, Size_Clause (Enumtype), "size clause");
6668                   end if;
6669                end if;
6670
6671             else
6672                Set_RM_Size    (Enumtype, Minsize);
6673                Set_Enum_Esize (Enumtype);
6674             end if;
6675
6676             Set_RM_Size   (Base_Type (Enumtype), RM_Size   (Enumtype));
6677             Set_Esize     (Base_Type (Enumtype), Esize     (Enumtype));
6678             Set_Alignment (Base_Type (Enumtype), Alignment (Enumtype));
6679          end;
6680       end if;
6681
6682       --  We repeat the too late test in case it froze itself
6683
6684       if Rep_Item_Too_Late (Enumtype, N) then
6685          null;
6686       end if;
6687    end Analyze_Enumeration_Representation_Clause;
6688
6689    ----------------------------
6690    -- Analyze_Free_Statement --
6691    ----------------------------
6692
6693    procedure Analyze_Free_Statement (N : Node_Id) is
6694    begin
6695       Analyze (Expression (N));
6696    end Analyze_Free_Statement;
6697
6698    ---------------------------
6699    -- Analyze_Freeze_Entity --
6700    ---------------------------
6701
6702    procedure Analyze_Freeze_Entity (N : Node_Id) is
6703    begin
6704       Freeze_Entity_Checks (N);
6705    end Analyze_Freeze_Entity;
6706
6707    -----------------------------------
6708    -- Analyze_Freeze_Generic_Entity --
6709    -----------------------------------
6710
6711    procedure Analyze_Freeze_Generic_Entity (N : Node_Id) is
6712       E : constant Entity_Id := Entity (N);
6713
6714    begin
6715       if not Is_Frozen (E) and then Has_Delayed_Aspects (E) then
6716          Analyze_Aspects_At_Freeze_Point (E);
6717       end if;
6718
6719       Freeze_Entity_Checks (N);
6720    end Analyze_Freeze_Generic_Entity;
6721
6722    ------------------------------------------
6723    -- Analyze_Record_Representation_Clause --
6724    ------------------------------------------
6725
6726    --  Note: we check as much as we can here, but we can't do any checks
6727    --  based on the position values (e.g. overlap checks) until freeze time
6728    --  because especially in Ada 2005 (machine scalar mode), the processing
6729    --  for non-standard bit order can substantially change the positions.
6730    --  See procedure Check_Record_Representation_Clause (called from Freeze)
6731    --  for the remainder of this processing.
6732
6733    procedure Analyze_Record_Representation_Clause (N : Node_Id) is
6734       Ident   : constant Node_Id := Identifier (N);
6735       Biased  : Boolean;
6736       CC      : Node_Id;
6737       Comp    : Entity_Id;
6738       Fbit    : Uint;
6739       Hbit    : Uint := Uint_0;
6740       Lbit    : Uint;
6741       Ocomp   : Entity_Id;
6742       Posit   : Uint;
6743       Rectype : Entity_Id;
6744       Recdef  : Node_Id;
6745
6746       function Is_Inherited (Comp : Entity_Id) return Boolean;
6747       --  True if Comp is an inherited component in a record extension
6748
6749       ------------------
6750       -- Is_Inherited --
6751       ------------------
6752
6753       function Is_Inherited (Comp : Entity_Id) return Boolean is
6754          Comp_Base : Entity_Id;
6755
6756       begin
6757          if Ekind (Rectype) = E_Record_Subtype then
6758             Comp_Base := Original_Record_Component (Comp);
6759          else
6760             Comp_Base := Comp;
6761          end if;
6762
6763          return Comp_Base /= Original_Record_Component (Comp_Base);
6764       end Is_Inherited;
6765
6766       --  Local variables
6767
6768       Is_Record_Extension : Boolean;
6769       --  True if Rectype is a record extension
6770
6771       CR_Pragma : Node_Id := Empty;
6772       --  Points to N_Pragma node if Complete_Representation pragma present
6773
6774    --  Start of processing for Analyze_Record_Representation_Clause
6775
6776    begin
6777       if Ignore_Rep_Clauses then
6778          Kill_Rep_Clause (N);
6779          return;
6780       end if;
6781
6782       Find_Type (Ident);
6783       Rectype := Entity (Ident);
6784
6785       if Rectype = Any_Type or else Rep_Item_Too_Early (Rectype, N) then
6786          return;
6787       else
6788          Rectype := Underlying_Type (Rectype);
6789       end if;
6790
6791       --  First some basic error checks
6792
6793       if not Is_Record_Type (Rectype) then
6794          Error_Msg_NE
6795            ("record type required, found}", Ident, First_Subtype (Rectype));
6796          return;
6797
6798       elsif Scope (Rectype) /= Current_Scope then
6799          Error_Msg_N ("type must be declared in this scope", N);
6800          return;
6801
6802       elsif not Is_First_Subtype (Rectype) then
6803          Error_Msg_N ("cannot give record rep clause for subtype", N);
6804          return;
6805
6806       elsif Has_Record_Rep_Clause (Rectype) then
6807          Error_Msg_N ("duplicate record rep clause ignored", N);
6808          return;
6809
6810       elsif Rep_Item_Too_Late (Rectype, N) then
6811          return;
6812       end if;
6813
6814       --  We know we have a first subtype, now possibly go to the anonymous
6815       --  base type to determine whether Rectype is a record extension.
6816
6817       Recdef := Type_Definition (Declaration_Node (Base_Type (Rectype)));
6818       Is_Record_Extension :=
6819         Nkind (Recdef) = N_Derived_Type_Definition
6820           and then Present (Record_Extension_Part (Recdef));
6821
6822       if Present (Mod_Clause (N)) then
6823          declare
6824             Loc     : constant Source_Ptr := Sloc (N);
6825             M       : constant Node_Id := Mod_Clause (N);
6826             P       : constant List_Id := Pragmas_Before (M);
6827             AtM_Nod : Node_Id;
6828
6829             Mod_Val : Uint;
6830             pragma Warnings (Off, Mod_Val);
6831
6832          begin
6833             Check_Restriction (No_Obsolescent_Features, Mod_Clause (N));
6834
6835             if Warn_On_Obsolescent_Feature then
6836                Error_Msg_N
6837                  ("?j?mod clause is an obsolescent feature (RM J.8)", N);
6838                Error_Msg_N
6839                  ("\?j?use alignment attribute definition clause instead", N);
6840             end if;
6841
6842             if Present (P) then
6843                Analyze_List (P);
6844             end if;
6845
6846             --  In ASIS_Mode mode, expansion is disabled, but we must convert
6847             --  the Mod clause into an alignment clause anyway, so that the
6848             --  back end can compute and back-annotate properly the size and
6849             --  alignment of types that may include this record.
6850
6851             --  This seems dubious, this destroys the source tree in a manner
6852             --  not detectable by ASIS ???
6853
6854             if Operating_Mode = Check_Semantics and then ASIS_Mode then
6855                AtM_Nod :=
6856                  Make_Attribute_Definition_Clause (Loc,
6857                    Name       => New_Occurrence_Of (Base_Type (Rectype), Loc),
6858                    Chars      => Name_Alignment,
6859                    Expression => Relocate_Node (Expression (M)));
6860
6861                Set_From_At_Mod (AtM_Nod);
6862                Insert_After (N, AtM_Nod);
6863                Mod_Val := Get_Alignment_Value (Expression (AtM_Nod));
6864                Set_Mod_Clause (N, Empty);
6865
6866             else
6867                --  Get the alignment value to perform error checking
6868
6869                Mod_Val := Get_Alignment_Value (Expression (M));
6870             end if;
6871          end;
6872       end if;
6873
6874       --  For untagged types, clear any existing component clauses for the
6875       --  type. If the type is derived, this is what allows us to override
6876       --  a rep clause for the parent. For type extensions, the representation
6877       --  of the inherited components is inherited, so we want to keep previous
6878       --  component clauses for completeness.
6879
6880       if not Is_Tagged_Type (Rectype) then
6881          Comp := First_Component_Or_Discriminant (Rectype);
6882          while Present (Comp) loop
6883             Set_Component_Clause (Comp, Empty);
6884             Next_Component_Or_Discriminant (Comp);
6885          end loop;
6886       end if;
6887
6888       --  All done if no component clauses
6889
6890       CC := First (Component_Clauses (N));
6891
6892       if No (CC) then
6893          return;
6894       end if;
6895
6896       --  A representation like this applies to the base type
6897
6898       Set_Has_Record_Rep_Clause (Base_Type (Rectype));
6899       Set_Has_Non_Standard_Rep  (Base_Type (Rectype));
6900       Set_Has_Specified_Layout  (Base_Type (Rectype));
6901
6902       --  Process the component clauses
6903
6904       while Present (CC) loop
6905
6906          --  Pragma
6907
6908          if Nkind (CC) = N_Pragma then
6909             Analyze (CC);
6910
6911             --  The only pragma of interest is Complete_Representation
6912
6913             if Pragma_Name (CC) = Name_Complete_Representation then
6914                CR_Pragma := CC;
6915             end if;
6916
6917          --  Processing for real component clause
6918
6919          else
6920             Posit := Static_Integer (Position  (CC));
6921             Fbit  := Static_Integer (First_Bit (CC));
6922             Lbit  := Static_Integer (Last_Bit  (CC));
6923
6924             if Posit /= No_Uint
6925               and then Fbit /= No_Uint
6926               and then Lbit /= No_Uint
6927             then
6928                if Posit < 0 then
6929                   Error_Msg_N ("position cannot be negative", Position (CC));
6930
6931                elsif Fbit < 0 then
6932                   Error_Msg_N ("first bit cannot be negative", First_Bit (CC));
6933
6934                --  The Last_Bit specified in a component clause must not be
6935                --  less than the First_Bit minus one (RM-13.5.1(10)).
6936
6937                elsif Lbit < Fbit - 1 then
6938                   Error_Msg_N
6939                     ("last bit cannot be less than first bit minus one",
6940                      Last_Bit (CC));
6941
6942                --  Values look OK, so find the corresponding record component
6943                --  Even though the syntax allows an attribute reference for
6944                --  implementation-defined components, GNAT does not allow the
6945                --  tag to get an explicit position.
6946
6947                elsif Nkind (Component_Name (CC)) = N_Attribute_Reference then
6948                   if Attribute_Name (Component_Name (CC)) = Name_Tag then
6949                      Error_Msg_N ("position of tag cannot be specified", CC);
6950                   else
6951                      Error_Msg_N ("illegal component name", CC);
6952                   end if;
6953
6954                else
6955                   Comp := First_Entity (Rectype);
6956                   while Present (Comp) loop
6957                      exit when Chars (Comp) = Chars (Component_Name (CC));
6958                      Next_Entity (Comp);
6959                   end loop;
6960
6961                   if No (Comp) then
6962
6963                      --  Maybe component of base type that is absent from
6964                      --  statically constrained first subtype.
6965
6966                      Comp := First_Entity (Base_Type (Rectype));
6967                      while Present (Comp) loop
6968                         exit when Chars (Comp) = Chars (Component_Name (CC));
6969                         Next_Entity (Comp);
6970                      end loop;
6971                   end if;
6972
6973                   if No (Comp) then
6974                      Error_Msg_N
6975                        ("component clause is for non-existent field", CC);
6976
6977                   --  Ada 2012 (AI05-0026): Any name that denotes a
6978                   --  discriminant of an object of an unchecked union type
6979                   --  shall not occur within a record_representation_clause.
6980
6981                   --  The general restriction of using record rep clauses on
6982                   --  Unchecked_Union types has now been lifted. Since it is
6983                   --  possible to introduce a record rep clause which mentions
6984                   --  the discriminant of an Unchecked_Union in non-Ada 2012
6985                   --  code, this check is applied to all versions of the
6986                   --  language.
6987
6988                   elsif Ekind (Comp) = E_Discriminant
6989                     and then Is_Unchecked_Union (Rectype)
6990                   then
6991                      Error_Msg_N
6992                        ("cannot reference discriminant of unchecked union",
6993                         Component_Name (CC));
6994
6995                   elsif Is_Record_Extension and then Is_Inherited (Comp) then
6996                      Error_Msg_NE
6997                        ("component clause not allowed for inherited "
6998                         & "component&", CC, Comp);
6999
7000                   elsif Present (Component_Clause (Comp)) then
7001
7002                      --  Diagnose duplicate rep clause, or check consistency
7003                      --  if this is an inherited component. In a double fault,
7004                      --  there may be a duplicate inconsistent clause for an
7005                      --  inherited component.
7006
7007                      if Scope (Original_Record_Component (Comp)) = Rectype
7008                        or else Parent (Component_Clause (Comp)) = N
7009                      then
7010                         Error_Msg_Sloc := Sloc (Component_Clause (Comp));
7011                         Error_Msg_N ("component clause previously given#", CC);
7012
7013                      else
7014                         declare
7015                            Rep1 : constant Node_Id := Component_Clause (Comp);
7016                         begin
7017                            if Intval (Position (Rep1)) /=
7018                                                    Intval (Position (CC))
7019                              or else Intval (First_Bit (Rep1)) /=
7020                                                    Intval (First_Bit (CC))
7021                              or else Intval (Last_Bit (Rep1)) /=
7022                                                    Intval (Last_Bit (CC))
7023                            then
7024                               Error_Msg_N
7025                                 ("component clause inconsistent with "
7026                                  & "representation of ancestor", CC);
7027
7028                            elsif Warn_On_Redundant_Constructs then
7029                               Error_Msg_N
7030                                 ("?r?redundant confirming component clause "
7031                                  & "for component!", CC);
7032                            end if;
7033                         end;
7034                      end if;
7035
7036                   --  Normal case where this is the first component clause we
7037                   --  have seen for this entity, so set it up properly.
7038
7039                   else
7040                      --  Make reference for field in record rep clause and set
7041                      --  appropriate entity field in the field identifier.
7042
7043                      Generate_Reference
7044                        (Comp, Component_Name (CC), Set_Ref => False);
7045                      Set_Entity (Component_Name (CC), Comp);
7046
7047                      --  Update Fbit and Lbit to the actual bit number
7048
7049                      Fbit := Fbit + UI_From_Int (SSU) * Posit;
7050                      Lbit := Lbit + UI_From_Int (SSU) * Posit;
7051
7052                      if Has_Size_Clause (Rectype)
7053                        and then RM_Size (Rectype) <= Lbit
7054                      then
7055                         Error_Msg_N
7056                           ("bit number out of range of specified size",
7057                            Last_Bit (CC));
7058                      else
7059                         Set_Component_Clause     (Comp, CC);
7060                         Set_Component_Bit_Offset (Comp, Fbit);
7061                         Set_Esize                (Comp, 1 + (Lbit - Fbit));
7062                         Set_Normalized_First_Bit (Comp, Fbit mod SSU);
7063                         Set_Normalized_Position  (Comp, Fbit / SSU);
7064
7065                         if Warn_On_Overridden_Size
7066                           and then Has_Size_Clause (Etype (Comp))
7067                           and then RM_Size (Etype (Comp)) /= Esize (Comp)
7068                         then
7069                            Error_Msg_NE
7070                              ("?S?component size overrides size clause for&",
7071                               Component_Name (CC), Etype (Comp));
7072                         end if;
7073
7074                         --  This information is also set in the corresponding
7075                         --  component of the base type, found by accessing the
7076                         --  Original_Record_Component link if it is present.
7077
7078                         Ocomp := Original_Record_Component (Comp);
7079
7080                         if Hbit < Lbit then
7081                            Hbit := Lbit;
7082                         end if;
7083
7084                         Check_Size
7085                           (Component_Name (CC),
7086                            Etype (Comp),
7087                            Esize (Comp),
7088                            Biased);
7089
7090                         Set_Biased
7091                           (Comp, First_Node (CC), "component clause", Biased);
7092
7093                         if Present (Ocomp) then
7094                            Set_Component_Clause     (Ocomp, CC);
7095                            Set_Component_Bit_Offset (Ocomp, Fbit);
7096                            Set_Normalized_First_Bit (Ocomp, Fbit mod SSU);
7097                            Set_Normalized_Position  (Ocomp, Fbit / SSU);
7098                            Set_Esize                (Ocomp, 1 + (Lbit - Fbit));
7099
7100                            Set_Normalized_Position_Max
7101                              (Ocomp, Normalized_Position (Ocomp));
7102
7103                            --  Note: we don't use Set_Biased here, because we
7104                            --  already gave a warning above if needed, and we
7105                            --  would get a duplicate for the same name here.
7106
7107                            Set_Has_Biased_Representation
7108                              (Ocomp, Has_Biased_Representation (Comp));
7109                         end if;
7110
7111                         if Esize (Comp) < 0 then
7112                            Error_Msg_N ("component size is negative", CC);
7113                         end if;
7114                      end if;
7115                   end if;
7116                end if;
7117             end if;
7118          end if;
7119
7120          Next (CC);
7121       end loop;
7122
7123       --  Check missing components if Complete_Representation pragma appeared
7124
7125       if Present (CR_Pragma) then
7126          Comp := First_Component_Or_Discriminant (Rectype);
7127          while Present (Comp) loop
7128             if No (Component_Clause (Comp)) then
7129                Error_Msg_NE
7130                  ("missing component clause for &", CR_Pragma, Comp);
7131             end if;
7132
7133             Next_Component_Or_Discriminant (Comp);
7134          end loop;
7135
7136       --  Give missing components warning if required
7137
7138       elsif Warn_On_Unrepped_Components then
7139          declare
7140             Num_Repped_Components   : Nat := 0;
7141             Num_Unrepped_Components : Nat := 0;
7142
7143          begin
7144             --  First count number of repped and unrepped components
7145
7146             Comp := First_Component_Or_Discriminant (Rectype);
7147             while Present (Comp) loop
7148                if Present (Component_Clause (Comp)) then
7149                   Num_Repped_Components := Num_Repped_Components + 1;
7150                else
7151                   Num_Unrepped_Components := Num_Unrepped_Components + 1;
7152                end if;
7153
7154                Next_Component_Or_Discriminant (Comp);
7155             end loop;
7156
7157             --  We are only interested in the case where there is at least one
7158             --  unrepped component, and at least half the components have rep
7159             --  clauses. We figure that if less than half have them, then the
7160             --  partial rep clause is really intentional. If the component
7161             --  type has no underlying type set at this point (as for a generic
7162             --  formal type), we don't know enough to give a warning on the
7163             --  component.
7164
7165             if Num_Unrepped_Components > 0
7166               and then Num_Unrepped_Components < Num_Repped_Components
7167             then
7168                Comp := First_Component_Or_Discriminant (Rectype);
7169                while Present (Comp) loop
7170                   if No (Component_Clause (Comp))
7171                     and then Comes_From_Source (Comp)
7172                     and then Present (Underlying_Type (Etype (Comp)))
7173                     and then (Is_Scalar_Type (Underlying_Type (Etype (Comp)))
7174                                or else Size_Known_At_Compile_Time
7175                                          (Underlying_Type (Etype (Comp))))
7176                     and then not Has_Warnings_Off (Rectype)
7177
7178                     --  Ignore discriminant in unchecked union, since it is
7179                     --  not there, and cannot have a component clause.
7180
7181                     and then (not Is_Unchecked_Union (Rectype)
7182                                or else Ekind (Comp) /= E_Discriminant)
7183                   then
7184                      Error_Msg_Sloc := Sloc (Comp);
7185                      Error_Msg_NE
7186                        ("?C?no component clause given for & declared #",
7187                         N, Comp);
7188                   end if;
7189
7190                   Next_Component_Or_Discriminant (Comp);
7191                end loop;
7192             end if;
7193          end;
7194       end if;
7195    end Analyze_Record_Representation_Clause;
7196
7197    -------------------------------------
7198    -- Build_Discrete_Static_Predicate --
7199    -------------------------------------
7200
7201    procedure Build_Discrete_Static_Predicate
7202      (Typ  : Entity_Id;
7203       Expr : Node_Id;
7204       Nam  : Name_Id)
7205    is
7206       Loc : constant Source_Ptr := Sloc (Expr);
7207
7208       Non_Static : exception;
7209       --  Raised if something non-static is found
7210
7211       Btyp : constant Entity_Id := Base_Type (Typ);
7212
7213       BLo : constant Uint := Expr_Value (Type_Low_Bound  (Btyp));
7214       BHi : constant Uint := Expr_Value (Type_High_Bound (Btyp));
7215       --  Low bound and high bound value of base type of Typ
7216
7217       TLo : Uint;
7218       THi : Uint;
7219       --  Bounds for constructing the static predicate. We use the bound of the
7220       --  subtype if it is static, otherwise the corresponding base type bound.
7221       --  Note: a non-static subtype can have a static predicate.
7222
7223       type REnt is record
7224          Lo, Hi : Uint;
7225       end record;
7226       --  One entry in a Rlist value, a single REnt (range entry) value denotes
7227       --  one range from Lo to Hi. To represent a single value range Lo = Hi =
7228       --  value.
7229
7230       type RList is array (Nat range <>) of REnt;
7231       --  A list of ranges. The ranges are sorted in increasing order, and are
7232       --  disjoint (there is a gap of at least one value between each range in
7233       --  the table). A value is in the set of ranges in Rlist if it lies
7234       --  within one of these ranges.
7235
7236       False_Range : constant RList :=
7237         RList'(1 .. 0 => REnt'(No_Uint, No_Uint));
7238       --  An empty set of ranges represents a range list that can never be
7239       --  satisfied, since there are no ranges in which the value could lie,
7240       --  so it does not lie in any of them. False_Range is a canonical value
7241       --  for this empty set, but general processing should test for an Rlist
7242       --  with length zero (see Is_False predicate), since other null ranges
7243       --  may appear which must be treated as False.
7244
7245       True_Range : constant RList := RList'(1 => REnt'(BLo, BHi));
7246       --  Range representing True, value must be in the base range
7247
7248       function "and" (Left : RList; Right : RList) return RList;
7249       --  And's together two range lists, returning a range list. This is a set
7250       --  intersection operation.
7251
7252       function "or" (Left : RList; Right : RList) return RList;
7253       --  Or's together two range lists, returning a range list. This is a set
7254       --  union operation.
7255
7256       function "not" (Right : RList) return RList;
7257       --  Returns complement of a given range list, i.e. a range list
7258       --  representing all the values in TLo .. THi that are not in the input
7259       --  operand Right.
7260
7261       function Build_Val (V : Uint) return Node_Id;
7262       --  Return an analyzed N_Identifier node referencing this value, suitable
7263       --  for use as an entry in the Static_Discrte_Predicate list. This node
7264       --  is typed with the base type.
7265
7266       function Build_Range (Lo : Uint; Hi : Uint) return Node_Id;
7267       --  Return an analyzed N_Range node referencing this range, suitable for
7268       --  use as an entry in the Static_Discrete_Predicate list. This node is
7269       --  typed with the base type.
7270
7271       function Get_RList (Exp : Node_Id) return RList;
7272       --  This is a recursive routine that converts the given expression into a
7273       --  list of ranges, suitable for use in building the static predicate.
7274
7275       function Is_False (R : RList) return Boolean;
7276       pragma Inline (Is_False);
7277       --  Returns True if the given range list is empty, and thus represents a
7278       --  False list of ranges that can never be satisfied.
7279
7280       function Is_True (R : RList) return Boolean;
7281       --  Returns True if R trivially represents the True predicate by having a
7282       --  single range from BLo to BHi.
7283
7284       function Is_Type_Ref (N : Node_Id) return Boolean;
7285       pragma Inline (Is_Type_Ref);
7286       --  Returns if True if N is a reference to the type for the predicate in
7287       --  the expression (i.e. if it is an identifier whose Chars field matches
7288       --  the Nam given in the call). N must not be parenthesized, if the type
7289       --  name appears in parens, this routine will return False.
7290
7291       function Lo_Val (N : Node_Id) return Uint;
7292       --  Given an entry from a Static_Discrete_Predicate list that is either
7293       --  a static expression or static range, gets either the expression value
7294       --  or the low bound of the range.
7295
7296       function Hi_Val (N : Node_Id) return Uint;
7297       --  Given an entry from a Static_Discrete_Predicate list that is either
7298       --  a static expression or static range, gets either the expression value
7299       --  or the high bound of the range.
7300
7301       function Membership_Entry (N : Node_Id) return RList;
7302       --  Given a single membership entry (range, value, or subtype), returns
7303       --  the corresponding range list. Raises Static_Error if not static.
7304
7305       function Membership_Entries (N : Node_Id) return RList;
7306       --  Given an element on an alternatives list of a membership operation,
7307       --  returns the range list corresponding to this entry and all following
7308       --  entries (i.e. returns the "or" of this list of values).
7309
7310       function Stat_Pred (Typ : Entity_Id) return RList;
7311       --  Given a type, if it has a static predicate, then return the predicate
7312       --  as a range list, otherwise raise Non_Static.
7313
7314       -----------
7315       -- "and" --
7316       -----------
7317
7318       function "and" (Left : RList; Right : RList) return RList is
7319          FEnt : REnt;
7320          --  First range of result
7321
7322          SLeft : Nat := Left'First;
7323          --  Start of rest of left entries
7324
7325          SRight : Nat := Right'First;
7326          --  Start of rest of right entries
7327
7328       begin
7329          --  If either range is True, return the other
7330
7331          if Is_True (Left) then
7332             return Right;
7333          elsif Is_True (Right) then
7334             return Left;
7335          end if;
7336
7337          --  If either range is False, return False
7338
7339          if Is_False (Left) or else Is_False (Right) then
7340             return False_Range;
7341          end if;
7342
7343          --  Loop to remove entries at start that are disjoint, and thus just
7344          --  get discarded from the result entirely.
7345
7346          loop
7347             --  If no operands left in either operand, result is false
7348
7349             if SLeft > Left'Last or else SRight > Right'Last then
7350                return False_Range;
7351
7352             --  Discard first left operand entry if disjoint with right
7353
7354             elsif Left (SLeft).Hi < Right (SRight).Lo then
7355                SLeft := SLeft + 1;
7356
7357             --  Discard first right operand entry if disjoint with left
7358
7359             elsif Right (SRight).Hi < Left (SLeft).Lo then
7360                SRight := SRight + 1;
7361
7362             --  Otherwise we have an overlapping entry
7363
7364             else
7365                exit;
7366             end if;
7367          end loop;
7368
7369          --  Now we have two non-null operands, and first entries overlap. The
7370          --  first entry in the result will be the overlapping part of these
7371          --  two entries.
7372
7373          FEnt := REnt'(Lo => UI_Max (Left (SLeft).Lo, Right (SRight).Lo),
7374                        Hi => UI_Min (Left (SLeft).Hi, Right (SRight).Hi));
7375
7376          --  Now we can remove the entry that ended at a lower value, since its
7377          --  contribution is entirely contained in Fent.
7378
7379          if Left (SLeft).Hi <= Right (SRight).Hi then
7380             SLeft := SLeft + 1;
7381          else
7382             SRight := SRight + 1;
7383          end if;
7384
7385          --  Compute result by concatenating this first entry with the "and" of
7386          --  the remaining parts of the left and right operands. Note that if
7387          --  either of these is empty, "and" will yield empty, so that we will
7388          --  end up with just Fent, which is what we want in that case.
7389
7390          return
7391            FEnt & (Left (SLeft .. Left'Last) and Right (SRight .. Right'Last));
7392       end "and";
7393
7394       -----------
7395       -- "not" --
7396       -----------
7397
7398       function "not" (Right : RList) return RList is
7399       begin
7400          --  Return True if False range
7401
7402          if Is_False (Right) then
7403             return True_Range;
7404          end if;
7405
7406          --  Return False if True range
7407
7408          if Is_True (Right) then
7409             return False_Range;
7410          end if;
7411
7412          --  Here if not trivial case
7413
7414          declare
7415             Result : RList (1 .. Right'Length + 1);
7416             --  May need one more entry for gap at beginning and end
7417
7418             Count : Nat := 0;
7419             --  Number of entries stored in Result
7420
7421          begin
7422             --  Gap at start
7423
7424             if Right (Right'First).Lo > TLo then
7425                Count := Count + 1;
7426                Result (Count) := REnt'(TLo, Right (Right'First).Lo - 1);
7427             end if;
7428
7429             --  Gaps between ranges
7430
7431             for J in Right'First .. Right'Last - 1 loop
7432                Count := Count + 1;
7433                Result (Count) := REnt'(Right (J).Hi + 1, Right (J + 1).Lo - 1);
7434             end loop;
7435
7436             --  Gap at end
7437
7438             if Right (Right'Last).Hi < THi then
7439                Count := Count + 1;
7440                Result (Count) := REnt'(Right (Right'Last).Hi + 1, THi);
7441             end if;
7442
7443             return Result (1 .. Count);
7444          end;
7445       end "not";
7446
7447       ----------
7448       -- "or" --
7449       ----------
7450
7451       function "or" (Left : RList; Right : RList) return RList is
7452          FEnt : REnt;
7453          --  First range of result
7454
7455          SLeft : Nat := Left'First;
7456          --  Start of rest of left entries
7457
7458          SRight : Nat := Right'First;
7459          --  Start of rest of right entries
7460
7461       begin
7462          --  If either range is True, return True
7463
7464          if Is_True (Left) or else Is_True (Right) then
7465             return True_Range;
7466          end if;
7467
7468          --  If either range is False (empty), return the other
7469
7470          if Is_False (Left) then
7471             return Right;
7472          elsif Is_False (Right) then
7473             return Left;
7474          end if;
7475
7476          --  Initialize result first entry from left or right operand depending
7477          --  on which starts with the lower range.
7478
7479          if Left (SLeft).Lo < Right (SRight).Lo then
7480             FEnt := Left (SLeft);
7481             SLeft := SLeft + 1;
7482          else
7483             FEnt := Right (SRight);
7484             SRight := SRight + 1;
7485          end if;
7486
7487          --  This loop eats ranges from left and right operands that are
7488          --  contiguous with the first range we are gathering.
7489
7490          loop
7491             --  Eat first entry in left operand if contiguous or overlapped by
7492             --  gathered first operand of result.
7493
7494             if SLeft <= Left'Last
7495               and then Left (SLeft).Lo <= FEnt.Hi + 1
7496             then
7497                FEnt.Hi := UI_Max (FEnt.Hi, Left (SLeft).Hi);
7498                SLeft := SLeft + 1;
7499
7500             --  Eat first entry in right operand if contiguous or overlapped by
7501             --  gathered right operand of result.
7502
7503             elsif SRight <= Right'Last
7504               and then Right (SRight).Lo <= FEnt.Hi + 1
7505             then
7506                FEnt.Hi := UI_Max (FEnt.Hi, Right (SRight).Hi);
7507                SRight := SRight + 1;
7508
7509             --  All done if no more entries to eat
7510
7511             else
7512                exit;
7513             end if;
7514          end loop;
7515
7516          --  Obtain result as the first entry we just computed, concatenated
7517          --  to the "or" of the remaining results (if one operand is empty,
7518          --  this will just concatenate with the other
7519
7520          return
7521            FEnt & (Left (SLeft .. Left'Last) or Right (SRight .. Right'Last));
7522       end "or";
7523
7524       -----------------
7525       -- Build_Range --
7526       -----------------
7527
7528       function Build_Range (Lo : Uint; Hi : Uint) return Node_Id is
7529          Result : Node_Id;
7530       begin
7531          Result :=
7532            Make_Range (Loc,
7533               Low_Bound  => Build_Val (Lo),
7534               High_Bound => Build_Val (Hi));
7535          Set_Etype (Result, Btyp);
7536          Set_Analyzed (Result);
7537          return Result;
7538       end Build_Range;
7539
7540       ---------------
7541       -- Build_Val --
7542       ---------------
7543
7544       function Build_Val (V : Uint) return Node_Id is
7545          Result : Node_Id;
7546
7547       begin
7548          if Is_Enumeration_Type (Typ) then
7549             Result := Get_Enum_Lit_From_Pos (Typ, V, Loc);
7550          else
7551             Result := Make_Integer_Literal (Loc, V);
7552          end if;
7553
7554          Set_Etype (Result, Btyp);
7555          Set_Is_Static_Expression (Result);
7556          Set_Analyzed (Result);
7557          return Result;
7558       end Build_Val;
7559
7560       ---------------
7561       -- Get_RList --
7562       ---------------
7563
7564       function Get_RList (Exp : Node_Id) return RList is
7565          Op  : Node_Kind;
7566          Val : Uint;
7567
7568       begin
7569          --  Static expression can only be true or false
7570
7571          if Is_OK_Static_Expression (Exp) then
7572             if Expr_Value (Exp) = 0 then
7573                return False_Range;
7574             else
7575                return True_Range;
7576             end if;
7577          end if;
7578
7579          --  Otherwise test node type
7580
7581          Op := Nkind (Exp);
7582
7583          case Op is
7584
7585             --  And
7586
7587             when N_Op_And | N_And_Then =>
7588                return Get_RList (Left_Opnd (Exp))
7589                         and
7590                       Get_RList (Right_Opnd (Exp));
7591
7592             --  Or
7593
7594             when N_Op_Or | N_Or_Else =>
7595                return Get_RList (Left_Opnd (Exp))
7596                         or
7597                       Get_RList (Right_Opnd (Exp));
7598
7599             --  Not
7600
7601             when N_Op_Not =>
7602                return not Get_RList (Right_Opnd (Exp));
7603
7604                --  Comparisons of type with static value
7605
7606             when N_Op_Compare =>
7607
7608                --  Type is left operand
7609
7610                if Is_Type_Ref (Left_Opnd (Exp))
7611                  and then Is_OK_Static_Expression (Right_Opnd (Exp))
7612                then
7613                   Val := Expr_Value (Right_Opnd (Exp));
7614
7615                --  Typ is right operand
7616
7617                elsif Is_Type_Ref (Right_Opnd (Exp))
7618                  and then Is_OK_Static_Expression (Left_Opnd (Exp))
7619                then
7620                   Val := Expr_Value (Left_Opnd (Exp));
7621
7622                   --  Invert sense of comparison
7623
7624                   case Op is
7625                      when N_Op_Gt => Op := N_Op_Lt;
7626                      when N_Op_Lt => Op := N_Op_Gt;
7627                      when N_Op_Ge => Op := N_Op_Le;
7628                      when N_Op_Le => Op := N_Op_Ge;
7629                      when others  => null;
7630                   end case;
7631
7632                --  Other cases are non-static
7633
7634                else
7635                   raise Non_Static;
7636                end if;
7637
7638                --  Construct range according to comparison operation
7639
7640                case Op is
7641                   when N_Op_Eq =>
7642                      return RList'(1 => REnt'(Val, Val));
7643
7644                   when N_Op_Ge =>
7645                      return RList'(1 => REnt'(Val, BHi));
7646
7647                   when N_Op_Gt =>
7648                      return RList'(1 => REnt'(Val + 1, BHi));
7649
7650                   when N_Op_Le =>
7651                      return RList'(1 => REnt'(BLo, Val));
7652
7653                   when N_Op_Lt =>
7654                      return RList'(1 => REnt'(BLo, Val - 1));
7655
7656                   when N_Op_Ne =>
7657                      return RList'(REnt'(BLo, Val - 1), REnt'(Val + 1, BHi));
7658
7659                   when others  =>
7660                      raise Program_Error;
7661                end case;
7662
7663             --  Membership (IN)
7664
7665             when N_In =>
7666                if not Is_Type_Ref (Left_Opnd (Exp)) then
7667                   raise Non_Static;
7668                end if;
7669
7670                if Present (Right_Opnd (Exp)) then
7671                   return Membership_Entry (Right_Opnd (Exp));
7672                else
7673                   return Membership_Entries (First (Alternatives (Exp)));
7674                end if;
7675
7676             --  Negative membership (NOT IN)
7677
7678             when N_Not_In =>
7679                if not Is_Type_Ref (Left_Opnd (Exp)) then
7680                   raise Non_Static;
7681                end if;
7682
7683                if Present (Right_Opnd (Exp)) then
7684                   return not Membership_Entry (Right_Opnd (Exp));
7685                else
7686                   return not Membership_Entries (First (Alternatives (Exp)));
7687                end if;
7688
7689             --  Function call, may be call to static predicate
7690
7691             when N_Function_Call =>
7692                if Is_Entity_Name (Name (Exp)) then
7693                   declare
7694                      Ent : constant Entity_Id := Entity (Name (Exp));
7695                   begin
7696                      if Is_Predicate_Function (Ent)
7697                           or else
7698                         Is_Predicate_Function_M (Ent)
7699                      then
7700                         return Stat_Pred (Etype (First_Formal (Ent)));
7701                      end if;
7702                   end;
7703                end if;
7704
7705                --  Other function call cases are non-static
7706
7707                raise Non_Static;
7708
7709             --  Qualified expression, dig out the expression
7710
7711             when N_Qualified_Expression =>
7712                return Get_RList (Expression (Exp));
7713
7714             when N_Case_Expression =>
7715                declare
7716                   Alt     : Node_Id;
7717                   Choices : List_Id;
7718                   Dep     : Node_Id;
7719
7720                begin
7721                   if not Is_Entity_Name (Expression (Expr))
7722                     or else Etype (Expression (Expr)) /= Typ
7723                   then
7724                      Error_Msg_N
7725                        ("expression must denaote subtype", Expression (Expr));
7726                      return False_Range;
7727                   end if;
7728
7729                   --  Collect discrete choices in all True alternatives
7730
7731                   Choices := New_List;
7732                   Alt := First (Alternatives (Exp));
7733                   while Present (Alt) loop
7734                      Dep := Expression (Alt);
7735
7736                      if not Is_OK_Static_Expression (Dep) then
7737                         raise Non_Static;
7738
7739                      elsif Is_True (Expr_Value (Dep)) then
7740                         Append_List_To (Choices,
7741                           New_Copy_List (Discrete_Choices (Alt)));
7742                      end if;
7743
7744                      Next (Alt);
7745                   end loop;
7746
7747                   return Membership_Entries (First (Choices));
7748                end;
7749
7750             --  Expression with actions: if no actions, dig out expression
7751
7752             when N_Expression_With_Actions =>
7753                if Is_Empty_List (Actions (Exp)) then
7754                   return Get_RList (Expression (Exp));
7755                else
7756                   raise Non_Static;
7757                end if;
7758
7759             --  Xor operator
7760
7761             when N_Op_Xor =>
7762                return (Get_RList (Left_Opnd (Exp))
7763                         and not Get_RList (Right_Opnd (Exp)))
7764                  or   (Get_RList (Right_Opnd (Exp))
7765                         and not Get_RList (Left_Opnd (Exp)));
7766
7767             --  Any other node type is non-static
7768
7769             when others =>
7770                raise Non_Static;
7771          end case;
7772       end Get_RList;
7773
7774       ------------
7775       -- Hi_Val --
7776       ------------
7777
7778       function Hi_Val (N : Node_Id) return Uint is
7779       begin
7780          if Is_OK_Static_Expression (N) then
7781             return Expr_Value (N);
7782          else
7783             pragma Assert (Nkind (N) = N_Range);
7784             return Expr_Value (High_Bound (N));
7785          end if;
7786       end Hi_Val;
7787
7788       --------------
7789       -- Is_False --
7790       --------------
7791
7792       function Is_False (R : RList) return Boolean is
7793       begin
7794          return R'Length = 0;
7795       end Is_False;
7796
7797       -------------
7798       -- Is_True --
7799       -------------
7800
7801       function Is_True (R : RList) return Boolean is
7802       begin
7803          return R'Length = 1
7804            and then R (R'First).Lo = BLo
7805            and then R (R'First).Hi = BHi;
7806       end Is_True;
7807
7808       -----------------
7809       -- Is_Type_Ref --
7810       -----------------
7811
7812       function Is_Type_Ref (N : Node_Id) return Boolean is
7813       begin
7814          return Nkind (N) = N_Identifier
7815            and then Chars (N) = Nam
7816            and then Paren_Count (N) = 0;
7817       end Is_Type_Ref;
7818
7819       ------------
7820       -- Lo_Val --
7821       ------------
7822
7823       function Lo_Val (N : Node_Id) return Uint is
7824       begin
7825          if Is_OK_Static_Expression (N) then
7826             return Expr_Value (N);
7827          else
7828             pragma Assert (Nkind (N) = N_Range);
7829             return Expr_Value (Low_Bound (N));
7830          end if;
7831       end Lo_Val;
7832
7833       ------------------------
7834       -- Membership_Entries --
7835       ------------------------
7836
7837       function Membership_Entries (N : Node_Id) return RList is
7838       begin
7839          if No (Next (N)) then
7840             return Membership_Entry (N);
7841          else
7842             return Membership_Entry (N) or Membership_Entries (Next (N));
7843          end if;
7844       end Membership_Entries;
7845
7846       ----------------------
7847       -- Membership_Entry --
7848       ----------------------
7849
7850       function Membership_Entry (N : Node_Id) return RList is
7851          Val : Uint;
7852          SLo : Uint;
7853          SHi : Uint;
7854
7855       begin
7856          --  Range case
7857
7858          if Nkind (N) = N_Range then
7859             if not Is_OK_Static_Expression (Low_Bound  (N))
7860                  or else
7861                not Is_OK_Static_Expression (High_Bound (N))
7862             then
7863                raise Non_Static;
7864             else
7865                SLo := Expr_Value (Low_Bound  (N));
7866                SHi := Expr_Value (High_Bound (N));
7867                return RList'(1 => REnt'(SLo, SHi));
7868             end if;
7869
7870          --  Static expression case
7871
7872          elsif Is_OK_Static_Expression (N) then
7873             Val := Expr_Value (N);
7874             return RList'(1 => REnt'(Val, Val));
7875
7876          --  Identifier (other than static expression) case
7877
7878          else pragma Assert (Nkind (N) = N_Identifier);
7879
7880             --  Type case
7881
7882             if Is_Type (Entity (N)) then
7883
7884                --  If type has predicates, process them
7885
7886                if Has_Predicates (Entity (N)) then
7887                   return Stat_Pred (Entity (N));
7888
7889                --  For static subtype without predicates, get range
7890
7891                elsif Is_OK_Static_Subtype (Entity (N)) then
7892                   SLo := Expr_Value (Type_Low_Bound  (Entity (N)));
7893                   SHi := Expr_Value (Type_High_Bound (Entity (N)));
7894                   return RList'(1 => REnt'(SLo, SHi));
7895
7896                --  Any other type makes us non-static
7897
7898                else
7899                   raise Non_Static;
7900                end if;
7901
7902             --  Any other kind of identifier in predicate (e.g. a non-static
7903             --  expression value) means this is not a static predicate.
7904
7905             else
7906                raise Non_Static;
7907             end if;
7908          end if;
7909       end Membership_Entry;
7910
7911       ---------------
7912       -- Stat_Pred --
7913       ---------------
7914
7915       function Stat_Pred (Typ : Entity_Id) return RList is
7916       begin
7917          --  Not static if type does not have static predicates
7918
7919          if not Has_Static_Predicate (Typ) then
7920             raise Non_Static;
7921          end if;
7922
7923          --  Otherwise we convert the predicate list to a range list
7924
7925          declare
7926             Spred  : constant List_Id := Static_Discrete_Predicate (Typ);
7927             Result : RList (1 .. List_Length (Spred));
7928             P      : Node_Id;
7929
7930          begin
7931             P := First (Static_Discrete_Predicate (Typ));
7932             for J in Result'Range loop
7933                Result (J) := REnt'(Lo_Val (P), Hi_Val (P));
7934                Next (P);
7935             end loop;
7936
7937             return Result;
7938          end;
7939       end Stat_Pred;
7940
7941    --  Start of processing for Build_Discrete_Static_Predicate
7942
7943    begin
7944       --  Establish bounds for the predicate
7945
7946       if Compile_Time_Known_Value (Type_Low_Bound (Typ)) then
7947          TLo := Expr_Value (Type_Low_Bound (Typ));
7948       else
7949          TLo := BLo;
7950       end if;
7951
7952       if Compile_Time_Known_Value (Type_High_Bound (Typ)) then
7953          THi := Expr_Value (Type_High_Bound (Typ));
7954       else
7955          THi := BHi;
7956       end if;
7957
7958       --  Analyze the expression to see if it is a static predicate
7959
7960       declare
7961          Ranges : constant RList := Get_RList (Expr);
7962          --  Range list from expression if it is static
7963
7964          Plist : List_Id;
7965
7966       begin
7967          --  Convert range list into a form for the static predicate. In the
7968          --  Ranges array, we just have raw ranges, these must be converted
7969          --  to properly typed and analyzed static expressions or range nodes.
7970
7971          --  Note: here we limit ranges to the ranges of the subtype, so that
7972          --  a predicate is always false for values outside the subtype. That
7973          --  seems fine, such values are invalid anyway, and considering them
7974          --  to fail the predicate seems allowed and friendly, and furthermore
7975          --  simplifies processing for case statements and loops.
7976
7977          Plist := New_List;
7978
7979          for J in Ranges'Range loop
7980             declare
7981                Lo : Uint := Ranges (J).Lo;
7982                Hi : Uint := Ranges (J).Hi;
7983
7984             begin
7985                --  Ignore completely out of range entry
7986
7987                if Hi < TLo or else Lo > THi then
7988                   null;
7989
7990                --  Otherwise process entry
7991
7992                else
7993                   --  Adjust out of range value to subtype range
7994
7995                   if Lo < TLo then
7996                      Lo := TLo;
7997                   end if;
7998
7999                   if Hi > THi then
8000                      Hi := THi;
8001                   end if;
8002
8003                   --  Convert range into required form
8004
8005                   Append_To (Plist, Build_Range (Lo, Hi));
8006                end if;
8007             end;
8008          end loop;
8009
8010          --  Processing was successful and all entries were static, so now we
8011          --  can store the result as the predicate list.
8012
8013          Set_Static_Discrete_Predicate (Typ, Plist);
8014
8015          --  The processing for static predicates put the expression into
8016          --  canonical form as a series of ranges. It also eliminated
8017          --  duplicates and collapsed and combined ranges. We might as well
8018          --  replace the alternatives list of the right operand of the
8019          --  membership test with the static predicate list, which will
8020          --  usually be more efficient.
8021
8022          declare
8023             New_Alts : constant List_Id := New_List;
8024             Old_Node : Node_Id;
8025             New_Node : Node_Id;
8026
8027          begin
8028             Old_Node := First (Plist);
8029             while Present (Old_Node) loop
8030                New_Node := New_Copy (Old_Node);
8031
8032                if Nkind (New_Node) = N_Range then
8033                   Set_Low_Bound  (New_Node, New_Copy (Low_Bound  (Old_Node)));
8034                   Set_High_Bound (New_Node, New_Copy (High_Bound (Old_Node)));
8035                end if;
8036
8037                Append_To (New_Alts, New_Node);
8038                Next (Old_Node);
8039             end loop;
8040
8041             --  If empty list, replace by False
8042
8043             if Is_Empty_List (New_Alts) then
8044                Rewrite (Expr, New_Occurrence_Of (Standard_False, Loc));
8045
8046                --  Else replace by set membership test
8047
8048             else
8049                Rewrite (Expr,
8050                  Make_In (Loc,
8051                    Left_Opnd    => Make_Identifier (Loc, Nam),
8052                    Right_Opnd   => Empty,
8053                    Alternatives => New_Alts));
8054
8055                --  Resolve new expression in function context
8056
8057                Install_Formals (Predicate_Function (Typ));
8058                Push_Scope (Predicate_Function (Typ));
8059                Analyze_And_Resolve (Expr, Standard_Boolean);
8060                Pop_Scope;
8061             end if;
8062          end;
8063       end;
8064
8065       --  If non-static, return doing nothing
8066
8067    exception
8068       when Non_Static =>
8069          return;
8070    end Build_Discrete_Static_Predicate;
8071
8072    --------------------------------
8073    -- Build_Export_Import_Pragma --
8074    --------------------------------
8075
8076    function Build_Export_Import_Pragma
8077      (Asp : Node_Id;
8078       Id  : Entity_Id) return Node_Id
8079    is
8080       Asp_Id : constant Aspect_Id  := Get_Aspect_Id (Asp);
8081       Expr   : constant Node_Id    := Expression (Asp);
8082       Loc    : constant Source_Ptr := Sloc (Asp);
8083
8084       Args     : List_Id;
8085       Conv     : Node_Id;
8086       Conv_Arg : Node_Id;
8087       Dummy_1  : Node_Id;
8088       Dummy_2  : Node_Id;
8089       EN       : Node_Id;
8090       LN       : Node_Id;
8091       Prag     : Node_Id;
8092
8093       Create_Pragma : Boolean := False;
8094       --  This flag is set when the aspect form is such that it warrants the
8095       --  creation of a corresponding pragma.
8096
8097    begin
8098       if Present (Expr) then
8099          if Error_Posted (Expr) then
8100             null;
8101
8102          elsif Is_True (Expr_Value (Expr)) then
8103             Create_Pragma := True;
8104          end if;
8105
8106       --  Otherwise the aspect defaults to True
8107
8108       else
8109          Create_Pragma := True;
8110       end if;
8111
8112       --  Nothing to do when the expression is False or is erroneous
8113
8114       if not Create_Pragma then
8115          return Empty;
8116       end if;
8117
8118       --  Obtain all interfacing aspects that apply to the related entity
8119
8120       Get_Interfacing_Aspects
8121         (Iface_Asp => Asp,
8122          Conv_Asp  => Conv,
8123          EN_Asp    => EN,
8124          Expo_Asp  => Dummy_1,
8125          Imp_Asp   => Dummy_2,
8126          LN_Asp    => LN);
8127
8128       Args := New_List;
8129
8130       --  Handle the convention argument
8131
8132       if Present (Conv) then
8133          Conv_Arg := New_Copy_Tree (Expression (Conv));
8134
8135       --  Assume convention "Ada' when aspect Convention is missing
8136
8137       else
8138          Conv_Arg := Make_Identifier (Loc, Name_Ada);
8139       end if;
8140
8141       Append_To (Args,
8142         Make_Pragma_Argument_Association (Loc,
8143           Chars      => Name_Convention,
8144           Expression => Conv_Arg));
8145
8146       --  Handle the entity argument
8147
8148       Append_To (Args,
8149         Make_Pragma_Argument_Association (Loc,
8150           Chars      => Name_Entity,
8151           Expression => New_Occurrence_Of (Id, Loc)));
8152
8153       --  Handle the External_Name argument
8154
8155       if Present (EN) then
8156          Append_To (Args,
8157            Make_Pragma_Argument_Association (Loc,
8158              Chars      => Name_External_Name,
8159              Expression => New_Copy_Tree (Expression (EN))));
8160       end if;
8161
8162       --  Handle the Link_Name argument
8163
8164       if Present (LN) then
8165          Append_To (Args,
8166            Make_Pragma_Argument_Association (Loc,
8167              Chars      => Name_Link_Name,
8168              Expression => New_Copy_Tree (Expression (LN))));
8169       end if;
8170
8171       --  Generate:
8172       --    pragma Export/Import
8173       --      (Convention    => <Conv>/Ada,
8174       --       Entity        => <Id>,
8175       --      [External_Name => <EN>,]
8176       --      [Link_Name     => <LN>]);
8177
8178       Prag :=
8179         Make_Pragma (Loc,
8180           Pragma_Identifier            =>
8181             Make_Identifier (Loc, Chars (Identifier (Asp))),
8182           Pragma_Argument_Associations => Args);
8183
8184       --  Decorate the relevant aspect and the pragma
8185
8186       Set_Aspect_Rep_Item (Asp, Prag);
8187
8188       Set_Corresponding_Aspect      (Prag, Asp);
8189       Set_From_Aspect_Specification (Prag);
8190       Set_Parent                    (Prag, Asp);
8191
8192       if Asp_Id = Aspect_Import and then Is_Subprogram (Id) then
8193          Set_Import_Pragma (Id, Prag);
8194       end if;
8195
8196       return Prag;
8197    end Build_Export_Import_Pragma;
8198
8199    -------------------------------
8200    -- Build_Predicate_Functions --
8201    -------------------------------
8202
8203    --  The procedures that are constructed here have the form:
8204
8205    --    function typPredicate (Ixxx : typ) return Boolean is
8206    --    begin
8207    --       return
8208    --          typ1Predicate (typ1 (Ixxx))
8209    --          and then typ2Predicate (typ2 (Ixxx))
8210    --          and then ...;
8211    --          exp1 and then exp2 and then ...
8212    --    end typPredicate;
8213
8214    --  Here exp1, and exp2 are expressions from Predicate pragmas. Note that
8215    --  this is the point at which these expressions get analyzed, providing the
8216    --  required delay, and typ1, typ2, are entities from which predicates are
8217    --  inherited. Note that we do NOT generate Check pragmas, that's because we
8218    --  use this function even if checks are off, e.g. for membership tests.
8219
8220    --  Note that the inherited predicates are evaluated first, as required by
8221    --  AI12-0071-1.
8222
8223    --  Note that Sem_Eval.Real_Or_String_Static_Predicate_Matches depends on
8224    --  the form of this return expression.
8225
8226    --  If the expression has at least one Raise_Expression, then we also build
8227    --  the typPredicateM version of the function, in which any occurrence of a
8228    --  Raise_Expression is converted to "return False".
8229
8230    procedure Build_Predicate_Functions (Typ : Entity_Id; N : Node_Id) is
8231       Loc : constant Source_Ptr := Sloc (Typ);
8232
8233       Expr : Node_Id;
8234       --  This is the expression for the result of the function. It is
8235       --  is build by connecting the component predicates with AND THEN.
8236
8237       Expr_M : Node_Id;
8238       --  This is the corresponding return expression for the Predicate_M
8239       --  function. It differs in that raise expressions are marked for
8240       --  special expansion (see Process_REs).
8241
8242       Object_Name : Name_Id;
8243       --  Name for argument of Predicate procedure. Note that we use the same
8244       --  name for both predicate functions. That way the reference within the
8245       --  predicate expression is the same in both functions.
8246
8247       Object_Entity : Entity_Id;
8248       --  Entity for argument of Predicate procedure
8249
8250       Object_Entity_M : Entity_Id;
8251       --  Entity for argument of separate Predicate procedure when exceptions
8252       --  are present in expression.
8253
8254       FDecl : Node_Id;
8255       --  The function declaration
8256
8257       SId : Entity_Id;
8258       --  Its entity
8259
8260       Raise_Expression_Present : Boolean := False;
8261       --  Set True if Expr has at least one Raise_Expression
8262
8263       procedure Add_Condition (Cond : Node_Id);
8264       --  Append Cond to Expr using "and then" (or just copy Cond to Expr if
8265       --  Expr is empty).
8266
8267       procedure Add_Predicates;
8268       --  Appends expressions for any Predicate pragmas in the rep item chain
8269       --  Typ to Expr. Note that we look only at items for this exact entity.
8270       --  Inheritance of predicates for the parent type is done by calling the
8271       --  Predicate_Function of the parent type, using Add_Call above.
8272
8273       procedure Add_Call (T : Entity_Id);
8274       --  Includes a call to the predicate function for type T in Expr if T
8275       --  has predicates and Predicate_Function (T) is non-empty.
8276
8277       function Process_RE (N : Node_Id) return Traverse_Result;
8278       --  Used in Process REs, tests if node N is a raise expression, and if
8279       --  so, marks it to be converted to return False.
8280
8281       procedure Process_REs is new Traverse_Proc (Process_RE);
8282       --  Marks any raise expressions in Expr_M to return False
8283
8284       function Test_RE (N : Node_Id) return Traverse_Result;
8285       --  Used in Test_REs, tests one node for being a raise expression, and if
8286       --  so sets Raise_Expression_Present True.
8287
8288       procedure Test_REs is new Traverse_Proc (Test_RE);
8289       --  Tests to see if Expr contains any raise expressions
8290
8291       --------------
8292       -- Add_Call --
8293       --------------
8294
8295       procedure Add_Call (T : Entity_Id) is
8296          Exp : Node_Id;
8297
8298       begin
8299          if Present (T) and then Present (Predicate_Function (T)) then
8300             Set_Has_Predicates (Typ);
8301
8302             --  Build the call to the predicate function of T
8303
8304             Exp :=
8305               Make_Predicate_Call
8306                 (T, Convert_To (T, Make_Identifier (Loc, Object_Name)));
8307
8308             --  "and"-in the call to evolving expression
8309
8310             Add_Condition (Exp);
8311
8312             --  Output info message on inheritance if required. Note we do not
8313             --  give this information for generic actual types, since it is
8314             --  unwelcome noise in that case in instantiations. We also
8315             --  generally suppress the message in instantiations, and also
8316             --  if it involves internal names.
8317
8318             if Opt.List_Inherited_Aspects
8319               and then not Is_Generic_Actual_Type (Typ)
8320               and then Instantiation_Depth (Sloc (Typ)) = 0
8321               and then not Is_Internal_Name (Chars (T))
8322               and then not Is_Internal_Name (Chars (Typ))
8323             then
8324                Error_Msg_Sloc := Sloc (Predicate_Function (T));
8325                Error_Msg_Node_2 := T;
8326                Error_Msg_N ("info: & inherits predicate from & #?L?", Typ);
8327             end if;
8328          end if;
8329       end Add_Call;
8330
8331       -------------------
8332       -- Add_Condition --
8333       -------------------
8334
8335       procedure Add_Condition (Cond : Node_Id) is
8336       begin
8337          --  This is the first predicate expression
8338
8339          if No (Expr) then
8340             Expr := Cond;
8341
8342          --  Otherwise concatenate to the existing predicate expressions by
8343          --  using "and then".
8344
8345          else
8346             Expr :=
8347               Make_And_Then (Loc,
8348                 Left_Opnd  => Relocate_Node (Expr),
8349                 Right_Opnd => Cond);
8350          end if;
8351       end Add_Condition;
8352
8353       --------------------
8354       -- Add_Predicates --
8355       --------------------
8356
8357       procedure Add_Predicates is
8358          procedure Add_Predicate (Prag : Node_Id);
8359          --  Concatenate the expression of predicate pragma Prag to Expr by
8360          --  using a short circuit "and then" operator.
8361
8362          -------------------
8363          -- Add_Predicate --
8364          -------------------
8365
8366          procedure Add_Predicate (Prag : Node_Id) is
8367             procedure Replace_Type_Reference (N : Node_Id);
8368             --  Replace a single occurrence N of the subtype name with a
8369             --  reference to the formal of the predicate function. N can be an
8370             --  identifier referencing the subtype, or a selected component,
8371             --  representing an appropriately qualified occurrence of the
8372             --  subtype name.
8373
8374             procedure Replace_Type_References is
8375               new Replace_Type_References_Generic (Replace_Type_Reference);
8376             --  Traverse an expression changing every occurrence of an
8377             --  identifier whose name matches the name of the subtype with a
8378             --  reference to the formal parameter of the predicate function.
8379
8380             ----------------------------
8381             -- Replace_Type_Reference --
8382             ----------------------------
8383
8384             procedure Replace_Type_Reference (N : Node_Id) is
8385             begin
8386                Rewrite (N, Make_Identifier (Sloc (N), Object_Name));
8387                --  Use the Sloc of the usage name, not the defining name
8388
8389                Set_Etype (N, Typ);
8390                Set_Entity (N, Object_Entity);
8391
8392                --  We want to treat the node as if it comes from source, so
8393                --  that ASIS will not ignore it.
8394
8395                Set_Comes_From_Source (N, True);
8396             end Replace_Type_Reference;
8397
8398             --  Local variables
8399
8400             Asp  : constant Node_Id := Corresponding_Aspect (Prag);
8401             Arg1 : Node_Id;
8402             Arg2 : Node_Id;
8403
8404          --  Start of processing for Add_Predicate
8405
8406          begin
8407             --  Extract the arguments of the pragma. The expression itself
8408             --  is copied for use in the predicate function, to preserve the
8409             --  original version for ASIS use.
8410
8411             Arg1 := First (Pragma_Argument_Associations (Prag));
8412             Arg2 := Next (Arg1);
8413
8414             Arg1 := Get_Pragma_Arg (Arg1);
8415             Arg2 := New_Copy_Tree (Get_Pragma_Arg (Arg2));
8416
8417             --  When the predicate pragma applies to the current type or its
8418             --  full view, replace all occurrences of the subtype name with
8419             --  references to the formal parameter of the predicate function.
8420
8421             if Entity (Arg1) = Typ
8422               or else Full_View (Entity (Arg1)) = Typ
8423             then
8424                Replace_Type_References (Arg2, Typ);
8425
8426                --  If the predicate pragma comes from an aspect, replace the
8427                --  saved expression because we need the subtype references
8428                --  replaced for the calls to Preanalyze_Spec_Expression in
8429                --  Check_Aspect_At_xxx routines.
8430
8431                if Present (Asp) then
8432                   Set_Entity (Identifier (Asp), New_Copy_Tree (Arg2));
8433                end if;
8434
8435                --  "and"-in the Arg2 condition to evolving expression
8436
8437                Add_Condition (Relocate_Node (Arg2));
8438             end if;
8439          end Add_Predicate;
8440
8441          --  Local variables
8442
8443          Ritem : Node_Id;
8444
8445       --  Start of processing for Add_Predicates
8446
8447       begin
8448          Ritem := First_Rep_Item (Typ);
8449          while Present (Ritem) loop
8450             if Nkind (Ritem) = N_Pragma
8451               and then Pragma_Name (Ritem) = Name_Predicate
8452             then
8453                Add_Predicate (Ritem);
8454
8455             --  If the type is declared in an inner package it may be frozen
8456             --  outside of the package, and the generated pragma has not been
8457             --  analyzed yet, so capture the expression for the predicate
8458             --  function at this point.
8459
8460             elsif Nkind (Ritem) = N_Aspect_Specification
8461               and then Present (Aspect_Rep_Item (Ritem))
8462               and then Scope (Typ) /= Current_Scope
8463             then
8464                declare
8465                   Prag : constant Node_Id := Aspect_Rep_Item (Ritem);
8466
8467                begin
8468                   if Nkind (Prag) = N_Pragma
8469                     and then Pragma_Name (Prag) = Name_Predicate
8470                   then
8471                      Add_Predicate (Prag);
8472                   end if;
8473                end;
8474             end if;
8475
8476             Next_Rep_Item (Ritem);
8477          end loop;
8478       end Add_Predicates;
8479
8480       ----------------
8481       -- Process_RE --
8482       ----------------
8483
8484       function Process_RE (N : Node_Id) return Traverse_Result is
8485       begin
8486          if Nkind (N) = N_Raise_Expression then
8487             Set_Convert_To_Return_False (N);
8488             return Skip;
8489          else
8490             return OK;
8491          end if;
8492       end Process_RE;
8493
8494       -------------
8495       -- Test_RE --
8496       -------------
8497
8498       function Test_RE (N : Node_Id) return Traverse_Result is
8499       begin
8500          if Nkind (N) = N_Raise_Expression then
8501             Raise_Expression_Present := True;
8502             return Abandon;
8503          else
8504             return OK;
8505          end if;
8506       end Test_RE;
8507
8508       --  Local variables
8509
8510       Save_Ghost_Mode : constant Ghost_Mode_Type := Ghost_Mode;
8511
8512    --  Start of processing for Build_Predicate_Functions
8513
8514    begin
8515       --  Return if already built or if type does not have predicates
8516
8517       SId := Predicate_Function (Typ);
8518       if not Has_Predicates (Typ)
8519         or else (Present (SId) and then Has_Completion (SId))
8520       then
8521          return;
8522       end if;
8523
8524       --  The related type may be subject to pragma Ghost. Set the mode now to
8525       --  ensure that the predicate functions are properly marked as Ghost.
8526
8527       Set_Ghost_Mode_From_Entity (Typ);
8528
8529       --  Prepare to construct predicate expression
8530
8531       Expr := Empty;
8532
8533       if Present (SId) then
8534          FDecl := Unit_Declaration_Node (SId);
8535
8536       else
8537          FDecl := Build_Predicate_Function_Declaration (Typ);
8538          SId   := Defining_Entity (FDecl);
8539       end if;
8540
8541       --  Recover name of formal parameter of function that replaces references
8542       --  to the type in predicate expressions.
8543
8544       Object_Entity :=
8545          Defining_Identifier
8546            (First (Parameter_Specifications (Specification (FDecl))));
8547
8548       Object_Name     := Chars (Object_Entity);
8549       Object_Entity_M := Make_Defining_Identifier (Loc, Chars => Object_Name);
8550
8551       --  Add predicates for ancestor if present. These must come before the
8552       --  ones for the current type, as required by AI12-0071-1.
8553
8554       declare
8555          Atyp : constant Entity_Id := Nearest_Ancestor (Typ);
8556       begin
8557          if Present (Atyp) then
8558             Add_Call (Atyp);
8559          end if;
8560       end;
8561
8562       --  Add Predicates for the current type
8563
8564       Add_Predicates;
8565
8566       --  Case where predicates are present
8567
8568       if Present (Expr) then
8569
8570          --  Test for raise expression present
8571
8572          Test_REs (Expr);
8573
8574          --  If raise expression is present, capture a copy of Expr for use
8575          --  in building the predicateM function version later on. For this
8576          --  copy we replace references to Object_Entity by Object_Entity_M.
8577
8578          if Raise_Expression_Present then
8579             declare
8580                Map   : constant Elist_Id := New_Elmt_List;
8581                New_V : Entity_Id := Empty;
8582
8583                --  The unanalyzed expression will be copied and appear in
8584                --  both functions. Normally expressions do not declare new
8585                --  entities, but quantified expressions do, so we need to
8586                --  create new entities for their bound variables, to prevent
8587                --  multiple definitions in gigi.
8588
8589                function Reset_Loop_Variable (N : Node_Id)
8590                  return Traverse_Result;
8591
8592                procedure Collect_Loop_Variables is
8593                  new Traverse_Proc (Reset_Loop_Variable);
8594
8595                ------------------------
8596                -- Reset_Loop_Variable --
8597                ------------------------
8598
8599                function Reset_Loop_Variable (N : Node_Id)
8600                  return Traverse_Result
8601                is
8602                begin
8603                   if Nkind (N) = N_Iterator_Specification then
8604                      New_V := Make_Defining_Identifier
8605                        (Sloc (N), Chars (Defining_Identifier (N)));
8606
8607                      Set_Defining_Identifier (N, New_V);
8608                   end if;
8609
8610                   return OK;
8611                end Reset_Loop_Variable;
8612
8613             begin
8614                Append_Elmt (Object_Entity, Map);
8615                Append_Elmt (Object_Entity_M, Map);
8616                Expr_M := New_Copy_Tree (Expr, Map => Map);
8617                Collect_Loop_Variables (Expr_M);
8618             end;
8619          end if;
8620
8621          --  Build the main predicate function
8622
8623          declare
8624             SIdB : constant Entity_Id :=
8625               Make_Defining_Identifier (Loc,
8626                 Chars => New_External_Name (Chars (Typ), "Predicate"));
8627             --  The entity for the function body
8628
8629             Spec  : Node_Id;
8630             FBody : Node_Id;
8631
8632          begin
8633
8634             --  The predicate function is shared between views of a type
8635
8636             if Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
8637                Set_Predicate_Function (Full_View (Typ), SId);
8638             end if;
8639
8640             --  Mark the predicate function explicitly as Ghost because it does
8641             --  not come from source.
8642
8643             if Ghost_Mode > None then
8644                Set_Is_Ghost_Entity (SId);
8645             end if;
8646
8647             --  Build function body
8648
8649             Spec :=
8650               Make_Function_Specification (Loc,
8651                 Defining_Unit_Name       => SIdB,
8652                 Parameter_Specifications => New_List (
8653                   Make_Parameter_Specification (Loc,
8654                     Defining_Identifier =>
8655                       Make_Defining_Identifier (Loc, Object_Name),
8656                     Parameter_Type =>
8657                       New_Occurrence_Of (Typ, Loc))),
8658                 Result_Definition        =>
8659                   New_Occurrence_Of (Standard_Boolean, Loc));
8660
8661             FBody :=
8662               Make_Subprogram_Body (Loc,
8663                 Specification              => Spec,
8664                 Declarations               => Empty_List,
8665                 Handled_Statement_Sequence =>
8666                   Make_Handled_Sequence_Of_Statements (Loc,
8667                     Statements => New_List (
8668                       Make_Simple_Return_Statement (Loc,
8669                         Expression => Expr))));
8670
8671             --  If declaration has not been analyzed yet, Insert declaration
8672             --  before freeze node.  Insert body itself after freeze node.
8673
8674             if not Analyzed (FDecl) then
8675                Insert_Before_And_Analyze (N, FDecl);
8676             end if;
8677
8678             Insert_After_And_Analyze (N, FBody);
8679
8680             --  Static predicate functions are always side-effect free, and
8681             --  in most cases dynamic predicate functions are as well. Mark
8682             --  them as such whenever possible, so redundant predicate checks
8683             --  can be optimized. If there is a variable reference within the
8684             --  expression, the function is not pure.
8685
8686             if Expander_Active then
8687                Set_Is_Pure (SId,
8688                  Side_Effect_Free (Expr, Variable_Ref => True));
8689                Set_Is_Inlined (SId);
8690             end if;
8691          end;
8692
8693          --  Test for raise expressions present and if so build M version
8694
8695          if Raise_Expression_Present then
8696             declare
8697                SId : constant Entity_Id :=
8698                  Make_Defining_Identifier (Loc,
8699                    Chars => New_External_Name (Chars (Typ), "PredicateM"));
8700                --  The entity for the function spec
8701
8702                SIdB : constant Entity_Id :=
8703                  Make_Defining_Identifier (Loc,
8704                    Chars => New_External_Name (Chars (Typ), "PredicateM"));
8705                --  The entity for the function body
8706
8707                Spec  : Node_Id;
8708                FBody : Node_Id;
8709                FDecl : Node_Id;
8710                BTemp : Entity_Id;
8711
8712             begin
8713                --  Mark any raise expressions for special expansion
8714
8715                Process_REs (Expr_M);
8716
8717                --  Build function declaration
8718
8719                Set_Ekind (SId, E_Function);
8720                Set_Is_Predicate_Function_M (SId);
8721                Set_Predicate_Function_M (Typ, SId);
8722
8723                --  The predicate function is shared between views of a type
8724
8725                if Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
8726                   Set_Predicate_Function_M (Full_View (Typ), SId);
8727                end if;
8728
8729                --  Mark the predicate function explicitly as Ghost because it
8730                --  does not come from source.
8731
8732                if Ghost_Mode > None then
8733                   Set_Is_Ghost_Entity (SId);
8734                end if;
8735
8736                Spec :=
8737                  Make_Function_Specification (Loc,
8738                    Defining_Unit_Name       => SId,
8739                    Parameter_Specifications => New_List (
8740                      Make_Parameter_Specification (Loc,
8741                        Defining_Identifier => Object_Entity_M,
8742                        Parameter_Type      => New_Occurrence_Of (Typ, Loc))),
8743                    Result_Definition        =>
8744                      New_Occurrence_Of (Standard_Boolean, Loc));
8745
8746                FDecl :=
8747                  Make_Subprogram_Declaration (Loc,
8748                    Specification => Spec);
8749
8750                --  Build function body
8751
8752                Spec :=
8753                  Make_Function_Specification (Loc,
8754                    Defining_Unit_Name       => SIdB,
8755                    Parameter_Specifications => New_List (
8756                      Make_Parameter_Specification (Loc,
8757                        Defining_Identifier =>
8758                          Make_Defining_Identifier (Loc, Object_Name),
8759                        Parameter_Type =>
8760                          New_Occurrence_Of (Typ, Loc))),
8761                    Result_Definition        =>
8762                      New_Occurrence_Of (Standard_Boolean, Loc));
8763
8764                --  Build the body, we declare the boolean expression before
8765                --  doing the return, because we are not really confident of
8766                --  what happens if a return appears within a return.
8767
8768                BTemp :=
8769                  Make_Defining_Identifier (Loc,
8770                    Chars => New_Internal_Name ('B'));
8771
8772                FBody :=
8773                  Make_Subprogram_Body (Loc,
8774                    Specification              => Spec,
8775
8776                    Declarations               => New_List (
8777                      Make_Object_Declaration (Loc,
8778                        Defining_Identifier => BTemp,
8779                        Constant_Present    => True,
8780                          Object_Definition =>
8781                            New_Occurrence_Of (Standard_Boolean, Loc),
8782                          Expression        => Expr_M)),
8783
8784                    Handled_Statement_Sequence =>
8785                      Make_Handled_Sequence_Of_Statements (Loc,
8786                        Statements => New_List (
8787                          Make_Simple_Return_Statement (Loc,
8788                            Expression => New_Occurrence_Of (BTemp, Loc)))));
8789
8790                --  Insert declaration before freeze node and body after
8791
8792                Insert_Before_And_Analyze (N, FDecl);
8793                Insert_After_And_Analyze  (N, FBody);
8794             end;
8795          end if;
8796
8797          --  See if we have a static predicate. Note that the answer may be
8798          --  yes even if we have an explicit Dynamic_Predicate present.
8799
8800          declare
8801             PS : Boolean;
8802             EN : Node_Id;
8803
8804          begin
8805             if not Is_Scalar_Type (Typ) and then not Is_String_Type (Typ) then
8806                PS := False;
8807             else
8808                PS := Is_Predicate_Static (Expr, Object_Name);
8809             end if;
8810
8811             --  Case where we have a predicate-static aspect
8812
8813             if PS then
8814
8815                --  We don't set Has_Static_Predicate_Aspect, since we can have
8816                --  any of the three cases (Predicate, Dynamic_Predicate, or
8817                --  Static_Predicate) generating a predicate with an expression
8818                --  that is predicate-static. We just indicate that we have a
8819                --  predicate that can be treated as static.
8820
8821                Set_Has_Static_Predicate (Typ);
8822
8823                --  For discrete subtype, build the static predicate list
8824
8825                if Is_Discrete_Type (Typ) then
8826                   Build_Discrete_Static_Predicate (Typ, Expr, Object_Name);
8827
8828                   --  If we don't get a static predicate list, it means that we
8829                   --  have a case where this is not possible, most typically in
8830                   --  the case where we inherit a dynamic predicate. We do not
8831                   --  consider this an error, we just leave the predicate as
8832                   --  dynamic. But if we do succeed in building the list, then
8833                   --  we mark the predicate as static.
8834
8835                   if No (Static_Discrete_Predicate (Typ)) then
8836                      Set_Has_Static_Predicate (Typ, False);
8837                   end if;
8838
8839                --  For real or string subtype, save predicate expression
8840
8841                elsif Is_Real_Type (Typ) or else Is_String_Type (Typ) then
8842                   Set_Static_Real_Or_String_Predicate (Typ, Expr);
8843                end if;
8844
8845             --  Case of dynamic predicate (expression is not predicate-static)
8846
8847             else
8848                --  Again, we don't set Has_Dynamic_Predicate_Aspect, since that
8849                --  is only set if we have an explicit Dynamic_Predicate aspect
8850                --  given. Here we may simply have a Predicate aspect where the
8851                --  expression happens not to be predicate-static.
8852
8853                --  Emit an error when the predicate is categorized as static
8854                --  but its expression is not predicate-static.
8855
8856                --  First a little fiddling to get a nice location for the
8857                --  message. If the expression is of the form (A and then B),
8858                --  where A is an inherited predicate, then use the right
8859                --  operand for the Sloc. This avoids getting confused by a call
8860                --  to an inherited predicate with a less convenient source
8861                --  location.
8862
8863                EN := Expr;
8864                while Nkind (EN) = N_And_Then
8865                  and then Nkind (Left_Opnd (EN)) = N_Function_Call
8866                  and then Is_Predicate_Function
8867                             (Entity (Name (Left_Opnd (EN))))
8868                loop
8869                   EN := Right_Opnd (EN);
8870                end loop;
8871
8872                --  Now post appropriate message
8873
8874                if Has_Static_Predicate_Aspect (Typ) then
8875                   if Is_Scalar_Type (Typ) or else Is_String_Type (Typ) then
8876                      Error_Msg_F
8877                        ("expression is not predicate-static (RM 3.2.4(16-22))",
8878                         EN);
8879                   else
8880                      Error_Msg_F
8881                        ("static predicate requires scalar or string type", EN);
8882                   end if;
8883                end if;
8884             end if;
8885          end;
8886       end if;
8887
8888       Ghost_Mode := Save_Ghost_Mode;
8889    end Build_Predicate_Functions;
8890
8891    ------------------------------------------
8892    -- Build_Predicate_Function_Declaration --
8893    ------------------------------------------
8894
8895    function Build_Predicate_Function_Declaration
8896      (Typ : Entity_Id) return Node_Id
8897    is
8898       Loc : constant Source_Ptr := Sloc (Typ);
8899
8900       Object_Entity : constant Entity_Id :=
8901                         Make_Defining_Identifier (Loc,
8902                           Chars => New_Internal_Name ('I'));
8903
8904       --  The formal parameter of the function
8905
8906       SId : constant Entity_Id :=
8907               Make_Defining_Identifier (Loc,
8908                 Chars => New_External_Name (Chars (Typ), "Predicate"));
8909
8910       --  The entity for the function spec
8911
8912       FDecl : Node_Id;
8913       Spec  : Node_Id;
8914
8915    begin
8916       Spec :=
8917         Make_Function_Specification (Loc,
8918           Defining_Unit_Name       => SId,
8919           Parameter_Specifications => New_List (
8920             Make_Parameter_Specification (Loc,
8921               Defining_Identifier => Object_Entity,
8922               Parameter_Type      => New_Occurrence_Of (Typ, Loc))),
8923           Result_Definition        =>
8924             New_Occurrence_Of (Standard_Boolean, Loc));
8925
8926       FDecl := Make_Subprogram_Declaration (Loc, Specification => Spec);
8927
8928       Set_Ekind (SId, E_Function);
8929       Set_Etype (SId, Standard_Boolean);
8930       Set_Is_Internal (SId);
8931       Set_Is_Predicate_Function (SId);
8932       Set_Predicate_Function (Typ, SId);
8933
8934       Insert_After (Parent (Typ), FDecl);
8935
8936       Analyze (FDecl);
8937
8938       return FDecl;
8939    end Build_Predicate_Function_Declaration;
8940
8941    -----------------------------------------
8942    -- Check_Aspect_At_End_Of_Declarations --
8943    -----------------------------------------
8944
8945    procedure Check_Aspect_At_End_Of_Declarations (ASN : Node_Id) is
8946       Ent   : constant Entity_Id := Entity     (ASN);
8947       Ident : constant Node_Id   := Identifier (ASN);
8948       A_Id  : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
8949
8950       End_Decl_Expr : constant Node_Id := Entity (Ident);
8951       --  Expression to be analyzed at end of declarations
8952
8953       Freeze_Expr : constant Node_Id := Expression (ASN);
8954       --  Expression from call to Check_Aspect_At_Freeze_Point
8955
8956       T : constant Entity_Id := Etype (Freeze_Expr);
8957       --  Type required for preanalyze call
8958
8959       Err : Boolean;
8960       --  Set False if error
8961
8962       --  On entry to this procedure, Entity (Ident) contains a copy of the
8963       --  original expression from the aspect, saved for this purpose, and
8964       --  but Expression (Ident) is a preanalyzed copy of the expression,
8965       --  preanalyzed just after the freeze point.
8966
8967       procedure Check_Overloaded_Name;
8968       --  For aspects whose expression is simply a name, this routine checks if
8969       --  the name is overloaded or not. If so, it verifies there is an
8970       --  interpretation that matches the entity obtained at the freeze point,
8971       --  otherwise the compiler complains.
8972
8973       ---------------------------
8974       -- Check_Overloaded_Name --
8975       ---------------------------
8976
8977       procedure Check_Overloaded_Name is
8978       begin
8979          if not Is_Overloaded (End_Decl_Expr) then
8980             Err := not Is_Entity_Name (End_Decl_Expr)
8981                      or else Entity (End_Decl_Expr) /= Entity (Freeze_Expr);
8982
8983          else
8984             Err := True;
8985
8986             declare
8987                Index : Interp_Index;
8988                It    : Interp;
8989
8990             begin
8991                Get_First_Interp (End_Decl_Expr, Index, It);
8992                while Present (It.Typ) loop
8993                   if It.Nam = Entity (Freeze_Expr) then
8994                      Err := False;
8995                      exit;
8996                   end if;
8997
8998                   Get_Next_Interp (Index, It);
8999                end loop;
9000             end;
9001          end if;
9002       end Check_Overloaded_Name;
9003
9004    --  Start of processing for Check_Aspect_At_End_Of_Declarations
9005
9006    begin
9007       --  In an instance we do not perform the consistency check between freeze
9008       --  point and end of declarations, because it was done already in the
9009       --  analysis of the generic. Furthermore, the delayed analysis of an
9010       --  aspect of the instance may produce spurious errors when the generic
9011       --  is a child unit that references entities in the parent (which might
9012       --  not be in scope at the freeze point of the instance).
9013
9014       if In_Instance then
9015          return;
9016
9017       --  Case of aspects Dimension, Dimension_System and Synchronization
9018
9019       elsif A_Id = Aspect_Synchronization then
9020          return;
9021
9022       --  Case of stream attributes, just have to compare entities. However,
9023       --  the expression is just a name (possibly overloaded), and there may
9024       --  be stream operations declared for unrelated types, so we just need
9025       --  to verify that one of these interpretations is the one available at
9026       --  at the freeze point.
9027
9028       elsif A_Id = Aspect_Input  or else
9029             A_Id = Aspect_Output or else
9030             A_Id = Aspect_Read   or else
9031             A_Id = Aspect_Write
9032       then
9033          Analyze (End_Decl_Expr);
9034          Check_Overloaded_Name;
9035
9036       elsif A_Id = Aspect_Variable_Indexing or else
9037             A_Id = Aspect_Constant_Indexing or else
9038             A_Id = Aspect_Default_Iterator  or else
9039             A_Id = Aspect_Iterator_Element
9040       then
9041          --  Make type unfrozen before analysis, to prevent spurious errors
9042          --  about late attributes.
9043
9044          Set_Is_Frozen (Ent, False);
9045          Analyze (End_Decl_Expr);
9046          Set_Is_Frozen (Ent, True);
9047
9048          --  If the end of declarations comes before any other freeze
9049          --  point, the Freeze_Expr is not analyzed: no check needed.
9050
9051          if Analyzed (Freeze_Expr) and then not In_Instance then
9052             Check_Overloaded_Name;
9053          else
9054             Err := False;
9055          end if;
9056
9057       --  All other cases
9058
9059       else
9060          --  Indicate that the expression comes from an aspect specification,
9061          --  which is used in subsequent analysis even if expansion is off.
9062
9063          Set_Parent (End_Decl_Expr, ASN);
9064
9065          --  In a generic context the aspect expressions have not been
9066          --  preanalyzed, so do it now. There are no conformance checks
9067          --  to perform in this case.
9068
9069          if No (T) then
9070             Check_Aspect_At_Freeze_Point (ASN);
9071             return;
9072
9073          --  The default values attributes may be defined in the private part,
9074          --  and the analysis of the expression may take place when only the
9075          --  partial view is visible. The expression must be scalar, so use
9076          --  the full view to resolve.
9077
9078          elsif (A_Id = Aspect_Default_Value
9079                   or else
9080                 A_Id = Aspect_Default_Component_Value)
9081             and then Is_Private_Type (T)
9082          then
9083             Preanalyze_Spec_Expression (End_Decl_Expr, Full_View (T));
9084
9085          else
9086             Preanalyze_Spec_Expression (End_Decl_Expr, T);
9087          end if;
9088
9089          Err := not Fully_Conformant_Expressions (End_Decl_Expr, Freeze_Expr);
9090       end if;
9091
9092       --  Output error message if error. Force error on aspect specification
9093       --  even if there is an error on the expression itself.
9094
9095       if Err then
9096          Error_Msg_NE
9097            ("!visibility of aspect for& changes after freeze point",
9098             ASN, Ent);
9099          Error_Msg_NE
9100            ("info: & is frozen here, aspects evaluated at this point??",
9101             Freeze_Node (Ent), Ent);
9102       end if;
9103    end Check_Aspect_At_End_Of_Declarations;
9104
9105    ----------------------------------
9106    -- Check_Aspect_At_Freeze_Point --
9107    ----------------------------------
9108
9109    procedure Check_Aspect_At_Freeze_Point (ASN : Node_Id) is
9110       Ident : constant Node_Id := Identifier (ASN);
9111       --  Identifier (use Entity field to save expression)
9112
9113       A_Id : constant Aspect_Id := Get_Aspect_Id (Chars (Ident));
9114
9115       T : Entity_Id := Empty;
9116       --  Type required for preanalyze call
9117
9118    begin
9119       --  On entry to this procedure, Entity (Ident) contains a copy of the
9120       --  original expression from the aspect, saved for this purpose.
9121
9122       --  On exit from this procedure Entity (Ident) is unchanged, still
9123       --  containing that copy, but Expression (Ident) is a preanalyzed copy
9124       --  of the expression, preanalyzed just after the freeze point.
9125
9126       --  Make a copy of the expression to be preanalyzed
9127
9128       Set_Expression (ASN, New_Copy_Tree (Entity (Ident)));
9129
9130       --  Find type for preanalyze call
9131
9132       case A_Id is
9133
9134          --  No_Aspect should be impossible
9135
9136          when No_Aspect =>
9137             raise Program_Error;
9138
9139          --  Aspects taking an optional boolean argument
9140
9141          when Boolean_Aspects      |
9142               Library_Unit_Aspects =>
9143
9144             T := Standard_Boolean;
9145
9146          --  Aspects corresponding to attribute definition clauses
9147
9148          when Aspect_Address =>
9149             T := RTE (RE_Address);
9150
9151          when Aspect_Attach_Handler =>
9152             T := RTE (RE_Interrupt_ID);
9153
9154          when Aspect_Bit_Order | Aspect_Scalar_Storage_Order =>
9155             T := RTE (RE_Bit_Order);
9156
9157          when Aspect_Convention =>
9158             return;
9159
9160          when Aspect_CPU =>
9161             T := RTE (RE_CPU_Range);
9162
9163          --  Default_Component_Value is resolved with the component type
9164
9165          when Aspect_Default_Component_Value =>
9166             T := Component_Type (Entity (ASN));
9167
9168          when Aspect_Default_Storage_Pool =>
9169             T := Class_Wide_Type (RTE (RE_Root_Storage_Pool));
9170
9171          --  Default_Value is resolved with the type entity in question
9172
9173          when Aspect_Default_Value =>
9174             T := Entity (ASN);
9175
9176          when Aspect_Dispatching_Domain =>
9177             T := RTE (RE_Dispatching_Domain);
9178
9179          when Aspect_External_Tag =>
9180             T := Standard_String;
9181
9182          when Aspect_External_Name =>
9183             T := Standard_String;
9184
9185          when Aspect_Link_Name =>
9186             T := Standard_String;
9187
9188          when Aspect_Priority | Aspect_Interrupt_Priority =>
9189             T := Standard_Integer;
9190
9191          when Aspect_Relative_Deadline =>
9192             T := RTE (RE_Time_Span);
9193
9194          when Aspect_Secondary_Stack_Size =>
9195             T := Standard_Integer;
9196
9197          when Aspect_Small =>
9198             T := Universal_Real;
9199
9200          --  For a simple storage pool, we have to retrieve the type of the
9201          --  pool object associated with the aspect's corresponding attribute
9202          --  definition clause.
9203
9204          when Aspect_Simple_Storage_Pool =>
9205             T := Etype (Expression (Aspect_Rep_Item (ASN)));
9206
9207          when Aspect_Storage_Pool =>
9208             T := Class_Wide_Type (RTE (RE_Root_Storage_Pool));
9209
9210          when Aspect_Alignment      |
9211               Aspect_Component_Size |
9212               Aspect_Machine_Radix  |
9213               Aspect_Object_Size    |
9214               Aspect_Size           |
9215               Aspect_Storage_Size   |
9216               Aspect_Stream_Size    |
9217               Aspect_Value_Size     =>
9218             T := Any_Integer;
9219
9220          when Aspect_Linker_Section =>
9221             T := Standard_String;
9222
9223          when Aspect_Synchronization =>
9224             return;
9225
9226          --  Special case, the expression of these aspects is just an entity
9227          --  that does not need any resolution, so just analyze.
9228
9229          when Aspect_Input      |
9230               Aspect_Output     |
9231               Aspect_Read       |
9232               Aspect_Suppress   |
9233               Aspect_Unsuppress |
9234               Aspect_Warnings   |
9235               Aspect_Write      =>
9236             Analyze (Expression (ASN));
9237             return;
9238
9239          --  Same for Iterator aspects, where the expression is a function
9240          --  name. Legality rules are checked separately.
9241
9242          when Aspect_Constant_Indexing |
9243               Aspect_Default_Iterator  |
9244               Aspect_Iterator_Element  |
9245               Aspect_Variable_Indexing =>
9246             Analyze (Expression (ASN));
9247             return;
9248
9249          --  Ditto for Iterable, legality checks in Validate_Iterable_Aspect.
9250
9251          when Aspect_Iterable =>
9252             T := Entity (ASN);
9253
9254             declare
9255                Cursor : constant Entity_Id := Get_Cursor_Type (ASN, T);
9256                Assoc  : Node_Id;
9257                Expr   : Node_Id;
9258
9259             begin
9260                if Cursor = Any_Type then
9261                   return;
9262                end if;
9263
9264                Assoc := First (Component_Associations (Expression (ASN)));
9265                while Present (Assoc) loop
9266                   Expr := Expression (Assoc);
9267                   Analyze (Expr);
9268
9269                   if not Error_Posted (Expr) then
9270                      Resolve_Iterable_Operation
9271                        (Expr, Cursor, T, Chars (First (Choices (Assoc))));
9272                   end if;
9273
9274                   Next (Assoc);
9275                end loop;
9276             end;
9277
9278             return;
9279
9280          --  Invariant/Predicate take boolean expressions
9281
9282          when Aspect_Dynamic_Predicate |
9283               Aspect_Invariant         |
9284               Aspect_Predicate         |
9285               Aspect_Static_Predicate  |
9286               Aspect_Type_Invariant    =>
9287             T := Standard_Boolean;
9288
9289          when Aspect_Predicate_Failure =>
9290             T := Standard_String;
9291
9292          --  Here is the list of aspects that don't require delay analysis
9293
9294          when Aspect_Abstract_State             |
9295               Aspect_Annotate                   |
9296               Aspect_Async_Readers              |
9297               Aspect_Async_Writers              |
9298               Aspect_Constant_After_Elaboration |
9299               Aspect_Contract_Cases             |
9300               Aspect_Default_Initial_Condition  |
9301               Aspect_Depends                    |
9302               Aspect_Dimension                  |
9303               Aspect_Dimension_System           |
9304               Aspect_Effective_Reads            |
9305               Aspect_Effective_Writes           |
9306               Aspect_Extensions_Visible         |
9307               Aspect_Ghost                      |
9308               Aspect_Global                     |
9309               Aspect_Implicit_Dereference       |
9310               Aspect_Initial_Condition          |
9311               Aspect_Initializes                |
9312               Aspect_Max_Queue_Length           |
9313               Aspect_Obsolescent                |
9314               Aspect_Part_Of                    |
9315               Aspect_Post                       |
9316               Aspect_Postcondition              |
9317               Aspect_Pre                        |
9318               Aspect_Precondition               |
9319               Aspect_Refined_Depends            |
9320               Aspect_Refined_Global             |
9321               Aspect_Refined_Post               |
9322               Aspect_Refined_State              |
9323               Aspect_SPARK_Mode                 |
9324               Aspect_Test_Case                  |
9325               Aspect_Unimplemented              |
9326               Aspect_Volatile_Function          =>
9327             raise Program_Error;
9328
9329       end case;
9330
9331       --  Do the preanalyze call
9332
9333       Preanalyze_Spec_Expression (Expression (ASN), T);
9334    end Check_Aspect_At_Freeze_Point;
9335
9336    -----------------------------------
9337    -- Check_Constant_Address_Clause --
9338    -----------------------------------
9339
9340    procedure Check_Constant_Address_Clause
9341      (Expr  : Node_Id;
9342       U_Ent : Entity_Id)
9343    is
9344       procedure Check_At_Constant_Address (Nod : Node_Id);
9345       --  Checks that the given node N represents a name whose 'Address is
9346       --  constant (in the same sense as OK_Constant_Address_Clause, i.e. the
9347       --  address value is the same at the point of declaration of U_Ent and at
9348       --  the time of elaboration of the address clause.
9349
9350       procedure Check_Expr_Constants (Nod : Node_Id);
9351       --  Checks that Nod meets the requirements for a constant address clause
9352       --  in the sense of the enclosing procedure.
9353
9354       procedure Check_List_Constants (Lst : List_Id);
9355       --  Check that all elements of list Lst meet the requirements for a
9356       --  constant address clause in the sense of the enclosing procedure.
9357
9358       -------------------------------
9359       -- Check_At_Constant_Address --
9360       -------------------------------
9361
9362       procedure Check_At_Constant_Address (Nod : Node_Id) is
9363       begin
9364          if Is_Entity_Name (Nod) then
9365             if Present (Address_Clause (Entity ((Nod)))) then
9366                Error_Msg_NE
9367                  ("invalid address clause for initialized object &!",
9368                            Nod, U_Ent);
9369                Error_Msg_NE
9370                  ("address for& cannot" &
9371                     " depend on another address clause! (RM 13.1(22))!",
9372                   Nod, U_Ent);
9373
9374             elsif In_Same_Source_Unit (Entity (Nod), U_Ent)
9375               and then Sloc (U_Ent) < Sloc (Entity (Nod))
9376             then
9377                Error_Msg_NE
9378                  ("invalid address clause for initialized object &!",
9379                   Nod, U_Ent);
9380                Error_Msg_Node_2 := U_Ent;
9381                Error_Msg_NE
9382                  ("\& must be defined before & (RM 13.1(22))!",
9383                   Nod, Entity (Nod));
9384             end if;
9385
9386          elsif Nkind (Nod) = N_Selected_Component then
9387             declare
9388                T : constant Entity_Id := Etype (Prefix (Nod));
9389
9390             begin
9391                if (Is_Record_Type (T)
9392                     and then Has_Discriminants (T))
9393                  or else
9394                   (Is_Access_Type (T)
9395                     and then Is_Record_Type (Designated_Type (T))
9396                     and then Has_Discriminants (Designated_Type (T)))
9397                then
9398                   Error_Msg_NE
9399                     ("invalid address clause for initialized object &!",
9400                      Nod, U_Ent);
9401                   Error_Msg_N
9402                     ("\address cannot depend on component" &
9403                      " of discriminated record (RM 13.1(22))!",
9404                      Nod);
9405                else
9406                   Check_At_Constant_Address (Prefix (Nod));
9407                end if;
9408             end;
9409
9410          elsif Nkind (Nod) = N_Indexed_Component then
9411             Check_At_Constant_Address (Prefix (Nod));
9412             Check_List_Constants (Expressions (Nod));
9413
9414          else
9415             Check_Expr_Constants (Nod);
9416          end if;
9417       end Check_At_Constant_Address;
9418
9419       --------------------------
9420       -- Check_Expr_Constants --
9421       --------------------------
9422
9423       procedure Check_Expr_Constants (Nod : Node_Id) is
9424          Loc_U_Ent : constant Source_Ptr := Sloc (U_Ent);
9425          Ent       : Entity_Id           := Empty;
9426
9427       begin
9428          if Nkind (Nod) in N_Has_Etype
9429            and then Etype (Nod) = Any_Type
9430          then
9431             return;
9432          end if;
9433
9434          case Nkind (Nod) is
9435             when N_Empty | N_Error =>
9436                return;
9437
9438             when N_Identifier | N_Expanded_Name =>
9439                Ent := Entity (Nod);
9440
9441                --  We need to look at the original node if it is different
9442                --  from the node, since we may have rewritten things and
9443                --  substituted an identifier representing the rewrite.
9444
9445                if Original_Node (Nod) /= Nod then
9446                   Check_Expr_Constants (Original_Node (Nod));
9447
9448                   --  If the node is an object declaration without initial
9449                   --  value, some code has been expanded, and the expression
9450                   --  is not constant, even if the constituents might be
9451                   --  acceptable, as in A'Address + offset.
9452
9453                   if Ekind (Ent) = E_Variable
9454                     and then
9455                       Nkind (Declaration_Node (Ent)) = N_Object_Declaration
9456                     and then
9457                       No (Expression (Declaration_Node (Ent)))
9458                   then
9459                      Error_Msg_NE
9460                        ("invalid address clause for initialized object &!",
9461                         Nod, U_Ent);
9462
9463                   --  If entity is constant, it may be the result of expanding
9464                   --  a check. We must verify that its declaration appears
9465                   --  before the object in question, else we also reject the
9466                   --  address clause.
9467
9468                   elsif Ekind (Ent) = E_Constant
9469                     and then In_Same_Source_Unit (Ent, U_Ent)
9470                     and then Sloc (Ent) > Loc_U_Ent
9471                   then
9472                      Error_Msg_NE
9473                        ("invalid address clause for initialized object &!",
9474                         Nod, U_Ent);
9475                   end if;
9476
9477                   return;
9478                end if;
9479
9480                --  Otherwise look at the identifier and see if it is OK
9481
9482                if Ekind_In (Ent, E_Named_Integer, E_Named_Real)
9483                  or else Is_Type (Ent)
9484                then
9485                   return;
9486
9487                elsif Ekind_In (Ent, E_Constant, E_In_Parameter) then
9488
9489                   --  This is the case where we must have Ent defined before
9490                   --  U_Ent. Clearly if they are in different units this
9491                   --  requirement is met since the unit containing Ent is
9492                   --  already processed.
9493
9494                   if not In_Same_Source_Unit (Ent, U_Ent) then
9495                      return;
9496
9497                   --  Otherwise location of Ent must be before the location
9498                   --  of U_Ent, that's what prior defined means.
9499
9500                   elsif Sloc (Ent) < Loc_U_Ent then
9501                      return;
9502
9503                   else
9504                      Error_Msg_NE
9505                        ("invalid address clause for initialized object &!",
9506                         Nod, U_Ent);
9507                      Error_Msg_Node_2 := U_Ent;
9508                      Error_Msg_NE
9509                        ("\& must be defined before & (RM 13.1(22))!",
9510                         Nod, Ent);
9511                   end if;
9512
9513                elsif Nkind (Original_Node (Nod)) = N_Function_Call then
9514                   Check_Expr_Constants (Original_Node (Nod));
9515
9516                else
9517                   Error_Msg_NE
9518                     ("invalid address clause for initialized object &!",
9519                      Nod, U_Ent);
9520
9521                   if Comes_From_Source (Ent) then
9522                      Error_Msg_NE
9523                        ("\reference to variable& not allowed"
9524                           & " (RM 13.1(22))!", Nod, Ent);
9525                   else
9526                      Error_Msg_N
9527                        ("non-static expression not allowed"
9528                           & " (RM 13.1(22))!", Nod);
9529                   end if;
9530                end if;
9531
9532             when N_Integer_Literal   =>
9533
9534                --  If this is a rewritten unchecked conversion, in a system
9535                --  where Address is an integer type, always use the base type
9536                --  for a literal value. This is user-friendly and prevents
9537                --  order-of-elaboration issues with instances of unchecked
9538                --  conversion.
9539
9540                if Nkind (Original_Node (Nod)) = N_Function_Call then
9541                   Set_Etype (Nod, Base_Type (Etype (Nod)));
9542                end if;
9543
9544             when N_Real_Literal      |
9545                  N_String_Literal    |
9546                  N_Character_Literal =>
9547                return;
9548
9549             when N_Range =>
9550                Check_Expr_Constants (Low_Bound (Nod));
9551                Check_Expr_Constants (High_Bound (Nod));
9552
9553             when N_Explicit_Dereference =>
9554                Check_Expr_Constants (Prefix (Nod));
9555
9556             when N_Indexed_Component =>
9557                Check_Expr_Constants (Prefix (Nod));
9558                Check_List_Constants (Expressions (Nod));
9559
9560             when N_Slice =>
9561                Check_Expr_Constants (Prefix (Nod));
9562                Check_Expr_Constants (Discrete_Range (Nod));
9563
9564             when N_Selected_Component =>
9565                Check_Expr_Constants (Prefix (Nod));
9566
9567             when N_Attribute_Reference =>
9568                if Nam_In (Attribute_Name (Nod), Name_Address,
9569                                                 Name_Access,
9570                                                 Name_Unchecked_Access,
9571                                                 Name_Unrestricted_Access)
9572                then
9573                   Check_At_Constant_Address (Prefix (Nod));
9574
9575                else
9576                   Check_Expr_Constants (Prefix (Nod));
9577                   Check_List_Constants (Expressions (Nod));
9578                end if;
9579
9580             when N_Aggregate =>
9581                Check_List_Constants (Component_Associations (Nod));
9582                Check_List_Constants (Expressions (Nod));
9583
9584             when N_Component_Association =>
9585                Check_Expr_Constants (Expression (Nod));
9586
9587             when N_Extension_Aggregate =>
9588                Check_Expr_Constants (Ancestor_Part (Nod));
9589                Check_List_Constants (Component_Associations (Nod));
9590                Check_List_Constants (Expressions (Nod));
9591
9592             when N_Null =>
9593                return;
9594
9595             when N_Binary_Op | N_Short_Circuit | N_Membership_Test =>
9596                Check_Expr_Constants (Left_Opnd (Nod));
9597                Check_Expr_Constants (Right_Opnd (Nod));
9598
9599             when N_Unary_Op =>
9600                Check_Expr_Constants (Right_Opnd (Nod));
9601
9602             when N_Type_Conversion           |
9603                  N_Qualified_Expression      |
9604                  N_Allocator                 |
9605                  N_Unchecked_Type_Conversion =>
9606                Check_Expr_Constants (Expression (Nod));
9607
9608             when N_Function_Call =>
9609                if not Is_Pure (Entity (Name (Nod))) then
9610                   Error_Msg_NE
9611                     ("invalid address clause for initialized object &!",
9612                      Nod, U_Ent);
9613
9614                   Error_Msg_NE
9615                     ("\function & is not pure (RM 13.1(22))!",
9616                      Nod, Entity (Name (Nod)));
9617
9618                else
9619                   Check_List_Constants (Parameter_Associations (Nod));
9620                end if;
9621
9622             when N_Parameter_Association =>
9623                Check_Expr_Constants (Explicit_Actual_Parameter (Nod));
9624
9625             when others =>
9626                Error_Msg_NE
9627                  ("invalid address clause for initialized object &!",
9628                   Nod, U_Ent);
9629                Error_Msg_NE
9630                  ("\must be constant defined before& (RM 13.1(22))!",
9631                   Nod, U_Ent);
9632          end case;
9633       end Check_Expr_Constants;
9634
9635       --------------------------
9636       -- Check_List_Constants --
9637       --------------------------
9638
9639       procedure Check_List_Constants (Lst : List_Id) is
9640          Nod1 : Node_Id;
9641
9642       begin
9643          if Present (Lst) then
9644             Nod1 := First (Lst);
9645             while Present (Nod1) loop
9646                Check_Expr_Constants (Nod1);
9647                Next (Nod1);
9648             end loop;
9649          end if;
9650       end Check_List_Constants;
9651
9652    --  Start of processing for Check_Constant_Address_Clause
9653
9654    begin
9655       --  If rep_clauses are to be ignored, no need for legality checks. In
9656       --  particular, no need to pester user about rep clauses that violate the
9657       --  rule on constant addresses, given that these clauses will be removed
9658       --  by Freeze before they reach the back end. Similarly in CodePeer mode,
9659       --  we want to relax these checks.
9660
9661       if not Ignore_Rep_Clauses and not CodePeer_Mode then
9662          Check_Expr_Constants (Expr);
9663       end if;
9664    end Check_Constant_Address_Clause;
9665
9666    ---------------------------
9667    -- Check_Pool_Size_Clash --
9668    ---------------------------
9669
9670    procedure Check_Pool_Size_Clash (Ent : Entity_Id; SP, SS : Node_Id) is
9671       Post : Node_Id;
9672
9673    begin
9674       --  We need to find out which one came first. Note that in the case of
9675       --  aspects mixed with pragmas there are cases where the processing order
9676       --  is reversed, which is why we do the check here.
9677
9678       if Sloc (SP) < Sloc (SS) then
9679          Error_Msg_Sloc := Sloc (SP);
9680          Post := SS;
9681          Error_Msg_NE ("Storage_Pool previously given for&#", Post, Ent);
9682
9683       else
9684          Error_Msg_Sloc := Sloc (SS);
9685          Post := SP;
9686          Error_Msg_NE ("Storage_Size previously given for&#", Post, Ent);
9687       end if;
9688
9689       Error_Msg_N
9690         ("\cannot have Storage_Size and Storage_Pool (RM 13.11(3))", Post);
9691    end Check_Pool_Size_Clash;
9692
9693    ----------------------------------------
9694    -- Check_Record_Representation_Clause --
9695    ----------------------------------------
9696
9697    procedure Check_Record_Representation_Clause (N : Node_Id) is
9698       Loc     : constant Source_Ptr := Sloc (N);
9699       Ident   : constant Node_Id    := Identifier (N);
9700       Rectype : Entity_Id;
9701       Fent    : Entity_Id;
9702       CC      : Node_Id;
9703       Fbit    : Uint;
9704       Lbit    : Uint;
9705       Hbit    : Uint := Uint_0;
9706       Comp    : Entity_Id;
9707       Pcomp   : Entity_Id;
9708
9709       Max_Bit_So_Far : Uint;
9710       --  Records the maximum bit position so far. If all field positions
9711       --  are monotonically increasing, then we can skip the circuit for
9712       --  checking for overlap, since no overlap is possible.
9713
9714       Tagged_Parent : Entity_Id := Empty;
9715       --  This is set in the case of a derived tagged type for which we have
9716       --  Is_Fully_Repped_Tagged_Type True (indicating that all components are
9717       --  positioned by record representation clauses). In this case we must
9718       --  check for overlap between components of this tagged type, and the
9719       --  components of its parent. Tagged_Parent will point to this parent
9720       --  type. For all other cases Tagged_Parent is left set to Empty.
9721
9722       Parent_Last_Bit : Uint;
9723       --  Relevant only if Tagged_Parent is set, Parent_Last_Bit indicates the
9724       --  last bit position for any field in the parent type. We only need to
9725       --  check overlap for fields starting below this point.
9726
9727       Overlap_Check_Required : Boolean;
9728       --  Used to keep track of whether or not an overlap check is required
9729
9730       Overlap_Detected : Boolean := False;
9731       --  Set True if an overlap is detected
9732
9733       Ccount : Natural := 0;
9734       --  Number of component clauses in record rep clause
9735
9736       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id);
9737       --  Given two entities for record components or discriminants, checks
9738       --  if they have overlapping component clauses and issues errors if so.
9739
9740       procedure Find_Component;
9741       --  Finds component entity corresponding to current component clause (in
9742       --  CC), and sets Comp to the entity, and Fbit/Lbit to the zero origin
9743       --  start/stop bits for the field. If there is no matching component or
9744       --  if the matching component does not have a component clause, then
9745       --  that's an error and Comp is set to Empty, but no error message is
9746       --  issued, since the message was already given. Comp is also set to
9747       --  Empty if the current "component clause" is in fact a pragma.
9748
9749       -----------------------------
9750       -- Check_Component_Overlap --
9751       -----------------------------
9752
9753       procedure Check_Component_Overlap (C1_Ent, C2_Ent : Entity_Id) is
9754          CC1 : constant Node_Id := Component_Clause (C1_Ent);
9755          CC2 : constant Node_Id := Component_Clause (C2_Ent);
9756
9757       begin
9758          if Present (CC1) and then Present (CC2) then
9759
9760             --  Exclude odd case where we have two tag components in the same
9761             --  record, both at location zero. This seems a bit strange, but
9762             --  it seems to happen in some circumstances, perhaps on an error.
9763
9764             if Nam_In (Chars (C1_Ent), Name_uTag, Name_uTag) then
9765                return;
9766             end if;
9767
9768             --  Here we check if the two fields overlap
9769
9770             declare
9771                S1 : constant Uint := Component_Bit_Offset (C1_Ent);
9772                S2 : constant Uint := Component_Bit_Offset (C2_Ent);
9773                E1 : constant Uint := S1 + Esize (C1_Ent);
9774                E2 : constant Uint := S2 + Esize (C2_Ent);
9775
9776             begin
9777                if E2 <= S1 or else E1 <= S2 then
9778                   null;
9779                else
9780                   Error_Msg_Node_2 := Component_Name (CC2);
9781                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
9782                   Error_Msg_Node_1 := Component_Name (CC1);
9783                   Error_Msg_N
9784                     ("component& overlaps & #", Component_Name (CC1));
9785                   Overlap_Detected := True;
9786                end if;
9787             end;
9788          end if;
9789       end Check_Component_Overlap;
9790
9791       --------------------
9792       -- Find_Component --
9793       --------------------
9794
9795       procedure Find_Component is
9796
9797          procedure Search_Component (R : Entity_Id);
9798          --  Search components of R for a match. If found, Comp is set
9799
9800          ----------------------
9801          -- Search_Component --
9802          ----------------------
9803
9804          procedure Search_Component (R : Entity_Id) is
9805          begin
9806             Comp := First_Component_Or_Discriminant (R);
9807             while Present (Comp) loop
9808
9809                --  Ignore error of attribute name for component name (we
9810                --  already gave an error message for this, so no need to
9811                --  complain here)
9812
9813                if Nkind (Component_Name (CC)) = N_Attribute_Reference then
9814                   null;
9815                else
9816                   exit when Chars (Comp) = Chars (Component_Name (CC));
9817                end if;
9818
9819                Next_Component_Or_Discriminant (Comp);
9820             end loop;
9821          end Search_Component;
9822
9823       --  Start of processing for Find_Component
9824
9825       begin
9826          --  Return with Comp set to Empty if we have a pragma
9827
9828          if Nkind (CC) = N_Pragma then
9829             Comp := Empty;
9830             return;
9831          end if;
9832
9833          --  Search current record for matching component
9834
9835          Search_Component (Rectype);
9836
9837          --  If not found, maybe component of base type discriminant that is
9838          --  absent from statically constrained first subtype.
9839
9840          if No (Comp) then
9841             Search_Component (Base_Type (Rectype));
9842          end if;
9843
9844          --  If no component, or the component does not reference the component
9845          --  clause in question, then there was some previous error for which
9846          --  we already gave a message, so just return with Comp Empty.
9847
9848          if No (Comp) or else Component_Clause (Comp) /= CC then
9849             Check_Error_Detected;
9850             Comp := Empty;
9851
9852          --  Normal case where we have a component clause
9853
9854          else
9855             Fbit := Component_Bit_Offset (Comp);
9856             Lbit := Fbit + Esize (Comp) - 1;
9857          end if;
9858       end Find_Component;
9859
9860    --  Start of processing for Check_Record_Representation_Clause
9861
9862    begin
9863       Find_Type (Ident);
9864       Rectype := Entity (Ident);
9865
9866       if Rectype = Any_Type then
9867          return;
9868       else
9869          Rectype := Underlying_Type (Rectype);
9870       end if;
9871
9872       --  See if we have a fully repped derived tagged type
9873
9874       declare
9875          PS : constant Entity_Id := Parent_Subtype (Rectype);
9876
9877       begin
9878          if Present (PS) and then Is_Fully_Repped_Tagged_Type (PS) then
9879             Tagged_Parent := PS;
9880
9881             --  Find maximum bit of any component of the parent type
9882
9883             Parent_Last_Bit := UI_From_Int (System_Address_Size - 1);
9884             Pcomp := First_Entity (Tagged_Parent);
9885             while Present (Pcomp) loop
9886                if Ekind_In (Pcomp, E_Discriminant, E_Component) then
9887                   if Component_Bit_Offset (Pcomp) /= No_Uint
9888                     and then Known_Static_Esize (Pcomp)
9889                   then
9890                      Parent_Last_Bit :=
9891                        UI_Max
9892                          (Parent_Last_Bit,
9893                           Component_Bit_Offset (Pcomp) + Esize (Pcomp) - 1);
9894                   end if;
9895                else
9896
9897                   --  Skip anonymous types generated for constrained array
9898                   --  or record components.
9899
9900                   null;
9901                end if;
9902
9903                Next_Entity (Pcomp);
9904             end loop;
9905          end if;
9906       end;
9907
9908       --  All done if no component clauses
9909
9910       CC := First (Component_Clauses (N));
9911
9912       if No (CC) then
9913          return;
9914       end if;
9915
9916       --  If a tag is present, then create a component clause that places it
9917       --  at the start of the record (otherwise gigi may place it after other
9918       --  fields that have rep clauses).
9919
9920       Fent := First_Entity (Rectype);
9921
9922       if Nkind (Fent) = N_Defining_Identifier
9923         and then Chars (Fent) = Name_uTag
9924       then
9925          Set_Component_Bit_Offset    (Fent, Uint_0);
9926          Set_Normalized_Position     (Fent, Uint_0);
9927          Set_Normalized_First_Bit    (Fent, Uint_0);
9928          Set_Normalized_Position_Max (Fent, Uint_0);
9929          Init_Esize                  (Fent, System_Address_Size);
9930
9931          Set_Component_Clause (Fent,
9932            Make_Component_Clause (Loc,
9933              Component_Name => Make_Identifier (Loc, Name_uTag),
9934
9935              Position  => Make_Integer_Literal (Loc, Uint_0),
9936              First_Bit => Make_Integer_Literal (Loc, Uint_0),
9937              Last_Bit  =>
9938                Make_Integer_Literal (Loc,
9939                  UI_From_Int (System_Address_Size))));
9940
9941          Ccount := Ccount + 1;
9942       end if;
9943
9944       Max_Bit_So_Far := Uint_Minus_1;
9945       Overlap_Check_Required := False;
9946
9947       --  Process the component clauses
9948
9949       while Present (CC) loop
9950          Find_Component;
9951
9952          if Present (Comp) then
9953             Ccount := Ccount + 1;
9954
9955             --  We need a full overlap check if record positions non-monotonic
9956
9957             if Fbit <= Max_Bit_So_Far then
9958                Overlap_Check_Required := True;
9959             end if;
9960
9961             Max_Bit_So_Far := Lbit;
9962
9963             --  Check bit position out of range of specified size
9964
9965             if Has_Size_Clause (Rectype)
9966               and then RM_Size (Rectype) <= Lbit
9967             then
9968                Error_Msg_N
9969                  ("bit number out of range of specified size",
9970                   Last_Bit (CC));
9971
9972                --  Check for overlap with tag component
9973
9974             else
9975                if Is_Tagged_Type (Rectype)
9976                  and then Fbit < System_Address_Size
9977                then
9978                   Error_Msg_NE
9979                     ("component overlaps tag field of&",
9980                      Component_Name (CC), Rectype);
9981                   Overlap_Detected := True;
9982                end if;
9983
9984                if Hbit < Lbit then
9985                   Hbit := Lbit;
9986                end if;
9987             end if;
9988
9989             --  Check parent overlap if component might overlap parent field
9990
9991             if Present (Tagged_Parent) and then Fbit <= Parent_Last_Bit then
9992                Pcomp := First_Component_Or_Discriminant (Tagged_Parent);
9993                while Present (Pcomp) loop
9994                   if not Is_Tag (Pcomp)
9995                     and then Chars (Pcomp) /= Name_uParent
9996                   then
9997                      Check_Component_Overlap (Comp, Pcomp);
9998                   end if;
9999
10000                   Next_Component_Or_Discriminant (Pcomp);
10001                end loop;
10002             end if;
10003          end if;
10004
10005          Next (CC);
10006       end loop;
10007
10008       --  Now that we have processed all the component clauses, check for
10009       --  overlap. We have to leave this till last, since the components can
10010       --  appear in any arbitrary order in the representation clause.
10011
10012       --  We do not need this check if all specified ranges were monotonic,
10013       --  as recorded by Overlap_Check_Required being False at this stage.
10014
10015       --  This first section checks if there are any overlapping entries at
10016       --  all. It does this by sorting all entries and then seeing if there are
10017       --  any overlaps. If there are none, then that is decisive, but if there
10018       --  are overlaps, they may still be OK (they may result from fields in
10019       --  different variants).
10020
10021       if Overlap_Check_Required then
10022          Overlap_Check1 : declare
10023
10024             OC_Fbit : array (0 .. Ccount) of Uint;
10025             --  First-bit values for component clauses, the value is the offset
10026             --  of the first bit of the field from start of record. The zero
10027             --  entry is for use in sorting.
10028
10029             OC_Lbit : array (0 .. Ccount) of Uint;
10030             --  Last-bit values for component clauses, the value is the offset
10031             --  of the last bit of the field from start of record. The zero
10032             --  entry is for use in sorting.
10033
10034             OC_Count : Natural := 0;
10035             --  Count of entries in OC_Fbit and OC_Lbit
10036
10037             function OC_Lt (Op1, Op2 : Natural) return Boolean;
10038             --  Compare routine for Sort
10039
10040             procedure OC_Move (From : Natural; To : Natural);
10041             --  Move routine for Sort
10042
10043             package Sorting is new GNAT.Heap_Sort_G (OC_Move, OC_Lt);
10044
10045             -----------
10046             -- OC_Lt --
10047             -----------
10048
10049             function OC_Lt (Op1, Op2 : Natural) return Boolean is
10050             begin
10051                return OC_Fbit (Op1) < OC_Fbit (Op2);
10052             end OC_Lt;
10053
10054             -------------
10055             -- OC_Move --
10056             -------------
10057
10058             procedure OC_Move (From : Natural; To : Natural) is
10059             begin
10060                OC_Fbit (To) := OC_Fbit (From);
10061                OC_Lbit (To) := OC_Lbit (From);
10062             end OC_Move;
10063
10064             --  Start of processing for Overlap_Check
10065
10066          begin
10067             CC := First (Component_Clauses (N));
10068             while Present (CC) loop
10069
10070                --  Exclude component clause already marked in error
10071
10072                if not Error_Posted (CC) then
10073                   Find_Component;
10074
10075                   if Present (Comp) then
10076                      OC_Count := OC_Count + 1;
10077                      OC_Fbit (OC_Count) := Fbit;
10078                      OC_Lbit (OC_Count) := Lbit;
10079                   end if;
10080                end if;
10081
10082                Next (CC);
10083             end loop;
10084
10085             Sorting.Sort (OC_Count);
10086
10087             Overlap_Check_Required := False;
10088             for J in 1 .. OC_Count - 1 loop
10089                if OC_Lbit (J) >= OC_Fbit (J + 1) then
10090                   Overlap_Check_Required := True;
10091                   exit;
10092                end if;
10093             end loop;
10094          end Overlap_Check1;
10095       end if;
10096
10097       --  If Overlap_Check_Required is still True, then we have to do the full
10098       --  scale overlap check, since we have at least two fields that do
10099       --  overlap, and we need to know if that is OK since they are in
10100       --  different variant, or whether we have a definite problem.
10101
10102       if Overlap_Check_Required then
10103          Overlap_Check2 : declare
10104             C1_Ent, C2_Ent : Entity_Id;
10105             --  Entities of components being checked for overlap
10106
10107             Clist : Node_Id;
10108             --  Component_List node whose Component_Items are being checked
10109
10110             Citem : Node_Id;
10111             --  Component declaration for component being checked
10112
10113          begin
10114             C1_Ent := First_Entity (Base_Type (Rectype));
10115
10116             --  Loop through all components in record. For each component check
10117             --  for overlap with any of the preceding elements on the component
10118             --  list containing the component and also, if the component is in
10119             --  a variant, check against components outside the case structure.
10120             --  This latter test is repeated recursively up the variant tree.
10121
10122             Main_Component_Loop : while Present (C1_Ent) loop
10123                if not Ekind_In (C1_Ent, E_Component, E_Discriminant) then
10124                   goto Continue_Main_Component_Loop;
10125                end if;
10126
10127                --  Skip overlap check if entity has no declaration node. This
10128                --  happens with discriminants in constrained derived types.
10129                --  Possibly we are missing some checks as a result, but that
10130                --  does not seem terribly serious.
10131
10132                if No (Declaration_Node (C1_Ent)) then
10133                   goto Continue_Main_Component_Loop;
10134                end if;
10135
10136                Clist := Parent (List_Containing (Declaration_Node (C1_Ent)));
10137
10138                --  Loop through component lists that need checking. Check the
10139                --  current component list and all lists in variants above us.
10140
10141                Component_List_Loop : loop
10142
10143                   --  If derived type definition, go to full declaration
10144                   --  If at outer level, check discriminants if there are any.
10145
10146                   if Nkind (Clist) = N_Derived_Type_Definition then
10147                      Clist := Parent (Clist);
10148                   end if;
10149
10150                   --  Outer level of record definition, check discriminants
10151
10152                   if Nkind_In (Clist, N_Full_Type_Declaration,
10153                                       N_Private_Type_Declaration)
10154                   then
10155                      if Has_Discriminants (Defining_Identifier (Clist)) then
10156                         C2_Ent :=
10157                           First_Discriminant (Defining_Identifier (Clist));
10158                         while Present (C2_Ent) loop
10159                            exit when C1_Ent = C2_Ent;
10160                            Check_Component_Overlap (C1_Ent, C2_Ent);
10161                            Next_Discriminant (C2_Ent);
10162                         end loop;
10163                      end if;
10164
10165                      --  Record extension case
10166
10167                   elsif Nkind (Clist) = N_Derived_Type_Definition then
10168                      Clist := Empty;
10169
10170                      --  Otherwise check one component list
10171
10172                   else
10173                      Citem := First (Component_Items (Clist));
10174                      while Present (Citem) loop
10175                         if Nkind (Citem) = N_Component_Declaration then
10176                            C2_Ent := Defining_Identifier (Citem);
10177                            exit when C1_Ent = C2_Ent;
10178                            Check_Component_Overlap (C1_Ent, C2_Ent);
10179                         end if;
10180
10181                         Next (Citem);
10182                      end loop;
10183                   end if;
10184
10185                   --  Check for variants above us (the parent of the Clist can
10186                   --  be a variant, in which case its parent is a variant part,
10187                   --  and the parent of the variant part is a component list
10188                   --  whose components must all be checked against the current
10189                   --  component for overlap).
10190
10191                   if Nkind (Parent (Clist)) = N_Variant then
10192                      Clist := Parent (Parent (Parent (Clist)));
10193
10194                      --  Check for possible discriminant part in record, this
10195                      --  is treated essentially as another level in the
10196                      --  recursion. For this case the parent of the component
10197                      --  list is the record definition, and its parent is the
10198                      --  full type declaration containing the discriminant
10199                      --  specifications.
10200
10201                   elsif Nkind (Parent (Clist)) = N_Record_Definition then
10202                      Clist := Parent (Parent ((Clist)));
10203
10204                      --  If neither of these two cases, we are at the top of
10205                      --  the tree.
10206
10207                   else
10208                      exit Component_List_Loop;
10209                   end if;
10210                end loop Component_List_Loop;
10211
10212                <<Continue_Main_Component_Loop>>
10213                Next_Entity (C1_Ent);
10214
10215             end loop Main_Component_Loop;
10216          end Overlap_Check2;
10217       end if;
10218
10219       --  The following circuit deals with warning on record holes (gaps). We
10220       --  skip this check if overlap was detected, since it makes sense for the
10221       --  programmer to fix this illegality before worrying about warnings.
10222
10223       if not Overlap_Detected and Warn_On_Record_Holes then
10224          Record_Hole_Check : declare
10225             Decl : constant Node_Id := Declaration_Node (Base_Type (Rectype));
10226             --  Full declaration of record type
10227
10228             procedure Check_Component_List
10229               (CL   : Node_Id;
10230                Sbit : Uint;
10231                DS   : List_Id);
10232             --  Check component list CL for holes. The starting bit should be
10233             --  Sbit. which is zero for the main record component list and set
10234             --  appropriately for recursive calls for variants. DS is set to
10235             --  a list of discriminant specifications to be included in the
10236             --  consideration of components. It is No_List if none to consider.
10237
10238             --------------------------
10239             -- Check_Component_List --
10240             --------------------------
10241
10242             procedure Check_Component_List
10243               (CL   : Node_Id;
10244                Sbit : Uint;
10245                DS   : List_Id)
10246             is
10247                Compl : Integer;
10248
10249             begin
10250                Compl := Integer (List_Length (Component_Items (CL)));
10251
10252                if DS /= No_List then
10253                   Compl := Compl + Integer (List_Length (DS));
10254                end if;
10255
10256                declare
10257                   Comps : array (Natural range 0 .. Compl) of Entity_Id;
10258                   --  Gather components (zero entry is for sort routine)
10259
10260                   Ncomps : Natural := 0;
10261                   --  Number of entries stored in Comps (starting at Comps (1))
10262
10263                   Citem : Node_Id;
10264                   --  One component item or discriminant specification
10265
10266                   Nbit  : Uint;
10267                   --  Starting bit for next component
10268
10269                   CEnt  : Entity_Id;
10270                   --  Component entity
10271
10272                   Variant : Node_Id;
10273                   --  One variant
10274
10275                   function Lt (Op1, Op2 : Natural) return Boolean;
10276                   --  Compare routine for Sort
10277
10278                   procedure Move (From : Natural; To : Natural);
10279                   --  Move routine for Sort
10280
10281                   package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
10282
10283                   --------
10284                   -- Lt --
10285                   --------
10286
10287                   function Lt (Op1, Op2 : Natural) return Boolean is
10288                   begin
10289                      return Component_Bit_Offset (Comps (Op1))
10290                        <
10291                        Component_Bit_Offset (Comps (Op2));
10292                   end Lt;
10293
10294                   ----------
10295                   -- Move --
10296                   ----------
10297
10298                   procedure Move (From : Natural; To : Natural) is
10299                   begin
10300                      Comps (To) := Comps (From);
10301                   end Move;
10302
10303                begin
10304                   --  Gather discriminants into Comp
10305
10306                   if DS /= No_List then
10307                      Citem := First (DS);
10308                      while Present (Citem) loop
10309                         if Nkind (Citem) = N_Discriminant_Specification then
10310                            declare
10311                               Ent : constant Entity_Id :=
10312                                       Defining_Identifier (Citem);
10313                            begin
10314                               if Ekind (Ent) = E_Discriminant then
10315                                  Ncomps := Ncomps + 1;
10316                                  Comps (Ncomps) := Ent;
10317                               end if;
10318                            end;
10319                         end if;
10320
10321                         Next (Citem);
10322                      end loop;
10323                   end if;
10324
10325                   --  Gather component entities into Comp
10326
10327                   Citem := First (Component_Items (CL));
10328                   while Present (Citem) loop
10329                      if Nkind (Citem) = N_Component_Declaration then
10330                         Ncomps := Ncomps + 1;
10331                         Comps (Ncomps) := Defining_Identifier (Citem);
10332                      end if;
10333
10334                      Next (Citem);
10335                   end loop;
10336
10337                   --  Now sort the component entities based on the first bit.
10338                   --  Note we already know there are no overlapping components.
10339
10340                   Sorting.Sort (Ncomps);
10341
10342                   --  Loop through entries checking for holes
10343
10344                   Nbit := Sbit;
10345                   for J in 1 .. Ncomps loop
10346                      CEnt := Comps (J);
10347                      Error_Msg_Uint_1 := Component_Bit_Offset (CEnt) - Nbit;
10348
10349                      if Error_Msg_Uint_1 > 0 then
10350                         Error_Msg_NE
10351                           ("?H?^-bit gap before component&",
10352                            Component_Name (Component_Clause (CEnt)), CEnt);
10353                      end if;
10354
10355                      Nbit := Component_Bit_Offset (CEnt) + Esize (CEnt);
10356                   end loop;
10357
10358                   --  Process variant parts recursively if present
10359
10360                   if Present (Variant_Part (CL)) then
10361                      Variant := First (Variants (Variant_Part (CL)));
10362                      while Present (Variant) loop
10363                         Check_Component_List
10364                           (Component_List (Variant), Nbit, No_List);
10365                         Next (Variant);
10366                      end loop;
10367                   end if;
10368                end;
10369             end Check_Component_List;
10370
10371          --  Start of processing for Record_Hole_Check
10372
10373          begin
10374             declare
10375                Sbit : Uint;
10376
10377             begin
10378                if Is_Tagged_Type (Rectype) then
10379                   Sbit := UI_From_Int (System_Address_Size);
10380                else
10381                   Sbit := Uint_0;
10382                end if;
10383
10384                if Nkind (Decl) = N_Full_Type_Declaration
10385                  and then Nkind (Type_Definition (Decl)) = N_Record_Definition
10386                then
10387                   Check_Component_List
10388                     (Component_List (Type_Definition (Decl)),
10389                      Sbit,
10390                      Discriminant_Specifications (Decl));
10391                end if;
10392             end;
10393          end Record_Hole_Check;
10394       end if;
10395
10396       --  For records that have component clauses for all components, and whose
10397       --  size is less than or equal to 32, we need to know the size in the
10398       --  front end to activate possible packed array processing where the
10399       --  component type is a record.
10400
10401       --  At this stage Hbit + 1 represents the first unused bit from all the
10402       --  component clauses processed, so if the component clauses are
10403       --  complete, then this is the length of the record.
10404
10405       --  For records longer than System.Storage_Unit, and for those where not
10406       --  all components have component clauses, the back end determines the
10407       --  length (it may for example be appropriate to round up the size
10408       --  to some convenient boundary, based on alignment considerations, etc).
10409
10410       if Unknown_RM_Size (Rectype) and then Hbit + 1 <= 32 then
10411
10412          --  Nothing to do if at least one component has no component clause
10413
10414          Comp := First_Component_Or_Discriminant (Rectype);
10415          while Present (Comp) loop
10416             exit when No (Component_Clause (Comp));
10417             Next_Component_Or_Discriminant (Comp);
10418          end loop;
10419
10420          --  If we fall out of loop, all components have component clauses
10421          --  and so we can set the size to the maximum value.
10422
10423          if No (Comp) then
10424             Set_RM_Size (Rectype, Hbit + 1);
10425          end if;
10426       end if;
10427    end Check_Record_Representation_Clause;
10428
10429    ----------------
10430    -- Check_Size --
10431    ----------------
10432
10433    procedure Check_Size
10434      (N      : Node_Id;
10435       T      : Entity_Id;
10436       Siz    : Uint;
10437       Biased : out Boolean)
10438    is
10439       procedure Size_Too_Small_Error (Min_Siz : Uint);
10440       --  Emit an error concerning illegal size Siz. Min_Siz denotes the
10441       --  minimum size.
10442
10443       --------------------------
10444       -- Size_Too_Small_Error --
10445       --------------------------
10446
10447       procedure Size_Too_Small_Error (Min_Siz : Uint) is
10448       begin
10449          --  This error is suppressed in ASIS mode to allow for different ASIS
10450          --  back ends or ASIS-based tools to query the illegal clause.
10451
10452          if not ASIS_Mode then
10453             Error_Msg_Uint_1 := Min_Siz;
10454             Error_Msg_NE ("size for& too small, minimum allowed is ^", N, T);
10455          end if;
10456       end Size_Too_Small_Error;
10457
10458       --  Local variables
10459
10460       UT : constant Entity_Id := Underlying_Type (T);
10461       M  : Uint;
10462
10463    --  Start of processing for Check_Size
10464
10465    begin
10466       Biased := False;
10467
10468       --  Reject patently improper size values
10469
10470       if Is_Elementary_Type (T)
10471         and then Siz > UI_From_Int (Int'Last)
10472       then
10473          Error_Msg_N ("Size value too large for elementary type", N);
10474
10475          if Nkind (Original_Node (N)) = N_Op_Expon then
10476             Error_Msg_N
10477               ("\maybe '* was meant, rather than '*'*", Original_Node (N));
10478          end if;
10479       end if;
10480
10481       --  Dismiss generic types
10482
10483       if Is_Generic_Type (T)
10484            or else
10485          Is_Generic_Type (UT)
10486            or else
10487          Is_Generic_Type (Root_Type (UT))
10488       then
10489          return;
10490
10491       --  Guard against previous errors
10492
10493       elsif No (UT) or else UT = Any_Type then
10494          Check_Error_Detected;
10495          return;
10496
10497       --  Check case of bit packed array
10498
10499       elsif Is_Array_Type (UT)
10500         and then Known_Static_Component_Size (UT)
10501         and then Is_Bit_Packed_Array (UT)
10502       then
10503          declare
10504             Asiz : Uint;
10505             Indx : Node_Id;
10506             Ityp : Entity_Id;
10507
10508          begin
10509             Asiz := Component_Size (UT);
10510             Indx := First_Index (UT);
10511             loop
10512                Ityp := Etype (Indx);
10513
10514                --  If non-static bound, then we are not in the business of
10515                --  trying to check the length, and indeed an error will be
10516                --  issued elsewhere, since sizes of non-static array types
10517                --  cannot be set implicitly or explicitly.
10518
10519                if not Is_OK_Static_Subtype (Ityp) then
10520                   return;
10521                end if;
10522
10523                --  Otherwise accumulate next dimension
10524
10525                Asiz := Asiz * (Expr_Value (Type_High_Bound (Ityp)) -
10526                                Expr_Value (Type_Low_Bound  (Ityp)) +
10527                                Uint_1);
10528
10529                Next_Index (Indx);
10530                exit when No (Indx);
10531             end loop;
10532
10533             if Asiz <= Siz then
10534                return;
10535
10536             else
10537                Size_Too_Small_Error (Asiz);
10538                Set_Esize   (T, Asiz);
10539                Set_RM_Size (T, Asiz);
10540             end if;
10541          end;
10542
10543       --  All other composite types are ignored
10544
10545       elsif Is_Composite_Type (UT) then
10546          return;
10547
10548       --  For fixed-point types, don't check minimum if type is not frozen,
10549       --  since we don't know all the characteristics of the type that can
10550       --  affect the size (e.g. a specified small) till freeze time.
10551
10552       elsif Is_Fixed_Point_Type (UT) and then not Is_Frozen (UT) then
10553          null;
10554
10555       --  Cases for which a minimum check is required
10556
10557       else
10558          --  Ignore if specified size is correct for the type
10559
10560          if Known_Esize (UT) and then Siz = Esize (UT) then
10561             return;
10562          end if;
10563
10564          --  Otherwise get minimum size
10565
10566          M := UI_From_Int (Minimum_Size (UT));
10567
10568          if Siz < M then
10569
10570             --  Size is less than minimum size, but one possibility remains
10571             --  that we can manage with the new size if we bias the type.
10572
10573             M := UI_From_Int (Minimum_Size (UT, Biased => True));
10574
10575             if Siz < M then
10576                Size_Too_Small_Error (M);
10577                Set_Esize   (T, M);
10578                Set_RM_Size (T, M);
10579             else
10580                Biased := True;
10581             end if;
10582          end if;
10583       end if;
10584    end Check_Size;
10585
10586    --------------------------
10587    -- Freeze_Entity_Checks --
10588    --------------------------
10589
10590    procedure Freeze_Entity_Checks (N : Node_Id) is
10591       procedure Hide_Non_Overridden_Subprograms (Typ : Entity_Id);
10592       --  Inspect the primitive operations of type Typ and hide all pairs of
10593       --  implicitly declared non-overridden non-fully conformant homographs
10594       --  (Ada RM 8.3 12.3/2).
10595
10596       -------------------------------------
10597       -- Hide_Non_Overridden_Subprograms --
10598       -------------------------------------
10599
10600       procedure Hide_Non_Overridden_Subprograms (Typ : Entity_Id) is
10601          procedure Hide_Matching_Homographs
10602            (Subp_Id    : Entity_Id;
10603             Start_Elmt : Elmt_Id);
10604          --  Inspect a list of primitive operations starting with Start_Elmt
10605          --  and find matching implicitly declared non-overridden non-fully
10606          --  conformant homographs of Subp_Id. If found, all matches along
10607          --  with Subp_Id are hidden from all visibility.
10608
10609          function Is_Non_Overridden_Or_Null_Procedure
10610            (Subp_Id : Entity_Id) return Boolean;
10611          --  Determine whether subprogram Subp_Id is implicitly declared non-
10612          --  overridden subprogram or an implicitly declared null procedure.
10613
10614          ------------------------------
10615          -- Hide_Matching_Homographs --
10616          ------------------------------
10617
10618          procedure Hide_Matching_Homographs
10619            (Subp_Id    : Entity_Id;
10620             Start_Elmt : Elmt_Id)
10621          is
10622             Prim      : Entity_Id;
10623             Prim_Elmt : Elmt_Id;
10624
10625          begin
10626             Prim_Elmt := Start_Elmt;
10627             while Present (Prim_Elmt) loop
10628                Prim := Node (Prim_Elmt);
10629
10630                --  The current primitive is implicitly declared non-overridden
10631                --  non-fully conformant homograph of Subp_Id. Both subprograms
10632                --  must be hidden from visibility.
10633
10634                if Chars (Prim) = Chars (Subp_Id)
10635                  and then Is_Non_Overridden_Or_Null_Procedure (Prim)
10636                  and then not Fully_Conformant (Prim, Subp_Id)
10637                then
10638                   Set_Is_Hidden_Non_Overridden_Subpgm (Prim);
10639                   Set_Is_Immediately_Visible          (Prim, False);
10640                   Set_Is_Potentially_Use_Visible      (Prim, False);
10641
10642                   Set_Is_Hidden_Non_Overridden_Subpgm (Subp_Id);
10643                   Set_Is_Immediately_Visible          (Subp_Id, False);
10644                   Set_Is_Potentially_Use_Visible      (Subp_Id, False);
10645                end if;
10646
10647                Next_Elmt (Prim_Elmt);
10648             end loop;
10649          end Hide_Matching_Homographs;
10650
10651          -----------------------------------------
10652          -- Is_Non_Overridden_Or_Null_Procedure --
10653          -----------------------------------------
10654
10655          function Is_Non_Overridden_Or_Null_Procedure
10656            (Subp_Id : Entity_Id) return Boolean
10657          is
10658             Alias_Id : Entity_Id;
10659
10660          begin
10661             --  The subprogram is inherited (implicitly declared), it does not
10662             --  override and does not cover a primitive of an interface.
10663
10664             if Ekind_In (Subp_Id, E_Function, E_Procedure)
10665               and then Present (Alias (Subp_Id))
10666               and then No (Interface_Alias (Subp_Id))
10667               and then No (Overridden_Operation (Subp_Id))
10668             then
10669                Alias_Id := Alias (Subp_Id);
10670
10671                if Requires_Overriding (Alias_Id) then
10672                   return True;
10673
10674                elsif Nkind (Parent (Alias_Id)) = N_Procedure_Specification
10675                  and then Null_Present (Parent (Alias_Id))
10676                then
10677                   return True;
10678                end if;
10679             end if;
10680
10681             return False;
10682          end Is_Non_Overridden_Or_Null_Procedure;
10683
10684          --  Local variables
10685
10686          Prim_Ops  : constant Elist_Id := Direct_Primitive_Operations (Typ);
10687          Prim      : Entity_Id;
10688          Prim_Elmt : Elmt_Id;
10689
10690       --  Start of processing for Hide_Non_Overridden_Subprograms
10691
10692       begin
10693          --  Inspect the list of primitives looking for non-overridden
10694          --  subprograms.
10695
10696          if Present (Prim_Ops) then
10697             Prim_Elmt := First_Elmt (Prim_Ops);
10698             while Present (Prim_Elmt) loop
10699                Prim := Node (Prim_Elmt);
10700                Next_Elmt (Prim_Elmt);
10701
10702                if Is_Non_Overridden_Or_Null_Procedure (Prim) then
10703                   Hide_Matching_Homographs
10704                     (Subp_Id    => Prim,
10705                      Start_Elmt => Prim_Elmt);
10706                end if;
10707             end loop;
10708          end if;
10709       end Hide_Non_Overridden_Subprograms;
10710
10711       --  Local variables
10712
10713       E : constant Entity_Id := Entity (N);
10714
10715       Non_Generic_Case : constant Boolean := Nkind (N) = N_Freeze_Entity;
10716       --  True in non-generic case. Some of the processing here is skipped
10717       --  for the generic case since it is not needed. Basically in the
10718       --  generic case, we only need to do stuff that might generate error
10719       --  messages or warnings.
10720
10721    --  Start of processing for Freeze_Entity_Checks
10722
10723    begin
10724       --  Remember that we are processing a freezing entity. Required to
10725       --  ensure correct decoration of internal entities associated with
10726       --  interfaces (see New_Overloaded_Entity).
10727
10728       Inside_Freezing_Actions := Inside_Freezing_Actions + 1;
10729
10730       --  For tagged types covering interfaces add internal entities that link
10731       --  the primitives of the interfaces with the primitives that cover them.
10732       --  Note: These entities were originally generated only when generating
10733       --  code because their main purpose was to provide support to initialize
10734       --  the secondary dispatch tables. They are now generated also when
10735       --  compiling with no code generation to provide ASIS the relationship
10736       --  between interface primitives and tagged type primitives. They are
10737       --  also used to locate primitives covering interfaces when processing
10738       --  generics (see Derive_Subprograms).
10739
10740       --  This is not needed in the generic case
10741
10742       if Ada_Version >= Ada_2005
10743         and then Non_Generic_Case
10744         and then Ekind (E) = E_Record_Type
10745         and then Is_Tagged_Type (E)
10746         and then not Is_Interface (E)
10747         and then Has_Interfaces (E)
10748       then
10749          --  This would be a good common place to call the routine that checks
10750          --  overriding of interface primitives (and thus factorize calls to
10751          --  Check_Abstract_Overriding located at different contexts in the
10752          --  compiler). However, this is not possible because it causes
10753          --  spurious errors in case of late overriding.
10754
10755          Add_Internal_Interface_Entities (E);
10756       end if;
10757
10758       --  After all forms of overriding have been resolved, a tagged type may
10759       --  be left with a set of implicitly declared and possibly erroneous
10760       --  abstract subprograms, null procedures and subprograms that require
10761       --  overriding. If this set contains fully conformant homographs, then
10762       --  one is chosen arbitrarily (already done during resolution), otherwise
10763       --  all remaining non-fully conformant homographs are hidden from
10764       --  visibility (Ada RM 8.3 12.3/2).
10765
10766       if Is_Tagged_Type (E) then
10767          Hide_Non_Overridden_Subprograms (E);
10768       end if;
10769
10770       --  Check CPP types
10771
10772       if Ekind (E) = E_Record_Type
10773         and then Is_CPP_Class (E)
10774         and then Is_Tagged_Type (E)
10775         and then Tagged_Type_Expansion
10776       then
10777          if CPP_Num_Prims (E) = 0 then
10778
10779             --  If the CPP type has user defined components then it must import
10780             --  primitives from C++. This is required because if the C++ class
10781             --  has no primitives then the C++ compiler does not added the _tag
10782             --  component to the type.
10783
10784             if First_Entity (E) /= Last_Entity (E) then
10785                Error_Msg_N
10786                  ("'C'P'P type must import at least one primitive from C++??",
10787                   E);
10788             end if;
10789          end if;
10790
10791          --  Check that all its primitives are abstract or imported from C++.
10792          --  Check also availability of the C++ constructor.
10793
10794          declare
10795             Has_Constructors : constant Boolean := Has_CPP_Constructors (E);
10796             Elmt             : Elmt_Id;
10797             Error_Reported   : Boolean := False;
10798             Prim             : Node_Id;
10799
10800          begin
10801             Elmt := First_Elmt (Primitive_Operations (E));
10802             while Present (Elmt) loop
10803                Prim := Node (Elmt);
10804
10805                if Comes_From_Source (Prim) then
10806                   if Is_Abstract_Subprogram (Prim) then
10807                      null;
10808
10809                   elsif not Is_Imported (Prim)
10810                     or else Convention (Prim) /= Convention_CPP
10811                   then
10812                      Error_Msg_N
10813                        ("primitives of 'C'P'P types must be imported from C++ "
10814                         & "or abstract??", Prim);
10815
10816                   elsif not Has_Constructors
10817                      and then not Error_Reported
10818                   then
10819                      Error_Msg_Name_1 := Chars (E);
10820                      Error_Msg_N
10821                        ("??'C'P'P constructor required for type %", Prim);
10822                      Error_Reported := True;
10823                   end if;
10824                end if;
10825
10826                Next_Elmt (Elmt);
10827             end loop;
10828          end;
10829       end if;
10830
10831       --  Check Ada derivation of CPP type
10832
10833       if Expander_Active              -- why? losing errors in -gnatc mode???
10834         and then Present (Etype (E))  -- defend against errors
10835         and then Tagged_Type_Expansion
10836         and then Ekind (E) = E_Record_Type
10837         and then Etype (E) /= E
10838         and then Is_CPP_Class (Etype (E))
10839         and then CPP_Num_Prims (Etype (E)) > 0
10840         and then not Is_CPP_Class (E)
10841         and then not Has_CPP_Constructors (Etype (E))
10842       then
10843          --  If the parent has C++ primitives but it has no constructor then
10844          --  check that all the primitives are overridden in this derivation;
10845          --  otherwise the constructor of the parent is needed to build the
10846          --  dispatch table.
10847
10848          declare
10849             Elmt : Elmt_Id;
10850             Prim : Node_Id;
10851
10852          begin
10853             Elmt := First_Elmt (Primitive_Operations (E));
10854             while Present (Elmt) loop
10855                Prim := Node (Elmt);
10856
10857                if not Is_Abstract_Subprogram (Prim)
10858                  and then No (Interface_Alias (Prim))
10859                  and then Find_Dispatching_Type (Ultimate_Alias (Prim)) /= E
10860                then
10861                   Error_Msg_Name_1 := Chars (Etype (E));
10862                   Error_Msg_N
10863                     ("'C'P'P constructor required for parent type %", E);
10864                   exit;
10865                end if;
10866
10867                Next_Elmt (Elmt);
10868             end loop;
10869          end;
10870       end if;
10871
10872       Inside_Freezing_Actions := Inside_Freezing_Actions - 1;
10873
10874       --  If we have a type with predicates, build predicate function. This is
10875       --  not needed in the generic case, nor within TSS subprograms and other
10876       --  predefined primitives.
10877
10878       if Is_Type (E)
10879         and then Non_Generic_Case
10880         and then not Within_Internal_Subprogram
10881         and then Has_Predicates (E)
10882       then
10883          Build_Predicate_Functions (E, N);
10884       end if;
10885
10886       --  If type has delayed aspects, this is where we do the preanalysis at
10887       --  the freeze point, as part of the consistent visibility check. Note
10888       --  that this must be done after calling Build_Predicate_Functions or
10889       --  Build_Invariant_Procedure since these subprograms fix occurrences of
10890       --  the subtype name in the saved expression so that they will not cause
10891       --  trouble in the preanalysis.
10892
10893       --  This is also not needed in the generic case
10894
10895       if Non_Generic_Case
10896         and then Has_Delayed_Aspects (E)
10897         and then Scope (E) = Current_Scope
10898       then
10899          --  Retrieve the visibility to the discriminants in order to properly
10900          --  analyze the aspects.
10901
10902          Push_Scope_And_Install_Discriminants (E);
10903
10904          declare
10905             Ritem : Node_Id;
10906
10907          begin
10908             --  Look for aspect specification entries for this entity
10909
10910             Ritem := First_Rep_Item (E);
10911             while Present (Ritem) loop
10912                if Nkind (Ritem) = N_Aspect_Specification
10913                  and then Entity (Ritem) = E
10914                  and then Is_Delayed_Aspect (Ritem)
10915                then
10916                   Check_Aspect_At_Freeze_Point (Ritem);
10917                end if;
10918
10919                Next_Rep_Item (Ritem);
10920             end loop;
10921          end;
10922
10923          Uninstall_Discriminants_And_Pop_Scope (E);
10924       end if;
10925
10926       --  For a record type, deal with variant parts. This has to be delayed
10927       --  to this point, because of the issue of statically predicated
10928       --  subtypes, which we have to ensure are frozen before checking
10929       --  choices, since we need to have the static choice list set.
10930
10931       if Is_Record_Type (E) then
10932          Check_Variant_Part : declare
10933             D  : constant Node_Id := Declaration_Node (E);
10934             T  : Node_Id;
10935             C  : Node_Id;
10936             VP : Node_Id;
10937
10938             Others_Present : Boolean;
10939             pragma Warnings (Off, Others_Present);
10940             --  Indicates others present, not used in this case
10941
10942             procedure Non_Static_Choice_Error (Choice : Node_Id);
10943             --  Error routine invoked by the generic instantiation below when
10944             --  the variant part has a non static choice.
10945
10946             procedure Process_Declarations (Variant : Node_Id);
10947             --  Processes declarations associated with a variant. We analyzed
10948             --  the declarations earlier (in Sem_Ch3.Analyze_Variant_Part),
10949             --  but we still need the recursive call to Check_Choices for any
10950             --  nested variant to get its choices properly processed. This is
10951             --  also where we expand out the choices if expansion is active.
10952
10953             package Variant_Choices_Processing is new
10954               Generic_Check_Choices
10955                 (Process_Empty_Choice      => No_OP,
10956                  Process_Non_Static_Choice => Non_Static_Choice_Error,
10957                  Process_Associated_Node   => Process_Declarations);
10958             use Variant_Choices_Processing;
10959
10960             -----------------------------
10961             -- Non_Static_Choice_Error --
10962             -----------------------------
10963
10964             procedure Non_Static_Choice_Error (Choice : Node_Id) is
10965             begin
10966                Flag_Non_Static_Expr
10967                  ("choice given in variant part is not static!", Choice);
10968             end Non_Static_Choice_Error;
10969
10970             --------------------------
10971             -- Process_Declarations --
10972             --------------------------
10973
10974             procedure Process_Declarations (Variant : Node_Id) is
10975                CL : constant Node_Id := Component_List (Variant);
10976                VP : Node_Id;
10977
10978             begin
10979                --  Check for static predicate present in this variant
10980
10981                if Has_SP_Choice (Variant) then
10982
10983                   --  Here we expand. You might expect to find this call in
10984                   --  Expand_N_Variant_Part, but that is called when we first
10985                   --  see the variant part, and we cannot do this expansion
10986                   --  earlier than the freeze point, since for statically
10987                   --  predicated subtypes, the predicate is not known till
10988                   --  the freeze point.
10989
10990                   --  Furthermore, we do this expansion even if the expander
10991                   --  is not active, because other semantic processing, e.g.
10992                   --  for aggregates, requires the expanded list of choices.
10993
10994                   --  If the expander is not active, then we can't just clobber
10995                   --  the list since it would invalidate the ASIS -gnatct tree.
10996                   --  So we have to rewrite the variant part with a Rewrite
10997                   --  call that replaces it with a copy and clobber the copy.
10998
10999                   if not Expander_Active then
11000                      declare
11001                         NewV : constant Node_Id := New_Copy (Variant);
11002                      begin
11003                         Set_Discrete_Choices
11004                           (NewV, New_Copy_List (Discrete_Choices (Variant)));
11005                         Rewrite (Variant, NewV);
11006                      end;
11007                   end if;
11008
11009                   Expand_Static_Predicates_In_Choices (Variant);
11010                end if;
11011
11012                --  We don't need to worry about the declarations in the variant
11013                --  (since they were analyzed by Analyze_Choices when we first
11014                --  encountered the variant), but we do need to take care of
11015                --  expansion of any nested variants.
11016
11017                if not Null_Present (CL) then
11018                   VP := Variant_Part (CL);
11019
11020                   if Present (VP) then
11021                      Check_Choices
11022                        (VP, Variants (VP), Etype (Name (VP)), Others_Present);
11023                   end if;
11024                end if;
11025             end Process_Declarations;
11026
11027          --  Start of processing for Check_Variant_Part
11028
11029          begin
11030             --  Find component list
11031
11032             C := Empty;
11033
11034             if Nkind (D) = N_Full_Type_Declaration then
11035                T := Type_Definition (D);
11036
11037                if Nkind (T) = N_Record_Definition then
11038                   C := Component_List (T);
11039
11040                elsif Nkind (T) = N_Derived_Type_Definition
11041                  and then Present (Record_Extension_Part (T))
11042                then
11043                   C := Component_List (Record_Extension_Part (T));
11044                end if;
11045             end if;
11046
11047             --  Case of variant part present
11048
11049             if Present (C) and then Present (Variant_Part (C)) then
11050                VP := Variant_Part (C);
11051
11052                --  Check choices
11053
11054                Check_Choices
11055                  (VP, Variants (VP), Etype (Name (VP)), Others_Present);
11056
11057                --  If the last variant does not contain the Others choice,
11058                --  replace it with an N_Others_Choice node since Gigi always
11059                --  wants an Others. Note that we do not bother to call Analyze
11060                --  on the modified variant part, since its only effect would be
11061                --  to compute the Others_Discrete_Choices node laboriously, and
11062                --  of course we already know the list of choices corresponding
11063                --  to the others choice (it's the list we're replacing).
11064
11065                --  We only want to do this if the expander is active, since
11066                --  we do not want to clobber the ASIS tree.
11067
11068                if Expander_Active then
11069                   declare
11070                      Last_Var : constant Node_Id :=
11071                                      Last_Non_Pragma (Variants (VP));
11072
11073                      Others_Node : Node_Id;
11074
11075                   begin
11076                      if Nkind (First (Discrete_Choices (Last_Var))) /=
11077                                                             N_Others_Choice
11078                      then
11079                         Others_Node := Make_Others_Choice (Sloc (Last_Var));
11080                         Set_Others_Discrete_Choices
11081                           (Others_Node, Discrete_Choices (Last_Var));
11082                         Set_Discrete_Choices
11083                           (Last_Var, New_List (Others_Node));
11084                      end if;
11085                   end;
11086                end if;
11087             end if;
11088          end Check_Variant_Part;
11089       end if;
11090    end Freeze_Entity_Checks;
11091
11092    -------------------------
11093    -- Get_Alignment_Value --
11094    -------------------------
11095
11096    function Get_Alignment_Value (Expr : Node_Id) return Uint is
11097       Align : constant Uint := Static_Integer (Expr);
11098
11099    begin
11100       if Align = No_Uint then
11101          return No_Uint;
11102
11103       elsif Align <= 0 then
11104
11105          --  This error is suppressed in ASIS mode to allow for different ASIS
11106          --  back ends or ASIS-based tools to query the illegal clause.
11107
11108          if not ASIS_Mode then
11109             Error_Msg_N ("alignment value must be positive", Expr);
11110          end if;
11111
11112          return No_Uint;
11113
11114       else
11115          for J in Int range 0 .. 64 loop
11116             declare
11117                M : constant Uint := Uint_2 ** J;
11118
11119             begin
11120                exit when M = Align;
11121
11122                if M > Align then
11123
11124                   --  This error is suppressed in ASIS mode to allow for
11125                   --  different ASIS back ends or ASIS-based tools to query the
11126                   --  illegal clause.
11127
11128                   if not ASIS_Mode then
11129                      Error_Msg_N ("alignment value must be power of 2", Expr);
11130                   end if;
11131
11132                   return No_Uint;
11133                end if;
11134             end;
11135          end loop;
11136
11137          return Align;
11138       end if;
11139    end Get_Alignment_Value;
11140
11141    -----------------------------
11142    -- Get_Interfacing_Aspects --
11143    -----------------------------
11144
11145    procedure Get_Interfacing_Aspects
11146      (Iface_Asp : Node_Id;
11147       Conv_Asp  : out Node_Id;
11148       EN_Asp    : out Node_Id;
11149       Expo_Asp  : out Node_Id;
11150       Imp_Asp   : out Node_Id;
11151       LN_Asp    : out Node_Id;
11152       Do_Checks : Boolean := False)
11153    is
11154       procedure Save_Or_Duplication_Error
11155         (Asp : Node_Id;
11156          To  : in out Node_Id);
11157       --  Save the value of aspect Asp in node To. If To already has a value,
11158       --  then this is considered a duplicate use of aspect. Emit an error if
11159       --  flag Do_Checks is set.
11160
11161       -------------------------------
11162       -- Save_Or_Duplication_Error --
11163       -------------------------------
11164
11165       procedure Save_Or_Duplication_Error
11166         (Asp : Node_Id;
11167          To  : in out Node_Id)
11168       is
11169       begin
11170          --  Detect an extra aspect and issue an error
11171
11172          if Present (To) then
11173             if Do_Checks then
11174                Error_Msg_Name_1 := Chars (Identifier (Asp));
11175                Error_Msg_Sloc   := Sloc (To);
11176                Error_Msg_N ("aspect % previously given #", Asp);
11177             end if;
11178
11179          --  Otherwise capture the aspect
11180
11181          else
11182             To := Asp;
11183          end if;
11184       end Save_Or_Duplication_Error;
11185
11186       --  Local variables
11187
11188       Asp    : Node_Id;
11189       Asp_Id : Aspect_Id;
11190
11191       --  The following variables capture each individual aspect
11192
11193       Conv : Node_Id := Empty;
11194       EN   : Node_Id := Empty;
11195       Expo : Node_Id := Empty;
11196       Imp  : Node_Id := Empty;
11197       LN   : Node_Id := Empty;
11198
11199    --  Start of processing for Get_Interfacing_Aspects
11200
11201    begin
11202       --  The input interfacing aspect should reside in an aspect specification
11203       --  list.
11204
11205       pragma Assert (Is_List_Member (Iface_Asp));
11206
11207       --  Examine the aspect specifications of the related entity. Find and
11208       --  capture all interfacing aspects. Detect duplicates and emit errors
11209       --  if applicable.
11210
11211       Asp := First (List_Containing (Iface_Asp));
11212       while Present (Asp) loop
11213          Asp_Id := Get_Aspect_Id (Asp);
11214
11215          if Asp_Id = Aspect_Convention then
11216             Save_Or_Duplication_Error (Asp, Conv);
11217
11218          elsif Asp_Id = Aspect_External_Name then
11219             Save_Or_Duplication_Error (Asp, EN);
11220
11221          elsif Asp_Id = Aspect_Export then
11222             Save_Or_Duplication_Error (Asp, Expo);
11223
11224          elsif Asp_Id = Aspect_Import then
11225             Save_Or_Duplication_Error (Asp, Imp);
11226
11227          elsif Asp_Id = Aspect_Link_Name then
11228             Save_Or_Duplication_Error (Asp, LN);
11229          end if;
11230
11231          Next (Asp);
11232       end loop;
11233
11234       Conv_Asp := Conv;
11235       EN_Asp   := EN;
11236       Expo_Asp := Expo;
11237       Imp_Asp  := Imp;
11238       LN_Asp   := LN;
11239    end Get_Interfacing_Aspects;
11240
11241    -------------------------------------
11242    -- Inherit_Aspects_At_Freeze_Point --
11243    -------------------------------------
11244
11245    procedure Inherit_Aspects_At_Freeze_Point (Typ : Entity_Id) is
11246       function Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11247         (Rep_Item : Node_Id) return Boolean;
11248       --  This routine checks if Rep_Item is either a pragma or an aspect
11249       --  specification node whose correponding pragma (if any) is present in
11250       --  the Rep Item chain of the entity it has been specified to.
11251
11252       --------------------------------------------------
11253       -- Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item --
11254       --------------------------------------------------
11255
11256       function Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11257         (Rep_Item : Node_Id) return Boolean
11258       is
11259       begin
11260          return
11261            Nkind (Rep_Item) = N_Pragma
11262              or else Present_In_Rep_Item
11263                        (Entity (Rep_Item), Aspect_Rep_Item (Rep_Item));
11264       end Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item;
11265
11266    --  Start of processing for Inherit_Aspects_At_Freeze_Point
11267
11268    begin
11269       --  A representation item is either subtype-specific (Size and Alignment
11270       --  clauses) or type-related (all others).  Subtype-specific aspects may
11271       --  differ for different subtypes of the same type (RM 13.1.8).
11272
11273       --  A derived type inherits each type-related representation aspect of
11274       --  its parent type that was directly specified before the declaration of
11275       --  the derived type (RM 13.1.15).
11276
11277       --  A derived subtype inherits each subtype-specific representation
11278       --  aspect of its parent subtype that was directly specified before the
11279       --  declaration of the derived type (RM 13.1.15).
11280
11281       --  The general processing involves inheriting a representation aspect
11282       --  from a parent type whenever the first rep item (aspect specification,
11283       --  attribute definition clause, pragma) corresponding to the given
11284       --  representation aspect in the rep item chain of Typ, if any, isn't
11285       --  directly specified to Typ but to one of its parents.
11286
11287       --  ??? Note that, for now, just a limited number of representation
11288       --  aspects have been inherited here so far. Many of them are
11289       --  still inherited in Sem_Ch3. This will be fixed soon. Here is
11290       --  a non- exhaustive list of aspects that likely also need to
11291       --  be moved to this routine: Alignment, Component_Alignment,
11292       --  Component_Size, Machine_Radix, Object_Size, Pack, Predicates,
11293       --  Preelaborable_Initialization, RM_Size and Small.
11294
11295       --  In addition, Convention must be propagated from base type to subtype,
11296       --  because the subtype may have been declared on an incomplete view.
11297
11298       if Nkind (Parent (Typ)) = N_Private_Extension_Declaration then
11299          return;
11300       end if;
11301
11302       --  Ada_05/Ada_2005
11303
11304       if not Has_Rep_Item (Typ, Name_Ada_05, Name_Ada_2005, False)
11305         and then Has_Rep_Item (Typ, Name_Ada_05, Name_Ada_2005)
11306         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11307                    (Get_Rep_Item (Typ, Name_Ada_05, Name_Ada_2005))
11308       then
11309          Set_Is_Ada_2005_Only (Typ);
11310       end if;
11311
11312       --  Ada_12/Ada_2012
11313
11314       if not Has_Rep_Item (Typ, Name_Ada_12, Name_Ada_2012, False)
11315         and then Has_Rep_Item (Typ, Name_Ada_12, Name_Ada_2012)
11316         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11317                    (Get_Rep_Item (Typ, Name_Ada_12, Name_Ada_2012))
11318       then
11319          Set_Is_Ada_2012_Only (Typ);
11320       end if;
11321
11322       --  Atomic/Shared
11323
11324       if not Has_Rep_Item (Typ, Name_Atomic, Name_Shared, False)
11325         and then Has_Rep_Pragma (Typ, Name_Atomic, Name_Shared)
11326         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11327                    (Get_Rep_Item (Typ, Name_Atomic, Name_Shared))
11328       then
11329          Set_Is_Atomic (Typ);
11330          Set_Is_Volatile (Typ);
11331          Set_Treat_As_Volatile (Typ);
11332       end if;
11333
11334       --  Convention
11335
11336       if Is_Record_Type (Typ)
11337         and then Typ /= Base_Type (Typ) and then Is_Frozen (Base_Type (Typ))
11338       then
11339          Set_Convention (Typ, Convention (Base_Type (Typ)));
11340       end if;
11341
11342       --  Default_Component_Value
11343
11344       --  Verify that there is no rep_item declared for the type, and there
11345       --  is one coming from an ancestor.
11346
11347       if Is_Array_Type (Typ)
11348         and then Is_Base_Type (Typ)
11349         and then not Has_Rep_Item (Typ, Name_Default_Component_Value, False)
11350         and then Has_Rep_Item (Typ, Name_Default_Component_Value)
11351       then
11352          Set_Default_Aspect_Component_Value (Typ,
11353            Default_Aspect_Component_Value
11354              (Entity (Get_Rep_Item (Typ, Name_Default_Component_Value))));
11355       end if;
11356
11357       --  Default_Value
11358
11359       if Is_Scalar_Type (Typ)
11360         and then Is_Base_Type (Typ)
11361         and then not Has_Rep_Item (Typ, Name_Default_Value, False)
11362         and then Has_Rep_Item (Typ, Name_Default_Value)
11363       then
11364          Set_Has_Default_Aspect (Typ);
11365          Set_Default_Aspect_Value (Typ,
11366            Default_Aspect_Value
11367              (Entity (Get_Rep_Item (Typ, Name_Default_Value))));
11368       end if;
11369
11370       --  Discard_Names
11371
11372       if not Has_Rep_Item (Typ, Name_Discard_Names, False)
11373         and then Has_Rep_Item (Typ, Name_Discard_Names)
11374         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11375                    (Get_Rep_Item (Typ, Name_Discard_Names))
11376       then
11377          Set_Discard_Names (Typ);
11378       end if;
11379
11380       --  Volatile
11381
11382       if not Has_Rep_Item (Typ, Name_Volatile, False)
11383         and then Has_Rep_Item (Typ, Name_Volatile)
11384         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11385                    (Get_Rep_Item (Typ, Name_Volatile))
11386       then
11387          Set_Is_Volatile (Typ);
11388          Set_Treat_As_Volatile (Typ);
11389       end if;
11390
11391       --  Volatile_Full_Access
11392
11393       if not Has_Rep_Item (Typ, Name_Volatile_Full_Access, False)
11394         and then Has_Rep_Pragma (Typ, Name_Volatile_Full_Access)
11395         and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11396                    (Get_Rep_Item (Typ, Name_Volatile_Full_Access))
11397       then
11398          Set_Is_Volatile_Full_Access (Typ);
11399          Set_Is_Volatile (Typ);
11400          Set_Treat_As_Volatile (Typ);
11401       end if;
11402
11403       --  Inheritance for derived types only
11404
11405       if Is_Derived_Type (Typ) then
11406          declare
11407             Bas_Typ     : constant Entity_Id := Base_Type (Typ);
11408             Imp_Bas_Typ : constant Entity_Id := Implementation_Base_Type (Typ);
11409
11410          begin
11411             --  Atomic_Components
11412
11413             if not Has_Rep_Item (Typ, Name_Atomic_Components, False)
11414               and then Has_Rep_Item (Typ, Name_Atomic_Components)
11415               and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11416                    (Get_Rep_Item (Typ, Name_Atomic_Components))
11417             then
11418                Set_Has_Atomic_Components (Imp_Bas_Typ);
11419             end if;
11420
11421             --  Volatile_Components
11422
11423             if not Has_Rep_Item (Typ, Name_Volatile_Components, False)
11424               and then Has_Rep_Item (Typ, Name_Volatile_Components)
11425               and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11426                    (Get_Rep_Item (Typ, Name_Volatile_Components))
11427             then
11428                Set_Has_Volatile_Components (Imp_Bas_Typ);
11429             end if;
11430
11431             --  Finalize_Storage_Only
11432
11433             if not Has_Rep_Pragma (Typ, Name_Finalize_Storage_Only, False)
11434               and then Has_Rep_Pragma (Typ, Name_Finalize_Storage_Only)
11435             then
11436                Set_Finalize_Storage_Only (Bas_Typ);
11437             end if;
11438
11439             --  Universal_Aliasing
11440
11441             if not Has_Rep_Item (Typ, Name_Universal_Aliasing, False)
11442               and then Has_Rep_Item (Typ, Name_Universal_Aliasing)
11443               and then Is_Pragma_Or_Corr_Pragma_Present_In_Rep_Item
11444                    (Get_Rep_Item (Typ, Name_Universal_Aliasing))
11445             then
11446                Set_Universal_Aliasing (Imp_Bas_Typ);
11447             end if;
11448
11449             --  Bit_Order
11450
11451             if Is_Record_Type (Typ) then
11452                if not Has_Rep_Item (Typ, Name_Bit_Order, False)
11453                  and then Has_Rep_Item (Typ, Name_Bit_Order)
11454                then
11455                   Set_Reverse_Bit_Order (Bas_Typ,
11456                     Reverse_Bit_Order (Entity (Name
11457                       (Get_Rep_Item (Typ, Name_Bit_Order)))));
11458                end if;
11459             end if;
11460
11461             --  Scalar_Storage_Order
11462
11463             --  Note: the aspect is specified on a first subtype, but recorded
11464             --  in a flag of the base type!
11465
11466             if (Is_Record_Type (Typ) or else Is_Array_Type (Typ))
11467                  and then Typ = Bas_Typ
11468             then
11469                --  For a type extension, always inherit from parent; otherwise
11470                --  inherit if no default applies. Note: we do not check for
11471                --  an explicit rep item on the parent type when inheriting,
11472                --  because the parent SSO may itself have been set by default.
11473
11474                if not Has_Rep_Item (First_Subtype (Typ),
11475                                     Name_Scalar_Storage_Order, False)
11476                  and then (Is_Tagged_Type (Bas_Typ)
11477                             or else not (SSO_Set_Low_By_Default  (Bas_Typ)
11478                                            or else
11479                                          SSO_Set_High_By_Default (Bas_Typ)))
11480                then
11481                   Set_Reverse_Storage_Order (Bas_Typ,
11482                     Reverse_Storage_Order
11483                       (Implementation_Base_Type (Etype (Bas_Typ))));
11484
11485                   --  Clear default SSO indications, since the inherited aspect
11486                   --  which was set explicitly overrides the default.
11487
11488                   Set_SSO_Set_Low_By_Default  (Bas_Typ, False);
11489                   Set_SSO_Set_High_By_Default (Bas_Typ, False);
11490                end if;
11491             end if;
11492          end;
11493       end if;
11494    end Inherit_Aspects_At_Freeze_Point;
11495
11496    ----------------
11497    -- Initialize --
11498    ----------------
11499
11500    procedure Initialize is
11501    begin
11502       Address_Clause_Checks.Init;
11503       Compile_Time_Warnings_Errors.Init;
11504       Unchecked_Conversions.Init;
11505
11506       if AAMP_On_Target then
11507          Independence_Checks.Init;
11508       end if;
11509    end Initialize;
11510
11511    ---------------------------
11512    -- Install_Discriminants --
11513    ---------------------------
11514
11515    procedure Install_Discriminants (E : Entity_Id) is
11516       Disc : Entity_Id;
11517       Prev : Entity_Id;
11518    begin
11519       Disc := First_Discriminant (E);
11520       while Present (Disc) loop
11521          Prev := Current_Entity (Disc);
11522          Set_Current_Entity (Disc);
11523          Set_Is_Immediately_Visible (Disc);
11524          Set_Homonym (Disc, Prev);
11525          Next_Discriminant (Disc);
11526       end loop;
11527    end Install_Discriminants;
11528
11529    -------------------------
11530    -- Is_Operational_Item --
11531    -------------------------
11532
11533    function Is_Operational_Item (N : Node_Id) return Boolean is
11534    begin
11535       if Nkind (N) /= N_Attribute_Definition_Clause then
11536          return False;
11537
11538       else
11539          declare
11540             Id : constant Attribute_Id := Get_Attribute_Id (Chars (N));
11541          begin
11542
11543             --  List of operational items is given in AARM 13.1(8.mm/1).
11544             --  It is clearly incomplete, as it does not include iterator
11545             --  aspects, among others.
11546
11547             return    Id = Attribute_Constant_Indexing
11548               or else Id = Attribute_Default_Iterator
11549               or else Id = Attribute_Implicit_Dereference
11550               or else Id = Attribute_Input
11551               or else Id = Attribute_Iterator_Element
11552               or else Id = Attribute_Iterable
11553               or else Id = Attribute_Output
11554               or else Id = Attribute_Read
11555               or else Id = Attribute_Variable_Indexing
11556               or else Id = Attribute_Write
11557               or else Id = Attribute_External_Tag;
11558          end;
11559       end if;
11560    end Is_Operational_Item;
11561
11562    -------------------------
11563    -- Is_Predicate_Static --
11564    -------------------------
11565
11566    --  Note: the basic legality of the expression has already been checked, so
11567    --  we don't need to worry about cases or ranges on strings for example.
11568
11569    function Is_Predicate_Static
11570      (Expr : Node_Id;
11571       Nam  : Name_Id) return Boolean
11572    is
11573       function All_Static_Case_Alternatives (L : List_Id) return Boolean;
11574       --  Given a list of case expression alternatives, returns True if all
11575       --  the alternatives are static (have all static choices, and a static
11576       --  expression).
11577
11578       function All_Static_Choices (L : List_Id) return Boolean;
11579       --  Returns true if all elements of the list are OK static choices
11580       --  as defined below for Is_Static_Choice. Used for case expression
11581       --  alternatives and for the right operand of a membership test. An
11582       --  others_choice is static if the corresponding expression is static.
11583       --  The staticness of the bounds is checked separately.
11584
11585       function Is_Static_Choice (N : Node_Id) return Boolean;
11586       --  Returns True if N represents a static choice (static subtype, or
11587       --  static subtype indication, or static expression, or static range).
11588       --
11589       --  Note that this is a bit more inclusive than we actually need
11590       --  (in particular membership tests do not allow the use of subtype
11591       --  indications). But that doesn't matter, we have already checked
11592       --  that the construct is legal to get this far.
11593
11594       function Is_Type_Ref (N : Node_Id) return Boolean;
11595       pragma Inline (Is_Type_Ref);
11596       --  Returns True if N is a reference to the type for the predicate in the
11597       --  expression (i.e. if it is an identifier whose Chars field matches the
11598       --  Nam given in the call). N must not be parenthesized, if the type name
11599       --  appears in parens, this routine will return False.
11600
11601       ----------------------------------
11602       -- All_Static_Case_Alternatives --
11603       ----------------------------------
11604
11605       function All_Static_Case_Alternatives (L : List_Id) return Boolean is
11606          N : Node_Id;
11607
11608       begin
11609          N := First (L);
11610          while Present (N) loop
11611             if not (All_Static_Choices (Discrete_Choices (N))
11612                      and then Is_OK_Static_Expression (Expression (N)))
11613             then
11614                return False;
11615             end if;
11616
11617             Next (N);
11618          end loop;
11619
11620          return True;
11621       end All_Static_Case_Alternatives;
11622
11623       ------------------------
11624       -- All_Static_Choices --
11625       ------------------------
11626
11627       function All_Static_Choices (L : List_Id) return Boolean is
11628          N : Node_Id;
11629
11630       begin
11631          N := First (L);
11632          while Present (N) loop
11633             if not Is_Static_Choice (N) then
11634                return False;
11635             end if;
11636
11637             Next (N);
11638          end loop;
11639
11640          return True;
11641       end All_Static_Choices;
11642
11643       ----------------------
11644       -- Is_Static_Choice --
11645       ----------------------
11646
11647       function Is_Static_Choice (N : Node_Id) return Boolean is
11648       begin
11649          return Nkind (N) = N_Others_Choice
11650            or else Is_OK_Static_Expression (N)
11651            or else (Is_Entity_Name (N) and then Is_Type (Entity (N))
11652                      and then Is_OK_Static_Subtype (Entity (N)))
11653            or else (Nkind (N) = N_Subtype_Indication
11654                      and then Is_OK_Static_Subtype (Entity (N)))
11655            or else (Nkind (N) = N_Range and then Is_OK_Static_Range (N));
11656       end Is_Static_Choice;
11657
11658       -----------------
11659       -- Is_Type_Ref --
11660       -----------------
11661
11662       function Is_Type_Ref (N : Node_Id) return Boolean is
11663       begin
11664          return Nkind (N) = N_Identifier
11665            and then Chars (N) = Nam
11666            and then Paren_Count (N) = 0;
11667       end Is_Type_Ref;
11668
11669    --  Start of processing for Is_Predicate_Static
11670
11671    begin
11672       --  Predicate_Static means one of the following holds. Numbers are the
11673       --  corresponding paragraph numbers in (RM 3.2.4(16-22)).
11674
11675       --  16: A static expression
11676
11677       if Is_OK_Static_Expression (Expr) then
11678          return True;
11679
11680       --  17: A membership test whose simple_expression is the current
11681       --  instance, and whose membership_choice_list meets the requirements
11682       --  for a static membership test.
11683
11684       elsif Nkind (Expr) in N_Membership_Test
11685         and then ((Present (Right_Opnd (Expr))
11686                     and then Is_Static_Choice (Right_Opnd (Expr)))
11687                   or else
11688                     (Present (Alternatives (Expr))
11689                       and then All_Static_Choices (Alternatives (Expr))))
11690       then
11691          return True;
11692
11693       --  18. A case_expression whose selecting_expression is the current
11694       --  instance, and whose dependent expressions are static expressions.
11695
11696       elsif Nkind (Expr) = N_Case_Expression
11697         and then Is_Type_Ref (Expression (Expr))
11698         and then All_Static_Case_Alternatives (Alternatives (Expr))
11699       then
11700          return True;
11701
11702       --  19. A call to a predefined equality or ordering operator, where one
11703       --  operand is the current instance, and the other is a static
11704       --  expression.
11705
11706       --  Note: the RM is clearly wrong here in not excluding string types.
11707       --  Without this exclusion, we would allow expressions like X > "ABC"
11708       --  to be considered as predicate-static, which is clearly not intended,
11709       --  since the idea is for predicate-static to be a subset of normal
11710       --  static expressions (and "DEF" > "ABC" is not a static expression).
11711
11712       --  However, we do allow internally generated (not from source) equality
11713       --  and inequality operations to be valid on strings (this helps deal
11714       --  with cases where we transform A in "ABC" to A = "ABC).
11715
11716       elsif Nkind (Expr) in N_Op_Compare
11717         and then ((not Is_String_Type (Etype (Left_Opnd (Expr))))
11718                     or else (Nkind_In (Expr, N_Op_Eq, N_Op_Ne)
11719                               and then not Comes_From_Source (Expr)))
11720         and then ((Is_Type_Ref (Left_Opnd (Expr))
11721                     and then Is_OK_Static_Expression (Right_Opnd (Expr)))
11722                   or else
11723                     (Is_Type_Ref (Right_Opnd (Expr))
11724                       and then Is_OK_Static_Expression (Left_Opnd (Expr))))
11725       then
11726          return True;
11727
11728       --  20. A call to a predefined boolean logical operator, where each
11729       --  operand is predicate-static.
11730
11731       elsif (Nkind_In (Expr, N_Op_And, N_Op_Or, N_Op_Xor)
11732               and then Is_Predicate_Static (Left_Opnd (Expr), Nam)
11733               and then Is_Predicate_Static (Right_Opnd (Expr), Nam))
11734         or else
11735             (Nkind (Expr) = N_Op_Not
11736               and then Is_Predicate_Static (Right_Opnd (Expr), Nam))
11737       then
11738          return True;
11739
11740       --  21. A short-circuit control form where both operands are
11741       --  predicate-static.
11742
11743       elsif Nkind (Expr) in N_Short_Circuit
11744         and then Is_Predicate_Static (Left_Opnd (Expr), Nam)
11745         and then Is_Predicate_Static (Right_Opnd (Expr), Nam)
11746       then
11747          return True;
11748
11749       --  22. A parenthesized predicate-static expression. This does not
11750       --  require any special test, since we just ignore paren levels in
11751       --  all the cases above.
11752
11753       --  One more test that is an implementation artifact caused by the fact
11754       --  that we are analyzing not the original expression, but the generated
11755       --  expression in the body of the predicate function. This can include
11756       --  references to inherited predicates, so that the expression we are
11757       --  processing looks like:
11758
11759       --    xxPredicate (typ (Inns)) and then expression
11760
11761       --  Where the call is to a Predicate function for an inherited predicate.
11762       --  We simply ignore such a call, which could be to either a dynamic or
11763       --  a static predicate. Note that if the parent predicate is dynamic then
11764       --  eventually this type will be marked as dynamic, but you are allowed
11765       --  to specify a static predicate for a subtype which is inheriting a
11766       --  dynamic predicate, so the static predicate validation here ignores
11767       --  the inherited predicate even if it is dynamic.
11768       --  In all cases, a static predicate can only apply to a scalar type.
11769
11770       elsif Nkind (Expr) = N_Function_Call
11771         and then Is_Predicate_Function (Entity (Name (Expr)))
11772         and then Is_Scalar_Type (Etype (First_Entity (Entity (Name (Expr)))))
11773       then
11774          return True;
11775
11776       --  That's an exhaustive list of tests, all other cases are not
11777       --  predicate-static, so we return False.
11778
11779       else
11780          return False;
11781       end if;
11782    end Is_Predicate_Static;
11783
11784    ---------------------
11785    -- Kill_Rep_Clause --
11786    ---------------------
11787
11788    procedure Kill_Rep_Clause (N : Node_Id) is
11789    begin
11790       pragma Assert (Ignore_Rep_Clauses);
11791
11792       --  Note: we use Replace rather than Rewrite, because we don't want
11793       --  ASIS to be able to use Original_Node to dig out the (undecorated)
11794       --  rep clause that is being replaced.
11795
11796       Replace (N, Make_Null_Statement (Sloc (N)));
11797
11798       --  The null statement must be marked as not coming from source. This is
11799       --  so that ASIS ignores it, and also the back end does not expect bogus
11800       --  "from source" null statements in weird places (e.g. in declarative
11801       --  regions where such null statements are not allowed).
11802
11803       Set_Comes_From_Source (N, False);
11804    end Kill_Rep_Clause;
11805
11806    ------------------
11807    -- Minimum_Size --
11808    ------------------
11809
11810    function Minimum_Size
11811      (T      : Entity_Id;
11812       Biased : Boolean := False) return Nat
11813    is
11814       Lo     : Uint    := No_Uint;
11815       Hi     : Uint    := No_Uint;
11816       LoR    : Ureal   := No_Ureal;
11817       HiR    : Ureal   := No_Ureal;
11818       LoSet  : Boolean := False;
11819       HiSet  : Boolean := False;
11820       B      : Uint;
11821       S      : Nat;
11822       Ancest : Entity_Id;
11823       R_Typ  : constant Entity_Id := Root_Type (T);
11824
11825    begin
11826       --  If bad type, return 0
11827
11828       if T = Any_Type then
11829          return 0;
11830
11831       --  For generic types, just return zero. There cannot be any legitimate
11832       --  need to know such a size, but this routine may be called with a
11833       --  generic type as part of normal processing.
11834
11835       elsif Is_Generic_Type (R_Typ) or else R_Typ = Any_Type then
11836          return 0;
11837
11838          --  Access types (cannot have size smaller than System.Address)
11839
11840       elsif Is_Access_Type (T) then
11841          return System_Address_Size;
11842
11843       --  Floating-point types
11844
11845       elsif Is_Floating_Point_Type (T) then
11846          return UI_To_Int (Esize (R_Typ));
11847
11848       --  Discrete types
11849
11850       elsif Is_Discrete_Type (T) then
11851
11852          --  The following loop is looking for the nearest compile time known
11853          --  bounds following the ancestor subtype chain. The idea is to find
11854          --  the most restrictive known bounds information.
11855
11856          Ancest := T;
11857          loop
11858             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
11859                return 0;
11860             end if;
11861
11862             if not LoSet then
11863                if Compile_Time_Known_Value (Type_Low_Bound (Ancest)) then
11864                   Lo := Expr_Rep_Value (Type_Low_Bound (Ancest));
11865                   LoSet := True;
11866                   exit when HiSet;
11867                end if;
11868             end if;
11869
11870             if not HiSet then
11871                if Compile_Time_Known_Value (Type_High_Bound (Ancest)) then
11872                   Hi := Expr_Rep_Value (Type_High_Bound (Ancest));
11873                   HiSet := True;
11874                   exit when LoSet;
11875                end if;
11876             end if;
11877
11878             Ancest := Ancestor_Subtype (Ancest);
11879
11880             if No (Ancest) then
11881                Ancest := Base_Type (T);
11882
11883                if Is_Generic_Type (Ancest) then
11884                   return 0;
11885                end if;
11886             end if;
11887          end loop;
11888
11889       --  Fixed-point types. We can't simply use Expr_Value to get the
11890       --  Corresponding_Integer_Value values of the bounds, since these do not
11891       --  get set till the type is frozen, and this routine can be called
11892       --  before the type is frozen. Similarly the test for bounds being static
11893       --  needs to include the case where we have unanalyzed real literals for
11894       --  the same reason.
11895
11896       elsif Is_Fixed_Point_Type (T) then
11897
11898          --  The following loop is looking for the nearest compile time known
11899          --  bounds following the ancestor subtype chain. The idea is to find
11900          --  the most restrictive known bounds information.
11901
11902          Ancest := T;
11903          loop
11904             if Ancest = Any_Type or else Etype (Ancest) = Any_Type then
11905                return 0;
11906             end if;
11907
11908             --  Note: In the following two tests for LoSet and HiSet, it may
11909             --  seem redundant to test for N_Real_Literal here since normally
11910             --  one would assume that the test for the value being known at
11911             --  compile time includes this case. However, there is a glitch.
11912             --  If the real literal comes from folding a non-static expression,
11913             --  then we don't consider any non- static expression to be known
11914             --  at compile time if we are in configurable run time mode (needed
11915             --  in some cases to give a clearer definition of what is and what
11916             --  is not accepted). So the test is indeed needed. Without it, we
11917             --  would set neither Lo_Set nor Hi_Set and get an infinite loop.
11918
11919             if not LoSet then
11920                if Nkind (Type_Low_Bound (Ancest)) = N_Real_Literal
11921                  or else Compile_Time_Known_Value (Type_Low_Bound (Ancest))
11922                then
11923                   LoR := Expr_Value_R (Type_Low_Bound (Ancest));
11924                   LoSet := True;
11925                   exit when HiSet;
11926                end if;
11927             end if;
11928
11929             if not HiSet then
11930                if Nkind (Type_High_Bound (Ancest)) = N_Real_Literal
11931                  or else Compile_Time_Known_Value (Type_High_Bound (Ancest))
11932                then
11933                   HiR := Expr_Value_R (Type_High_Bound (Ancest));
11934                   HiSet := True;
11935                   exit when LoSet;
11936                end if;
11937             end if;
11938
11939             Ancest := Ancestor_Subtype (Ancest);
11940
11941             if No (Ancest) then
11942                Ancest := Base_Type (T);
11943
11944                if Is_Generic_Type (Ancest) then
11945                   return 0;
11946                end if;
11947             end if;
11948          end loop;
11949
11950          Lo := UR_To_Uint (LoR / Small_Value (T));
11951          Hi := UR_To_Uint (HiR / Small_Value (T));
11952
11953       --  No other types allowed
11954
11955       else
11956          raise Program_Error;
11957       end if;
11958
11959       --  Fall through with Hi and Lo set. Deal with biased case
11960
11961       if (Biased
11962            and then not Is_Fixed_Point_Type (T)
11963            and then not (Is_Enumeration_Type (T)
11964                           and then Has_Non_Standard_Rep (T)))
11965         or else Has_Biased_Representation (T)
11966       then
11967          Hi := Hi - Lo;
11968          Lo := Uint_0;
11969       end if;
11970
11971       --  Null range case, size is always zero. We only do this in the discrete
11972       --  type case, since that's the odd case that came up. Probably we should
11973       --  also do this in the fixed-point case, but doing so causes peculiar
11974       --  gigi failures, and it is not worth worrying about this incredibly
11975       --  marginal case (explicit null-range fixed-point type declarations)???
11976
11977       if Lo > Hi and then Is_Discrete_Type (T) then
11978          S := 0;
11979
11980       --  Signed case. Note that we consider types like range 1 .. -1 to be
11981       --  signed for the purpose of computing the size, since the bounds have
11982       --  to be accommodated in the base type.
11983
11984       elsif Lo < 0 or else Hi < 0 then
11985          S := 1;
11986          B := Uint_1;
11987
11988          --  S = size, B = 2 ** (size - 1) (can accommodate -B .. +(B - 1))
11989          --  Note that we accommodate the case where the bounds cross. This
11990          --  can happen either because of the way the bounds are declared
11991          --  or because of the algorithm in Freeze_Fixed_Point_Type.
11992
11993          while Lo < -B
11994            or else Hi < -B
11995            or else Lo >= B
11996            or else Hi >= B
11997          loop
11998             B := Uint_2 ** S;
11999             S := S + 1;
12000          end loop;
12001
12002       --  Unsigned case
12003
12004       else
12005          --  If both bounds are positive, make sure that both are represen-
12006          --  table in the case where the bounds are crossed. This can happen
12007          --  either because of the way the bounds are declared, or because of
12008          --  the algorithm in Freeze_Fixed_Point_Type.
12009
12010          if Lo > Hi then
12011             Hi := Lo;
12012          end if;
12013
12014          --  S = size, (can accommodate 0 .. (2**size - 1))
12015
12016          S := 0;
12017          while Hi >= Uint_2 ** S loop
12018             S := S + 1;
12019          end loop;
12020       end if;
12021
12022       return S;
12023    end Minimum_Size;
12024
12025    ---------------------------
12026    -- New_Stream_Subprogram --
12027    ---------------------------
12028
12029    procedure New_Stream_Subprogram
12030      (N     : Node_Id;
12031       Ent   : Entity_Id;
12032       Subp  : Entity_Id;
12033       Nam   : TSS_Name_Type)
12034    is
12035       Loc       : constant Source_Ptr := Sloc (N);
12036       Sname     : constant Name_Id    := Make_TSS_Name (Base_Type (Ent), Nam);
12037       Subp_Id   : Entity_Id;
12038       Subp_Decl : Node_Id;
12039       F         : Entity_Id;
12040       Etyp      : Entity_Id;
12041
12042       Defer_Declaration : constant Boolean :=
12043                             Is_Tagged_Type (Ent) or else Is_Private_Type (Ent);
12044       --  For a tagged type, there is a declaration for each stream attribute
12045       --  at the freeze point, and we must generate only a completion of this
12046       --  declaration. We do the same for private types, because the full view
12047       --  might be tagged. Otherwise we generate a declaration at the point of
12048       --  the attribute definition clause. If the attribute definition comes
12049       --  from an aspect specification the declaration is part of the freeze
12050       --  actions of the type.
12051
12052       function Build_Spec return Node_Id;
12053       --  Used for declaration and renaming declaration, so that this is
12054       --  treated as a renaming_as_body.
12055
12056       ----------------
12057       -- Build_Spec --
12058       ----------------
12059
12060       function Build_Spec return Node_Id is
12061          Out_P   : constant Boolean := (Nam = TSS_Stream_Read);
12062          Formals : List_Id;
12063          Spec    : Node_Id;
12064          T_Ref   : constant Node_Id := New_Occurrence_Of (Etyp, Loc);
12065
12066       begin
12067          Subp_Id := Make_Defining_Identifier (Loc, Sname);
12068
12069          --  S : access Root_Stream_Type'Class
12070
12071          Formals := New_List (
12072                       Make_Parameter_Specification (Loc,
12073                         Defining_Identifier =>
12074                           Make_Defining_Identifier (Loc, Name_S),
12075                         Parameter_Type =>
12076                           Make_Access_Definition (Loc,
12077                             Subtype_Mark =>
12078                               New_Occurrence_Of (
12079                                 Designated_Type (Etype (F)), Loc))));
12080
12081          if Nam = TSS_Stream_Input then
12082             Spec :=
12083               Make_Function_Specification (Loc,
12084                 Defining_Unit_Name       => Subp_Id,
12085                 Parameter_Specifications => Formals,
12086                 Result_Definition        => T_Ref);
12087          else
12088             --  V : [out] T
12089
12090             Append_To (Formals,
12091               Make_Parameter_Specification (Loc,
12092                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
12093                 Out_Present         => Out_P,
12094                 Parameter_Type      => T_Ref));
12095
12096             Spec :=
12097               Make_Procedure_Specification (Loc,
12098                 Defining_Unit_Name       => Subp_Id,
12099                 Parameter_Specifications => Formals);
12100          end if;
12101
12102          return Spec;
12103       end Build_Spec;
12104
12105    --  Start of processing for New_Stream_Subprogram
12106
12107    begin
12108       F := First_Formal (Subp);
12109
12110       if Ekind (Subp) = E_Procedure then
12111          Etyp := Etype (Next_Formal (F));
12112       else
12113          Etyp := Etype (Subp);
12114       end if;
12115
12116       --  Prepare subprogram declaration and insert it as an action on the
12117       --  clause node. The visibility for this entity is used to test for
12118       --  visibility of the attribute definition clause (in the sense of
12119       --  8.3(23) as amended by AI-195).
12120
12121       if not Defer_Declaration then
12122          Subp_Decl :=
12123            Make_Subprogram_Declaration (Loc,
12124              Specification => Build_Spec);
12125
12126       --  For a tagged type, there is always a visible declaration for each
12127       --  stream TSS (it is a predefined primitive operation), and the
12128       --  completion of this declaration occurs at the freeze point, which is
12129       --  not always visible at places where the attribute definition clause is
12130       --  visible. So, we create a dummy entity here for the purpose of
12131       --  tracking the visibility of the attribute definition clause itself.
12132
12133       else
12134          Subp_Id :=
12135            Make_Defining_Identifier (Loc, New_External_Name (Sname, 'V'));
12136          Subp_Decl :=
12137            Make_Object_Declaration (Loc,
12138              Defining_Identifier => Subp_Id,
12139              Object_Definition   => New_Occurrence_Of (Standard_Boolean, Loc));
12140       end if;
12141
12142       if not Defer_Declaration
12143         and then From_Aspect_Specification (N)
12144         and then Has_Delayed_Freeze (Ent)
12145       then
12146          Append_Freeze_Action (Ent, Subp_Decl);
12147
12148       else
12149          Insert_Action (N, Subp_Decl);
12150          Set_Entity (N, Subp_Id);
12151       end if;
12152
12153       Subp_Decl :=
12154         Make_Subprogram_Renaming_Declaration (Loc,
12155           Specification => Build_Spec,
12156           Name          => New_Occurrence_Of (Subp, Loc));
12157
12158       if Defer_Declaration then
12159          Set_TSS (Base_Type (Ent), Subp_Id);
12160
12161       else
12162          if From_Aspect_Specification (N) then
12163             Append_Freeze_Action (Ent, Subp_Decl);
12164          else
12165             Insert_Action (N, Subp_Decl);
12166          end if;
12167
12168          Copy_TSS (Subp_Id, Base_Type (Ent));
12169       end if;
12170    end New_Stream_Subprogram;
12171
12172    ------------------------------------------
12173    -- Push_Scope_And_Install_Discriminants --
12174    ------------------------------------------
12175
12176    procedure Push_Scope_And_Install_Discriminants (E : Entity_Id) is
12177    begin
12178       if Has_Discriminants (E) then
12179          Push_Scope (E);
12180
12181          --  Make the discriminants visible for type declarations and protected
12182          --  type declarations, not for subtype declarations (RM 13.1.1 (12/3))
12183
12184          if Nkind (Parent (E)) /= N_Subtype_Declaration then
12185             Install_Discriminants (E);
12186          end if;
12187       end if;
12188    end Push_Scope_And_Install_Discriminants;
12189
12190    ------------------------
12191    -- Rep_Item_Too_Early --
12192    ------------------------
12193
12194    function Rep_Item_Too_Early (T : Entity_Id; N : Node_Id) return Boolean is
12195    begin
12196       --  Cannot apply non-operational rep items to generic types
12197
12198       if Is_Operational_Item (N) then
12199          return False;
12200
12201       elsif Is_Type (T)
12202         and then Is_Generic_Type (Root_Type (T))
12203         and then (Nkind (N) /= N_Pragma
12204                    or else Get_Pragma_Id (N) /= Pragma_Convention)
12205       then
12206          Error_Msg_N ("representation item not allowed for generic type", N);
12207          return True;
12208       end if;
12209
12210       --  Otherwise check for incomplete type
12211
12212       if Is_Incomplete_Or_Private_Type (T)
12213         and then No (Underlying_Type (T))
12214         and then
12215           (Nkind (N) /= N_Pragma
12216             or else Get_Pragma_Id (N) /= Pragma_Import)
12217       then
12218          Error_Msg_N
12219            ("representation item must be after full type declaration", N);
12220          return True;
12221
12222       --  If the type has incomplete components, a representation clause is
12223       --  illegal but stream attributes and Convention pragmas are correct.
12224
12225       elsif Has_Private_Component (T) then
12226          if Nkind (N) = N_Pragma then
12227             return False;
12228
12229          else
12230             Error_Msg_N
12231               ("representation item must appear after type is fully defined",
12232                 N);
12233             return True;
12234          end if;
12235       else
12236          return False;
12237       end if;
12238    end Rep_Item_Too_Early;
12239
12240    -----------------------
12241    -- Rep_Item_Too_Late --
12242    -----------------------
12243
12244    function Rep_Item_Too_Late
12245      (T     : Entity_Id;
12246       N     : Node_Id;
12247       FOnly : Boolean := False) return Boolean
12248    is
12249       S           : Entity_Id;
12250       Parent_Type : Entity_Id;
12251
12252       procedure No_Type_Rep_Item;
12253       --  Output message indicating that no type-related aspects can be
12254       --  specified due to some property of the parent type.
12255
12256       procedure Too_Late;
12257       --  Output message for an aspect being specified too late
12258
12259       --  Note that neither of the above errors is considered a serious one,
12260       --  since the effect is simply that we ignore the representation clause
12261       --  in these cases.
12262       --  Is this really true? In any case if we make this change we must
12263       --  document the requirement in the spec of Rep_Item_Too_Late that
12264       --  if True is returned, then the rep item must be completely ignored???
12265
12266       ----------------------
12267       -- No_Type_Rep_Item --
12268       ----------------------
12269
12270       procedure No_Type_Rep_Item is
12271       begin
12272          Error_Msg_N ("|type-related representation item not permitted!", N);
12273       end No_Type_Rep_Item;
12274
12275       --------------
12276       -- Too_Late --
12277       --------------
12278
12279       procedure Too_Late is
12280       begin
12281          --  Other compilers seem more relaxed about rep items appearing too
12282          --  late. Since analysis tools typically don't care about rep items
12283          --  anyway, no reason to be too strict about this.
12284
12285          if not Relaxed_RM_Semantics then
12286             Error_Msg_N ("|representation item appears too late!", N);
12287          end if;
12288       end Too_Late;
12289
12290    --  Start of processing for Rep_Item_Too_Late
12291
12292    begin
12293       --  First make sure entity is not frozen (RM 13.1(9))
12294
12295       if Is_Frozen (T)
12296
12297         --  Exclude imported types, which may be frozen if they appear in a
12298         --  representation clause for a local type.
12299
12300         and then not From_Limited_With (T)
12301
12302         --  Exclude generated entities (not coming from source). The common
12303         --  case is when we generate a renaming which prematurely freezes the
12304         --  renamed internal entity, but we still want to be able to set copies
12305         --  of attribute values such as Size/Alignment.
12306
12307         and then Comes_From_Source (T)
12308       then
12309          --  A self-referential aspect is illegal if it forces freezing the
12310          --  entity before the corresponding pragma has been analyzed.
12311
12312          if Nkind_In (N, N_Attribute_Definition_Clause, N_Pragma)
12313            and then From_Aspect_Specification (N)
12314          then
12315             Error_Msg_NE
12316               ("aspect specification causes premature freezing of&", T, N);
12317             Set_Has_Delayed_Freeze (T, False);
12318             return True;
12319          end if;
12320
12321          Too_Late;
12322          S := First_Subtype (T);
12323
12324          if Present (Freeze_Node (S)) then
12325             if not Relaxed_RM_Semantics then
12326                Error_Msg_NE
12327                  ("??no more representation items for }", Freeze_Node (S), S);
12328             end if;
12329          end if;
12330
12331          return True;
12332
12333       --  Check for case of untagged derived type whose parent either has
12334       --  primitive operations, or is a by reference type (RM 13.1(10)). In
12335       --  this case we do not output a Too_Late message, since there is no
12336       --  earlier point where the rep item could be placed to make it legal.
12337
12338       elsif Is_Type (T)
12339         and then not FOnly
12340         and then Is_Derived_Type (T)
12341         and then not Is_Tagged_Type (T)
12342       then
12343          Parent_Type := Etype (Base_Type (T));
12344
12345          if Has_Primitive_Operations (Parent_Type) then
12346             No_Type_Rep_Item;
12347
12348             if not Relaxed_RM_Semantics then
12349                Error_Msg_NE
12350                  ("\parent type & has primitive operations!", N, Parent_Type);
12351             end if;
12352
12353             return True;
12354
12355          elsif Is_By_Reference_Type (Parent_Type) then
12356             No_Type_Rep_Item;
12357
12358             if not Relaxed_RM_Semantics then
12359                Error_Msg_NE
12360                  ("\parent type & is a by reference type!", N, Parent_Type);
12361             end if;
12362
12363             return True;
12364          end if;
12365       end if;
12366
12367       --  No error, but one more warning to consider. The RM (surprisingly)
12368       --  allows this pattern:
12369
12370       --    type S is ...
12371       --    primitive operations for S
12372       --    type R is new S;
12373       --    rep clause for S
12374
12375       --  Meaning that calls on the primitive operations of S for values of
12376       --  type R may require possibly expensive implicit conversion operations.
12377       --  This is not an error, but is worth a warning.
12378
12379       if not Relaxed_RM_Semantics and then Is_Type (T) then
12380          declare
12381             DTL : constant Entity_Id := Derived_Type_Link (Base_Type (T));
12382
12383          begin
12384             if Present (DTL)
12385               and then Has_Primitive_Operations (Base_Type (T))
12386
12387               --  For now, do not generate this warning for the case of aspect
12388               --  specification using Ada 2012 syntax, since we get wrong
12389               --  messages we do not understand. The whole business of derived
12390               --  types and rep items seems a bit confused when aspects are
12391               --  used, since the aspects are not evaluated till freeze time.
12392
12393               and then not From_Aspect_Specification (N)
12394             then
12395                Error_Msg_Sloc := Sloc (DTL);
12396                Error_Msg_N
12397                  ("representation item for& appears after derived type "
12398                   & "declaration#??", N);
12399                Error_Msg_NE
12400                  ("\may result in implicit conversions for primitive "
12401                   & "operations of&??", N, T);
12402                Error_Msg_NE
12403                  ("\to change representations when called with arguments "
12404                   & "of type&??", N, DTL);
12405             end if;
12406          end;
12407       end if;
12408
12409       --  No error, link item into head of chain of rep items for the entity,
12410       --  but avoid chaining if we have an overloadable entity, and the pragma
12411       --  is one that can apply to multiple overloaded entities.
12412
12413       if Is_Overloadable (T) and then Nkind (N) = N_Pragma then
12414          declare
12415             Pname : constant Name_Id := Pragma_Name (N);
12416          begin
12417             if Nam_In (Pname, Name_Convention, Name_Import,   Name_Export,
12418                               Name_External,   Name_Interface)
12419             then
12420                return False;
12421             end if;
12422          end;
12423       end if;
12424
12425       Record_Rep_Item (T, N);
12426       return False;
12427    end Rep_Item_Too_Late;
12428
12429    -------------------------------------
12430    -- Replace_Type_References_Generic --
12431    -------------------------------------
12432
12433    procedure Replace_Type_References_Generic (N : Node_Id; T : Entity_Id) is
12434       TName : constant Name_Id := Chars (T);
12435
12436       function Replace_Type_Ref (N : Node_Id) return Traverse_Result;
12437       --  Processes a single node in the traversal procedure below, checking
12438       --  if node N should be replaced, and if so, doing the replacement.
12439
12440       function Visible_Component (Comp : Name_Id) return Entity_Id;
12441       --  Given an identifier in the expression, check whether there is a
12442       --  discriminant or component of the type that is directy visible, and
12443       --  rewrite it as the corresponding selected component of the formal of
12444       --  the subprogram. The entity is located by a sequential search, which
12445       --  seems acceptable given the typical size of component lists and check
12446       --  expressions. Possible optimization ???
12447
12448       ----------------------
12449       -- Replace_Type_Ref --
12450       ----------------------
12451
12452       function Replace_Type_Ref (N : Node_Id) return Traverse_Result is
12453          Loc : constant Source_Ptr := Sloc (N);
12454
12455          procedure Add_Prefix (Ref : Node_Id; Comp : Entity_Id);
12456          --  Add the proper prefix to a reference to a component of the type
12457          --  when it is not already a selected component.
12458
12459          ----------------
12460          -- Add_Prefix --
12461          ----------------
12462
12463          procedure Add_Prefix (Ref : Node_Id; Comp : Entity_Id) is
12464          begin
12465             Rewrite (Ref,
12466               Make_Selected_Component (Loc,
12467                 Prefix        => New_Occurrence_Of (T, Loc),
12468                 Selector_Name => New_Occurrence_Of (Comp, Loc)));
12469             Replace_Type_Reference (Prefix (Ref));
12470          end Add_Prefix;
12471
12472          --  Local variables
12473
12474          Comp : Entity_Id;
12475          Pref : Node_Id;
12476          Scop : Entity_Id;
12477
12478       --  Start of processing for Replace_Type_Ref
12479
12480       begin
12481          if Nkind (N) = N_Identifier then
12482
12483             --  If not the type name, check whether it is a reference to some
12484             --  other type, which must be frozen before the predicate function
12485             --  is analyzed, i.e. before the freeze node of the type to which
12486             --  the predicate applies.
12487
12488             if Chars (N) /= TName then
12489                if Present (Current_Entity (N))
12490                  and then Is_Type (Current_Entity (N))
12491                then
12492                   Freeze_Before (Freeze_Node (T), Current_Entity (N));
12493                end if;
12494
12495                --  The components of the type are directly visible and can
12496                --  be referenced without a prefix.
12497
12498                if Nkind (Parent (N)) = N_Selected_Component then
12499                   null;
12500
12501                --  In expression C (I), C may be a directly visible function
12502                --  or a visible component that has an array type. Disambiguate
12503                --  by examining the component type.
12504
12505                elsif Nkind (Parent (N)) = N_Indexed_Component
12506                  and then N = Prefix (Parent (N))
12507                then
12508                   Comp := Visible_Component (Chars (N));
12509
12510                   if Present (Comp) and then Is_Array_Type (Etype (Comp)) then
12511                      Add_Prefix (N, Comp);
12512                   end if;
12513
12514                else
12515                   Comp := Visible_Component (Chars (N));
12516
12517                   if Present (Comp) then
12518                      Add_Prefix (N, Comp);
12519                   end if;
12520                end if;
12521
12522                return Skip;
12523
12524             --  Otherwise do the replacement and we are done with this node
12525
12526             else
12527                Replace_Type_Reference (N);
12528                return Skip;
12529             end if;
12530
12531          --  Case of selected component (which is what a qualification looks
12532          --  like in the unanalyzed tree, which is what we have.
12533
12534          elsif Nkind (N) = N_Selected_Component then
12535
12536             --  If selector name is not our type, keeping going (we might still
12537             --  have an occurrence of the type in the prefix).
12538
12539             if Nkind (Selector_Name (N)) /= N_Identifier
12540               or else Chars (Selector_Name (N)) /= TName
12541             then
12542                return OK;
12543
12544             --  Selector name is our type, check qualification
12545
12546             else
12547                --  Loop through scopes and prefixes, doing comparison
12548
12549                Scop := Current_Scope;
12550                Pref := Prefix (N);
12551                loop
12552                   --  Continue if no more scopes or scope with no name
12553
12554                   if No (Scop) or else Nkind (Scop) not in N_Has_Chars then
12555                      return OK;
12556                   end if;
12557
12558                   --  Do replace if prefix is an identifier matching the scope
12559                   --  that we are currently looking at.
12560
12561                   if Nkind (Pref) = N_Identifier
12562                     and then Chars (Pref) = Chars (Scop)
12563                   then
12564                      Replace_Type_Reference (N);
12565                      return Skip;
12566                   end if;
12567
12568                   --  Go check scope above us if prefix is itself of the form
12569                   --  of a selected component, whose selector matches the scope
12570                   --  we are currently looking at.
12571
12572                   if Nkind (Pref) = N_Selected_Component
12573                     and then Nkind (Selector_Name (Pref)) = N_Identifier
12574                     and then Chars (Selector_Name (Pref)) = Chars (Scop)
12575                   then
12576                      Scop := Scope (Scop);
12577                      Pref := Prefix (Pref);
12578
12579                   --  For anything else, we don't have a match, so keep on
12580                   --  going, there are still some weird cases where we may
12581                   --  still have a replacement within the prefix.
12582
12583                   else
12584                      return OK;
12585                   end if;
12586                end loop;
12587             end if;
12588
12589          --  Continue for any other node kind
12590
12591          else
12592             return OK;
12593          end if;
12594       end Replace_Type_Ref;
12595
12596       procedure Replace_Type_Refs is new Traverse_Proc (Replace_Type_Ref);
12597
12598       -----------------------
12599       -- Visible_Component --
12600       -----------------------
12601
12602       function Visible_Component (Comp : Name_Id) return Entity_Id is
12603          E : Entity_Id;
12604
12605       begin
12606          if Ekind (T) /= E_Record_Type then
12607             return Empty;
12608
12609          else
12610             E := First_Entity (T);
12611             while Present (E) loop
12612                if Comes_From_Source (E) and then Chars (E) = Comp then
12613                   return E;
12614                end if;
12615
12616                Next_Entity (E);
12617             end loop;
12618
12619             return Empty;
12620          end if;
12621       end Visible_Component;
12622
12623    --  Start of processing for Replace_Type_References_Generic
12624
12625    begin
12626       Replace_Type_Refs (N);
12627    end Replace_Type_References_Generic;
12628
12629    --------------------------------
12630    -- Resolve_Aspect_Expressions --
12631    --------------------------------
12632
12633    procedure Resolve_Aspect_Expressions (E : Entity_Id) is
12634       ASN  : Node_Id;
12635       A_Id : Aspect_Id;
12636       Expr : Node_Id;
12637
12638       function Resolve_Name (N : Node_Id) return Traverse_Result;
12639       --  Verify that all identifiers in the expression, with the exception
12640       --  of references to the current entity, denote visible entities. This
12641       --  is done only to detect visibility errors, as the expression will be
12642       --  properly analyzed/expanded during analysis of the predicate function
12643       --  body. We omit quantified expressions from this test, given that they
12644       --  introduce a local identifier that would require proper expansion to
12645       --  handle properly.
12646
12647       ------------------
12648       -- Resolve_Name --
12649       ------------------
12650
12651       function Resolve_Name (N : Node_Id) return Traverse_Result is
12652       begin
12653          if Nkind (N) = N_Selected_Component then
12654             if Nkind (Prefix (N)) = N_Identifier
12655               and then Chars (Prefix (N)) /= Chars (E)
12656             then
12657                Find_Selected_Component (N);
12658             end if;
12659
12660             return Skip;
12661
12662          elsif Nkind (N) = N_Identifier and then Chars (N) /= Chars (E) then
12663             Find_Direct_Name (N);
12664             Set_Entity (N, Empty);
12665
12666          elsif Nkind (N) = N_Quantified_Expression then
12667             return Skip;
12668          end if;
12669
12670          return OK;
12671       end Resolve_Name;
12672
12673       procedure Resolve_Aspect_Expression is new Traverse_Proc (Resolve_Name);
12674
12675    --  Start of processing for Resolve_Aspect_Expressions
12676
12677    begin
12678       ASN := First_Rep_Item (E);
12679       while Present (ASN) loop
12680          if Nkind (ASN) = N_Aspect_Specification and then Entity (ASN) = E then
12681             A_Id := Get_Aspect_Id (ASN);
12682             Expr := Expression (ASN);
12683
12684             case A_Id is
12685
12686                --  For now we only deal with aspects that do not generate
12687                --  subprograms, or that may mention current instances of
12688                --  types. These will require special handling (???TBD).
12689
12690                when Aspect_Predicate         |
12691                     Aspect_Predicate_Failure |
12692                     Aspect_Invariant         =>
12693                   null;
12694
12695                when Aspect_Dynamic_Predicate |
12696                     Aspect_Static_Predicate  =>
12697
12698                   --  Build predicate function specification and preanalyze
12699                   --  expression after type replacement.
12700
12701                   if No (Predicate_Function (E)) then
12702                      declare
12703                         FDecl : constant Node_Id :=
12704                                   Build_Predicate_Function_Declaration (E);
12705                         pragma Unreferenced (FDecl);
12706                      begin
12707                         Resolve_Aspect_Expression (Expr);
12708                      end;
12709                   end if;
12710
12711                when Pre_Post_Aspects =>
12712                   null;
12713
12714                when Aspect_Iterable =>
12715                   if Nkind (Expr) = N_Aggregate then
12716                      declare
12717                         Assoc : Node_Id;
12718
12719                      begin
12720                         Assoc := First (Component_Associations (Expr));
12721                         while Present (Assoc) loop
12722                            Find_Direct_Name (Expression (Assoc));
12723                            Next (Assoc);
12724                         end loop;
12725                      end;
12726                   end if;
12727
12728                when others =>
12729                   if Present (Expr) then
12730                      case Aspect_Argument (A_Id) is
12731                         when Expression | Optional_Expression  =>
12732                            Analyze_And_Resolve (Expression (ASN));
12733
12734                         when Name | Optional_Name =>
12735                            if Nkind (Expr) = N_Identifier then
12736                               Find_Direct_Name (Expr);
12737
12738                            elsif Nkind (Expr) = N_Selected_Component then
12739                               Find_Selected_Component (Expr);
12740
12741                            else
12742                               null;
12743                            end if;
12744                      end case;
12745                   end if;
12746             end case;
12747          end if;
12748
12749          ASN := Next_Rep_Item (ASN);
12750       end loop;
12751    end Resolve_Aspect_Expressions;
12752
12753    -------------------------
12754    -- Same_Representation --
12755    -------------------------
12756
12757    function Same_Representation (Typ1, Typ2 : Entity_Id) return Boolean is
12758       T1 : constant Entity_Id := Underlying_Type (Typ1);
12759       T2 : constant Entity_Id := Underlying_Type (Typ2);
12760
12761    begin
12762       --  A quick check, if base types are the same, then we definitely have
12763       --  the same representation, because the subtype specific representation
12764       --  attributes (Size and Alignment) do not affect representation from
12765       --  the point of view of this test.
12766
12767       if Base_Type (T1) = Base_Type (T2) then
12768          return True;
12769
12770       elsif Is_Private_Type (Base_Type (T2))
12771         and then Base_Type (T1) = Full_View (Base_Type (T2))
12772       then
12773          return True;
12774       end if;
12775
12776       --  Tagged types never have differing representations
12777
12778       if Is_Tagged_Type (T1) then
12779          return True;
12780       end if;
12781
12782       --  Representations are definitely different if conventions differ
12783
12784       if Convention (T1) /= Convention (T2) then
12785          return False;
12786       end if;
12787
12788       --  Representations are different if component alignments or scalar
12789       --  storage orders differ.
12790
12791       if (Is_Record_Type (T1) or else Is_Array_Type (T1))
12792             and then
12793          (Is_Record_Type (T2) or else Is_Array_Type (T2))
12794         and then
12795          (Component_Alignment (T1) /= Component_Alignment (T2)
12796            or else Reverse_Storage_Order (T1) /= Reverse_Storage_Order (T2))
12797       then
12798          return False;
12799       end if;
12800
12801       --  For arrays, the only real issue is component size. If we know the
12802       --  component size for both arrays, and it is the same, then that's
12803       --  good enough to know we don't have a change of representation.
12804
12805       if Is_Array_Type (T1) then
12806          if Known_Component_Size (T1)
12807            and then Known_Component_Size (T2)
12808            and then Component_Size (T1) = Component_Size (T2)
12809          then
12810             return True;
12811          end if;
12812       end if;
12813
12814       --  Types definitely have same representation if neither has non-standard
12815       --  representation since default representations are always consistent.
12816       --  If only one has non-standard representation, and the other does not,
12817       --  then we consider that they do not have the same representation. They
12818       --  might, but there is no way of telling early enough.
12819
12820       if Has_Non_Standard_Rep (T1) then
12821          if not Has_Non_Standard_Rep (T2) then
12822             return False;
12823          end if;
12824       else
12825          return not Has_Non_Standard_Rep (T2);
12826       end if;
12827
12828       --  Here the two types both have non-standard representation, and we need
12829       --  to determine if they have the same non-standard representation.
12830
12831       --  For arrays, we simply need to test if the component sizes are the
12832       --  same. Pragma Pack is reflected in modified component sizes, so this
12833       --  check also deals with pragma Pack.
12834
12835       if Is_Array_Type (T1) then
12836          return Component_Size (T1) = Component_Size (T2);
12837
12838       --  Tagged types always have the same representation, because it is not
12839       --  possible to specify different representations for common fields.
12840
12841       elsif Is_Tagged_Type (T1) then
12842          return True;
12843
12844       --  Case of record types
12845
12846       elsif Is_Record_Type (T1) then
12847
12848          --  Packed status must conform
12849
12850          if Is_Packed (T1) /= Is_Packed (T2) then
12851             return False;
12852
12853          --  Otherwise we must check components. Typ2 maybe a constrained
12854          --  subtype with fewer components, so we compare the components
12855          --  of the base types.
12856
12857          else
12858             Record_Case : declare
12859                CD1, CD2 : Entity_Id;
12860
12861                function Same_Rep return Boolean;
12862                --  CD1 and CD2 are either components or discriminants. This
12863                --  function tests whether they have the same representation.
12864
12865                --------------
12866                -- Same_Rep --
12867                --------------
12868
12869                function Same_Rep return Boolean is
12870                begin
12871                   if No (Component_Clause (CD1)) then
12872                      return No (Component_Clause (CD2));
12873                   else
12874                      --  Note: at this point, component clauses have been
12875                      --  normalized to the default bit order, so that the
12876                      --  comparison of Component_Bit_Offsets is meaningful.
12877
12878                      return
12879                         Present (Component_Clause (CD2))
12880                           and then
12881                         Component_Bit_Offset (CD1) = Component_Bit_Offset (CD2)
12882                           and then
12883                         Esize (CD1) = Esize (CD2);
12884                   end if;
12885                end Same_Rep;
12886
12887             --  Start of processing for Record_Case
12888
12889             begin
12890                if Has_Discriminants (T1) then
12891
12892                   --  The number of discriminants may be different if the
12893                   --  derived type has fewer (constrained by values). The
12894                   --  invisible discriminants retain the representation of
12895                   --  the original, so the discrepancy does not per se
12896                   --  indicate a different representation.
12897
12898                   CD1 := First_Discriminant (T1);
12899                   CD2 := First_Discriminant (T2);
12900                   while Present (CD1) and then Present (CD2) loop
12901                      if not Same_Rep then
12902                         return False;
12903                      else
12904                         Next_Discriminant (CD1);
12905                         Next_Discriminant (CD2);
12906                      end if;
12907                   end loop;
12908                end if;
12909
12910                CD1 := First_Component (Underlying_Type (Base_Type (T1)));
12911                CD2 := First_Component (Underlying_Type (Base_Type (T2)));
12912                while Present (CD1) loop
12913                   if not Same_Rep then
12914                      return False;
12915                   else
12916                      Next_Component (CD1);
12917                      Next_Component (CD2);
12918                   end if;
12919                end loop;
12920
12921                return True;
12922             end Record_Case;
12923          end if;
12924
12925       --  For enumeration types, we must check each literal to see if the
12926       --  representation is the same. Note that we do not permit enumeration
12927       --  representation clauses for Character and Wide_Character, so these
12928       --  cases were already dealt with.
12929
12930       elsif Is_Enumeration_Type (T1) then
12931          Enumeration_Case : declare
12932             L1, L2 : Entity_Id;
12933
12934          begin
12935             L1 := First_Literal (T1);
12936             L2 := First_Literal (T2);
12937             while Present (L1) loop
12938                if Enumeration_Rep (L1) /= Enumeration_Rep (L2) then
12939                   return False;
12940                else
12941                   Next_Literal (L1);
12942                   Next_Literal (L2);
12943                end if;
12944             end loop;
12945
12946             return True;
12947          end Enumeration_Case;
12948
12949       --  Any other types have the same representation for these purposes
12950
12951       else
12952          return True;
12953       end if;
12954    end Same_Representation;
12955
12956    --------------------------------
12957    -- Resolve_Iterable_Operation --
12958    --------------------------------
12959
12960    procedure Resolve_Iterable_Operation
12961      (N      : Node_Id;
12962       Cursor : Entity_Id;
12963       Typ    : Entity_Id;
12964       Nam    : Name_Id)
12965    is
12966       Ent : Entity_Id;
12967       F1  : Entity_Id;
12968       F2  : Entity_Id;
12969
12970    begin
12971       if not Is_Overloaded (N) then
12972          if not Is_Entity_Name (N)
12973            or else Ekind (Entity (N)) /= E_Function
12974            or else Scope (Entity (N)) /= Scope (Typ)
12975            or else No (First_Formal (Entity (N)))
12976            or else Etype (First_Formal (Entity (N))) /= Typ
12977          then
12978             Error_Msg_N ("iterable primitive must be local function name "
12979                          & "whose first formal is an iterable type", N);
12980             return;
12981          end if;
12982
12983          Ent := Entity (N);
12984          F1 := First_Formal (Ent);
12985          if Nam = Name_First then
12986
12987             --  First (Container) => Cursor
12988
12989             if Etype (Ent) /= Cursor then
12990                Error_Msg_N ("primitive for First must yield a curosr", N);
12991             end if;
12992
12993          elsif Nam = Name_Next then
12994
12995             --  Next (Container, Cursor) => Cursor
12996
12997             F2 := Next_Formal (F1);
12998
12999             if Etype (F2) /= Cursor
13000               or else Etype (Ent) /= Cursor
13001               or else Present (Next_Formal (F2))
13002             then
13003                Error_Msg_N ("no match for Next iterable primitive", N);
13004             end if;
13005
13006          elsif Nam = Name_Has_Element then
13007
13008             --  Has_Element (Container, Cursor) => Boolean
13009
13010             F2 := Next_Formal (F1);
13011             if Etype (F2) /= Cursor
13012               or else Etype (Ent) /= Standard_Boolean
13013               or else Present (Next_Formal (F2))
13014             then
13015                Error_Msg_N ("no match for Has_Element iterable primitive", N);
13016             end if;
13017
13018          elsif Nam = Name_Element then
13019             F2 := Next_Formal (F1);
13020
13021             if No (F2)
13022               or else Etype (F2) /= Cursor
13023               or else Present (Next_Formal (F2))
13024             then
13025                Error_Msg_N ("no match for Element iterable primitive", N);
13026             end if;
13027             null;
13028
13029          else
13030             raise Program_Error;
13031          end if;
13032
13033       else
13034          --  Overloaded case: find subprogram with proper signature.
13035          --  Caller will report error if no match is found.
13036
13037          declare
13038             I  : Interp_Index;
13039             It : Interp;
13040
13041          begin
13042             Get_First_Interp (N, I, It);
13043             while Present (It.Typ) loop
13044                if Ekind (It.Nam) = E_Function
13045                   and then Scope (It.Nam) = Scope (Typ)
13046                   and then Etype (First_Formal (It.Nam)) = Typ
13047                then
13048                   F1 := First_Formal (It.Nam);
13049
13050                   if Nam = Name_First then
13051                      if Etype (It.Nam) = Cursor
13052                        and then No (Next_Formal (F1))
13053                      then
13054                         Set_Entity (N, It.Nam);
13055                         exit;
13056                      end if;
13057
13058                   elsif Nam = Name_Next then
13059                      F2 := Next_Formal (F1);
13060
13061                      if Present (F2)
13062                        and then No (Next_Formal (F2))
13063                        and then Etype (F2) = Cursor
13064                        and then Etype (It.Nam) = Cursor
13065                      then
13066                         Set_Entity (N, It.Nam);
13067                         exit;
13068                      end if;
13069
13070                   elsif Nam = Name_Has_Element then
13071                      F2 := Next_Formal (F1);
13072
13073                      if Present (F2)
13074                        and then No (Next_Formal (F2))
13075                        and then Etype (F2) = Cursor
13076                        and then Etype (It.Nam) = Standard_Boolean
13077                      then
13078                         Set_Entity (N, It.Nam);
13079                         F2 := Next_Formal (F1);
13080                         exit;
13081                      end if;
13082
13083                   elsif Nam = Name_Element then
13084                      F2 := Next_Formal (F1);
13085
13086                      if Present (F2)
13087                        and then No (Next_Formal (F2))
13088                        and then Etype (F2) = Cursor
13089                      then
13090                         Set_Entity (N, It.Nam);
13091                         exit;
13092                      end if;
13093                   end if;
13094                end if;
13095
13096                Get_Next_Interp (I, It);
13097             end loop;
13098          end;
13099       end if;
13100    end Resolve_Iterable_Operation;
13101
13102    ----------------
13103    -- Set_Biased --
13104    ----------------
13105
13106    procedure Set_Biased
13107      (E      : Entity_Id;
13108       N      : Node_Id;
13109       Msg    : String;
13110       Biased : Boolean := True)
13111    is
13112    begin
13113       if Biased then
13114          Set_Has_Biased_Representation (E);
13115
13116          if Warn_On_Biased_Representation then
13117             Error_Msg_NE
13118               ("?B?" & Msg & " forces biased representation for&", N, E);
13119          end if;
13120       end if;
13121    end Set_Biased;
13122
13123    --------------------
13124    -- Set_Enum_Esize --
13125    --------------------
13126
13127    procedure Set_Enum_Esize (T : Entity_Id) is
13128       Lo : Uint;
13129       Hi : Uint;
13130       Sz : Nat;
13131
13132    begin
13133       Init_Alignment (T);
13134
13135       --  Find the minimum standard size (8,16,32,64) that fits
13136
13137       Lo := Enumeration_Rep (Entity (Type_Low_Bound (T)));
13138       Hi := Enumeration_Rep (Entity (Type_High_Bound (T)));
13139
13140       if Lo < 0 then
13141          if Lo >= -Uint_2**07 and then Hi < Uint_2**07 then
13142             Sz := Standard_Character_Size;  -- May be > 8 on some targets
13143
13144          elsif Lo >= -Uint_2**15 and then Hi < Uint_2**15 then
13145             Sz := 16;
13146
13147          elsif Lo >= -Uint_2**31 and then Hi < Uint_2**31 then
13148             Sz := 32;
13149
13150          else pragma Assert (Lo >= -Uint_2**63 and then Hi < Uint_2**63);
13151             Sz := 64;
13152          end if;
13153
13154       else
13155          if Hi < Uint_2**08 then
13156             Sz := Standard_Character_Size;  -- May be > 8 on some targets
13157
13158          elsif Hi < Uint_2**16 then
13159             Sz := 16;
13160
13161          elsif Hi < Uint_2**32 then
13162             Sz := 32;
13163
13164          else pragma Assert (Hi < Uint_2**63);
13165             Sz := 64;
13166          end if;
13167       end if;
13168
13169       --  That minimum is the proper size unless we have a foreign convention
13170       --  and the size required is 32 or less, in which case we bump the size
13171       --  up to 32. This is required for C and C++ and seems reasonable for
13172       --  all other foreign conventions.
13173
13174       if Has_Foreign_Convention (T)
13175         and then Esize (T) < Standard_Integer_Size
13176
13177         --  Don't do this if Short_Enums on target
13178
13179         and then not Target_Short_Enums
13180       then
13181          Init_Esize (T, Standard_Integer_Size);
13182       else
13183          Init_Esize (T, Sz);
13184       end if;
13185    end Set_Enum_Esize;
13186
13187    -----------------------------
13188    -- Uninstall_Discriminants --
13189    -----------------------------
13190
13191    procedure Uninstall_Discriminants (E : Entity_Id) is
13192       Disc  : Entity_Id;
13193       Prev  : Entity_Id;
13194       Outer : Entity_Id;
13195
13196    begin
13197       --  Discriminants have been made visible for type declarations and
13198       --  protected type declarations, not for subtype declarations.
13199
13200       if Nkind (Parent (E)) /= N_Subtype_Declaration then
13201          Disc := First_Discriminant (E);
13202          while Present (Disc) loop
13203             if Disc /= Current_Entity (Disc) then
13204                Prev := Current_Entity (Disc);
13205                while Present (Prev)
13206                  and then Present (Homonym (Prev))
13207                  and then Homonym (Prev) /= Disc
13208                loop
13209                   Prev := Homonym (Prev);
13210                end loop;
13211             else
13212                Prev := Empty;
13213             end if;
13214
13215             Set_Is_Immediately_Visible (Disc, False);
13216
13217             Outer := Homonym (Disc);
13218             while Present (Outer) and then Scope (Outer) = E loop
13219                Outer := Homonym (Outer);
13220             end loop;
13221
13222             --  Reset homonym link of other entities, but do not modify link
13223             --  between entities in current scope, so that the back end can
13224             --  have a proper count of local overloadings.
13225
13226             if No (Prev) then
13227                Set_Name_Entity_Id (Chars (Disc), Outer);
13228
13229             elsif Scope (Prev) /= Scope (Disc) then
13230                Set_Homonym (Prev,  Outer);
13231             end if;
13232
13233             Next_Discriminant (Disc);
13234          end loop;
13235       end if;
13236    end Uninstall_Discriminants;
13237
13238    -------------------------------------------
13239    -- Uninstall_Discriminants_And_Pop_Scope --
13240    -------------------------------------------
13241
13242    procedure Uninstall_Discriminants_And_Pop_Scope (E : Entity_Id) is
13243    begin
13244       if Has_Discriminants (E) then
13245          Uninstall_Discriminants (E);
13246          Pop_Scope;
13247       end if;
13248    end Uninstall_Discriminants_And_Pop_Scope;
13249
13250    ------------------------------
13251    -- Validate_Address_Clauses --
13252    ------------------------------
13253
13254    procedure Validate_Address_Clauses is
13255       function Offset_Value (Expr : Node_Id) return Uint;
13256       --  Given an Address attribute reference, return the value in bits of its
13257       --  offset from the first bit of the underlying entity, or 0 if it is not
13258       --  known at compile time.
13259
13260       ------------------
13261       -- Offset_Value --
13262       ------------------
13263
13264       function Offset_Value (Expr : Node_Id) return Uint is
13265          N   : Node_Id := Prefix (Expr);
13266          Off : Uint;
13267          Val : Uint := Uint_0;
13268
13269       begin
13270          --  Climb the prefix chain and compute the cumulative offset
13271
13272          loop
13273             if Is_Entity_Name (N) then
13274                return Val;
13275
13276             elsif Nkind (N) = N_Selected_Component then
13277                Off := Component_Bit_Offset (Entity (Selector_Name (N)));
13278                if Off /= No_Uint and then Off >= Uint_0 then
13279                   Val := Val + Off;
13280                   N   := Prefix (N);
13281                else
13282                   return Uint_0;
13283                end if;
13284
13285             elsif Nkind (N) = N_Indexed_Component then
13286                Off := Indexed_Component_Bit_Offset (N);
13287                if Off /= No_Uint then
13288                   Val := Val + Off;
13289                   N   := Prefix (N);
13290                else
13291                   return Uint_0;
13292                end if;
13293
13294             else
13295                return Uint_0;
13296             end if;
13297          end loop;
13298       end Offset_Value;
13299
13300    --  Start of processing for Validate_Address_Clauses
13301
13302    begin
13303       for J in Address_Clause_Checks.First .. Address_Clause_Checks.Last loop
13304          declare
13305             ACCR : Address_Clause_Check_Record
13306                      renames Address_Clause_Checks.Table (J);
13307
13308             Expr : Node_Id;
13309
13310             X_Alignment : Uint;
13311             Y_Alignment : Uint;
13312
13313             X_Size : Uint;
13314             Y_Size : Uint;
13315
13316             X_Offs : Uint;
13317
13318          begin
13319             --  Skip processing of this entry if warning already posted
13320
13321             if not Address_Warning_Posted (ACCR.N) then
13322                Expr := Original_Node (Expression (ACCR.N));
13323
13324                --  Get alignments, sizes and offset, if any
13325
13326                X_Alignment := Alignment (ACCR.X);
13327                X_Size      := Esize (ACCR.X);
13328
13329                if Present (ACCR.Y) then
13330                   Y_Alignment := Alignment (ACCR.Y);
13331                   Y_Size      := Esize (ACCR.Y);
13332                end if;
13333
13334                if ACCR.Off
13335                  and then Nkind (Expr) = N_Attribute_Reference
13336                  and then Attribute_Name (Expr) = Name_Address
13337                then
13338                   X_Offs := Offset_Value (Expr);
13339                else
13340                   X_Offs := Uint_0;
13341                end if;
13342
13343                --  Check for known value not multiple of alignment
13344
13345                if No (ACCR.Y) then
13346                   if not Alignment_Checks_Suppressed (ACCR.X)
13347                     and then X_Alignment /= 0
13348                     and then ACCR.A mod X_Alignment /= 0
13349                   then
13350                      Error_Msg_NE
13351                        ("??specified address for& is inconsistent with "
13352                         & "alignment", ACCR.N, ACCR.X);
13353                      Error_Msg_N
13354                        ("\??program execution may be erroneous (RM 13.3(27))",
13355                         ACCR.N);
13356
13357                      Error_Msg_Uint_1 := X_Alignment;
13358                      Error_Msg_NE ("\??alignment of & is ^", ACCR.N, ACCR.X);
13359                   end if;
13360
13361                --  Check for large object overlaying smaller one
13362
13363                elsif Y_Size > Uint_0
13364                  and then X_Size > Uint_0
13365                  and then X_Offs + X_Size > Y_Size
13366                then
13367                   Error_Msg_NE ("??& overlays smaller object", ACCR.N, ACCR.X);
13368                   Error_Msg_N
13369                     ("\??program execution may be erroneous", ACCR.N);
13370
13371                   Error_Msg_Uint_1 := X_Size;
13372                   Error_Msg_NE ("\??size of & is ^", ACCR.N, ACCR.X);
13373
13374                   Error_Msg_Uint_1 := Y_Size;
13375                   Error_Msg_NE ("\??size of & is ^", ACCR.N, ACCR.Y);
13376
13377                   if Y_Size >= X_Size then
13378                      Error_Msg_Uint_1 := X_Offs;
13379                      Error_Msg_NE ("\??but offset of & is ^", ACCR.N, ACCR.X);
13380                   end if;
13381
13382                --  Check for inadequate alignment, both of the base object
13383                --  and of the offset, if any. We only do this check if the
13384                --  run-time Alignment_Check is active. No point in warning
13385                --  if this check has been suppressed (or is suppressed by
13386                --  default in the non-strict alignment machine case).
13387
13388                --  Note: we do not check the alignment if we gave a size
13389                --  warning, since it would likely be redundant.
13390
13391                elsif not Alignment_Checks_Suppressed (ACCR.X)
13392                  and then Y_Alignment /= Uint_0
13393                  and then
13394                    (Y_Alignment < X_Alignment
13395                      or else
13396                        (ACCR.Off
13397                          and then Nkind (Expr) = N_Attribute_Reference
13398                          and then Attribute_Name (Expr) = Name_Address
13399                          and then Has_Compatible_Alignment
13400                                     (ACCR.X, Prefix (Expr), True) /=
13401                                       Known_Compatible))
13402                then
13403                   Error_Msg_NE
13404                     ("??specified address for& may be inconsistent with "
13405                      & "alignment", ACCR.N, ACCR.X);
13406                   Error_Msg_N
13407                     ("\??program execution may be erroneous (RM 13.3(27))",
13408                      ACCR.N);
13409
13410                   Error_Msg_Uint_1 := X_Alignment;
13411                   Error_Msg_NE ("\??alignment of & is ^", ACCR.N, ACCR.X);
13412
13413                   Error_Msg_Uint_1 := Y_Alignment;
13414                   Error_Msg_NE ("\??alignment of & is ^", ACCR.N, ACCR.Y);
13415
13416                   if Y_Alignment >= X_Alignment then
13417                      Error_Msg_N
13418                        ("\??but offset is not multiple of alignment", ACCR.N);
13419                   end if;
13420                end if;
13421             end if;
13422          end;
13423       end loop;
13424    end Validate_Address_Clauses;
13425
13426    -----------------------------------------
13427    -- Validate_Compile_Time_Warning_Error --
13428    -----------------------------------------
13429
13430    procedure Validate_Compile_Time_Warning_Error (N : Node_Id) is
13431    begin
13432       Compile_Time_Warnings_Errors.Append
13433         (New_Val => CTWE_Entry'(Eloc  => Sloc (N),
13434                                 Scope => Current_Scope,
13435                                 Prag  => N));
13436    end Validate_Compile_Time_Warning_Error;
13437
13438    ------------------------------------------
13439    -- Validate_Compile_Time_Warning_Errors --
13440    ------------------------------------------
13441
13442    procedure Validate_Compile_Time_Warning_Errors is
13443       procedure Set_Scope (S : Entity_Id);
13444       --  Install all enclosing scopes of S along with S itself
13445
13446       procedure Unset_Scope (S : Entity_Id);
13447       --  Uninstall all enclosing scopes of S along with S itself
13448
13449       ---------------
13450       -- Set_Scope --
13451       ---------------
13452
13453       procedure Set_Scope (S : Entity_Id) is
13454       begin
13455          if S /= Standard_Standard then
13456             Set_Scope (Scope (S));
13457          end if;
13458
13459          Push_Scope (S);
13460       end Set_Scope;
13461
13462       -----------------
13463       -- Unset_Scope --
13464       -----------------
13465
13466       procedure Unset_Scope (S : Entity_Id) is
13467       begin
13468          if S /= Standard_Standard then
13469             Unset_Scope (Scope (S));
13470          end if;
13471
13472          Pop_Scope;
13473       end Unset_Scope;
13474
13475    --  Start of processing for Validate_Compile_Time_Warning_Errors
13476
13477    begin
13478       Expander_Mode_Save_And_Set (False);
13479       In_Compile_Time_Warning_Or_Error := True;
13480
13481       for N in Compile_Time_Warnings_Errors.First ..
13482                Compile_Time_Warnings_Errors.Last
13483       loop
13484          declare
13485             T : CTWE_Entry renames Compile_Time_Warnings_Errors.Table (N);
13486
13487          begin
13488             Set_Scope (T.Scope);
13489             Reset_Analyzed_Flags (T.Prag);
13490             Process_Compile_Time_Warning_Or_Error (T.Prag, T.Eloc);
13491             Unset_Scope (T.Scope);
13492          end;
13493       end loop;
13494
13495       In_Compile_Time_Warning_Or_Error := False;
13496       Expander_Mode_Restore;
13497    end Validate_Compile_Time_Warning_Errors;
13498
13499    ---------------------------
13500    -- Validate_Independence --
13501    ---------------------------
13502
13503    procedure Validate_Independence is
13504       SU   : constant Uint := UI_From_Int (System_Storage_Unit);
13505       N    : Node_Id;
13506       E    : Entity_Id;
13507       IC   : Boolean;
13508       Comp : Entity_Id;
13509       Addr : Node_Id;
13510       P    : Node_Id;
13511
13512       procedure Check_Array_Type (Atyp : Entity_Id);
13513       --  Checks if the array type Atyp has independent components, and
13514       --  if not, outputs an appropriate set of error messages.
13515
13516       procedure No_Independence;
13517       --  Output message that independence cannot be guaranteed
13518
13519       function OK_Component (C : Entity_Id) return Boolean;
13520       --  Checks one component to see if it is independently accessible, and
13521       --  if so yields True, otherwise yields False if independent access
13522       --  cannot be guaranteed. This is a conservative routine, it only
13523       --  returns True if it knows for sure, it returns False if it knows
13524       --  there is a problem, or it cannot be sure there is no problem.
13525
13526       procedure Reason_Bad_Component (C : Entity_Id);
13527       --  Outputs continuation message if a reason can be determined for
13528       --  the component C being bad.
13529
13530       ----------------------
13531       -- Check_Array_Type --
13532       ----------------------
13533
13534       procedure Check_Array_Type (Atyp : Entity_Id) is
13535          Ctyp : constant Entity_Id := Component_Type (Atyp);
13536
13537       begin
13538          --  OK if no alignment clause, no pack, and no component size
13539
13540          if not Has_Component_Size_Clause (Atyp)
13541            and then not Has_Alignment_Clause (Atyp)
13542            and then not Is_Packed (Atyp)
13543          then
13544             return;
13545          end if;
13546
13547          --  Case of component size is greater than or equal to 64 and the
13548          --  alignment of the array is at least as large as the alignment
13549          --  of the component. We are definitely OK in this situation.
13550
13551          if Known_Component_Size (Atyp)
13552            and then Component_Size (Atyp) >= 64
13553            and then Known_Alignment (Atyp)
13554            and then Known_Alignment (Ctyp)
13555            and then Alignment (Atyp) >= Alignment (Ctyp)
13556          then
13557             return;
13558          end if;
13559
13560          --  Check actual component size
13561
13562          if not Known_Component_Size (Atyp)
13563            or else not (Addressable (Component_Size (Atyp))
13564                          and then Component_Size (Atyp) < 64)
13565            or else Component_Size (Atyp) mod Esize (Ctyp) /= 0
13566          then
13567             No_Independence;
13568
13569             --  Bad component size, check reason
13570
13571             if Has_Component_Size_Clause (Atyp) then
13572                P := Get_Attribute_Definition_Clause
13573                       (Atyp, Attribute_Component_Size);
13574
13575                if Present (P) then
13576                   Error_Msg_Sloc := Sloc (P);
13577                   Error_Msg_N ("\because of Component_Size clause#", N);
13578                   return;
13579                end if;
13580             end if;
13581
13582             if Is_Packed (Atyp) then
13583                P := Get_Rep_Pragma (Atyp, Name_Pack);
13584
13585                if Present (P) then
13586                   Error_Msg_Sloc := Sloc (P);
13587                   Error_Msg_N ("\because of pragma Pack#", N);
13588                   return;
13589                end if;
13590             end if;
13591
13592             --  No reason found, just return
13593
13594             return;
13595          end if;
13596
13597          --  Array type is OK independence-wise
13598
13599          return;
13600       end Check_Array_Type;
13601
13602       ---------------------
13603       -- No_Independence --
13604       ---------------------
13605
13606       procedure No_Independence is
13607       begin
13608          if Pragma_Name (N) = Name_Independent then
13609             Error_Msg_NE ("independence cannot be guaranteed for&", N, E);
13610          else
13611             Error_Msg_NE
13612               ("independent components cannot be guaranteed for&", N, E);
13613          end if;
13614       end No_Independence;
13615
13616       ------------------
13617       -- OK_Component --
13618       ------------------
13619
13620       function OK_Component (C : Entity_Id) return Boolean is
13621          Rec  : constant Entity_Id := Scope (C);
13622          Ctyp : constant Entity_Id := Etype (C);
13623
13624       begin
13625          --  OK if no component clause, no Pack, and no alignment clause
13626
13627          if No (Component_Clause (C))
13628            and then not Is_Packed (Rec)
13629            and then not Has_Alignment_Clause (Rec)
13630          then
13631             return True;
13632          end if;
13633
13634          --  Here we look at the actual component layout. A component is
13635          --  addressable if its size is a multiple of the Esize of the
13636          --  component type, and its starting position in the record has
13637          --  appropriate alignment, and the record itself has appropriate
13638          --  alignment to guarantee the component alignment.
13639
13640          --  Make sure sizes are static, always assume the worst for any
13641          --  cases where we cannot check static values.
13642
13643          if not (Known_Static_Esize (C)
13644                   and then
13645                  Known_Static_Esize (Ctyp))
13646          then
13647             return False;
13648          end if;
13649
13650          --  Size of component must be addressable or greater than 64 bits
13651          --  and a multiple of bytes.
13652
13653          if not Addressable (Esize (C)) and then Esize (C) < Uint_64 then
13654             return False;
13655          end if;
13656
13657          --  Check size is proper multiple
13658
13659          if Esize (C) mod Esize (Ctyp) /= 0 then
13660             return False;
13661          end if;
13662
13663          --  Check alignment of component is OK
13664
13665          if not Known_Component_Bit_Offset (C)
13666            or else Component_Bit_Offset (C) < Uint_0
13667            or else Component_Bit_Offset (C) mod Esize (Ctyp) /= 0
13668          then
13669             return False;
13670          end if;
13671
13672          --  Check alignment of record type is OK
13673
13674          if not Known_Alignment (Rec)
13675            or else (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
13676          then
13677             return False;
13678          end if;
13679
13680          --  All tests passed, component is addressable
13681
13682          return True;
13683       end OK_Component;
13684
13685       --------------------------
13686       -- Reason_Bad_Component --
13687       --------------------------
13688
13689       procedure Reason_Bad_Component (C : Entity_Id) is
13690          Rec  : constant Entity_Id := Scope (C);
13691          Ctyp : constant Entity_Id := Etype (C);
13692
13693       begin
13694          --  If component clause present assume that's the problem
13695
13696          if Present (Component_Clause (C)) then
13697             Error_Msg_Sloc := Sloc (Component_Clause (C));
13698             Error_Msg_N ("\because of Component_Clause#", N);
13699             return;
13700          end if;
13701
13702          --  If pragma Pack clause present, assume that's the problem
13703
13704          if Is_Packed (Rec) then
13705             P := Get_Rep_Pragma (Rec, Name_Pack);
13706
13707             if Present (P) then
13708                Error_Msg_Sloc := Sloc (P);
13709                Error_Msg_N ("\because of pragma Pack#", N);
13710                return;
13711             end if;
13712          end if;
13713
13714          --  See if record has bad alignment clause
13715
13716          if Has_Alignment_Clause (Rec)
13717            and then Known_Alignment (Rec)
13718            and then (Alignment (Rec) * SU) mod Esize (Ctyp) /= 0
13719          then
13720             P := Get_Attribute_Definition_Clause (Rec, Attribute_Alignment);
13721
13722             if Present (P) then
13723                Error_Msg_Sloc := Sloc (P);
13724                Error_Msg_N ("\because of Alignment clause#", N);
13725             end if;
13726          end if;
13727
13728          --  Couldn't find a reason, so return without a message
13729
13730          return;
13731       end Reason_Bad_Component;
13732
13733    --  Start of processing for Validate_Independence
13734
13735    begin
13736       for J in Independence_Checks.First .. Independence_Checks.Last loop
13737          N  := Independence_Checks.Table (J).N;
13738          E  := Independence_Checks.Table (J).E;
13739          IC := Pragma_Name (N) = Name_Independent_Components;
13740
13741          --  Deal with component case
13742
13743          if Ekind (E) = E_Discriminant or else Ekind (E) = E_Component then
13744             if not OK_Component (E) then
13745                No_Independence;
13746                Reason_Bad_Component (E);
13747                goto Continue;
13748             end if;
13749          end if;
13750
13751          --  Deal with record with Independent_Components
13752
13753          if IC and then Is_Record_Type (E) then
13754             Comp := First_Component_Or_Discriminant (E);
13755             while Present (Comp) loop
13756                if not OK_Component (Comp) then
13757                   No_Independence;
13758                   Reason_Bad_Component (Comp);
13759                   goto Continue;
13760                end if;
13761
13762                Next_Component_Or_Discriminant (Comp);
13763             end loop;
13764          end if;
13765
13766          --  Deal with address clause case
13767
13768          if Is_Object (E) then
13769             Addr := Address_Clause (E);
13770
13771             if Present (Addr) then
13772                No_Independence;
13773                Error_Msg_Sloc := Sloc (Addr);
13774                Error_Msg_N ("\because of Address clause#", N);
13775                goto Continue;
13776             end if;
13777          end if;
13778
13779          --  Deal with independent components for array type
13780
13781          if IC and then Is_Array_Type (E) then
13782             Check_Array_Type (E);
13783          end if;
13784
13785          --  Deal with independent components for array object
13786
13787          if IC and then Is_Object (E) and then Is_Array_Type (Etype (E)) then
13788             Check_Array_Type (Etype (E));
13789          end if;
13790
13791       <<Continue>> null;
13792       end loop;
13793    end Validate_Independence;
13794
13795    ------------------------------
13796    -- Validate_Iterable_Aspect --
13797    ------------------------------
13798
13799    procedure Validate_Iterable_Aspect (Typ : Entity_Id; ASN : Node_Id) is
13800       Assoc : Node_Id;
13801       Expr  : Node_Id;
13802
13803       Prim   : Node_Id;
13804       Cursor : constant Entity_Id := Get_Cursor_Type (ASN, Typ);
13805
13806       First_Id       : Entity_Id;
13807       Next_Id        : Entity_Id;
13808       Has_Element_Id : Entity_Id;
13809       Element_Id     : Entity_Id;
13810
13811    begin
13812       --  If previous error aspect is unusable
13813
13814       if Cursor = Any_Type then
13815          return;
13816       end if;
13817
13818       First_Id       := Empty;
13819       Next_Id        := Empty;
13820       Has_Element_Id := Empty;
13821       Element_Id     := Empty;
13822
13823       --  Each expression must resolve to a function with the proper signature
13824
13825       Assoc := First (Component_Associations (Expression (ASN)));
13826       while Present (Assoc) loop
13827          Expr := Expression (Assoc);
13828          Analyze (Expr);
13829
13830          Prim := First (Choices (Assoc));
13831
13832          if Nkind (Prim) /= N_Identifier or else Present (Next (Prim)) then
13833             Error_Msg_N ("illegal name in association", Prim);
13834
13835          elsif Chars (Prim) = Name_First then
13836             Resolve_Iterable_Operation (Expr, Cursor, Typ, Name_First);
13837             First_Id := Entity (Expr);
13838
13839          elsif Chars (Prim) = Name_Next then
13840             Resolve_Iterable_Operation (Expr, Cursor, Typ, Name_Next);
13841             Next_Id := Entity (Expr);
13842
13843          elsif Chars (Prim) = Name_Has_Element then
13844             Resolve_Iterable_Operation (Expr, Cursor, Typ, Name_Has_Element);
13845             Has_Element_Id := Entity (Expr);
13846
13847          elsif Chars (Prim) = Name_Element then
13848             Resolve_Iterable_Operation (Expr, Cursor, Typ, Name_Element);
13849             Element_Id := Entity (Expr);
13850
13851          else
13852             Error_Msg_N ("invalid name for iterable function", Prim);
13853          end if;
13854
13855          Next (Assoc);
13856       end loop;
13857
13858       if No (First_Id) then
13859          Error_Msg_N ("match for First primitive not found", ASN);
13860
13861       elsif No (Next_Id) then
13862          Error_Msg_N ("match for Next primitive not found", ASN);
13863
13864       elsif No (Has_Element_Id) then
13865          Error_Msg_N ("match for Has_Element primitive not found", ASN);
13866
13867       elsif No (Element_Id) then
13868          null;  --  Optional.
13869       end if;
13870    end Validate_Iterable_Aspect;
13871
13872    -----------------------------------
13873    -- Validate_Unchecked_Conversion --
13874    -----------------------------------
13875
13876    procedure Validate_Unchecked_Conversion
13877      (N        : Node_Id;
13878       Act_Unit : Entity_Id)
13879    is
13880       Source : Entity_Id;
13881       Target : Entity_Id;
13882       Vnode  : Node_Id;
13883
13884    begin
13885       --  Obtain source and target types. Note that we call Ancestor_Subtype
13886       --  here because the processing for generic instantiation always makes
13887       --  subtypes, and we want the original frozen actual types.
13888
13889       --  If we are dealing with private types, then do the check on their
13890       --  fully declared counterparts if the full declarations have been
13891       --  encountered (they don't have to be visible, but they must exist).
13892
13893       Source := Ancestor_Subtype (Etype (First_Formal (Act_Unit)));
13894
13895       if Is_Private_Type (Source)
13896         and then Present (Underlying_Type (Source))
13897       then
13898          Source := Underlying_Type (Source);
13899       end if;
13900
13901       Target := Ancestor_Subtype (Etype (Act_Unit));
13902
13903       --  If either type is generic, the instantiation happens within a generic
13904       --  unit, and there is nothing to check. The proper check will happen
13905       --  when the enclosing generic is instantiated.
13906
13907       if Is_Generic_Type (Source) or else Is_Generic_Type (Target) then
13908          return;
13909       end if;
13910
13911       if Is_Private_Type (Target)
13912         and then Present (Underlying_Type (Target))
13913       then
13914          Target := Underlying_Type (Target);
13915       end if;
13916
13917       --  Source may be unconstrained array, but not target, except in relaxed
13918       --  semantics mode.
13919
13920       if Is_Array_Type (Target)
13921         and then not Is_Constrained (Target)
13922         and then not Relaxed_RM_Semantics
13923       then
13924          Error_Msg_N
13925            ("unchecked conversion to unconstrained array not allowed", N);
13926          return;
13927       end if;
13928
13929       --  Warn if conversion between two different convention pointers
13930
13931       if Is_Access_Type (Target)
13932         and then Is_Access_Type (Source)
13933         and then Convention (Target) /= Convention (Source)
13934         and then Warn_On_Unchecked_Conversion
13935       then
13936          --  Give warnings for subprogram pointers only on most targets
13937
13938          if Is_Access_Subprogram_Type (Target)
13939            or else Is_Access_Subprogram_Type (Source)
13940          then
13941             Error_Msg_N
13942               ("?z?conversion between pointers with different conventions!",
13943                N);
13944          end if;
13945       end if;
13946
13947       --  Warn if one of the operands is Ada.Calendar.Time. Do not emit a
13948       --  warning when compiling GNAT-related sources.
13949
13950       if Warn_On_Unchecked_Conversion
13951         and then not In_Predefined_Unit (N)
13952         and then RTU_Loaded (Ada_Calendar)
13953         and then (Chars (Source) = Name_Time
13954                     or else
13955                   Chars (Target) = Name_Time)
13956       then
13957          --  If Ada.Calendar is loaded and the name of one of the operands is
13958          --  Time, there is a good chance that this is Ada.Calendar.Time.
13959
13960          declare
13961             Calendar_Time : constant Entity_Id := Full_View (RTE (RO_CA_Time));
13962          begin
13963             pragma Assert (Present (Calendar_Time));
13964
13965             if Source = Calendar_Time or else Target = Calendar_Time then
13966                Error_Msg_N
13967                  ("?z?representation of 'Time values may change between "
13968                   & "'G'N'A'T versions", N);
13969             end if;
13970          end;
13971       end if;
13972
13973       --  Make entry in unchecked conversion table for later processing by
13974       --  Validate_Unchecked_Conversions, which will check sizes and alignments
13975       --  (using values set by the back end where possible). This is only done
13976       --  if the appropriate warning is active.
13977
13978       if Warn_On_Unchecked_Conversion then
13979          Unchecked_Conversions.Append
13980            (New_Val => UC_Entry'(Eloc     => Sloc (N),
13981                                  Source   => Source,
13982                                  Target   => Target,
13983                                  Act_Unit => Act_Unit));
13984
13985          --  If both sizes are known statically now, then back-end annotation
13986          --  is not required to do a proper check but if either size is not
13987          --  known statically, then we need the annotation.
13988
13989          if Known_Static_RM_Size (Source)
13990               and then
13991             Known_Static_RM_Size (Target)
13992          then
13993             null;
13994          else
13995             Back_Annotate_Rep_Info := True;
13996          end if;
13997       end if;
13998
13999       --  If unchecked conversion to access type, and access type is declared
14000       --  in the same unit as the unchecked conversion, then set the flag
14001       --  No_Strict_Aliasing (no strict aliasing is implicit here)
14002
14003       if Is_Access_Type (Target) and then
14004         In_Same_Source_Unit (Target, N)
14005       then
14006          Set_No_Strict_Aliasing (Implementation_Base_Type (Target));
14007       end if;
14008
14009       --  Generate N_Validate_Unchecked_Conversion node for back end in case
14010       --  the back end needs to perform special validation checks.
14011
14012       --  Shouldn't this be in Exp_Ch13, since the check only gets done if we
14013       --  have full expansion and the back end is called ???
14014
14015       Vnode :=
14016         Make_Validate_Unchecked_Conversion (Sloc (N));
14017       Set_Source_Type (Vnode, Source);
14018       Set_Target_Type (Vnode, Target);
14019
14020       --  If the unchecked conversion node is in a list, just insert before it.
14021       --  If not we have some strange case, not worth bothering about.
14022
14023       if Is_List_Member (N) then
14024          Insert_After (N, Vnode);
14025       end if;
14026    end Validate_Unchecked_Conversion;
14027
14028    ------------------------------------
14029    -- Validate_Unchecked_Conversions --
14030    ------------------------------------
14031
14032    procedure Validate_Unchecked_Conversions is
14033    begin
14034       for N in Unchecked_Conversions.First .. Unchecked_Conversions.Last loop
14035          declare
14036             T : UC_Entry renames Unchecked_Conversions.Table (N);
14037
14038             Act_Unit : constant Entity_Id  := T.Act_Unit;
14039             Eloc     : constant Source_Ptr := T.Eloc;
14040             Source   : constant Entity_Id  := T.Source;
14041             Target   : constant Entity_Id  := T.Target;
14042
14043             Source_Siz : Uint;
14044             Target_Siz : Uint;
14045
14046          begin
14047             --  Skip if function marked as warnings off
14048
14049             if Warnings_Off (Act_Unit) then
14050                goto Continue;
14051             end if;
14052
14053             --  This validation check, which warns if we have unequal sizes for
14054             --  unchecked conversion, and thus potentially implementation
14055             --  dependent semantics, is one of the few occasions on which we
14056             --  use the official RM size instead of Esize. See description in
14057             --  Einfo "Handling of Type'Size Values" for details.
14058
14059             if Serious_Errors_Detected = 0
14060               and then Known_Static_RM_Size (Source)
14061               and then Known_Static_RM_Size (Target)
14062
14063               --  Don't do the check if warnings off for either type, note the
14064               --  deliberate use of OR here instead of OR ELSE to get the flag
14065               --  Warnings_Off_Used set for both types if appropriate.
14066
14067               and then not (Has_Warnings_Off (Source)
14068                               or
14069                             Has_Warnings_Off (Target))
14070             then
14071                Source_Siz := RM_Size (Source);
14072                Target_Siz := RM_Size (Target);
14073
14074                if Source_Siz /= Target_Siz then
14075                   Error_Msg
14076                     ("?z?types for unchecked conversion have different sizes!",
14077                      Eloc);
14078
14079                   if All_Errors_Mode then
14080                      Error_Msg_Name_1 := Chars (Source);
14081                      Error_Msg_Uint_1 := Source_Siz;
14082                      Error_Msg_Name_2 := Chars (Target);
14083                      Error_Msg_Uint_2 := Target_Siz;
14084                      Error_Msg ("\size of % is ^, size of % is ^?z?", Eloc);
14085
14086                      Error_Msg_Uint_1 := UI_Abs (Source_Siz - Target_Siz);
14087
14088                      if Is_Discrete_Type (Source)
14089                           and then
14090                         Is_Discrete_Type (Target)
14091                      then
14092                         if Source_Siz > Target_Siz then
14093                            Error_Msg
14094                              ("\?z?^ high order bits of source will "
14095                               & "be ignored!", Eloc);
14096
14097                         elsif Is_Unsigned_Type (Source) then
14098                            Error_Msg
14099                              ("\?z?source will be extended with ^ high order "
14100                               & "zero bits!", Eloc);
14101
14102                         else
14103                            Error_Msg
14104                              ("\?z?source will be extended with ^ high order "
14105                               & "sign bits!", Eloc);
14106                         end if;
14107
14108                      elsif Source_Siz < Target_Siz then
14109                         if Is_Discrete_Type (Target) then
14110                            if Bytes_Big_Endian then
14111                               Error_Msg
14112                                 ("\?z?target value will include ^ undefined "
14113                                  & "low order bits!", Eloc);
14114                            else
14115                               Error_Msg
14116                                 ("\?z?target value will include ^ undefined "
14117                                  & "high order bits!", Eloc);
14118                            end if;
14119
14120                         else
14121                            Error_Msg
14122                              ("\?z?^ trailing bits of target value will be "
14123                               & "undefined!", Eloc);
14124                         end if;
14125
14126                      else pragma Assert (Source_Siz > Target_Siz);
14127                         if Is_Discrete_Type (Source) then
14128                            if Bytes_Big_Endian then
14129                               Error_Msg
14130                                 ("\?z?^ low order bits of source will be "
14131                                  & "ignored!", Eloc);
14132                            else
14133                               Error_Msg
14134                                 ("\?z?^ high order bits of source will be "
14135                                  & "ignored!", Eloc);
14136                            end if;
14137
14138                         else
14139                            Error_Msg
14140                              ("\?z?^ trailing bits of source will be "
14141                               & "ignored!", Eloc);
14142                         end if;
14143                      end if;
14144                   end if;
14145                end if;
14146             end if;
14147
14148             --  If both types are access types, we need to check the alignment.
14149             --  If the alignment of both is specified, we can do it here.
14150
14151             if Serious_Errors_Detected = 0
14152               and then Is_Access_Type (Source)
14153               and then Is_Access_Type (Target)
14154               and then Target_Strict_Alignment
14155               and then Present (Designated_Type (Source))
14156               and then Present (Designated_Type (Target))
14157             then
14158                declare
14159                   D_Source : constant Entity_Id := Designated_Type (Source);
14160                   D_Target : constant Entity_Id := Designated_Type (Target);
14161
14162                begin
14163                   if Known_Alignment (D_Source)
14164                        and then
14165                      Known_Alignment (D_Target)
14166                   then
14167                      declare
14168                         Source_Align : constant Uint := Alignment (D_Source);
14169                         Target_Align : constant Uint := Alignment (D_Target);
14170
14171                      begin
14172                         if Source_Align < Target_Align
14173                           and then not Is_Tagged_Type (D_Source)
14174
14175                           --  Suppress warning if warnings suppressed on either
14176                           --  type or either designated type. Note the use of
14177                           --  OR here instead of OR ELSE. That is intentional,
14178                           --  we would like to set flag Warnings_Off_Used in
14179                           --  all types for which warnings are suppressed.
14180
14181                           and then not (Has_Warnings_Off (D_Source)
14182                                           or
14183                                         Has_Warnings_Off (D_Target)
14184                                           or
14185                                         Has_Warnings_Off (Source)
14186                                           or
14187                                         Has_Warnings_Off (Target))
14188                         then
14189                            Error_Msg_Uint_1 := Target_Align;
14190                            Error_Msg_Uint_2 := Source_Align;
14191                            Error_Msg_Node_1 := D_Target;
14192                            Error_Msg_Node_2 := D_Source;
14193                            Error_Msg
14194                              ("?z?alignment of & (^) is stricter than "
14195                               & "alignment of & (^)!", Eloc);
14196                            Error_Msg
14197                              ("\?z?resulting access value may have invalid "
14198                               & "alignment!", Eloc);
14199                         end if;
14200                      end;
14201                   end if;
14202                end;
14203             end if;
14204          end;
14205
14206       <<Continue>>
14207          null;
14208       end loop;
14209    end Validate_Unchecked_Conversions;
14210
14211 end Sem_Ch13;