1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                               F R E E Z E                                --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2021, 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
26with Aspects;        use Aspects;
27with Atree;          use Atree;
28with Checks;         use Checks;
29with Contracts;      use Contracts;
30with Debug;          use Debug;
31with Einfo;          use Einfo;
32with Einfo.Entities; use Einfo.Entities;
33with Einfo.Utils;    use Einfo.Utils;
34with Elists;         use Elists;
35with Errout;         use Errout;
36with Exp_Ch3;        use Exp_Ch3;
37with Exp_Ch7;        use Exp_Ch7;
38with Exp_Disp;       use Exp_Disp;
39with Exp_Pakd;       use Exp_Pakd;
40with Exp_Util;       use Exp_Util;
41with Exp_Tss;        use Exp_Tss;
42with Ghost;          use Ghost;
43with Layout;         use Layout;
44with Lib;            use Lib;
45with Namet;          use Namet;
46with Nlists;         use Nlists;
47with Nmake;          use Nmake;
48with Opt;            use Opt;
49with Restrict;       use Restrict;
50with Rident;         use Rident;
51with Rtsfind;        use Rtsfind;
52with Sem;            use Sem;
53with Sem_Aux;        use Sem_Aux;
54with Sem_Cat;        use Sem_Cat;
55with Sem_Ch3;        use Sem_Ch3;
56with Sem_Ch6;        use Sem_Ch6;
57with Sem_Ch7;        use Sem_Ch7;
58with Sem_Ch8;        use Sem_Ch8;
59with Sem_Ch13;       use Sem_Ch13;
60with Sem_Disp;       use Sem_Disp;
61with Sem_Eval;       use Sem_Eval;
62with Sem_Mech;       use Sem_Mech;
63with Sem_Prag;       use Sem_Prag;
64with Sem_Res;        use Sem_Res;
65with Sem_Util;       use Sem_Util;
66with Sinfo;          use Sinfo;
67with Sinfo.Nodes;    use Sinfo.Nodes;
68with Sinfo.Utils;    use Sinfo.Utils;
69with Snames;         use Snames;
70with Stand;          use Stand;
71with Stringt;        use Stringt;
72with Strub;          use Strub;
73with Targparm;       use Targparm;
74with Tbuild;         use Tbuild;
75with Ttypes;         use Ttypes;
76with Uintp;          use Uintp;
77with Urealp;         use Urealp;
78with Warnsw;         use Warnsw;
79
80package body Freeze is
81
82   -----------------------
83   -- Local Subprograms --
84   -----------------------
85
86   procedure Adjust_Esize_For_Alignment (Typ : Entity_Id);
87   --  Typ is a type that is being frozen. If no size clause is given,
88   --  but a default Esize has been computed, then this default Esize is
89   --  adjusted up if necessary to be consistent with a given alignment,
90   --  but never to a value greater than System_Max_Integer_Size. This is
91   --  used for all discrete types and for fixed-point types.
92
93   procedure Build_And_Analyze_Renamed_Body
94     (Decl  : Node_Id;
95      New_S : Entity_Id;
96      After : in out Node_Id);
97   --  Build body for a renaming declaration, insert in tree and analyze
98
99   procedure Check_Address_Clause (E : Entity_Id);
100   --  Apply legality checks to address clauses for object declarations,
101   --  at the point the object is frozen. Also ensure any initialization is
102   --  performed only after the object has been frozen.
103
104   procedure Check_Component_Storage_Order
105     (Encl_Type        : Entity_Id;
106      Comp             : Entity_Id;
107      ADC              : Node_Id;
108      Comp_ADC_Present : out Boolean);
109   --  For an Encl_Type that has a Scalar_Storage_Order attribute definition
110   --  clause, verify that the component type has an explicit and compatible
111   --  attribute/aspect. For arrays, Comp is Empty; for records, it is the
112   --  entity of the component under consideration. For an Encl_Type that
113   --  does not have a Scalar_Storage_Order attribute definition clause,
114   --  verify that the component also does not have such a clause.
115   --  ADC is the attribute definition clause if present (or Empty). On return,
116   --  Comp_ADC_Present is set True if the component has a Scalar_Storage_Order
117   --  attribute definition clause.
118
119   procedure Check_Debug_Info_Needed (T : Entity_Id);
120   --  As each entity is frozen, this routine is called to deal with the
121   --  setting of Debug_Info_Needed for the entity. This flag is set if
122   --  the entity comes from source, or if we are in Debug_Generated_Code
123   --  mode or if the -gnatdV debug flag is set. However, it never sets
124   --  the flag if Debug_Info_Off is set. This procedure also ensures that
125   --  subsidiary entities have the flag set as required.
126
127   procedure Check_Expression_Function (N : Node_Id; Nam : Entity_Id);
128   --  When an expression function is frozen by a use of it, the expression
129   --  itself is frozen. Check that the expression does not include references
130   --  to deferred constants without completion. We report this at the freeze
131   --  point of the function, to provide a better error message.
132   --
133   --  In most cases the expression itself is frozen by the time the function
134   --  itself is frozen, because the formals will be frozen by then. However,
135   --  Attribute references to outer types are freeze points for those types;
136   --  this routine generates the required freeze nodes for them.
137
138   procedure Check_Strict_Alignment (E : Entity_Id);
139   --  E is a base type. If E is tagged or has a component that is aliased
140   --  or tagged or contains something this is aliased or tagged, set
141   --  Strict_Alignment.
142
143   procedure Check_Unsigned_Type (E : Entity_Id);
144   pragma Inline (Check_Unsigned_Type);
145   --  If E is a fixed-point or discrete type, then all the necessary work
146   --  to freeze it is completed except for possible setting of the flag
147   --  Is_Unsigned_Type, which is done by this procedure. The call has no
148   --  effect if the entity E is not a discrete or fixed-point type.
149
150   procedure Freeze_And_Append
151     (Ent    : Entity_Id;
152      N      : Node_Id;
153      Result : in out List_Id);
154   --  Freezes Ent using Freeze_Entity, and appends the resulting list of
155   --  nodes to Result, modifying Result from No_List if necessary. N has
156   --  the same usage as in Freeze_Entity.
157
158   procedure Freeze_Enumeration_Type (Typ : Entity_Id);
159   --  Freeze enumeration type. The Esize field is set as processing
160   --  proceeds (i.e. set by default when the type is declared and then
161   --  adjusted by rep clauses). What this procedure does is to make sure
162   --  that if a foreign convention is specified, and no specific size
163   --  is given, then the size must be at least Integer'Size.
164
165   procedure Freeze_Static_Object (E : Entity_Id);
166   --  If an object is frozen which has Is_Statically_Allocated set, then
167   --  all referenced types must also be marked with this flag. This routine
168   --  is in charge of meeting this requirement for the object entity E.
169
170   procedure Freeze_Subprogram (E : Entity_Id);
171   --  Perform freezing actions for a subprogram (create extra formals,
172   --  and set proper default mechanism values). Note that this routine
173   --  is not called for internal subprograms, for which neither of these
174   --  actions is needed (or desirable, we do not want for example to have
175   --  these extra formals present in initialization procedures, where they
176   --  would serve no purpose). In this call E is either a subprogram or
177   --  a subprogram type (i.e. an access to a subprogram).
178
179   function Is_Fully_Defined (T : Entity_Id) return Boolean;
180   --  True if T is not private and has no private components, or has a full
181   --  view. Used to determine whether the designated type of an access type
182   --  should be frozen when the access type is frozen. This is done when an
183   --  allocator is frozen, or an expression that may involve attributes of
184   --  the designated type. Otherwise freezing the access type does not freeze
185   --  the designated type.
186
187   function Should_Freeze_Type (Typ : Entity_Id; E : Entity_Id) return Boolean;
188   --  If Typ is in the current scope or in an instantiation, then return True.
189   --  ???Expression functions (represented by E) shouldn't freeze types in
190   --  general, but our current expansion and freezing model requires an early
191   --  freezing when the dispatch table is needed or when building an aggregate
192   --  with a subtype of Typ, so return True also in this case.
193   --  Note that expression function completions do freeze and are
194   --  handled in Sem_Ch6.Analyze_Expression_Function.
195
196   ------------------------
197   -- Should_Freeze_Type --
198   ------------------------
199
200   function Should_Freeze_Type
201     (Typ : Entity_Id; E : Entity_Id) return Boolean
202   is
203      function Is_Dispatching_Call_Or_Aggregate
204        (N : Node_Id) return Traverse_Result;
205      --  Return Abandon if N is a dispatching call to a subprogram
206      --  declared in the same scope as Typ or an aggregate whose type
207      --  is Typ.
208
209      --------------------------------------
210      -- Is_Dispatching_Call_Or_Aggregate --
211      --------------------------------------
212
213      function Is_Dispatching_Call_Or_Aggregate
214        (N : Node_Id) return Traverse_Result is
215      begin
216         if Nkind (N) = N_Function_Call
217           and then Present (Controlling_Argument (N))
218           and then Scope (Entity (Original_Node (Name (N))))
219                      = Scope (Typ)
220         then
221            return Abandon;
222         elsif Nkind (N) = N_Aggregate
223           and then Base_Type (Etype (N)) = Base_Type (Typ)
224         then
225            return Abandon;
226         else
227            return OK;
228         end if;
229      end Is_Dispatching_Call_Or_Aggregate;
230
231      -------------------------
232      -- Need_Dispatch_Table --
233      -------------------------
234
235      function Need_Dispatch_Table is new
236        Traverse_Func (Is_Dispatching_Call_Or_Aggregate);
237      --  Return Abandon if the input expression requires access to
238      --  Typ's dispatch table.
239
240      Decl : constant Node_Id :=
241        (if No (E) then E else Original_Node (Unit_Declaration_Node (E)));
242
243   --  Start of processing for Should_Freeze_Type
244
245   begin
246      return Within_Scope (Typ, Current_Scope)
247        or else In_Instance
248        or else (Present (Decl)
249                 and then Nkind (Decl) = N_Expression_Function
250                 and then Need_Dispatch_Table (Expression (Decl)) = Abandon);
251   end Should_Freeze_Type;
252
253   procedure Process_Default_Expressions
254     (E     : Entity_Id;
255      After : in out Node_Id);
256   --  This procedure is called for each subprogram to complete processing of
257   --  default expressions at the point where all types are known to be frozen.
258   --  The expressions must be analyzed in full, to make sure that all error
259   --  processing is done (they have only been preanalyzed). If the expression
260   --  is not an entity or literal, its analysis may generate code which must
261   --  not be executed. In that case we build a function body to hold that
262   --  code. This wrapper function serves no other purpose (it used to be
263   --  called to evaluate the default, but now the default is inlined at each
264   --  point of call).
265
266   procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id);
267   --  Typ is a record or array type that is being frozen. This routine sets
268   --  the default component alignment from the scope stack values if the
269   --  alignment is otherwise not specified.
270
271   procedure Set_SSO_From_Default (T : Entity_Id);
272   --  T is a record or array type that is being frozen. If it is a base type,
273   --  and if SSO_Set_Low/High_By_Default is set, then Reverse_Storage order
274   --  will be set appropriately. Note that an explicit occurrence of aspect
275   --  Scalar_Storage_Order or an explicit setting of this aspect with an
276   --  attribute definition clause occurs, then these two flags are reset in
277   --  any case, so call will have no effect.
278
279   procedure Undelay_Type (T : Entity_Id);
280   --  T is a type of a component that we know to be an Itype. We don't want
281   --  this to have a Freeze_Node, so ensure it doesn't. Do the same for any
282   --  Full_View or Corresponding_Record_Type.
283
284   procedure Warn_Overlay (Expr : Node_Id; Typ : Entity_Id; Nam : Node_Id);
285   --  Expr is the expression for an address clause for the entity denoted by
286   --  Nam whose type is Typ. If Typ has a default initialization, and there is
287   --  no explicit initialization in the source declaration, check whether the
288   --  address clause might cause overlaying of an entity, and emit a warning
289   --  on the side effect that the initialization will cause.
290
291   -------------------------------
292   -- Adjust_Esize_For_Alignment --
293   -------------------------------
294
295   procedure Adjust_Esize_For_Alignment (Typ : Entity_Id) is
296      Align : Uint;
297
298   begin
299      if Known_Esize (Typ) and then Known_Alignment (Typ) then
300         Align := Alignment_In_Bits (Typ);
301
302         if Align > Esize (Typ) and then Align <= System_Max_Integer_Size then
303            Set_Esize (Typ, Align);
304         end if;
305      end if;
306   end Adjust_Esize_For_Alignment;
307
308   ------------------------------------
309   -- Build_And_Analyze_Renamed_Body --
310   ------------------------------------
311
312   procedure Build_And_Analyze_Renamed_Body
313     (Decl  : Node_Id;
314      New_S : Entity_Id;
315      After : in out Node_Id)
316   is
317      Body_Decl    : constant Node_Id := Unit_Declaration_Node (New_S);
318      Ent          : constant Entity_Id := Defining_Entity (Decl);
319      Body_Node    : Node_Id;
320      Renamed_Subp : Entity_Id;
321
322   begin
323      --  If the renamed subprogram is intrinsic, there is no need for a
324      --  wrapper body: we set the alias that will be called and expanded which
325      --  completes the declaration. This transformation is only legal if the
326      --  renamed entity has already been elaborated.
327
328      --  Note that it is legal for a renaming_as_body to rename an intrinsic
329      --  subprogram, as long as the renaming occurs before the new entity
330      --  is frozen (RM 8.5.4 (5)).
331
332      if Nkind (Body_Decl) = N_Subprogram_Renaming_Declaration
333        and then Is_Entity_Name (Name (Body_Decl))
334      then
335         Renamed_Subp := Entity (Name (Body_Decl));
336      else
337         Renamed_Subp := Empty;
338      end if;
339
340      if Present (Renamed_Subp)
341        and then Is_Intrinsic_Subprogram (Renamed_Subp)
342        and then
343          (not In_Same_Source_Unit (Renamed_Subp, Ent)
344            or else Sloc (Renamed_Subp) < Sloc (Ent))
345
346        --  We can make the renaming entity intrinsic if the renamed function
347        --  has an interface name, or if it is one of the shift/rotate
348        --  operations known to the compiler.
349
350        and then
351          (Present (Interface_Name (Renamed_Subp))
352            or else Chars (Renamed_Subp) in Name_Rotate_Left
353                                          | Name_Rotate_Right
354                                          | Name_Shift_Left
355                                          | Name_Shift_Right
356                                          | Name_Shift_Right_Arithmetic)
357      then
358         Set_Interface_Name (Ent, Interface_Name (Renamed_Subp));
359
360         if Present (Alias (Renamed_Subp)) then
361            Set_Alias (Ent, Alias (Renamed_Subp));
362         else
363            Set_Alias (Ent, Renamed_Subp);
364         end if;
365
366         Set_Is_Intrinsic_Subprogram (Ent);
367         Set_Has_Completion (Ent);
368
369      else
370         Body_Node := Build_Renamed_Body (Decl, New_S);
371         Insert_After (After, Body_Node);
372         Mark_Rewrite_Insertion (Body_Node);
373         Analyze (Body_Node);
374         After := Body_Node;
375      end if;
376   end Build_And_Analyze_Renamed_Body;
377
378   ------------------------
379   -- Build_Renamed_Body --
380   ------------------------
381
382   function Build_Renamed_Body
383     (Decl  : Node_Id;
384      New_S : Entity_Id) return Node_Id
385   is
386      Loc : constant Source_Ptr := Sloc (New_S);
387      --  We use for the source location of the renamed body, the location of
388      --  the spec entity. It might seem more natural to use the location of
389      --  the renaming declaration itself, but that would be wrong, since then
390      --  the body we create would look as though it was created far too late,
391      --  and this could cause problems with elaboration order analysis,
392      --  particularly in connection with instantiations.
393
394      N          : constant Node_Id := Unit_Declaration_Node (New_S);
395      Nam        : constant Node_Id := Name (N);
396      Old_S      : Entity_Id;
397      Spec       : constant Node_Id := New_Copy_Tree (Specification (Decl));
398      Actuals    : List_Id := No_List;
399      Call_Node  : Node_Id;
400      Call_Name  : Node_Id;
401      Body_Node  : Node_Id;
402      Formal     : Entity_Id;
403      O_Formal   : Entity_Id;
404      Param_Spec : Node_Id;
405
406      Pref : Node_Id := Empty;
407      --  If the renamed entity is a primitive operation given in prefix form,
408      --  the prefix is the target object and it has to be added as the first
409      --  actual in the generated call.
410
411   begin
412      --  Determine the entity being renamed, which is the target of the call
413      --  statement. If the name is an explicit dereference, this is a renaming
414      --  of a subprogram type rather than a subprogram. The name itself is
415      --  fully analyzed.
416
417      if Nkind (Nam) = N_Selected_Component then
418         Old_S := Entity (Selector_Name (Nam));
419
420      elsif Nkind (Nam) = N_Explicit_Dereference then
421         Old_S := Etype (Nam);
422
423      elsif Nkind (Nam) = N_Indexed_Component then
424         if Is_Entity_Name (Prefix (Nam)) then
425            Old_S := Entity (Prefix (Nam));
426         else
427            Old_S := Entity (Selector_Name (Prefix (Nam)));
428         end if;
429
430      elsif Nkind (Nam) = N_Character_Literal then
431         Old_S := Etype (New_S);
432
433      else
434         Old_S := Entity (Nam);
435      end if;
436
437      if Is_Entity_Name (Nam) then
438
439         --  If the renamed entity is a predefined operator, retain full name
440         --  to ensure its visibility.
441
442         if Ekind (Old_S) = E_Operator
443           and then Nkind (Nam) = N_Expanded_Name
444         then
445            Call_Name := New_Copy (Name (N));
446         else
447            Call_Name := New_Occurrence_Of (Old_S, Loc);
448         end if;
449
450      else
451         if Nkind (Nam) = N_Selected_Component
452           and then Present (First_Formal (Old_S))
453           and then
454             (Is_Controlling_Formal (First_Formal (Old_S))
455                or else Is_Class_Wide_Type (Etype (First_Formal (Old_S))))
456         then
457
458            --  Retrieve the target object, to be added as a first actual
459            --  in the call.
460
461            Call_Name := New_Occurrence_Of (Old_S, Loc);
462            Pref := Prefix (Nam);
463
464         else
465            Call_Name := New_Copy (Name (N));
466         end if;
467
468         --  Original name may have been overloaded, but is fully resolved now
469
470         Set_Is_Overloaded (Call_Name, False);
471      end if;
472
473      --  For simple renamings, subsequent calls can be expanded directly as
474      --  calls to the renamed entity. The body must be generated in any case
475      --  for calls that may appear elsewhere. This is not done in the case
476      --  where the subprogram is an instantiation because the actual proper
477      --  body has not been built yet. This is also not done in GNATprove mode
478      --  as we need to check other conditions for creating a body to inline
479      --  in that case, which are controlled in Analyze_Subprogram_Body_Helper.
480
481      if Ekind (Old_S) in E_Function | E_Procedure
482        and then Nkind (Decl) = N_Subprogram_Declaration
483        and then not Is_Generic_Instance (Old_S)
484        and then not GNATprove_Mode
485      then
486         Set_Body_To_Inline (Decl, Old_S);
487      end if;
488
489      --  Check whether the return type is a limited view. If the subprogram
490      --  is already frozen the generated body may have a non-limited view
491      --  of the type, that must be used, because it is the one in the spec
492      --  of the renaming declaration.
493
494      if Ekind (Old_S) = E_Function
495        and then Is_Entity_Name (Result_Definition (Spec))
496      then
497         declare
498            Ret_Type : constant Entity_Id := Etype (Result_Definition (Spec));
499         begin
500            if Has_Non_Limited_View (Ret_Type) then
501               Set_Result_Definition
502                 (Spec, New_Occurrence_Of (Non_Limited_View (Ret_Type), Loc));
503            end if;
504         end;
505      end if;
506
507      --  The body generated for this renaming is an internal artifact, and
508      --  does not  constitute a freeze point for the called entity.
509
510      Set_Must_Not_Freeze (Call_Name);
511
512      Formal := First_Formal (Defining_Entity (Decl));
513
514      if Present (Pref) then
515         declare
516            Pref_Type : constant Entity_Id := Etype (Pref);
517            Form_Type : constant Entity_Id := Etype (First_Formal (Old_S));
518
519         begin
520            --  The controlling formal may be an access parameter, or the
521            --  actual may be an access value, so adjust accordingly.
522
523            if Is_Access_Type (Pref_Type)
524              and then not Is_Access_Type (Form_Type)
525            then
526               Actuals := New_List
527                 (Make_Explicit_Dereference (Loc, Relocate_Node (Pref)));
528
529            elsif Is_Access_Type (Form_Type)
530              and then not Is_Access_Type (Pref)
531            then
532               Actuals :=
533                 New_List (
534                   Make_Attribute_Reference (Loc,
535                     Attribute_Name => Name_Access,
536                     Prefix         => Relocate_Node (Pref)));
537            else
538               Actuals := New_List (Pref);
539            end if;
540         end;
541
542      elsif Present (Formal) then
543         Actuals := New_List;
544
545      else
546         Actuals := No_List;
547      end if;
548
549      while Present (Formal) loop
550         Append (New_Occurrence_Of (Formal, Loc), Actuals);
551         Next_Formal (Formal);
552      end loop;
553
554      --  If the renamed entity is an entry, inherit its profile. For other
555      --  renamings as bodies, both profiles must be subtype conformant, so it
556      --  is not necessary to replace the profile given in the declaration.
557      --  However, default values that are aggregates are rewritten when
558      --  partially analyzed, so we recover the original aggregate to insure
559      --  that subsequent conformity checking works. Similarly, if the default
560      --  expression was constant-folded, recover the original expression.
561
562      Formal := First_Formal (Defining_Entity (Decl));
563
564      if Present (Formal) then
565         O_Formal := First_Formal (Old_S);
566         Param_Spec := First (Parameter_Specifications (Spec));
567         while Present (Formal) loop
568            if Is_Entry (Old_S) then
569               if Nkind (Parameter_Type (Param_Spec)) /=
570                                                    N_Access_Definition
571               then
572                  Set_Etype (Formal, Etype (O_Formal));
573                  Set_Entity (Parameter_Type (Param_Spec), Etype (O_Formal));
574               end if;
575
576            elsif Nkind (Default_Value (O_Formal)) = N_Aggregate
577              or else Nkind (Original_Node (Default_Value (O_Formal))) /=
578                                           Nkind (Default_Value (O_Formal))
579            then
580               Set_Expression (Param_Spec,
581                 New_Copy_Tree (Original_Node (Default_Value (O_Formal))));
582            end if;
583
584            Next_Formal (Formal);
585            Next_Formal (O_Formal);
586            Next (Param_Spec);
587         end loop;
588      end if;
589
590      --  If the renamed entity is a function, the generated body contains a
591      --  return statement. Otherwise, build a procedure call. If the entity is
592      --  an entry, subsequent analysis of the call will transform it into the
593      --  proper entry or protected operation call. If the renamed entity is
594      --  a character literal, return it directly.
595
596      if Ekind (Old_S) = E_Function
597        or else Ekind (Old_S) = E_Operator
598        or else (Ekind (Old_S) = E_Subprogram_Type
599                  and then Etype (Old_S) /= Standard_Void_Type)
600      then
601         Call_Node :=
602           Make_Simple_Return_Statement (Loc,
603              Expression =>
604                Make_Function_Call (Loc,
605                  Name                   => Call_Name,
606                  Parameter_Associations => Actuals));
607
608      elsif Ekind (Old_S) = E_Enumeration_Literal then
609         Call_Node :=
610           Make_Simple_Return_Statement (Loc,
611              Expression => New_Occurrence_Of (Old_S, Loc));
612
613      elsif Nkind (Nam) = N_Character_Literal then
614         Call_Node :=
615           Make_Simple_Return_Statement (Loc, Expression => Call_Name);
616
617      else
618         Call_Node :=
619           Make_Procedure_Call_Statement (Loc,
620             Name                   => Call_Name,
621             Parameter_Associations => Actuals);
622      end if;
623
624      --  Create entities for subprogram body and formals
625
626      Set_Defining_Unit_Name (Spec,
627        Make_Defining_Identifier (Loc, Chars => Chars (New_S)));
628
629      Param_Spec := First (Parameter_Specifications (Spec));
630      while Present (Param_Spec) loop
631         Set_Defining_Identifier (Param_Spec,
632           Make_Defining_Identifier (Loc,
633             Chars => Chars (Defining_Identifier (Param_Spec))));
634         Next (Param_Spec);
635      end loop;
636
637      --  In GNATprove, prefer to generate an expression function whenever
638      --  possible, to benefit from the more precise analysis in that case
639      --  (as if an implicit postcondition had been generated).
640
641      if GNATprove_Mode
642        and then Nkind (Call_Node) = N_Simple_Return_Statement
643      then
644         Body_Node :=
645           Make_Expression_Function (Loc,
646             Specification => Spec,
647             Expression    => Expression (Call_Node));
648      else
649         Body_Node :=
650           Make_Subprogram_Body (Loc,
651             Specification              => Spec,
652             Declarations               => New_List,
653             Handled_Statement_Sequence =>
654               Make_Handled_Sequence_Of_Statements (Loc,
655                 Statements => New_List (Call_Node)));
656      end if;
657
658      if Nkind (Decl) /= N_Subprogram_Declaration then
659         Rewrite (N,
660           Make_Subprogram_Declaration (Loc,
661             Specification => Specification (N)));
662      end if;
663
664      --  Link the body to the entity whose declaration it completes. If
665      --  the body is analyzed when the renamed entity is frozen, it may
666      --  be necessary to restore the proper scope (see package Exp_Ch13).
667
668      if Nkind (N) = N_Subprogram_Renaming_Declaration
669        and then Present (Corresponding_Spec (N))
670      then
671         Set_Corresponding_Spec (Body_Node, Corresponding_Spec (N));
672      else
673         Set_Corresponding_Spec (Body_Node, New_S);
674      end if;
675
676      return Body_Node;
677   end Build_Renamed_Body;
678
679   --------------------------
680   -- Check_Address_Clause --
681   --------------------------
682
683   procedure Check_Address_Clause (E : Entity_Id) is
684      Addr       : constant Node_Id   := Address_Clause (E);
685      Typ        : constant Entity_Id := Etype (E);
686      Decl       : Node_Id;
687      Expr       : Node_Id;
688      Init       : Node_Id;
689      Lhs        : Node_Id;
690      Tag_Assign : Node_Id;
691
692   begin
693      if Present (Addr) then
694
695         --  For a deferred constant, the initialization value is on full view
696
697         if Ekind (E) = E_Constant and then Present (Full_View (E)) then
698            Decl := Declaration_Node (Full_View (E));
699         else
700            Decl := Declaration_Node (E);
701         end if;
702
703         Expr := Expression (Addr);
704
705         if Needs_Constant_Address (Decl, Typ) then
706            Check_Constant_Address_Clause (Expr, E);
707
708            --  Has_Delayed_Freeze was set on E when the address clause was
709            --  analyzed, and must remain set because we want the address
710            --  clause to be elaborated only after any entity it references
711            --  has been elaborated.
712         end if;
713
714         --  If Rep_Clauses are to be ignored, remove address clause from
715         --  list attached to entity, because it may be illegal for gigi,
716         --  for example by breaking order of elaboration.
717
718         if Ignore_Rep_Clauses then
719            declare
720               Rep : Node_Id;
721
722            begin
723               Rep := First_Rep_Item (E);
724
725               if Rep = Addr then
726                  Set_First_Rep_Item (E, Next_Rep_Item (Addr));
727
728               else
729                  while Present (Rep)
730                    and then Next_Rep_Item (Rep) /= Addr
731                  loop
732                     Next_Rep_Item (Rep);
733                  end loop;
734               end if;
735
736               if Present (Rep) then
737                  Set_Next_Rep_Item (Rep, Next_Rep_Item (Addr));
738               end if;
739            end;
740
741            --  And now remove the address clause
742
743            Kill_Rep_Clause (Addr);
744
745         elsif not Error_Posted (Expr)
746           and then not Needs_Finalization (Typ)
747         then
748            Warn_Overlay (Expr, Typ, Name (Addr));
749         end if;
750
751         Init := Expression (Decl);
752
753         --  If a variable, or a non-imported constant, overlays a constant
754         --  object and has an initialization value, then the initialization
755         --  may end up writing into read-only memory. Detect the cases of
756         --  statically identical values and remove the initialization. In
757         --  the other cases, give a warning. We will give other warnings
758         --  later for the variable if it is assigned.
759
760         if (Ekind (E) = E_Variable
761              or else (Ekind (E) = E_Constant
762                        and then not Is_Imported (E)))
763           and then Overlays_Constant (E)
764           and then Present (Init)
765         then
766            declare
767               O_Ent : Entity_Id;
768               Off   : Boolean;
769
770            begin
771               Find_Overlaid_Entity (Addr, O_Ent, Off);
772
773               if Ekind (O_Ent) = E_Constant
774                 and then Etype (O_Ent) = Typ
775                 and then Present (Constant_Value (O_Ent))
776                 and then Compile_Time_Compare
777                            (Init,
778                             Constant_Value (O_Ent),
779                             Assume_Valid => True) = EQ
780               then
781                  Set_No_Initialization (Decl);
782                  return;
783
784               elsif Comes_From_Source (Init)
785                 and then Address_Clause_Overlay_Warnings
786               then
787                  Error_Msg_Sloc := Sloc (Addr);
788                  Error_Msg_NE
789                    ("??constant& may be modified via address clause#",
790                     Decl, O_Ent);
791               end if;
792            end;
793         end if;
794
795         --  Remove side effects from initial expression, except in the case of
796         --  limited build-in-place calls and aggregates, which have their own
797         --  expansion elsewhere. This exception is necessary to avoid copying
798         --  limited objects.
799
800         if Present (Init)
801           and then not Is_Limited_View (Typ)
802         then
803            --  Capture initialization value at point of declaration, and make
804            --  explicit assignment legal, because object may be a constant.
805
806            Remove_Side_Effects (Init);
807            Lhs := New_Occurrence_Of (E, Sloc (Decl));
808            Set_Assignment_OK (Lhs);
809
810            --  Move initialization to freeze actions, once the object has
811            --  been frozen and the address clause alignment check has been
812            --  performed.
813
814            Append_Freeze_Action (E,
815              Make_Assignment_Statement (Sloc (Decl),
816                Name       => Lhs,
817                Expression => Expression (Decl)));
818
819            Set_No_Initialization (Decl);
820
821            --  If the object is tagged, check whether the tag must be
822            --  reassigned explicitly.
823
824            Tag_Assign := Make_Tag_Assignment (Decl);
825            if Present (Tag_Assign) then
826               Append_Freeze_Action (E, Tag_Assign);
827            end if;
828         end if;
829      end if;
830   end Check_Address_Clause;
831
832   -----------------------------
833   -- Check_Compile_Time_Size --
834   -----------------------------
835
836   procedure Check_Compile_Time_Size (T : Entity_Id) is
837
838      procedure Set_Small_Size (T : Entity_Id; S : Uint);
839      --  Sets the compile time known size in the RM_Size field of T, checking
840      --  for a size clause that was given which attempts to give a small size.
841
842      function Size_Known (T : Entity_Id) return Boolean;
843      --  Recursive function that does all the work
844
845      function Static_Discriminated_Components (T : Entity_Id) return Boolean;
846      --  If T is a constrained subtype, its size is not known if any of its
847      --  discriminant constraints is not static and it is not a null record.
848      --  The test is conservative and doesn't check that the components are
849      --  in fact constrained by non-static discriminant values. Could be made
850      --  more precise ???
851
852      --------------------
853      -- Set_Small_Size --
854      --------------------
855
856      procedure Set_Small_Size (T : Entity_Id; S : Uint) is
857      begin
858         if S > System_Max_Integer_Size then
859            return;
860
861         --  Check for bad size clause given
862
863         elsif Has_Size_Clause (T) then
864            if RM_Size (T) < S then
865               Error_Msg_Uint_1 := S;
866               Error_Msg_NE (Size_Too_Small_Message, Size_Clause (T), T);
867            end if;
868
869         --  Set size if not set already. Do not set it to Uint_0, because in
870         --  some cases (notably array-of-record), the Component_Size is
871         --  No_Uint, which causes S to be Uint_0. Presumably the RM_Size and
872         --  Component_Size will eventually be set correctly by the back end.
873
874         elsif not Known_RM_Size (T) and then S /= Uint_0 then
875            Set_RM_Size (T, S);
876         end if;
877      end Set_Small_Size;
878
879      ----------------
880      -- Size_Known --
881      ----------------
882
883      function Size_Known (T : Entity_Id) return Boolean is
884         Comp  : Entity_Id;
885         Ctyp  : Entity_Id;
886
887      begin
888         if Size_Known_At_Compile_Time (T) then
889            return True;
890
891         --  Always True for elementary types, even generic formal elementary
892         --  types. We used to return False in the latter case, but the size
893         --  is known at compile time, even in the template, we just do not
894         --  know the exact size but that's not the point of this routine.
895
896         elsif Is_Elementary_Type (T) or else Is_Task_Type (T) then
897            return True;
898
899         --  Array types
900
901         elsif Is_Array_Type (T) then
902
903            --  String literals always have known size, and we can set it
904
905            if Ekind (T) = E_String_Literal_Subtype then
906               if Known_Component_Size (T) then
907                  Set_Small_Size
908                    (T, Component_Size (T) * String_Literal_Length (T));
909
910               else
911                  --  The following is wrong, but does what previous versions
912                  --  did. The Component_Size is unknown for the string in a
913                  --  pragma Warnings.
914                  Set_Small_Size (T, Uint_0);
915               end if;
916
917               return True;
918
919            --  Unconstrained types never have known at compile time size
920
921            elsif not Is_Constrained (T) then
922               return False;
923
924            --  Don't do any recursion on type with error posted, since we may
925            --  have a malformed type that leads us into a loop.
926
927            elsif Error_Posted (T) then
928               return False;
929
930            --  Otherwise if component size unknown, then array size unknown
931
932            elsif not Size_Known (Component_Type (T)) then
933               return False;
934            end if;
935
936            --  Check for all indexes static, and also compute possible size
937            --  (in case it is not greater than System_Max_Integer_Size and
938            --  thus may be packable).
939
940            declare
941               Index : Entity_Id;
942               Low   : Node_Id;
943               High  : Node_Id;
944               Size  : Uint := Component_Size (T);
945               Dim   : Uint;
946
947            begin
948               --  See comment in Set_Small_Size above
949
950               if No (Size) then
951                  Size := Uint_0;
952               end if;
953
954               Index := First_Index (T);
955               while Present (Index) loop
956                  if Nkind (Index) = N_Range then
957                     Get_Index_Bounds (Index, Low, High);
958
959                  elsif Error_Posted (Scalar_Range (Etype (Index))) then
960                     return False;
961
962                  else
963                     Low  := Type_Low_Bound (Etype (Index));
964                     High := Type_High_Bound (Etype (Index));
965                  end if;
966
967                  if not Compile_Time_Known_Value (Low)
968                    or else not Compile_Time_Known_Value (High)
969                    or else Etype (Index) = Any_Type
970                  then
971                     return False;
972
973                  else
974                     Dim := Expr_Value (High) - Expr_Value (Low) + 1;
975
976                     if Dim > Uint_0 then
977                        Size := Size * Dim;
978                     else
979                        Size := Uint_0;
980                     end if;
981                  end if;
982
983                  Next_Index (Index);
984               end loop;
985
986               Set_Small_Size (T, Size);
987               return True;
988            end;
989
990         --  For non-generic private types, go to underlying type if present
991
992         elsif Is_Private_Type (T)
993           and then not Is_Generic_Type (T)
994           and then Present (Underlying_Type (T))
995         then
996            --  Don't do any recursion on type with error posted, since we may
997            --  have a malformed type that leads us into a loop.
998
999            if Error_Posted (T) then
1000               return False;
1001            else
1002               return Size_Known (Underlying_Type (T));
1003            end if;
1004
1005         --  Record types
1006
1007         elsif Is_Record_Type (T) then
1008
1009            --  A class-wide type is never considered to have a known size
1010
1011            if Is_Class_Wide_Type (T) then
1012               return False;
1013
1014            --  A subtype of a variant record must not have non-static
1015            --  discriminated components.
1016
1017            elsif T /= Base_Type (T)
1018              and then not Static_Discriminated_Components (T)
1019            then
1020               return False;
1021
1022            --  Don't do any recursion on type with error posted, since we may
1023            --  have a malformed type that leads us into a loop.
1024
1025            elsif Error_Posted (T) then
1026               return False;
1027            end if;
1028
1029            --  Now look at the components of the record
1030
1031            declare
1032               --  The following two variables are used to keep track of the
1033               --  size of packed records if we can tell the size of the packed
1034               --  record in the front end. Packed_Size_Known is True if so far
1035               --  we can figure out the size. It is initialized to True for a
1036               --  packed record, unless the record has either discriminants or
1037               --  independent components, or is a strict-alignment type, since
1038               --  it cannot be fully packed in this case.
1039
1040               --  The reason we eliminate the discriminated case is that
1041               --  we don't know the way the back end lays out discriminated
1042               --  packed records. If Packed_Size_Known is True, then
1043               --  Packed_Size is the size in bits so far.
1044
1045               Packed_Size_Known : Boolean :=
1046                 Is_Packed (T)
1047                   and then not Has_Discriminants (T)
1048                   and then not Has_Independent_Components (T)
1049                   and then not Strict_Alignment (T);
1050
1051               Packed_Size : Uint := Uint_0;
1052               --  Size in bits so far
1053
1054            begin
1055               --  Test for variant part present
1056
1057               if Has_Discriminants (T)
1058                 and then Present (Parent (T))
1059                 and then Nkind (Parent (T)) = N_Full_Type_Declaration
1060                 and then Nkind (Type_Definition (Parent (T))) =
1061                                               N_Record_Definition
1062                 and then not Null_Present (Type_Definition (Parent (T)))
1063                 and then
1064                   Present (Variant_Part
1065                              (Component_List (Type_Definition (Parent (T)))))
1066               then
1067                  --  If variant part is present, and type is unconstrained,
1068                  --  then we must have defaulted discriminants, or a size
1069                  --  clause must be present for the type, or else the size
1070                  --  is definitely not known at compile time.
1071
1072                  if not Is_Constrained (T)
1073                    and then
1074                      No (Discriminant_Default_Value (First_Discriminant (T)))
1075                    and then not Known_RM_Size (T)
1076                  then
1077                     return False;
1078                  end if;
1079               end if;
1080
1081               --  Loop through components
1082
1083               Comp := First_Component_Or_Discriminant (T);
1084               while Present (Comp) loop
1085                  Ctyp := Etype (Comp);
1086
1087                  --  We do not know the packed size if there is a component
1088                  --  clause present (we possibly could, but this would only
1089                  --  help in the case of a record with partial rep clauses.
1090                  --  That's because in the case of full rep clauses, the
1091                  --  size gets figured out anyway by a different circuit).
1092
1093                  if Present (Component_Clause (Comp)) then
1094                     Packed_Size_Known := False;
1095                  end if;
1096
1097                  --  We do not know the packed size for an independent
1098                  --  component or if it is of a strict-alignment type,
1099                  --  since packing does not touch these (RM 13.2(7)).
1100
1101                  if Is_Independent (Comp)
1102                    or else Is_Independent (Ctyp)
1103                    or else Strict_Alignment (Ctyp)
1104                  then
1105                     Packed_Size_Known := False;
1106                  end if;
1107
1108                  --  We need to identify a component that is an array where
1109                  --  the index type is an enumeration type with non-standard
1110                  --  representation, and some bound of the type depends on a
1111                  --  discriminant.
1112
1113                  --  This is because gigi computes the size by doing a
1114                  --  substitution of the appropriate discriminant value in
1115                  --  the size expression for the base type, and gigi is not
1116                  --  clever enough to evaluate the resulting expression (which
1117                  --  involves a call to rep_to_pos) at compile time.
1118
1119                  --  It would be nice if gigi would either recognize that
1120                  --  this expression can be computed at compile time, or
1121                  --  alternatively figured out the size from the subtype
1122                  --  directly, where all the information is at hand ???
1123
1124                  if Is_Array_Type (Etype (Comp))
1125                    and then Present (Packed_Array_Impl_Type (Etype (Comp)))
1126                  then
1127                     declare
1128                        Ocomp  : constant Entity_Id :=
1129                                   Original_Record_Component (Comp);
1130                        OCtyp  : constant Entity_Id := Etype (Ocomp);
1131                        Ind    : Node_Id;
1132                        Indtyp : Entity_Id;
1133                        Lo, Hi : Node_Id;
1134
1135                     begin
1136                        Ind := First_Index (OCtyp);
1137                        while Present (Ind) loop
1138                           Indtyp := Etype (Ind);
1139
1140                           if Is_Enumeration_Type (Indtyp)
1141                             and then Has_Non_Standard_Rep (Indtyp)
1142                           then
1143                              Lo := Type_Low_Bound  (Indtyp);
1144                              Hi := Type_High_Bound (Indtyp);
1145
1146                              if Is_Entity_Name (Lo)
1147                                and then Ekind (Entity (Lo)) = E_Discriminant
1148                              then
1149                                 return False;
1150
1151                              elsif Is_Entity_Name (Hi)
1152                                and then Ekind (Entity (Hi)) = E_Discriminant
1153                              then
1154                                 return False;
1155                              end if;
1156                           end if;
1157
1158                           Next_Index (Ind);
1159                        end loop;
1160                     end;
1161                  end if;
1162
1163                  --  Clearly size of record is not known if the size of one of
1164                  --  the components is not known.
1165
1166                  if not Size_Known (Ctyp) then
1167                     return False;
1168                  end if;
1169
1170                  --  Accumulate packed size if possible
1171
1172                  if Packed_Size_Known then
1173
1174                     --  We can deal with elementary types, small packed arrays
1175                     --  if the representation is a modular type and also small
1176                     --  record types as checked by Set_Small_Size.
1177
1178                     if Is_Elementary_Type (Ctyp)
1179                       or else (Is_Array_Type (Ctyp)
1180                                 and then Present
1181                                            (Packed_Array_Impl_Type (Ctyp))
1182                                 and then Is_Modular_Integer_Type
1183                                            (Packed_Array_Impl_Type (Ctyp)))
1184                       or else Is_Record_Type (Ctyp)
1185                     then
1186                        --  If RM_Size is known and static, then we can keep
1187                        --  accumulating the packed size.
1188
1189                        if Known_Static_RM_Size (Ctyp) then
1190
1191                           Packed_Size := Packed_Size + RM_Size (Ctyp);
1192
1193                        --  If we have a field whose RM_Size is not known then
1194                        --  we can't figure out the packed size here.
1195
1196                        else
1197                           Packed_Size_Known := False;
1198                        end if;
1199
1200                     --  For other types we can't figure out the packed size
1201
1202                     else
1203                        Packed_Size_Known := False;
1204                     end if;
1205                  end if;
1206
1207                  Next_Component_Or_Discriminant (Comp);
1208               end loop;
1209
1210               if Packed_Size_Known then
1211                  Set_Small_Size (T, Packed_Size);
1212               end if;
1213
1214               return True;
1215            end;
1216
1217         --  All other cases, size not known at compile time
1218
1219         else
1220            return False;
1221         end if;
1222      end Size_Known;
1223
1224      -------------------------------------
1225      -- Static_Discriminated_Components --
1226      -------------------------------------
1227
1228      function Static_Discriminated_Components
1229        (T : Entity_Id) return Boolean
1230      is
1231         Constraint : Elmt_Id;
1232
1233      begin
1234         if Has_Discriminants (T)
1235           and then Present (Discriminant_Constraint (T))
1236           and then Present (First_Component (T))
1237         then
1238            Constraint := First_Elmt (Discriminant_Constraint (T));
1239            while Present (Constraint) loop
1240               if not Compile_Time_Known_Value (Node (Constraint)) then
1241                  return False;
1242               end if;
1243
1244               Next_Elmt (Constraint);
1245            end loop;
1246         end if;
1247
1248         return True;
1249      end Static_Discriminated_Components;
1250
1251   --  Start of processing for Check_Compile_Time_Size
1252
1253   begin
1254      Set_Size_Known_At_Compile_Time (T, Size_Known (T));
1255   end Check_Compile_Time_Size;
1256
1257   -----------------------------------
1258   -- Check_Component_Storage_Order --
1259   -----------------------------------
1260
1261   procedure Check_Component_Storage_Order
1262     (Encl_Type        : Entity_Id;
1263      Comp             : Entity_Id;
1264      ADC              : Node_Id;
1265      Comp_ADC_Present : out Boolean)
1266   is
1267      Comp_Base : Entity_Id;
1268      Comp_ADC  : Node_Id;
1269      Encl_Base : Entity_Id;
1270      Err_Node  : Node_Id;
1271
1272      Component_Aliased : Boolean;
1273
1274      Comp_Byte_Aligned : Boolean := False;
1275      --  Set for the record case, True if Comp is aligned on byte boundaries
1276      --  (in which case it is allowed to have different storage order).
1277
1278      Comp_SSO_Differs  : Boolean;
1279      --  Set True when the component is a nested composite, and it does not
1280      --  have the same scalar storage order as Encl_Type.
1281
1282   begin
1283      --  Record case
1284
1285      if Present (Comp) then
1286         Err_Node  := Comp;
1287         Comp_Base := Etype (Comp);
1288
1289         if Is_Tag (Comp) then
1290            Comp_Byte_Aligned := True;
1291            Component_Aliased := False;
1292
1293         else
1294            --  If a component clause is present, check if the component starts
1295            --  and ends on byte boundaries. Otherwise conservatively assume it
1296            --  does so only in the case where the record is not packed.
1297
1298            if Present (Component_Clause (Comp)) then
1299               Comp_Byte_Aligned :=
1300                 Known_Normalized_First_Bit (Comp)
1301                   and then
1302                 Known_Esize (Comp)
1303                   and then
1304                 Normalized_First_Bit (Comp) mod System_Storage_Unit = 0
1305                   and then
1306                 Esize (Comp) mod System_Storage_Unit = 0;
1307            else
1308               Comp_Byte_Aligned := not Is_Packed (Encl_Type);
1309            end if;
1310
1311            Component_Aliased := Is_Aliased (Comp);
1312         end if;
1313
1314      --  Array case
1315
1316      else
1317         Err_Node  := Encl_Type;
1318         Comp_Base := Component_Type (Encl_Type);
1319
1320         Component_Aliased := Has_Aliased_Components (Encl_Type);
1321      end if;
1322
1323      --  Note: the Reverse_Storage_Order flag is set on the base type, but
1324      --  the attribute definition clause is attached to the first subtype.
1325      --  Also, if the base type is incomplete or private, go to full view
1326      --  if known
1327
1328      Encl_Base := Base_Type (Encl_Type);
1329      if Present (Underlying_Type (Encl_Base)) then
1330         Encl_Base := Underlying_Type (Encl_Base);
1331      end if;
1332
1333      Comp_Base := Base_Type (Comp_Base);
1334      if Present (Underlying_Type (Comp_Base)) then
1335         Comp_Base := Underlying_Type (Comp_Base);
1336      end if;
1337
1338      Comp_ADC :=
1339        Get_Attribute_Definition_Clause
1340          (First_Subtype (Comp_Base), Attribute_Scalar_Storage_Order);
1341      Comp_ADC_Present := Present (Comp_ADC);
1342
1343      --  Case of record or array component: check storage order compatibility.
1344      --  But, if the record has Complex_Representation, then it is treated as
1345      --  a scalar in the back end so the storage order is irrelevant.
1346
1347      if (Is_Record_Type (Comp_Base)
1348            and then not Has_Complex_Representation (Comp_Base))
1349        or else Is_Array_Type (Comp_Base)
1350      then
1351         Comp_SSO_Differs :=
1352           Reverse_Storage_Order (Encl_Base) /=
1353             Reverse_Storage_Order (Comp_Base);
1354
1355         --  Parent and extension must have same storage order
1356
1357         if Present (Comp) and then Chars (Comp) = Name_uParent then
1358            if Comp_SSO_Differs then
1359               Error_Msg_N
1360                 ("record extension must have same scalar storage order as "
1361                  & "parent", Err_Node);
1362            end if;
1363
1364         --  If component and composite SSO differs, check that component
1365         --  falls on byte boundaries and isn't bit packed.
1366
1367         elsif Comp_SSO_Differs then
1368
1369            --  Component SSO differs from enclosing composite:
1370
1371            --  Reject if composite is a bit-packed array, as it is rewritten
1372            --  into an array of scalars.
1373
1374            if Is_Bit_Packed_Array (Encl_Base) then
1375               Error_Msg_N
1376                 ("type of packed array must have same scalar storage order "
1377                  & "as component", Err_Node);
1378
1379            --  Reject if not byte aligned
1380
1381            elsif Is_Record_Type (Encl_Base)
1382              and then not Comp_Byte_Aligned
1383            then
1384               if Present (Component_Clause (Comp)) then
1385                  Error_Msg_N
1386                    ("type of non-byte-aligned component must have same scalar"
1387                     & " storage order as enclosing record", Err_Node);
1388               else
1389                  Error_Msg_N
1390                    ("type of packed component must have same scalar"
1391                     & " storage order as enclosing record", Err_Node);
1392               end if;
1393
1394            --  Warn if specified only for the outer composite
1395
1396            elsif Present (ADC) and then No (Comp_ADC) then
1397               Error_Msg_NE
1398                 ("scalar storage order specified for & does not apply to "
1399                  & "component?", Err_Node, Encl_Base);
1400            end if;
1401         end if;
1402
1403      --  Enclosing type has explicit SSO: non-composite component must not
1404      --  be aliased.
1405
1406      elsif Present (ADC) and then Component_Aliased then
1407         Error_Msg_N
1408           ("aliased component not permitted for type with explicit "
1409            & "Scalar_Storage_Order", Err_Node);
1410      end if;
1411   end Check_Component_Storage_Order;
1412
1413   -----------------------------
1414   -- Check_Debug_Info_Needed --
1415   -----------------------------
1416
1417   procedure Check_Debug_Info_Needed (T : Entity_Id) is
1418   begin
1419      if Debug_Info_Off (T) then
1420         return;
1421
1422      elsif Comes_From_Source (T)
1423        or else Debug_Generated_Code
1424        or else Debug_Flag_VV
1425        or else Needs_Debug_Info (T)
1426      then
1427         Set_Debug_Info_Needed (T);
1428      end if;
1429   end Check_Debug_Info_Needed;
1430
1431   -------------------------------
1432   -- Check_Expression_Function --
1433   -------------------------------
1434
1435   procedure Check_Expression_Function (N : Node_Id; Nam : Entity_Id) is
1436      function Find_Constant (Nod : Node_Id) return Traverse_Result;
1437      --  Function to search for deferred constant
1438
1439      -------------------
1440      -- Find_Constant --
1441      -------------------
1442
1443      function Find_Constant (Nod : Node_Id) return Traverse_Result is
1444      begin
1445         --  When a constant is initialized with the result of a dispatching
1446         --  call, the constant declaration is rewritten as a renaming of the
1447         --  displaced function result. This scenario is not a premature use of
1448         --  a constant even though the Has_Completion flag is not set.
1449
1450         if Is_Entity_Name (Nod)
1451           and then Present (Entity (Nod))
1452           and then Ekind (Entity (Nod)) = E_Constant
1453           and then Scope (Entity (Nod)) = Current_Scope
1454           and then Nkind (Declaration_Node (Entity (Nod))) =
1455                                                         N_Object_Declaration
1456           and then not Is_Imported (Entity (Nod))
1457           and then not Has_Completion (Entity (Nod))
1458           and then not Is_Frozen (Entity (Nod))
1459         then
1460            Error_Msg_NE
1461              ("premature use of& in call or instance", N, Entity (Nod));
1462
1463         elsif Nkind (Nod) = N_Attribute_Reference then
1464            Analyze (Prefix (Nod));
1465
1466            if Is_Entity_Name (Prefix (Nod))
1467              and then Is_Type (Entity (Prefix (Nod)))
1468            then
1469               Freeze_Before (N, Entity (Prefix (Nod)));
1470            end if;
1471         end if;
1472
1473         return OK;
1474      end Find_Constant;
1475
1476      procedure Check_Deferred is new Traverse_Proc (Find_Constant);
1477
1478      --  Local variables
1479
1480      Decl : Node_Id;
1481
1482   --  Start of processing for Check_Expression_Function
1483
1484   begin
1485      Decl := Original_Node (Unit_Declaration_Node (Nam));
1486
1487      --  The subprogram body created for the expression function is not
1488      --  itself a freeze point.
1489
1490      if Scope (Nam) = Current_Scope
1491        and then Nkind (Decl) = N_Expression_Function
1492        and then Nkind (N) /= N_Subprogram_Body
1493      then
1494         Check_Deferred (Expression (Decl));
1495      end if;
1496   end Check_Expression_Function;
1497
1498   --------------------------------
1499   -- Check_Inherited_Conditions --
1500   --------------------------------
1501
1502   procedure Check_Inherited_Conditions
1503     (R               : Entity_Id;
1504      Late_Overriding : Boolean := False)
1505   is
1506      Prim_Ops       : constant Elist_Id := Primitive_Operations (R);
1507      Decls          : List_Id;
1508      Op_Node        : Elmt_Id;
1509      Par_Prim       : Entity_Id;
1510      Prim           : Entity_Id;
1511      Wrapper_Needed : Boolean;
1512
1513      function Build_DTW_Body
1514        (Loc          : Source_Ptr;
1515         DTW_Spec     : Node_Id;
1516         DTW_Decls    : List_Id;
1517         Par_Prim     : Entity_Id;
1518         Wrapped_Subp : Entity_Id) return Node_Id;
1519      --  Build the body of the dispatch table wrapper containing the given
1520      --  spec and declarations; the call to the wrapped subprogram includes
1521      --  the proper type conversion.
1522
1523      function Build_DTW_Spec (Par_Prim : Entity_Id) return Node_Id;
1524      --  Build the spec of the dispatch table wrapper
1525
1526      procedure Build_Inherited_Condition_Pragmas
1527        (Subp           : Entity_Id;
1528         Wrapper_Needed : out Boolean);
1529      --  Build corresponding pragmas for an operation whose ancestor has
1530      --  class-wide pre/postconditions. If the operation is inherited then
1531      --  Wrapper_Needed is returned True to force the creation of a wrapper
1532      --  for the inherited operation. If the ancestor is being overridden,
1533      --  the pragmas are constructed only to verify their legality, in case
1534      --  they contain calls to other primitives that may have been overridden.
1535
1536      function Needs_Wrapper
1537        (Class_Cond : Node_Id;
1538         Subp       : Entity_Id;
1539         Par_Subp   : Entity_Id) return Boolean;
1540      --  Checks whether the dispatch-table wrapper (DTW) for Subp must be
1541      --  built to evaluate the given class-wide condition.
1542
1543      --------------------
1544      -- Build_DTW_Body --
1545      --------------------
1546
1547      function Build_DTW_Body
1548        (Loc          : Source_Ptr;
1549         DTW_Spec     : Node_Id;
1550         DTW_Decls    : List_Id;
1551         Par_Prim     : Entity_Id;
1552         Wrapped_Subp : Entity_Id) return Node_Id
1553      is
1554         Par_Typ    : constant Entity_Id := Find_Dispatching_Type (Par_Prim);
1555         Actuals    : constant List_Id   := Empty_List;
1556         Call       : Node_Id;
1557         Formal     : Entity_Id := First_Formal (Par_Prim);
1558         New_F_Spec : Entity_Id := First (Parameter_Specifications (DTW_Spec));
1559         New_Formal : Entity_Id;
1560
1561      begin
1562         --  Build parameter association for call to wrapped subprogram
1563
1564         while Present (Formal) loop
1565            New_Formal := Defining_Identifier (New_F_Spec);
1566
1567            --  If the controlling argument is inherited, add conversion to
1568            --  parent type for the call.
1569
1570            if Etype (Formal) = Par_Typ
1571              and then Is_Controlling_Formal (Formal)
1572            then
1573               Append_To (Actuals,
1574                 Make_Type_Conversion (Loc,
1575                   New_Occurrence_Of (Par_Typ, Loc),
1576                   New_Occurrence_Of (New_Formal, Loc)));
1577            else
1578               Append_To (Actuals, New_Occurrence_Of (New_Formal, Loc));
1579            end if;
1580
1581            Next_Formal (Formal);
1582            Next (New_F_Spec);
1583         end loop;
1584
1585         if Ekind (Wrapped_Subp) = E_Procedure then
1586            Call :=
1587              Make_Procedure_Call_Statement (Loc,
1588                Name => New_Occurrence_Of (Wrapped_Subp, Loc),
1589                Parameter_Associations => Actuals);
1590         else
1591            Call :=
1592              Make_Simple_Return_Statement (Loc,
1593                Expression =>
1594                  Make_Function_Call (Loc,
1595                    Name => New_Occurrence_Of (Wrapped_Subp, Loc),
1596                    Parameter_Associations => Actuals));
1597         end if;
1598
1599         return
1600           Make_Subprogram_Body (Loc,
1601             Specification              => Copy_Subprogram_Spec (DTW_Spec),
1602             Declarations               => DTW_Decls,
1603             Handled_Statement_Sequence =>
1604               Make_Handled_Sequence_Of_Statements (Loc,
1605                 Statements => New_List (Call),
1606                 End_Label  => Make_Identifier (Loc,
1607                                 Chars (Defining_Entity (DTW_Spec)))));
1608      end Build_DTW_Body;
1609
1610      --------------------
1611      -- Build_DTW_Spec --
1612      --------------------
1613
1614      function Build_DTW_Spec (Par_Prim : Entity_Id) return Node_Id is
1615         DTW_Id   : Entity_Id;
1616         DTW_Spec : Node_Id;
1617
1618      begin
1619         DTW_Spec := Build_Overriding_Spec (Par_Prim, R);
1620         DTW_Id   := Defining_Entity (DTW_Spec);
1621
1622         --  Add minimal decoration of fields
1623
1624         Mutate_Ekind (DTW_Id, Ekind (Par_Prim));
1625         Set_LSP_Subprogram (DTW_Id, Par_Prim);
1626         Set_Is_Dispatch_Table_Wrapper (DTW_Id);
1627         Set_Is_Wrapper (DTW_Id);
1628
1629         --  The DTW wrapper is never a null procedure
1630
1631         if Nkind (DTW_Spec) = N_Procedure_Specification then
1632            Set_Null_Present (DTW_Spec, False);
1633         end if;
1634
1635         return DTW_Spec;
1636      end Build_DTW_Spec;
1637
1638      ---------------------------------------
1639      -- Build_Inherited_Condition_Pragmas --
1640      ---------------------------------------
1641
1642      procedure Build_Inherited_Condition_Pragmas
1643        (Subp           : Entity_Id;
1644         Wrapper_Needed : out Boolean)
1645      is
1646         Class_Pre  : constant Node_Id :=
1647                        Class_Preconditions (Ultimate_Alias (Subp));
1648         Class_Post : Node_Id := Class_Postconditions (Par_Prim);
1649         A_Post     : Node_Id;
1650         New_Prag   : Node_Id;
1651
1652      begin
1653         Wrapper_Needed := False;
1654
1655         if No (Class_Pre) and then No (Class_Post) then
1656            return;
1657         end if;
1658
1659         --  For class-wide preconditions we just evaluate whether the wrapper
1660         --  is needed; there is no need to build the pragma since the check
1661         --  is performed on the caller side.
1662
1663         if Present (Class_Pre)
1664           and then Needs_Wrapper (Class_Pre, Subp, Par_Prim)
1665         then
1666            Wrapper_Needed := True;
1667         end if;
1668
1669         --  For class-wide postconditions we evaluate whether the wrapper is
1670         --  needed and we build the class-wide postcondition pragma to install
1671         --  it in the wrapper.
1672
1673         if Present (Class_Post)
1674           and then Needs_Wrapper (Class_Post, Subp, Par_Prim)
1675         then
1676            Wrapper_Needed := True;
1677
1678            --  Update the class-wide postcondition
1679
1680            Class_Post := New_Copy_Tree (Class_Post);
1681            Build_Class_Wide_Expression
1682              (Pragma_Or_Expr => Class_Post,
1683               Subp           => Subp,
1684               Par_Subp       => Par_Prim,
1685               Adjust_Sloc    => False);
1686
1687            --  Install the updated class-wide postcondition in a copy of the
1688            --  pragma postcondition defined for the nearest ancestor.
1689
1690            A_Post := Get_Class_Wide_Pragma (Par_Prim,
1691                        Pragma_Postcondition);
1692
1693            if No (A_Post) then
1694               declare
1695                  Subps : constant Subprogram_List :=
1696                            Inherited_Subprograms (Subp);
1697               begin
1698                  for Index in Subps'Range loop
1699                     A_Post := Get_Class_Wide_Pragma (Subps (Index),
1700                                 Pragma_Postcondition);
1701                     exit when Present (A_Post);
1702                  end loop;
1703               end;
1704            end if;
1705
1706            New_Prag := New_Copy_Tree (A_Post);
1707            Rewrite
1708              (Expression (First (Pragma_Argument_Associations (New_Prag))),
1709               Class_Post);
1710            Append (New_Prag, Decls);
1711         end if;
1712      end Build_Inherited_Condition_Pragmas;
1713
1714      -------------------
1715      -- Needs_Wrapper --
1716      -------------------
1717
1718      function Needs_Wrapper
1719        (Class_Cond : Node_Id;
1720         Subp       : Entity_Id;
1721         Par_Subp   : Entity_Id) return Boolean
1722      is
1723         Result : Boolean := False;
1724
1725         function Check_Entity (N : Node_Id) return Traverse_Result;
1726         --  Check calls to overridden primitives
1727
1728         --------------------
1729         -- Replace_Entity --
1730         --------------------
1731
1732         function Check_Entity (N : Node_Id) return Traverse_Result is
1733            New_E : Entity_Id;
1734
1735         begin
1736            if Nkind (N) = N_Identifier
1737              and then Present (Entity (N))
1738              and then
1739                (Is_Formal (Entity (N)) or else Is_Subprogram (Entity (N)))
1740              and then
1741                (Nkind (Parent (N)) /= N_Attribute_Reference
1742                  or else Attribute_Name (Parent (N)) /= Name_Class)
1743            then
1744               --  The check does not apply to dispatching calls within the
1745               --  condition, but only to calls whose static tag is that of
1746               --  the parent type.
1747
1748               if Is_Subprogram (Entity (N))
1749                 and then Nkind (Parent (N)) = N_Function_Call
1750                 and then Present (Controlling_Argument (Parent (N)))
1751               then
1752                  return OK;
1753               end if;
1754
1755               --  Determine whether entity has a renaming
1756
1757               New_E := Get_Mapped_Entity (Entity (N));
1758
1759               --  If the entity is an overridden primitive and we are not
1760               --  in GNATprove mode, we must build a wrapper for the current
1761               --  inherited operation. If the reference is the prefix of an
1762               --  attribute such as 'Result (or others ???) there is no need
1763               --  for a wrapper: the condition is just rewritten in terms of
1764               --  the inherited subprogram.
1765
1766               if Present (New_E)
1767                 and then Comes_From_Source (New_E)
1768                 and then Is_Subprogram (New_E)
1769                 and then Nkind (Parent (N)) /= N_Attribute_Reference
1770                 and then not GNATprove_Mode
1771               then
1772                  Result := True;
1773                  return Abandon;
1774               end if;
1775            end if;
1776
1777            return OK;
1778         end Check_Entity;
1779
1780         procedure Check_Condition_Entities is
1781           new Traverse_Proc (Check_Entity);
1782
1783      --  Start of processing for Needs_Wrapper
1784
1785      begin
1786         Update_Primitives_Mapping (Par_Subp, Subp);
1787
1788         Map_Formals (Par_Subp, Subp);
1789         Check_Condition_Entities (Class_Cond);
1790
1791         return Result;
1792      end Needs_Wrapper;
1793
1794      Ifaces_List    : Elist_Id := No_Elist;
1795      Ifaces_Listed  : Boolean := False;
1796      --  Cache the list of interface operations inherited by R
1797
1798   --  Start of processing for Check_Inherited_Conditions
1799
1800   begin
1801      if Late_Overriding then
1802         Op_Node := First_Elmt (Prim_Ops);
1803         while Present (Op_Node) loop
1804            Prim := Node (Op_Node);
1805
1806            --  Map the overridden primitive to the overriding one
1807
1808            if Present (Overridden_Operation (Prim))
1809              and then Comes_From_Source (Prim)
1810            then
1811               Par_Prim := Overridden_Operation (Prim);
1812               Update_Primitives_Mapping (Par_Prim, Prim);
1813
1814               --  Force discarding previous mappings of its formals
1815
1816               Map_Formals (Par_Prim, Prim, Force_Update => True);
1817            end if;
1818
1819            Next_Elmt (Op_Node);
1820         end loop;
1821      end if;
1822
1823      --  Perform validity checks on the inherited conditions of overriding
1824      --  operations, for conformance with LSP, and apply SPARK-specific
1825      --  restrictions on inherited conditions.
1826
1827      Op_Node := First_Elmt (Prim_Ops);
1828      while Present (Op_Node) loop
1829         Prim := Node (Op_Node);
1830
1831         Par_Prim := Overridden_Operation (Prim);
1832         if Present (Par_Prim)
1833           and then Comes_From_Source (Prim)
1834         then
1835            --  When the primitive is an LSP wrapper we climb to the parent
1836            --  primitive that has the inherited contract.
1837
1838            if Is_Wrapper (Par_Prim)
1839              and then Present (LSP_Subprogram (Par_Prim))
1840            then
1841               Par_Prim := LSP_Subprogram (Par_Prim);
1842            end if;
1843
1844            --  Check that overrider and overridden operations have
1845            --  the same strub mode.
1846
1847            Check_Same_Strub_Mode (Prim, Par_Prim);
1848
1849            --  Analyze the contract items of the overridden operation, before
1850            --  they are rewritten as pragmas.
1851
1852            Analyze_Entry_Or_Subprogram_Contract (Par_Prim);
1853
1854            --  In GNATprove mode this is where we can collect the inherited
1855            --  conditions, because we do not create the Check pragmas that
1856            --  normally convey the modified class-wide conditions on
1857            --  overriding operations.
1858
1859            if GNATprove_Mode then
1860               Collect_Inherited_Class_Wide_Conditions (Prim);
1861            end if;
1862         end if;
1863
1864         --  Go over operations inherited from interfaces and check
1865         --  them for strub mode compatibility as well.
1866
1867         if Has_Interfaces (R)
1868           and then Is_Dispatching_Operation (Prim)
1869           and then Find_Dispatching_Type (Prim) = R
1870         then
1871            declare
1872               Elmt        : Elmt_Id;
1873               Iface_Elmt  : Elmt_Id;
1874               Iface       : Entity_Id;
1875               Iface_Prim  : Entity_Id;
1876
1877            begin
1878               --  Collect the interfaces only once. We haven't
1879               --  finished freezing yet, so we can't use the faster
1880               --  search from Sem_Disp.Covered_Interface_Primitives.
1881
1882               if not Ifaces_Listed then
1883                  Collect_Interfaces (R, Ifaces_List);
1884                  Ifaces_Listed := True;
1885               end if;
1886
1887               Iface_Elmt := First_Elmt (Ifaces_List);
1888               while Present (Iface_Elmt) loop
1889                  Iface := Node (Iface_Elmt);
1890
1891                  Elmt := First_Elmt (Primitive_Operations (Iface));
1892                  while Present (Elmt) loop
1893                     Iface_Prim := Node (Elmt);
1894
1895                     if Iface_Prim /= Par_Prim
1896                       and then Chars (Iface_Prim) = Chars (Prim)
1897                       and then Comes_From_Source (Iface_Prim)
1898                       and then (Is_Interface_Conformant
1899                                   (R, Iface_Prim, Prim))
1900                     then
1901                        Check_Same_Strub_Mode (Prim, Iface_Prim);
1902                     end if;
1903
1904                     Next_Elmt (Elmt);
1905                  end loop;
1906
1907                  Next_Elmt (Iface_Elmt);
1908               end loop;
1909            end;
1910         end if;
1911
1912         Next_Elmt (Op_Node);
1913      end loop;
1914
1915      --  Now examine the inherited operations to check whether they require
1916      --  a wrapper to handle inherited conditions that call other primitives,
1917      --  so that LSP can be verified/enforced.
1918
1919      Op_Node := First_Elmt (Prim_Ops);
1920
1921      while Present (Op_Node) loop
1922         Decls          := Empty_List;
1923         Prim           := Node (Op_Node);
1924         Wrapper_Needed := False;
1925
1926         --  Skip internal entities built for mapping interface primitives
1927
1928         if not Comes_From_Source (Prim)
1929           and then Present (Alias (Prim))
1930           and then No (Interface_Alias (Prim))
1931         then
1932            Par_Prim := Ultimate_Alias (Prim);
1933
1934            --  When the primitive is an LSP wrapper we climb to the parent
1935            --  primitive that has the inherited contract.
1936
1937            if Is_Wrapper (Par_Prim)
1938              and then Present (LSP_Subprogram (Par_Prim))
1939            then
1940               Par_Prim := LSP_Subprogram (Par_Prim);
1941            end if;
1942
1943            --  Analyze the contract items of the parent operation, and
1944            --  determine whether a wrapper is needed. This is determined
1945            --  when the condition is rewritten in sem_prag, using the
1946            --  mapping between overridden and overriding operations built
1947            --  in the loop above.
1948
1949            Analyze_Entry_Or_Subprogram_Contract (Par_Prim);
1950            Build_Inherited_Condition_Pragmas (Prim, Wrapper_Needed);
1951         end if;
1952
1953         if Wrapper_Needed
1954           and then not Is_Abstract_Subprogram (Par_Prim)
1955           and then Expander_Active
1956         then
1957            --  Build the dispatch-table wrapper (DTW). The support for
1958            --  AI12-0195 relies on two kind of wrappers: one for indirect
1959            --  calls (also used for AI12-0220), and one for putting in the
1960            --  dispatch table:
1961            --
1962            --    1) "indirect-call wrapper" (ICW) is needed anytime there are
1963            --       class-wide preconditions. Prim'Access will point directly
1964            --       at the ICW if any, or at the "pristine" body if Prim has
1965            --       no class-wide preconditions.
1966            --
1967            --    2) "dispatch-table wrapper" (DTW) is needed anytime the class
1968            --       wide preconditions *or* the class-wide postconditions are
1969            --       affected by overriding.
1970            --
1971            --  The DTW holds a single statement that is a single call where
1972            --  the controlling actuals are conversions to the corresponding
1973            --  type in the parent primitive. If the primitive is a function
1974            --  the statement is a return statement with a call.
1975
1976            declare
1977               Alias_Id : constant Entity_Id  := Ultimate_Alias (Prim);
1978               Loc      : constant Source_Ptr := Sloc (R);
1979               DTW_Body : Node_Id;
1980               DTW_Decl : Node_Id;
1981               DTW_Id   : Entity_Id;
1982               DTW_Spec : Node_Id;
1983
1984            begin
1985               --  The wrapper must be analyzed in the scope of its wrapped
1986               --  primitive (to ensure its correct decoration).
1987
1988               Push_Scope (Scope (Prim));
1989
1990               DTW_Spec := Build_DTW_Spec (Par_Prim);
1991               DTW_Id   := Defining_Entity (DTW_Spec);
1992               DTW_Decl := Make_Subprogram_Declaration (Loc,
1993                             Specification => DTW_Spec);
1994
1995               --  For inherited class-wide preconditions the DTW wrapper
1996               --  reuses the ICW of the parent (which checks the parent
1997               --  interpretation of the class-wide preconditions); the
1998               --  interpretation of the class-wide preconditions for the
1999               --  inherited subprogram is checked at the caller side.
2000
2001               --  When the subprogram inherits class-wide postconditions
2002               --  the DTW also checks the interpretation of the class-wide
2003               --  postconditions for the inherited subprogram, and the body
2004               --  of the parent checks its interpretation of the parent for
2005               --  the class-wide postconditions.
2006
2007               --      procedure Prim (F1 : T1; ...) is
2008               --         [ pragma Check (Postcondition, Expr); ]
2009               --      begin
2010               --         Par_Prim_ICW (Par_Type (F1), ...);
2011               --      end;
2012
2013               if Present (Indirect_Call_Wrapper (Par_Prim)) then
2014                  DTW_Body :=
2015                    Build_DTW_Body (Loc,
2016                      DTW_Spec     => DTW_Spec,
2017                      DTW_Decls    => Decls,
2018                      Par_Prim     => Par_Prim,
2019                      Wrapped_Subp => Indirect_Call_Wrapper (Par_Prim));
2020
2021               --  For subprograms that only inherit class-wide postconditions
2022               --  the DTW wrapper calls the parent primitive (which on its
2023               --  body checks the interpretation of the class-wide post-
2024               --  conditions for the parent subprogram), and the DTW checks
2025               --  the interpretation of the class-wide postconditions for the
2026               --  inherited subprogram.
2027
2028               --      procedure Prim (F1 : T1; ...) is
2029               --         pragma Check (Postcondition, Expr);
2030               --      begin
2031               --         Par_Prim (Par_Type (F1), ...);
2032               --      end;
2033
2034               else
2035                  DTW_Body :=
2036                    Build_DTW_Body (Loc,
2037                      DTW_Spec     => DTW_Spec,
2038                      DTW_Decls    => Decls,
2039                      Par_Prim     => Par_Prim,
2040                      Wrapped_Subp => Par_Prim);
2041               end if;
2042
2043               --  Insert the declaration of the wrapper before the freezing
2044               --  node of the record type declaration to ensure that it will
2045               --  override the internal primitive built by Derive_Subprogram.
2046
2047               if Late_Overriding then
2048                  Ensure_Freeze_Node (R);
2049                  Insert_Before_And_Analyze (Freeze_Node (R), DTW_Decl);
2050               else
2051                  Append_Freeze_Action (R, DTW_Decl);
2052               end if;
2053
2054               Analyze (DTW_Decl);
2055
2056               --  Insert the body of the wrapper in the freeze actions of
2057               --  its record type declaration to ensure that it is placed
2058               --  in the scope of its declaration but not too early to cause
2059               --  premature freezing of other entities.
2060
2061               Append_Freeze_Action (R, DTW_Body);
2062               Analyze (DTW_Body);
2063
2064               --  Ensure correct decoration
2065
2066               pragma Assert (Is_Dispatching_Operation (DTW_Id));
2067               pragma Assert (Present (Overridden_Operation (DTW_Id)));
2068               pragma Assert (Overridden_Operation (DTW_Id) = Alias_Id);
2069
2070               --  Inherit dispatch table slot
2071
2072               Set_DTC_Entity_Value (R, DTW_Id);
2073               Set_DT_Position (DTW_Id, DT_Position (Alias_Id));
2074
2075               --  Register the wrapper in the dispatch table
2076
2077               if Late_Overriding
2078                 and then not Building_Static_DT (R)
2079               then
2080                  Insert_List_After_And_Analyze (Freeze_Node (R),
2081                    Register_Primitive (Loc, DTW_Id));
2082               end if;
2083
2084               --  Build the helper and ICW for the DTW
2085
2086               if Present (Indirect_Call_Wrapper (Par_Prim)) then
2087                  declare
2088                     CW_Subp : Entity_Id;
2089                     Decl_N  : Node_Id;
2090                     Body_N  : Node_Id;
2091
2092                  begin
2093                     Merge_Class_Conditions (DTW_Id);
2094                     Make_Class_Precondition_Subps (DTW_Id,
2095                       Late_Overriding => Late_Overriding);
2096
2097                     CW_Subp := Static_Call_Helper (DTW_Id);
2098                     Decl_N  := Unit_Declaration_Node (CW_Subp);
2099                     Analyze (Decl_N);
2100
2101                     --  If the DTW was built for a late-overriding primitive
2102                     --  its body must be analyzed now (since the tagged type
2103                     --  is already frozen).
2104
2105                     if Late_Overriding then
2106                        Body_N :=
2107                          Unit_Declaration_Node
2108                            (Corresponding_Body (Decl_N));
2109                        Analyze (Body_N);
2110                     end if;
2111                  end;
2112               end if;
2113
2114               Pop_Scope;
2115            end;
2116         end if;
2117
2118         Next_Elmt (Op_Node);
2119      end loop;
2120   end Check_Inherited_Conditions;
2121
2122   ----------------------------
2123   -- Check_Strict_Alignment --
2124   ----------------------------
2125
2126   procedure Check_Strict_Alignment (E : Entity_Id) is
2127      Comp  : Entity_Id;
2128
2129   begin
2130      --  Bit-packed array types do not require strict alignment, even if they
2131      --  are by-reference types, because they are accessed in a special way.
2132
2133      if Is_By_Reference_Type (E) and then not Is_Bit_Packed_Array (E) then
2134         Set_Strict_Alignment (E);
2135
2136      elsif Is_Array_Type (E) then
2137         Set_Strict_Alignment (E, Strict_Alignment (Component_Type (E)));
2138
2139         --  ??? AI12-001: Any component of a packed type that contains an
2140         --  aliased part must be aligned according to the alignment of its
2141         --  subtype (RM 13.2(7)). This means that the following test:
2142
2143         --    if Has_Aliased_Components (E) then
2144         --      Set_Strict_Alignment (E);
2145         --    end if;
2146
2147         --  should be implemented here. Unfortunately it would break Florist,
2148         --  which has the bad habit of overaligning all the types it declares
2149         --  on 32-bit platforms. Other legacy codebases could also be affected
2150         --  because this check has historically been missing in GNAT.
2151
2152      elsif Is_Record_Type (E) then
2153         Comp := First_Component (E);
2154         while Present (Comp) loop
2155            if not Is_Type (Comp)
2156              and then (Is_Aliased (Comp)
2157                         or else Strict_Alignment (Etype (Comp)))
2158            then
2159               Set_Strict_Alignment (E);
2160               return;
2161            end if;
2162
2163            Next_Component (Comp);
2164         end loop;
2165      end if;
2166   end Check_Strict_Alignment;
2167
2168   -------------------------
2169   -- Check_Unsigned_Type --
2170   -------------------------
2171
2172   procedure Check_Unsigned_Type (E : Entity_Id) is
2173      Ancestor : Entity_Id;
2174      Lo_Bound : Node_Id;
2175      Btyp     : Entity_Id;
2176
2177   begin
2178      if not Is_Discrete_Or_Fixed_Point_Type (E) then
2179         return;
2180      end if;
2181
2182      --  Do not attempt to analyze case where range was in error
2183
2184      if No (Scalar_Range (E)) or else Error_Posted (Scalar_Range (E)) then
2185         return;
2186      end if;
2187
2188      --  The situation that is nontrivial is something like:
2189
2190      --     subtype x1 is integer range -10 .. +10;
2191      --     subtype x2 is x1 range 0 .. V1;
2192      --     subtype x3 is x2 range V2 .. V3;
2193      --     subtype x4 is x3 range V4 .. V5;
2194
2195      --  where Vn are variables. Here the base type is signed, but we still
2196      --  know that x4 is unsigned because of the lower bound of x2.
2197
2198      --  The only way to deal with this is to look up the ancestor chain
2199
2200      Ancestor := E;
2201      loop
2202         if Ancestor = Any_Type or else Etype (Ancestor) = Any_Type then
2203            return;
2204         end if;
2205
2206         Lo_Bound := Type_Low_Bound (Ancestor);
2207
2208         if Compile_Time_Known_Value (Lo_Bound) then
2209            if Expr_Rep_Value (Lo_Bound) >= 0 then
2210               Set_Is_Unsigned_Type (E, True);
2211            end if;
2212
2213            return;
2214
2215         else
2216            Ancestor := Ancestor_Subtype (Ancestor);
2217
2218            --  If no ancestor had a static lower bound, go to base type
2219
2220            if No (Ancestor) then
2221
2222               --  Note: the reason we still check for a compile time known
2223               --  value for the base type is that at least in the case of
2224               --  generic formals, we can have bounds that fail this test,
2225               --  and there may be other cases in error situations.
2226
2227               Btyp := Base_Type (E);
2228
2229               if Btyp = Any_Type or else Etype (Btyp) = Any_Type then
2230                  return;
2231               end if;
2232
2233               Lo_Bound := Type_Low_Bound (Base_Type (E));
2234
2235               if Compile_Time_Known_Value (Lo_Bound)
2236                 and then Expr_Rep_Value (Lo_Bound) >= 0
2237               then
2238                  Set_Is_Unsigned_Type (E, True);
2239               end if;
2240
2241               return;
2242            end if;
2243         end if;
2244      end loop;
2245   end Check_Unsigned_Type;
2246
2247   ------------------------------
2248   -- Is_Full_Access_Aggregate --
2249   ------------------------------
2250
2251   function Is_Full_Access_Aggregate (N : Node_Id) return Boolean is
2252      Loc   : constant Source_Ptr := Sloc (N);
2253      New_N : Node_Id;
2254      Par   : Node_Id;
2255      Temp  : Entity_Id;
2256      Typ   : Entity_Id;
2257
2258   begin
2259      Par := Parent (N);
2260
2261      --  Array may be qualified, so find outer context
2262
2263      if Nkind (Par) = N_Qualified_Expression then
2264         Par := Parent (Par);
2265      end if;
2266
2267      if not Comes_From_Source (Par) then
2268         return False;
2269      end if;
2270
2271      case Nkind (Par) is
2272         when N_Assignment_Statement =>
2273            Typ := Etype (Name (Par));
2274
2275            if not Is_Full_Access (Typ)
2276              and then not Is_Full_Access_Object (Name (Par))
2277            then
2278               return False;
2279            end if;
2280
2281         when N_Object_Declaration =>
2282            Typ := Etype (Defining_Identifier (Par));
2283
2284            if not Is_Full_Access (Typ)
2285              and then not Is_Full_Access (Defining_Identifier (Par))
2286            then
2287               return False;
2288            end if;
2289
2290         when others =>
2291            return False;
2292      end case;
2293
2294      Temp := Make_Temporary (Loc, 'T', N);
2295      New_N :=
2296        Make_Object_Declaration (Loc,
2297          Defining_Identifier => Temp,
2298          Constant_Present    => True,
2299          Object_Definition   => New_Occurrence_Of (Typ, Loc),
2300          Expression          => Relocate_Node (N));
2301      Insert_Before (Par, New_N);
2302      Analyze (New_N);
2303
2304      Set_Expression (Par, New_Occurrence_Of (Temp, Loc));
2305      return True;
2306   end Is_Full_Access_Aggregate;
2307
2308   -----------------------------------------------
2309   -- Explode_Initialization_Compound_Statement --
2310   -----------------------------------------------
2311
2312   procedure Explode_Initialization_Compound_Statement (E : Entity_Id) is
2313      Init_Stmts : constant Node_Id := Initialization_Statements (E);
2314
2315   begin
2316      if Present (Init_Stmts)
2317        and then Nkind (Init_Stmts) = N_Compound_Statement
2318      then
2319         Insert_List_Before (Init_Stmts, Actions (Init_Stmts));
2320
2321         --  Note that we rewrite Init_Stmts into a NULL statement, rather than
2322         --  just removing it, because Freeze_All may rely on this particular
2323         --  Node_Id still being present in the enclosing list to know where to
2324         --  stop freezing.
2325
2326         Rewrite (Init_Stmts, Make_Null_Statement (Sloc (Init_Stmts)));
2327
2328         Set_Initialization_Statements (E, Empty);
2329      end if;
2330   end Explode_Initialization_Compound_Statement;
2331
2332   ----------------
2333   -- Freeze_All --
2334   ----------------
2335
2336   --  Note: the easy coding for this procedure would be to just build a
2337   --  single list of freeze nodes and then insert them and analyze them
2338   --  all at once. This won't work, because the analysis of earlier freeze
2339   --  nodes may recursively freeze types which would otherwise appear later
2340   --  on in the freeze list. So we must analyze and expand the freeze nodes
2341   --  as they are generated.
2342
2343   procedure Freeze_All (From : Entity_Id; After : in out Node_Id) is
2344      procedure Freeze_All_Ent (From : Entity_Id; After : in out Node_Id);
2345      --  This is the internal recursive routine that does freezing of entities
2346      --  (but NOT the analysis of default expressions, which should not be
2347      --  recursive, we don't want to analyze those till we are sure that ALL
2348      --  the types are frozen).
2349
2350      --------------------
2351      -- Freeze_All_Ent --
2352      --------------------
2353
2354      procedure Freeze_All_Ent (From : Entity_Id; After : in out Node_Id) is
2355         E     : Entity_Id;
2356         Flist : List_Id;
2357         Lastn : Node_Id;
2358
2359         procedure Process_Flist;
2360         --  If freeze nodes are present, insert and analyze, and reset cursor
2361         --  for next insertion.
2362
2363         -------------------
2364         -- Process_Flist --
2365         -------------------
2366
2367         procedure Process_Flist is
2368         begin
2369            if Is_Non_Empty_List (Flist) then
2370               Lastn := Next (After);
2371               Insert_List_After_And_Analyze (After, Flist);
2372
2373               if Present (Lastn) then
2374                  After := Prev (Lastn);
2375               else
2376                  After := Last (List_Containing (After));
2377               end if;
2378            end if;
2379         end Process_Flist;
2380
2381      --  Start of processing for Freeze_All_Ent
2382
2383      begin
2384         E := From;
2385         while Present (E) loop
2386
2387            --  If the entity is an inner package which is not a package
2388            --  renaming, then its entities must be frozen at this point. Note
2389            --  that such entities do NOT get frozen at the end of the nested
2390            --  package itself (only library packages freeze).
2391
2392            --  Same is true for task declarations, where anonymous records
2393            --  created for entry parameters must be frozen.
2394
2395            if Ekind (E) = E_Package
2396              and then No (Renamed_Entity (E))
2397              and then not Is_Child_Unit (E)
2398              and then not Is_Frozen (E)
2399            then
2400               Push_Scope (E);
2401
2402               Install_Visible_Declarations (E);
2403               Install_Private_Declarations (E);
2404               Freeze_All (First_Entity (E), After);
2405
2406               End_Package_Scope (E);
2407
2408               if Is_Generic_Instance (E)
2409                 and then Has_Delayed_Freeze (E)
2410               then
2411                  Set_Has_Delayed_Freeze (E, False);
2412                  Expand_N_Package_Declaration (Unit_Declaration_Node (E));
2413               end if;
2414
2415            elsif Ekind (E) in Task_Kind
2416              and then Nkind (Parent (E)) in
2417                         N_Single_Task_Declaration | N_Task_Type_Declaration
2418            then
2419               Push_Scope (E);
2420               Freeze_All (First_Entity (E), After);
2421               End_Scope;
2422
2423            --  For a derived tagged type, we must ensure that all the
2424            --  primitive operations of the parent have been frozen, so that
2425            --  their addresses will be in the parent's dispatch table at the
2426            --  point it is inherited.
2427
2428            elsif Ekind (E) = E_Record_Type
2429              and then Is_Tagged_Type (E)
2430              and then Is_Tagged_Type (Etype (E))
2431              and then Is_Derived_Type (E)
2432            then
2433               declare
2434                  Prim_List : constant Elist_Id :=
2435                               Primitive_Operations (Etype (E));
2436
2437                  Prim : Elmt_Id;
2438                  Subp : Entity_Id;
2439
2440               begin
2441                  Prim := First_Elmt (Prim_List);
2442                  while Present (Prim) loop
2443                     Subp := Node (Prim);
2444
2445                     if Comes_From_Source (Subp)
2446                       and then not Is_Frozen (Subp)
2447                     then
2448                        Flist := Freeze_Entity (Subp, After);
2449                        Process_Flist;
2450                     end if;
2451
2452                     Next_Elmt (Prim);
2453                  end loop;
2454               end;
2455            end if;
2456
2457            if not Is_Frozen (E) then
2458               Flist := Freeze_Entity (E, After);
2459               Process_Flist;
2460
2461            --  If already frozen, and there are delayed aspects, this is where
2462            --  we do the visibility check for these aspects (see Sem_Ch13 spec
2463            --  for a description of how we handle aspect visibility).
2464
2465            elsif Has_Delayed_Aspects (E) then
2466               declare
2467                  Ritem : Node_Id;
2468
2469               begin
2470                  Ritem := First_Rep_Item (E);
2471                  while Present (Ritem) loop
2472                     if Nkind (Ritem) = N_Aspect_Specification
2473                       and then Entity (Ritem) = E
2474                       and then Is_Delayed_Aspect (Ritem)
2475                     then
2476                        Check_Aspect_At_End_Of_Declarations (Ritem);
2477                     end if;
2478
2479                     Next_Rep_Item (Ritem);
2480                  end loop;
2481               end;
2482            end if;
2483
2484            --  If an incomplete type is still not frozen, this may be a
2485            --  premature freezing because of a body declaration that follows.
2486            --  Indicate where the freezing took place. Freezing will happen
2487            --  if the body comes from source, but not if it is internally
2488            --  generated, for example as the body of a type invariant.
2489
2490            --  If the freezing is caused by the end of the current declarative
2491            --  part, it is a Taft Amendment type, and there is no error.
2492
2493            if not Is_Frozen (E)
2494              and then Ekind (E) = E_Incomplete_Type
2495            then
2496               declare
2497                  Bod : constant Node_Id := Next (After);
2498
2499               begin
2500                  --  The presence of a body freezes all entities previously
2501                  --  declared in the current list of declarations, but this
2502                  --  does not apply if the body does not come from source.
2503                  --  A type invariant is transformed into a subprogram body
2504                  --  which is placed at the end of the private part of the
2505                  --  current package, but this body does not freeze incomplete
2506                  --  types that may be declared in this private part.
2507
2508                  if Comes_From_Source (Bod)
2509                    and then Nkind (Bod) in N_Entry_Body
2510                                          | N_Package_Body
2511                                          | N_Protected_Body
2512                                          | N_Subprogram_Body
2513                                          | N_Task_Body
2514                                          | N_Body_Stub
2515                    and then
2516                      In_Same_List (After, Parent (E))
2517                  then
2518                     Error_Msg_Sloc := Sloc (Next (After));
2519                     Error_Msg_NE
2520                       ("type& is frozen# before its full declaration",
2521                         Parent (E), E);
2522                  end if;
2523               end;
2524            end if;
2525
2526            Next_Entity (E);
2527         end loop;
2528      end Freeze_All_Ent;
2529
2530      --  Local variables
2531
2532      Decl : Node_Id;
2533      E    : Entity_Id;
2534      Item : Entity_Id;
2535
2536   --  Start of processing for Freeze_All
2537
2538   begin
2539      Freeze_All_Ent (From, After);
2540
2541      --  Now that all types are frozen, we can deal with default expressions
2542      --  that require us to build a default expression functions. This is the
2543      --  point at which such functions are constructed (after all types that
2544      --  might be used in such expressions have been frozen).
2545
2546      --  For subprograms that are renaming_as_body, we create the wrapper
2547      --  bodies as needed.
2548
2549      --  We also add finalization chains to access types whose designated
2550      --  types are controlled. This is normally done when freezing the type,
2551      --  but this misses recursive type definitions where the later members
2552      --  of the recursion introduce controlled components.
2553
2554      --  Loop through entities
2555
2556      E := From;
2557      while Present (E) loop
2558         if Is_Subprogram (E) then
2559            if not Default_Expressions_Processed (E) then
2560               Process_Default_Expressions (E, After);
2561            end if;
2562
2563            --  Check subprogram renamings for the same strub-mode.
2564            --  Avoid rechecking dispatching operations, that's taken
2565            --  care of in Check_Inherited_Conditions, that covers
2566            --  inherited interface operations.
2567
2568            Item := Alias (E);
2569            if Present (Item)
2570              and then not Is_Dispatching_Operation (E)
2571            then
2572               Check_Same_Strub_Mode (E, Item);
2573            end if;
2574
2575            if not Has_Completion (E) then
2576               Decl := Unit_Declaration_Node (E);
2577
2578               if Nkind (Decl) = N_Subprogram_Renaming_Declaration then
2579                  if Error_Posted (Decl) then
2580                     Set_Has_Completion (E);
2581                  else
2582                     Build_And_Analyze_Renamed_Body (Decl, E, After);
2583                  end if;
2584
2585               elsif Nkind (Decl) = N_Subprogram_Declaration
2586                 and then Present (Corresponding_Body (Decl))
2587                 and then
2588                   Nkind (Unit_Declaration_Node (Corresponding_Body (Decl))) =
2589                     N_Subprogram_Renaming_Declaration
2590               then
2591                  Build_And_Analyze_Renamed_Body
2592                    (Decl, Corresponding_Body (Decl), After);
2593               end if;
2594            end if;
2595
2596         --  Freeze the default expressions of entries, entry families, and
2597         --  protected subprograms.
2598
2599         elsif Is_Concurrent_Type (E) then
2600            Item := First_Entity (E);
2601            while Present (Item) loop
2602               if Is_Subprogram_Or_Entry (Item)
2603                 and then not Default_Expressions_Processed (Item)
2604               then
2605                  Process_Default_Expressions (Item, After);
2606               end if;
2607
2608               Next_Entity (Item);
2609            end loop;
2610         end if;
2611
2612         --  Historical note: We used to create a finalization master for an
2613         --  access type whose designated type is not controlled, but contains
2614         --  private controlled compoments. This form of postprocessing is no
2615         --  longer needed because the finalization master is now created when
2616         --  the access type is frozen (see Exp_Ch3.Freeze_Type).
2617
2618         Next_Entity (E);
2619      end loop;
2620   end Freeze_All;
2621
2622   -----------------------
2623   -- Freeze_And_Append --
2624   -----------------------
2625
2626   procedure Freeze_And_Append
2627     (Ent    : Entity_Id;
2628      N      : Node_Id;
2629      Result : in out List_Id)
2630   is
2631      L : constant List_Id := Freeze_Entity (Ent, N);
2632   begin
2633      if Is_Non_Empty_List (L) then
2634         if Result = No_List then
2635            Result := L;
2636         else
2637            Append_List (L, Result);
2638         end if;
2639      end if;
2640   end Freeze_And_Append;
2641
2642   -------------------
2643   -- Freeze_Before --
2644   -------------------
2645
2646   procedure Freeze_Before
2647     (N                 : Node_Id;
2648      T                 : Entity_Id;
2649      Do_Freeze_Profile : Boolean := True)
2650   is
2651      --  Freeze T, then insert the generated Freeze nodes before the node N.
2652      --  Flag Freeze_Profile is used when T is an overloadable entity, and
2653      --  indicates whether its profile should be frozen at the same time.
2654
2655      Freeze_Nodes : constant List_Id :=
2656                       Freeze_Entity (T, N, Do_Freeze_Profile);
2657      Pack         : constant Entity_Id := Scope (T);
2658
2659   begin
2660      if Ekind (T) = E_Function then
2661         Check_Expression_Function (N, T);
2662      end if;
2663
2664      if Is_Non_Empty_List (Freeze_Nodes) then
2665
2666         --  If the entity is a type declared in an inner package, it may be
2667         --  frozen by an outer declaration before the package itself is
2668         --  frozen. Install the package scope to analyze the freeze nodes,
2669         --  which may include generated subprograms such as predicate
2670         --  functions, etc.
2671
2672         if Is_Type (T) and then From_Nested_Package (T) then
2673            Push_Scope (Pack);
2674            Install_Visible_Declarations (Pack);
2675            Install_Private_Declarations (Pack);
2676            Insert_Actions (N, Freeze_Nodes);
2677            End_Package_Scope (Pack);
2678
2679         else
2680            Insert_Actions (N, Freeze_Nodes);
2681         end if;
2682      end if;
2683   end Freeze_Before;
2684
2685   -------------------
2686   -- Freeze_Entity --
2687   -------------------
2688
2689   --  WARNING: This routine manages Ghost regions. Return statements must be
2690   --  replaced by gotos which jump to the end of the routine and restore the
2691   --  Ghost mode.
2692
2693   function Freeze_Entity
2694     (E                 : Entity_Id;
2695      N                 : Node_Id;
2696      Do_Freeze_Profile : Boolean := True) return List_Id
2697   is
2698      Loc : constant Source_Ptr := Sloc (N);
2699
2700      Saved_GM  : constant Ghost_Mode_Type := Ghost_Mode;
2701      Saved_IGR : constant Node_Id         := Ignored_Ghost_Region;
2702      --  Save the Ghost-related attributes to restore on exit
2703
2704      Atype  : Entity_Id;
2705      Comp   : Entity_Id;
2706      F_Node : Node_Id;
2707      Formal : Entity_Id;
2708      Indx   : Node_Id;
2709
2710      Result : List_Id := No_List;
2711      --  List of freezing actions, left at No_List if none
2712
2713      Test_E : Entity_Id := E;
2714      --  This could use a comment ???
2715
2716      procedure Add_To_Result (Fnod : Node_Id);
2717      --  Add freeze action Fnod to list Result
2718
2719      function After_Last_Declaration return Boolean;
2720      --  If Loc is a freeze_entity that appears after the last declaration
2721      --  in the scope, inhibit error messages on late completion.
2722
2723      procedure Check_Current_Instance (Comp_Decl : Node_Id);
2724      --  Check that an Access or Unchecked_Access attribute with a prefix
2725      --  which is the current instance type can only be applied when the type
2726      --  is limited.
2727
2728      procedure Check_No_Parts_Violations
2729        (Typ : Entity_Id; Aspect_No_Parts : Aspect_Id) with
2730         Pre => Aspect_No_Parts in
2731                  Aspect_No_Controlled_Parts | Aspect_No_Task_Parts;
2732      --  Check that Typ does not violate the semantics of the specified
2733      --  Aspect_No_Parts (No_Controlled_Parts or No_Task_Parts) when it is
2734      --  specified on Typ or one of its ancestors.
2735
2736      procedure Check_Suspicious_Convention (Rec_Type : Entity_Id);
2737      --  Give a warning for pragma Convention with language C or C++ applied
2738      --  to a discriminated record type. This is suppressed for the unchecked
2739      --  union case, since the whole point in this case is interface C. We
2740      --  also do not generate this within instantiations, since we will have
2741      --  generated a message on the template.
2742
2743      procedure Check_Suspicious_Modulus (Utype : Entity_Id);
2744      --  Give warning for modulus of 8, 16, 32, 64 or 128 given as an explicit
2745      --  integer literal without an explicit corresponding size clause. The
2746      --  caller has checked that Utype is a modular integer type.
2747
2748      procedure Freeze_Array_Type (Arr : Entity_Id);
2749      --  Freeze array type, including freezing index and component types
2750
2751      procedure Freeze_Object_Declaration (E : Entity_Id);
2752      --  Perform checks and generate freeze node if needed for a constant or
2753      --  variable declared by an object declaration.
2754
2755      function Freeze_Generic_Entities (Pack : Entity_Id) return List_Id;
2756      --  Create Freeze_Generic_Entity nodes for types declared in a generic
2757      --  package. Recurse on inner generic packages.
2758
2759      function Freeze_Profile (E : Entity_Id) return Boolean;
2760      --  Freeze formals and return type of subprogram. If some type in the
2761      --  profile is incomplete and we are in an instance, freezing of the
2762      --  entity will take place elsewhere, and the function returns False.
2763
2764      procedure Freeze_Record_Type (Rec : Entity_Id);
2765      --  Freeze record type, including freezing component types, and freezing
2766      --  primitive operations if this is a tagged type.
2767
2768      function Has_Boolean_Aspect_Import (E : Entity_Id) return Boolean;
2769      --  Determine whether an arbitrary entity is subject to Boolean aspect
2770      --  Import and its value is specified as True.
2771
2772      procedure Inherit_Freeze_Node
2773        (Fnod : Node_Id;
2774         Typ  : Entity_Id);
2775      --  Set type Typ's freeze node to refer to Fnode. This routine ensures
2776      --  that any attributes attached to Typ's original node are preserved.
2777
2778      procedure Wrap_Imported_Subprogram (E : Entity_Id);
2779      --  If E is an entity for an imported subprogram with pre/post-conditions
2780      --  then this procedure will create a wrapper to ensure that proper run-
2781      --  time checking of the pre/postconditions. See body for details.
2782
2783      -------------------
2784      -- Add_To_Result --
2785      -------------------
2786
2787      procedure Add_To_Result (Fnod : Node_Id) is
2788      begin
2789         Append_New_To (Result, Fnod);
2790      end Add_To_Result;
2791
2792      ----------------------------
2793      -- After_Last_Declaration --
2794      ----------------------------
2795
2796      function After_Last_Declaration return Boolean is
2797         Spec : constant Node_Id := Parent (Current_Scope);
2798
2799      begin
2800         if Nkind (Spec) = N_Package_Specification then
2801            if Present (Private_Declarations (Spec)) then
2802               return Loc >= Sloc (Last (Private_Declarations (Spec)));
2803            elsif Present (Visible_Declarations (Spec)) then
2804               return Loc >= Sloc (Last (Visible_Declarations (Spec)));
2805            else
2806               return False;
2807            end if;
2808
2809         else
2810            return False;
2811         end if;
2812      end After_Last_Declaration;
2813
2814      ----------------------------
2815      -- Check_Current_Instance --
2816      ----------------------------
2817
2818      procedure Check_Current_Instance (Comp_Decl : Node_Id) is
2819
2820         function Is_Aliased_View_Of_Type (Typ : Entity_Id) return Boolean;
2821         --  Determine whether Typ is compatible with the rules for aliased
2822         --  views of types as defined in RM 3.10 in the various dialects.
2823
2824         function Process (N : Node_Id) return Traverse_Result;
2825         --  Process routine to apply check to given node
2826
2827         -----------------------------
2828         -- Is_Aliased_View_Of_Type --
2829         -----------------------------
2830
2831         function Is_Aliased_View_Of_Type (Typ : Entity_Id) return Boolean is
2832            Typ_Decl : constant Node_Id := Parent (Typ);
2833
2834         begin
2835            --  Common case
2836
2837            if Nkind (Typ_Decl) = N_Full_Type_Declaration
2838              and then Limited_Present (Type_Definition (Typ_Decl))
2839            then
2840               return True;
2841
2842            --  The following paragraphs describe what a legal aliased view of
2843            --  a type is in the various dialects of Ada.
2844
2845            --  Ada 95
2846
2847            --  The current instance of a limited type, and a formal parameter
2848            --  or generic formal object of a tagged type.
2849
2850            --  Ada 95 limited type
2851            --    * Type with reserved word "limited"
2852            --    * A protected or task type
2853            --    * A composite type with limited component
2854
2855            elsif Ada_Version <= Ada_95 then
2856               return Is_Limited_Type (Typ);
2857
2858            --  Ada 2005
2859
2860            --  The current instance of a limited tagged type, a protected
2861            --  type, a task type, or a type that has the reserved word
2862            --  "limited" in its full definition ... a formal parameter or
2863            --  generic formal object of a tagged type.
2864
2865            --  Ada 2005 limited type
2866            --    * Type with reserved word "limited", "synchronized", "task"
2867            --      or "protected"
2868            --    * A composite type with limited component
2869            --    * A derived type whose parent is a non-interface limited type
2870
2871            elsif Ada_Version = Ada_2005 then
2872               return
2873                 (Is_Limited_Type (Typ) and then Is_Tagged_Type (Typ))
2874                   or else
2875                     (Is_Derived_Type (Typ)
2876                       and then not Is_Interface (Etype (Typ))
2877                       and then Is_Limited_Type (Etype (Typ)));
2878
2879            --  Ada 2012 and beyond
2880
2881            --  The current instance of an immutably limited type ... a formal
2882            --  parameter or generic formal object of a tagged type.
2883
2884            --  Ada 2012 limited type
2885            --    * Type with reserved word "limited", "synchronized", "task"
2886            --      or "protected"
2887            --    * A composite type with limited component
2888            --    * A derived type whose parent is a non-interface limited type
2889            --    * An incomplete view
2890
2891            --  Ada 2012 immutably limited type
2892            --    * Explicitly limited record type
2893            --    * Record extension with "limited" present
2894            --    * Non-formal limited private type that is either tagged
2895            --      or has at least one access discriminant with a default
2896            --      expression
2897            --    * Task type, protected type or synchronized interface
2898            --    * Type derived from immutably limited type
2899
2900            else
2901               return
2902                 Is_Immutably_Limited_Type (Typ)
2903                   or else Is_Incomplete_Type (Typ);
2904            end if;
2905         end Is_Aliased_View_Of_Type;
2906
2907         -------------
2908         -- Process --
2909         -------------
2910
2911         function Process (N : Node_Id) return Traverse_Result is
2912         begin
2913            case Nkind (N) is
2914               when N_Attribute_Reference =>
2915                  if Attribute_Name (N) in Name_Access | Name_Unchecked_Access
2916                    and then Is_Entity_Name (Prefix (N))
2917                    and then Is_Type (Entity (Prefix (N)))
2918                    and then Entity (Prefix (N)) = E
2919                  then
2920                     if Ada_Version < Ada_2012 then
2921                        Error_Msg_N
2922                          ("current instance must be a limited type",
2923                           Prefix (N));
2924                     else
2925                        Error_Msg_N
2926                          ("current instance must be an immutably limited "
2927                           & "type (RM-2012, 7.5 (8.1/3))", Prefix (N));
2928                     end if;
2929
2930                     return Abandon;
2931
2932                  else
2933                     return OK;
2934                  end if;
2935
2936               when others =>
2937                  return OK;
2938            end case;
2939         end Process;
2940
2941         procedure Traverse is new Traverse_Proc (Process);
2942
2943         --  Local variables
2944
2945         Rec_Type : constant Entity_Id :=
2946                      Scope (Defining_Identifier (Comp_Decl));
2947
2948      --  Start of processing for Check_Current_Instance
2949
2950      begin
2951         if not Is_Aliased_View_Of_Type (Rec_Type) then
2952            Traverse (Comp_Decl);
2953         end if;
2954      end Check_Current_Instance;
2955
2956      -------------------------------
2957      -- Check_No_Parts_Violations --
2958      -------------------------------
2959
2960      procedure Check_No_Parts_Violations
2961        (Typ : Entity_Id; Aspect_No_Parts : Aspect_Id)
2962      is
2963
2964         function Find_Aspect_No_Parts
2965           (Typ : Entity_Id) return Node_Id;
2966         --  Search for Aspect_No_Parts on a given type. When
2967         --  the aspect is not explicity specified Empty is returned.
2968
2969         function Get_Aspect_No_Parts_Value
2970           (Typ : Entity_Id) return Entity_Id;
2971         --  Obtain the value for the Aspect_No_Parts on a given
2972         --  type. When the aspect is not explicitly specified Empty is
2973         --  returned.
2974
2975         function Has_Aspect_No_Parts
2976           (Typ : Entity_Id) return Boolean;
2977         --  Predicate function which identifies whether No_Parts
2978         --  is explicitly specified on a given type.
2979
2980         -------------------------------------
2981         -- Find_Aspect_No_Parts --
2982         -------------------------------------
2983
2984         function Find_Aspect_No_Parts
2985           (Typ : Entity_Id) return Node_Id
2986         is
2987            Partial_View : constant Entity_Id :=
2988              Incomplete_Or_Partial_View (Typ);
2989
2990            Aspect_Spec : Entity_Id :=
2991              Find_Aspect (Typ, Aspect_No_Parts);
2992            Curr_Aspect_Spec : Entity_Id;
2993         begin
2994
2995            --  Examine Typ's associated node, when present, since aspect
2996            --  specifications do not get transferred when nodes get rewritten.
2997
2998            --  For example, this can happen in the expansion of array types
2999
3000            if No (Aspect_Spec)
3001              and then Present (Associated_Node_For_Itype (Typ))
3002              and then Nkind (Associated_Node_For_Itype (Typ))
3003                         = N_Full_Type_Declaration
3004            then
3005               Aspect_Spec :=
3006                 Find_Aspect
3007                   (Id => Defining_Identifier
3008                            (Associated_Node_For_Itype (Typ)),
3009                    A  => Aspect_No_Parts);
3010            end if;
3011
3012            --  Examine aspects specifications on private type declarations
3013
3014            --  Should Find_Aspect be improved to handle this case ???
3015
3016            if No (Aspect_Spec)
3017              and then Present (Partial_View)
3018              and then Present
3019                         (Aspect_Specifications
3020                           (Declaration_Node
3021                             (Partial_View)))
3022            then
3023               Curr_Aspect_Spec :=
3024                 First
3025                   (Aspect_Specifications
3026                     (Declaration_Node
3027                       (Partial_View)));
3028
3029               --  Search through aspects present on the private type
3030
3031               while Present (Curr_Aspect_Spec) loop
3032                  if Get_Aspect_Id (Curr_Aspect_Spec)
3033                       = Aspect_No_Parts
3034                  then
3035                     Aspect_Spec := Curr_Aspect_Spec;
3036                     exit;
3037                  end if;
3038
3039                  Next (Curr_Aspect_Spec);
3040               end loop;
3041
3042            end if;
3043
3044            --  When errors are posted on the aspect return Empty
3045
3046            if Error_Posted (Aspect_Spec) then
3047               return Empty;
3048            end if;
3049
3050            return Aspect_Spec;
3051         end Find_Aspect_No_Parts;
3052
3053         ------------------------------------------
3054         -- Get_Aspect_No_Parts_Value --
3055         ------------------------------------------
3056
3057         function Get_Aspect_No_Parts_Value
3058           (Typ : Entity_Id) return Entity_Id
3059         is
3060            Aspect_Spec : constant Entity_Id :=
3061              Find_Aspect_No_Parts (Typ);
3062         begin
3063
3064            --  Return the value of the aspect when present
3065
3066            if Present (Aspect_Spec) then
3067
3068               --  No expression is the same as True
3069
3070               if No (Expression (Aspect_Spec)) then
3071                  return Standard_True;
3072               end if;
3073
3074               --  Assume its expression has already been constant folded into
3075               --  a Boolean value and return its value.
3076
3077               return Entity (Expression (Aspect_Spec));
3078            end if;
3079
3080            --  Otherwise, the aspect is not specified - so return Empty
3081
3082            return Empty;
3083         end Get_Aspect_No_Parts_Value;
3084
3085         ------------------------------------
3086         -- Has_Aspect_No_Parts --
3087         ------------------------------------
3088
3089         function Has_Aspect_No_Parts
3090           (Typ : Entity_Id) return Boolean
3091         is (Present (Find_Aspect_No_Parts (Typ)));
3092
3093         --  Generic instances
3094
3095         -------------------------------------------
3096         -- Get_Generic_Formal_Types_In_Hierarchy --
3097         -------------------------------------------
3098
3099         function Get_Generic_Formal_Types_In_Hierarchy
3100           is new Collect_Types_In_Hierarchy (Predicate => Is_Generic_Formal);
3101         --  Return a list of all types within a given type's hierarchy which
3102         --  are generic formals.
3103
3104         ----------------------------------------
3105         -- Get_Types_With_Aspect_In_Hierarchy --
3106         ----------------------------------------
3107
3108         function Get_Types_With_Aspect_In_Hierarchy
3109           is new Collect_Types_In_Hierarchy
3110                    (Predicate => Has_Aspect_No_Parts);
3111         --  Returns a list of all types within a given type's hierarchy which
3112         --  have the Aspect_No_Parts specified.
3113
3114         --  Local declarations
3115
3116         Aspect_Value      : Entity_Id;
3117         Curr_Value        : Entity_Id;
3118         Curr_Typ_Elmt     : Elmt_Id;
3119         Curr_Body_Elmt    : Elmt_Id;
3120         Curr_Formal_Elmt  : Elmt_Id;
3121         Gen_Bodies        : Elist_Id;
3122         Gen_Formals       : Elist_Id;
3123         Scop              : Entity_Id;
3124         Types_With_Aspect : Elist_Id;
3125
3126      --  Start of processing for Check_No_Parts_Violations
3127
3128      begin
3129         --  Nothing to check if the type is elementary or artificial
3130
3131         if Is_Elementary_Type (Typ) or else not Comes_From_Source (Typ) then
3132            return;
3133         end if;
3134
3135         Types_With_Aspect := Get_Types_With_Aspect_In_Hierarchy (Typ);
3136
3137         --  Nothing to check if there are no types with No_Parts specified
3138
3139         if Is_Empty_Elmt_List (Types_With_Aspect) then
3140            return;
3141         end if;
3142
3143         --  Set name for all errors below
3144
3145         Error_Msg_Name_1 := Aspect_Names (Aspect_No_Parts);
3146
3147         --  Obtain the aspect value for No_Parts for comparison
3148
3149         Aspect_Value :=
3150           Get_Aspect_No_Parts_Value
3151             (Node (First_Elmt (Types_With_Aspect)));
3152
3153         --  When the value is True and there are controlled/task parts or the
3154         --  type itself is controlled/task, trigger the appropriate error.
3155
3156         if Aspect_Value = Standard_True then
3157            if Aspect_No_Parts = Aspect_No_Controlled_Parts then
3158               if Is_Controlled (Typ) or else Has_Controlled_Component (Typ)
3159               then
3160                  Error_Msg_N
3161                    ("aspect % applied to controlled type &", Typ);
3162               end if;
3163
3164            elsif Aspect_No_Parts = Aspect_No_Task_Parts then
3165               if Has_Task (Typ) then
3166                  Error_Msg_N
3167                    ("aspect % applied to task type &", Typ);
3168               end if;
3169
3170            else
3171               raise Program_Error;
3172            end if;
3173         end if;
3174
3175         --  Move through Types_With_Aspect - checking that the value specified
3176         --  for their corresponding Aspect_No_Parts do not override each
3177         --  other.
3178
3179         Curr_Typ_Elmt := First_Elmt (Types_With_Aspect);
3180         while Present (Curr_Typ_Elmt) loop
3181            Curr_Value :=
3182              Get_Aspect_No_Parts_Value (Node (Curr_Typ_Elmt));
3183
3184            --  Compare the aspect value against the current type
3185
3186            if Curr_Value /= Aspect_Value then
3187               Error_Msg_NE
3188                 ("cannot override aspect % of "
3189                   & "ancestor type &", Typ, Node (Curr_Typ_Elmt));
3190               return;
3191            end if;
3192
3193            Next_Elmt (Curr_Typ_Elmt);
3194         end loop;
3195
3196         --  Issue an error if the aspect applies to a type declared inside a
3197         --  generic body and if said type derives from or has a component
3198         --  of ageneric formal type - since those are considered to have
3199         --  controlled/task parts and have Aspect_No_Parts specified as
3200         --  False by default (RM H.4.1(4/5) is about the language-defined
3201         --  No_Controlled_Parts aspect, and we are using the same rules for
3202         --  No_Task_Parts).
3203
3204         --  We do not check tagged types since deriving from a formal type
3205         --  within an enclosing generic unit is already illegal
3206         --  (RM 3.9.1 (4/2)).
3207
3208         if Aspect_Value = Standard_True
3209           and then In_Generic_Body (Typ)
3210           and then not Is_Tagged_Type (Typ)
3211         then
3212            Gen_Bodies  := New_Elmt_List;
3213            Gen_Formals :=
3214              Get_Generic_Formal_Types_In_Hierarchy
3215                (Typ                => Typ,
3216                 Examine_Components => True);
3217
3218            --  Climb scopes collecting generic bodies
3219
3220            Scop := Scope (Typ);
3221            while Present (Scop) and then Scop /= Standard_Standard loop
3222
3223               --  Generic package body
3224
3225               if Ekind (Scop) = E_Generic_Package
3226                 and then In_Package_Body (Scop)
3227               then
3228                  Append_Elmt (Scop, Gen_Bodies);
3229
3230               --  Generic subprogram body
3231
3232               elsif Is_Generic_Subprogram (Scop) then
3233                  Append_Elmt (Scop, Gen_Bodies);
3234               end if;
3235
3236               Scop := Scope (Scop);
3237            end loop;
3238
3239            --  Warn about the improper use of Aspect_No_Parts on a type
3240            --  declaration deriving from or that has a component of a generic
3241            --  formal type within the formal type's corresponding generic
3242            --  body by moving through all formal types in Typ's hierarchy and
3243            --  checking if they are formals in any of the enclosing generic
3244            --  bodies.
3245
3246            --  However, a special exception gets made for formal types which
3247            --  derive from a type which has Aspect_No_Parts True.
3248
3249            --  For example:
3250
3251            --  generic
3252            --     type Form is private;
3253            --  package G is
3254            --     type Type_A is new Form with No_Controlled_Parts; --  OK
3255            --  end;
3256            --
3257            --  package body G is
3258            --     type Type_B is new Form with No_Controlled_Parts; --  ERROR
3259            --  end;
3260
3261            --  generic
3262            --     type Form is private;
3263            --  package G is
3264            --     type Type_A is record C : Form; end record
3265            --       with No_Controlled_Parts;                       --  OK
3266            --  end;
3267            --
3268            --  package body G is
3269            --     type Type_B is record C : Form; end record
3270            --       with No_Controlled_Parts;                       --  ERROR
3271            --  end;
3272
3273            --  type Root is tagged null record with No_Controlled_Parts;
3274            --
3275            --  generic
3276            --     type Form is new Root with private;
3277            --  package G is
3278            --     type Type_A is record C : Form; end record
3279            --       with No_Controlled_Parts;                       --  OK
3280            --  end;
3281            --
3282            --  package body G is
3283            --     type Type_B is record C : Form; end record
3284            --       with No_Controlled_Parts;                       --  OK
3285            --  end;
3286
3287            Curr_Formal_Elmt := First_Elmt (Gen_Formals);
3288            while Present (Curr_Formal_Elmt) loop
3289
3290               Curr_Body_Elmt := First_Elmt (Gen_Bodies);
3291               while Present (Curr_Body_Elmt) loop
3292
3293                  --  Obtain types in the formal type's hierarchy which have
3294                  --  the aspect specified.
3295
3296                  Types_With_Aspect :=
3297                    Get_Types_With_Aspect_In_Hierarchy
3298                      (Node (Curr_Formal_Elmt));
3299
3300                  --  We found a type declaration in a generic body where both
3301                  --  Aspect_No_Parts is true and one of its ancestors is a
3302                  --  generic formal type.
3303
3304                  if Scope (Node (Curr_Formal_Elmt)) =
3305                       Node (Curr_Body_Elmt)
3306
3307                    --  Check that no ancestors of the formal type have
3308                    --  Aspect_No_Parts True before issuing the error.
3309
3310                    and then (Is_Empty_Elmt_List (Types_With_Aspect)
3311                               or else
3312                                 Get_Aspect_No_Parts_Value
3313                                   (Node (First_Elmt (Types_With_Aspect)))
3314                                  = Standard_False)
3315                  then
3316                     Error_Msg_Node_1 := Typ;
3317                     Error_Msg_Node_2 := Node (Curr_Formal_Elmt);
3318                     Error_Msg
3319                       ("aspect % cannot be applied to "
3320                         & "type & which has an ancestor or component of "
3321                         & "formal type & within the formal type's "
3322                         & "corresponding generic body", Sloc (Typ));
3323                  end if;
3324
3325                  Next_Elmt (Curr_Body_Elmt);
3326               end loop;
3327
3328               Next_Elmt (Curr_Formal_Elmt);
3329            end loop;
3330         end if;
3331      end Check_No_Parts_Violations;
3332
3333      ---------------------------------
3334      -- Check_Suspicious_Convention --
3335      ---------------------------------
3336
3337      procedure Check_Suspicious_Convention (Rec_Type : Entity_Id) is
3338      begin
3339         if Has_Discriminants (Rec_Type)
3340           and then Is_Base_Type (Rec_Type)
3341           and then not Is_Unchecked_Union (Rec_Type)
3342           and then (Convention (Rec_Type) = Convention_C
3343                       or else
3344                     Convention (Rec_Type) = Convention_CPP)
3345           and then Comes_From_Source (Rec_Type)
3346           and then not In_Instance
3347           and then not Has_Warnings_Off (Rec_Type)
3348         then
3349            declare
3350               Cprag : constant Node_Id :=
3351                         Get_Rep_Pragma (Rec_Type, Name_Convention);
3352               A2    : Node_Id;
3353
3354            begin
3355               if Present (Cprag) then
3356                  A2 := Next (First (Pragma_Argument_Associations (Cprag)));
3357
3358                  if Convention (Rec_Type) = Convention_C then
3359                     Error_Msg_N
3360                       ("?x?discriminated record has no direct equivalent in "
3361                        & "C", A2);
3362                  else
3363                     Error_Msg_N
3364                       ("?x?discriminated record has no direct equivalent in "
3365                        & "C++", A2);
3366                  end if;
3367
3368                  Error_Msg_NE
3369                    ("\?x?use of convention for type& is dubious",
3370                     A2, Rec_Type);
3371               end if;
3372            end;
3373         end if;
3374      end Check_Suspicious_Convention;
3375
3376      ------------------------------
3377      -- Check_Suspicious_Modulus --
3378      ------------------------------
3379
3380      procedure Check_Suspicious_Modulus (Utype : Entity_Id) is
3381         Decl : constant Node_Id := Declaration_Node (Underlying_Type (Utype));
3382
3383      begin
3384         if not Warn_On_Suspicious_Modulus_Value then
3385            return;
3386         end if;
3387
3388         if Nkind (Decl) = N_Full_Type_Declaration then
3389            declare
3390               Tdef : constant Node_Id := Type_Definition (Decl);
3391
3392            begin
3393               if Nkind (Tdef) = N_Modular_Type_Definition then
3394                  declare
3395                     Modulus : constant Node_Id :=
3396                                 Original_Node (Expression (Tdef));
3397
3398                  begin
3399                     if Nkind (Modulus) = N_Integer_Literal then
3400                        declare
3401                           Modv : constant Uint := Intval (Modulus);
3402                           Sizv : constant Uint := RM_Size (Utype);
3403
3404                        begin
3405                           --  First case, modulus and size are the same. This
3406                           --  happens if you have something like mod 32, with
3407                           --  an explicit size of 32, this is for sure a case
3408                           --  where the warning is given, since it is seems
3409                           --  very unlikely that someone would want e.g. a
3410                           --  five bit type stored in 32 bits. It is much
3411                           --  more likely they wanted a 32-bit type.
3412
3413                           if Modv = Sizv then
3414                              null;
3415
3416                           --  Second case, the modulus is 32 or 64 and no
3417                           --  size clause is present. This is a less clear
3418                           --  case for giving the warning, but in the case
3419                           --  of 32/64 (5-bit or 6-bit types) these seem rare
3420                           --  enough that it is a likely error (and in any
3421                           --  case using 2**5 or 2**6 in these cases seems
3422                           --  clearer. We don't include 8 or 16 here, simply
3423                           --  because in practice 3-bit and 4-bit types are
3424                           --  more common and too many false positives if
3425                           --  we warn in these cases.
3426
3427                           elsif not Has_Size_Clause (Utype)
3428                             and then (Modv = Uint_32 or else Modv = Uint_64)
3429                           then
3430                              null;
3431
3432                           --  No warning needed
3433
3434                           else
3435                              return;
3436                           end if;
3437
3438                           --  If we fall through, give warning
3439
3440                           Error_Msg_Uint_1 := Modv;
3441                           Error_Msg_N
3442                             ("?.m?2 '*'*^' may have been intended here",
3443                              Modulus);
3444                        end;
3445                     end if;
3446                  end;
3447               end if;
3448            end;
3449         end if;
3450      end Check_Suspicious_Modulus;
3451
3452      -----------------------
3453      -- Freeze_Array_Type --
3454      -----------------------
3455
3456      procedure Freeze_Array_Type (Arr : Entity_Id) is
3457         FS     : constant Entity_Id := First_Subtype (Arr);
3458         Ctyp   : constant Entity_Id := Component_Type (Arr);
3459         Clause : Entity_Id;
3460
3461         Non_Standard_Enum : Boolean := False;
3462         --  Set true if any of the index types is an enumeration type with a
3463         --  non-standard representation.
3464
3465      begin
3466         Freeze_And_Append (Ctyp, N, Result);
3467
3468         Indx := First_Index (Arr);
3469         while Present (Indx) loop
3470            Freeze_And_Append (Etype (Indx), N, Result);
3471
3472            if Is_Enumeration_Type (Etype (Indx))
3473              and then Has_Non_Standard_Rep (Etype (Indx))
3474            then
3475               Non_Standard_Enum := True;
3476            end if;
3477
3478            Next_Index (Indx);
3479         end loop;
3480
3481         --  Processing that is done only for base types
3482
3483         if Ekind (Arr) = E_Array_Type then
3484
3485            --  Deal with default setting of reverse storage order
3486
3487            Set_SSO_From_Default (Arr);
3488
3489            --  Propagate flags for component type
3490
3491            if Is_Controlled (Ctyp)
3492              or else Has_Controlled_Component (Ctyp)
3493            then
3494               Set_Has_Controlled_Component (Arr);
3495            end if;
3496
3497            if Has_Unchecked_Union (Ctyp) then
3498               Set_Has_Unchecked_Union (Arr);
3499            end if;
3500
3501            --  The array type requires its own invariant procedure in order to
3502            --  verify the component invariant over all elements. In GNATprove
3503            --  mode, the component invariants are checked by other means. They
3504            --  should not be added to the array type invariant procedure, so
3505            --  that the procedure can be used to check the array type
3506            --  invariants if any.
3507
3508            if Has_Invariants (Ctyp)
3509              and then not GNATprove_Mode
3510            then
3511               Set_Has_Own_Invariants (Arr);
3512            end if;
3513
3514            --  Warn for pragma Pack overriding foreign convention
3515
3516            if Has_Foreign_Convention (Ctyp)
3517              and then Has_Pragma_Pack (Arr)
3518            then
3519               declare
3520                  CN : constant Name_Id :=
3521                         Get_Convention_Name (Convention (Ctyp));
3522                  PP : constant Node_Id :=
3523                         Get_Pragma (First_Subtype (Arr), Pragma_Pack);
3524               begin
3525                  if Present (PP) then
3526                     Error_Msg_Name_1 := CN;
3527                     Error_Msg_Sloc := Sloc (Arr);
3528                     Error_Msg_N
3529                       ("pragma Pack affects convention % components #??", PP);
3530                     Error_Msg_Name_1 := CN;
3531                     Error_Msg_N
3532                       ("\array components may not have % compatible "
3533                        & "representation??", PP);
3534                  end if;
3535               end;
3536            end if;
3537
3538            --  Check for Aliased or Atomic_Components or Full Access with
3539            --  unsuitable packing or explicit component size clause given.
3540
3541            if (Has_Aliased_Components (Arr)
3542                 or else Has_Atomic_Components (Arr)
3543                 or else Is_Full_Access (Ctyp))
3544              and then
3545                (Has_Component_Size_Clause (Arr) or else Is_Packed (Arr))
3546            then
3547               Alias_Atomic_Check : declare
3548
3549                  procedure Complain_CS (T : String);
3550                  --  Outputs error messages for incorrect CS clause or pragma
3551                  --  Pack for aliased or full access components (T is either
3552                  --  "aliased" or "atomic" or "volatile full access");
3553
3554                  -----------------
3555                  -- Complain_CS --
3556                  -----------------
3557
3558                  procedure Complain_CS (T : String) is
3559                  begin
3560                     if Has_Component_Size_Clause (Arr) then
3561                        Clause :=
3562                          Get_Attribute_Definition_Clause
3563                            (FS, Attribute_Component_Size);
3564
3565                        Error_Msg_N
3566                          ("incorrect component size for "
3567                           & T & " components", Clause);
3568                        Error_Msg_Uint_1 := Esize (Ctyp);
3569                        Error_Msg_N
3570                          ("\only allowed value is^", Clause);
3571
3572                     else
3573                        Error_Msg_N
3574                          ("?cannot pack " & T & " components (RM 13.2(7))",
3575                           Get_Rep_Pragma (FS, Name_Pack));
3576                        Set_Is_Packed (Arr, False);
3577                     end if;
3578                  end Complain_CS;
3579
3580                  --  Start of processing for Alias_Atomic_Check
3581
3582               begin
3583                  --  If object size of component type isn't known, we cannot
3584                  --  be sure so we defer to the back end.
3585
3586                  if not Known_Static_Esize (Ctyp) then
3587                     null;
3588
3589                  --  Case where component size has no effect. First check for
3590                  --  object size of component type multiple of the storage
3591                  --  unit size.
3592
3593                  elsif Esize (Ctyp) mod System_Storage_Unit = 0
3594
3595                    --  OK in both packing case and component size case if RM
3596                    --  size is known and static and same as the object size.
3597
3598                    and then
3599                      ((Known_Static_RM_Size (Ctyp)
3600                         and then Esize (Ctyp) = RM_Size (Ctyp))
3601
3602                        --  Or if we have an explicit component size clause and
3603                        --  the component size and object size are equal.
3604
3605                        or else
3606                          (Has_Component_Size_Clause (Arr)
3607                            and then Component_Size (Arr) = Esize (Ctyp)))
3608                  then
3609                     null;
3610
3611                  elsif Has_Aliased_Components (Arr) then
3612                     Complain_CS ("aliased");
3613
3614                  elsif Has_Atomic_Components (Arr)
3615                    or else Is_Atomic (Ctyp)
3616                  then
3617                     Complain_CS ("atomic");
3618
3619                  elsif Is_Volatile_Full_Access (Ctyp) then
3620                     Complain_CS ("volatile full access");
3621                  end if;
3622               end Alias_Atomic_Check;
3623            end if;
3624
3625            --  Check for Independent_Components/Independent with unsuitable
3626            --  packing or explicit component size clause given.
3627
3628            if (Has_Independent_Components (Arr) or else Is_Independent (Ctyp))
3629                  and then
3630               (Has_Component_Size_Clause  (Arr) or else Is_Packed (Arr))
3631            then
3632               begin
3633                  --  If object size of component type isn't known, we cannot
3634                  --  be sure so we defer to the back end.
3635
3636                  if not Known_Static_Esize (Ctyp) then
3637                     null;
3638
3639                  --  Case where component size has no effect. First check for
3640                  --  object size of component type multiple of the storage
3641                  --  unit size.
3642
3643                  elsif Esize (Ctyp) mod System_Storage_Unit = 0
3644
3645                    --  OK in both packing case and component size case if RM
3646                    --  size is known and multiple of the storage unit size.
3647
3648                    and then
3649                      ((Known_Static_RM_Size (Ctyp)
3650                         and then RM_Size (Ctyp) mod System_Storage_Unit = 0)
3651
3652                        --  Or if we have an explicit component size clause and
3653                        --  the component size is larger than the object size.
3654
3655                        or else
3656                          (Has_Component_Size_Clause (Arr)
3657                            and then Component_Size (Arr) >= Esize (Ctyp)))
3658                  then
3659                     null;
3660
3661                  else
3662                     if Has_Component_Size_Clause (Arr) then
3663                        Clause :=
3664                          Get_Attribute_Definition_Clause
3665                            (FS, Attribute_Component_Size);
3666
3667                        Error_Msg_N
3668                          ("incorrect component size for "
3669                           & "independent components", Clause);
3670                        Error_Msg_Uint_1 := Esize (Ctyp);
3671                        Error_Msg_N
3672                          ("\minimum allowed is^", Clause);
3673
3674                     else
3675                        Error_Msg_N
3676                          ("?cannot pack independent components (RM 13.2(7))",
3677                           Get_Rep_Pragma (FS, Name_Pack));
3678                        Set_Is_Packed (Arr, False);
3679                     end if;
3680                  end if;
3681               end;
3682            end if;
3683
3684            --  If packing was requested or if the component size was
3685            --  set explicitly, then see if bit packing is required. This
3686            --  processing is only done for base types, since all of the
3687            --  representation aspects involved are type-related.
3688
3689            --  This is not just an optimization, if we start processing the
3690            --  subtypes, they interfere with the settings on the base type
3691            --  (this is because Is_Packed has a slightly different meaning
3692            --  before and after freezing).
3693
3694            declare
3695               Csiz : Uint;
3696               Esiz : Uint;
3697
3698            begin
3699               if Is_Packed (Arr)
3700                 and then Known_Static_RM_Size (Ctyp)
3701                 and then not Has_Component_Size_Clause (Arr)
3702               then
3703                  Csiz := UI_Max (RM_Size (Ctyp), 1);
3704
3705               elsif Known_Component_Size (Arr) then
3706                  Csiz := Component_Size (Arr);
3707
3708               elsif not Known_Static_Esize (Ctyp) then
3709                  Csiz := Uint_0;
3710
3711               else
3712                  Esiz := Esize (Ctyp);
3713
3714                  --  We can set the component size if it is less than 16,
3715                  --  rounding it up to the next storage unit size.
3716
3717                  if Esiz <= 8 then
3718                     Csiz := Uint_8;
3719                  elsif Esiz <= 16 then
3720                     Csiz := Uint_16;
3721                  else
3722                     Csiz := Uint_0;
3723                  end if;
3724
3725                  --  Set component size up to match alignment if it would
3726                  --  otherwise be less than the alignment. This deals with
3727                  --  cases of types whose alignment exceeds their size (the
3728                  --  padded type cases).
3729
3730                  if Csiz /= 0 and then Known_Alignment (Ctyp) then
3731                     declare
3732                        A : constant Uint := Alignment_In_Bits (Ctyp);
3733                     begin
3734                        if Csiz < A then
3735                           Csiz := A;
3736                        end if;
3737                     end;
3738                  end if;
3739               end if;
3740
3741               --  Case of component size that may result in bit packing
3742
3743               if 1 <= Csiz and then Csiz <= System_Max_Integer_Size then
3744                  declare
3745                     Ent         : constant Entity_Id :=
3746                                     First_Subtype (Arr);
3747                     Pack_Pragma : constant Node_Id :=
3748                                     Get_Rep_Pragma (Ent, Name_Pack);
3749                     Comp_Size_C : constant Node_Id :=
3750                                     Get_Attribute_Definition_Clause
3751                                       (Ent, Attribute_Component_Size);
3752
3753                  begin
3754                     --  Warn if we have pack and component size so that the
3755                     --  pack is ignored.
3756
3757                     --  Note: here we must check for the presence of a
3758                     --  component size before checking for a Pack pragma to
3759                     --  deal with the case where the array type is a derived
3760                     --  type whose parent is currently private.
3761
3762                     if Present (Comp_Size_C)
3763                       and then Has_Pragma_Pack (Ent)
3764                       and then Warn_On_Redundant_Constructs
3765                     then
3766                        Error_Msg_Sloc := Sloc (Comp_Size_C);
3767                        Error_Msg_NE
3768                          ("?r?pragma Pack for& ignored!", Pack_Pragma, Ent);
3769                        Error_Msg_N
3770                          ("\?r?explicit component size given#!", Pack_Pragma);
3771                        Set_Is_Packed (Base_Type (Ent), False);
3772                        Set_Is_Bit_Packed_Array (Base_Type (Ent), False);
3773                     end if;
3774
3775                     --  Set component size if not already set by a component
3776                     --  size clause.
3777
3778                     if not Present (Comp_Size_C) then
3779                        Set_Component_Size (Arr, Csiz);
3780                     end if;
3781
3782                     --  Check for base type of 8, 16, 32 bits, where an
3783                     --  unsigned subtype has a length one less than the
3784                     --  base type (e.g. Natural subtype of Integer).
3785
3786                     --  In such cases, if a component size was not set
3787                     --  explicitly, then generate a warning.
3788
3789                     if Has_Pragma_Pack (Arr)
3790                       and then not Present (Comp_Size_C)
3791                       and then (Csiz = 7 or else Csiz = 15 or else Csiz = 31)
3792                       and then Known_Esize (Base_Type (Ctyp))
3793                       and then Esize (Base_Type (Ctyp)) = Csiz + 1
3794                     then
3795                        Error_Msg_Uint_1 := Csiz;
3796
3797                        if Present (Pack_Pragma) then
3798                           Error_Msg_N
3799                             ("??pragma Pack causes component size to be ^!",
3800                              Pack_Pragma);
3801                           Error_Msg_N
3802                             ("\??use Component_Size to set desired value!",
3803                              Pack_Pragma);
3804                        end if;
3805                     end if;
3806
3807                     --  Bit packing is never needed for 8, 16, 32, 64 or 128
3808
3809                     if Addressable (Csiz) then
3810
3811                        --  If the Esize of the component is known and equal to
3812                        --  the component size then even packing is not needed.
3813
3814                        if Known_Static_Esize (Ctyp)
3815                          and then Esize (Ctyp) = Csiz
3816                        then
3817                           --  Here the array was requested to be packed, but
3818                           --  the packing request had no effect whatsoever,
3819                           --  so flag Is_Packed is reset.
3820
3821                           --  Note: semantically this means that we lose track
3822                           --  of the fact that a derived type inherited pragma
3823                           --  Pack that was non-effective, but that is fine.
3824
3825                           --  We regard a Pack pragma as a request to set a
3826                           --  representation characteristic, and this request
3827                           --  may be ignored.
3828
3829                           Set_Is_Packed            (Base_Type (Arr), False);
3830                           Set_Has_Non_Standard_Rep (Base_Type (Arr), False);
3831                        else
3832                           Set_Is_Packed            (Base_Type (Arr), True);
3833                           Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
3834                        end if;
3835
3836                        Set_Is_Bit_Packed_Array (Base_Type (Arr), False);
3837
3838                     --  Bit packing is not needed for multiples of the storage
3839                     --  unit if the type is composite because the back end can
3840                     --  byte pack composite types efficiently. That's not true
3841                     --  for discrete types because every read would generate a
3842                     --  lot of instructions, so we keep using the manipulation
3843                     --  routines of the runtime for them.
3844
3845                     elsif Csiz mod System_Storage_Unit = 0
3846                       and then Is_Composite_Type (Ctyp)
3847                     then
3848                        Set_Is_Packed            (Base_Type (Arr), True);
3849                        Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
3850                        Set_Is_Bit_Packed_Array  (Base_Type (Arr), False);
3851
3852                     --  In all other cases, bit packing is needed
3853
3854                     else
3855                        Set_Is_Packed            (Base_Type (Arr), True);
3856                        Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
3857                        Set_Is_Bit_Packed_Array  (Base_Type (Arr), True);
3858                     end if;
3859                  end;
3860               end if;
3861            end;
3862
3863            --  Warn for case of atomic type
3864
3865            Clause := Get_Rep_Pragma (FS, Name_Atomic);
3866
3867            if Present (Clause)
3868              and then not Addressable (Component_Size (FS))
3869            then
3870               Error_Msg_NE
3871                 ("non-atomic components of type& may not be "
3872                  & "accessible by separate tasks??", Clause, Arr);
3873
3874               if Has_Component_Size_Clause (Arr) then
3875                  Error_Msg_Sloc := Sloc (Get_Attribute_Definition_Clause
3876                                           (FS, Attribute_Component_Size));
3877                  Error_Msg_N ("\because of component size clause#??", Clause);
3878
3879               elsif Has_Pragma_Pack (Arr) then
3880                  Error_Msg_Sloc := Sloc (Get_Rep_Pragma (FS, Name_Pack));
3881                  Error_Msg_N ("\because of pragma Pack#??", Clause);
3882               end if;
3883            end if;
3884
3885            --  Check for scalar storage order
3886
3887            declare
3888               Dummy : Boolean;
3889            begin
3890               Check_Component_Storage_Order
3891                 (Encl_Type        => Arr,
3892                  Comp             => Empty,
3893                  ADC              => Get_Attribute_Definition_Clause
3894                                        (First_Subtype (Arr),
3895                                         Attribute_Scalar_Storage_Order),
3896                  Comp_ADC_Present => Dummy);
3897            end;
3898
3899         --  Processing that is done only for subtypes
3900
3901         else
3902            --  Acquire alignment from base type. Known_Alignment of the base
3903            --  type is False for Wide_String, for example.
3904
3905            if not Known_Alignment (Arr)
3906              and then Known_Alignment (Base_Type (Arr))
3907            then
3908               Set_Alignment (Arr, Alignment (Base_Type (Arr)));
3909               Adjust_Esize_Alignment (Arr);
3910            end if;
3911         end if;
3912
3913         --  Specific checks for bit-packed arrays
3914
3915         if Is_Bit_Packed_Array (Arr) then
3916
3917            --  Check number of elements for bit-packed arrays that come from
3918            --  source and have compile time known ranges. The bit-packed
3919            --  arrays circuitry does not support arrays with more than
3920            --  Integer'Last + 1 elements, and when this restriction is
3921            --  violated, causes incorrect data access.
3922
3923            --  For the case where this is not compile time known, a run-time
3924            --  check should be generated???
3925
3926            if Comes_From_Source (Arr) and then Is_Constrained (Arr) then
3927               declare
3928                  Elmts : Uint;
3929                  Index : Node_Id;
3930                  Ilen  : Node_Id;
3931                  Ityp  : Entity_Id;
3932
3933               begin
3934                  Elmts := Uint_1;
3935                  Index := First_Index (Arr);
3936                  while Present (Index) loop
3937                     Ityp := Etype (Index);
3938
3939                     --  Never generate an error if any index is of a generic
3940                     --  type. We will check this in instances.
3941
3942                     if Is_Generic_Type (Ityp) then
3943                        Elmts := Uint_0;
3944                        exit;
3945                     end if;
3946
3947                     Ilen :=
3948                       Make_Attribute_Reference (Loc,
3949                         Prefix         => New_Occurrence_Of (Ityp, Loc),
3950                         Attribute_Name => Name_Range_Length);
3951                     Analyze_And_Resolve (Ilen);
3952
3953                     --  No attempt is made to check number of elements if not
3954                     --  compile time known.
3955
3956                     if Nkind (Ilen) /= N_Integer_Literal then
3957                        Elmts := Uint_0;
3958                        exit;
3959                     end if;
3960
3961                     Elmts := Elmts * Intval (Ilen);
3962                     Next_Index (Index);
3963                  end loop;
3964
3965                  if Elmts > Intval (High_Bound
3966                                       (Scalar_Range (Standard_Integer))) + 1
3967                  then
3968                     Error_Msg_N
3969                       ("bit packed array type may not have "
3970                        & "more than Integer''Last+1 elements", Arr);
3971                  end if;
3972               end;
3973            end if;
3974
3975            --  Check size
3976
3977            if Known_RM_Size (Arr) then
3978               declare
3979                  SizC    : constant Node_Id := Size_Clause (Arr);
3980                  Discard : Boolean;
3981
3982               begin
3983                  --  It is not clear if it is possible to have no size clause
3984                  --  at this stage, but it is not worth worrying about. Post
3985                  --  error on the entity name in the size clause if present,
3986                  --  else on the type entity itself.
3987
3988                  if Present (SizC) then
3989                     Check_Size (Name (SizC), Arr, RM_Size (Arr), Discard);
3990                  else
3991                     Check_Size (Arr, Arr, RM_Size (Arr), Discard);
3992                  end if;
3993               end;
3994            end if;
3995         end if;
3996
3997         --  If any of the index types was an enumeration type with a non-
3998         --  standard rep clause, then we indicate that the array type is
3999         --  always packed (even if it is not bit-packed).
4000
4001         if Non_Standard_Enum then
4002            Set_Has_Non_Standard_Rep (Base_Type (Arr));
4003            Set_Is_Packed            (Base_Type (Arr));
4004         end if;
4005
4006         Set_Component_Alignment_If_Not_Set (Arr);
4007
4008         --  If the array is packed and bit-packed or packed to eliminate holes
4009         --  in the non-contiguous enumeration index types, we must create the
4010         --  packed array type to be used to actually implement the type. This
4011         --  is only needed for real array types (not for string literal types,
4012         --  since they are present only for the front end).
4013
4014         if Is_Packed (Arr)
4015           and then (Is_Bit_Packed_Array (Arr) or else Non_Standard_Enum)
4016           and then Ekind (Arr) /= E_String_Literal_Subtype
4017         then
4018            Create_Packed_Array_Impl_Type (Arr);
4019            Freeze_And_Append (Packed_Array_Impl_Type (Arr), N, Result);
4020
4021            --  Make sure that we have the necessary routines to implement the
4022            --  packing, and complain now if not. Note that we only test this
4023            --  for constrained array types.
4024
4025            if Is_Constrained (Arr)
4026              and then Is_Bit_Packed_Array (Arr)
4027              and then Present (Packed_Array_Impl_Type (Arr))
4028              and then Is_Array_Type (Packed_Array_Impl_Type (Arr))
4029            then
4030               declare
4031                  CS : constant Uint  := Component_Size (Arr);
4032                  RE : constant RE_Id := Get_Id (UI_To_Int (CS));
4033
4034               begin
4035                  if RE /= RE_Null
4036                    and then not RTE_Available (RE)
4037                  then
4038                     Error_Msg_CRT
4039                       ("packing of " & UI_Image (CS) & "-bit components",
4040                        First_Subtype (Etype (Arr)));
4041
4042                     --  Cancel the packing
4043
4044                     Set_Is_Packed (Base_Type (Arr), False);
4045                     Set_Is_Bit_Packed_Array (Base_Type (Arr), False);
4046                     Set_Packed_Array_Impl_Type (Arr, Empty);
4047                     goto Skip_Packed;
4048                  end if;
4049               end;
4050            end if;
4051
4052            --  Size information of packed array type is copied to the array
4053            --  type, since this is really the representation. But do not
4054            --  override explicit existing size values. If the ancestor subtype
4055            --  is constrained the Packed_Array_Impl_Type will be inherited
4056            --  from it, but the size may have been provided already, and
4057            --  must not be overridden either.
4058
4059            if not Has_Size_Clause (Arr)
4060              and then
4061                (No (Ancestor_Subtype (Arr))
4062                  or else not Has_Size_Clause (Ancestor_Subtype (Arr)))
4063            then
4064               Copy_Esize (To => Arr, From => Packed_Array_Impl_Type (Arr));
4065               Copy_RM_Size (To => Arr, From => Packed_Array_Impl_Type (Arr));
4066            end if;
4067
4068            if not Has_Alignment_Clause (Arr) then
4069               Copy_Alignment
4070                 (To => Arr, From => Packed_Array_Impl_Type (Arr));
4071            end if;
4072         end if;
4073
4074         <<Skip_Packed>>
4075
4076         --  A Ghost type cannot have a component of protected or task type
4077         --  (SPARK RM 6.9(19)).
4078
4079         if Is_Ghost_Entity (Arr) and then Is_Concurrent_Type (Ctyp) then
4080            Error_Msg_N
4081              ("ghost array type & cannot have concurrent component type",
4082               Arr);
4083         end if;
4084      end Freeze_Array_Type;
4085
4086      -------------------------------
4087      -- Freeze_Object_Declaration --
4088      -------------------------------
4089
4090      procedure Freeze_Object_Declaration (E : Entity_Id) is
4091         procedure Check_Large_Modular_Array (Typ : Entity_Id);
4092         --  Check that the size of array type Typ can be computed without
4093         --  overflow, and generates a Storage_Error otherwise. This is only
4094         --  relevant for array types whose index has System_Max_Integer_Size
4095         --  bits, where wrap-around arithmetic might yield a meaningless value
4096         --  for the length of the array, or its corresponding attribute.
4097
4098         procedure Check_Pragma_Thread_Local_Storage (Var_Id : Entity_Id);
4099         --  Ensure that the initialization state of variable Var_Id subject
4100         --  to pragma Thread_Local_Storage agrees with the semantics of the
4101         --  pragma.
4102
4103         function Has_Default_Initialization
4104           (Obj_Id : Entity_Id) return Boolean;
4105         --  Determine whether object Obj_Id default initialized
4106
4107         -------------------------------
4108         -- Check_Large_Modular_Array --
4109         -------------------------------
4110
4111         procedure Check_Large_Modular_Array (Typ : Entity_Id) is
4112            Obj_Loc : constant Source_Ptr := Sloc (E);
4113            Idx_Typ : Entity_Id;
4114
4115         begin
4116            --  Nothing to do when expansion is disabled because this routine
4117            --  generates a runtime check.
4118
4119            if not Expander_Active then
4120               return;
4121
4122            --  Nothing to do for String literal subtypes because their index
4123            --  cannot be a modular type.
4124
4125            elsif Ekind (Typ) = E_String_Literal_Subtype then
4126               return;
4127
4128            --  Nothing to do for an imported object because the object will
4129            --  be created on the exporting side.
4130
4131            elsif Is_Imported (E) then
4132               return;
4133
4134            --  Nothing to do for unconstrained array types. This case arises
4135            --  when the object declaration is illegal.
4136
4137            elsif not Is_Constrained (Typ) then
4138               return;
4139            end if;
4140
4141            Idx_Typ := Etype (First_Index (Typ));
4142
4143            --  To prevent arithmetic overflow with large values, we raise
4144            --  Storage_Error under the following guard:
4145            --
4146            --    (Arr'Last / 2 - Arr'First / 2) > (2 ** 30)
4147            --
4148            --  This takes care of the boundary case, but it is preferable to
4149            --  use a smaller limit, because even on 64-bit architectures an
4150            --  array of more than 2 ** 30 bytes is likely to raise
4151            --  Storage_Error.
4152
4153            if Is_Modular_Integer_Type (Idx_Typ)
4154              and then RM_Size (Idx_Typ) = RM_Size (Standard_Long_Long_Integer)
4155            then
4156               Insert_Action (Declaration_Node (E),
4157                 Make_Raise_Storage_Error (Obj_Loc,
4158                   Condition =>
4159                     Make_Op_Ge (Obj_Loc,
4160                       Left_Opnd  =>
4161                         Make_Op_Subtract (Obj_Loc,
4162                           Left_Opnd  =>
4163                             Make_Op_Divide (Obj_Loc,
4164                               Left_Opnd  =>
4165                                 Make_Attribute_Reference (Obj_Loc,
4166                                   Prefix         =>
4167                                     New_Occurrence_Of (Typ, Obj_Loc),
4168                                   Attribute_Name => Name_Last),
4169                               Right_Opnd =>
4170                                 Make_Integer_Literal (Obj_Loc, Uint_2)),
4171                           Right_Opnd =>
4172                             Make_Op_Divide (Obj_Loc,
4173                               Left_Opnd =>
4174                                 Make_Attribute_Reference (Obj_Loc,
4175                                   Prefix         =>
4176                                     New_Occurrence_Of (Typ, Obj_Loc),
4177                                   Attribute_Name => Name_First),
4178                               Right_Opnd =>
4179                                 Make_Integer_Literal (Obj_Loc, Uint_2))),
4180                       Right_Opnd =>
4181                         Make_Integer_Literal (Obj_Loc, (Uint_2 ** 30))),
4182                   Reason    => SE_Object_Too_Large));
4183            end if;
4184         end Check_Large_Modular_Array;
4185
4186         ---------------------------------------
4187         -- Check_Pragma_Thread_Local_Storage --
4188         ---------------------------------------
4189
4190         procedure Check_Pragma_Thread_Local_Storage (Var_Id : Entity_Id) is
4191            function Has_Incompatible_Initialization
4192              (Var_Decl : Node_Id) return Boolean;
4193            --  Determine whether variable Var_Id with declaration Var_Decl is
4194            --  initialized with a value that violates the semantics of pragma
4195            --  Thread_Local_Storage.
4196
4197            -------------------------------------
4198            -- Has_Incompatible_Initialization --
4199            -------------------------------------
4200
4201            function Has_Incompatible_Initialization
4202              (Var_Decl : Node_Id) return Boolean
4203            is
4204               Init_Expr : constant Node_Id := Expression (Var_Decl);
4205
4206            begin
4207               --  The variable is default-initialized. This directly violates
4208               --  the semantics of the pragma.
4209
4210               if Has_Default_Initialization (Var_Id) then
4211                  return True;
4212
4213               --  The variable has explicit initialization. In this case only
4214               --  a handful of values satisfy the semantics of the pragma.
4215
4216               elsif Has_Init_Expression (Var_Decl)
4217                 and then Present (Init_Expr)
4218               then
4219                  --  "null" is a legal form of initialization
4220
4221                  if Nkind (Init_Expr) = N_Null then
4222                     return False;
4223
4224                  --  A static expression is a legal form of initialization
4225
4226                  elsif Is_Static_Expression (Init_Expr) then
4227                     return False;
4228
4229                  --  A static aggregate is a legal form of initialization
4230
4231                  elsif Nkind (Init_Expr) = N_Aggregate
4232                    and then Compile_Time_Known_Aggregate (Init_Expr)
4233                  then
4234                     return False;
4235
4236                  --  All other initialization expressions violate the semantic
4237                  --  of the pragma.
4238
4239                  else
4240                     return True;
4241                  end if;
4242
4243               --  The variable lacks any kind of initialization, which agrees
4244               --  with the semantics of the pragma.
4245
4246               else
4247                  return False;
4248               end if;
4249            end Has_Incompatible_Initialization;
4250
4251            --  Local declarations
4252
4253            Var_Decl : constant Node_Id := Declaration_Node (Var_Id);
4254
4255         --  Start of processing for Check_Pragma_Thread_Local_Storage
4256
4257         begin
4258            --  A variable whose initialization is suppressed lacks any kind of
4259            --  initialization.
4260
4261            if Suppress_Initialization (Var_Id) then
4262               null;
4263
4264            --  The variable has default initialization, or is explicitly
4265            --  initialized to a value other than null, static expression,
4266            --  or a static aggregate.
4267
4268            elsif Has_Incompatible_Initialization (Var_Decl) then
4269               Error_Msg_NE
4270                 ("Thread_Local_Storage variable& is improperly initialized",
4271                  Var_Decl, Var_Id);
4272               Error_Msg_NE
4273                 ("\only allowed initialization is explicit NULL, static "
4274                  & "expression or static aggregate", Var_Decl, Var_Id);
4275            end if;
4276         end Check_Pragma_Thread_Local_Storage;
4277
4278         --------------------------------
4279         -- Has_Default_Initialization --
4280         --------------------------------
4281
4282         function Has_Default_Initialization
4283           (Obj_Id : Entity_Id) return Boolean
4284         is
4285            Obj_Decl : constant Node_Id   := Declaration_Node (Obj_Id);
4286            Obj_Typ  : constant Entity_Id := Etype (Obj_Id);
4287
4288         begin
4289            return
4290              Comes_From_Source (Obj_Id)
4291                and then not Is_Imported (Obj_Id)
4292                and then not Has_Init_Expression (Obj_Decl)
4293                and then
4294                  ((Has_Non_Null_Base_Init_Proc (Obj_Typ)
4295                     and then not No_Initialization (Obj_Decl)
4296                     and then not Initialization_Suppressed (Obj_Typ))
4297                   or else
4298                     (Needs_Simple_Initialization (Obj_Typ)
4299                       and then not Is_Internal (Obj_Id)));
4300         end Has_Default_Initialization;
4301
4302         --  Local variables
4303
4304         Typ : constant Entity_Id := Etype (E);
4305         Def : Node_Id;
4306
4307      --  Start of processing for Freeze_Object_Declaration
4308
4309      begin
4310         --  Abstract type allowed only for C++ imported variables or constants
4311
4312         --  Note: we inhibit this check for objects that do not come from
4313         --  source because there is at least one case (the expansion of
4314         --  x'Class'Input where x is abstract) where we legitimately
4315         --  generate an abstract object.
4316
4317         if Is_Abstract_Type (Typ)
4318           and then Comes_From_Source (Parent (E))
4319           and then not (Is_Imported (E) and then Is_CPP_Class (Typ))
4320         then
4321            Def := Object_Definition (Parent (E));
4322
4323            Error_Msg_N ("type of object cannot be abstract", Def);
4324
4325            if Is_CPP_Class (Etype (E)) then
4326               Error_Msg_NE ("\} may need a cpp_constructor", Def, Typ);
4327
4328            elsif Present (Expression (Parent (E))) then
4329               Error_Msg_N --  CODEFIX
4330                 ("\maybe a class-wide type was meant", Def);
4331            end if;
4332         end if;
4333
4334         --  For object created by object declaration, perform required
4335         --  categorization (preelaborate and pure) checks. Defer these
4336         --  checks to freeze time since pragma Import inhibits default
4337         --  initialization and thus pragma Import affects these checks.
4338
4339         Validate_Object_Declaration (Declaration_Node (E));
4340
4341         --  If there is an address clause, check that it is valid and if need
4342         --  be move initialization to the freeze node.
4343
4344         Check_Address_Clause (E);
4345
4346         --  Similar processing is needed for aspects that may affect object
4347         --  layout, like Address, if there is an initialization expression.
4348         --  We don't do this if there is a pragma Linker_Section, because it
4349         --  would prevent the back end from statically initializing the
4350         --  object; we don't want elaboration code in that case.
4351
4352         if Has_Delayed_Aspects (E)
4353           and then Expander_Active
4354           and then Is_Array_Type (Typ)
4355           and then Present (Expression (Declaration_Node (E)))
4356           and then No (Linker_Section_Pragma (E))
4357         then
4358            declare
4359               Decl : constant Node_Id := Declaration_Node (E);
4360               Lhs  : constant Node_Id := New_Occurrence_Of (E, Loc);
4361
4362            begin
4363               --  Capture initialization value at point of declaration, and
4364               --  make explicit assignment legal, because object may be a
4365               --  constant.
4366
4367               Remove_Side_Effects (Expression (Decl));
4368               Set_Assignment_OK (Lhs);
4369
4370               --  Move initialization to freeze actions
4371
4372               Append_Freeze_Action (E,
4373                 Make_Assignment_Statement (Loc,
4374                   Name       => Lhs,
4375                   Expression => Expression (Decl)));
4376
4377               Set_No_Initialization (Decl);
4378               --  Set_Is_Frozen (E, False);
4379            end;
4380         end if;
4381
4382         --  Reset Is_True_Constant for non-constant aliased object. We
4383         --  consider that the fact that a non-constant object is aliased may
4384         --  indicate that some funny business is going on, e.g. an aliased
4385         --  object is passed by reference to a procedure which captures the
4386         --  address of the object, which is later used to assign a new value,
4387         --  even though the compiler thinks that it is not modified. Such
4388         --  code is highly dubious, but we choose to make it "work" for
4389         --  non-constant aliased objects.
4390
4391         --  Note that we used to do this for all aliased objects, whether or
4392         --  not constant, but this caused anomalies down the line because we
4393         --  ended up with static objects that were not Is_True_Constant. Not
4394         --  resetting Is_True_Constant for (aliased) constant objects ensures
4395         --  that this anomaly never occurs.
4396
4397         --  However, we don't do that for internal entities. We figure that if
4398         --  we deliberately set Is_True_Constant for an internal entity, e.g.
4399         --  a dispatch table entry, then we mean it.
4400
4401         if Ekind (E) /= E_Constant
4402           and then (Is_Aliased (E) or else Is_Aliased (Typ))
4403           and then not Is_Internal_Name (Chars (E))
4404         then
4405            Set_Is_True_Constant (E, False);
4406         end if;
4407
4408         --  If the object needs any kind of default initialization, an error
4409         --  must be issued if No_Default_Initialization applies. The check
4410         --  doesn't apply to imported objects, which are not ever default
4411         --  initialized, and is why the check is deferred until freezing, at
4412         --  which point we know if Import applies. Deferred constants are also
4413         --  exempted from this test because their completion is explicit, or
4414         --  through an import pragma.
4415
4416         if Ekind (E) = E_Constant and then Present (Full_View (E)) then
4417            null;
4418
4419         elsif Has_Default_Initialization (E) then
4420            Check_Restriction
4421              (No_Default_Initialization, Declaration_Node (E));
4422         end if;
4423
4424         --  Ensure that a variable subject to pragma Thread_Local_Storage
4425         --
4426         --    * Lacks default initialization, or
4427         --
4428         --    * The initialization expression is either "null", a static
4429         --      constant, or a compile-time known aggregate.
4430
4431         if Has_Pragma_Thread_Local_Storage (E) then
4432            Check_Pragma_Thread_Local_Storage (E);
4433         end if;
4434
4435         --  For imported objects, set Is_Public unless there is also an
4436         --  address clause, which means that there is no external symbol
4437         --  needed for the Import (Is_Public may still be set for other
4438         --  unrelated reasons). Note that we delayed this processing
4439         --  till freeze time so that we can be sure not to set the flag
4440         --  if there is an address clause. If there is such a clause,
4441         --  then the only purpose of the Import pragma is to suppress
4442         --  implicit initialization.
4443
4444         if Is_Imported (E) and then No (Address_Clause (E)) then
4445            Set_Is_Public (E);
4446         end if;
4447
4448         --  For source objects that are not Imported and are library level, if
4449         --  no linker section pragma was given inherit the appropriate linker
4450         --  section from the corresponding type.
4451
4452         if Comes_From_Source (E)
4453           and then not Is_Imported (E)
4454           and then Is_Library_Level_Entity (E)
4455           and then No (Linker_Section_Pragma (E))
4456         then
4457            Set_Linker_Section_Pragma (E, Linker_Section_Pragma (Typ));
4458         end if;
4459
4460         --  For convention C objects of an enumeration type, warn if the size
4461         --  is not integer size and no explicit size given. Skip warning for
4462         --  Boolean and Character, and assume programmer expects 8-bit sizes
4463         --  for these cases.
4464
4465         if (Convention (E) = Convention_C
4466               or else
4467             Convention (E) = Convention_CPP)
4468           and then Is_Enumeration_Type (Typ)
4469           and then not Is_Character_Type (Typ)
4470           and then not Is_Boolean_Type (Typ)
4471           and then Esize (Typ) < Standard_Integer_Size
4472           and then not Has_Size_Clause (E)
4473         then
4474            Error_Msg_Uint_1 := UI_From_Int (Standard_Integer_Size);
4475            Error_Msg_N
4476              ("??convention C enumeration object has size less than ^", E);
4477            Error_Msg_N ("\??use explicit size clause to set size", E);
4478         end if;
4479
4480         --  Declaring too big an array in disabled ghost code is OK
4481
4482         if Is_Array_Type (Typ) and then not Is_Ignored_Ghost_Entity (E) then
4483            Check_Large_Modular_Array (Typ);
4484         end if;
4485      end Freeze_Object_Declaration;
4486
4487      -----------------------------
4488      -- Freeze_Generic_Entities --
4489      -----------------------------
4490
4491      function Freeze_Generic_Entities (Pack : Entity_Id) return List_Id is
4492         E     : Entity_Id;
4493         F     : Node_Id;
4494         Flist : List_Id;
4495
4496      begin
4497         Flist := New_List;
4498         E := First_Entity (Pack);
4499         while Present (E) loop
4500            if Is_Type (E) and then not Is_Generic_Type (E) then
4501               F := Make_Freeze_Generic_Entity (Sloc (Pack));
4502               Set_Entity (F, E);
4503               Append_To (Flist, F);
4504
4505            elsif Ekind (E) = E_Generic_Package then
4506               Append_List_To (Flist, Freeze_Generic_Entities (E));
4507            end if;
4508
4509            Next_Entity (E);
4510         end loop;
4511
4512         return Flist;
4513      end Freeze_Generic_Entities;
4514
4515      --------------------
4516      -- Freeze_Profile --
4517      --------------------
4518
4519      function Freeze_Profile (E : Entity_Id) return Boolean is
4520         F_Type    : Entity_Id;
4521         R_Type    : Entity_Id;
4522         Warn_Node : Node_Id;
4523
4524      begin
4525         --  Loop through formals
4526
4527         Formal := First_Formal (E);
4528         while Present (Formal) loop
4529            F_Type := Etype (Formal);
4530
4531            --  AI05-0151: incomplete types can appear in a profile. By the
4532            --  time the entity is frozen, the full view must be available,
4533            --  unless it is a limited view.
4534
4535            if Is_Incomplete_Type (F_Type)
4536              and then Present (Full_View (F_Type))
4537              and then not From_Limited_With (F_Type)
4538            then
4539               F_Type := Full_View (F_Type);
4540               Set_Etype (Formal, F_Type);
4541            end if;
4542
4543            if not From_Limited_With (F_Type)
4544              and then Should_Freeze_Type (F_Type, E)
4545            then
4546               Freeze_And_Append (F_Type, N, Result);
4547            end if;
4548
4549            if Is_Private_Type (F_Type)
4550              and then Is_Private_Type (Base_Type (F_Type))
4551              and then No (Full_View (Base_Type (F_Type)))
4552              and then not Is_Generic_Type (F_Type)
4553              and then not Is_Derived_Type (F_Type)
4554            then
4555               --  If the type of a formal is incomplete, subprogram is being
4556               --  frozen prematurely. Within an instance (but not within a
4557               --  wrapper package) this is an artifact of our need to regard
4558               --  the end of an instantiation as a freeze point. Otherwise it
4559               --  is a definite error.
4560
4561               if In_Instance then
4562                  Set_Is_Frozen (E, False);
4563                  Result := No_List;
4564                  return False;
4565
4566               elsif not After_Last_Declaration
4567                 and then not Freezing_Library_Level_Tagged_Type
4568               then
4569                  Error_Msg_NE
4570                    ("type & must be fully defined before this point",
4571                     N,
4572                     F_Type);
4573               end if;
4574            end if;
4575
4576            --  Check suspicious parameter for C function. These tests apply
4577            --  only to exported/imported subprograms.
4578
4579            if Warn_On_Export_Import
4580              and then Comes_From_Source (E)
4581              and then Convention (E) in Convention_C_Family
4582              and then (Is_Imported (E) or else Is_Exported (E))
4583              and then Convention (E) /= Convention (Formal)
4584              and then not Has_Warnings_Off (E)
4585              and then not Has_Warnings_Off (F_Type)
4586              and then not Has_Warnings_Off (Formal)
4587            then
4588               --  Qualify mention of formals with subprogram name
4589
4590               Error_Msg_Qual_Level := 1;
4591
4592               --  Check suspicious use of fat C pointer, but do not emit
4593               --  a warning on an access to subprogram when unnesting is
4594               --  active.
4595
4596               if Is_Access_Type (F_Type)
4597                 and then Known_Esize (F_Type)
4598                 and then Esize (F_Type) > Ttypes.System_Address_Size
4599                 and then (not Unnest_Subprogram_Mode
4600                            or else not Is_Access_Subprogram_Type (F_Type))
4601               then
4602                  Error_Msg_N
4603                    ("?x?type of & does not correspond to C pointer!", Formal);
4604
4605               --  Check suspicious return of boolean
4606
4607               elsif Root_Type (F_Type) = Standard_Boolean
4608                 and then Convention (F_Type) = Convention_Ada
4609                 and then not Has_Warnings_Off (F_Type)
4610                 and then not Has_Size_Clause (F_Type)
4611               then
4612                  Error_Msg_N
4613                    ("& is an 8-bit Ada Boolean?x?", Formal);
4614                  Error_Msg_N
4615                    ("\use appropriate corresponding type in C "
4616                     & "(e.g. char)?x?", Formal);
4617
4618               --  Check suspicious tagged type
4619
4620               elsif (Is_Tagged_Type (F_Type)
4621                       or else
4622                        (Is_Access_Type (F_Type)
4623                          and then Is_Tagged_Type (Designated_Type (F_Type))))
4624                 and then Convention (E) = Convention_C
4625               then
4626                  Error_Msg_N
4627                    ("?x?& involves a tagged type which does not "
4628                     & "correspond to any C type!", Formal);
4629
4630               --  Check wrong convention subprogram pointer
4631
4632               elsif Ekind (F_Type) = E_Access_Subprogram_Type
4633                 and then not Has_Foreign_Convention (F_Type)
4634               then
4635                  Error_Msg_N
4636                    ("?x?subprogram pointer & should "
4637                     & "have foreign convention!", Formal);
4638                  Error_Msg_Sloc := Sloc (F_Type);
4639                  Error_Msg_NE
4640                    ("\?x?add Convention pragma to declaration of &#",
4641                     Formal, F_Type);
4642               end if;
4643
4644               --  Turn off name qualification after message output
4645
4646               Error_Msg_Qual_Level := 0;
4647            end if;
4648
4649            --  Check for unconstrained array in exported foreign convention
4650            --  case.
4651
4652            if Has_Foreign_Convention (E)
4653              and then not Is_Imported (E)
4654              and then Is_Array_Type (F_Type)
4655              and then not Is_Constrained (F_Type)
4656              and then Warn_On_Export_Import
4657            then
4658               Error_Msg_Qual_Level := 1;
4659
4660               --  If this is an inherited operation, place the warning on
4661               --  the derived type declaration, rather than on the original
4662               --  subprogram.
4663
4664               if Nkind (Original_Node (Parent (E))) = N_Full_Type_Declaration
4665               then
4666                  Warn_Node := Parent (E);
4667
4668                  if Formal = First_Formal (E) then
4669                     Error_Msg_NE ("??in inherited operation&", Warn_Node, E);
4670                  end if;
4671               else
4672                  Warn_Node := Formal;
4673               end if;
4674
4675               Error_Msg_NE ("?x?type of argument& is unconstrained array",
4676                  Warn_Node, Formal);
4677               Error_Msg_N ("\?x?foreign caller must pass bounds explicitly",
4678                  Warn_Node);
4679               Error_Msg_Qual_Level := 0;
4680            end if;
4681
4682            if not From_Limited_With (F_Type) then
4683               if Is_Access_Type (F_Type) then
4684                  F_Type := Designated_Type (F_Type);
4685               end if;
4686
4687               --  If the formal is an anonymous_access_to_subprogram
4688               --  freeze the  subprogram type as well, to prevent
4689               --  scope anomalies in gigi, because there is no other
4690               --  clear point at which it could be frozen.
4691
4692               if Is_Itype (Etype (Formal))
4693                 and then Ekind (F_Type) = E_Subprogram_Type
4694               then
4695                  Freeze_And_Append (F_Type, N, Result);
4696               end if;
4697            end if;
4698
4699            Next_Formal (Formal);
4700         end loop;
4701
4702         --  Case of function: similar checks on return type
4703
4704         if Ekind (E) = E_Function then
4705
4706            --  Freeze return type
4707
4708            R_Type := Etype (E);
4709
4710            --  AI05-0151: the return type may have been incomplete at the
4711            --  point of declaration. Replace it with the full view, unless the
4712            --  current type is a limited view. In that case the full view is
4713            --  in a different unit, and gigi finds the non-limited view after
4714            --  the other unit is elaborated.
4715
4716            if Ekind (R_Type) = E_Incomplete_Type
4717              and then Present (Full_View (R_Type))
4718              and then not From_Limited_With (R_Type)
4719            then
4720               R_Type := Full_View (R_Type);
4721               Set_Etype (E, R_Type);
4722            end if;
4723
4724            if Should_Freeze_Type (R_Type, E) then
4725               Freeze_And_Append (R_Type, N, Result);
4726            end if;
4727
4728            --  Check suspicious return type for C function
4729
4730            if Warn_On_Export_Import
4731              and then Comes_From_Source (E)
4732              and then Convention (E) in Convention_C_Family
4733              and then (Is_Imported (E) or else Is_Exported (E))
4734            then
4735               --  Check suspicious return of fat C pointer
4736
4737               if Is_Access_Type (R_Type)
4738                 and then Known_Esize (R_Type)
4739                 and then Esize (R_Type) > Ttypes.System_Address_Size
4740                 and then not Has_Warnings_Off (E)
4741                 and then not Has_Warnings_Off (R_Type)
4742               then
4743                  Error_Msg_N
4744                    ("?x?return type of& does not correspond to C pointer!",
4745                     E);
4746
4747               --  Check suspicious return of boolean
4748
4749               elsif Root_Type (R_Type) = Standard_Boolean
4750                 and then Convention (R_Type) = Convention_Ada
4751                 and then not Has_Warnings_Off (E)
4752                 and then not Has_Warnings_Off (R_Type)
4753                 and then not Has_Size_Clause (R_Type)
4754               then
4755                  declare
4756                     N : constant Node_Id :=
4757                           Result_Definition (Declaration_Node (E));
4758                  begin
4759                     Error_Msg_NE
4760                       ("return type of & is an 8-bit Ada Boolean?x?", N, E);
4761                     Error_Msg_NE
4762                       ("\use appropriate corresponding type in C "
4763                        & "(e.g. char)?x?", N, E);
4764                  end;
4765
4766               --  Check suspicious return tagged type
4767
4768               elsif (Is_Tagged_Type (R_Type)
4769                       or else (Is_Access_Type (R_Type)
4770                                 and then
4771                                   Is_Tagged_Type
4772                                     (Designated_Type (R_Type))))
4773                 and then Convention (E) = Convention_C
4774                 and then not Has_Warnings_Off (E)
4775                 and then not Has_Warnings_Off (R_Type)
4776               then
4777                  Error_Msg_N ("?x?return type of & does not "
4778                     & "correspond to C type!", E);
4779
4780               --  Check return of wrong convention subprogram pointer
4781
4782               elsif Ekind (R_Type) = E_Access_Subprogram_Type
4783                 and then not Has_Foreign_Convention (R_Type)
4784                 and then not Has_Warnings_Off (E)
4785                 and then not Has_Warnings_Off (R_Type)
4786               then
4787                  Error_Msg_N ("?x?& should return a foreign "
4788                     & "convention subprogram pointer", E);
4789                  Error_Msg_Sloc := Sloc (R_Type);
4790                  Error_Msg_NE
4791                    ("\?x?add Convention pragma to declaration of& #",
4792                     E, R_Type);
4793               end if;
4794            end if;
4795
4796            --  Give warning for suspicious return of a result of an
4797            --  unconstrained array type in a foreign convention function.
4798
4799            if Has_Foreign_Convention (E)
4800
4801              --  We are looking for a return of unconstrained array
4802
4803              and then Is_Array_Type (R_Type)
4804              and then not Is_Constrained (R_Type)
4805
4806              --  Exclude imported routines, the warning does not belong on
4807              --  the import, but rather on the routine definition.
4808
4809              and then not Is_Imported (E)
4810
4811              --  Check that general warning is enabled, and that it is not
4812              --  suppressed for this particular case.
4813
4814              and then Warn_On_Export_Import
4815              and then not Has_Warnings_Off (E)
4816              and then not Has_Warnings_Off (R_Type)
4817            then
4818               Error_Msg_N
4819                 ("?x?foreign convention function& should not return "
4820                  & "unconstrained array!", E);
4821            end if;
4822         end if;
4823
4824         --  Check suspicious use of Import in pure unit (cases where the RM
4825         --  allows calls to be omitted).
4826
4827         if Is_Imported (E)
4828
4829           --  It might be suspicious if the compilation unit has the Pure
4830           --  aspect/pragma.
4831
4832           and then Has_Pragma_Pure (Cunit_Entity (Current_Sem_Unit))
4833
4834           --  The RM allows omission of calls only in the case of
4835           --  library-level subprograms (see RM-10.2.1(18)).
4836
4837           and then Is_Library_Level_Entity (E)
4838
4839           --  Ignore internally generated entity. This happens in some cases
4840           --  of subprograms in specs, where we generate an implied body.
4841
4842           and then Comes_From_Source (Import_Pragma (E))
4843
4844           --  Assume run-time knows what it is doing
4845
4846           and then not GNAT_Mode
4847
4848           --  Assume explicit Pure_Function means import is pure
4849
4850           and then not Has_Pragma_Pure_Function (E)
4851
4852           --  Don't need warning in relaxed semantics mode
4853
4854           and then not Relaxed_RM_Semantics
4855
4856           --  Assume convention Intrinsic is OK, since this is specialized.
4857           --  This deals with the DEC unit current_exception.ads
4858
4859           and then Convention (E) /= Convention_Intrinsic
4860
4861           --  Assume that ASM interface knows what it is doing
4862
4863           and then Convention (E) /= Convention_Assembler
4864         then
4865            Error_Msg_N
4866              ("pragma Import in Pure unit??", Import_Pragma (E));
4867            Error_Msg_NE
4868              ("\calls to & may be omitted (RM 10.2.1(18/3))??",
4869               Import_Pragma (E), E);
4870         end if;
4871
4872         return True;
4873      end Freeze_Profile;
4874
4875      ------------------------
4876      -- Freeze_Record_Type --
4877      ------------------------
4878
4879      procedure Freeze_Record_Type (Rec : Entity_Id) is
4880         ADC  : Node_Id;
4881         Comp : Entity_Id;
4882         IR   : Node_Id;
4883         Prev : Entity_Id;
4884
4885         Junk : Boolean;
4886         pragma Warnings (Off, Junk);
4887
4888         Aliased_Component : Boolean := False;
4889         --  Set True if we find at least one component which is aliased. This
4890         --  is used to prevent Implicit_Packing of the record, since packing
4891         --  cannot modify the size of alignment of an aliased component.
4892
4893         All_Elem_Components : Boolean := True;
4894         --  True if all components are of a type whose underlying type is
4895         --  elementary.
4896
4897         All_Sized_Components : Boolean := True;
4898         --  True if all components have a known RM_Size
4899
4900         All_Storage_Unit_Components : Boolean := True;
4901         --  True if all components have an RM_Size that is a multiple of the
4902         --  storage unit.
4903
4904         Elem_Component_Total_Esize : Uint := Uint_0;
4905         --  Accumulates total Esize values of all elementary components. Used
4906         --  for processing of Implicit_Packing.
4907
4908         Placed_Component : Boolean := False;
4909         --  Set True if we find at least one component with a component
4910         --  clause (used to warn about useless Bit_Order pragmas, and also
4911         --  to detect cases where Implicit_Packing may have an effect).
4912
4913         Sized_Component_Total_RM_Size : Uint := Uint_0;
4914         --  Accumulates total RM_Size values of all sized components. Used
4915         --  for processing of Implicit_Packing.
4916
4917         Sized_Component_Total_Round_RM_Size : Uint := Uint_0;
4918         --  Accumulates total RM_Size values of all sized components, rounded
4919         --  individually to a multiple of the storage unit.
4920
4921         SSO_ADC : Node_Id;
4922         --  Scalar_Storage_Order attribute definition clause for the record
4923
4924         SSO_ADC_Component : Boolean := False;
4925         --  Set True if we find at least one component whose type has a
4926         --  Scalar_Storage_Order attribute definition clause.
4927
4928         Unplaced_Component : Boolean := False;
4929         --  Set True if we find at least one component with no component
4930         --  clause (used to warn about useless Pack pragmas).
4931
4932         procedure Check_Itype (Typ : Entity_Id);
4933         --  If the component subtype is an access to a constrained subtype of
4934         --  an already frozen type, make the subtype frozen as well. It might
4935         --  otherwise be frozen in the wrong scope, and a freeze node on
4936         --  subtype has no effect. Similarly, if the component subtype is a
4937         --  regular (not protected) access to subprogram, set the anonymous
4938         --  subprogram type to frozen as well, to prevent an out-of-scope
4939         --  freeze node at some eventual point of call. Protected operations
4940         --  are handled elsewhere.
4941
4942         procedure Freeze_Choices_In_Variant_Part (VP : Node_Id);
4943         --  Make sure that all types mentioned in Discrete_Choices of the
4944         --  variants referenceed by the Variant_Part VP are frozen. This is
4945         --  a recursive routine to deal with nested variants.
4946
4947         -----------------
4948         -- Check_Itype --
4949         -----------------
4950
4951         procedure Check_Itype (Typ : Entity_Id) is
4952            Desig : constant Entity_Id := Designated_Type (Typ);
4953
4954         begin
4955            if not Is_Frozen (Desig)
4956              and then Is_Frozen (Base_Type (Desig))
4957            then
4958               Set_Is_Frozen (Desig);
4959
4960               --  In addition, add an Itype_Reference to ensure that the
4961               --  access subtype is elaborated early enough. This cannot be
4962               --  done if the subtype may depend on discriminants.
4963
4964               if Ekind (Comp) = E_Component
4965                 and then Is_Itype (Etype (Comp))
4966                 and then not Has_Discriminants (Rec)
4967               then
4968                  IR := Make_Itype_Reference (Sloc (Comp));
4969                  Set_Itype (IR, Desig);
4970                  Add_To_Result (IR);
4971               end if;
4972
4973            elsif Ekind (Typ) = E_Anonymous_Access_Subprogram_Type
4974              and then Convention (Desig) /= Convention_Protected
4975            then
4976               Set_Is_Frozen (Desig);
4977            end if;
4978         end Check_Itype;
4979
4980         ------------------------------------
4981         -- Freeze_Choices_In_Variant_Part --
4982         ------------------------------------
4983
4984         procedure Freeze_Choices_In_Variant_Part (VP : Node_Id) is
4985            pragma Assert (Nkind (VP) = N_Variant_Part);
4986
4987            Variant : Node_Id;
4988            Choice  : Node_Id;
4989            CL      : Node_Id;
4990
4991         begin
4992            --  Loop through variants
4993
4994            Variant := First_Non_Pragma (Variants (VP));
4995            while Present (Variant) loop
4996
4997               --  Loop through choices, checking that all types are frozen
4998
4999               Choice := First_Non_Pragma (Discrete_Choices (Variant));
5000               while Present (Choice) loop
5001                  if Nkind (Choice) in N_Has_Etype
5002                    and then Present (Etype (Choice))
5003                  then
5004                     Freeze_And_Append (Etype (Choice), N, Result);
5005                  end if;
5006
5007                  Next_Non_Pragma (Choice);
5008               end loop;
5009
5010               --  Check for nested variant part to process
5011
5012               CL := Component_List (Variant);
5013
5014               if not Null_Present (CL) then
5015                  if Present (Variant_Part (CL)) then
5016                     Freeze_Choices_In_Variant_Part (Variant_Part (CL));
5017                  end if;
5018               end if;
5019
5020               Next_Non_Pragma (Variant);
5021            end loop;
5022         end Freeze_Choices_In_Variant_Part;
5023
5024      --  Start of processing for Freeze_Record_Type
5025
5026      begin
5027         --  Freeze components and embedded subtypes
5028
5029         Comp := First_Entity (Rec);
5030         Prev := Empty;
5031         while Present (Comp) loop
5032            if Is_Aliased (Comp) then
5033               Aliased_Component := True;
5034            end if;
5035
5036            --  Handle the component and discriminant case
5037
5038            if Ekind (Comp) in E_Component | E_Discriminant then
5039               declare
5040                  CC : constant Node_Id := Component_Clause (Comp);
5041
5042               begin
5043                  --  Freezing a record type freezes the type of each of its
5044                  --  components. However, if the type of the component is
5045                  --  part of this record, we do not want or need a separate
5046                  --  Freeze_Node. Note that Is_Itype is wrong because that's
5047                  --  also set in private type cases. We also can't check for
5048                  --  the Scope being exactly Rec because of private types and
5049                  --  record extensions.
5050
5051                  if Is_Itype (Etype (Comp))
5052                    and then Is_Record_Type (Underlying_Type
5053                                               (Scope (Etype (Comp))))
5054                  then
5055                     Undelay_Type (Etype (Comp));
5056                  end if;
5057
5058                  Freeze_And_Append (Etype (Comp), N, Result);
5059
5060                  --  Warn for pragma Pack overriding foreign convention
5061
5062                  if Has_Foreign_Convention (Etype (Comp))
5063                    and then Has_Pragma_Pack (Rec)
5064
5065                    --  Don't warn for aliased components, since override
5066                    --  cannot happen in that case.
5067
5068                    and then not Is_Aliased (Comp)
5069                  then
5070                     declare
5071                        CN : constant Name_Id :=
5072                               Get_Convention_Name (Convention (Etype (Comp)));
5073                        PP : constant Node_Id :=
5074                               Get_Pragma (Rec, Pragma_Pack);
5075                     begin
5076                        if Present (PP) then
5077                           Error_Msg_Name_1 := CN;
5078                           Error_Msg_Sloc := Sloc (Comp);
5079                           Error_Msg_N
5080                             ("pragma Pack affects convention % component#??",
5081                              PP);
5082                           Error_Msg_Name_1 := CN;
5083                           Error_Msg_NE
5084                             ("\component & may not have % compatible "
5085                              & "representation??", PP, Comp);
5086                        end if;
5087                     end;
5088                  end if;
5089
5090                  --  Check for error of component clause given for variable
5091                  --  sized type. We have to delay this test till this point,
5092                  --  since the component type has to be frozen for us to know
5093                  --  if it is variable length.
5094
5095                  if Present (CC) then
5096                     Placed_Component := True;
5097
5098                     --  We omit this test in a generic context, it will be
5099                     --  applied at instantiation time.
5100
5101                     if Inside_A_Generic then
5102                        null;
5103
5104                     --  Also omit this test in CodePeer mode, since we do not
5105                     --  have sufficient info on size and rep clauses.
5106
5107                     elsif CodePeer_Mode then
5108                        null;
5109
5110                     --  Do the check
5111
5112                     elsif not
5113                       Size_Known_At_Compile_Time
5114                         (Underlying_Type (Etype (Comp)))
5115                     then
5116                        Error_Msg_N
5117                          ("component clause not allowed for variable " &
5118                           "length component", CC);
5119                     end if;
5120
5121                  else
5122                     Unplaced_Component := True;
5123                  end if;
5124
5125                  --  Case of component requires byte alignment
5126
5127                  if Must_Be_On_Byte_Boundary (Etype (Comp)) then
5128
5129                     --  Set the enclosing record to also require byte align
5130
5131                     Set_Must_Be_On_Byte_Boundary (Rec);
5132
5133                     --  Check for component clause that is inconsistent with
5134                     --  the required byte boundary alignment.
5135
5136                     if Present (CC)
5137                       and then Normalized_First_Bit (Comp) mod
5138                                  System_Storage_Unit /= 0
5139                     then
5140                        Error_Msg_N
5141                          ("component & must be byte aligned",
5142                           Component_Name (Component_Clause (Comp)));
5143                     end if;
5144                  end if;
5145               end;
5146            end if;
5147
5148            --  Gather data for possible Implicit_Packing later. Note that at
5149            --  this stage we might be dealing with a real component, or with
5150            --  an implicit subtype declaration.
5151
5152            if Known_Static_RM_Size (Etype (Comp)) then
5153               declare
5154                  Comp_Type : constant Entity_Id := Etype (Comp);
5155                  Comp_Size : constant Uint := RM_Size (Comp_Type);
5156                  SSU       : constant Int := Ttypes.System_Storage_Unit;
5157
5158               begin
5159                  Sized_Component_Total_RM_Size :=
5160                    Sized_Component_Total_RM_Size + Comp_Size;
5161
5162                  Sized_Component_Total_Round_RM_Size :=
5163                    Sized_Component_Total_Round_RM_Size +
5164                      (Comp_Size + SSU - 1) / SSU * SSU;
5165
5166                  if Present (Underlying_Type (Comp_Type))
5167                    and then Is_Elementary_Type (Underlying_Type (Comp_Type))
5168                  then
5169                     Elem_Component_Total_Esize :=
5170                       Elem_Component_Total_Esize + Esize (Comp_Type);
5171                  else
5172                     All_Elem_Components := False;
5173
5174                     if Comp_Size mod SSU /= 0 then
5175                        All_Storage_Unit_Components := False;
5176                     end if;
5177                  end if;
5178               end;
5179            else
5180               All_Sized_Components := False;
5181            end if;
5182
5183            --  If the component is an Itype with Delayed_Freeze and is either
5184            --  a record or array subtype and its base type has not yet been
5185            --  frozen, we must remove this from the entity list of this record
5186            --  and put it on the entity list of the scope of its base type.
5187            --  Note that we know that this is not the type of a component
5188            --  since we cleared Has_Delayed_Freeze for it in the previous
5189            --  loop. Thus this must be the Designated_Type of an access type,
5190            --  which is the type of a component.
5191
5192            if Is_Itype (Comp)
5193              and then Is_Type (Scope (Comp))
5194              and then Is_Composite_Type (Comp)
5195              and then Base_Type (Comp) /= Comp
5196              and then Has_Delayed_Freeze (Comp)
5197              and then not Is_Frozen (Base_Type (Comp))
5198            then
5199               declare
5200                  Will_Be_Frozen : Boolean := False;
5201                  S              : Entity_Id;
5202
5203               begin
5204                  --  We have a difficult case to handle here. Suppose Rec is
5205                  --  subtype being defined in a subprogram that's created as
5206                  --  part of the freezing of Rec'Base. In that case, we know
5207                  --  that Comp'Base must have already been frozen by the time
5208                  --  we get to elaborate this because Gigi doesn't elaborate
5209                  --  any bodies until it has elaborated all of the declarative
5210                  --  part. But Is_Frozen will not be set at this point because
5211                  --  we are processing code in lexical order.
5212
5213                  --  We detect this case by going up the Scope chain of Rec
5214                  --  and seeing if we have a subprogram scope before reaching
5215                  --  the top of the scope chain or that of Comp'Base. If we
5216                  --  do, then mark that Comp'Base will actually be frozen. If
5217                  --  so, we merely undelay it.
5218
5219                  S := Scope (Rec);
5220                  while Present (S) loop
5221                     if Is_Subprogram (S) then
5222                        Will_Be_Frozen := True;
5223                        exit;
5224                     elsif S = Scope (Base_Type (Comp)) then
5225                        exit;
5226                     end if;
5227
5228                     S := Scope (S);
5229                  end loop;
5230
5231                  if Will_Be_Frozen then
5232                     Undelay_Type (Comp);
5233
5234                  else
5235                     if Present (Prev) then
5236                        Link_Entities (Prev, Next_Entity (Comp));
5237                     else
5238                        Set_First_Entity (Rec, Next_Entity (Comp));
5239                     end if;
5240
5241                     --  Insert in entity list of scope of base type (which
5242                     --  must be an enclosing scope, because still unfrozen).
5243
5244                     Append_Entity (Comp, Scope (Base_Type (Comp)));
5245                  end if;
5246               end;
5247
5248            --  If the component is an access type with an allocator as default
5249            --  value, the designated type will be frozen by the corresponding
5250            --  expression in init_proc. In order to place the freeze node for
5251            --  the designated type before that for the current record type,
5252            --  freeze it now.
5253
5254            --  Same process if the component is an array of access types,
5255            --  initialized with an aggregate. If the designated type is
5256            --  private, it cannot contain allocators, and it is premature
5257            --  to freeze the type, so we check for this as well.
5258
5259            elsif Is_Access_Type (Etype (Comp))
5260              and then Present (Parent (Comp))
5261              and then
5262                Nkind (Parent (Comp))
5263                  in N_Component_Declaration | N_Discriminant_Specification
5264              and then Present (Expression (Parent (Comp)))
5265            then
5266               declare
5267                  Alloc : constant Node_Id :=
5268                            Unqualify (Expression (Parent (Comp)));
5269
5270               begin
5271                  if Nkind (Alloc) = N_Allocator then
5272
5273                     --  If component is pointer to a class-wide type, freeze
5274                     --  the specific type in the expression being allocated.
5275                     --  The expression may be a subtype indication, in which
5276                     --  case freeze the subtype mark.
5277
5278                     if Is_Class_Wide_Type (Designated_Type (Etype (Comp)))
5279                     then
5280                        if Is_Entity_Name (Expression (Alloc)) then
5281                           Freeze_And_Append
5282                             (Entity (Expression (Alloc)), N, Result);
5283
5284                        elsif Nkind (Expression (Alloc)) = N_Subtype_Indication
5285                        then
5286                           Freeze_And_Append
5287                            (Entity (Subtype_Mark (Expression (Alloc))),
5288                             N, Result);
5289                        end if;
5290                     elsif Is_Itype (Designated_Type (Etype (Comp))) then
5291                        Check_Itype (Etype (Comp));
5292                     else
5293                        Freeze_And_Append
5294                          (Designated_Type (Etype (Comp)), N, Result);
5295                     end if;
5296                  end if;
5297               end;
5298            elsif Is_Access_Type (Etype (Comp))
5299              and then Is_Itype (Designated_Type (Etype (Comp)))
5300            then
5301               Check_Itype (Etype (Comp));
5302
5303            --  Freeze the designated type when initializing a component with
5304            --  an aggregate in case the aggregate contains allocators.
5305
5306            --     type T is ...;
5307            --     type T_Ptr is access all T;
5308            --     type T_Array is array ... of T_Ptr;
5309
5310            --     type Rec is record
5311            --        Comp : T_Array := (others => ...);
5312            --     end record;
5313
5314            elsif Is_Array_Type (Etype (Comp))
5315              and then Is_Access_Type (Component_Type (Etype (Comp)))
5316            then
5317               declare
5318                  Comp_Par  : constant Node_Id   := Parent (Comp);
5319                  Desig_Typ : constant Entity_Id :=
5320                                Designated_Type
5321                                  (Component_Type (Etype (Comp)));
5322
5323               begin
5324                  --  The only case when this sort of freezing is not done is
5325                  --  when the designated type is class-wide and the root type
5326                  --  is the record owning the component. This scenario results
5327                  --  in a circularity because the class-wide type requires
5328                  --  primitives that have not been created yet as the root
5329                  --  type is in the process of being frozen.
5330
5331                  --     type Rec is tagged;
5332                  --     type Rec_Ptr is access all Rec'Class;
5333                  --     type Rec_Array is array ... of Rec_Ptr;
5334
5335                  --     type Rec is record
5336                  --        Comp : Rec_Array := (others => ...);
5337                  --     end record;
5338
5339                  if Is_Class_Wide_Type (Desig_Typ)
5340                    and then Root_Type (Desig_Typ) = Rec
5341                  then
5342                     null;
5343
5344                  elsif Is_Fully_Defined (Desig_Typ)
5345                    and then Present (Comp_Par)
5346                    and then Nkind (Comp_Par) = N_Component_Declaration
5347                    and then Present (Expression (Comp_Par))
5348                    and then Nkind (Expression (Comp_Par)) = N_Aggregate
5349                  then
5350                     Freeze_And_Append (Desig_Typ, N, Result);
5351                  end if;
5352               end;
5353            end if;
5354
5355            Prev := Comp;
5356            Next_Entity (Comp);
5357         end loop;
5358
5359         SSO_ADC :=
5360           Get_Attribute_Definition_Clause
5361             (Rec, Attribute_Scalar_Storage_Order);
5362
5363         --  If the record type has Complex_Representation, then it is treated
5364         --  as a scalar in the back end so the storage order is irrelevant.
5365
5366         if Has_Complex_Representation (Rec) then
5367            if Present (SSO_ADC) then
5368               Error_Msg_N
5369                 ("??storage order has no effect with Complex_Representation",
5370                  SSO_ADC);
5371            end if;
5372
5373         else
5374            --  Deal with default setting of reverse storage order
5375
5376            Set_SSO_From_Default (Rec);
5377
5378            --  Check consistent attribute setting on component types
5379
5380            declare
5381               Comp_ADC_Present : Boolean;
5382            begin
5383               Comp := First_Component (Rec);
5384               while Present (Comp) loop
5385                  Check_Component_Storage_Order
5386                    (Encl_Type        => Rec,
5387                     Comp             => Comp,
5388                     ADC              => SSO_ADC,
5389                     Comp_ADC_Present => Comp_ADC_Present);
5390                  SSO_ADC_Component := SSO_ADC_Component or Comp_ADC_Present;
5391                  Next_Component (Comp);
5392               end loop;
5393            end;
5394
5395            --  Now deal with reverse storage order/bit order issues
5396
5397            if Present (SSO_ADC) then
5398
5399               --  Check compatibility of Scalar_Storage_Order with Bit_Order,
5400               --  if the former is specified.
5401
5402               if Reverse_Bit_Order (Rec) /= Reverse_Storage_Order (Rec) then
5403
5404                  --  Note: report error on Rec, not on SSO_ADC, as ADC may
5405                  --  apply to some ancestor type.
5406
5407                  Error_Msg_Sloc := Sloc (SSO_ADC);
5408                  Error_Msg_N
5409                    ("scalar storage order for& specified# inconsistent with "
5410                     & "bit order", Rec);
5411               end if;
5412
5413               --  Warn if there is a Scalar_Storage_Order attribute definition
5414               --  clause but no component clause, no component that itself has
5415               --  such an attribute definition, and no pragma Pack.
5416
5417               if not (Placed_Component
5418                         or else
5419                       SSO_ADC_Component
5420                         or else
5421                       Is_Packed (Rec))
5422               then
5423                  Error_Msg_N
5424                    ("??scalar storage order specified but no component "
5425                     & "clause", SSO_ADC);
5426               end if;
5427            end if;
5428         end if;
5429
5430         --  Deal with Bit_Order aspect
5431
5432         ADC := Get_Attribute_Definition_Clause (Rec, Attribute_Bit_Order);
5433
5434         if Present (ADC) and then Base_Type (Rec) = Rec then
5435            if not (Placed_Component
5436                     or else Present (SSO_ADC)
5437                     or else Is_Packed (Rec))
5438            then
5439               --  Warn if clause has no effect when no component clause is
5440               --  present, but suppress warning if the Bit_Order is required
5441               --  due to the presence of a Scalar_Storage_Order attribute.
5442
5443               Error_Msg_N
5444                 ("??bit order specification has no effect", ADC);
5445               Error_Msg_N
5446                 ("\??since no component clauses were specified", ADC);
5447
5448            --  Here is where we do the processing to adjust component clauses
5449            --  for reversed bit order, when not using reverse SSO. If an error
5450            --  has been reported on Rec already (such as SSO incompatible with
5451            --  bit order), don't bother adjusting as this may generate extra
5452            --  noise.
5453
5454            elsif Reverse_Bit_Order (Rec)
5455              and then not Reverse_Storage_Order (Rec)
5456              and then not Error_Posted (Rec)
5457            then
5458               Adjust_Record_For_Reverse_Bit_Order (Rec);
5459
5460            --  Case where we have both an explicit Bit_Order and the same
5461            --  Scalar_Storage_Order: leave record untouched, the back-end
5462            --  will take care of required layout conversions.
5463
5464            else
5465               null;
5466
5467            end if;
5468         end if;
5469
5470         --  Check for useless pragma Pack when all components placed. We only
5471         --  do this check for record types, not subtypes, since a subtype may
5472         --  have all its components placed, and it still makes perfectly good
5473         --  sense to pack other subtypes or the parent type. We do not give
5474         --  this warning if Optimize_Alignment is set to Space, since the
5475         --  pragma Pack does have an effect in this case (it always resets
5476         --  the alignment to one).
5477
5478         if Ekind (Rec) = E_Record_Type
5479           and then Is_Packed (Rec)
5480           and then not Unplaced_Component
5481           and then Optimize_Alignment /= 'S'
5482         then
5483            --  Reset packed status. Probably not necessary, but we do it so
5484            --  that there is no chance of the back end doing something strange
5485            --  with this redundant indication of packing.
5486
5487            Set_Is_Packed (Rec, False);
5488
5489            --  Give warning if redundant constructs warnings on
5490
5491            if Warn_On_Redundant_Constructs then
5492               Error_Msg_N -- CODEFIX
5493                 ("??pragma Pack has no effect, no unplaced components",
5494                  Get_Rep_Pragma (Rec, Name_Pack));
5495            end if;
5496         end if;
5497
5498         --  If this is the record corresponding to a remote type, freeze the
5499         --  remote type here since that is what we are semantically freezing.
5500         --  This prevents the freeze node for that type in an inner scope.
5501
5502         if Ekind (Rec) = E_Record_Type then
5503            if Present (Corresponding_Remote_Type (Rec)) then
5504               Freeze_And_Append (Corresponding_Remote_Type (Rec), N, Result);
5505            end if;
5506
5507            --  Check for controlled components, unchecked unions, and type
5508            --  invariants.
5509
5510            Comp := First_Component (Rec);
5511            while Present (Comp) loop
5512
5513               --  Do not set Has_Controlled_Component on a class-wide
5514               --  equivalent type. See Make_CW_Equivalent_Type.
5515
5516               if not Is_Class_Wide_Equivalent_Type (Rec)
5517                 and then
5518                   (Has_Controlled_Component (Etype (Comp))
5519                     or else
5520                       (Chars (Comp) /= Name_uParent
5521                         and then Is_Controlled (Etype (Comp)))
5522                     or else
5523                       (Is_Protected_Type (Etype (Comp))
5524                         and then
5525                           Present (Corresponding_Record_Type (Etype (Comp)))
5526                         and then
5527                           Has_Controlled_Component
5528                             (Corresponding_Record_Type (Etype (Comp)))))
5529               then
5530                  Set_Has_Controlled_Component (Rec);
5531               end if;
5532
5533               if Has_Unchecked_Union (Etype (Comp)) then
5534                  Set_Has_Unchecked_Union (Rec);
5535               end if;
5536
5537               --  The record type requires its own invariant procedure in
5538               --  order to verify the invariant of each individual component.
5539               --  Do not consider internal components such as _parent because
5540               --  parent class-wide invariants are always inherited.
5541               --  In GNATprove mode, the component invariants are checked by
5542               --  other means. They should not be added to the record type
5543               --  invariant procedure, so that the procedure can be used to
5544               --  check the recordy type invariants if any.
5545
5546               if Comes_From_Source (Comp)
5547                 and then Has_Invariants (Etype (Comp))
5548                   and then not GNATprove_Mode
5549               then
5550                  Set_Has_Own_Invariants (Rec);
5551               end if;
5552
5553               --  Scan component declaration for likely misuses of current
5554               --  instance, either in a constraint or a default expression.
5555
5556               if Has_Per_Object_Constraint (Comp) then
5557                  Check_Current_Instance (Parent (Comp));
5558               end if;
5559
5560               Next_Component (Comp);
5561            end loop;
5562         end if;
5563
5564         --  Enforce the restriction that access attributes with a current
5565         --  instance prefix can only apply to limited types. This comment
5566         --  is floating here, but does not seem to belong here???
5567
5568         --  Set component alignment if not otherwise already set
5569
5570         Set_Component_Alignment_If_Not_Set (Rec);
5571
5572         --  For first subtypes, check if there are any fixed-point fields with
5573         --  component clauses, where we must check the size. This is not done
5574         --  till the freeze point since for fixed-point types, we do not know
5575         --  the size until the type is frozen. Similar processing applies to
5576         --  bit-packed arrays.
5577
5578         if Is_First_Subtype (Rec) then
5579            Comp := First_Component (Rec);
5580            while Present (Comp) loop
5581               if Present (Component_Clause (Comp))
5582                 and then (Is_Fixed_Point_Type (Etype (Comp))
5583                            or else Is_Bit_Packed_Array (Etype (Comp)))
5584               then
5585                  Check_Size
5586                    (Component_Name (Component_Clause (Comp)),
5587                     Etype (Comp),
5588                     Esize (Comp),
5589                     Junk);
5590               end if;
5591
5592               Next_Component (Comp);
5593            end loop;
5594         end if;
5595
5596         --  See if Size is too small as is (and implicit packing might help)
5597
5598         if not Is_Packed (Rec)
5599
5600           --  No implicit packing if even one component is explicitly placed
5601
5602           and then not Placed_Component
5603
5604           --  Or even one component is aliased
5605
5606           and then not Aliased_Component
5607
5608           --  Must have size clause and all sized components
5609
5610           and then Has_Size_Clause (Rec)
5611           and then All_Sized_Components
5612
5613           --  Do not try implicit packing on records with discriminants, too
5614           --  complicated, especially in the variant record case.
5615
5616           and then not Has_Discriminants (Rec)
5617
5618           --  We want to implicitly pack if the specified size of the record
5619           --  is less than the sum of the object sizes (no point in packing
5620           --  if this is not the case), if we can compute it, i.e. if we have
5621           --  only elementary components. Otherwise, we have at least one
5622           --  composite component and we want to implicitly pack only if bit
5623           --  packing is required for it, as we are sure in this case that
5624           --  the back end cannot do the expected layout without packing.
5625
5626           and then
5627              ((All_Elem_Components
5628                 and then RM_Size (Rec) < Elem_Component_Total_Esize)
5629             or else
5630               (not All_Elem_Components
5631                 and then not All_Storage_Unit_Components
5632                 and then RM_Size (Rec) < Sized_Component_Total_Round_RM_Size))
5633
5634           --  And the total RM size cannot be greater than the specified size
5635           --  since otherwise packing will not get us where we have to be.
5636
5637           and then Sized_Component_Total_RM_Size <= RM_Size (Rec)
5638
5639           --  Never do implicit packing in CodePeer or SPARK modes since
5640           --  we don't do any packing in these modes, since this generates
5641           --  over-complex code that confuses static analysis, and in
5642           --  general, neither CodePeer not GNATprove care about the
5643           --  internal representation of objects.
5644
5645           and then not (CodePeer_Mode or GNATprove_Mode)
5646         then
5647            --  If implicit packing enabled, do it
5648
5649            if Implicit_Packing then
5650               Set_Is_Packed (Rec);
5651
5652               --  Otherwise flag the size clause
5653
5654            else
5655               declare
5656                  Sz : constant Node_Id := Size_Clause (Rec);
5657               begin
5658                  Error_Msg_NE -- CODEFIX
5659                    ("size given for& too small", Sz, Rec);
5660                  Error_Msg_N -- CODEFIX
5661                    ("\use explicit pragma Pack "
5662                     & "or use pragma Implicit_Packing", Sz);
5663               end;
5664            end if;
5665         end if;
5666
5667         --  The following checks are relevant only when SPARK_Mode is on as
5668         --  they are not standard Ada legality rules.
5669
5670         if SPARK_Mode = On then
5671
5672            --  A discriminated type cannot be effectively volatile
5673            --  (SPARK RM 7.1.3(5)).
5674
5675            if Is_Effectively_Volatile (Rec) then
5676               if Has_Discriminants (Rec) then
5677                  Error_Msg_N ("discriminated type & cannot be volatile", Rec);
5678               end if;
5679
5680            --  A non-effectively volatile record type cannot contain
5681            --  effectively volatile components (SPARK RM 7.1.3(6)).
5682
5683            else
5684               Comp := First_Component (Rec);
5685               while Present (Comp) loop
5686                  if Comes_From_Source (Comp)
5687                    and then Is_Effectively_Volatile (Etype (Comp))
5688                  then
5689                     Error_Msg_Name_1 := Chars (Rec);
5690                     Error_Msg_N
5691                       ("component & of non-volatile type % cannot be "
5692                        & "volatile", Comp);
5693                  end if;
5694
5695                  Next_Component (Comp);
5696               end loop;
5697            end if;
5698
5699            --  A type which does not yield a synchronized object cannot have
5700            --  a component that yields a synchronized object (SPARK RM 9.5).
5701
5702            if not Yields_Synchronized_Object (Rec) then
5703               Comp := First_Component (Rec);
5704               while Present (Comp) loop
5705                  if Comes_From_Source (Comp)
5706                    and then Yields_Synchronized_Object (Etype (Comp))
5707                  then
5708                     Error_Msg_Name_1 := Chars (Rec);
5709                     Error_Msg_N
5710                       ("component & of non-synchronized type % cannot be "
5711                        & "synchronized", Comp);
5712                  end if;
5713
5714                  Next_Component (Comp);
5715               end loop;
5716            end if;
5717
5718            --  A Ghost type cannot have a component of protected or task type
5719            --  (SPARK RM 6.9(19)).
5720
5721            if Is_Ghost_Entity (Rec) then
5722               Comp := First_Component (Rec);
5723               while Present (Comp) loop
5724                  if Comes_From_Source (Comp)
5725                    and then Is_Concurrent_Type (Etype (Comp))
5726                  then
5727                     Error_Msg_Name_1 := Chars (Rec);
5728                     Error_Msg_N
5729                       ("component & of ghost type % cannot be concurrent",
5730                        Comp);
5731                  end if;
5732
5733                  Next_Component (Comp);
5734               end loop;
5735            end if;
5736         end if;
5737
5738         --  Make sure that if we have an iterator aspect, then we have
5739         --  either Constant_Indexing or Variable_Indexing.
5740
5741         declare
5742            Iterator_Aspect : Node_Id;
5743
5744         begin
5745            Iterator_Aspect := Find_Aspect (Rec, Aspect_Iterator_Element);
5746
5747            if No (Iterator_Aspect) then
5748               Iterator_Aspect := Find_Aspect (Rec, Aspect_Default_Iterator);
5749            end if;
5750
5751            if Present (Iterator_Aspect) then
5752               if Has_Aspect (Rec, Aspect_Constant_Indexing)
5753                    or else
5754                  Has_Aspect (Rec, Aspect_Variable_Indexing)
5755               then
5756                  null;
5757               else
5758                  Error_Msg_N
5759                    ("Iterator_Element requires indexing aspect",
5760                     Iterator_Aspect);
5761               end if;
5762            end if;
5763         end;
5764
5765         --  All done if not a full record definition
5766
5767         if Ekind (Rec) /= E_Record_Type then
5768            return;
5769         end if;
5770
5771         --  Finally we need to check the variant part to make sure that
5772         --  all types within choices are properly frozen as part of the
5773         --  freezing of the record type.
5774
5775         Check_Variant_Part : declare
5776            D : constant Node_Id := Declaration_Node (Rec);
5777            T : Node_Id;
5778            C : Node_Id;
5779
5780         begin
5781            --  Find component list
5782
5783            C := Empty;
5784
5785            if Nkind (D) = N_Full_Type_Declaration then
5786               T := Type_Definition (D);
5787
5788               if Nkind (T) = N_Record_Definition then
5789                  C := Component_List (T);
5790
5791               elsif Nkind (T) = N_Derived_Type_Definition
5792                 and then Present (Record_Extension_Part (T))
5793               then
5794                  C := Component_List (Record_Extension_Part (T));
5795               end if;
5796            end if;
5797
5798            --  Case of variant part present
5799
5800            if Present (C) and then Present (Variant_Part (C)) then
5801               Freeze_Choices_In_Variant_Part (Variant_Part (C));
5802            end if;
5803
5804            --  Note: we used to call Check_Choices here, but it is too early,
5805            --  since predicated subtypes are frozen here, but their freezing
5806            --  actions are in Analyze_Freeze_Entity, which has not been called
5807            --  yet for entities frozen within this procedure, so we moved that
5808            --  call to the Analyze_Freeze_Entity for the record type.
5809
5810         end Check_Variant_Part;
5811
5812         --  Check that all the primitives of an interface type are abstract
5813         --  or null procedures.
5814
5815         if Is_Interface (Rec)
5816           and then not Error_Posted (Parent (Rec))
5817         then
5818            declare
5819               Elmt : Elmt_Id;
5820               Subp : Entity_Id;
5821
5822            begin
5823               Elmt := First_Elmt (Primitive_Operations (Rec));
5824               while Present (Elmt) loop
5825                  Subp := Node (Elmt);
5826
5827                  if not Is_Abstract_Subprogram (Subp)
5828
5829                     --  Avoid reporting the error on inherited primitives
5830
5831                    and then Comes_From_Source (Subp)
5832                  then
5833                     Error_Msg_Name_1 := Chars (Subp);
5834
5835                     if Ekind (Subp) = E_Procedure then
5836                        if not Null_Present (Parent (Subp)) then
5837                           Error_Msg_N
5838                             ("interface procedure % must be abstract or null",
5839                              Parent (Subp));
5840                        end if;
5841                     else
5842                        Error_Msg_N
5843                          ("interface function % must be abstract",
5844                           Parent (Subp));
5845                     end if;
5846                  end if;
5847
5848                  Next_Elmt (Elmt);
5849               end loop;
5850            end;
5851         end if;
5852
5853         --  For a derived tagged type, check whether inherited primitives
5854         --  might require a wrapper to handle class-wide conditions.
5855
5856         if Is_Tagged_Type (Rec) and then Is_Derived_Type (Rec) then
5857            Check_Inherited_Conditions (Rec);
5858         end if;
5859      end Freeze_Record_Type;
5860
5861      -------------------------------
5862      -- Has_Boolean_Aspect_Import --
5863      -------------------------------
5864
5865      function Has_Boolean_Aspect_Import (E : Entity_Id) return Boolean is
5866         Decl : constant Node_Id := Declaration_Node (E);
5867         Asp  : Node_Id;
5868         Expr : Node_Id;
5869
5870      begin
5871         if Has_Aspects (Decl) then
5872            Asp := First (Aspect_Specifications (Decl));
5873            while Present (Asp) loop
5874               Expr := Expression (Asp);
5875
5876               --  The value of aspect Import is True when the expression is
5877               --  either missing or it is explicitly set to True.
5878
5879               if Get_Aspect_Id (Asp) = Aspect_Import
5880                 and then (No (Expr)
5881                            or else (Compile_Time_Known_Value (Expr)
5882                                      and then Is_True (Expr_Value (Expr))))
5883               then
5884                  return True;
5885               end if;
5886
5887               Next (Asp);
5888            end loop;
5889         end if;
5890
5891         return False;
5892      end Has_Boolean_Aspect_Import;
5893
5894      -------------------------
5895      -- Inherit_Freeze_Node --
5896      -------------------------
5897
5898      procedure Inherit_Freeze_Node
5899        (Fnod : Node_Id;
5900         Typ  : Entity_Id)
5901      is
5902         Typ_Fnod : constant Node_Id := Freeze_Node (Typ);
5903
5904      begin
5905         Set_Freeze_Node (Typ, Fnod);
5906         Set_Entity (Fnod, Typ);
5907
5908         --  The input type had an existing node. Propagate relevant attributes
5909         --  from the old freeze node to the inherited freeze node.
5910
5911         --  ??? if both freeze nodes have attributes, would they differ?
5912
5913         if Present (Typ_Fnod) then
5914
5915            --  Attribute Access_Types_To_Process
5916
5917            if Present (Access_Types_To_Process (Typ_Fnod))
5918              and then No (Access_Types_To_Process (Fnod))
5919            then
5920               Set_Access_Types_To_Process (Fnod,
5921                 Access_Types_To_Process (Typ_Fnod));
5922            end if;
5923
5924            --  Attribute Actions
5925
5926            if Present (Actions (Typ_Fnod)) and then No (Actions (Fnod)) then
5927               Set_Actions (Fnod, Actions (Typ_Fnod));
5928            end if;
5929
5930            --  Attribute First_Subtype_Link
5931
5932            if Present (First_Subtype_Link (Typ_Fnod))
5933              and then No (First_Subtype_Link (Fnod))
5934            then
5935               Set_First_Subtype_Link (Fnod, First_Subtype_Link (Typ_Fnod));
5936            end if;
5937
5938            --  Attribute TSS_Elist
5939
5940            if Present (TSS_Elist (Typ_Fnod))
5941              and then No (TSS_Elist (Fnod))
5942            then
5943               Set_TSS_Elist (Fnod, TSS_Elist (Typ_Fnod));
5944            end if;
5945         end if;
5946      end Inherit_Freeze_Node;
5947
5948      ------------------------------
5949      -- Wrap_Imported_Subprogram --
5950      ------------------------------
5951
5952      --  The issue here is that our normal approach of checking preconditions
5953      --  and postconditions does not work for imported procedures, since we
5954      --  are not generating code for the body. To get around this we create
5955      --  a wrapper, as shown by the following example:
5956
5957      --    procedure K (A : Integer);
5958      --    pragma Import (C, K);
5959
5960      --  The spec is rewritten by removing the effects of pragma Import, but
5961      --  leaving the convention unchanged, as though the source had said:
5962
5963      --    procedure K (A : Integer);
5964      --    pragma Convention (C, K);
5965
5966      --  and we create a body, added to the entity K freeze actions, which
5967      --  looks like:
5968
5969      --    procedure K (A : Integer) is
5970      --       procedure K (A : Integer);
5971      --       pragma Import (C, K);
5972      --    begin
5973      --       K (A);
5974      --    end K;
5975
5976      --  Now the contract applies in the normal way to the outer procedure,
5977      --  and the inner procedure has no contracts, so there is no problem
5978      --  in just calling it to get the original effect.
5979
5980      --  In the case of a function, we create an appropriate return statement
5981      --  for the subprogram body that calls the inner procedure.
5982
5983      procedure Wrap_Imported_Subprogram (E : Entity_Id) is
5984         function Copy_Import_Pragma return Node_Id;
5985         --  Obtain a copy of the Import_Pragma which belongs to subprogram E
5986
5987         ------------------------
5988         -- Copy_Import_Pragma --
5989         ------------------------
5990
5991         function Copy_Import_Pragma return Node_Id is
5992
5993            --  The subprogram should have an import pragma, otherwise it does
5994            --  need a wrapper.
5995
5996            Prag : constant Node_Id := Import_Pragma (E);
5997            pragma Assert (Present (Prag));
5998
5999            --  Save all semantic fields of the pragma
6000
6001            Save_Asp  : constant Node_Id := Corresponding_Aspect (Prag);
6002            Save_From : constant Boolean := From_Aspect_Specification (Prag);
6003            Save_Prag : constant Node_Id := Next_Pragma (Prag);
6004            Save_Rep  : constant Node_Id := Next_Rep_Item (Prag);
6005
6006            Result : Node_Id;
6007
6008         begin
6009            --  Reset all semantic fields. This avoids a potential infinite
6010            --  loop when the pragma comes from an aspect as the duplication
6011            --  will copy the aspect, then copy the corresponding pragma and
6012            --  so on.
6013
6014            Set_Corresponding_Aspect      (Prag, Empty);
6015            Set_From_Aspect_Specification (Prag, False);
6016            Set_Next_Pragma               (Prag, Empty);
6017            Set_Next_Rep_Item             (Prag, Empty);
6018
6019            Result := Copy_Separate_Tree (Prag);
6020
6021            --  Restore the original semantic fields
6022
6023            Set_Corresponding_Aspect      (Prag, Save_Asp);
6024            Set_From_Aspect_Specification (Prag, Save_From);
6025            Set_Next_Pragma               (Prag, Save_Prag);
6026            Set_Next_Rep_Item             (Prag, Save_Rep);
6027
6028            return Result;
6029         end Copy_Import_Pragma;
6030
6031         --  Local variables
6032
6033         Loc   : constant Source_Ptr := Sloc (E);
6034         CE    : constant Name_Id    := Chars (E);
6035         Bod   : Node_Id;
6036         Forml : Entity_Id;
6037         Parms : List_Id;
6038         Prag  : Node_Id;
6039         Spec  : Node_Id;
6040         Stmt  : Node_Id;
6041
6042      --  Start of processing for Wrap_Imported_Subprogram
6043
6044      begin
6045         --  Nothing to do if not imported
6046
6047         if not Is_Imported (E) then
6048            return;
6049
6050         --  Test enabling conditions for wrapping
6051
6052         elsif Is_Subprogram (E)
6053           and then Present (Contract (E))
6054           and then Present (Pre_Post_Conditions (Contract (E)))
6055           and then not GNATprove_Mode
6056         then
6057            --  Here we do the wrap
6058
6059            --  Note on calls to Copy_Separate_Tree. The trees we are copying
6060            --  here are fully analyzed, but we definitely want fully syntactic
6061            --  unanalyzed trees in the body we construct, so that the analysis
6062            --  generates the right visibility, and that is exactly what the
6063            --  calls to Copy_Separate_Tree give us.
6064
6065            Prag := Copy_Import_Pragma;
6066
6067            --  Fix up spec so it is no longer imported and has convention Ada
6068
6069            Set_Has_Completion (E, False);
6070            Set_Import_Pragma  (E, Empty);
6071            Set_Interface_Name (E, Empty);
6072            Set_Is_Imported    (E, False);
6073            Set_Convention     (E, Convention_Ada);
6074
6075            --  Grab the subprogram declaration and specification
6076
6077            Spec := Declaration_Node (E);
6078
6079            --  Build parameter list that we need
6080
6081            Parms := New_List;
6082            Forml := First_Formal (E);
6083            while Present (Forml) loop
6084               Append_To (Parms, Make_Identifier (Loc, Chars (Forml)));
6085               Next_Formal (Forml);
6086            end loop;
6087
6088            --  Build the call
6089
6090            --  An imported function whose result type is anonymous access
6091            --  creates a new anonymous access type when it is relocated into
6092            --  the declarations of the body generated below. As a result, the
6093            --  accessibility level of these two anonymous access types may not
6094            --  be compatible even though they are essentially the same type.
6095            --  Use an unchecked type conversion to reconcile this case. Note
6096            --  that the conversion is safe because in the named access type
6097            --  case, both the body and imported function utilize the same
6098            --  type.
6099
6100            if Ekind (E) in E_Function | E_Generic_Function then
6101               Stmt :=
6102                 Make_Simple_Return_Statement (Loc,
6103                   Expression =>
6104                     Unchecked_Convert_To (Etype (E),
6105                       Make_Function_Call (Loc,
6106                         Name                   => Make_Identifier (Loc, CE),
6107                         Parameter_Associations => Parms)));
6108
6109            else
6110               Stmt :=
6111                 Make_Procedure_Call_Statement (Loc,
6112                   Name                   => Make_Identifier (Loc, CE),
6113                   Parameter_Associations => Parms);
6114            end if;
6115
6116            --  Now build the body
6117
6118            Bod :=
6119              Make_Subprogram_Body (Loc,
6120                Specification              =>
6121                  Copy_Separate_Tree (Spec),
6122                Declarations               => New_List (
6123                  Make_Subprogram_Declaration (Loc,
6124                    Specification => Copy_Separate_Tree (Spec)),
6125                  Prag),
6126                Handled_Statement_Sequence =>
6127                  Make_Handled_Sequence_Of_Statements (Loc,
6128                    Statements => New_List (Stmt),
6129                    End_Label  => Make_Identifier (Loc, CE)));
6130
6131            --  Append the body to freeze result
6132
6133            Add_To_Result (Bod);
6134            return;
6135
6136         --  Case of imported subprogram that does not get wrapped
6137
6138         else
6139            --  Set Is_Public. All imported entities need an external symbol
6140            --  created for them since they are always referenced from another
6141            --  object file. Note this used to be set when we set Is_Imported
6142            --  back in Sem_Prag, but now we delay it to this point, since we
6143            --  don't want to set this flag if we wrap an imported subprogram.
6144
6145            Set_Is_Public (E);
6146         end if;
6147      end Wrap_Imported_Subprogram;
6148
6149   --  Start of processing for Freeze_Entity
6150
6151   begin
6152      --  The entity being frozen may be subject to pragma Ghost. Set the mode
6153      --  now to ensure that any nodes generated during freezing are properly
6154      --  flagged as Ghost.
6155
6156      Set_Ghost_Mode (E);
6157
6158      --  We are going to test for various reasons why this entity need not be
6159      --  frozen here, but in the case of an Itype that's defined within a
6160      --  record, that test actually applies to the record.
6161
6162      if Is_Itype (E) and then Is_Record_Type (Scope (E)) then
6163         Test_E := Scope (E);
6164
6165      elsif Is_Itype (E) and then Present (Underlying_Type (Scope (E)))
6166        and then Is_Record_Type (Underlying_Type (Scope (E)))
6167      then
6168         Test_E := Underlying_Type (Scope (E));
6169      end if;
6170
6171      --  Do not freeze if already frozen since we only need one freeze node
6172
6173      if Is_Frozen (E) then
6174         Result := No_List;
6175         goto Leave;
6176
6177      --  Do not freeze if we are preanalyzing without freezing
6178
6179      elsif Inside_Preanalysis_Without_Freezing > 0 then
6180         Result := No_List;
6181         goto Leave;
6182
6183      elsif Ekind (E) = E_Generic_Package then
6184         Result := Freeze_Generic_Entities (E);
6185         goto Leave;
6186
6187      --  It is improper to freeze an external entity within a generic because
6188      --  its freeze node will appear in a non-valid context. The entity will
6189      --  be frozen in the proper scope after the current generic is analyzed.
6190      --  However, aspects must be analyzed because they may be queried later
6191      --  within the generic itself, and the corresponding pragma or attribute
6192      --  definition has not been analyzed yet. After this, indicate that the
6193      --  entity has no further delayed aspects, to prevent a later aspect
6194      --  analysis out of the scope of the generic.
6195
6196      elsif Inside_A_Generic and then External_Ref_In_Generic (Test_E) then
6197         if Has_Delayed_Aspects (E) then
6198            Analyze_Aspects_At_Freeze_Point (E);
6199            Set_Has_Delayed_Aspects (E, False);
6200         end if;
6201
6202         Result := No_List;
6203         goto Leave;
6204
6205      --  AI05-0213: A formal incomplete type does not freeze the actual. In
6206      --  the instance, the same applies to the subtype renaming the actual.
6207
6208      elsif Is_Private_Type (E)
6209        and then Is_Generic_Actual_Type (E)
6210        and then No (Full_View (Base_Type (E)))
6211        and then Ada_Version >= Ada_2012
6212      then
6213         Result := No_List;
6214         goto Leave;
6215
6216      --  Formal subprograms are never frozen
6217
6218      elsif Is_Formal_Subprogram (E) then
6219         Result := No_List;
6220         goto Leave;
6221
6222      --  Generic types are never frozen as they lack delayed semantic checks
6223
6224      elsif Is_Generic_Type (E) then
6225         Result := No_List;
6226         goto Leave;
6227
6228      --  Do not freeze a global entity within an inner scope created during
6229      --  expansion. A call to subprogram E within some internal procedure
6230      --  (a stream attribute for example) might require freezing E, but the
6231      --  freeze node must appear in the same declarative part as E itself.
6232      --  The two-pass elaboration mechanism in gigi guarantees that E will
6233      --  be frozen before the inner call is elaborated. We exclude constants
6234      --  from this test, because deferred constants may be frozen early, and
6235      --  must be diagnosed (e.g. in the case of a deferred constant being used
6236      --  in a default expression). If the enclosing subprogram comes from
6237      --  source, or is a generic instance, then the freeze point is the one
6238      --  mandated by the language, and we freeze the entity. A subprogram that
6239      --  is a child unit body that acts as a spec does not have a spec that
6240      --  comes from source, but can only come from source.
6241
6242      elsif In_Open_Scopes (Scope (Test_E))
6243        and then Scope (Test_E) /= Current_Scope
6244        and then Ekind (Test_E) /= E_Constant
6245      then
6246         declare
6247            S : Entity_Id;
6248
6249         begin
6250            S := Current_Scope;
6251            while Present (S) loop
6252               if Is_Overloadable (S) then
6253                  if Comes_From_Source (S)
6254                    or else Is_Generic_Instance (S)
6255                    or else Is_Child_Unit (S)
6256                  then
6257                     exit;
6258                  else
6259                     Result := No_List;
6260                     goto Leave;
6261                  end if;
6262               end if;
6263
6264               S := Scope (S);
6265            end loop;
6266         end;
6267
6268      --  Similarly, an inlined instance body may make reference to global
6269      --  entities, but these references cannot be the proper freezing point
6270      --  for them, and in the absence of inlining freezing will take place in
6271      --  their own scope. Normally instance bodies are analyzed after the
6272      --  enclosing compilation, and everything has been frozen at the proper
6273      --  place, but with front-end inlining an instance body is compiled
6274      --  before the end of the enclosing scope, and as a result out-of-order
6275      --  freezing must be prevented.
6276
6277      elsif Front_End_Inlining
6278        and then In_Instance_Body
6279        and then Present (Scope (Test_E))
6280      then
6281         declare
6282            S : Entity_Id;
6283
6284         begin
6285            S := Scope (Test_E);
6286            while Present (S) loop
6287               if Is_Generic_Instance (S) then
6288                  exit;
6289               else
6290                  S := Scope (S);
6291               end if;
6292            end loop;
6293
6294            if No (S) then
6295               Result := No_List;
6296               goto Leave;
6297            end if;
6298         end;
6299      end if;
6300
6301      --  Add checks to detect proper initialization of scalars that may appear
6302      --  as subprogram parameters.
6303
6304      if Is_Subprogram (E) and then Check_Validity_Of_Parameters then
6305         Apply_Parameter_Validity_Checks (E);
6306      end if;
6307
6308      --  Deal with delayed aspect specifications. The analysis of the aspect
6309      --  is required to be delayed to the freeze point, thus we analyze the
6310      --  pragma or attribute definition clause in the tree at this point. We
6311      --  also analyze the aspect specification node at the freeze point when
6312      --  the aspect doesn't correspond to pragma/attribute definition clause.
6313      --  In addition, a derived type may have inherited aspects that were
6314      --  delayed in the parent, so these must also be captured now.
6315
6316      --  For a record type, we deal with the delayed aspect specifications on
6317      --  components first, which is consistent with the non-delayed case and
6318      --  makes it possible to have a single processing to detect conflicts.
6319
6320      if Is_Record_Type (E) then
6321         declare
6322            Comp : Entity_Id;
6323
6324            Rec_Pushed : Boolean := False;
6325            --  Set True if the record type E has been pushed on the scope
6326            --  stack. Needed for the analysis of delayed aspects specified
6327            --  to the components of Rec.
6328
6329         begin
6330            Comp := First_Component (E);
6331            while Present (Comp) loop
6332               if Has_Delayed_Aspects (Comp) then
6333                  if not Rec_Pushed then
6334                     Push_Scope (E);
6335                     Rec_Pushed := True;
6336
6337                     --  The visibility to the discriminants must be restored
6338                     --  in order to properly analyze the aspects.
6339
6340                     if Has_Discriminants (E) then
6341                        Install_Discriminants (E);
6342                     end if;
6343                  end if;
6344
6345                  Analyze_Aspects_At_Freeze_Point (Comp);
6346               end if;
6347
6348               Next_Component (Comp);
6349            end loop;
6350
6351            --  Pop the scope if Rec scope has been pushed on the scope stack
6352            --  during the delayed aspect analysis process.
6353
6354            if Rec_Pushed then
6355               if Has_Discriminants (E) then
6356                  Uninstall_Discriminants (E);
6357               end if;
6358
6359               Pop_Scope;
6360            end if;
6361         end;
6362      end if;
6363
6364      if Has_Delayed_Aspects (E)
6365        or else May_Inherit_Delayed_Rep_Aspects (E)
6366      then
6367         Analyze_Aspects_At_Freeze_Point (E);
6368      end if;
6369
6370      --  Here to freeze the entity
6371
6372      Set_Is_Frozen (E);
6373
6374      --  Case of entity being frozen is other than a type
6375
6376      if not Is_Type (E) then
6377
6378         --  If entity is exported or imported and does not have an external
6379         --  name, now is the time to provide the appropriate default name.
6380         --  Skip this if the entity is stubbed, since we don't need a name
6381         --  for any stubbed routine. For the case on intrinsics, if no
6382         --  external name is specified, then calls will be handled in
6383         --  Exp_Intr.Expand_Intrinsic_Call, and no name is needed. If an
6384         --  external name is provided, then Expand_Intrinsic_Call leaves
6385         --  calls in place for expansion by GIGI.
6386
6387         if (Is_Imported (E) or else Is_Exported (E))
6388           and then No (Interface_Name (E))
6389           and then Convention (E) /= Convention_Stubbed
6390           and then Convention (E) /= Convention_Intrinsic
6391         then
6392            Set_Encoded_Interface_Name
6393              (E, Get_Default_External_Name (E));
6394
6395         --  If entity is an atomic object appearing in a declaration and
6396         --  the expression is an aggregate, assign it to a temporary to
6397         --  ensure that the actual assignment is done atomically rather
6398         --  than component-wise (the assignment to the temp may be done
6399         --  component-wise, but that is harmless).
6400
6401         elsif Is_Full_Access (E)
6402           and then Nkind (Parent (E)) = N_Object_Declaration
6403           and then Present (Expression (Parent (E)))
6404           and then Nkind (Expression (Parent (E))) = N_Aggregate
6405           and then Is_Full_Access_Aggregate (Expression (Parent (E)))
6406         then
6407            null;
6408         end if;
6409
6410         --  Subprogram case
6411
6412         if Is_Subprogram (E) then
6413
6414            --  Check for needing to wrap imported subprogram
6415
6416            Wrap_Imported_Subprogram (E);
6417
6418            --  Freeze all parameter types and the return type (RM 13.14(14)).
6419            --  However skip this for internal subprograms. This is also where
6420            --  any extra formal parameters are created since we now know
6421            --  whether the subprogram will use a foreign convention.
6422
6423            --  In Ada 2012, freezing a subprogram does not always freeze the
6424            --  corresponding profile (see AI05-019). An attribute reference
6425            --  is not a freezing point of the profile. Flag Do_Freeze_Profile
6426            --  indicates whether the profile should be frozen now.
6427            --  Other constructs that should not freeze ???
6428
6429            --  This processing doesn't apply to internal entities (see below)
6430
6431            if not Is_Internal (E) and then Do_Freeze_Profile then
6432               if not Freeze_Profile (E) then
6433                  goto Leave;
6434               end if;
6435            end if;
6436
6437            --  Must freeze its parent first if it is a derived subprogram
6438
6439            if Present (Alias (E)) then
6440               Freeze_And_Append (Alias (E), N, Result);
6441            end if;
6442
6443            --  We don't freeze internal subprograms, because we don't normally
6444            --  want addition of extra formals or mechanism setting to happen
6445            --  for those. However we do pass through predefined dispatching
6446            --  cases, since extra formals may be needed in some cases, such as
6447            --  for the stream 'Input function (build-in-place formals).
6448
6449            if not Is_Internal (E)
6450              or else Is_Predefined_Dispatching_Operation (E)
6451            then
6452               Freeze_Subprogram (E);
6453            end if;
6454
6455            --  If warning on suspicious contracts then check for the case of
6456            --  a postcondition other than False for a No_Return subprogram.
6457
6458            if No_Return (E)
6459              and then Warn_On_Suspicious_Contract
6460              and then Present (Contract (E))
6461            then
6462               declare
6463                  Prag : Node_Id := Pre_Post_Conditions (Contract (E));
6464                  Exp  : Node_Id;
6465
6466               begin
6467                  while Present (Prag) loop
6468                     if Pragma_Name_Unmapped (Prag) in Name_Post
6469                                                     | Name_Postcondition
6470                                                     | Name_Refined_Post
6471                     then
6472                        Exp :=
6473                          Expression
6474                            (First (Pragma_Argument_Associations (Prag)));
6475
6476                        if Nkind (Exp) /= N_Identifier
6477                          or else Chars (Exp) /= Name_False
6478                        then
6479                           Error_Msg_NE
6480                             ("useless postcondition, & is marked "
6481                              & "No_Return?.t?", Exp, E);
6482                        end if;
6483                     end if;
6484
6485                     Prag := Next_Pragma (Prag);
6486                  end loop;
6487               end;
6488            end if;
6489
6490         --  Here for other than a subprogram or type
6491
6492         else
6493            --  If entity has a type declared in the current scope, and it is
6494            --  not a generic unit, then freeze it first.
6495
6496            if Present (Etype (E))
6497              and then Ekind (E) /= E_Generic_Function
6498              and then Within_Scope (Etype (E), Current_Scope)
6499            then
6500               Freeze_And_Append (Etype (E), N, Result);
6501
6502               --  For an object of an anonymous array type, aspects on the
6503               --  object declaration apply to the type itself. This is the
6504               --  case for Atomic_Components, Volatile_Components, and
6505               --  Independent_Components. In these cases analysis of the
6506               --  generated pragma will mark the anonymous types accordingly,
6507               --  and the object itself does not require a freeze node.
6508
6509               if Ekind (E) = E_Variable
6510                 and then Is_Itype (Etype (E))
6511                 and then Is_Array_Type (Etype (E))
6512                 and then Has_Delayed_Aspects (E)
6513               then
6514                  Set_Has_Delayed_Aspects (E, False);
6515                  Set_Has_Delayed_Freeze  (E, False);
6516                  Set_Freeze_Node (E, Empty);
6517               end if;
6518            end if;
6519
6520            --  Special processing for objects created by object declaration
6521
6522            if Nkind (Declaration_Node (E)) = N_Object_Declaration then
6523               Freeze_Object_Declaration (E);
6524            end if;
6525
6526            --  Check that a constant which has a pragma Volatile[_Components]
6527            --  or Atomic[_Components] also has a pragma Import (RM C.6(13)).
6528
6529            --  Note: Atomic[_Components] also sets Volatile[_Components]
6530
6531            if Ekind (E) = E_Constant
6532              and then (Has_Volatile_Components (E) or else Is_Volatile (E))
6533              and then not Is_Imported (E)
6534              and then not Has_Boolean_Aspect_Import (E)
6535            then
6536               --  Make sure we actually have a pragma, and have not merely
6537               --  inherited the indication from elsewhere (e.g. an address
6538               --  clause, which is not good enough in RM terms).
6539
6540               if Has_Rep_Pragma (E, Name_Atomic)
6541                    or else
6542                  Has_Rep_Pragma (E, Name_Atomic_Components)
6543               then
6544                  Error_Msg_N
6545                    ("standalone atomic constant must be " &
6546                     "imported (RM C.6(13))", E);
6547
6548               elsif Has_Rep_Pragma (E, Name_Volatile)
6549                       or else
6550                     Has_Rep_Pragma (E, Name_Volatile_Components)
6551               then
6552                  Error_Msg_N
6553                    ("standalone volatile constant must be " &
6554                     "imported (RM C.6(13))", E);
6555               end if;
6556            end if;
6557
6558            --  Static objects require special handling
6559
6560            if (Ekind (E) = E_Constant or else Ekind (E) = E_Variable)
6561              and then Is_Statically_Allocated (E)
6562            then
6563               Freeze_Static_Object (E);
6564            end if;
6565
6566            --  Remaining step is to layout objects
6567
6568            if Ekind (E) in E_Variable | E_Constant | E_Loop_Parameter
6569              or else Is_Formal (E)
6570            then
6571               Layout_Object (E);
6572            end if;
6573
6574            --  For an object that does not have delayed freezing, and whose
6575            --  initialization actions have been captured in a compound
6576            --  statement, move them back now directly within the enclosing
6577            --  statement sequence.
6578
6579            if Ekind (E) in E_Constant | E_Variable
6580              and then not Has_Delayed_Freeze (E)
6581            then
6582               Explode_Initialization_Compound_Statement (E);
6583            end if;
6584
6585            --  Do not generate a freeze node for a generic unit
6586
6587            if Is_Generic_Unit (E) then
6588               Result := No_List;
6589               goto Leave;
6590            end if;
6591         end if;
6592
6593      --  Case of a type or subtype being frozen
6594
6595      else
6596         --  Verify several SPARK legality rules related to Ghost types now
6597         --  that the type is frozen.
6598
6599         Check_Ghost_Type (E);
6600
6601         --  We used to check here that a full type must have preelaborable
6602         --  initialization if it completes a private type specified with
6603         --  pragma Preelaborable_Initialization, but that missed cases where
6604         --  the types occur within a generic package, since the freezing
6605         --  that occurs within a containing scope generally skips traversal
6606         --  of a generic unit's declarations (those will be frozen within
6607         --  instances). This check was moved to Analyze_Package_Specification.
6608
6609         --  The type may be defined in a generic unit. This can occur when
6610         --  freezing a generic function that returns the type (which is
6611         --  defined in a parent unit). It is clearly meaningless to freeze
6612         --  this type. However, if it is a subtype, its size may be determi-
6613         --  nable and used in subsequent checks, so might as well try to
6614         --  compute it.
6615
6616         --  In Ada 2012, Freeze_Entities is also used in the front end to
6617         --  trigger the analysis of aspect expressions, so in this case we
6618         --  want to continue the freezing process.
6619
6620         --  Is_Generic_Unit (Scope (E)) is dubious here, do we want instead
6621         --  In_Generic_Scope (E)???
6622
6623         if Present (Scope (E))
6624           and then Is_Generic_Unit (Scope (E))
6625           and then
6626             (not Has_Predicates (E)
6627               and then not Has_Delayed_Freeze (E))
6628         then
6629            Check_Compile_Time_Size (E);
6630            Result := No_List;
6631            goto Leave;
6632         end if;
6633
6634         --  Check for error of Type_Invariant'Class applied to an untagged
6635         --  type (check delayed to freeze time when full type is available).
6636
6637         declare
6638            Prag : constant Node_Id := Get_Pragma (E, Pragma_Invariant);
6639         begin
6640            if Present (Prag)
6641              and then Class_Present (Prag)
6642              and then not Is_Tagged_Type (E)
6643            then
6644               Error_Msg_NE
6645                 ("Type_Invariant''Class cannot be specified for &", Prag, E);
6646               Error_Msg_N
6647                 ("\can only be specified for a tagged type", Prag);
6648            end if;
6649         end;
6650
6651         --  Deal with special cases of freezing for subtype
6652
6653         if E /= Base_Type (E) then
6654
6655            --  Before we do anything else, a specific test for the case of a
6656            --  size given for an array where the array would need to be packed
6657            --  in order for the size to be honored, but is not. This is the
6658            --  case where implicit packing may apply. The reason we do this so
6659            --  early is that, if we have implicit packing, the layout of the
6660            --  base type is affected, so we must do this before we freeze the
6661            --  base type.
6662
6663            --  We could do this processing only if implicit packing is enabled
6664            --  since in all other cases, the error would be caught by the back
6665            --  end. However, we choose to do the check even if we do not have
6666            --  implicit packing enabled, since this allows us to give a more
6667            --  useful error message (advising use of pragma Implicit_Packing
6668            --  or pragma Pack).
6669
6670            if Is_Array_Type (E) then
6671               declare
6672                  Ctyp : constant Entity_Id := Component_Type (E);
6673                  Rsiz : constant Uint :=
6674                    (if Known_RM_Size (Ctyp) then RM_Size (Ctyp) else Uint_0);
6675                  SZ   : constant Node_Id   := Size_Clause (E);
6676                  Btyp : constant Entity_Id := Base_Type (E);
6677
6678                  Lo   : Node_Id;
6679                  Hi   : Node_Id;
6680                  Indx : Node_Id;
6681
6682                  Dim       : Uint;
6683                  Num_Elmts : Uint := Uint_1;
6684                  --  Number of elements in array
6685
6686               begin
6687                  --  Check enabling conditions. These are straightforward
6688                  --  except for the test for a limited composite type. This
6689                  --  eliminates the rare case of a array of limited components
6690                  --  where there are issues of whether or not we can go ahead
6691                  --  and pack the array (since we can't freely pack and unpack
6692                  --  arrays if they are limited).
6693
6694                  --  Note that we check the root type explicitly because the
6695                  --  whole point is we are doing this test before we have had
6696                  --  a chance to freeze the base type (and it is that freeze
6697                  --  action that causes stuff to be inherited).
6698
6699                  --  The conditions on the size are identical to those used in
6700                  --  Freeze_Array_Type to set the Is_Packed flag.
6701
6702                  if Has_Size_Clause (E)
6703                    and then Known_Static_RM_Size (E)
6704                    and then not Is_Packed (E)
6705                    and then not Has_Pragma_Pack (E)
6706                    and then not Has_Component_Size_Clause (E)
6707                    and then Known_Static_RM_Size (Ctyp)
6708                    and then Rsiz <= System_Max_Integer_Size
6709                    and then not (Addressable (Rsiz)
6710                                   and then Known_Static_Esize (Ctyp)
6711                                   and then Esize (Ctyp) = Rsiz)
6712                    and then not (Rsiz mod System_Storage_Unit = 0
6713                                   and then Is_Composite_Type (Ctyp))
6714                    and then not Is_Limited_Composite (E)
6715                    and then not Is_Packed (Root_Type (E))
6716                    and then not Has_Component_Size_Clause (Root_Type (E))
6717                    and then not (CodePeer_Mode or GNATprove_Mode)
6718                  then
6719                     --  Compute number of elements in array
6720
6721                     Indx := First_Index (E);
6722                     while Present (Indx) loop
6723                        Get_Index_Bounds (Indx, Lo, Hi);
6724
6725                        if not (Compile_Time_Known_Value (Lo)
6726                                  and then
6727                                Compile_Time_Known_Value (Hi))
6728                        then
6729                           goto No_Implicit_Packing;
6730                        end if;
6731
6732                        Dim := Expr_Value (Hi) - Expr_Value (Lo) + 1;
6733
6734                        if Dim > Uint_0 then
6735                           Num_Elmts := Num_Elmts * Dim;
6736                        else
6737                           Num_Elmts := Uint_0;
6738                        end if;
6739
6740                        Next_Index (Indx);
6741                     end loop;
6742
6743                     --  What we are looking for here is the situation where
6744                     --  the RM_Size given would be exactly right if there was
6745                     --  a pragma Pack, resulting in the component size being
6746                     --  the RM_Size of the component type.
6747
6748                     if RM_Size (E) = Num_Elmts * Rsiz then
6749
6750                        --  For implicit packing mode, just set the component
6751                        --  size and Freeze_Array_Type will do the rest.
6752
6753                        if Implicit_Packing then
6754                           Set_Component_Size (Btyp, Rsiz);
6755
6756                        --  Otherwise give an error message, except that if the
6757                        --  specified Size is zero, there is no need for pragma
6758                        --  Pack. Note that size zero is not considered
6759                        --  Addressable.
6760
6761                        elsif RM_Size (E) /= Uint_0 then
6762                           Error_Msg_NE
6763                             ("size given for& too small", SZ, E);
6764                           Error_Msg_N -- CODEFIX
6765                             ("\use explicit pragma Pack or use pragma "
6766                              & "Implicit_Packing", SZ);
6767                        end if;
6768                     end if;
6769                  end if;
6770               end;
6771            end if;
6772
6773            <<No_Implicit_Packing>>
6774
6775            --  If ancestor subtype present, freeze that first. Note that this
6776            --  will also get the base type frozen. Need RM reference ???
6777
6778            Atype := Ancestor_Subtype (E);
6779
6780            if Present (Atype) then
6781               Freeze_And_Append (Atype, N, Result);
6782
6783            --  No ancestor subtype present
6784
6785            else
6786               --  See if we have a nearest ancestor that has a predicate.
6787               --  That catches the case of derived type with a predicate.
6788               --  Need RM reference here ???
6789
6790               Atype := Nearest_Ancestor (E);
6791
6792               if Present (Atype) and then Has_Predicates (Atype) then
6793                  Freeze_And_Append (Atype, N, Result);
6794               end if;
6795
6796               --  Freeze base type before freezing the entity (RM 13.14(15))
6797
6798               if E /= Base_Type (E) then
6799                  Freeze_And_Append (Base_Type (E), N, Result);
6800               end if;
6801            end if;
6802
6803            --  A subtype inherits all the type-related representation aspects
6804            --  from its parents (RM 13.1(8)).
6805
6806            Inherit_Aspects_At_Freeze_Point (E);
6807
6808         --  For a derived type, freeze its parent type first (RM 13.14(15))
6809
6810         elsif Is_Derived_Type (E) then
6811            Freeze_And_Append (Etype (E), N, Result);
6812            Freeze_And_Append (First_Subtype (Etype (E)), N, Result);
6813
6814            --  A derived type inherits each type-related representation aspect
6815            --  of its parent type that was directly specified before the
6816            --  declaration of the derived type (RM 13.1(15)).
6817
6818            Inherit_Aspects_At_Freeze_Point (E);
6819         end if;
6820
6821         --  Case of array type
6822
6823         if Is_Array_Type (E) then
6824            Freeze_Array_Type (E);
6825         end if;
6826
6827         --  Check for incompatible size and alignment for array/record type
6828
6829         if Warn_On_Size_Alignment
6830           and then (Is_Array_Type (E) or else Is_Record_Type (E))
6831           and then Has_Size_Clause (E)
6832           and then Has_Alignment_Clause (E)
6833
6834           --  If explicit Object_Size clause given assume that the programmer
6835           --  knows what he is doing, and expects the compiler behavior.
6836
6837           and then not Has_Object_Size_Clause (E)
6838
6839           --  It does not really make sense to warn for the minimum alignment
6840           --  since the programmer could not get rid of the warning.
6841
6842           and then Alignment (E) > 1
6843
6844           --  Check for size not a multiple of alignment
6845
6846           and then RM_Size (E) mod (Alignment (E) * System_Storage_Unit) /= 0
6847         then
6848            declare
6849               SC    : constant Node_Id := Size_Clause (E);
6850               AC    : constant Node_Id := Alignment_Clause (E);
6851               Loc   : Node_Id;
6852               Abits : constant Uint := Alignment (E) * System_Storage_Unit;
6853
6854            begin
6855               if Present (SC) and then Present (AC) then
6856
6857                  --  Give a warning
6858
6859                  if Sloc (SC) > Sloc (AC) then
6860                     Loc := SC;
6861                     Error_Msg_NE
6862                       ("?.z?size is not a multiple of alignment for &",
6863                        Loc, E);
6864                     Error_Msg_Sloc := Sloc (AC);
6865                     Error_Msg_Uint_1 := Alignment (E);
6866                     Error_Msg_N ("\?.z?alignment of ^ specified #", Loc);
6867
6868                  else
6869                     Loc := AC;
6870                     Error_Msg_NE
6871                       ("?.z?size is not a multiple of alignment for &",
6872                        Loc, E);
6873                     Error_Msg_Sloc := Sloc (SC);
6874                     Error_Msg_Uint_1 := RM_Size (E);
6875                     Error_Msg_N ("\?.z?size of ^ specified #", Loc);
6876                  end if;
6877
6878                  Error_Msg_Uint_1 := ((RM_Size (E) / Abits) + 1) * Abits;
6879                  Error_Msg_N ("\?.z?Object_Size will be increased to ^", Loc);
6880               end if;
6881            end;
6882         end if;
6883
6884         --  For a class-wide type, the corresponding specific type is
6885         --  frozen as well (RM 13.14(15))
6886
6887         if Is_Class_Wide_Type (E) then
6888            Freeze_And_Append (Root_Type (E), N, Result);
6889
6890            --  If the base type of the class-wide type is still incomplete,
6891            --  the class-wide remains unfrozen as well. This is legal when
6892            --  E is the formal of a primitive operation of some other type
6893            --  which is being frozen.
6894
6895            if not Is_Frozen (Root_Type (E)) then
6896               Set_Is_Frozen (E, False);
6897               goto Leave;
6898            end if;
6899
6900            --  The equivalent type associated with a class-wide subtype needs
6901            --  to be frozen to ensure that its layout is done.
6902
6903            if Ekind (E) = E_Class_Wide_Subtype
6904              and then Present (Equivalent_Type (E))
6905            then
6906               Freeze_And_Append (Equivalent_Type (E), N, Result);
6907            end if;
6908
6909            --  Generate an itype reference for a library-level class-wide type
6910            --  at the freeze point. Otherwise the first explicit reference to
6911            --  the type may appear in an inner scope which will be rejected by
6912            --  the back-end.
6913
6914            if Is_Itype (E)
6915              and then Is_Compilation_Unit (Scope (E))
6916            then
6917               declare
6918                  Ref : constant Node_Id := Make_Itype_Reference (Loc);
6919
6920               begin
6921                  Set_Itype (Ref, E);
6922
6923                  --  From a gigi point of view, a class-wide subtype derives
6924                  --  from its record equivalent type. As a result, the itype
6925                  --  reference must appear after the freeze node of the
6926                  --  equivalent type or gigi will reject the reference.
6927
6928                  if Ekind (E) = E_Class_Wide_Subtype
6929                    and then Present (Equivalent_Type (E))
6930                  then
6931                     Insert_After (Freeze_Node (Equivalent_Type (E)), Ref);
6932                  else
6933                     Add_To_Result (Ref);
6934                  end if;
6935               end;
6936            end if;
6937
6938         --  For a record type or record subtype, freeze all component types
6939         --  (RM 13.14(15)). We test for E_Record_(sub)Type here, rather than
6940         --  using Is_Record_Type, because we don't want to attempt the freeze
6941         --  for the case of a private type with record extension (we will do
6942         --  that later when the full type is frozen).
6943
6944         elsif Ekind (E) in E_Record_Type | E_Record_Subtype then
6945            if not In_Generic_Scope (E) then
6946               Freeze_Record_Type (E);
6947            end if;
6948
6949            --  Report a warning if a discriminated record base type has a
6950            --  convention with language C or C++ applied to it. This check is
6951            --  done even within generic scopes (but not in instantiations),
6952            --  which is why we don't do it as part of Freeze_Record_Type.
6953
6954            Check_Suspicious_Convention (E);
6955
6956         --  For a concurrent type, freeze corresponding record type. This does
6957         --  not correspond to any specific rule in the RM, but the record type
6958         --  is essentially part of the concurrent type. Also freeze all local
6959         --  entities. This includes record types created for entry parameter
6960         --  blocks and whatever local entities may appear in the private part.
6961
6962         elsif Is_Concurrent_Type (E) then
6963            if Present (Corresponding_Record_Type (E)) then
6964               Freeze_And_Append (Corresponding_Record_Type (E), N, Result);
6965            end if;
6966
6967            Comp := First_Entity (E);
6968            while Present (Comp) loop
6969               if Is_Type (Comp) then
6970                  Freeze_And_Append (Comp, N, Result);
6971
6972               elsif (Ekind (Comp)) /= E_Function then
6973
6974                  --  The guard on the presence of the Etype seems to be needed
6975                  --  for some CodePeer (-gnatcC) cases, but not clear why???
6976
6977                  if Present (Etype (Comp)) then
6978                     if Is_Itype (Etype (Comp))
6979                       and then Underlying_Type (Scope (Etype (Comp))) = E
6980                     then
6981                        Undelay_Type (Etype (Comp));
6982                     end if;
6983
6984                     Freeze_And_Append (Etype (Comp), N, Result);
6985                  end if;
6986               end if;
6987
6988               Next_Entity (Comp);
6989            end loop;
6990
6991         --  Private types are required to point to the same freeze node as
6992         --  their corresponding full views. The freeze node itself has to
6993         --  point to the partial view of the entity (because from the partial
6994         --  view, we can retrieve the full view, but not the reverse).
6995         --  However, in order to freeze correctly, we need to freeze the full
6996         --  view. If we are freezing at the end of a scope (or within the
6997         --  scope) of the private type, the partial and full views will have
6998         --  been swapped, the full view appears first in the entity chain and
6999         --  the swapping mechanism ensures that the pointers are properly set
7000         --  (on scope exit).
7001
7002         --  If we encounter the partial view before the full view (e.g. when
7003         --  freezing from another scope), we freeze the full view, and then
7004         --  set the pointers appropriately since we cannot rely on swapping to
7005         --  fix things up (subtypes in an outer scope might not get swapped).
7006
7007         --  If the full view is itself private, the above requirements apply
7008         --  to the underlying full view instead of the full view. But there is
7009         --  no swapping mechanism for the underlying full view so we need to
7010         --  set the pointers appropriately in both cases.
7011
7012         elsif Is_Incomplete_Or_Private_Type (E)
7013           and then not Is_Generic_Type (E)
7014         then
7015            --  The construction of the dispatch table associated with library
7016            --  level tagged types forces freezing of all the primitives of the
7017            --  type, which may cause premature freezing of the partial view.
7018            --  For example:
7019
7020            --     package Pkg is
7021            --        type T is tagged private;
7022            --        type DT is new T with private;
7023            --        procedure Prim (X : in out T; Y : in out DT'Class);
7024            --     private
7025            --        type T is tagged null record;
7026            --        Obj : T;
7027            --        type DT is new T with null record;
7028            --     end;
7029
7030            --  In this case the type will be frozen later by the usual
7031            --  mechanism: an object declaration, an instantiation, or the
7032            --  end of a declarative part.
7033
7034            if Is_Library_Level_Tagged_Type (E)
7035              and then not Present (Full_View (E))
7036            then
7037               Set_Is_Frozen (E, False);
7038               goto Leave;
7039
7040            --  Case of full view present
7041
7042            elsif Present (Full_View (E)) then
7043
7044               --  If full view has already been frozen, then no further
7045               --  processing is required
7046
7047               if Is_Frozen (Full_View (E)) then
7048                  Set_Has_Delayed_Freeze (E, False);
7049                  Set_Freeze_Node (E, Empty);
7050
7051               --  Otherwise freeze full view and patch the pointers so that
7052               --  the freeze node will elaborate both views in the back end.
7053               --  However, if full view is itself private, freeze underlying
7054               --  full view instead and patch the pointers so that the freeze
7055               --  node will elaborate the three views in the back end.
7056
7057               else
7058                  declare
7059                     Full : Entity_Id := Full_View (E);
7060
7061                  begin
7062                     if Is_Private_Type (Full)
7063                       and then Present (Underlying_Full_View (Full))
7064                     then
7065                        Full := Underlying_Full_View (Full);
7066                     end if;
7067
7068                     Freeze_And_Append (Full, N, Result);
7069
7070                     if Full /= Full_View (E)
7071                       and then Has_Delayed_Freeze (Full_View (E))
7072                     then
7073                        F_Node := Freeze_Node (Full);
7074
7075                        if Present (F_Node) then
7076                           Inherit_Freeze_Node
7077                             (Fnod => F_Node, Typ => Full_View (E));
7078                        else
7079                           Set_Has_Delayed_Freeze (Full_View (E), False);
7080                           Set_Freeze_Node (Full_View (E), Empty);
7081                        end if;
7082                     end if;
7083
7084                     if Has_Delayed_Freeze (E) then
7085                        F_Node := Freeze_Node (Full_View (E));
7086
7087                        if Present (F_Node) then
7088                           Inherit_Freeze_Node (Fnod => F_Node, Typ => E);
7089                        else
7090                           --  {Incomplete,Private}_Subtypes with Full_Views
7091                           --  constrained by discriminants.
7092
7093                           Set_Has_Delayed_Freeze (E, False);
7094                           Set_Freeze_Node (E, Empty);
7095                        end if;
7096                     end if;
7097                  end;
7098               end if;
7099
7100               Check_Debug_Info_Needed (E);
7101
7102               --  AI-117 requires that the convention of a partial view be the
7103               --  same as the convention of the full view. Note that this is a
7104               --  recognized breach of privacy, but it's essential for logical
7105               --  consistency of representation, and the lack of a rule in
7106               --  RM95 was an oversight.
7107
7108               Set_Convention (E, Convention (Full_View (E)));
7109
7110               Set_Size_Known_At_Compile_Time (E,
7111                 Size_Known_At_Compile_Time (Full_View (E)));
7112
7113               --  Size information is copied from the full view to the
7114               --  incomplete or private view for consistency.
7115
7116               --  We skip this is the full view is not a type. This is very
7117               --  strange of course, and can only happen as a result of
7118               --  certain illegalities, such as a premature attempt to derive
7119               --  from an incomplete type.
7120
7121               if Is_Type (Full_View (E)) then
7122                  Set_Size_Info (E, Full_View (E));
7123                  Copy_RM_Size (To => E, From => Full_View (E));
7124               end if;
7125
7126               goto Leave;
7127
7128            --  Case of underlying full view present
7129
7130            elsif Is_Private_Type (E)
7131              and then Present (Underlying_Full_View (E))
7132            then
7133               if not Is_Frozen (Underlying_Full_View (E)) then
7134                  Freeze_And_Append (Underlying_Full_View (E), N, Result);
7135               end if;
7136
7137               --  Patch the pointers so that the freeze node will elaborate
7138               --  both views in the back end.
7139
7140               if Has_Delayed_Freeze (E) then
7141                  F_Node := Freeze_Node (Underlying_Full_View (E));
7142
7143                  if Present (F_Node) then
7144                     Inherit_Freeze_Node
7145                       (Fnod => F_Node,
7146                        Typ  => E);
7147                  else
7148                     Set_Has_Delayed_Freeze (E, False);
7149                     Set_Freeze_Node (E, Empty);
7150                  end if;
7151               end if;
7152
7153               Check_Debug_Info_Needed (E);
7154
7155               goto Leave;
7156
7157            --  Case of no full view present. If entity is subtype or derived,
7158            --  it is safe to freeze, correctness depends on the frozen status
7159            --  of parent. Otherwise it is either premature usage, or a Taft
7160            --  amendment type, so diagnosis is at the point of use and the
7161            --  type might be frozen later.
7162
7163            elsif E /= Base_Type (E) then
7164               declare
7165                  Btyp : constant Entity_Id := Base_Type (E);
7166
7167               begin
7168                  --  However, if the base type is itself private and has no
7169                  --  (underlying) full view either, wait until the full type
7170                  --  declaration is seen and all the full views are created.
7171
7172                  if Is_Private_Type (Btyp)
7173                    and then No (Full_View (Btyp))
7174                    and then No (Underlying_Full_View (Btyp))
7175                    and then Has_Delayed_Freeze (Btyp)
7176                    and then No (Freeze_Node (Btyp))
7177                  then
7178                     Set_Is_Frozen (E, False);
7179                     Result := No_List;
7180                     goto Leave;
7181                  end if;
7182               end;
7183
7184            elsif Is_Derived_Type (E) then
7185               null;
7186
7187            else
7188               Set_Is_Frozen (E, False);
7189               Result := No_List;
7190               goto Leave;
7191            end if;
7192
7193         --  For access subprogram, freeze types of all formals, the return
7194         --  type was already frozen, since it is the Etype of the function.
7195         --  Formal types can be tagged Taft amendment types, but otherwise
7196         --  they cannot be incomplete.
7197
7198         elsif Ekind (E) = E_Subprogram_Type then
7199            Formal := First_Formal (E);
7200            while Present (Formal) loop
7201               if Ekind (Etype (Formal)) = E_Incomplete_Type
7202                 and then No (Full_View (Etype (Formal)))
7203               then
7204                  if Is_Tagged_Type (Etype (Formal)) then
7205                     null;
7206
7207                  --  AI05-151: Incomplete types are allowed in access to
7208                  --  subprogram specifications.
7209
7210                  elsif Ada_Version < Ada_2012 then
7211                     Error_Msg_NE
7212                       ("invalid use of incomplete type&", E, Etype (Formal));
7213                  end if;
7214               end if;
7215
7216               Freeze_And_Append (Etype (Formal), N, Result);
7217               Next_Formal (Formal);
7218            end loop;
7219
7220            Freeze_Subprogram (E);
7221
7222         --  For access to a protected subprogram, freeze the equivalent type
7223         --  (however this is not set if we are not generating code or if this
7224         --  is an anonymous type used just for resolution).
7225
7226         elsif Is_Access_Protected_Subprogram_Type (E) then
7227            if Present (Equivalent_Type (E)) then
7228               Freeze_And_Append (Equivalent_Type (E), N, Result);
7229            end if;
7230         end if;
7231
7232         --  Generic types are never seen by the back-end, and are also not
7233         --  processed by the expander (since the expander is turned off for
7234         --  generic processing), so we never need freeze nodes for them.
7235
7236         if Is_Generic_Type (E) then
7237            goto Leave;
7238         end if;
7239
7240         --  Some special processing for non-generic types to complete
7241         --  representation details not known till the freeze point.
7242
7243         if Is_Fixed_Point_Type (E) then
7244            Freeze_Fixed_Point_Type (E);
7245
7246         elsif Is_Enumeration_Type (E) then
7247            Freeze_Enumeration_Type (E);
7248
7249         elsif Is_Integer_Type (E) then
7250            Adjust_Esize_For_Alignment (E);
7251
7252            if Is_Modular_Integer_Type (E)
7253              and then Warn_On_Suspicious_Modulus_Value
7254            then
7255               Check_Suspicious_Modulus (E);
7256            end if;
7257
7258         --  The pool applies to named and anonymous access types, but not
7259         --  to subprogram and to internal types generated for 'Access
7260         --  references.
7261
7262         elsif Is_Access_Object_Type (E)
7263           and then Ekind (E) /= E_Access_Attribute_Type
7264         then
7265            --  If a pragma Default_Storage_Pool applies, and this type has no
7266            --  Storage_Pool or Storage_Size clause (which must have occurred
7267            --  before the freezing point), then use the default. This applies
7268            --  only to base types.
7269
7270            --  None of this applies to access to subprograms, for which there
7271            --  are clearly no pools.
7272
7273            if Present (Default_Pool)
7274              and then Is_Base_Type (E)
7275              and then not Has_Storage_Size_Clause (E)
7276              and then No (Associated_Storage_Pool (E))
7277            then
7278               --  Case of pragma Default_Storage_Pool (null)
7279
7280               if Nkind (Default_Pool) = N_Null then
7281                  Set_No_Pool_Assigned (E);
7282
7283               --  Case of pragma Default_Storage_Pool (Standard)
7284
7285               elsif Entity (Default_Pool) = Standard_Standard then
7286                  Set_Associated_Storage_Pool (E, RTE (RE_Global_Pool_Object));
7287
7288               --  Case of pragma Default_Storage_Pool (storage_pool_NAME)
7289
7290               else
7291                  Set_Associated_Storage_Pool (E, Entity (Default_Pool));
7292               end if;
7293            end if;
7294
7295            --  Check restriction for standard storage pool
7296
7297            if No (Associated_Storage_Pool (E)) then
7298               Check_Restriction (No_Standard_Storage_Pools, E);
7299            end if;
7300
7301            --  Deal with error message for pure access type. This is not an
7302            --  error in Ada 2005 if there is no pool (see AI-366).
7303
7304            if Is_Pure_Unit_Access_Type (E)
7305              and then (Ada_Version < Ada_2005
7306                         or else not No_Pool_Assigned (E))
7307              and then not Is_Generic_Unit (Scope (E))
7308            then
7309               Error_Msg_N ("named access type not allowed in pure unit", E);
7310
7311               if Ada_Version >= Ada_2005 then
7312                  Error_Msg_N
7313                    ("\would be legal if Storage_Size of 0 given??", E);
7314
7315               elsif No_Pool_Assigned (E) then
7316                  Error_Msg_N
7317                    ("\would be legal in Ada 2005??", E);
7318
7319               else
7320                  Error_Msg_N
7321                    ("\would be legal in Ada 2005 if "
7322                     & "Storage_Size of 0 given??", E);
7323               end if;
7324            end if;
7325         end if;
7326
7327         --  Case of composite types
7328
7329         if Is_Composite_Type (E) then
7330
7331            --  AI-117 requires that all new primitives of a tagged type must
7332            --  inherit the convention of the full view of the type. Inherited
7333            --  and overriding operations are defined to inherit the convention
7334            --  of their parent or overridden subprogram (also specified in
7335            --  AI-117), which will have occurred earlier (in Derive_Subprogram
7336            --  and New_Overloaded_Entity). Here we set the convention of
7337            --  primitives that are still convention Ada, which will ensure
7338            --  that any new primitives inherit the type's convention. Class-
7339            --  wide types can have a foreign convention inherited from their
7340            --  specific type, but are excluded from this since they don't have
7341            --  any associated primitives.
7342
7343            if Is_Tagged_Type (E)
7344              and then not Is_Class_Wide_Type (E)
7345              and then Convention (E) /= Convention_Ada
7346            then
7347               declare
7348                  Prim_List : constant Elist_Id := Primitive_Operations (E);
7349                  Prim      : Elmt_Id;
7350
7351               begin
7352                  Prim := First_Elmt (Prim_List);
7353                  while Present (Prim) loop
7354                     if Convention (Node (Prim)) = Convention_Ada then
7355                        Set_Convention (Node (Prim), Convention (E));
7356                     end if;
7357
7358                     Next_Elmt (Prim);
7359                  end loop;
7360               end;
7361            end if;
7362
7363            --  If the type is a simple storage pool type, then this is where
7364            --  we attempt to locate and validate its Allocate, Deallocate, and
7365            --  Storage_Size operations (the first is required, and the latter
7366            --  two are optional). We also verify that the full type for a
7367            --  private type is allowed to be a simple storage pool type.
7368
7369            if Present (Get_Rep_Pragma (E, Name_Simple_Storage_Pool_Type))
7370              and then (Is_Base_Type (E) or else Has_Private_Declaration (E))
7371            then
7372               --  If the type is marked Has_Private_Declaration, then this is
7373               --  a full type for a private type that was specified with the
7374               --  pragma Simple_Storage_Pool_Type, and here we ensure that the
7375               --  pragma is allowed for the full type (for example, it can't
7376               --  be an array type, or a nonlimited record type).
7377
7378               if Has_Private_Declaration (E) then
7379                  if (not Is_Record_Type (E) or else not Is_Limited_View (E))
7380                    and then not Is_Private_Type (E)
7381                  then
7382                     Error_Msg_Name_1 := Name_Simple_Storage_Pool_Type;
7383                     Error_Msg_N
7384                       ("pragma% can only apply to full type that is an " &
7385                        "explicitly limited type", E);
7386                  end if;
7387               end if;
7388
7389               Validate_Simple_Pool_Ops : declare
7390                  Pool_Type    : Entity_Id renames E;
7391                  Address_Type : constant Entity_Id := RTE (RE_Address);
7392                  Stg_Cnt_Type : constant Entity_Id := RTE (RE_Storage_Count);
7393
7394                  procedure Validate_Simple_Pool_Op_Formal
7395                    (Pool_Op        : Entity_Id;
7396                     Pool_Op_Formal : in out Entity_Id;
7397                     Expected_Mode  : Formal_Kind;
7398                     Expected_Type  : Entity_Id;
7399                     Formal_Name    : String;
7400                     OK_Formal      : in out Boolean);
7401                  --  Validate one formal Pool_Op_Formal of the candidate pool
7402                  --  operation Pool_Op. The formal must be of Expected_Type
7403                  --  and have mode Expected_Mode. OK_Formal will be set to
7404                  --  False if the formal doesn't match. If OK_Formal is False
7405                  --  on entry, then the formal will effectively be ignored
7406                  --  (because validation of the pool op has already failed).
7407                  --  Upon return, Pool_Op_Formal will be updated to the next
7408                  --  formal, if any.
7409
7410                  procedure Validate_Simple_Pool_Operation
7411                    (Op_Name : Name_Id);
7412                  --  Search for and validate a simple pool operation with the
7413                  --  name Op_Name. If the name is Allocate, then there must be
7414                  --  exactly one such primitive operation for the simple pool
7415                  --  type. If the name is Deallocate or Storage_Size, then
7416                  --  there can be at most one such primitive operation. The
7417                  --  profile of the located primitive must conform to what
7418                  --  is expected for each operation.
7419
7420                  ------------------------------------
7421                  -- Validate_Simple_Pool_Op_Formal --
7422                  ------------------------------------
7423
7424                  procedure Validate_Simple_Pool_Op_Formal
7425                    (Pool_Op        : Entity_Id;
7426                     Pool_Op_Formal : in out Entity_Id;
7427                     Expected_Mode  : Formal_Kind;
7428                     Expected_Type  : Entity_Id;
7429                     Formal_Name    : String;
7430                     OK_Formal      : in out Boolean)
7431                  is
7432                  begin
7433                     --  If OK_Formal is False on entry, then simply ignore
7434                     --  the formal, because an earlier formal has already
7435                     --  been flagged.
7436
7437                     if not OK_Formal then
7438                        return;
7439
7440                     --  If no formal is passed in, then issue an error for a
7441                     --  missing formal.
7442
7443                     elsif not Present (Pool_Op_Formal) then
7444                        Error_Msg_NE
7445                          ("simple storage pool op missing formal " &
7446                           Formal_Name & " of type&", Pool_Op, Expected_Type);
7447                        OK_Formal := False;
7448
7449                        return;
7450                     end if;
7451
7452                     if Etype (Pool_Op_Formal) /= Expected_Type then
7453
7454                        --  If the pool type was expected for this formal, then
7455                        --  this will not be considered a candidate operation
7456                        --  for the simple pool, so we unset OK_Formal so that
7457                        --  the op and any later formals will be ignored.
7458
7459                        if Expected_Type = Pool_Type then
7460                           OK_Formal := False;
7461
7462                           return;
7463
7464                        else
7465                           Error_Msg_NE
7466                             ("wrong type for formal " & Formal_Name &
7467                              " of simple storage pool op; expected type&",
7468                              Pool_Op_Formal, Expected_Type);
7469                        end if;
7470                     end if;
7471
7472                     --  Issue error if formal's mode is not the expected one
7473
7474                     if Ekind (Pool_Op_Formal) /= Expected_Mode then
7475                        Error_Msg_N
7476                          ("wrong mode for formal of simple storage pool op",
7477                           Pool_Op_Formal);
7478                     end if;
7479
7480                     --  Advance to the next formal
7481
7482                     Next_Formal (Pool_Op_Formal);
7483                  end Validate_Simple_Pool_Op_Formal;
7484
7485                  ------------------------------------
7486                  -- Validate_Simple_Pool_Operation --
7487                  ------------------------------------
7488
7489                  procedure Validate_Simple_Pool_Operation
7490                    (Op_Name : Name_Id)
7491                  is
7492                     Op       : Entity_Id;
7493                     Found_Op : Entity_Id := Empty;
7494                     Formal   : Entity_Id;
7495                     Is_OK    : Boolean;
7496
7497                  begin
7498                     pragma Assert
7499                       (Op_Name in Name_Allocate
7500                                 | Name_Deallocate
7501                                 | Name_Storage_Size);
7502
7503                     Error_Msg_Name_1 := Op_Name;
7504
7505                     --  For each homonym declared immediately in the scope
7506                     --  of the simple storage pool type, determine whether
7507                     --  the homonym is an operation of the pool type, and,
7508                     --  if so, check that its profile is as expected for
7509                     --  a simple pool operation of that name.
7510
7511                     Op := Get_Name_Entity_Id (Op_Name);
7512                     while Present (Op) loop
7513                        if Ekind (Op) in E_Function | E_Procedure
7514                          and then Scope (Op) = Current_Scope
7515                        then
7516                           Formal := First_Entity (Op);
7517
7518                           Is_OK := True;
7519
7520                           --  The first parameter must be of the pool type
7521                           --  in order for the operation to qualify.
7522
7523                           if Op_Name = Name_Storage_Size then
7524                              Validate_Simple_Pool_Op_Formal
7525                                (Op, Formal, E_In_Parameter, Pool_Type,
7526                                 "Pool", Is_OK);
7527                           else
7528                              Validate_Simple_Pool_Op_Formal
7529                                (Op, Formal, E_In_Out_Parameter, Pool_Type,
7530                                 "Pool", Is_OK);
7531                           end if;
7532
7533                           --  If another operation with this name has already
7534                           --  been located for the type, then flag an error,
7535                           --  since we only allow the type to have a single
7536                           --  such primitive.
7537
7538                           if Present (Found_Op) and then Is_OK then
7539                              Error_Msg_NE
7540                                ("only one % operation allowed for " &
7541                                 "simple storage pool type&", Op, Pool_Type);
7542                           end if;
7543
7544                           --  In the case of Allocate and Deallocate, a formal
7545                           --  of type System.Address is required.
7546
7547                           if Op_Name = Name_Allocate then
7548                              Validate_Simple_Pool_Op_Formal
7549                                (Op, Formal, E_Out_Parameter,
7550                                  Address_Type, "Storage_Address", Is_OK);
7551
7552                           elsif Op_Name = Name_Deallocate then
7553                              Validate_Simple_Pool_Op_Formal
7554                                (Op, Formal, E_In_Parameter,
7555                                 Address_Type, "Storage_Address", Is_OK);
7556                           end if;
7557
7558                           --  In the case of Allocate and Deallocate, formals
7559                           --  of type Storage_Count are required as the third
7560                           --  and fourth parameters.
7561
7562                           if Op_Name /= Name_Storage_Size then
7563                              Validate_Simple_Pool_Op_Formal
7564                                (Op, Formal, E_In_Parameter,
7565                                 Stg_Cnt_Type, "Size_In_Storage_Units", Is_OK);
7566                              Validate_Simple_Pool_Op_Formal
7567                                (Op, Formal, E_In_Parameter,
7568                                 Stg_Cnt_Type, "Alignment", Is_OK);
7569                           end if;
7570
7571                           --  If no mismatched formals have been found (Is_OK)
7572                           --  and no excess formals are present, then this
7573                           --  operation has been validated, so record it.
7574
7575                           if not Present (Formal) and then Is_OK then
7576                              Found_Op := Op;
7577                           end if;
7578                        end if;
7579
7580                        Op := Homonym (Op);
7581                     end loop;
7582
7583                     --  There must be a valid Allocate operation for the type,
7584                     --  so issue an error if none was found.
7585
7586                     if Op_Name = Name_Allocate
7587                       and then not Present (Found_Op)
7588                     then
7589                        Error_Msg_N ("missing % operation for simple " &
7590                                     "storage pool type", Pool_Type);
7591
7592                     elsif Present (Found_Op) then
7593
7594                        --  Simple pool operations can't be abstract
7595
7596                        if Is_Abstract_Subprogram (Found_Op) then
7597                           Error_Msg_N
7598                             ("simple storage pool operation must not be " &
7599                              "abstract", Found_Op);
7600                        end if;
7601
7602                        --  The Storage_Size operation must be a function with
7603                        --  Storage_Count as its result type.
7604
7605                        if Op_Name = Name_Storage_Size then
7606                           if Ekind (Found_Op) = E_Procedure then
7607                              Error_Msg_N
7608                                ("% operation must be a function", Found_Op);
7609
7610                           elsif Etype (Found_Op) /= Stg_Cnt_Type then
7611                              Error_Msg_NE
7612                                ("wrong result type for%, expected type&",
7613                                 Found_Op, Stg_Cnt_Type);
7614                           end if;
7615
7616                        --  Allocate and Deallocate must be procedures
7617
7618                        elsif Ekind (Found_Op) = E_Function then
7619                           Error_Msg_N
7620                             ("% operation must be a procedure", Found_Op);
7621                        end if;
7622                     end if;
7623                  end Validate_Simple_Pool_Operation;
7624
7625               --  Start of processing for Validate_Simple_Pool_Ops
7626
7627               begin
7628                  Validate_Simple_Pool_Operation (Name_Allocate);
7629                  Validate_Simple_Pool_Operation (Name_Deallocate);
7630                  Validate_Simple_Pool_Operation (Name_Storage_Size);
7631               end Validate_Simple_Pool_Ops;
7632            end if;
7633         end if;
7634
7635         --  Now that all types from which E may depend are frozen, see if
7636         --  strict alignment is required, a component clause on a record
7637         --  is correct, the size is known at compile time and if it must
7638         --  be unsigned, in that order.
7639
7640         if Base_Type (E) = E then
7641            Check_Strict_Alignment (E);
7642         end if;
7643
7644         if Ekind (E) in E_Record_Type | E_Record_Subtype then
7645            declare
7646               RC : constant Node_Id := Get_Record_Representation_Clause (E);
7647            begin
7648               if Present (RC) then
7649                  Check_Record_Representation_Clause (RC);
7650               end if;
7651            end;
7652         end if;
7653
7654         Check_Compile_Time_Size (E);
7655
7656         Check_Unsigned_Type (E);
7657
7658         --  Do not allow a size clause for a type which does not have a size
7659         --  that is known at compile time
7660
7661         if (Has_Size_Clause (E) or else Has_Object_Size_Clause (E))
7662           and then not Size_Known_At_Compile_Time (E)
7663         then
7664            --  Suppress this message if errors posted on E, even if we are
7665            --  in all errors mode, since this is often a junk message
7666
7667            if not Error_Posted (E) then
7668               Error_Msg_N
7669                 ("size clause not allowed for variable length type",
7670                  Size_Clause (E));
7671            end if;
7672         end if;
7673
7674         --  Now we set/verify the representation information, in particular
7675         --  the size and alignment values. This processing is not required for
7676         --  generic types, since generic types do not play any part in code
7677         --  generation, and so the size and alignment values for such types
7678         --  are irrelevant. Ditto for types declared within a generic unit,
7679         --  which may have components that depend on generic parameters, and
7680         --  that will be recreated in an instance.
7681
7682         if Inside_A_Generic then
7683            null;
7684
7685         --  Otherwise we call the layout procedure
7686
7687         else
7688            Layout_Type (E);
7689         end if;
7690
7691         --  If this is an access to subprogram whose designated type is itself
7692         --  a subprogram type, the return type of this anonymous subprogram
7693         --  type must be decorated as well.
7694
7695         if Ekind (E) = E_Anonymous_Access_Subprogram_Type
7696           and then Ekind (Designated_Type (E)) = E_Subprogram_Type
7697         then
7698            Layout_Type (Etype (Designated_Type (E)));
7699         end if;
7700
7701         --  If the type has a Defaut_Value/Default_Component_Value aspect,
7702         --  this is where we analyze the expression (after the type is frozen,
7703         --  since in the case of Default_Value, we are analyzing with the
7704         --  type itself, and we treat Default_Component_Value similarly for
7705         --  the sake of uniformity).
7706
7707         if Is_First_Subtype (E) and then Has_Default_Aspect (E) then
7708            declare
7709               Nam : Name_Id;
7710               Exp : Node_Id;
7711               Typ : Entity_Id;
7712
7713            begin
7714               if Is_Scalar_Type (E) then
7715                  Nam := Name_Default_Value;
7716                  Typ := E;
7717                  Exp := Default_Aspect_Value (Typ);
7718               else
7719                  Nam := Name_Default_Component_Value;
7720                  Typ := Component_Type (E);
7721                  Exp := Default_Aspect_Component_Value (E);
7722               end if;
7723
7724               Analyze_And_Resolve (Exp, Typ);
7725
7726               if Etype (Exp) /= Any_Type then
7727                  if not Is_OK_Static_Expression (Exp) then
7728                     Error_Msg_Name_1 := Nam;
7729                     Flag_Non_Static_Expr
7730                       ("aspect% requires static expression", Exp);
7731                  end if;
7732               end if;
7733            end;
7734         end if;
7735
7736         --  Verify at this point that No_Controlled_Parts and No_Task_Parts,
7737         --  when specified on the current type or one of its ancestors, has
7738         --  not been overridden and that no violation of the aspect has
7739         --  occurred.
7740
7741         --  It is important that we perform the checks here after the type has
7742         --  been processed because if said type depended on a private type it
7743         --  will not have been marked controlled or having tasks.
7744
7745         Check_No_Parts_Violations (E, Aspect_No_Controlled_Parts);
7746         Check_No_Parts_Violations (E, Aspect_No_Task_Parts);
7747
7748         --  End of freeze processing for type entities
7749      end if;
7750
7751      --  Here is where we logically freeze the current entity. If it has a
7752      --  freeze node, then this is the point at which the freeze node is
7753      --  linked into the result list.
7754
7755      if Has_Delayed_Freeze (E) then
7756
7757         --  If a freeze node is already allocated, use it, otherwise allocate
7758         --  a new one. The preallocation happens in the case of anonymous base
7759         --  types, where we preallocate so that we can set First_Subtype_Link.
7760         --  Note that we reset the Sloc to the current freeze location.
7761
7762         if Present (Freeze_Node (E)) then
7763            F_Node := Freeze_Node (E);
7764            Set_Sloc (F_Node, Loc);
7765
7766         else
7767            F_Node := New_Node (N_Freeze_Entity, Loc);
7768            Set_Freeze_Node (E, F_Node);
7769            Set_Access_Types_To_Process (F_Node, No_Elist);
7770            Set_TSS_Elist (F_Node, No_Elist);
7771            Set_Actions (F_Node, No_List);
7772         end if;
7773
7774         Set_Entity (F_Node, E);
7775         Add_To_Result (F_Node);
7776
7777         --  A final pass over record types with discriminants. If the type
7778         --  has an incomplete declaration, there may be constrained access
7779         --  subtypes declared elsewhere, which do not depend on the discrimi-
7780         --  nants of the type, and which are used as component types (i.e.
7781         --  the full view is a recursive type). The designated types of these
7782         --  subtypes can only be elaborated after the type itself, and they
7783         --  need an itype reference.
7784
7785         if Ekind (E) = E_Record_Type and then Has_Discriminants (E) then
7786            declare
7787               Comp : Entity_Id;
7788               IR   : Node_Id;
7789               Typ  : Entity_Id;
7790
7791            begin
7792               Comp := First_Component (E);
7793               while Present (Comp) loop
7794                  Typ := Etype (Comp);
7795
7796                  if Is_Access_Type (Typ)
7797                    and then Scope (Typ) /= E
7798                    and then Base_Type (Designated_Type (Typ)) = E
7799                    and then Is_Itype (Designated_Type (Typ))
7800                  then
7801                     IR := Make_Itype_Reference (Sloc (Comp));
7802                     Set_Itype (IR, Designated_Type (Typ));
7803                     Append (IR, Result);
7804                  end if;
7805
7806                  Next_Component (Comp);
7807               end loop;
7808            end;
7809         end if;
7810      end if;
7811
7812      --  When a type is frozen, the first subtype of the type is frozen as
7813      --  well (RM 13.14(15)). This has to be done after freezing the type,
7814      --  since obviously the first subtype depends on its own base type.
7815
7816      if Is_Type (E) then
7817         Freeze_And_Append (First_Subtype (E), N, Result);
7818
7819         --  If we just froze a tagged non-class-wide record, then freeze the
7820         --  corresponding class-wide type. This must be done after the tagged
7821         --  type itself is frozen, because the class-wide type refers to the
7822         --  tagged type which generates the class.
7823
7824         if Is_Tagged_Type (E)
7825           and then not Is_Class_Wide_Type (E)
7826           and then Present (Class_Wide_Type (E))
7827         then
7828            Freeze_And_Append (Class_Wide_Type (E), N, Result);
7829         end if;
7830      end if;
7831
7832      Check_Debug_Info_Needed (E);
7833
7834      --  If subprogram has address clause then reset Is_Public flag, since we
7835      --  do not want the backend to generate external references.
7836
7837      if Is_Subprogram (E)
7838        and then Present (Address_Clause (E))
7839        and then not Is_Library_Level_Entity (E)
7840      then
7841         Set_Is_Public (E, False);
7842      end if;
7843
7844      --  The Ghost mode of the enclosing context is ignored, while the
7845      --  entity being frozen is living. Insert the freezing action prior
7846      --  to the start of the enclosing ignored Ghost region. As a result
7847      --  the freezeing action will be preserved when the ignored Ghost
7848      --  context is eliminated. The insertion must take place even when
7849      --  the context is a spec expression, otherwise "Handling of Default
7850      --  and Per-Object Expressions" will suppress the insertion, and the
7851      --  freeze node will be dropped on the floor.
7852
7853      if Saved_GM = Ignore
7854        and then Ghost_Mode /= Ignore
7855        and then Present (Ignored_Ghost_Region)
7856      then
7857         Insert_Actions
7858           (Assoc_Node   => Ignored_Ghost_Region,
7859            Ins_Actions  => Result,
7860            Spec_Expr_OK => True);
7861
7862         Result := No_List;
7863      end if;
7864
7865   <<Leave>>
7866      Restore_Ghost_Region (Saved_GM, Saved_IGR);
7867
7868      return Result;
7869   end Freeze_Entity;
7870
7871   -----------------------------
7872   -- Freeze_Enumeration_Type --
7873   -----------------------------
7874
7875   procedure Freeze_Enumeration_Type (Typ : Entity_Id) is
7876   begin
7877      --  By default, if no size clause is present, an enumeration type with
7878      --  Convention C is assumed to interface to a C enum and has integer
7879      --  size, except for a boolean type because it is assumed to interface
7880      --  to _Bool introduced in C99. This applies to types. For subtypes,
7881      --  verify that its base type has no size clause either. Treat other
7882      --  foreign conventions in the same way, and also make sure alignment
7883      --  is set right.
7884
7885      if Has_Foreign_Convention (Typ)
7886        and then not Is_Boolean_Type (Typ)
7887        and then not Has_Size_Clause (Typ)
7888        and then not Has_Size_Clause (Base_Type (Typ))
7889        and then Esize (Typ) < Standard_Integer_Size
7890
7891        --  Don't do this if Short_Enums on target
7892
7893        and then not Target_Short_Enums
7894      then
7895         Set_Esize (Typ, UI_From_Int (Standard_Integer_Size));
7896         Set_Alignment (Typ, Alignment (Standard_Integer));
7897
7898      --  Normal Ada case or size clause present or not Long_C_Enums on target
7899
7900      else
7901         --  If the enumeration type interfaces to C, and it has a size clause
7902         --  that specifies less than int size, it warrants a warning. The
7903         --  user may intend the C type to be an enum or a char, so this is
7904         --  not by itself an error that the Ada compiler can detect, but it
7905         --  it is a worth a heads-up. For Boolean and Character types we
7906         --  assume that the programmer has the proper C type in mind.
7907
7908         if Convention (Typ) = Convention_C
7909           and then Has_Size_Clause (Typ)
7910           and then Esize (Typ) /= Esize (Standard_Integer)
7911           and then not Is_Boolean_Type (Typ)
7912           and then not Is_Character_Type (Typ)
7913
7914           --  Don't do this if Short_Enums on target
7915
7916           and then not Target_Short_Enums
7917         then
7918            Error_Msg_N
7919              ("C enum types have the size of a C int??", Size_Clause (Typ));
7920         end if;
7921
7922         Adjust_Esize_For_Alignment (Typ);
7923      end if;
7924   end Freeze_Enumeration_Type;
7925
7926   -----------------------
7927   -- Freeze_Expression --
7928   -----------------------
7929
7930   procedure Freeze_Expression (N : Node_Id) is
7931
7932      function Find_Aggregate_Component_Desig_Type return Entity_Id;
7933      --  If the expression is an array aggregate, the type of the component
7934      --  expressions is also frozen. If the component type is an access type
7935      --  and the expressions include allocators, the designed type is frozen
7936      --  as well.
7937
7938      function In_Expanded_Body (N : Node_Id) return Boolean;
7939      --  Given an N_Handled_Sequence_Of_Statements node, determines whether it
7940      --  is the statement sequence of an expander-generated subprogram: body
7941      --  created for an expression function, for a predicate function, an init
7942      --  proc, a stream subprogram, or a renaming as body. If so, this is not
7943      --  a freezing context and the entity will be frozen at a later point.
7944
7945      function Has_Decl_In_List
7946        (E : Entity_Id;
7947         N : Node_Id;
7948         L : List_Id) return Boolean;
7949      --  Determines whether an entity E referenced in node N is declared in
7950      --  the list L.
7951
7952      -----------------------------------------
7953      -- Find_Aggregate_Component_Desig_Type --
7954      -----------------------------------------
7955
7956      function Find_Aggregate_Component_Desig_Type return Entity_Id is
7957         Assoc : Node_Id;
7958         Exp   : Node_Id;
7959
7960      begin
7961         if Present (Expressions (N)) then
7962            Exp := First (Expressions (N));
7963            while Present (Exp) loop
7964               if Nkind (Exp) = N_Allocator then
7965                  return Designated_Type (Component_Type (Etype (N)));
7966               end if;
7967
7968               Next (Exp);
7969            end loop;
7970         end if;
7971
7972         if Present (Component_Associations (N)) then
7973            Assoc := First  (Component_Associations (N));
7974            while Present (Assoc) loop
7975               if Nkind (Expression (Assoc)) = N_Allocator then
7976                  return Designated_Type (Component_Type (Etype (N)));
7977               end if;
7978
7979               Next (Assoc);
7980            end loop;
7981         end if;
7982
7983         return Empty;
7984      end Find_Aggregate_Component_Desig_Type;
7985
7986      ----------------------
7987      -- In_Expanded_Body --
7988      ----------------------
7989
7990      function In_Expanded_Body (N : Node_Id) return Boolean is
7991         P  : constant Node_Id := Parent (N);
7992         Id : Entity_Id;
7993
7994      begin
7995         if Nkind (P) /= N_Subprogram_Body then
7996            return False;
7997
7998         --  AI12-0157: An expression function that is a completion is a freeze
7999         --  point. If the body is the result of expansion, it is not.
8000
8001         elsif Was_Expression_Function (P) then
8002            return not Comes_From_Source (P);
8003
8004         --  This is the body of a generated predicate function
8005
8006         elsif Present (Corresponding_Spec (P))
8007           and then Is_Predicate_Function (Corresponding_Spec (P))
8008         then
8009            return True;
8010
8011         else
8012            Id := Defining_Unit_Name (Specification (P));
8013
8014            --  The following are expander-created bodies, or bodies that
8015            --  are not freeze points.
8016
8017            if Nkind (Id) = N_Defining_Identifier
8018              and then (Is_Init_Proc (Id)
8019                         or else Is_TSS (Id, TSS_Stream_Input)
8020                         or else Is_TSS (Id, TSS_Stream_Output)
8021                         or else Is_TSS (Id, TSS_Stream_Read)
8022                         or else Is_TSS (Id, TSS_Stream_Write)
8023                         or else Is_TSS (Id, TSS_Put_Image)
8024                         or else Nkind (Original_Node (P)) =
8025                                             N_Subprogram_Renaming_Declaration)
8026            then
8027               return True;
8028            else
8029               return False;
8030            end if;
8031         end if;
8032      end In_Expanded_Body;
8033
8034      ----------------------
8035      -- Has_Decl_In_List --
8036      ----------------------
8037
8038      function Has_Decl_In_List
8039        (E : Entity_Id;
8040         N : Node_Id;
8041         L : List_Id) return Boolean
8042      is
8043         Decl_Node : Node_Id;
8044
8045      begin
8046         --  If E is an itype, pretend that it is declared in N
8047
8048         if Is_Itype (E) then
8049            Decl_Node := N;
8050         else
8051            Decl_Node := Declaration_Node (E);
8052         end if;
8053
8054         return Is_List_Member (Decl_Node)
8055           and then List_Containing (Decl_Node) = L;
8056      end Has_Decl_In_List;
8057
8058      --  Local variables
8059
8060      In_Spec_Exp : constant Boolean := In_Spec_Expression;
8061
8062      Desig_Typ : Entity_Id;
8063      Nam       : Entity_Id;
8064      P         : Node_Id;
8065      Parent_P  : Node_Id;
8066      Typ       : Entity_Id;
8067
8068      Allocator_Typ : Entity_Id := Empty;
8069
8070      Freeze_Outside : Boolean := False;
8071      --  This flag is set true if the entity must be frozen outside the
8072      --  current subprogram. This happens in the case of expander generated
8073      --  subprograms (_Init_Proc, _Input, _Output, _Read, _Write) which do
8074      --  not freeze all entities like other bodies, but which nevertheless
8075      --  may reference entities that have to be frozen before the body and
8076      --  obviously cannot be frozen inside the body.
8077
8078      Freeze_Outside_Subp  : Entity_Id := Empty;
8079      --  This entity is set if we are inside a subprogram body and the frozen
8080      --  entity is defined in the enclosing scope of this subprogram. In such
8081      --  case we must skip the subprogram body when climbing the parents chain
8082      --  to locate the correct placement for the freezing node.
8083
8084   --  Start of processing for Freeze_Expression
8085
8086   begin
8087      --  Immediate return if freezing is inhibited. This flag is set by the
8088      --  analyzer to stop freezing on generated expressions that would cause
8089      --  freezing if they were in the source program, but which are not
8090      --  supposed to freeze, since they are created.
8091
8092      if Must_Not_Freeze (N) then
8093         return;
8094      end if;
8095
8096      --  If expression is non-static, then it does not freeze in a default
8097      --  expression, see section "Handling of Default Expressions" in the
8098      --  spec of package Sem for further details. Note that we have to make
8099      --  sure that we actually have a real expression (if we have a subtype
8100      --  indication, we can't test Is_OK_Static_Expression). However, we
8101      --  exclude the case of the prefix of an attribute of a static scalar
8102      --  subtype from this early return, because static subtype attributes
8103      --  should always cause freezing, even in default expressions, but
8104      --  the attribute may not have been marked as static yet (because in
8105      --  Resolve_Attribute, the call to Eval_Attribute follows the call of
8106      --  Freeze_Expression on the prefix).
8107
8108      if In_Spec_Exp
8109        and then Nkind (N) in N_Subexpr
8110        and then not Is_OK_Static_Expression (N)
8111        and then (Nkind (Parent (N)) /= N_Attribute_Reference
8112                   or else not (Is_Entity_Name (N)
8113                                 and then Is_Type (Entity (N))
8114                                 and then Is_OK_Static_Subtype (Entity (N))))
8115      then
8116         return;
8117      end if;
8118
8119      --  Freeze type of expression if not frozen already
8120
8121      Typ := Empty;
8122
8123      if Nkind (N) in N_Has_Etype and then Present (Etype (N)) then
8124         if not Is_Frozen (Etype (N)) then
8125            Typ := Etype (N);
8126
8127         --  Base type may be an derived numeric type that is frozen at the
8128         --  point of declaration, but first_subtype is still unfrozen.
8129
8130         elsif not Is_Frozen (First_Subtype (Etype (N))) then
8131            Typ := First_Subtype (Etype (N));
8132         end if;
8133      end if;
8134
8135      --  For entity name, freeze entity if not frozen already. A special
8136      --  exception occurs for an identifier that did not come from source.
8137      --  We don't let such identifiers freeze a non-internal entity, i.e.
8138      --  an entity that did come from source, since such an identifier was
8139      --  generated by the expander, and cannot have any semantic effect on
8140      --  the freezing semantics. For example, this stops the parameter of
8141      --  an initialization procedure from freezing the variable.
8142
8143      if Is_Entity_Name (N)
8144        and then Present (Entity (N))
8145        and then not Is_Frozen (Entity (N))
8146        and then (Nkind (N) /= N_Identifier
8147                   or else Comes_From_Source (N)
8148                   or else not Comes_From_Source (Entity (N)))
8149      then
8150         Nam := Entity (N);
8151
8152         if Present (Nam) and then Ekind (Nam) = E_Function then
8153            Check_Expression_Function (N, Nam);
8154         end if;
8155
8156      else
8157         Nam := Empty;
8158      end if;
8159
8160      --  For an allocator freeze designated type if not frozen already
8161
8162      --  For an aggregate whose component type is an access type, freeze the
8163      --  designated type now, so that its freeze does not appear within the
8164      --  loop that might be created in the expansion of the aggregate. If the
8165      --  designated type is a private type without full view, the expression
8166      --  cannot contain an allocator, so the type is not frozen.
8167
8168      --  For a function, we freeze the entity when the subprogram declaration
8169      --  is frozen, but a function call may appear in an initialization proc.
8170      --  before the declaration is frozen. We need to generate the extra
8171      --  formals, if any, to ensure that the expansion of the call includes
8172      --  the proper actuals. This only applies to Ada subprograms, not to
8173      --  imported ones.
8174
8175      Desig_Typ := Empty;
8176
8177      case Nkind (N) is
8178         when N_Allocator =>
8179            Desig_Typ := Designated_Type (Etype (N));
8180
8181            if Nkind (Expression (N)) = N_Qualified_Expression then
8182               Allocator_Typ := Entity (Subtype_Mark (Expression (N)));
8183            end if;
8184
8185         when N_Aggregate =>
8186            if Is_Array_Type (Etype (N))
8187              and then Is_Access_Type (Component_Type (Etype (N)))
8188            then
8189               --  Check whether aggregate includes allocators
8190
8191               Desig_Typ := Find_Aggregate_Component_Desig_Type;
8192            end if;
8193
8194         when N_Indexed_Component
8195            | N_Selected_Component
8196            | N_Slice
8197         =>
8198            if Is_Access_Type (Etype (Prefix (N))) then
8199               Desig_Typ := Designated_Type (Etype (Prefix (N)));
8200            end if;
8201
8202         when N_Identifier =>
8203            if Present (Nam)
8204              and then Ekind (Nam) = E_Function
8205              and then Nkind (Parent (N)) = N_Function_Call
8206              and then Convention (Nam) = Convention_Ada
8207            then
8208               Create_Extra_Formals (Nam);
8209            end if;
8210
8211         when others =>
8212            null;
8213      end case;
8214
8215      if Desig_Typ /= Empty
8216        and then (Is_Frozen (Desig_Typ)
8217                   or else (not Is_Fully_Defined (Desig_Typ)))
8218      then
8219         Desig_Typ := Empty;
8220      end if;
8221
8222      --  All done if nothing needs freezing
8223
8224      if No (Typ)
8225        and then No (Nam)
8226        and then No (Desig_Typ)
8227        and then No (Allocator_Typ)
8228      then
8229         return;
8230      end if;
8231
8232      --  Check if we are inside a subprogram body and the frozen entity is
8233      --  defined in the enclosing scope of this subprogram. In such case we
8234      --  must skip the subprogram when climbing the parents chain to locate
8235      --  the correct placement for the freezing node.
8236
8237      --  This is not needed for default expressions and other spec expressions
8238      --  in generic units since the Move_Freeze_Nodes mechanism (sem_ch12.adb)
8239      --  takes care of placing them at the proper place, after the generic
8240      --  unit.
8241
8242      if Present (Nam)
8243        and then Scope (Nam) /= Current_Scope
8244        and then not (In_Spec_Exp and then Inside_A_Generic)
8245      then
8246         declare
8247            S : Entity_Id := Current_Scope;
8248
8249         begin
8250            while Present (S)
8251              and then In_Same_Source_Unit (Nam, S)
8252            loop
8253               if Scope (S) = Scope (Nam) then
8254                  if Is_Subprogram (S) and then Has_Completion (S) then
8255                     Freeze_Outside_Subp := S;
8256                  end if;
8257
8258                  exit;
8259               end if;
8260
8261               S := Scope (S);
8262            end loop;
8263         end;
8264      end if;
8265
8266      --  Examine the enclosing context by climbing the parent chain
8267
8268      --  If we identified that we must freeze the entity outside of a given
8269      --  subprogram then we just climb up to that subprogram checking if some
8270      --  enclosing node is marked as Must_Not_Freeze (since in such case we
8271      --  must not freeze yet this entity).
8272
8273      P := N;
8274
8275      if Present (Freeze_Outside_Subp) then
8276         loop
8277            --  Do not freeze the current expression if another expression in
8278            --  the chain of parents must not be frozen.
8279
8280            if Nkind (P) in N_Subexpr and then Must_Not_Freeze (P) then
8281               return;
8282            end if;
8283
8284            Parent_P := Parent (P);
8285
8286            --  If we don't have a parent, then we are not in a well-formed
8287            --  tree. This is an unusual case, but there are some legitimate
8288            --  situations in which this occurs, notably when the expressions
8289            --  in the range of a type declaration are resolved. We simply
8290            --  ignore the freeze request in this case.
8291
8292            if No (Parent_P) then
8293               return;
8294            end if;
8295
8296            --  If the parent is a subprogram body, the candidate insertion
8297            --  point is just ahead of it.
8298
8299            if  Nkind (Parent_P) = N_Subprogram_Body
8300                and then Unique_Defining_Entity (Parent_P) =
8301                           Freeze_Outside_Subp
8302            then
8303               P := Parent_P;
8304               exit;
8305            end if;
8306
8307            P := Parent_P;
8308         end loop;
8309
8310      --  Otherwise the traversal serves two purposes - to detect scenarios
8311      --  where freezeing is not needed and to find the proper insertion point
8312      --  for the freeze nodes. Although somewhat similar to Insert_Actions,
8313      --  this traversal is freezing semantics-sensitive. Inserting freeze
8314      --  nodes blindly in the tree may result in types being frozen too early.
8315
8316      else
8317         loop
8318            --  Do not freeze the current expression if another expression in
8319            --  the chain of parents must not be frozen.
8320
8321            if Nkind (P) in N_Subexpr and then Must_Not_Freeze (P) then
8322               return;
8323            end if;
8324
8325            Parent_P := Parent (P);
8326
8327            --  If we don't have a parent, then we are not in a well-formed
8328            --  tree. This is an unusual case, but there are some legitimate
8329            --  situations in which this occurs, notably when the expressions
8330            --  in the range of a type declaration are resolved. We simply
8331            --  ignore the freeze request in this case.
8332
8333            if No (Parent_P) then
8334               return;
8335            end if;
8336
8337            --  See if we have got to an appropriate point in the tree
8338
8339            case Nkind (Parent_P) is
8340
8341               --  A special test for the exception of (RM 13.14(8)) for the
8342               --  case of per-object expressions (RM 3.8(18)) occurring in
8343               --  component definition or a discrete subtype definition. Note
8344               --  that we test for a component declaration which includes both
8345               --  cases we are interested in, and furthermore the tree does
8346               --  not have explicit nodes for either of these two constructs.
8347
8348               when N_Component_Declaration =>
8349
8350                  --  The case we want to test for here is an identifier that
8351                  --  is a per-object expression, this is either a discriminant
8352                  --  that appears in a context other than the component
8353                  --  declaration or it is a reference to the type of the
8354                  --  enclosing construct.
8355
8356                  --  For either of these cases, we skip the freezing
8357
8358                  if not In_Spec_Expression
8359                    and then Nkind (N) = N_Identifier
8360                    and then (Present (Entity (N)))
8361                  then
8362                     --  We recognize the discriminant case by just looking for
8363                     --  a reference to a discriminant. It can only be one for
8364                     --  the enclosing construct. Skip freezing in this case.
8365
8366                     if Ekind (Entity (N)) = E_Discriminant then
8367                        return;
8368
8369                     --  For the case of a reference to the enclosing record,
8370                     --  (or task or protected type), we look for a type that
8371                     --  matches the current scope.
8372
8373                     elsif Entity (N) = Current_Scope then
8374                        return;
8375                     end if;
8376                  end if;
8377
8378               --  If we have an enumeration literal that appears as the choice
8379               --  in the aggregate of an enumeration representation clause,
8380               --  then freezing does not occur (RM 13.14(10)).
8381
8382               when N_Enumeration_Representation_Clause =>
8383
8384                  --  The case we are looking for is an enumeration literal
8385
8386                  if Nkind (N) in N_Identifier | N_Character_Literal
8387                    and then Is_Enumeration_Type (Etype (N))
8388                  then
8389                     --  If enumeration literal appears directly as the choice,
8390                     --  do not freeze (this is the normal non-overloaded case)
8391
8392                     if Nkind (Parent (N)) = N_Component_Association
8393                       and then First (Choices (Parent (N))) = N
8394                     then
8395                        return;
8396
8397                     --  If enumeration literal appears as the name of function
8398                     --  which is the choice, then also do not freeze. This
8399                     --  happens in the overloaded literal case, where the
8400                     --  enumeration literal is temporarily changed to a
8401                     --  function call for overloading analysis purposes.
8402
8403                     elsif Nkind (Parent (N)) = N_Function_Call
8404                        and then Nkind (Parent (Parent (N))) =
8405                                   N_Component_Association
8406                        and then First (Choices (Parent (Parent (N)))) =
8407                                   Parent (N)
8408                     then
8409                        return;
8410                     end if;
8411                  end if;
8412
8413               --  Normally if the parent is a handled sequence of statements,
8414               --  then the current node must be a statement, and that is an
8415               --  appropriate place to insert a freeze node.
8416
8417               when N_Handled_Sequence_Of_Statements =>
8418
8419                  --  An exception occurs when the sequence of statements is
8420                  --  for an expander generated body that did not do the usual
8421                  --  freeze all operation. In this case we usually want to
8422                  --  freeze outside this body, not inside it, and we skip
8423                  --  past the subprogram body that we are inside.
8424
8425                  if In_Expanded_Body (Parent_P) then
8426                     declare
8427                        Subp_Body : constant Node_Id := Parent (Parent_P);
8428                        Spec_Id   : Entity_Id;
8429
8430                     begin
8431                        --  Freeze the entity only when it is declared inside
8432                        --  the body of the expander generated procedure. This
8433                        --  case is recognized by the subprogram scope of the
8434                        --  entity or its type, which is either the spec of an
8435                        --  enclosing body, or (in the case of init_procs for
8436                        --  which there is no separate spec) the current scope.
8437
8438                        if Nkind (Subp_Body) = N_Subprogram_Body then
8439                           declare
8440                              S : Entity_Id;
8441
8442                           begin
8443                              Spec_Id := Corresponding_Spec (Subp_Body);
8444
8445                              if Present (Typ) then
8446                                 S := Scope (Typ);
8447                              elsif Present (Nam) then
8448                                 S := Scope (Nam);
8449                              else
8450                                 S := Standard_Standard;
8451                              end if;
8452
8453                              while S /= Standard_Standard
8454                                and then not Is_Subprogram (S)
8455                              loop
8456                                 S := Scope (S);
8457                              end loop;
8458
8459                              if S = Spec_Id then
8460                                 exit;
8461
8462                              elsif Present (Typ)
8463                                and then Scope (Typ) = Current_Scope
8464                                and then
8465                                  Defining_Entity (Subp_Body) = Current_Scope
8466                              then
8467                                 exit;
8468                              end if;
8469                           end;
8470                        end if;
8471
8472                        --  If the entity is not frozen by an expression
8473                        --  function that is not a completion, continue
8474                        --  climbing the tree.
8475
8476                        if Nkind (Subp_Body) = N_Subprogram_Body
8477                          and then Was_Expression_Function (Subp_Body)
8478                        then
8479                           null;
8480
8481                        --  Freeze outside the body
8482
8483                        else
8484                           Parent_P := Parent (Parent_P);
8485                           Freeze_Outside := True;
8486                        end if;
8487                     end;
8488
8489                  --  Here if normal case where we are in handled statement
8490                  --  sequence and want to do the insertion right there.
8491
8492                  else
8493                     exit;
8494                  end if;
8495
8496               --  If parent is a body or a spec or a block, then the current
8497               --  node is a statement or declaration and we can insert the
8498               --  freeze node before it.
8499
8500               when N_Block_Statement
8501                  | N_Entry_Body
8502                  | N_Package_Body
8503                  | N_Package_Specification
8504                  | N_Protected_Body
8505                  | N_Subprogram_Body
8506                  | N_Task_Body
8507               =>
8508                  exit;
8509
8510               --  The expander is allowed to define types in any statements
8511               --  list, so any of the following parent nodes also mark a
8512               --  freezing point if the actual node is in a list of
8513               --  statements or declarations.
8514
8515               when N_Abortable_Part
8516                  | N_Accept_Alternative
8517                  | N_Case_Statement_Alternative
8518                  | N_Compilation_Unit_Aux
8519                  | N_Conditional_Entry_Call
8520                  | N_Delay_Alternative
8521                  | N_Elsif_Part
8522                  | N_Entry_Call_Alternative
8523                  | N_Exception_Handler
8524                  | N_Extended_Return_Statement
8525                  | N_Freeze_Entity
8526                  | N_If_Statement
8527                  | N_Selective_Accept
8528                  | N_Triggering_Alternative
8529               =>
8530                  exit when Is_List_Member (P);
8531
8532               --  The freeze nodes produced by an expression coming from the
8533               --  Actions list of an N_Expression_With_Actions, short-circuit
8534               --  expression or N_Case_Expression_Alternative node must remain
8535               --  within the Actions list if they freeze an entity declared in
8536               --  this list, as inserting the freeze nodes further up the tree
8537               --  may lead to use before declaration issues for the entity.
8538
8539               when N_Case_Expression_Alternative
8540                  | N_Expression_With_Actions
8541                  | N_Short_Circuit
8542               =>
8543                  exit when (Present (Nam)
8544                              and then
8545                             Has_Decl_In_List (Nam, P, Actions (Parent_P)))
8546                    or else (Present (Typ)
8547                              and then
8548                             Has_Decl_In_List (Typ, P, Actions (Parent_P)));
8549
8550               --  Likewise for an N_If_Expression and its two Actions list
8551
8552               when N_If_Expression =>
8553                  declare
8554                     L1 : constant List_Id := Then_Actions (Parent_P);
8555                     L2 : constant List_Id := Else_Actions (Parent_P);
8556
8557                  begin
8558                     exit when (Present (Nam)
8559                                 and then
8560                                Has_Decl_In_List (Nam, P, L1))
8561                       or else (Present (Typ)
8562                                 and then
8563                                Has_Decl_In_List (Typ, P, L1))
8564                       or else (Present (Nam)
8565                                 and then
8566                                Has_Decl_In_List (Nam, P, L2))
8567                       or else (Present (Typ)
8568                                 and then
8569                                Has_Decl_In_List (Typ, P, L2));
8570                  end;
8571
8572               --  N_Loop_Statement is a special case: a type that appears in
8573               --  the source can never be frozen in a loop (this occurs only
8574               --  because of a loop expanded by the expander), so we keep on
8575               --  going. Otherwise we terminate the search. Same is true of
8576               --  any entity which comes from source (if it has a predefined
8577               --  type, this type does not appear to come from source, but the
8578               --  entity should not be frozen here).
8579
8580               when N_Loop_Statement =>
8581                  exit when not Comes_From_Source (Etype (N))
8582                    and then (No (Nam) or else not Comes_From_Source (Nam));
8583
8584               --  For all other cases, keep looking at parents
8585
8586               when others =>
8587                  null;
8588            end case;
8589
8590            --  We fall through the case if we did not yet find the proper
8591            --  place in the tree for inserting the freeze node, so climb.
8592
8593            P := Parent_P;
8594         end loop;
8595      end if;
8596
8597      --  If the expression appears in a record or an initialization procedure,
8598      --  the freeze nodes are collected and attached to the current scope, to
8599      --  be inserted and analyzed on exit from the scope, to insure that
8600      --  generated entities appear in the correct scope. If the expression is
8601      --  a default for a discriminant specification, the scope is still void.
8602      --  The expression can also appear in the discriminant part of a private
8603      --  or concurrent type.
8604
8605      --  If the expression appears in a constrained subcomponent of an
8606      --  enclosing record declaration, the freeze nodes must be attached to
8607      --  the outer record type so they can eventually be placed in the
8608      --  enclosing declaration list.
8609
8610      --  The other case requiring this special handling is if we are in a
8611      --  default expression, since in that case we are about to freeze a
8612      --  static type, and the freeze scope needs to be the outer scope, not
8613      --  the scope of the subprogram with the default parameter.
8614
8615      --  For default expressions and other spec expressions in generic units,
8616      --  the Move_Freeze_Nodes mechanism (see sem_ch12.adb) takes care of
8617      --  placing them at the proper place, after the generic unit.
8618
8619      if (In_Spec_Exp and not Inside_A_Generic)
8620        or else Freeze_Outside
8621        or else (Is_Type (Current_Scope)
8622                  and then (not Is_Concurrent_Type (Current_Scope)
8623                             or else not Has_Completion (Current_Scope)))
8624        or else Ekind (Current_Scope) = E_Void
8625      then
8626         declare
8627            Freeze_Nodes : List_Id := No_List;
8628            Pos          : Int     := Scope_Stack.Last;
8629
8630         begin
8631            if Present (Desig_Typ) then
8632               Freeze_And_Append (Desig_Typ, N, Freeze_Nodes);
8633            end if;
8634
8635            if Present (Typ) then
8636               Freeze_And_Append (Typ, N, Freeze_Nodes);
8637            end if;
8638
8639            if Present (Nam) then
8640               Freeze_And_Append (Nam, N, Freeze_Nodes);
8641            end if;
8642
8643            --  The current scope may be that of a constrained component of
8644            --  an enclosing record declaration, or of a loop of an enclosing
8645            --  quantified expression, which is above the current scope in the
8646            --  scope stack. Indeed in the context of a quantified expression,
8647            --  a scope is created and pushed above the current scope in order
8648            --  to emulate the loop-like behavior of the quantified expression.
8649            --  If the expression is within a top-level pragma, as for a pre-
8650            --  condition on a library-level subprogram, nothing to do.
8651
8652            if not Is_Compilation_Unit (Current_Scope)
8653              and then (Is_Record_Type (Scope (Current_Scope))
8654                         or else Nkind (Parent (Current_Scope)) =
8655                                                     N_Quantified_Expression)
8656            then
8657               Pos := Pos - 1;
8658            end if;
8659
8660            if Is_Non_Empty_List (Freeze_Nodes) then
8661
8662               --  When the current scope is transient, insert the freeze nodes
8663               --  prior to the expression that produced them. Transient scopes
8664               --  may create additional declarations when finalizing objects
8665               --  or managing the secondary stack. Inserting the freeze nodes
8666               --  of those constructs prior to the scope would result in a
8667               --  freeze-before-declaration, therefore the freeze node must
8668               --  remain interleaved with their constructs.
8669
8670               if Scope_Is_Transient then
8671                  Insert_Actions (N, Freeze_Nodes);
8672
8673               elsif No (Scope_Stack.Table (Pos).Pending_Freeze_Actions) then
8674                  Scope_Stack.Table (Pos).Pending_Freeze_Actions :=
8675                    Freeze_Nodes;
8676               else
8677                  Append_List (Freeze_Nodes,
8678                    Scope_Stack.Table (Pos).Pending_Freeze_Actions);
8679               end if;
8680            end if;
8681         end;
8682
8683         return;
8684      end if;
8685
8686      --  Now we have the right place to do the freezing. First, a special
8687      --  adjustment, if we are in spec-expression analysis mode, these freeze
8688      --  actions must not be thrown away (normally all inserted actions are
8689      --  thrown away in this mode. However, the freeze actions are from static
8690      --  expressions and one of the important reasons we are doing this
8691      --  special analysis is to get these freeze actions. Therefore we turn
8692      --  off the In_Spec_Expression mode to propagate these freeze actions.
8693      --  This also means they get properly analyzed and expanded.
8694
8695      In_Spec_Expression := False;
8696
8697      --  Freeze the subtype mark before a qualified expression on an
8698      --  allocator as per AARM 13.14(4.a). This is needed in particular to
8699      --  generate predicate functions.
8700
8701      if Present (Allocator_Typ) then
8702         Freeze_Before (P, Allocator_Typ);
8703      end if;
8704
8705      --  Freeze the designated type of an allocator (RM 13.14(13))
8706
8707      if Present (Desig_Typ) then
8708         Freeze_Before (P, Desig_Typ);
8709      end if;
8710
8711      --  Freeze type of expression (RM 13.14(10)). Note that we took care of
8712      --  the enumeration representation clause exception in the loop above.
8713
8714      if Present (Typ) then
8715         Freeze_Before (P, Typ);
8716      end if;
8717
8718      --  Freeze name if one is present (RM 13.14(11))
8719
8720      if Present (Nam) then
8721         Freeze_Before (P, Nam);
8722      end if;
8723
8724      --  Restore In_Spec_Expression flag
8725
8726      In_Spec_Expression := In_Spec_Exp;
8727   end Freeze_Expression;
8728
8729   -----------------------
8730   -- Freeze_Expr_Types --
8731   -----------------------
8732
8733   procedure Freeze_Expr_Types
8734     (Def_Id : Entity_Id;
8735      Typ    : Entity_Id;
8736      Expr   : Node_Id;
8737      N      : Node_Id)
8738   is
8739      function Cloned_Expression return Node_Id;
8740      --  Build a duplicate of the expression of the return statement that has
8741      --  no defining entities shared with the original expression.
8742
8743      function Freeze_Type_Refs (Node : Node_Id) return Traverse_Result;
8744      --  Freeze all types referenced in the subtree rooted at Node
8745
8746      -----------------------
8747      -- Cloned_Expression --
8748      -----------------------
8749
8750      function Cloned_Expression return Node_Id is
8751         function Clone_Id (Node : Node_Id) return Traverse_Result;
8752         --  Tree traversal routine that clones the defining identifier of
8753         --  iterator and loop parameter specification nodes.
8754
8755         --------------
8756         -- Clone_Id --
8757         --------------
8758
8759         function Clone_Id (Node : Node_Id) return Traverse_Result is
8760         begin
8761            if Nkind (Node) in
8762                 N_Iterator_Specification | N_Loop_Parameter_Specification
8763            then
8764               Set_Defining_Identifier
8765                 (Node, New_Copy (Defining_Identifier (Node)));
8766            end if;
8767
8768            return OK;
8769         end Clone_Id;
8770
8771         procedure Clone_Def_Ids is new Traverse_Proc (Clone_Id);
8772
8773         --  Local variable
8774
8775         Dup_Expr : constant Node_Id := New_Copy_Tree (Expr);
8776
8777      --  Start of processing for Cloned_Expression
8778
8779      begin
8780         --  We must duplicate the expression with semantic information to
8781         --  inherit the decoration of global entities in generic instances.
8782         --  Set the parent of the new node to be the parent of the original
8783         --  to get the proper context, which is needed for complete error
8784         --  reporting and for semantic analysis.
8785
8786         Set_Parent (Dup_Expr, Parent (Expr));
8787
8788         --  Replace the defining identifier of iterators and loop param
8789         --  specifications by a clone to ensure that the cloned expression
8790         --  and the original expression don't have shared identifiers;
8791         --  otherwise, as part of the preanalysis of the expression, these
8792         --  shared identifiers may be left decorated with itypes which
8793         --  will not be available in the tree passed to the backend.
8794
8795         Clone_Def_Ids (Dup_Expr);
8796
8797         return Dup_Expr;
8798      end Cloned_Expression;
8799
8800      ----------------------
8801      -- Freeze_Type_Refs --
8802      ----------------------
8803
8804      function Freeze_Type_Refs (Node : Node_Id) return Traverse_Result is
8805         procedure Check_And_Freeze_Type (Typ : Entity_Id);
8806         --  Check that Typ is fully declared and freeze it if so
8807
8808         ---------------------------
8809         -- Check_And_Freeze_Type --
8810         ---------------------------
8811
8812         procedure Check_And_Freeze_Type (Typ : Entity_Id) is
8813         begin
8814            --  Skip Itypes created by the preanalysis, and itypes whose
8815            --  scope is another type (i.e. component subtypes that depend
8816            --  on a discriminant),
8817
8818            if Is_Itype (Typ)
8819              and then (Scope_Within_Or_Same (Scope (Typ), Def_Id)
8820                         or else Is_Type (Scope (Typ)))
8821            then
8822               return;
8823            end if;
8824
8825            --  This provides a better error message than generating primitives
8826            --  whose compilation fails much later. Refine the error message if
8827            --  possible.
8828
8829            Check_Fully_Declared (Typ, Node);
8830
8831            if Error_Posted (Node) then
8832               if Has_Private_Component (Typ)
8833                 and then not Is_Private_Type (Typ)
8834               then
8835                  Error_Msg_NE ("\type& has private component", Node, Typ);
8836               end if;
8837
8838            else
8839               Freeze_Before (N, Typ);
8840            end if;
8841         end Check_And_Freeze_Type;
8842
8843      --  Start of processing for Freeze_Type_Refs
8844
8845      begin
8846         --  Check that a type referenced by an entity can be frozen
8847
8848         if Is_Entity_Name (Node) and then Present (Entity (Node)) then
8849            --  The entity itself may be a type, as in a membership test
8850            --  or an attribute reference. Freezing its own type would be
8851            --  incomplete if the entity is derived or an extension.
8852
8853            if Is_Type (Entity (Node)) then
8854               Check_And_Freeze_Type (Entity (Node));
8855
8856            else
8857               Check_And_Freeze_Type (Etype (Entity (Node)));
8858            end if;
8859
8860            --  Check that the enclosing record type can be frozen
8861
8862            if Ekind (Entity (Node)) in E_Component | E_Discriminant then
8863               Check_And_Freeze_Type (Scope (Entity (Node)));
8864            end if;
8865
8866         --  Freezing an access type does not freeze the designated type, but
8867         --  freezing conversions between access to interfaces requires that
8868         --  the interface types themselves be frozen, so that dispatch table
8869         --  entities are properly created.
8870
8871         --  Unclear whether a more general rule is needed ???
8872
8873         elsif Nkind (Node) = N_Type_Conversion
8874           and then Is_Access_Type (Etype (Node))
8875           and then Is_Interface (Designated_Type (Etype (Node)))
8876         then
8877            Check_And_Freeze_Type (Designated_Type (Etype (Node)));
8878         end if;
8879
8880         --  An implicit dereference freezes the designated type. In the case
8881         --  of a dispatching call whose controlling argument is an access
8882         --  type, the dereference is not made explicit, so we must check for
8883         --  such a call and freeze the designated type.
8884
8885         if Nkind (Node) in N_Has_Etype
8886           and then Present (Etype (Node))
8887           and then Is_Access_Type (Etype (Node))
8888         then
8889            if Nkind (Parent (Node)) = N_Function_Call
8890              and then Node = Controlling_Argument (Parent (Node))
8891            then
8892               Check_And_Freeze_Type (Designated_Type (Etype (Node)));
8893
8894            --  An explicit dereference freezes the designated type as well,
8895            --  even though that type is not attached to an entity in the
8896            --  expression.
8897
8898            elsif Nkind (Parent (Node)) = N_Explicit_Dereference then
8899               Check_And_Freeze_Type (Designated_Type (Etype (Node)));
8900            end if;
8901
8902         --  An iterator specification freezes the iterator type, even though
8903         --  that type is not attached to an entity in the construct.
8904
8905         elsif Nkind (Node) in N_Has_Etype
8906           and then Nkind (Parent (Node)) = N_Iterator_Specification
8907           and then Node = Name (Parent (Node))
8908         then
8909            declare
8910               Iter : constant Node_Id :=
8911                 Find_Value_Of_Aspect (Etype (Node), Aspect_Default_Iterator);
8912
8913            begin
8914               if Present (Iter) then
8915                  Check_And_Freeze_Type (Etype (Iter));
8916               end if;
8917            end;
8918         end if;
8919
8920         --  No point in posting several errors on the same expression
8921
8922         if Serious_Errors_Detected > 0 then
8923            return Abandon;
8924         else
8925            return OK;
8926         end if;
8927      end Freeze_Type_Refs;
8928
8929      procedure Freeze_References is new Traverse_Proc (Freeze_Type_Refs);
8930
8931      --  Local variables
8932
8933      Saved_First_Entity : constant Entity_Id := First_Entity (Def_Id);
8934      Saved_Last_Entity  : constant Entity_Id := Last_Entity  (Def_Id);
8935      Dup_Expr           : constant Node_Id   := Cloned_Expression;
8936
8937   --  Start of processing for Freeze_Expr_Types
8938
8939   begin
8940      --  Preanalyze a duplicate of the expression to have available the
8941      --  minimum decoration needed to locate referenced unfrozen types
8942      --  without adding any decoration to the function expression.
8943
8944      --  This routine is also applied to expressions in the contract for
8945      --  the subprogram. If that happens when expanding the code for
8946      --  pre/postconditions during expansion of the subprogram body, the
8947      --  subprogram is already installed.
8948
8949      if Def_Id /= Current_Scope then
8950         Push_Scope (Def_Id);
8951         Install_Formals (Def_Id);
8952
8953         Preanalyze_Spec_Expression (Dup_Expr, Typ);
8954         End_Scope;
8955      else
8956         Preanalyze_Spec_Expression (Dup_Expr, Typ);
8957      end if;
8958
8959      --  Restore certain attributes of Def_Id since the preanalysis may
8960      --  have introduced itypes to this scope, thus modifying attributes
8961      --  First_Entity and Last_Entity.
8962
8963      Set_First_Entity (Def_Id, Saved_First_Entity);
8964      Set_Last_Entity  (Def_Id, Saved_Last_Entity);
8965
8966      if Present (Last_Entity (Def_Id)) then
8967         Set_Next_Entity (Last_Entity (Def_Id), Empty);
8968      end if;
8969
8970      --  Freeze all types referenced in the expression
8971
8972      Freeze_References (Dup_Expr);
8973   end Freeze_Expr_Types;
8974
8975   -----------------------------
8976   -- Freeze_Fixed_Point_Type --
8977   -----------------------------
8978
8979   --  Certain fixed-point types and subtypes, including implicit base types
8980   --  and declared first subtypes, have not yet set up a range. This is
8981   --  because the range cannot be set until the Small and Size values are
8982   --  known, and these are not known till the type is frozen.
8983
8984   --  To signal this case, Scalar_Range contains an unanalyzed syntactic range
8985   --  whose bounds are unanalyzed real literals. This routine will recognize
8986   --  this case, and transform this range node into a properly typed range
8987   --  with properly analyzed and resolved values.
8988
8989   procedure Freeze_Fixed_Point_Type (Typ : Entity_Id) is
8990      Rng   : constant Node_Id    := Scalar_Range (Typ);
8991      Lo    : constant Node_Id    := Low_Bound (Rng);
8992      Hi    : constant Node_Id    := High_Bound (Rng);
8993      Btyp  : constant Entity_Id  := Base_Type (Typ);
8994      Brng  : constant Node_Id    := Scalar_Range (Btyp);
8995      BLo   : constant Node_Id    := Low_Bound (Brng);
8996      BHi   : constant Node_Id    := High_Bound (Brng);
8997      Ftyp  : constant Entity_Id  := Underlying_Type (First_Subtype (Typ));
8998
8999      Small : Ureal;
9000      Loval : Ureal;
9001      Hival : Ureal;
9002      Atype : Entity_Id;
9003
9004      Orig_Lo : Ureal;
9005      Orig_Hi : Ureal;
9006      --  Save original bounds (for shaving tests)
9007
9008      Actual_Size : Int;
9009      --  Actual size chosen
9010
9011      function Fsize (Lov, Hiv : Ureal) return Int;
9012      --  Returns size of type with given bounds. Also leaves these
9013      --  bounds set as the current bounds of the Typ.
9014
9015      function Larger (A, B : Ureal) return Boolean;
9016      --  Returns true if A > B with a margin of Typ'Small
9017
9018      function Smaller (A, B : Ureal) return Boolean;
9019      --  Returns true if A < B with a margin of Typ'Small
9020
9021      -----------
9022      -- Fsize --
9023      -----------
9024
9025      function Fsize (Lov, Hiv : Ureal) return Int is
9026      begin
9027         Set_Realval (Lo, Lov);
9028         Set_Realval (Hi, Hiv);
9029         return Minimum_Size (Typ);
9030      end Fsize;
9031
9032      ------------
9033      -- Larger --
9034      ------------
9035
9036      function Larger (A, B : Ureal) return Boolean is
9037      begin
9038         return A > B and then A - Small_Value (Typ) > B;
9039      end Larger;
9040
9041      -------------
9042      -- Smaller --
9043      -------------
9044
9045      function Smaller (A, B : Ureal) return Boolean is
9046      begin
9047         return A < B and then A + Small_Value (Typ) < B;
9048      end Smaller;
9049
9050   --  Start of processing for Freeze_Fixed_Point_Type
9051
9052   begin
9053      --  The type, or its first subtype if we are freezing the anonymous
9054      --  base, may have a delayed Small aspect. It must be analyzed now,
9055      --  so that all characteristics of the type (size, bounds) can be
9056      --  computed and validated in the call to Minimum_Size that follows.
9057
9058      if Has_Delayed_Aspects (Ftyp) then
9059         Analyze_Aspects_At_Freeze_Point (Ftyp);
9060         Set_Has_Delayed_Aspects (Ftyp, False);
9061      end if;
9062
9063      --  Inherit the Small value from the first subtype in any case
9064
9065      if Typ /= Ftyp then
9066         Set_Small_Value (Typ, Small_Value (Ftyp));
9067      end if;
9068
9069      --  If Esize of a subtype has not previously been set, set it now
9070
9071      if not Known_Esize (Typ) then
9072         Atype := Ancestor_Subtype (Typ);
9073
9074         if Present (Atype) then
9075            Set_Esize (Typ, Esize (Atype));
9076         else
9077            Copy_Esize (To => Typ, From => Btyp);
9078         end if;
9079      end if;
9080
9081      --  Immediate return if the range is already analyzed. This means that
9082      --  the range is already set, and does not need to be computed by this
9083      --  routine.
9084
9085      if Analyzed (Rng) then
9086         return;
9087      end if;
9088
9089      --  Immediate return if either of the bounds raises Constraint_Error
9090
9091      if Raises_Constraint_Error (Lo)
9092        or else Raises_Constraint_Error (Hi)
9093      then
9094         return;
9095      end if;
9096
9097      Small := Small_Value (Typ);
9098      Loval := Realval (Lo);
9099      Hival := Realval (Hi);
9100
9101      Orig_Lo := Loval;
9102      Orig_Hi := Hival;
9103
9104      --  Ordinary fixed-point case
9105
9106      if Is_Ordinary_Fixed_Point_Type (Typ) then
9107
9108         --  For the ordinary fixed-point case, we are allowed to fudge the
9109         --  end-points up or down by small. Generally we prefer to fudge up,
9110         --  i.e. widen the bounds for non-model numbers so that the end points
9111         --  are included. However there are cases in which this cannot be
9112         --  done, and indeed cases in which we may need to narrow the bounds.
9113         --  The following circuit makes the decision.
9114
9115         --  Note: our terminology here is that Incl_EP means that the bounds
9116         --  are widened by Small if necessary to include the end points, and
9117         --  Excl_EP means that the bounds are narrowed by Small to exclude the
9118         --  end-points if this reduces the size.
9119
9120         --  Note that in the Incl case, all we care about is including the
9121         --  end-points. In the Excl case, we want to narrow the bounds as
9122         --  much as permitted by the RM, to give the smallest possible size.
9123
9124         Fudge : declare
9125            Loval_Incl_EP : Ureal;
9126            Hival_Incl_EP : Ureal;
9127
9128            Loval_Excl_EP : Ureal;
9129            Hival_Excl_EP : Ureal;
9130
9131            Size_Incl_EP  : Int;
9132            Size_Excl_EP  : Int;
9133
9134            Model_Num     : Ureal;
9135            Actual_Lo     : Ureal;
9136            Actual_Hi     : Ureal;
9137
9138         begin
9139            --  First step. Base types are required to be symmetrical. Right
9140            --  now, the base type range is a copy of the first subtype range.
9141            --  This will be corrected before we are done, but right away we
9142            --  need to deal with the case where both bounds are non-negative.
9143            --  In this case, we set the low bound to the negative of the high
9144            --  bound, to make sure that the size is computed to include the
9145            --  required sign. Note that we do not need to worry about the
9146            --  case of both bounds negative, because the sign will be dealt
9147            --  with anyway. Furthermore we can't just go making such a bound
9148            --  symmetrical, since in a twos-complement system, there is an
9149            --  extra negative value which could not be accommodated on the
9150            --  positive side.
9151
9152            if Typ = Btyp
9153              and then not UR_Is_Negative (Loval)
9154              and then Hival > Loval
9155            then
9156               Loval := -Hival;
9157               Set_Realval (Lo, Loval);
9158            end if;
9159
9160            --  Compute the fudged bounds. If the bound is a model number, (or
9161            --  greater if given low bound, smaller if high bound) then we do
9162            --  nothing to include it, but we are allowed to backoff to the
9163            --  next adjacent model number when we exclude it. If it is not a
9164            --  model number then we straddle the two values with the model
9165            --  numbers on either side.
9166
9167            Model_Num := UR_Trunc (Loval / Small) * Small;
9168
9169            if UR_Ge (Loval, Model_Num) then
9170               Loval_Incl_EP := Model_Num;
9171            else
9172               Loval_Incl_EP := Model_Num - Small;
9173            end if;
9174
9175            --  The low value excluding the end point is Small greater, but
9176            --  we do not do this exclusion if the low value is positive,
9177            --  since it can't help the size and could actually hurt by
9178            --  crossing the high bound.
9179
9180            if UR_Is_Negative (Loval_Incl_EP) then
9181               Loval_Excl_EP := Loval_Incl_EP + Small;
9182
9183               --  If the value went from negative to zero, then we have the
9184               --  case where Loval_Incl_EP is the model number just below
9185               --  zero, so we want to stick to the negative value for the
9186               --  base type to maintain the condition that the size will
9187               --  include signed values.
9188
9189               if Typ = Btyp
9190                 and then UR_Is_Zero (Loval_Excl_EP)
9191               then
9192                  Loval_Excl_EP := Loval_Incl_EP;
9193               end if;
9194
9195            else
9196               Loval_Excl_EP := Loval_Incl_EP;
9197            end if;
9198
9199            --  Similar processing for upper bound and high value
9200
9201            Model_Num := UR_Trunc (Hival / Small) * Small;
9202
9203            if UR_Le (Hival, Model_Num) then
9204               Hival_Incl_EP := Model_Num;
9205            else
9206               Hival_Incl_EP := Model_Num + Small;
9207            end if;
9208
9209            if UR_Is_Positive (Hival_Incl_EP) then
9210               Hival_Excl_EP := Hival_Incl_EP - Small;
9211            else
9212               Hival_Excl_EP := Hival_Incl_EP;
9213            end if;
9214
9215            --  One further adjustment is needed. In the case of subtypes, we
9216            --  cannot go outside the range of the base type, or we get
9217            --  peculiarities, and the base type range is already set. This
9218            --  only applies to the Incl values, since clearly the Excl values
9219            --  are already as restricted as they are allowed to be.
9220
9221            if Typ /= Btyp then
9222               Loval_Incl_EP := UR_Max (Loval_Incl_EP, Realval (BLo));
9223               Hival_Incl_EP := UR_Min (Hival_Incl_EP, Realval (BHi));
9224            end if;
9225
9226            --  Get size including and excluding end points
9227
9228            Size_Incl_EP := Fsize (Loval_Incl_EP, Hival_Incl_EP);
9229            Size_Excl_EP := Fsize (Loval_Excl_EP, Hival_Excl_EP);
9230
9231            --  No need to exclude end-points if it does not reduce size
9232
9233            if Fsize (Loval_Incl_EP, Hival_Excl_EP) = Size_Excl_EP then
9234               Loval_Excl_EP := Loval_Incl_EP;
9235            end if;
9236
9237            if Fsize (Loval_Excl_EP, Hival_Incl_EP) = Size_Excl_EP then
9238               Hival_Excl_EP := Hival_Incl_EP;
9239            end if;
9240
9241            --  Now we set the actual size to be used. We want to use the
9242            --  bounds fudged up to include the end-points but only if this
9243            --  can be done without violating a specifically given size
9244            --  size clause or causing an unacceptable increase in size.
9245
9246            --  Case of size clause given
9247
9248            if Has_Size_Clause (Typ) then
9249
9250               --  Use the inclusive size only if it is consistent with
9251               --  the explicitly specified size.
9252
9253               if Size_Incl_EP <= RM_Size (Typ) then
9254                  Actual_Lo   := Loval_Incl_EP;
9255                  Actual_Hi   := Hival_Incl_EP;
9256                  Actual_Size := Size_Incl_EP;
9257
9258               --  If the inclusive size is too large, we try excluding
9259               --  the end-points (will be caught later if does not work).
9260
9261               else
9262                  Actual_Lo   := Loval_Excl_EP;
9263                  Actual_Hi   := Hival_Excl_EP;
9264                  Actual_Size := Size_Excl_EP;
9265               end if;
9266
9267            --  Case of size clause not given
9268
9269            else
9270               --  If we have a base type whose corresponding first subtype
9271               --  has an explicit size that is large enough to include our
9272               --  end-points, then do so. There is no point in working hard
9273               --  to get a base type whose size is smaller than the specified
9274               --  size of the first subtype.
9275
9276               if Has_Size_Clause (Ftyp)
9277                 and then Size_Incl_EP <= Esize (Ftyp)
9278               then
9279                  Actual_Size := Size_Incl_EP;
9280                  Actual_Lo   := Loval_Incl_EP;
9281                  Actual_Hi   := Hival_Incl_EP;
9282
9283               --  If excluding the end-points makes the size smaller and
9284               --  results in a size of 8,16,32,64, then we take the smaller
9285               --  size. For the 64 case, this is compulsory. For the other
9286               --  cases, it seems reasonable. We like to include end points
9287               --  if we can, but not at the expense of moving to the next
9288               --  natural boundary of size.
9289
9290               elsif Size_Incl_EP /= Size_Excl_EP
9291                 and then Addressable (Size_Excl_EP)
9292               then
9293                  Actual_Size := Size_Excl_EP;
9294                  Actual_Lo   := Loval_Excl_EP;
9295                  Actual_Hi   := Hival_Excl_EP;
9296
9297               --  Otherwise we can definitely include the end points
9298
9299               else
9300                  Actual_Size := Size_Incl_EP;
9301                  Actual_Lo   := Loval_Incl_EP;
9302                  Actual_Hi   := Hival_Incl_EP;
9303               end if;
9304
9305               --  One pathological case: normally we never fudge a low bound
9306               --  down, since it would seem to increase the size (if it has
9307               --  any effect), but for ranges containing single value, or no
9308               --  values, the high bound can be small too large. Consider:
9309
9310               --    type t is delta 2.0**(-14)
9311               --      range 131072.0 .. 0;
9312
9313               --  That lower bound is *just* outside the range of 32 bits, and
9314               --  does need fudging down in this case. Note that the bounds
9315               --  will always have crossed here, since the high bound will be
9316               --  fudged down if necessary, as in the case of:
9317
9318               --    type t is delta 2.0**(-14)
9319               --      range 131072.0 .. 131072.0;
9320
9321               --  So we detect the situation by looking for crossed bounds,
9322               --  and if the bounds are crossed, and the low bound is greater
9323               --  than zero, we will always back it off by small, since this
9324               --  is completely harmless.
9325
9326               if Actual_Lo > Actual_Hi then
9327                  if UR_Is_Positive (Actual_Lo) then
9328                     Actual_Lo   := Loval_Incl_EP - Small;
9329                     Actual_Size := Fsize (Actual_Lo, Actual_Hi);
9330
9331                  --  And of course, we need to do exactly the same parallel
9332                  --  fudge for flat ranges in the negative region.
9333
9334                  elsif UR_Is_Negative (Actual_Hi) then
9335                     Actual_Hi := Hival_Incl_EP + Small;
9336                     Actual_Size := Fsize (Actual_Lo, Actual_Hi);
9337                  end if;
9338               end if;
9339            end if;
9340
9341            Set_Realval (Lo, Actual_Lo);
9342            Set_Realval (Hi, Actual_Hi);
9343         end Fudge;
9344
9345         --  Enforce some limitations for ordinary fixed-point types. They come
9346         --  from an exact algorithm used to implement Text_IO.Fixed_IO and the
9347         --  Fore, Image and Value attributes. The requirement on the Small is
9348         --  to lie in the range 2**(-(Siz - 1)) .. 2**(Siz - 1) for a type of
9349         --  Siz bits (Siz=32,64,128) and the requirement on the bounds is to
9350         --  be smaller in magnitude than 10.0**N * 2**(Siz - 1), where N is
9351         --  given by the formula N = floor ((Siz - 1) * log 2 / log 10).
9352
9353         --  If the bounds of a 32-bit type are too large, force 64-bit type
9354
9355         if Actual_Size <= 32
9356           and then Small <= Ureal_2_31
9357           and then (Smaller (Expr_Value_R (Lo), Ureal_M_2_10_18)
9358                      or else Larger (Expr_Value_R (Hi), Ureal_2_10_18))
9359         then
9360            Actual_Size := 33;
9361         end if;
9362
9363         --  If the bounds of a 64-bit type are too large, force 128-bit type
9364
9365         if System_Max_Integer_Size = 128
9366           and then Actual_Size <= 64
9367           and then Small <= Ureal_2_63
9368           and then (Smaller (Expr_Value_R (Lo), Ureal_M_9_10_36)
9369                      or else Larger (Expr_Value_R (Hi), Ureal_9_10_36))
9370         then
9371            Actual_Size := 65;
9372         end if;
9373
9374         --  Give error messages for first subtypes and not base types, as the
9375         --  bounds of base types are always maximum for their size, see below.
9376
9377         if System_Max_Integer_Size < 128 and then Typ /= Btyp then
9378
9379            --  See the 128-bit case below for the reason why we cannot test
9380            --  against the 2**(-63) .. 2**63 range. This quirk should have
9381            --  been kludged around as in the 128-bit case below, but it was
9382            --  not and we end up with a ludicrous range as a result???
9383
9384            if Small < Ureal_2_M_80 then
9385               Error_Msg_Name_1 := Name_Small;
9386               Error_Msg_N
9387                 ("`&''%` too small, minimum allowed is 2.0'*'*(-80)", Typ);
9388
9389            elsif Small > Ureal_2_80 then
9390               Error_Msg_Name_1 := Name_Small;
9391               Error_Msg_N
9392                 ("`&''%` too large, maximum allowed is 2.0'*'*80", Typ);
9393            end if;
9394
9395            if Smaller (Expr_Value_R (Lo), Ureal_M_9_10_36) then
9396               Error_Msg_Name_1 := Name_First;
9397               Error_Msg_N
9398                 ("`&''%` too small, minimum allowed is -9.0E+36", Typ);
9399            end if;
9400
9401            if Larger (Expr_Value_R (Hi), Ureal_9_10_36) then
9402               Error_Msg_Name_1 := Name_Last;
9403               Error_Msg_N
9404                 ("`&''%` too large, maximum allowed is 9.0E+36", Typ);
9405            end if;
9406
9407         elsif System_Max_Integer_Size = 128 and then Typ /= Btyp then
9408
9409            --  ACATS c35902d tests a delta equal to 2**(-(Max_Mantissa + 1))
9410            --  but we cannot really support anything smaller than Fine_Delta
9411            --  because of the way we implement I/O for fixed point types???
9412
9413            if Small = Ureal_2_M_128 then
9414               null;
9415
9416            elsif Small < Ureal_2_M_127 then
9417               Error_Msg_Name_1 := Name_Small;
9418               Error_Msg_N
9419                 ("`&''%` too small, minimum allowed is 2.0'*'*(-127)", Typ);
9420
9421            elsif Small > Ureal_2_127 then
9422               Error_Msg_Name_1 := Name_Small;
9423               Error_Msg_N
9424                 ("`&''%` too large, maximum allowed is 2.0'*'*127", Typ);
9425            end if;
9426
9427            if Actual_Size > 64
9428              and then (Norm_Num (Small) > Uint_2 ** 127
9429                         or else Norm_Den (Small) > Uint_2 ** 127)
9430              and then Small /= Ureal_2_M_128
9431            then
9432               Error_Msg_Name_1 := Name_Small;
9433               Error_Msg_N
9434                 ("`&''%` not the ratio of two 128-bit integers", Typ);
9435            end if;
9436
9437            if Smaller (Expr_Value_R (Lo), Ureal_M_10_76) then
9438               Error_Msg_Name_1 := Name_First;
9439               Error_Msg_N
9440                 ("`&''%` too small, minimum allowed is -1.0E+76", Typ);
9441            end if;
9442
9443            if Larger (Expr_Value_R (Hi), Ureal_10_76) then
9444               Error_Msg_Name_1 := Name_Last;
9445               Error_Msg_N
9446                 ("`&''%` too large, maximum allowed is 1.0E+76", Typ);
9447            end if;
9448         end if;
9449
9450      --  For the decimal case, none of this fudging is required, since there
9451      --  are no end-point problems in the decimal case (the end-points are
9452      --  always included).
9453
9454      else
9455         Actual_Size := Fsize (Loval, Hival);
9456      end if;
9457
9458      --  At this stage, the actual size has been calculated and the proper
9459      --  required bounds are stored in the low and high bounds.
9460
9461      if Actual_Size > System_Max_Integer_Size then
9462         Error_Msg_Uint_1 := UI_From_Int (Actual_Size);
9463         Error_Msg_Uint_2 := UI_From_Int (System_Max_Integer_Size);
9464         Error_Msg_N
9465           ("size required (^) for type& too large, maximum allowed is ^",
9466            Typ);
9467         Actual_Size := System_Max_Integer_Size;
9468      end if;
9469
9470      --  Check size against explicit given size
9471
9472      if Has_Size_Clause (Typ) then
9473         if Actual_Size > RM_Size (Typ) then
9474            Error_Msg_Uint_1 := RM_Size (Typ);
9475            Error_Msg_Uint_2 := UI_From_Int (Actual_Size);
9476            Error_Msg_NE
9477              ("size given (^) for type& too small, minimum allowed is ^",
9478               Size_Clause (Typ), Typ);
9479
9480         else
9481            Actual_Size := UI_To_Int (Esize (Typ));
9482         end if;
9483
9484      --  Increase size to next natural boundary if no size clause given
9485
9486      else
9487         if Actual_Size <= 8 then
9488            Actual_Size := 8;
9489         elsif Actual_Size <= 16 then
9490            Actual_Size := 16;
9491         elsif Actual_Size <= 32 then
9492            Actual_Size := 32;
9493         elsif Actual_Size <= 64 then
9494            Actual_Size := 64;
9495         else
9496            Actual_Size := 128;
9497         end if;
9498
9499         Set_Esize (Typ, UI_From_Int (Actual_Size));
9500         Adjust_Esize_For_Alignment (Typ);
9501      end if;
9502
9503      --  If we have a base type, then expand the bounds so that they extend to
9504      --  the full width of the allocated size in bits, to avoid junk range
9505      --  checks on intermediate computations.
9506
9507      if Typ = Btyp then
9508         Set_Realval (Lo, -(Small * (Uint_2 ** (Actual_Size - 1))));
9509         Set_Realval (Hi,  (Small * (Uint_2 ** (Actual_Size - 1) - 1)));
9510      end if;
9511
9512      --  Final step is to reanalyze the bounds using the proper type
9513      --  and set the Corresponding_Integer_Value fields of the literals.
9514
9515      Set_Etype (Lo, Empty);
9516      Set_Analyzed (Lo, False);
9517      Analyze (Lo);
9518
9519      --  Resolve with universal fixed if the base type, and with the base
9520      --  type if we are freezing a subtype. Note we can't resolve the base
9521      --  type with itself, that would be a reference before definition.
9522      --  The resolution of the bounds of a subtype, if they are given by real
9523      --  literals,  includes the setting of the Corresponding_Integer_Value,
9524      --  as for other literals of a fixed-point type.
9525
9526      if Typ = Btyp then
9527         Resolve (Lo, Universal_Fixed);
9528         Set_Corresponding_Integer_Value
9529           (Lo, UR_To_Uint (Realval (Lo) / Small));
9530      else
9531         Resolve (Lo, Btyp);
9532      end if;
9533
9534      --  Similar processing for high bound
9535
9536      Set_Etype (Hi, Empty);
9537      Set_Analyzed (Hi, False);
9538      Analyze (Hi);
9539
9540      if Typ = Btyp then
9541         Resolve (Hi, Universal_Fixed);
9542         Set_Corresponding_Integer_Value
9543           (Hi, UR_To_Uint (Realval (Hi) / Small));
9544      else
9545         Resolve (Hi, Btyp);
9546      end if;
9547
9548      --  Set type of range to correspond to bounds
9549
9550      Set_Etype (Rng, Etype (Lo));
9551
9552      --  Set Esize to calculated size if not set already
9553
9554      if not Known_Esize (Typ) then
9555         Set_Esize (Typ, UI_From_Int (Actual_Size));
9556      end if;
9557
9558      --  Set RM_Size if not already set. If already set, check value
9559
9560      declare
9561         Minsiz : constant Uint := UI_From_Int (Minimum_Size (Typ));
9562
9563      begin
9564         if Known_RM_Size (Typ) then
9565            if RM_Size (Typ) < Minsiz then
9566               Error_Msg_Uint_1 := RM_Size (Typ);
9567               Error_Msg_Uint_2 := Minsiz;
9568               Error_Msg_NE
9569                 ("size given (^) for type& too small, minimum allowed is ^",
9570                  Size_Clause (Typ), Typ);
9571            end if;
9572
9573         else
9574            Set_RM_Size (Typ, Minsiz);
9575         end if;
9576      end;
9577
9578      --  Check for shaving
9579
9580      if Comes_From_Source (Typ) then
9581
9582         --  In SPARK mode the given bounds must be strictly representable
9583
9584         if SPARK_Mode = On then
9585            if Orig_Lo < Expr_Value_R (Lo) then
9586               Error_Msg_NE
9587                 ("declared low bound of type & is outside type range",
9588                  Lo, Typ);
9589            end if;
9590
9591            if Orig_Hi > Expr_Value_R (Hi) then
9592               Error_Msg_NE
9593                 ("declared high bound of type & is outside type range",
9594                  Hi, Typ);
9595            end if;
9596
9597         else
9598            if Orig_Lo < Expr_Value_R (Lo) then
9599               Error_Msg_N
9600                 ("declared low bound of type & is outside type range??", Typ);
9601               Error_Msg_N
9602                 ("\low bound adjusted up by delta (RM 3.5.9(13))??", Typ);
9603            end if;
9604
9605            if Orig_Hi > Expr_Value_R (Hi) then
9606               Error_Msg_N
9607                 ("declared high bound of type & is outside type range??",
9608                  Typ);
9609               Error_Msg_N
9610                 ("\high bound adjusted down by delta (RM 3.5.9(13))??", Typ);
9611            end if;
9612         end if;
9613      end if;
9614   end Freeze_Fixed_Point_Type;
9615
9616   ------------------
9617   -- Freeze_Itype --
9618   ------------------
9619
9620   procedure Freeze_Itype (T : Entity_Id; N : Node_Id) is
9621      L : List_Id;
9622
9623   begin
9624      Set_Has_Delayed_Freeze (T);
9625      L := Freeze_Entity (T, N);
9626
9627      if Is_Non_Empty_List (L) then
9628         Insert_Actions (N, L);
9629      end if;
9630   end Freeze_Itype;
9631
9632   --------------------------
9633   -- Freeze_Static_Object --
9634   --------------------------
9635
9636   procedure Freeze_Static_Object (E : Entity_Id) is
9637
9638      Cannot_Be_Static : exception;
9639      --  Exception raised if the type of a static object cannot be made
9640      --  static. This happens if the type depends on non-global objects.
9641
9642      procedure Ensure_Expression_Is_SA (N : Node_Id);
9643      --  Called to ensure that an expression used as part of a type definition
9644      --  is statically allocatable, which means that the expression type is
9645      --  statically allocatable, and the expression is either static, or a
9646      --  reference to a library level constant.
9647
9648      procedure Ensure_Type_Is_SA (Typ : Entity_Id);
9649      --  Called to mark a type as static, checking that it is possible
9650      --  to set the type as static. If it is not possible, then the
9651      --  exception Cannot_Be_Static is raised.
9652
9653      -----------------------------
9654      -- Ensure_Expression_Is_SA --
9655      -----------------------------
9656
9657      procedure Ensure_Expression_Is_SA (N : Node_Id) is
9658         Ent : Entity_Id;
9659
9660      begin
9661         Ensure_Type_Is_SA (Etype (N));
9662
9663         if Is_OK_Static_Expression (N) then
9664            return;
9665
9666         elsif Nkind (N) = N_Identifier then
9667            Ent := Entity (N);
9668
9669            if Present (Ent)
9670              and then Ekind (Ent) = E_Constant
9671              and then Is_Library_Level_Entity (Ent)
9672            then
9673               return;
9674            end if;
9675         end if;
9676
9677         raise Cannot_Be_Static;
9678      end Ensure_Expression_Is_SA;
9679
9680      -----------------------
9681      -- Ensure_Type_Is_SA --
9682      -----------------------
9683
9684      procedure Ensure_Type_Is_SA (Typ : Entity_Id) is
9685         N : Node_Id;
9686         C : Entity_Id;
9687
9688      begin
9689         --  If type is library level, we are all set
9690
9691         if Is_Library_Level_Entity (Typ) then
9692            return;
9693         end if;
9694
9695         --  We are also OK if the type already marked as statically allocated,
9696         --  which means we processed it before.
9697
9698         if Is_Statically_Allocated (Typ) then
9699            return;
9700         end if;
9701
9702         --  Mark type as statically allocated
9703
9704         Set_Is_Statically_Allocated (Typ);
9705
9706         --  Check that it is safe to statically allocate this type
9707
9708         if Is_Scalar_Type (Typ) or else Is_Real_Type (Typ) then
9709            Ensure_Expression_Is_SA (Type_Low_Bound (Typ));
9710            Ensure_Expression_Is_SA (Type_High_Bound (Typ));
9711
9712         elsif Is_Array_Type (Typ) then
9713            N := First_Index (Typ);
9714            while Present (N) loop
9715               Ensure_Type_Is_SA (Etype (N));
9716               Next_Index (N);
9717            end loop;
9718
9719            Ensure_Type_Is_SA (Component_Type (Typ));
9720
9721         elsif Is_Access_Type (Typ) then
9722            if Ekind (Designated_Type (Typ)) = E_Subprogram_Type then
9723
9724               declare
9725                  F : Entity_Id;
9726                  T : constant Entity_Id := Etype (Designated_Type (Typ));
9727
9728               begin
9729                  if T /= Standard_Void_Type then
9730                     Ensure_Type_Is_SA (T);
9731                  end if;
9732
9733                  F := First_Formal (Designated_Type (Typ));
9734                  while Present (F) loop
9735                     Ensure_Type_Is_SA (Etype (F));
9736                     Next_Formal (F);
9737                  end loop;
9738               end;
9739
9740            else
9741               Ensure_Type_Is_SA (Designated_Type (Typ));
9742            end if;
9743
9744         elsif Is_Record_Type (Typ) then
9745            C := First_Entity (Typ);
9746            while Present (C) loop
9747               if Ekind (C) = E_Discriminant
9748                 or else Ekind (C) = E_Component
9749               then
9750                  Ensure_Type_Is_SA (Etype (C));
9751
9752               elsif Is_Type (C) then
9753                  Ensure_Type_Is_SA (C);
9754               end if;
9755
9756               Next_Entity (C);
9757            end loop;
9758
9759         elsif Ekind (Typ) = E_Subprogram_Type then
9760            Ensure_Type_Is_SA (Etype (Typ));
9761
9762            C := First_Formal (Typ);
9763            while Present (C) loop
9764               Ensure_Type_Is_SA (Etype (C));
9765               Next_Formal (C);
9766            end loop;
9767
9768         else
9769            raise Cannot_Be_Static;
9770         end if;
9771      end Ensure_Type_Is_SA;
9772
9773   --  Start of processing for Freeze_Static_Object
9774
9775   begin
9776      Ensure_Type_Is_SA (Etype (E));
9777
9778   exception
9779      when Cannot_Be_Static =>
9780
9781         --  If the object that cannot be static is imported or exported, then
9782         --  issue an error message saying that this object cannot be imported
9783         --  or exported. If it has an address clause it is an overlay in the
9784         --  current partition and the static requirement is not relevant.
9785         --  Do not issue any error message when ignoring rep clauses.
9786
9787         if Ignore_Rep_Clauses then
9788            null;
9789
9790         elsif Is_Imported (E) then
9791            if No (Address_Clause (E)) then
9792               Error_Msg_N
9793                 ("& cannot be imported (local type is not constant)", E);
9794            end if;
9795
9796         --  Otherwise must be exported, something is wrong if compiler
9797         --  is marking something as statically allocated which cannot be).
9798
9799         else pragma Assert (Is_Exported (E));
9800            Error_Msg_N
9801              ("& cannot be exported (local type is not constant)", E);
9802         end if;
9803   end Freeze_Static_Object;
9804
9805   -----------------------
9806   -- Freeze_Subprogram --
9807   -----------------------
9808
9809   procedure Freeze_Subprogram (E : Entity_Id) is
9810      function Check_Extra_Formals (E : Entity_Id) return Boolean;
9811      --  Return True if the decoration of the attributes associated with extra
9812      --  formals are properly set.
9813
9814      procedure Set_Profile_Convention (Subp_Id : Entity_Id);
9815      --  Set the conventions of all anonymous access-to-subprogram formals and
9816      --  result subtype of subprogram Subp_Id to the convention of Subp_Id.
9817
9818      -------------------------
9819      -- Check_Extra_Formals --
9820      -------------------------
9821
9822      function Check_Extra_Formals (E : Entity_Id) return Boolean is
9823         Last_Formal       : Entity_Id := Empty;
9824         Formal            : Entity_Id;
9825         Has_Extra_Formals : Boolean := False;
9826
9827      begin
9828         --  No check required if expansion is disabled because extra
9829         --  formals are only generated when we are generating code.
9830         --  See Create_Extra_Formals.
9831
9832         if not Expander_Active then
9833            return True;
9834         end if;
9835
9836         --  Check attribute Extra_Formal: If available, it must be set only
9837         --  on the last formal of E.
9838
9839         Formal := First_Formal (E);
9840         while Present (Formal) loop
9841            if Present (Extra_Formal (Formal)) then
9842               if Has_Extra_Formals then
9843                  return False;
9844               end if;
9845
9846               Has_Extra_Formals := True;
9847            end if;
9848
9849            Last_Formal := Formal;
9850            Next_Formal (Formal);
9851         end loop;
9852
9853         --  Check attribute Extra_Accessibility_Of_Result
9854
9855         if Ekind (E) in E_Function | E_Subprogram_Type
9856           and then Needs_Result_Accessibility_Level (E)
9857           and then No (Extra_Accessibility_Of_Result (E))
9858         then
9859            return False;
9860         end if;
9861
9862         --  Check attribute Extra_Formals: If E has extra formals, then this
9863         --  attribute must point to the first extra formal of E.
9864
9865         if Has_Extra_Formals then
9866            return Present (Extra_Formals (E))
9867              and then Present (Extra_Formal (Last_Formal))
9868              and then Extra_Formal (Last_Formal) = Extra_Formals (E);
9869
9870         --  When E has no formals, the first extra formal is available through
9871         --  the Extra_Formals attribute.
9872
9873         elsif Present (Extra_Formals (E)) then
9874            return No (First_Formal (E));
9875
9876         else
9877            return True;
9878         end if;
9879      end Check_Extra_Formals;
9880
9881      ----------------------------
9882      -- Set_Profile_Convention --
9883      ----------------------------
9884
9885      procedure Set_Profile_Convention (Subp_Id : Entity_Id) is
9886         Conv : constant Convention_Id := Convention (Subp_Id);
9887
9888         procedure Set_Type_Convention (Typ : Entity_Id);
9889         --  Set the convention of anonymous access-to-subprogram type Typ and
9890         --  its designated type to Conv.
9891
9892         -------------------------
9893         -- Set_Type_Convention --
9894         -------------------------
9895
9896         procedure Set_Type_Convention (Typ : Entity_Id) is
9897         begin
9898            --  Set the convention on both the anonymous access-to-subprogram
9899            --  type and the subprogram type it points to because both types
9900            --  participate in conformance-related checks.
9901
9902            if Ekind (Typ) = E_Anonymous_Access_Subprogram_Type then
9903               Set_Convention (Typ, Conv);
9904               Set_Convention (Designated_Type (Typ), Conv);
9905            end if;
9906         end Set_Type_Convention;
9907
9908         --  Local variables
9909
9910         Formal : Entity_Id;
9911
9912      --  Start of processing for Set_Profile_Convention
9913
9914      begin
9915         Formal := First_Formal (Subp_Id);
9916         while Present (Formal) loop
9917            Set_Type_Convention (Etype (Formal));
9918            Next_Formal (Formal);
9919         end loop;
9920
9921         if Ekind (Subp_Id) = E_Function then
9922            Set_Type_Convention (Etype (Subp_Id));
9923         end if;
9924      end Set_Profile_Convention;
9925
9926      --  Local variables
9927
9928      F      : Entity_Id;
9929      Retype : Entity_Id;
9930
9931   --  Start of processing for Freeze_Subprogram
9932
9933   begin
9934      --  Subprogram may not have an address clause unless it is imported
9935
9936      if Present (Address_Clause (E)) then
9937         if not Is_Imported (E) then
9938            Error_Msg_N
9939              ("address clause can only be given for imported subprogram",
9940               Name (Address_Clause (E)));
9941         end if;
9942      end if;
9943
9944      --  Reset the Pure indication on an imported subprogram unless an
9945      --  explicit Pure_Function pragma was present or the subprogram is an
9946      --  intrinsic. We do this because otherwise it is an insidious error
9947      --  to call a non-pure function from pure unit and have calls
9948      --  mysteriously optimized away. What happens here is that the Import
9949      --  can bypass the normal check to ensure that pure units call only pure
9950      --  subprograms.
9951
9952      --  The reason for the intrinsic exception is that in general, intrinsic
9953      --  functions (such as shifts) are pure anyway. The only exceptions are
9954      --  the intrinsics in GNAT.Source_Info, and that unit is not marked Pure
9955      --  in any case, so no problem arises.
9956
9957      if Is_Imported (E)
9958        and then Is_Pure (E)
9959        and then not Has_Pragma_Pure_Function (E)
9960        and then not Is_Intrinsic_Subprogram (E)
9961      then
9962         Set_Is_Pure (E, False);
9963      end if;
9964
9965      --  For C++ constructors check that their external name has been given
9966      --  (either in pragma CPP_Constructor or in a pragma import).
9967
9968      if Is_Constructor (E)
9969        and then Convention (E) = Convention_CPP
9970        and then
9971           (No (Interface_Name (E))
9972              or else String_Equal
9973                        (L => Strval (Interface_Name (E)),
9974                         R => Strval (Get_Default_External_Name (E))))
9975      then
9976         Error_Msg_N
9977           ("'C++ constructor must have external name or link name", E);
9978      end if;
9979
9980      --  We also reset the Pure indication on a subprogram with an Address
9981      --  parameter, because the parameter may be used as a pointer and the
9982      --  referenced data may change even if the address value does not.
9983
9984      --  Note that if the programmer gave an explicit Pure_Function pragma,
9985      --  then we believe the programmer, and leave the subprogram Pure. We
9986      --  also suppress this check on run-time files.
9987
9988      if Is_Pure (E)
9989        and then Is_Subprogram (E)
9990        and then not Has_Pragma_Pure_Function (E)
9991        and then not Is_Internal_Unit (Current_Sem_Unit)
9992      then
9993         Check_Function_With_Address_Parameter (E);
9994      end if;
9995
9996      --  Ensure that all anonymous access-to-subprogram types inherit the
9997      --  convention of their related subprogram (RM 6.3.1(13.1/5)). This is
9998      --  not done for a defaulted convention Ada because those types also
9999      --  default to Ada. Convention Protected must not be propagated when
10000      --  the subprogram is an entry because this would be illegal. The only
10001      --  way to force convention Protected on these kinds of types is to
10002      --  include keyword "protected" in the access definition. Conventions
10003      --  Entry and Intrinsic are also not propagated (specified by AI12-0207).
10004
10005      if Convention (E) /= Convention_Ada
10006        and then Convention (E) /= Convention_Protected
10007        and then Convention (E) /= Convention_Entry
10008        and then Convention (E) /= Convention_Intrinsic
10009      then
10010         Set_Profile_Convention (E);
10011      end if;
10012
10013      --  For non-foreign convention subprograms, this is where we create
10014      --  the extra formals (for accessibility level and constrained bit
10015      --  information). We delay this till the freeze point precisely so
10016      --  that we know the convention.
10017
10018      if not Has_Foreign_Convention (E) then
10019         if No (Extra_Formals (E)) then
10020
10021            --  Extra formals are shared by derived subprograms; therefore, if
10022            --  the ultimate alias of E has been frozen before E then the extra
10023            --  formals have been added, but the attribute Extra_Formals is
10024            --  still unset (and must be set now).
10025
10026            if Present (Alias (E))
10027              and then Is_Frozen (Ultimate_Alias (E))
10028              and then Present (Extra_Formals (Ultimate_Alias (E)))
10029              and then Last_Formal (Ultimate_Alias (E)) = Last_Formal (E)
10030            then
10031               Set_Extra_Formals (E, Extra_Formals (Ultimate_Alias (E)));
10032
10033               if Ekind (E) = E_Function then
10034                  Set_Extra_Accessibility_Of_Result (E,
10035                    Extra_Accessibility_Of_Result (Ultimate_Alias (E)));
10036               end if;
10037            else
10038               Create_Extra_Formals (E);
10039            end if;
10040         end if;
10041
10042         pragma Assert (Check_Extra_Formals (E));
10043         Set_Mechanisms (E);
10044
10045         --  If this is convention Ada and a Valued_Procedure, that's odd
10046
10047         if Ekind (E) = E_Procedure
10048           and then Is_Valued_Procedure (E)
10049           and then Convention (E) = Convention_Ada
10050           and then Warn_On_Export_Import
10051         then
10052            Error_Msg_N
10053              ("??Valued_Procedure has no effect for convention Ada", E);
10054            Set_Is_Valued_Procedure (E, False);
10055         end if;
10056
10057      --  Case of foreign convention
10058
10059      else
10060         Set_Mechanisms (E);
10061
10062         --  For foreign conventions, warn about return of unconstrained array
10063
10064         if Ekind (E) = E_Function then
10065            Retype := Underlying_Type (Etype (E));
10066
10067            --  If no return type, probably some other error, e.g. a
10068            --  missing full declaration, so ignore.
10069
10070            if No (Retype) then
10071               null;
10072
10073            --  If the return type is generic, we have emitted a warning
10074            --  earlier on, and there is nothing else to check here. Specific
10075            --  instantiations may lead to erroneous behavior.
10076
10077            elsif Is_Generic_Type (Etype (E)) then
10078               null;
10079
10080            --  Display warning if returning unconstrained array
10081
10082            elsif Is_Array_Type (Retype)
10083              and then not Is_Constrained (Retype)
10084
10085               --  Check appropriate warning is enabled (should we check for
10086               --  Warnings (Off) on specific entities here, probably so???)
10087
10088              and then Warn_On_Export_Import
10089            then
10090               Error_Msg_N
10091                ("?x?foreign convention function& should not return " &
10092                  "unconstrained array", E);
10093               return;
10094            end if;
10095         end if;
10096
10097         --  If any of the formals for an exported foreign convention
10098         --  subprogram have defaults, then emit an appropriate warning since
10099         --  this is odd (default cannot be used from non-Ada code)
10100
10101         if Is_Exported (E) then
10102            F := First_Formal (E);
10103            while Present (F) loop
10104               if Warn_On_Export_Import
10105                 and then Present (Default_Value (F))
10106               then
10107                  Error_Msg_N
10108                    ("?x?parameter cannot be defaulted in non-Ada call",
10109                     Default_Value (F));
10110               end if;
10111
10112               Next_Formal (F);
10113            end loop;
10114         end if;
10115      end if;
10116
10117      --  Pragma Inline_Always is disallowed for dispatching subprograms
10118      --  because the address of such subprograms is saved in the dispatch
10119      --  table to support dispatching calls, and dispatching calls cannot
10120      --  be inlined. This is consistent with the restriction against using
10121      --  'Access or 'Address on an Inline_Always subprogram.
10122
10123      if Is_Dispatching_Operation (E)
10124        and then Has_Pragma_Inline_Always (E)
10125      then
10126         Error_Msg_N
10127           ("pragma Inline_Always not allowed for dispatching subprograms", E);
10128      end if;
10129
10130      --  Because of the implicit representation of inherited predefined
10131      --  operators in the front-end, the overriding status of the operation
10132      --  may be affected when a full view of a type is analyzed, and this is
10133      --  not captured by the analysis of the corresponding type declaration.
10134      --  Therefore the correctness of a not-overriding indicator must be
10135      --  rechecked when the subprogram is frozen.
10136
10137      if Nkind (E) = N_Defining_Operator_Symbol
10138        and then not Error_Posted (Parent (E))
10139      then
10140         Check_Overriding_Indicator (E, Empty, Is_Primitive (E));
10141      end if;
10142
10143      Retype := Get_Fullest_View (Etype (E));
10144
10145      if Transform_Function_Array
10146        and then Nkind (Parent (E)) = N_Function_Specification
10147        and then Is_Array_Type (Retype)
10148        and then Is_Constrained (Retype)
10149        and then not Is_Unchecked_Conversion_Instance (E)
10150        and then not Rewritten_For_C (E)
10151      then
10152         Build_Procedure_Form (Unit_Declaration_Node (E));
10153      end if;
10154   end Freeze_Subprogram;
10155
10156   ----------------------
10157   -- Is_Fully_Defined --
10158   ----------------------
10159
10160   function Is_Fully_Defined (T : Entity_Id) return Boolean is
10161   begin
10162      if Ekind (T) = E_Class_Wide_Type then
10163         return Is_Fully_Defined (Etype (T));
10164
10165      elsif Is_Array_Type (T) then
10166         return Is_Fully_Defined (Component_Type (T));
10167
10168      elsif Is_Record_Type (T)
10169        and not Is_Private_Type (T)
10170      then
10171         --  Verify that the record type has no components with private types
10172         --  without completion.
10173
10174         declare
10175            Comp : Entity_Id;
10176
10177         begin
10178            Comp := First_Component (T);
10179            while Present (Comp) loop
10180               if not Is_Fully_Defined (Etype (Comp)) then
10181                  return False;
10182               end if;
10183
10184               Next_Component (Comp);
10185            end loop;
10186            return True;
10187         end;
10188
10189      --  For the designated type of an access to subprogram, all types in
10190      --  the profile must be fully defined.
10191
10192      elsif Ekind (T) = E_Subprogram_Type then
10193         declare
10194            F : Entity_Id;
10195
10196         begin
10197            F := First_Formal (T);
10198            while Present (F) loop
10199               if not Is_Fully_Defined (Etype (F)) then
10200                  return False;
10201               end if;
10202
10203               Next_Formal (F);
10204            end loop;
10205
10206            return Is_Fully_Defined (Etype (T));
10207         end;
10208
10209      else
10210         return not Is_Private_Type (T)
10211           or else Present (Full_View (Base_Type (T)));
10212      end if;
10213   end Is_Fully_Defined;
10214
10215   ---------------------------------
10216   -- Process_Default_Expressions --
10217   ---------------------------------
10218
10219   procedure Process_Default_Expressions
10220     (E     : Entity_Id;
10221      After : in out Node_Id)
10222   is
10223      Loc    : constant Source_Ptr := Sloc (E);
10224      Dbody  : Node_Id;
10225      Formal : Node_Id;
10226      Dcopy  : Node_Id;
10227      Dnam   : Entity_Id;
10228
10229   begin
10230      Set_Default_Expressions_Processed (E);
10231
10232      --  A subprogram instance and its associated anonymous subprogram share
10233      --  their signature. The default expression functions are defined in the
10234      --  wrapper packages for the anonymous subprogram, and should not be
10235      --  generated again for the instance.
10236
10237      if Is_Generic_Instance (E)
10238        and then Present (Alias (E))
10239        and then Default_Expressions_Processed (Alias (E))
10240      then
10241         return;
10242      end if;
10243
10244      Formal := First_Formal (E);
10245      while Present (Formal) loop
10246         if Present (Default_Value (Formal)) then
10247
10248            --  We work with a copy of the default expression because we
10249            --  do not want to disturb the original, since this would mess
10250            --  up the conformance checking.
10251
10252            Dcopy := New_Copy_Tree (Default_Value (Formal));
10253
10254            --  The analysis of the expression may generate insert actions,
10255            --  which of course must not be executed. We wrap those actions
10256            --  in a procedure that is not called, and later on eliminated.
10257            --  The following cases have no side effects, and are analyzed
10258            --  directly.
10259
10260            if Nkind (Dcopy) = N_Identifier
10261              or else Nkind (Dcopy) in N_Expanded_Name
10262                                     | N_Integer_Literal
10263                                     | N_Character_Literal
10264                                     | N_String_Literal
10265                                     | N_Real_Literal
10266              or else (Nkind (Dcopy) = N_Attribute_Reference
10267                        and then Attribute_Name (Dcopy) = Name_Null_Parameter)
10268              or else Known_Null (Dcopy)
10269            then
10270               --  If there is no default function, we must still do a full
10271               --  analyze call on the default value, to ensure that all error
10272               --  checks are performed, e.g. those associated with static
10273               --  evaluation. Note: this branch will always be taken if the
10274               --  analyzer is turned off (but we still need the error checks).
10275
10276               --  Note: the setting of parent here is to meet the requirement
10277               --  that we can only analyze the expression while attached to
10278               --  the tree. Really the requirement is that the parent chain
10279               --  be set, we don't actually need to be in the tree.
10280
10281               Set_Parent (Dcopy, Declaration_Node (Formal));
10282               Analyze (Dcopy);
10283
10284               --  Default expressions are resolved with their own type if the
10285               --  context is generic, to avoid anomalies with private types.
10286
10287               if Ekind (Scope (E)) = E_Generic_Package then
10288                  Resolve (Dcopy);
10289               else
10290                  Resolve (Dcopy, Etype (Formal));
10291               end if;
10292
10293               --  If that resolved expression will raise constraint error,
10294               --  then flag the default value as raising constraint error.
10295               --  This allows a proper error message on the calls.
10296
10297               if Raises_Constraint_Error (Dcopy) then
10298                  Set_Raises_Constraint_Error (Default_Value (Formal));
10299               end if;
10300
10301            --  If the default is a parameterless call, we use the name of
10302            --  the called function directly, and there is no body to build.
10303
10304            elsif Nkind (Dcopy) = N_Function_Call
10305              and then No (Parameter_Associations (Dcopy))
10306            then
10307               null;
10308
10309            --  Else construct and analyze the body of a wrapper procedure
10310            --  that contains an object declaration to hold the expression.
10311            --  Given that this is done only to complete the analysis, it is
10312            --  simpler to build a procedure than a function which might
10313            --  involve secondary stack expansion.
10314
10315            else
10316               Dnam := Make_Temporary (Loc, 'D');
10317
10318               Dbody :=
10319                 Make_Subprogram_Body (Loc,
10320                   Specification =>
10321                     Make_Procedure_Specification (Loc,
10322                       Defining_Unit_Name => Dnam),
10323
10324                   Declarations => New_List (
10325                     Make_Object_Declaration (Loc,
10326                       Defining_Identifier => Make_Temporary (Loc, 'T'),
10327                       Object_Definition   =>
10328                         New_Occurrence_Of (Etype (Formal), Loc),
10329                       Expression          => New_Copy_Tree (Dcopy))),
10330
10331                   Handled_Statement_Sequence =>
10332                     Make_Handled_Sequence_Of_Statements (Loc,
10333                       Statements => Empty_List));
10334
10335               Set_Scope (Dnam, Scope (E));
10336               Set_Assignment_OK (First (Declarations (Dbody)));
10337               Set_Is_Eliminated (Dnam);
10338               Insert_After (After, Dbody);
10339               Analyze (Dbody);
10340               After := Dbody;
10341            end if;
10342         end if;
10343
10344         Next_Formal (Formal);
10345      end loop;
10346   end Process_Default_Expressions;
10347
10348   ----------------------------------------
10349   -- Set_Component_Alignment_If_Not_Set --
10350   ----------------------------------------
10351
10352   procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id) is
10353   begin
10354      --  Ignore if not base type, subtypes don't need anything
10355
10356      if Typ /= Base_Type (Typ) then
10357         return;
10358      end if;
10359
10360      --  Do not override existing representation
10361
10362      if Is_Packed (Typ) then
10363         return;
10364
10365      elsif Has_Specified_Layout (Typ) then
10366         return;
10367
10368      elsif Component_Alignment (Typ) /= Calign_Default then
10369         return;
10370
10371      else
10372         Set_Component_Alignment
10373           (Typ, Scope_Stack.Table
10374                  (Scope_Stack.Last).Component_Alignment_Default);
10375      end if;
10376   end Set_Component_Alignment_If_Not_Set;
10377
10378   --------------------------
10379   -- Set_SSO_From_Default --
10380   --------------------------
10381
10382   procedure Set_SSO_From_Default (T : Entity_Id) is
10383      Reversed : Boolean;
10384
10385   begin
10386      --  Set default SSO for an array or record base type, except in case of
10387      --  a type extension (which always inherits the SSO of its parent type).
10388
10389      if Is_Base_Type (T)
10390        and then (Is_Array_Type (T)
10391                   or else (Is_Record_Type (T)
10392                             and then not (Is_Tagged_Type (T)
10393                                            and then Is_Derived_Type (T))))
10394      then
10395         Reversed :=
10396            (Bytes_Big_Endian     and then SSO_Set_Low_By_Default (T))
10397              or else
10398            (not Bytes_Big_Endian and then SSO_Set_High_By_Default (T));
10399
10400         if (SSO_Set_Low_By_Default (T) or else SSO_Set_High_By_Default (T))
10401
10402           --  For a record type, if bit order is specified explicitly,
10403           --  then do not set SSO from default if not consistent. Note that
10404           --  we do not want to look at a Bit_Order attribute definition
10405           --  for a parent: if we were to inherit Bit_Order, then both
10406           --  SSO_Set_*_By_Default flags would have been cleared already
10407           --  (by Inherit_Aspects_At_Freeze_Point).
10408
10409           and then not
10410             (Is_Record_Type (T)
10411               and then
10412                 Has_Rep_Item (T, Name_Bit_Order, Check_Parents => False)
10413               and then Reverse_Bit_Order (T) /= Reversed)
10414         then
10415            --  If flags cause reverse storage order, then set the result. Note
10416            --  that we would have ignored the pragma setting the non default
10417            --  storage order in any case, hence the assertion at this point.
10418
10419            pragma Assert
10420              (not Reversed or else Support_Nondefault_SSO_On_Target);
10421
10422            Set_Reverse_Storage_Order (T, Reversed);
10423
10424            --  For a record type, also set reversed bit order. Note: if a bit
10425            --  order has been specified explicitly, then this is a no-op.
10426
10427            if Is_Record_Type (T) then
10428               Set_Reverse_Bit_Order (T, Reversed);
10429            end if;
10430         end if;
10431      end if;
10432   end Set_SSO_From_Default;
10433
10434   ------------------
10435   -- Undelay_Type --
10436   ------------------
10437
10438   procedure Undelay_Type (T : Entity_Id) is
10439   begin
10440      Set_Has_Delayed_Freeze (T, False);
10441      Set_Freeze_Node (T, Empty);
10442
10443      --  Since we don't want T to have a Freeze_Node, we don't want its
10444      --  Full_View or Corresponding_Record_Type to have one either.
10445
10446      --  ??? Fundamentally, this whole handling is unpleasant. What we really
10447      --  want is to be sure that for an Itype that's part of record R and is a
10448      --  subtype of type T, that it's frozen after the later of the freeze
10449      --  points of R and T. We have no way of doing that directly, so what we
10450      --  do is force most such Itypes to be frozen as part of freezing R via
10451      --  this procedure and only delay the ones that need to be delayed
10452      --  (mostly the designated types of access types that are defined as part
10453      --  of the record).
10454
10455      if Is_Private_Type (T)
10456        and then Present (Full_View (T))
10457        and then Is_Itype (Full_View (T))
10458        and then Is_Record_Type (Scope (Full_View (T)))
10459      then
10460         Undelay_Type (Full_View (T));
10461      end if;
10462
10463      if Is_Concurrent_Type (T)
10464        and then Present (Corresponding_Record_Type (T))
10465        and then Is_Itype (Corresponding_Record_Type (T))
10466        and then Is_Record_Type (Scope (Corresponding_Record_Type (T)))
10467      then
10468         Undelay_Type (Corresponding_Record_Type (T));
10469      end if;
10470   end Undelay_Type;
10471
10472   ------------------
10473   -- Warn_Overlay --
10474   ------------------
10475
10476   procedure Warn_Overlay (Expr : Node_Id; Typ : Entity_Id; Nam : Node_Id) is
10477      Ent : constant Entity_Id := Entity (Nam);
10478      --  The object to which the address clause applies
10479
10480      Init : Node_Id;
10481      Old  : Entity_Id := Empty;
10482      Decl : Node_Id;
10483
10484   begin
10485      --  No warning if address clause overlay warnings are off
10486
10487      if not Address_Clause_Overlay_Warnings then
10488         return;
10489      end if;
10490
10491      --  No warning if there is an explicit initialization
10492
10493      Init := Original_Node (Expression (Declaration_Node (Ent)));
10494
10495      if Present (Init) and then Comes_From_Source (Init) then
10496         return;
10497      end if;
10498
10499      --  We only give the warning for non-imported entities of a type for
10500      --  which a non-null base init proc is defined, or for objects of access
10501      --  types with implicit null initialization, or when Normalize_Scalars
10502      --  applies and the type is scalar or a string type (the latter being
10503      --  tested for because predefined String types are initialized by inline
10504      --  code rather than by an init_proc). Note that we do not give the
10505      --  warning for Initialize_Scalars, since we suppressed initialization
10506      --  in this case. Also, do not warn if Suppress_Initialization is set
10507      --  either on the type, or on the object via pragma or aspect.
10508
10509      if Present (Expr)
10510        and then not Is_Imported (Ent)
10511        and then not Initialization_Suppressed (Typ)
10512        and then not (Ekind (Ent) = E_Variable
10513                       and then Initialization_Suppressed (Ent))
10514        and then (Has_Non_Null_Base_Init_Proc (Typ)
10515                   or else Is_Access_Type (Typ)
10516                   or else (Normalize_Scalars
10517                             and then (Is_Scalar_Type (Typ)
10518                                        or else Is_String_Type (Typ))))
10519      then
10520         if Nkind (Expr) = N_Attribute_Reference
10521           and then Is_Entity_Name (Prefix (Expr))
10522         then
10523            Old := Entity (Prefix (Expr));
10524
10525         elsif Is_Entity_Name (Expr)
10526           and then Ekind (Entity (Expr)) = E_Constant
10527         then
10528            Decl := Declaration_Node (Entity (Expr));
10529
10530            if Nkind (Decl) = N_Object_Declaration
10531              and then Present (Expression (Decl))
10532              and then Nkind (Expression (Decl)) = N_Attribute_Reference
10533              and then Is_Entity_Name (Prefix (Expression (Decl)))
10534            then
10535               Old := Entity (Prefix (Expression (Decl)));
10536
10537            elsif Nkind (Expr) = N_Function_Call then
10538               return;
10539            end if;
10540
10541         --  A function call (most likely to To_Address) is probably not an
10542         --  overlay, so skip warning. Ditto if the function call was inlined
10543         --  and transformed into an entity.
10544
10545         elsif Nkind (Original_Node (Expr)) = N_Function_Call then
10546            return;
10547         end if;
10548
10549         --  If a pragma Import follows, we assume that it is for the current
10550         --  target of the address clause, and skip the warning. There may be
10551         --  a source pragma or an aspect that specifies import and generates
10552         --  the corresponding pragma. These will indicate that the entity is
10553         --  imported and that is checked above so that the spurious warning
10554         --  (generated when the entity is frozen) will be suppressed. The
10555         --  pragma may be attached to the aspect, so it is not yet a list
10556         --  member.
10557
10558         if Is_List_Member (Parent (Expr)) then
10559            Decl := Next (Parent (Expr));
10560
10561            if Present (Decl)
10562              and then Nkind (Decl) = N_Pragma
10563              and then Pragma_Name (Decl) = Name_Import
10564            then
10565               return;
10566            end if;
10567         end if;
10568
10569         --  Otherwise give warning message
10570
10571         if Present (Old) then
10572            Error_Msg_Node_2 := Old;
10573            Error_Msg_N
10574              ("default initialization of & may modify &??",
10575               Nam);
10576         else
10577            Error_Msg_N
10578              ("default initialization of & may modify overlaid storage??",
10579               Nam);
10580         end if;
10581
10582         --  Add friendly warning if initialization comes from a packed array
10583         --  component.
10584
10585         if Is_Record_Type (Typ) then
10586            declare
10587               Comp : Entity_Id;
10588
10589            begin
10590               Comp := First_Component (Typ);
10591               while Present (Comp) loop
10592                  if Nkind (Parent (Comp)) = N_Component_Declaration
10593                    and then Present (Expression (Parent (Comp)))
10594                  then
10595                     exit;
10596                  elsif Is_Array_Type (Etype (Comp))
10597                     and then Present (Packed_Array_Impl_Type (Etype (Comp)))
10598                  then
10599                     Error_Msg_NE
10600                       ("\packed array component& " &
10601                        "will be initialized to zero??",
10602                        Nam, Comp);
10603                     exit;
10604                  else
10605                     Next_Component (Comp);
10606                  end if;
10607               end loop;
10608            end;
10609         end if;
10610
10611         Error_Msg_N
10612           ("\use pragma Import for & to " &
10613            "suppress initialization (RM B.1(24))??",
10614            Nam);
10615      end if;
10616   end Warn_Overlay;
10617
10618end Freeze;
10619