OSDN Git Service

2012-01-10 Bob Duff <duff@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch4.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 4                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Atag; use Exp_Atag;
34 with Exp_Ch2;  use Exp_Ch2;
35 with Exp_Ch3;  use Exp_Ch3;
36 with Exp_Ch6;  use Exp_Ch6;
37 with Exp_Ch7;  use Exp_Ch7;
38 with Exp_Ch9;  use Exp_Ch9;
39 with Exp_Disp; use Exp_Disp;
40 with Exp_Fixd; use Exp_Fixd;
41 with Exp_Intr; use Exp_Intr;
42 with Exp_Pakd; use Exp_Pakd;
43 with Exp_Tss;  use Exp_Tss;
44 with Exp_Util; use Exp_Util;
45 with Exp_VFpt; use Exp_VFpt;
46 with Freeze;   use Freeze;
47 with Inline;   use Inline;
48 with Lib;      use Lib;
49 with Namet;    use Namet;
50 with Nlists;   use Nlists;
51 with Nmake;    use Nmake;
52 with Opt;      use Opt;
53 with Par_SCO;  use Par_SCO;
54 with Restrict; use Restrict;
55 with Rident;   use Rident;
56 with Rtsfind;  use Rtsfind;
57 with Sem;      use Sem;
58 with Sem_Aux;  use Sem_Aux;
59 with Sem_Cat;  use Sem_Cat;
60 with Sem_Ch3;  use Sem_Ch3;
61 with Sem_Ch8;  use Sem_Ch8;
62 with Sem_Ch13; use Sem_Ch13;
63 with Sem_Eval; use Sem_Eval;
64 with Sem_Res;  use Sem_Res;
65 with Sem_Type; use Sem_Type;
66 with Sem_Util; use Sem_Util;
67 with Sem_Warn; use Sem_Warn;
68 with Sinfo;    use Sinfo;
69 with Snames;   use Snames;
70 with Stand;    use Stand;
71 with SCIL_LL;  use SCIL_LL;
72 with Targparm; use Targparm;
73 with Tbuild;   use Tbuild;
74 with Ttypes;   use Ttypes;
75 with Uintp;    use Uintp;
76 with Urealp;   use Urealp;
77 with Validsw;  use Validsw;
78
79 package body Exp_Ch4 is
80
81    -----------------------
82    -- Local Subprograms --
83    -----------------------
84
85    procedure Binary_Op_Validity_Checks (N : Node_Id);
86    pragma Inline (Binary_Op_Validity_Checks);
87    --  Performs validity checks for a binary operator
88
89    procedure Build_Boolean_Array_Proc_Call
90      (N   : Node_Id;
91       Op1 : Node_Id;
92       Op2 : Node_Id);
93    --  If a boolean array assignment can be done in place, build call to
94    --  corresponding library procedure.
95
96    function Current_Anonymous_Master return Entity_Id;
97    --  Return the entity of the heterogeneous finalization master belonging to
98    --  the current unit (either function, package or procedure). This master
99    --  services all anonymous access-to-controlled types. If the current unit
100    --  does not have such master, create one.
101
102    procedure Displace_Allocator_Pointer (N : Node_Id);
103    --  Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
104    --  Expand_Allocator_Expression. Allocating class-wide interface objects
105    --  this routine displaces the pointer to the allocated object to reference
106    --  the component referencing the corresponding secondary dispatch table.
107
108    procedure Expand_Allocator_Expression (N : Node_Id);
109    --  Subsidiary to Expand_N_Allocator, for the case when the expression
110    --  is a qualified expression or an aggregate.
111
112    procedure Expand_Array_Comparison (N : Node_Id);
113    --  This routine handles expansion of the comparison operators (N_Op_Lt,
114    --  N_Op_Le, N_Op_Gt, N_Op_Ge) when operating on an array type. The basic
115    --  code for these operators is similar, differing only in the details of
116    --  the actual comparison call that is made. Special processing (call a
117    --  run-time routine)
118
119    function Expand_Array_Equality
120      (Nod    : Node_Id;
121       Lhs    : Node_Id;
122       Rhs    : Node_Id;
123       Bodies : List_Id;
124       Typ    : Entity_Id) return Node_Id;
125    --  Expand an array equality into a call to a function implementing this
126    --  equality, and a call to it. Loc is the location for the generated nodes.
127    --  Lhs and Rhs are the array expressions to be compared. Bodies is a list
128    --  on which to attach bodies of local functions that are created in the
129    --  process. It is the responsibility of the caller to insert those bodies
130    --  at the right place. Nod provides the Sloc value for the generated code.
131    --  Normally the types used for the generated equality routine are taken
132    --  from Lhs and Rhs. However, in some situations of generated code, the
133    --  Etype fields of Lhs and Rhs are not set yet. In such cases, Typ supplies
134    --  the type to be used for the formal parameters.
135
136    procedure Expand_Boolean_Operator (N : Node_Id);
137    --  Common expansion processing for Boolean operators (And, Or, Xor) for the
138    --  case of array type arguments.
139
140    procedure Expand_Short_Circuit_Operator (N : Node_Id);
141    --  Common expansion processing for short-circuit boolean operators
142
143    function Expand_Composite_Equality
144      (Nod    : Node_Id;
145       Typ    : Entity_Id;
146       Lhs    : Node_Id;
147       Rhs    : Node_Id;
148       Bodies : List_Id) return Node_Id;
149    --  Local recursive function used to expand equality for nested composite
150    --  types. Used by Expand_Record/Array_Equality, Bodies is a list on which
151    --  to attach bodies of local functions that are created in the process.
152    --  This is the responsibility of the caller to insert those bodies at the
153    --  right place. Nod provides the Sloc value for generated code. Lhs and Rhs
154    --  are the left and right sides for the comparison, and Typ is the type of
155    --  the arrays to compare.
156
157    procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id);
158    --  Routine to expand concatenation of a sequence of two or more operands
159    --  (in the list Operands) and replace node Cnode with the result of the
160    --  concatenation. The operands can be of any appropriate type, and can
161    --  include both arrays and singleton elements.
162
163    procedure Fixup_Universal_Fixed_Operation (N : Node_Id);
164    --  N is a N_Op_Divide or N_Op_Multiply node whose result is universal
165    --  fixed. We do not have such a type at runtime, so the purpose of this
166    --  routine is to find the real type by looking up the tree. We also
167    --  determine if the operation must be rounded.
168
169    function Has_Inferable_Discriminants (N : Node_Id) return Boolean;
170    --  Ada 2005 (AI-216): A view of an Unchecked_Union object has inferable
171    --  discriminants if it has a constrained nominal type, unless the object
172    --  is a component of an enclosing Unchecked_Union object that is subject
173    --  to a per-object constraint and the enclosing object lacks inferable
174    --  discriminants.
175    --
176    --  An expression of an Unchecked_Union type has inferable discriminants
177    --  if it is either a name of an object with inferable discriminants or a
178    --  qualified expression whose subtype mark denotes a constrained subtype.
179
180    procedure Insert_Dereference_Action (N : Node_Id);
181    --  N is an expression whose type is an access. When the type of the
182    --  associated storage pool is derived from Checked_Pool, generate a
183    --  call to the 'Dereference' primitive operation.
184
185    function Make_Array_Comparison_Op
186      (Typ : Entity_Id;
187       Nod : Node_Id) return Node_Id;
188    --  Comparisons between arrays are expanded in line. This function produces
189    --  the body of the implementation of (a > b), where a and b are one-
190    --  dimensional arrays of some discrete type. The original node is then
191    --  expanded into the appropriate call to this function. Nod provides the
192    --  Sloc value for the generated code.
193
194    function Make_Boolean_Array_Op
195      (Typ : Entity_Id;
196       N   : Node_Id) return Node_Id;
197    --  Boolean operations on boolean arrays are expanded in line. This function
198    --  produce the body for the node N, which is (a and b), (a or b), or (a xor
199    --  b). It is used only the normal case and not the packed case. The type
200    --  involved, Typ, is the Boolean array type, and the logical operations in
201    --  the body are simple boolean operations. Note that Typ is always a
202    --  constrained type (the caller has ensured this by using
203    --  Convert_To_Actual_Subtype if necessary).
204
205    procedure Optimize_Length_Comparison (N : Node_Id);
206    --  Given an expression, if it is of the form X'Length op N (or the other
207    --  way round), where N is known at compile time to be 0 or 1, and X is a
208    --  simple entity, and op is a comparison operator, optimizes it into a
209    --  comparison of First and Last.
210
211    procedure Rewrite_Comparison (N : Node_Id);
212    --  If N is the node for a comparison whose outcome can be determined at
213    --  compile time, then the node N can be rewritten with True or False. If
214    --  the outcome cannot be determined at compile time, the call has no
215    --  effect. If N is a type conversion, then this processing is applied to
216    --  its expression. If N is neither comparison nor a type conversion, the
217    --  call has no effect.
218
219    procedure Tagged_Membership
220      (N         : Node_Id;
221       SCIL_Node : out Node_Id;
222       Result    : out Node_Id);
223    --  Construct the expression corresponding to the tagged membership test.
224    --  Deals with a second operand being (or not) a class-wide type.
225
226    function Safe_In_Place_Array_Op
227      (Lhs : Node_Id;
228       Op1 : Node_Id;
229       Op2 : Node_Id) return Boolean;
230    --  In the context of an assignment, where the right-hand side is a boolean
231    --  operation on arrays, check whether operation can be performed in place.
232
233    procedure Unary_Op_Validity_Checks (N : Node_Id);
234    pragma Inline (Unary_Op_Validity_Checks);
235    --  Performs validity checks for a unary operator
236
237    -------------------------------
238    -- Binary_Op_Validity_Checks --
239    -------------------------------
240
241    procedure Binary_Op_Validity_Checks (N : Node_Id) is
242    begin
243       if Validity_Checks_On and Validity_Check_Operands then
244          Ensure_Valid (Left_Opnd (N));
245          Ensure_Valid (Right_Opnd (N));
246       end if;
247    end Binary_Op_Validity_Checks;
248
249    ------------------------------------
250    -- Build_Boolean_Array_Proc_Call --
251    ------------------------------------
252
253    procedure Build_Boolean_Array_Proc_Call
254      (N   : Node_Id;
255       Op1 : Node_Id;
256       Op2 : Node_Id)
257    is
258       Loc       : constant Source_Ptr := Sloc (N);
259       Kind      : constant Node_Kind := Nkind (Expression (N));
260       Target    : constant Node_Id   :=
261                     Make_Attribute_Reference (Loc,
262                       Prefix         => Name (N),
263                       Attribute_Name => Name_Address);
264
265       Arg1      : Node_Id := Op1;
266       Arg2      : Node_Id := Op2;
267       Call_Node : Node_Id;
268       Proc_Name : Entity_Id;
269
270    begin
271       if Kind = N_Op_Not then
272          if Nkind (Op1) in N_Binary_Op then
273
274             --  Use negated version of the binary operators
275
276             if Nkind (Op1) = N_Op_And then
277                Proc_Name := RTE (RE_Vector_Nand);
278
279             elsif Nkind (Op1) = N_Op_Or then
280                Proc_Name := RTE (RE_Vector_Nor);
281
282             else pragma Assert (Nkind (Op1) = N_Op_Xor);
283                Proc_Name := RTE (RE_Vector_Xor);
284             end if;
285
286             Call_Node :=
287               Make_Procedure_Call_Statement (Loc,
288                 Name => New_Occurrence_Of (Proc_Name, Loc),
289
290                 Parameter_Associations => New_List (
291                   Target,
292                   Make_Attribute_Reference (Loc,
293                     Prefix => Left_Opnd (Op1),
294                     Attribute_Name => Name_Address),
295
296                   Make_Attribute_Reference (Loc,
297                     Prefix => Right_Opnd (Op1),
298                     Attribute_Name => Name_Address),
299
300                   Make_Attribute_Reference (Loc,
301                     Prefix => Left_Opnd (Op1),
302                     Attribute_Name => Name_Length)));
303
304          else
305             Proc_Name := RTE (RE_Vector_Not);
306
307             Call_Node :=
308               Make_Procedure_Call_Statement (Loc,
309                 Name => New_Occurrence_Of (Proc_Name, Loc),
310                 Parameter_Associations => New_List (
311                   Target,
312
313                   Make_Attribute_Reference (Loc,
314                     Prefix => Op1,
315                     Attribute_Name => Name_Address),
316
317                   Make_Attribute_Reference (Loc,
318                     Prefix => Op1,
319                      Attribute_Name => Name_Length)));
320          end if;
321
322       else
323          --  We use the following equivalences:
324
325          --   (not X) or  (not Y)  =  not (X and Y)  =  Nand (X, Y)
326          --   (not X) and (not Y)  =  not (X or Y)   =  Nor  (X, Y)
327          --   (not X) xor (not Y)  =  X xor Y
328          --   X       xor (not Y)  =  not (X xor Y)  =  Nxor (X, Y)
329
330          if Nkind (Op1) = N_Op_Not then
331             Arg1 := Right_Opnd (Op1);
332             Arg2 := Right_Opnd (Op2);
333             if Kind = N_Op_And then
334                Proc_Name := RTE (RE_Vector_Nor);
335             elsif Kind = N_Op_Or then
336                Proc_Name := RTE (RE_Vector_Nand);
337             else
338                Proc_Name := RTE (RE_Vector_Xor);
339             end if;
340
341          else
342             if Kind = N_Op_And then
343                Proc_Name := RTE (RE_Vector_And);
344             elsif Kind = N_Op_Or then
345                Proc_Name := RTE (RE_Vector_Or);
346             elsif Nkind (Op2) = N_Op_Not then
347                Proc_Name := RTE (RE_Vector_Nxor);
348                Arg2 := Right_Opnd (Op2);
349             else
350                Proc_Name := RTE (RE_Vector_Xor);
351             end if;
352          end if;
353
354          Call_Node :=
355            Make_Procedure_Call_Statement (Loc,
356              Name => New_Occurrence_Of (Proc_Name, Loc),
357              Parameter_Associations => New_List (
358                Target,
359                Make_Attribute_Reference (Loc,
360                  Prefix         => Arg1,
361                  Attribute_Name => Name_Address),
362                Make_Attribute_Reference (Loc,
363                  Prefix         => Arg2,
364                  Attribute_Name => Name_Address),
365                Make_Attribute_Reference (Loc,
366                  Prefix         => Arg1,
367                  Attribute_Name => Name_Length)));
368       end if;
369
370       Rewrite (N, Call_Node);
371       Analyze (N);
372
373    exception
374       when RE_Not_Available =>
375          return;
376    end Build_Boolean_Array_Proc_Call;
377
378    ------------------------------
379    -- Current_Anonymous_Master --
380    ------------------------------
381
382    function Current_Anonymous_Master return Entity_Id is
383       Decls     : List_Id;
384       Loc       : Source_Ptr;
385       Subp_Body : Node_Id;
386       Unit_Decl : Node_Id;
387       Unit_Id   : Entity_Id;
388
389    begin
390       Unit_Id := Cunit_Entity (Current_Sem_Unit);
391
392       --  Find the entity of the current unit
393
394       if Ekind (Unit_Id) = E_Subprogram_Body then
395
396          --  When processing subprogram bodies, the proper scope is always that
397          --  of the spec.
398
399          Subp_Body := Unit_Id;
400          while Present (Subp_Body)
401            and then Nkind (Subp_Body) /= N_Subprogram_Body
402          loop
403             Subp_Body := Parent (Subp_Body);
404          end loop;
405
406          Unit_Id := Corresponding_Spec (Subp_Body);
407       end if;
408
409       Loc := Sloc (Unit_Id);
410       Unit_Decl := Unit (Cunit (Current_Sem_Unit));
411
412       --  Find the declarations list of the current unit
413
414       if Nkind (Unit_Decl) = N_Package_Declaration then
415          Unit_Decl := Specification (Unit_Decl);
416          Decls := Visible_Declarations (Unit_Decl);
417
418          if No (Decls) then
419             Decls := New_List (Make_Null_Statement (Loc));
420             Set_Visible_Declarations (Unit_Decl, Decls);
421
422          elsif Is_Empty_List (Decls) then
423             Append_To (Decls, Make_Null_Statement (Loc));
424          end if;
425
426       else
427          Decls := Declarations (Unit_Decl);
428
429          if No (Decls) then
430             Decls := New_List (Make_Null_Statement (Loc));
431             Set_Declarations (Unit_Decl, Decls);
432
433          elsif Is_Empty_List (Decls) then
434             Append_To (Decls, Make_Null_Statement (Loc));
435          end if;
436       end if;
437
438       --  The current unit has an existing anonymous master, traverse its
439       --  declarations and locate the entity.
440
441       if Has_Anonymous_Master (Unit_Id) then
442          declare
443             Decl       : Node_Id;
444             Fin_Mas_Id : Entity_Id;
445
446          begin
447             Decl := First (Decls);
448             while Present (Decl) loop
449
450                --  Look for the first variable in the declarations whole type
451                --  is Finalization_Master.
452
453                if Nkind (Decl) = N_Object_Declaration then
454                   Fin_Mas_Id := Defining_Identifier (Decl);
455
456                   if Ekind (Fin_Mas_Id) = E_Variable
457                     and then Etype (Fin_Mas_Id) = RTE (RE_Finalization_Master)
458                   then
459                      return Fin_Mas_Id;
460                   end if;
461                end if;
462
463                Next (Decl);
464             end loop;
465
466             --  The master was not found even though the unit was labeled as
467             --  having one.
468
469             raise Program_Error;
470          end;
471
472       --  Create a new anonymous master
473
474       else
475          declare
476             First_Decl : constant Node_Id := First (Decls);
477             Action     : Node_Id;
478             Fin_Mas_Id : Entity_Id;
479
480          begin
481             --  Since the master and its associated initialization is inserted
482             --  at top level, use the scope of the unit when analyzing.
483
484             Push_Scope (Unit_Id);
485
486             --  Create the finalization master
487
488             Fin_Mas_Id :=
489               Make_Defining_Identifier (Loc,
490                 Chars => New_External_Name (Chars (Unit_Id), "AM"));
491
492             --  Generate:
493             --    <Fin_Mas_Id> : Finalization_Master;
494
495             Action :=
496               Make_Object_Declaration (Loc,
497                 Defining_Identifier => Fin_Mas_Id,
498                 Object_Definition =>
499                   New_Reference_To (RTE (RE_Finalization_Master), Loc));
500
501             Insert_Before_And_Analyze (First_Decl, Action);
502
503             --  Mark the unit to prevent the generation of multiple masters
504
505             Set_Has_Anonymous_Master (Unit_Id);
506
507             --  Do not set the base pool and mode of operation on .NET/JVM
508             --  since those targets do not support pools and all VM masters
509             --  are heterogeneous by default.
510
511             if VM_Target = No_VM then
512
513                --  Generate:
514                --    Set_Base_Pool
515                --      (<Fin_Mas_Id>, Global_Pool_Object'Unrestricted_Access);
516
517                Action :=
518                  Make_Procedure_Call_Statement (Loc,
519                    Name =>
520                      New_Reference_To (RTE (RE_Set_Base_Pool), Loc),
521
522                    Parameter_Associations => New_List (
523                      New_Reference_To (Fin_Mas_Id, Loc),
524                      Make_Attribute_Reference (Loc,
525                        Prefix =>
526                          New_Reference_To (RTE (RE_Global_Pool_Object), Loc),
527                        Attribute_Name => Name_Unrestricted_Access)));
528
529                Insert_Before_And_Analyze (First_Decl, Action);
530
531                --  Generate:
532                --    Set_Is_Heterogeneous (<Fin_Mas_Id>);
533
534                Action :=
535                  Make_Procedure_Call_Statement (Loc,
536                    Name =>
537                      New_Reference_To (RTE (RE_Set_Is_Heterogeneous), Loc),
538                    Parameter_Associations => New_List (
539                      New_Reference_To (Fin_Mas_Id, Loc)));
540
541                Insert_Before_And_Analyze (First_Decl, Action);
542             end if;
543
544             --  Restore the original state of the scope stack
545
546             Pop_Scope;
547
548             return Fin_Mas_Id;
549          end;
550       end if;
551    end Current_Anonymous_Master;
552
553    --------------------------------
554    -- Displace_Allocator_Pointer --
555    --------------------------------
556
557    procedure Displace_Allocator_Pointer (N : Node_Id) is
558       Loc       : constant Source_Ptr := Sloc (N);
559       Orig_Node : constant Node_Id := Original_Node (N);
560       Dtyp      : Entity_Id;
561       Etyp      : Entity_Id;
562       PtrT      : Entity_Id;
563
564    begin
565       --  Do nothing in case of VM targets: the virtual machine will handle
566       --  interfaces directly.
567
568       if not Tagged_Type_Expansion then
569          return;
570       end if;
571
572       pragma Assert (Nkind (N) = N_Identifier
573         and then Nkind (Orig_Node) = N_Allocator);
574
575       PtrT := Etype (Orig_Node);
576       Dtyp := Available_View (Designated_Type (PtrT));
577       Etyp := Etype (Expression (Orig_Node));
578
579       if Is_Class_Wide_Type (Dtyp)
580         and then Is_Interface (Dtyp)
581       then
582          --  If the type of the allocator expression is not an interface type
583          --  we can generate code to reference the record component containing
584          --  the pointer to the secondary dispatch table.
585
586          if not Is_Interface (Etyp) then
587             declare
588                Saved_Typ : constant Entity_Id := Etype (Orig_Node);
589
590             begin
591                --  1) Get access to the allocated object
592
593                Rewrite (N,
594                  Make_Explicit_Dereference (Loc, Relocate_Node (N)));
595                Set_Etype (N, Etyp);
596                Set_Analyzed (N);
597
598                --  2) Add the conversion to displace the pointer to reference
599                --     the secondary dispatch table.
600
601                Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
602                Analyze_And_Resolve (N, Dtyp);
603
604                --  3) The 'access to the secondary dispatch table will be used
605                --     as the value returned by the allocator.
606
607                Rewrite (N,
608                  Make_Attribute_Reference (Loc,
609                    Prefix         => Relocate_Node (N),
610                    Attribute_Name => Name_Access));
611                Set_Etype (N, Saved_Typ);
612                Set_Analyzed (N);
613             end;
614
615          --  If the type of the allocator expression is an interface type we
616          --  generate a run-time call to displace "this" to reference the
617          --  component containing the pointer to the secondary dispatch table
618          --  or else raise Constraint_Error if the actual object does not
619          --  implement the target interface. This case corresponds with the
620          --  following example:
621
622          --   function Op (Obj : Iface_1'Class) return access Iface_2'Class is
623          --   begin
624          --      return new Iface_2'Class'(Obj);
625          --   end Op;
626
627          else
628             Rewrite (N,
629               Unchecked_Convert_To (PtrT,
630                 Make_Function_Call (Loc,
631                   Name => New_Reference_To (RTE (RE_Displace), Loc),
632                   Parameter_Associations => New_List (
633                     Unchecked_Convert_To (RTE (RE_Address),
634                       Relocate_Node (N)),
635
636                     New_Occurrence_Of
637                       (Elists.Node
638                         (First_Elmt
639                           (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
640                        Loc)))));
641             Analyze_And_Resolve (N, PtrT);
642          end if;
643       end if;
644    end Displace_Allocator_Pointer;
645
646    ---------------------------------
647    -- Expand_Allocator_Expression --
648    ---------------------------------
649
650    procedure Expand_Allocator_Expression (N : Node_Id) is
651       Loc    : constant Source_Ptr := Sloc (N);
652       Exp    : constant Node_Id    := Expression (Expression (N));
653       PtrT   : constant Entity_Id  := Etype (N);
654       DesigT : constant Entity_Id  := Designated_Type (PtrT);
655
656       procedure Apply_Accessibility_Check
657         (Ref            : Node_Id;
658          Built_In_Place : Boolean := False);
659       --  Ada 2005 (AI-344): For an allocator with a class-wide designated
660       --  type, generate an accessibility check to verify that the level of the
661       --  type of the created object is not deeper than the level of the access
662       --  type. If the type of the qualified expression is class- wide, then
663       --  always generate the check (except in the case where it is known to be
664       --  unnecessary, see comment below). Otherwise, only generate the check
665       --  if the level of the qualified expression type is statically deeper
666       --  than the access type.
667       --
668       --  Although the static accessibility will generally have been performed
669       --  as a legality check, it won't have been done in cases where the
670       --  allocator appears in generic body, so a run-time check is needed in
671       --  general. One special case is when the access type is declared in the
672       --  same scope as the class-wide allocator, in which case the check can
673       --  never fail, so it need not be generated.
674       --
675       --  As an open issue, there seem to be cases where the static level
676       --  associated with the class-wide object's underlying type is not
677       --  sufficient to perform the proper accessibility check, such as for
678       --  allocators in nested subprograms or accept statements initialized by
679       --  class-wide formals when the actual originates outside at a deeper
680       --  static level. The nested subprogram case might require passing
681       --  accessibility levels along with class-wide parameters, and the task
682       --  case seems to be an actual gap in the language rules that needs to
683       --  be fixed by the ARG. ???
684
685       -------------------------------
686       -- Apply_Accessibility_Check --
687       -------------------------------
688
689       procedure Apply_Accessibility_Check
690         (Ref            : Node_Id;
691          Built_In_Place : Boolean := False)
692       is
693          New_Node : Node_Id;
694
695       begin
696          if Ada_Version >= Ada_2005
697            and then Is_Class_Wide_Type (DesigT)
698            and then not Scope_Suppress (Accessibility_Check)
699            and then
700              (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
701                or else
702                  (Is_Class_Wide_Type (Etype (Exp))
703                    and then Scope (PtrT) /= Current_Scope))
704          then
705             --  If the allocator was built in place Ref is already a reference
706             --  to the access object initialized to the result of the allocator
707             --  (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). Otherwise
708             --  it is the entity associated with the object containing the
709             --  address of the allocated object.
710
711             if Built_In_Place then
712                New_Node := New_Copy (Ref);
713             else
714                New_Node := New_Reference_To (Ref, Loc);
715             end if;
716
717             New_Node :=
718               Make_Attribute_Reference (Loc,
719                 Prefix         => New_Node,
720                 Attribute_Name => Name_Tag);
721
722             if Tagged_Type_Expansion then
723                New_Node := Build_Get_Access_Level (Loc, New_Node);
724
725             elsif VM_Target /= No_VM then
726                New_Node :=
727                  Make_Function_Call (Loc,
728                    Name => New_Reference_To (RTE (RE_Get_Access_Level), Loc),
729                    Parameter_Associations => New_List (New_Node));
730
731             --  Cannot generate the runtime check
732
733             else
734                return;
735             end if;
736
737             Insert_Action (N,
738               Make_Raise_Program_Error (Loc,
739                 Condition =>
740                   Make_Op_Gt (Loc,
741                     Left_Opnd  => New_Node,
742                     Right_Opnd =>
743                       Make_Integer_Literal (Loc, Type_Access_Level (PtrT))),
744                 Reason => PE_Accessibility_Check_Failed));
745          end if;
746       end Apply_Accessibility_Check;
747
748       --  Local variables
749
750       Aggr_In_Place : constant Boolean   := Is_Delayed_Aggregate (Exp);
751       Indic         : constant Node_Id   := Subtype_Mark (Expression (N));
752       T             : constant Entity_Id := Entity (Indic);
753       Node          : Node_Id;
754       Tag_Assign    : Node_Id;
755       Temp          : Entity_Id;
756       Temp_Decl     : Node_Id;
757
758       TagT : Entity_Id := Empty;
759       --  Type used as source for tag assignment
760
761       TagR : Node_Id := Empty;
762       --  Target reference for tag assignment
763
764    --  Start of processing for Expand_Allocator_Expression
765
766    begin
767       --  In the case of an Ada 2012 allocator whose initial value comes from a
768       --  function call, pass "the accessibility level determined by the point
769       --  of call" (AI05-0234) to the function. Conceptually, this belongs in
770       --  Expand_Call but it couldn't be done there (because the Etype of the
771       --  allocator wasn't set then) so we generate the parameter here. See
772       --  the Boolean variable Defer in (a block within) Expand_Call.
773
774       if Ada_Version >= Ada_2012 and then Nkind (Exp) = N_Function_Call then
775          declare
776             Subp : Entity_Id;
777
778          begin
779             if Nkind (Name (Exp)) = N_Explicit_Dereference then
780                Subp := Designated_Type (Etype (Prefix (Name (Exp))));
781             else
782                Subp := Entity (Name (Exp));
783             end if;
784
785             Subp := Ultimate_Alias (Subp);
786
787             if Present (Extra_Accessibility_Of_Result (Subp)) then
788                Add_Extra_Actual_To_Call
789                  (Subprogram_Call => Exp,
790                   Extra_Formal    => Extra_Accessibility_Of_Result (Subp),
791                   Extra_Actual    => Dynamic_Accessibility_Level (PtrT));
792             end if;
793          end;
794       end if;
795
796       --  Would be nice to comment the branches of this very long if ???
797
798       if Is_Tagged_Type (T) or else Needs_Finalization (T) then
799          if Is_CPP_Constructor_Call (Exp) then
800
801             --  Generate:
802             --    Pnnn : constant ptr_T := new (T);
803             --    Init (Pnnn.all,...);
804
805             --  Allocate the object without an expression
806
807             Node := Relocate_Node (N);
808             Set_Expression (Node, New_Reference_To (Etype (Exp), Loc));
809
810             --  Avoid its expansion to avoid generating a call to the default
811             --  C++ constructor.
812
813             Set_Analyzed (Node);
814
815             Temp := Make_Temporary (Loc, 'P', N);
816
817             Temp_Decl :=
818               Make_Object_Declaration (Loc,
819                 Defining_Identifier => Temp,
820                 Constant_Present    => True,
821                 Object_Definition   => New_Reference_To (PtrT, Loc),
822                 Expression          => Node);
823             Insert_Action (N, Temp_Decl);
824
825             Apply_Accessibility_Check (Temp);
826
827             --  Locate the enclosing list and insert the C++ constructor call
828
829             declare
830                P : Node_Id;
831
832             begin
833                P := Parent (Node);
834                while not Is_List_Member (P) loop
835                   P := Parent (P);
836                end loop;
837
838                Insert_List_After_And_Analyze (P,
839                  Build_Initialization_Call (Loc,
840                    Id_Ref          =>
841                      Make_Explicit_Dereference (Loc,
842                        Prefix => New_Reference_To (Temp, Loc)),
843                    Typ             => Etype (Exp),
844                    Constructor_Ref => Exp));
845             end;
846
847             Rewrite (N, New_Reference_To (Temp, Loc));
848             Analyze_And_Resolve (N, PtrT);
849             return;
850          end if;
851
852          --  Ada 2005 (AI-318-02): If the initialization expression is a call
853          --  to a build-in-place function, then access to the allocated object
854          --  must be passed to the function. Currently we limit such functions
855          --  to those with constrained limited result subtypes, but eventually
856          --  we plan to expand the allowed forms of functions that are treated
857          --  as build-in-place.
858
859          if Ada_Version >= Ada_2005
860            and then Is_Build_In_Place_Function_Call (Exp)
861          then
862             Make_Build_In_Place_Call_In_Allocator (N, Exp);
863             Apply_Accessibility_Check (N, Built_In_Place => True);
864             return;
865          end if;
866
867          --  Actions inserted before:
868          --    Temp : constant ptr_T := new T'(Expression);
869          --    Temp._tag = T'tag;  --  when not class-wide
870          --    [Deep_]Adjust (Temp.all);
871
872          --  We analyze by hand the new internal allocator to avoid any
873          --  recursion and inappropriate call to Initialize
874
875          --  We don't want to remove side effects when the expression must be
876          --  built in place. In the case of a build-in-place function call,
877          --  that could lead to a duplication of the call, which was already
878          --  substituted for the allocator.
879
880          if not Aggr_In_Place then
881             Remove_Side_Effects (Exp);
882          end if;
883
884          Temp := Make_Temporary (Loc, 'P', N);
885
886          --  For a class wide allocation generate the following code:
887
888          --    type Equiv_Record is record ... end record;
889          --    implicit subtype CW is <Class_Wide_Subytpe>;
890          --    temp : PtrT := new CW'(CW!(expr));
891
892          if Is_Class_Wide_Type (T) then
893             Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
894
895             --  Ada 2005 (AI-251): If the expression is a class-wide interface
896             --  object we generate code to move up "this" to reference the
897             --  base of the object before allocating the new object.
898
899             --  Note that Exp'Address is recursively expanded into a call
900             --  to Base_Address (Exp.Tag)
901
902             if Is_Class_Wide_Type (Etype (Exp))
903               and then Is_Interface (Etype (Exp))
904               and then Tagged_Type_Expansion
905             then
906                Set_Expression
907                  (Expression (N),
908                   Unchecked_Convert_To (Entity (Indic),
909                     Make_Explicit_Dereference (Loc,
910                       Unchecked_Convert_To (RTE (RE_Tag_Ptr),
911                         Make_Attribute_Reference (Loc,
912                           Prefix         => Exp,
913                           Attribute_Name => Name_Address)))));
914             else
915                Set_Expression
916                  (Expression (N),
917                   Unchecked_Convert_To (Entity (Indic), Exp));
918             end if;
919
920             Analyze_And_Resolve (Expression (N), Entity (Indic));
921          end if;
922
923          --  Processing for allocators returning non-interface types
924
925          if not Is_Interface (Directly_Designated_Type (PtrT)) then
926             if Aggr_In_Place then
927                Temp_Decl :=
928                  Make_Object_Declaration (Loc,
929                    Defining_Identifier => Temp,
930                    Object_Definition   => New_Reference_To (PtrT, Loc),
931                    Expression          =>
932                      Make_Allocator (Loc,
933                        Expression =>
934                          New_Reference_To (Etype (Exp), Loc)));
935
936                --  Copy the Comes_From_Source flag for the allocator we just
937                --  built, since logically this allocator is a replacement of
938                --  the original allocator node. This is for proper handling of
939                --  restriction No_Implicit_Heap_Allocations.
940
941                Set_Comes_From_Source
942                  (Expression (Temp_Decl), Comes_From_Source (N));
943
944                Set_No_Initialization (Expression (Temp_Decl));
945                Insert_Action (N, Temp_Decl);
946
947                Build_Allocate_Deallocate_Proc (Temp_Decl, True);
948                Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
949
950                --  Attach the object to the associated finalization master.
951                --  This is done manually on .NET/JVM since those compilers do
952                --  no support pools and can't benefit from internally generated
953                --  Allocate / Deallocate procedures.
954
955                if VM_Target /= No_VM
956                  and then Is_Controlled (DesigT)
957                  and then Present (Finalization_Master (PtrT))
958                then
959                   Insert_Action (N,
960                     Make_Attach_Call (
961                       Obj_Ref =>
962                         New_Reference_To (Temp, Loc),
963                       Ptr_Typ => PtrT));
964                end if;
965
966             else
967                Node := Relocate_Node (N);
968                Set_Analyzed (Node);
969
970                Temp_Decl :=
971                  Make_Object_Declaration (Loc,
972                    Defining_Identifier => Temp,
973                    Constant_Present    => True,
974                    Object_Definition   => New_Reference_To (PtrT, Loc),
975                    Expression          => Node);
976
977                Insert_Action (N, Temp_Decl);
978                Build_Allocate_Deallocate_Proc (Temp_Decl, True);
979
980                --  Attach the object to the associated finalization master.
981                --  This is done manually on .NET/JVM since those compilers do
982                --  no support pools and can't benefit from internally generated
983                --  Allocate / Deallocate procedures.
984
985                if VM_Target /= No_VM
986                  and then Is_Controlled (DesigT)
987                  and then Present (Finalization_Master (PtrT))
988                then
989                   Insert_Action (N,
990                     Make_Attach_Call (
991                       Obj_Ref =>
992                         New_Reference_To (Temp, Loc),
993                       Ptr_Typ => PtrT));
994                end if;
995             end if;
996
997          --  Ada 2005 (AI-251): Handle allocators whose designated type is an
998          --  interface type. In this case we use the type of the qualified
999          --  expression to allocate the object.
1000
1001          else
1002             declare
1003                Def_Id   : constant Entity_Id := Make_Temporary (Loc, 'T');
1004                New_Decl : Node_Id;
1005
1006             begin
1007                New_Decl :=
1008                  Make_Full_Type_Declaration (Loc,
1009                    Defining_Identifier => Def_Id,
1010                    Type_Definition =>
1011                      Make_Access_To_Object_Definition (Loc,
1012                        All_Present            => True,
1013                        Null_Exclusion_Present => False,
1014                        Constant_Present       => False,
1015                        Subtype_Indication     =>
1016                          New_Reference_To (Etype (Exp), Loc)));
1017
1018                Insert_Action (N, New_Decl);
1019
1020                --  Inherit the allocation-related attributes from the original
1021                --  access type.
1022
1023                Set_Finalization_Master (Def_Id, Finalization_Master (PtrT));
1024
1025                Set_Associated_Storage_Pool (Def_Id,
1026                  Associated_Storage_Pool (PtrT));
1027
1028                --  Declare the object using the previous type declaration
1029
1030                if Aggr_In_Place then
1031                   Temp_Decl :=
1032                     Make_Object_Declaration (Loc,
1033                       Defining_Identifier => Temp,
1034                       Object_Definition   => New_Reference_To (Def_Id, Loc),
1035                       Expression          =>
1036                         Make_Allocator (Loc,
1037                           New_Reference_To (Etype (Exp), Loc)));
1038
1039                   --  Copy the Comes_From_Source flag for the allocator we just
1040                   --  built, since logically this allocator is a replacement of
1041                   --  the original allocator node. This is for proper handling
1042                   --  of restriction No_Implicit_Heap_Allocations.
1043
1044                   Set_Comes_From_Source
1045                     (Expression (Temp_Decl), Comes_From_Source (N));
1046
1047                   Set_No_Initialization (Expression (Temp_Decl));
1048                   Insert_Action (N, Temp_Decl);
1049
1050                   Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1051                   Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1052
1053                else
1054                   Node := Relocate_Node (N);
1055                   Set_Analyzed (Node);
1056
1057                   Temp_Decl :=
1058                     Make_Object_Declaration (Loc,
1059                       Defining_Identifier => Temp,
1060                       Constant_Present    => True,
1061                       Object_Definition   => New_Reference_To (Def_Id, Loc),
1062                       Expression          => Node);
1063
1064                   Insert_Action (N, Temp_Decl);
1065                   Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1066                end if;
1067
1068                --  Generate an additional object containing the address of the
1069                --  returned object. The type of this second object declaration
1070                --  is the correct type required for the common processing that
1071                --  is still performed by this subprogram. The displacement of
1072                --  this pointer to reference the component associated with the
1073                --  interface type will be done at the end of common processing.
1074
1075                New_Decl :=
1076                  Make_Object_Declaration (Loc,
1077                    Defining_Identifier => Make_Temporary (Loc, 'P'),
1078                    Object_Definition   => New_Reference_To (PtrT, Loc),
1079                    Expression          =>
1080                      Unchecked_Convert_To (PtrT,
1081                        New_Reference_To (Temp, Loc)));
1082
1083                Insert_Action (N, New_Decl);
1084
1085                Temp_Decl := New_Decl;
1086                Temp      := Defining_Identifier (New_Decl);
1087             end;
1088          end if;
1089
1090          Apply_Accessibility_Check (Temp);
1091
1092          --  Generate the tag assignment
1093
1094          --  Suppress the tag assignment when VM_Target because VM tags are
1095          --  represented implicitly in objects.
1096
1097          if not Tagged_Type_Expansion then
1098             null;
1099
1100          --  Ada 2005 (AI-251): Suppress the tag assignment with class-wide
1101          --  interface objects because in this case the tag does not change.
1102
1103          elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
1104             pragma Assert (Is_Class_Wide_Type
1105                             (Directly_Designated_Type (Etype (N))));
1106             null;
1107
1108          elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
1109             TagT := T;
1110             TagR := New_Reference_To (Temp, Loc);
1111
1112          elsif Is_Private_Type (T)
1113            and then Is_Tagged_Type (Underlying_Type (T))
1114          then
1115             TagT := Underlying_Type (T);
1116             TagR :=
1117               Unchecked_Convert_To (Underlying_Type (T),
1118                 Make_Explicit_Dereference (Loc,
1119                   Prefix => New_Reference_To (Temp, Loc)));
1120          end if;
1121
1122          if Present (TagT) then
1123             declare
1124                Full_T : constant Entity_Id := Underlying_Type (TagT);
1125             begin
1126                Tag_Assign :=
1127                  Make_Assignment_Statement (Loc,
1128                    Name =>
1129                      Make_Selected_Component (Loc,
1130                        Prefix => TagR,
1131                        Selector_Name =>
1132                          New_Reference_To (First_Tag_Component (Full_T), Loc)),
1133                    Expression =>
1134                      Unchecked_Convert_To (RTE (RE_Tag),
1135                        New_Reference_To
1136                          (Elists.Node
1137                            (First_Elmt (Access_Disp_Table (Full_T))), Loc)));
1138             end;
1139
1140             --  The previous assignment has to be done in any case
1141
1142             Set_Assignment_OK (Name (Tag_Assign));
1143             Insert_Action (N, Tag_Assign);
1144          end if;
1145
1146          if Needs_Finalization (DesigT)
1147             and then Needs_Finalization (T)
1148          then
1149             --  Generate an Adjust call if the object will be moved. In Ada
1150             --  2005, the object may be inherently limited, in which case
1151             --  there is no Adjust procedure, and the object is built in
1152             --  place. In Ada 95, the object can be limited but not
1153             --  inherently limited if this allocator came from a return
1154             --  statement (we're allocating the result on the secondary
1155             --  stack). In that case, the object will be moved, so we _do_
1156             --  want to Adjust.
1157
1158             if not Aggr_In_Place
1159               and then not Is_Immutably_Limited_Type (T)
1160             then
1161                Insert_Action (N,
1162                  Make_Adjust_Call (
1163                    Obj_Ref    =>
1164
1165                      --  An unchecked conversion is needed in the classwide
1166                      --  case because the designated type can be an ancestor
1167                      --  of the subtype mark of the allocator.
1168
1169                      Unchecked_Convert_To (T,
1170                        Make_Explicit_Dereference (Loc,
1171                          Prefix => New_Reference_To (Temp, Loc))),
1172                    Typ => T));
1173             end if;
1174
1175             --  Generate:
1176             --    Set_Finalize_Address (<PtrT>FM, <T>FD'Unrestricted_Access);
1177
1178             --  Do not generate this call in the following cases:
1179
1180             --    * .NET/JVM - these targets do not support address arithmetic
1181             --    and unchecked conversion, key elements of Finalize_Address.
1182
1183             --    * Alfa mode - the call is useless and results in unwanted
1184             --    expansion.
1185
1186             --    * CodePeer mode - TSS primitive Finalize_Address is not
1187             --    created in this mode.
1188
1189             if VM_Target = No_VM
1190               and then not Alfa_Mode
1191               and then not CodePeer_Mode
1192               and then Present (Finalization_Master (PtrT))
1193               and then Present (Temp_Decl)
1194               and then Nkind (Expression (Temp_Decl)) = N_Allocator
1195             then
1196                Insert_Action (N,
1197                  Make_Set_Finalize_Address_Call
1198                    (Loc     => Loc,
1199                     Typ     => T,
1200                     Ptr_Typ => PtrT));
1201             end if;
1202          end if;
1203
1204          Rewrite (N, New_Reference_To (Temp, Loc));
1205          Analyze_And_Resolve (N, PtrT);
1206
1207          --  Ada 2005 (AI-251): Displace the pointer to reference the record
1208          --  component containing the secondary dispatch table of the interface
1209          --  type.
1210
1211          if Is_Interface (Directly_Designated_Type (PtrT)) then
1212             Displace_Allocator_Pointer (N);
1213          end if;
1214
1215       elsif Aggr_In_Place then
1216          Temp := Make_Temporary (Loc, 'P', N);
1217          Temp_Decl :=
1218            Make_Object_Declaration (Loc,
1219              Defining_Identifier => Temp,
1220              Object_Definition   => New_Reference_To (PtrT, Loc),
1221              Expression          =>
1222                Make_Allocator (Loc,
1223                  Expression => New_Reference_To (Etype (Exp), Loc)));
1224
1225          --  Copy the Comes_From_Source flag for the allocator we just built,
1226          --  since logically this allocator is a replacement of the original
1227          --  allocator node. This is for proper handling of restriction
1228          --  No_Implicit_Heap_Allocations.
1229
1230          Set_Comes_From_Source
1231            (Expression (Temp_Decl), Comes_From_Source (N));
1232
1233          Set_No_Initialization (Expression (Temp_Decl));
1234          Insert_Action (N, Temp_Decl);
1235
1236          Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1237          Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1238
1239          --  Attach the object to the associated finalization master. Thisis
1240          --  done manually on .NET/JVM since those compilers do no support
1241          --  pools and cannot benefit from internally generated Allocate and
1242          --  Deallocate procedures.
1243
1244          if VM_Target /= No_VM
1245            and then Is_Controlled (DesigT)
1246            and then Present (Finalization_Master (PtrT))
1247          then
1248             Insert_Action (N,
1249               Make_Attach_Call
1250                 (Obj_Ref => New_Reference_To (Temp, Loc),
1251                  Ptr_Typ => PtrT));
1252          end if;
1253
1254          Rewrite (N, New_Reference_To (Temp, Loc));
1255          Analyze_And_Resolve (N, PtrT);
1256
1257       elsif Is_Access_Type (T)
1258         and then Can_Never_Be_Null (T)
1259       then
1260          Install_Null_Excluding_Check (Exp);
1261
1262       elsif Is_Access_Type (DesigT)
1263         and then Nkind (Exp) = N_Allocator
1264         and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1265       then
1266          --  Apply constraint to designated subtype indication
1267
1268          Apply_Constraint_Check (Expression (Exp),
1269            Designated_Type (DesigT),
1270            No_Sliding => True);
1271
1272          if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1273
1274             --  Propagate constraint_error to enclosing allocator
1275
1276             Rewrite (Exp, New_Copy (Expression (Exp)));
1277          end if;
1278
1279       else
1280          Build_Allocate_Deallocate_Proc (N, True);
1281
1282          --  If we have:
1283          --    type A is access T1;
1284          --    X : A := new T2'(...);
1285          --  T1 and T2 can be different subtypes, and we might need to check
1286          --  both constraints. First check against the type of the qualified
1287          --  expression.
1288
1289          Apply_Constraint_Check (Exp, T, No_Sliding => True);
1290
1291          if Do_Range_Check (Exp) then
1292             Set_Do_Range_Check (Exp, False);
1293             Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1294          end if;
1295
1296          --  A check is also needed in cases where the designated subtype is
1297          --  constrained and differs from the subtype given in the qualified
1298          --  expression. Note that the check on the qualified expression does
1299          --  not allow sliding, but this check does (a relaxation from Ada 83).
1300
1301          if Is_Constrained (DesigT)
1302            and then not Subtypes_Statically_Match (T, DesigT)
1303          then
1304             Apply_Constraint_Check
1305               (Exp, DesigT, No_Sliding => False);
1306
1307             if Do_Range_Check (Exp) then
1308                Set_Do_Range_Check (Exp, False);
1309                Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1310             end if;
1311          end if;
1312
1313          --  For an access to unconstrained packed array, GIGI needs to see an
1314          --  expression with a constrained subtype in order to compute the
1315          --  proper size for the allocator.
1316
1317          if Is_Array_Type (T)
1318            and then not Is_Constrained (T)
1319            and then Is_Packed (T)
1320          then
1321             declare
1322                ConstrT      : constant Entity_Id := Make_Temporary (Loc, 'A');
1323                Internal_Exp : constant Node_Id   := Relocate_Node (Exp);
1324             begin
1325                Insert_Action (Exp,
1326                  Make_Subtype_Declaration (Loc,
1327                    Defining_Identifier => ConstrT,
1328                    Subtype_Indication  =>
1329                      Make_Subtype_From_Expr (Internal_Exp, T)));
1330                Freeze_Itype (ConstrT, Exp);
1331                Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1332             end;
1333          end if;
1334
1335          --  Ada 2005 (AI-318-02): If the initialization expression is a call
1336          --  to a build-in-place function, then access to the allocated object
1337          --  must be passed to the function. Currently we limit such functions
1338          --  to those with constrained limited result subtypes, but eventually
1339          --  we plan to expand the allowed forms of functions that are treated
1340          --  as build-in-place.
1341
1342          if Ada_Version >= Ada_2005
1343            and then Is_Build_In_Place_Function_Call (Exp)
1344          then
1345             Make_Build_In_Place_Call_In_Allocator (N, Exp);
1346          end if;
1347       end if;
1348
1349    exception
1350       when RE_Not_Available =>
1351          return;
1352    end Expand_Allocator_Expression;
1353
1354    -----------------------------
1355    -- Expand_Array_Comparison --
1356    -----------------------------
1357
1358    --  Expansion is only required in the case of array types. For the unpacked
1359    --  case, an appropriate runtime routine is called. For packed cases, and
1360    --  also in some other cases where a runtime routine cannot be called, the
1361    --  form of the expansion is:
1362
1363    --     [body for greater_nn; boolean_expression]
1364
1365    --  The body is built by Make_Array_Comparison_Op, and the form of the
1366    --  Boolean expression depends on the operator involved.
1367
1368    procedure Expand_Array_Comparison (N : Node_Id) is
1369       Loc  : constant Source_Ptr := Sloc (N);
1370       Op1  : Node_Id             := Left_Opnd (N);
1371       Op2  : Node_Id             := Right_Opnd (N);
1372       Typ1 : constant Entity_Id  := Base_Type (Etype (Op1));
1373       Ctyp : constant Entity_Id  := Component_Type (Typ1);
1374
1375       Expr      : Node_Id;
1376       Func_Body : Node_Id;
1377       Func_Name : Entity_Id;
1378
1379       Comp : RE_Id;
1380
1381       Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1382       --  True for byte addressable target
1383
1384       function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1385       --  Returns True if the length of the given operand is known to be less
1386       --  than 4. Returns False if this length is known to be four or greater
1387       --  or is not known at compile time.
1388
1389       ------------------------
1390       -- Length_Less_Than_4 --
1391       ------------------------
1392
1393       function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1394          Otyp : constant Entity_Id := Etype (Opnd);
1395
1396       begin
1397          if Ekind (Otyp) = E_String_Literal_Subtype then
1398             return String_Literal_Length (Otyp) < 4;
1399
1400          else
1401             declare
1402                Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1403                Lo   : constant Node_Id   := Type_Low_Bound (Ityp);
1404                Hi   : constant Node_Id   := Type_High_Bound (Ityp);
1405                Lov  : Uint;
1406                Hiv  : Uint;
1407
1408             begin
1409                if Compile_Time_Known_Value (Lo) then
1410                   Lov := Expr_Value (Lo);
1411                else
1412                   return False;
1413                end if;
1414
1415                if Compile_Time_Known_Value (Hi) then
1416                   Hiv := Expr_Value (Hi);
1417                else
1418                   return False;
1419                end if;
1420
1421                return Hiv < Lov + 3;
1422             end;
1423          end if;
1424       end Length_Less_Than_4;
1425
1426    --  Start of processing for Expand_Array_Comparison
1427
1428    begin
1429       --  Deal first with unpacked case, where we can call a runtime routine
1430       --  except that we avoid this for targets for which are not addressable
1431       --  by bytes, and for the JVM/CIL, since they do not support direct
1432       --  addressing of array components.
1433
1434       if not Is_Bit_Packed_Array (Typ1)
1435         and then Byte_Addressable
1436         and then VM_Target = No_VM
1437       then
1438          --  The call we generate is:
1439
1440          --  Compare_Array_xn[_Unaligned]
1441          --    (left'address, right'address, left'length, right'length) <op> 0
1442
1443          --  x = U for unsigned, S for signed
1444          --  n = 8,16,32,64 for component size
1445          --  Add _Unaligned if length < 4 and component size is 8.
1446          --  <op> is the standard comparison operator
1447
1448          if Component_Size (Typ1) = 8 then
1449             if Length_Less_Than_4 (Op1)
1450                  or else
1451                Length_Less_Than_4 (Op2)
1452             then
1453                if Is_Unsigned_Type (Ctyp) then
1454                   Comp := RE_Compare_Array_U8_Unaligned;
1455                else
1456                   Comp := RE_Compare_Array_S8_Unaligned;
1457                end if;
1458
1459             else
1460                if Is_Unsigned_Type (Ctyp) then
1461                   Comp := RE_Compare_Array_U8;
1462                else
1463                   Comp := RE_Compare_Array_S8;
1464                end if;
1465             end if;
1466
1467          elsif Component_Size (Typ1) = 16 then
1468             if Is_Unsigned_Type (Ctyp) then
1469                Comp := RE_Compare_Array_U16;
1470             else
1471                Comp := RE_Compare_Array_S16;
1472             end if;
1473
1474          elsif Component_Size (Typ1) = 32 then
1475             if Is_Unsigned_Type (Ctyp) then
1476                Comp := RE_Compare_Array_U32;
1477             else
1478                Comp := RE_Compare_Array_S32;
1479             end if;
1480
1481          else pragma Assert (Component_Size (Typ1) = 64);
1482             if Is_Unsigned_Type (Ctyp) then
1483                Comp := RE_Compare_Array_U64;
1484             else
1485                Comp := RE_Compare_Array_S64;
1486             end if;
1487          end if;
1488
1489          Remove_Side_Effects (Op1, Name_Req => True);
1490          Remove_Side_Effects (Op2, Name_Req => True);
1491
1492          Rewrite (Op1,
1493            Make_Function_Call (Sloc (Op1),
1494              Name => New_Occurrence_Of (RTE (Comp), Loc),
1495
1496              Parameter_Associations => New_List (
1497                Make_Attribute_Reference (Loc,
1498                  Prefix         => Relocate_Node (Op1),
1499                  Attribute_Name => Name_Address),
1500
1501                Make_Attribute_Reference (Loc,
1502                  Prefix         => Relocate_Node (Op2),
1503                  Attribute_Name => Name_Address),
1504
1505                Make_Attribute_Reference (Loc,
1506                  Prefix         => Relocate_Node (Op1),
1507                  Attribute_Name => Name_Length),
1508
1509                Make_Attribute_Reference (Loc,
1510                  Prefix         => Relocate_Node (Op2),
1511                  Attribute_Name => Name_Length))));
1512
1513          Rewrite (Op2,
1514            Make_Integer_Literal (Sloc (Op2),
1515              Intval => Uint_0));
1516
1517          Analyze_And_Resolve (Op1, Standard_Integer);
1518          Analyze_And_Resolve (Op2, Standard_Integer);
1519          return;
1520       end if;
1521
1522       --  Cases where we cannot make runtime call
1523
1524       --  For (a <= b) we convert to not (a > b)
1525
1526       if Chars (N) = Name_Op_Le then
1527          Rewrite (N,
1528            Make_Op_Not (Loc,
1529              Right_Opnd =>
1530                 Make_Op_Gt (Loc,
1531                  Left_Opnd  => Op1,
1532                  Right_Opnd => Op2)));
1533          Analyze_And_Resolve (N, Standard_Boolean);
1534          return;
1535
1536       --  For < the Boolean expression is
1537       --    greater__nn (op2, op1)
1538
1539       elsif Chars (N) = Name_Op_Lt then
1540          Func_Body := Make_Array_Comparison_Op (Typ1, N);
1541
1542          --  Switch operands
1543
1544          Op1 := Right_Opnd (N);
1545          Op2 := Left_Opnd  (N);
1546
1547       --  For (a >= b) we convert to not (a < b)
1548
1549       elsif Chars (N) = Name_Op_Ge then
1550          Rewrite (N,
1551            Make_Op_Not (Loc,
1552              Right_Opnd =>
1553                Make_Op_Lt (Loc,
1554                  Left_Opnd  => Op1,
1555                  Right_Opnd => Op2)));
1556          Analyze_And_Resolve (N, Standard_Boolean);
1557          return;
1558
1559       --  For > the Boolean expression is
1560       --    greater__nn (op1, op2)
1561
1562       else
1563          pragma Assert (Chars (N) = Name_Op_Gt);
1564          Func_Body := Make_Array_Comparison_Op (Typ1, N);
1565       end if;
1566
1567       Func_Name := Defining_Unit_Name (Specification (Func_Body));
1568       Expr :=
1569         Make_Function_Call (Loc,
1570           Name => New_Reference_To (Func_Name, Loc),
1571           Parameter_Associations => New_List (Op1, Op2));
1572
1573       Insert_Action (N, Func_Body);
1574       Rewrite (N, Expr);
1575       Analyze_And_Resolve (N, Standard_Boolean);
1576
1577    exception
1578       when RE_Not_Available =>
1579          return;
1580    end Expand_Array_Comparison;
1581
1582    ---------------------------
1583    -- Expand_Array_Equality --
1584    ---------------------------
1585
1586    --  Expand an equality function for multi-dimensional arrays. Here is an
1587    --  example of such a function for Nb_Dimension = 2
1588
1589    --  function Enn (A : atyp; B : btyp) return boolean is
1590    --  begin
1591    --     if (A'length (1) = 0 or else A'length (2) = 0)
1592    --          and then
1593    --        (B'length (1) = 0 or else B'length (2) = 0)
1594    --     then
1595    --        return True;    -- RM 4.5.2(22)
1596    --     end if;
1597
1598    --     if A'length (1) /= B'length (1)
1599    --               or else
1600    --           A'length (2) /= B'length (2)
1601    --     then
1602    --        return False;   -- RM 4.5.2(23)
1603    --     end if;
1604
1605    --     declare
1606    --        A1 : Index_T1 := A'first (1);
1607    --        B1 : Index_T1 := B'first (1);
1608    --     begin
1609    --        loop
1610    --           declare
1611    --              A2 : Index_T2 := A'first (2);
1612    --              B2 : Index_T2 := B'first (2);
1613    --           begin
1614    --              loop
1615    --                 if A (A1, A2) /= B (B1, B2) then
1616    --                    return False;
1617    --                 end if;
1618
1619    --                 exit when A2 = A'last (2);
1620    --                 A2 := Index_T2'succ (A2);
1621    --                 B2 := Index_T2'succ (B2);
1622    --              end loop;
1623    --           end;
1624
1625    --           exit when A1 = A'last (1);
1626    --           A1 := Index_T1'succ (A1);
1627    --           B1 := Index_T1'succ (B1);
1628    --        end loop;
1629    --     end;
1630
1631    --     return true;
1632    --  end Enn;
1633
1634    --  Note on the formal types used (atyp and btyp). If either of the arrays
1635    --  is of a private type, we use the underlying type, and do an unchecked
1636    --  conversion of the actual. If either of the arrays has a bound depending
1637    --  on a discriminant, then we use the base type since otherwise we have an
1638    --  escaped discriminant in the function.
1639
1640    --  If both arrays are constrained and have the same bounds, we can generate
1641    --  a loop with an explicit iteration scheme using a 'Range attribute over
1642    --  the first array.
1643
1644    function Expand_Array_Equality
1645      (Nod    : Node_Id;
1646       Lhs    : Node_Id;
1647       Rhs    : Node_Id;
1648       Bodies : List_Id;
1649       Typ    : Entity_Id) return Node_Id
1650    is
1651       Loc         : constant Source_Ptr := Sloc (Nod);
1652       Decls       : constant List_Id    := New_List;
1653       Index_List1 : constant List_Id    := New_List;
1654       Index_List2 : constant List_Id    := New_List;
1655
1656       Actuals   : List_Id;
1657       Formals   : List_Id;
1658       Func_Name : Entity_Id;
1659       Func_Body : Node_Id;
1660
1661       A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1662       B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1663
1664       Ltyp : Entity_Id;
1665       Rtyp : Entity_Id;
1666       --  The parameter types to be used for the formals
1667
1668       function Arr_Attr
1669         (Arr : Entity_Id;
1670          Nam : Name_Id;
1671          Num : Int) return Node_Id;
1672       --  This builds the attribute reference Arr'Nam (Expr)
1673
1674       function Component_Equality (Typ : Entity_Id) return Node_Id;
1675       --  Create one statement to compare corresponding components, designated
1676       --  by a full set of indexes.
1677
1678       function Get_Arg_Type (N : Node_Id) return Entity_Id;
1679       --  Given one of the arguments, computes the appropriate type to be used
1680       --  for that argument in the corresponding function formal
1681
1682       function Handle_One_Dimension
1683         (N     : Int;
1684          Index : Node_Id) return Node_Id;
1685       --  This procedure returns the following code
1686       --
1687       --    declare
1688       --       Bn : Index_T := B'First (N);
1689       --    begin
1690       --       loop
1691       --          xxx
1692       --          exit when An = A'Last (N);
1693       --          An := Index_T'Succ (An)
1694       --          Bn := Index_T'Succ (Bn)
1695       --       end loop;
1696       --    end;
1697       --
1698       --  If both indexes are constrained and identical, the procedure
1699       --  returns a simpler loop:
1700       --
1701       --      for An in A'Range (N) loop
1702       --         xxx
1703       --      end loop
1704       --
1705       --  N is the dimension for which we are generating a loop. Index is the
1706       --  N'th index node, whose Etype is Index_Type_n in the above code. The
1707       --  xxx statement is either the loop or declare for the next dimension
1708       --  or if this is the last dimension the comparison of corresponding
1709       --  components of the arrays.
1710       --
1711       --  The actual way the code works is to return the comparison of
1712       --  corresponding components for the N+1 call. That's neater!
1713
1714       function Test_Empty_Arrays return Node_Id;
1715       --  This function constructs the test for both arrays being empty
1716       --    (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1717       --      and then
1718       --    (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1719
1720       function Test_Lengths_Correspond return Node_Id;
1721       --  This function constructs the test for arrays having different lengths
1722       --  in at least one index position, in which case the resulting code is:
1723
1724       --     A'length (1) /= B'length (1)
1725       --       or else
1726       --     A'length (2) /= B'length (2)
1727       --       or else
1728       --       ...
1729
1730       --------------
1731       -- Arr_Attr --
1732       --------------
1733
1734       function Arr_Attr
1735         (Arr : Entity_Id;
1736          Nam : Name_Id;
1737          Num : Int) return Node_Id
1738       is
1739       begin
1740          return
1741            Make_Attribute_Reference (Loc,
1742             Attribute_Name => Nam,
1743             Prefix => New_Reference_To (Arr, Loc),
1744             Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1745       end Arr_Attr;
1746
1747       ------------------------
1748       -- Component_Equality --
1749       ------------------------
1750
1751       function Component_Equality (Typ : Entity_Id) return Node_Id is
1752          Test : Node_Id;
1753          L, R : Node_Id;
1754
1755       begin
1756          --  if a(i1...) /= b(j1...) then return false; end if;
1757
1758          L :=
1759            Make_Indexed_Component (Loc,
1760              Prefix      => Make_Identifier (Loc, Chars (A)),
1761              Expressions => Index_List1);
1762
1763          R :=
1764            Make_Indexed_Component (Loc,
1765              Prefix      => Make_Identifier (Loc, Chars (B)),
1766              Expressions => Index_List2);
1767
1768          Test := Expand_Composite_Equality
1769                    (Nod, Component_Type (Typ), L, R, Decls);
1770
1771          --  If some (sub)component is an unchecked_union, the whole operation
1772          --  will raise program error.
1773
1774          if Nkind (Test) = N_Raise_Program_Error then
1775
1776             --  This node is going to be inserted at a location where a
1777             --  statement is expected: clear its Etype so analysis will set
1778             --  it to the expected Standard_Void_Type.
1779
1780             Set_Etype (Test, Empty);
1781             return Test;
1782
1783          else
1784             return
1785               Make_Implicit_If_Statement (Nod,
1786                 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1787                 Then_Statements => New_List (
1788                   Make_Simple_Return_Statement (Loc,
1789                     Expression => New_Occurrence_Of (Standard_False, Loc))));
1790          end if;
1791       end Component_Equality;
1792
1793       ------------------
1794       -- Get_Arg_Type --
1795       ------------------
1796
1797       function Get_Arg_Type (N : Node_Id) return Entity_Id is
1798          T : Entity_Id;
1799          X : Node_Id;
1800
1801       begin
1802          T := Etype (N);
1803
1804          if No (T) then
1805             return Typ;
1806
1807          else
1808             T := Underlying_Type (T);
1809
1810             X := First_Index (T);
1811             while Present (X) loop
1812                if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1813                  or else
1814                    Denotes_Discriminant (Type_High_Bound (Etype (X)))
1815                then
1816                   T := Base_Type (T);
1817                   exit;
1818                end if;
1819
1820                Next_Index (X);
1821             end loop;
1822
1823             return T;
1824          end if;
1825       end Get_Arg_Type;
1826
1827       --------------------------
1828       -- Handle_One_Dimension --
1829       ---------------------------
1830
1831       function Handle_One_Dimension
1832         (N     : Int;
1833          Index : Node_Id) return Node_Id
1834       is
1835          Need_Separate_Indexes : constant Boolean :=
1836                                    Ltyp /= Rtyp
1837                                      or else not Is_Constrained (Ltyp);
1838          --  If the index types are identical, and we are working with
1839          --  constrained types, then we can use the same index for both
1840          --  of the arrays.
1841
1842          An : constant Entity_Id := Make_Temporary (Loc, 'A');
1843
1844          Bn       : Entity_Id;
1845          Index_T  : Entity_Id;
1846          Stm_List : List_Id;
1847          Loop_Stm : Node_Id;
1848
1849       begin
1850          if N > Number_Dimensions (Ltyp) then
1851             return Component_Equality (Ltyp);
1852          end if;
1853
1854          --  Case where we generate a loop
1855
1856          Index_T := Base_Type (Etype (Index));
1857
1858          if Need_Separate_Indexes then
1859             Bn := Make_Temporary (Loc, 'B');
1860          else
1861             Bn := An;
1862          end if;
1863
1864          Append (New_Reference_To (An, Loc), Index_List1);
1865          Append (New_Reference_To (Bn, Loc), Index_List2);
1866
1867          Stm_List := New_List (
1868            Handle_One_Dimension (N + 1, Next_Index (Index)));
1869
1870          if Need_Separate_Indexes then
1871
1872             --  Generate guard for loop, followed by increments of indexes
1873
1874             Append_To (Stm_List,
1875                Make_Exit_Statement (Loc,
1876                  Condition =>
1877                    Make_Op_Eq (Loc,
1878                       Left_Opnd => New_Reference_To (An, Loc),
1879                       Right_Opnd => Arr_Attr (A, Name_Last, N))));
1880
1881             Append_To (Stm_List,
1882               Make_Assignment_Statement (Loc,
1883                 Name       => New_Reference_To (An, Loc),
1884                 Expression =>
1885                   Make_Attribute_Reference (Loc,
1886                     Prefix         => New_Reference_To (Index_T, Loc),
1887                     Attribute_Name => Name_Succ,
1888                     Expressions    => New_List (New_Reference_To (An, Loc)))));
1889
1890             Append_To (Stm_List,
1891               Make_Assignment_Statement (Loc,
1892                 Name       => New_Reference_To (Bn, Loc),
1893                 Expression =>
1894                   Make_Attribute_Reference (Loc,
1895                     Prefix         => New_Reference_To (Index_T, Loc),
1896                     Attribute_Name => Name_Succ,
1897                     Expressions    => New_List (New_Reference_To (Bn, Loc)))));
1898          end if;
1899
1900          --  If separate indexes, we need a declare block for An and Bn, and a
1901          --  loop without an iteration scheme.
1902
1903          if Need_Separate_Indexes then
1904             Loop_Stm :=
1905               Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
1906
1907             return
1908               Make_Block_Statement (Loc,
1909                 Declarations => New_List (
1910                   Make_Object_Declaration (Loc,
1911                     Defining_Identifier => An,
1912                     Object_Definition   => New_Reference_To (Index_T, Loc),
1913                     Expression          => Arr_Attr (A, Name_First, N)),
1914
1915                   Make_Object_Declaration (Loc,
1916                     Defining_Identifier => Bn,
1917                     Object_Definition   => New_Reference_To (Index_T, Loc),
1918                     Expression          => Arr_Attr (B, Name_First, N))),
1919
1920                 Handled_Statement_Sequence =>
1921                   Make_Handled_Sequence_Of_Statements (Loc,
1922                     Statements => New_List (Loop_Stm)));
1923
1924          --  If no separate indexes, return loop statement with explicit
1925          --  iteration scheme on its own
1926
1927          else
1928             Loop_Stm :=
1929               Make_Implicit_Loop_Statement (Nod,
1930                 Statements       => Stm_List,
1931                 Iteration_Scheme =>
1932                   Make_Iteration_Scheme (Loc,
1933                     Loop_Parameter_Specification =>
1934                       Make_Loop_Parameter_Specification (Loc,
1935                         Defining_Identifier         => An,
1936                         Discrete_Subtype_Definition =>
1937                           Arr_Attr (A, Name_Range, N))));
1938             return Loop_Stm;
1939          end if;
1940       end Handle_One_Dimension;
1941
1942       -----------------------
1943       -- Test_Empty_Arrays --
1944       -----------------------
1945
1946       function Test_Empty_Arrays return Node_Id is
1947          Alist : Node_Id;
1948          Blist : Node_Id;
1949
1950          Atest : Node_Id;
1951          Btest : Node_Id;
1952
1953       begin
1954          Alist := Empty;
1955          Blist := Empty;
1956          for J in 1 .. Number_Dimensions (Ltyp) loop
1957             Atest :=
1958               Make_Op_Eq (Loc,
1959                 Left_Opnd  => Arr_Attr (A, Name_Length, J),
1960                 Right_Opnd => Make_Integer_Literal (Loc, 0));
1961
1962             Btest :=
1963               Make_Op_Eq (Loc,
1964                 Left_Opnd  => Arr_Attr (B, Name_Length, J),
1965                 Right_Opnd => Make_Integer_Literal (Loc, 0));
1966
1967             if No (Alist) then
1968                Alist := Atest;
1969                Blist := Btest;
1970
1971             else
1972                Alist :=
1973                  Make_Or_Else (Loc,
1974                    Left_Opnd  => Relocate_Node (Alist),
1975                    Right_Opnd => Atest);
1976
1977                Blist :=
1978                  Make_Or_Else (Loc,
1979                    Left_Opnd  => Relocate_Node (Blist),
1980                    Right_Opnd => Btest);
1981             end if;
1982          end loop;
1983
1984          return
1985            Make_And_Then (Loc,
1986              Left_Opnd  => Alist,
1987              Right_Opnd => Blist);
1988       end Test_Empty_Arrays;
1989
1990       -----------------------------
1991       -- Test_Lengths_Correspond --
1992       -----------------------------
1993
1994       function Test_Lengths_Correspond return Node_Id is
1995          Result : Node_Id;
1996          Rtest  : Node_Id;
1997
1998       begin
1999          Result := Empty;
2000          for J in 1 .. Number_Dimensions (Ltyp) loop
2001             Rtest :=
2002               Make_Op_Ne (Loc,
2003                 Left_Opnd  => Arr_Attr (A, Name_Length, J),
2004                 Right_Opnd => Arr_Attr (B, Name_Length, J));
2005
2006             if No (Result) then
2007                Result := Rtest;
2008             else
2009                Result :=
2010                  Make_Or_Else (Loc,
2011                    Left_Opnd  => Relocate_Node (Result),
2012                    Right_Opnd => Rtest);
2013             end if;
2014          end loop;
2015
2016          return Result;
2017       end Test_Lengths_Correspond;
2018
2019    --  Start of processing for Expand_Array_Equality
2020
2021    begin
2022       Ltyp := Get_Arg_Type (Lhs);
2023       Rtyp := Get_Arg_Type (Rhs);
2024
2025       --  For now, if the argument types are not the same, go to the base type,
2026       --  since the code assumes that the formals have the same type. This is
2027       --  fixable in future ???
2028
2029       if Ltyp /= Rtyp then
2030          Ltyp := Base_Type (Ltyp);
2031          Rtyp := Base_Type (Rtyp);
2032          pragma Assert (Ltyp = Rtyp);
2033       end if;
2034
2035       --  Build list of formals for function
2036
2037       Formals := New_List (
2038         Make_Parameter_Specification (Loc,
2039           Defining_Identifier => A,
2040           Parameter_Type      => New_Reference_To (Ltyp, Loc)),
2041
2042         Make_Parameter_Specification (Loc,
2043           Defining_Identifier => B,
2044           Parameter_Type      => New_Reference_To (Rtyp, Loc)));
2045
2046       Func_Name := Make_Temporary (Loc, 'E');
2047
2048       --  Build statement sequence for function
2049
2050       Func_Body :=
2051         Make_Subprogram_Body (Loc,
2052           Specification =>
2053             Make_Function_Specification (Loc,
2054               Defining_Unit_Name       => Func_Name,
2055               Parameter_Specifications => Formals,
2056               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
2057
2058           Declarations =>  Decls,
2059
2060           Handled_Statement_Sequence =>
2061             Make_Handled_Sequence_Of_Statements (Loc,
2062               Statements => New_List (
2063
2064                 Make_Implicit_If_Statement (Nod,
2065                   Condition => Test_Empty_Arrays,
2066                   Then_Statements => New_List (
2067                     Make_Simple_Return_Statement (Loc,
2068                       Expression =>
2069                         New_Occurrence_Of (Standard_True, Loc)))),
2070
2071                 Make_Implicit_If_Statement (Nod,
2072                   Condition => Test_Lengths_Correspond,
2073                   Then_Statements => New_List (
2074                     Make_Simple_Return_Statement (Loc,
2075                       Expression =>
2076                         New_Occurrence_Of (Standard_False, Loc)))),
2077
2078                 Handle_One_Dimension (1, First_Index (Ltyp)),
2079
2080                 Make_Simple_Return_Statement (Loc,
2081                   Expression => New_Occurrence_Of (Standard_True, Loc)))));
2082
2083          Set_Has_Completion (Func_Name, True);
2084          Set_Is_Inlined (Func_Name);
2085
2086          --  If the array type is distinct from the type of the arguments, it
2087          --  is the full view of a private type. Apply an unchecked conversion
2088          --  to insure that analysis of the call succeeds.
2089
2090          declare
2091             L, R : Node_Id;
2092
2093          begin
2094             L := Lhs;
2095             R := Rhs;
2096
2097             if No (Etype (Lhs))
2098               or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
2099             then
2100                L := OK_Convert_To (Ltyp, Lhs);
2101             end if;
2102
2103             if No (Etype (Rhs))
2104               or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
2105             then
2106                R := OK_Convert_To (Rtyp, Rhs);
2107             end if;
2108
2109             Actuals := New_List (L, R);
2110          end;
2111
2112          Append_To (Bodies, Func_Body);
2113
2114          return
2115            Make_Function_Call (Loc,
2116              Name                   => New_Reference_To (Func_Name, Loc),
2117              Parameter_Associations => Actuals);
2118    end Expand_Array_Equality;
2119
2120    -----------------------------
2121    -- Expand_Boolean_Operator --
2122    -----------------------------
2123
2124    --  Note that we first get the actual subtypes of the operands, since we
2125    --  always want to deal with types that have bounds.
2126
2127    procedure Expand_Boolean_Operator (N : Node_Id) is
2128       Typ : constant Entity_Id  := Etype (N);
2129
2130    begin
2131       --  Special case of bit packed array where both operands are known to be
2132       --  properly aligned. In this case we use an efficient run time routine
2133       --  to carry out the operation (see System.Bit_Ops).
2134
2135       if Is_Bit_Packed_Array (Typ)
2136         and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
2137         and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
2138       then
2139          Expand_Packed_Boolean_Operator (N);
2140          return;
2141       end if;
2142
2143       --  For the normal non-packed case, the general expansion is to build
2144       --  function for carrying out the comparison (use Make_Boolean_Array_Op)
2145       --  and then inserting it into the tree. The original operator node is
2146       --  then rewritten as a call to this function. We also use this in the
2147       --  packed case if either operand is a possibly unaligned object.
2148
2149       declare
2150          Loc       : constant Source_Ptr := Sloc (N);
2151          L         : constant Node_Id    := Relocate_Node (Left_Opnd  (N));
2152          R         : constant Node_Id    := Relocate_Node (Right_Opnd (N));
2153          Func_Body : Node_Id;
2154          Func_Name : Entity_Id;
2155
2156       begin
2157          Convert_To_Actual_Subtype (L);
2158          Convert_To_Actual_Subtype (R);
2159          Ensure_Defined (Etype (L), N);
2160          Ensure_Defined (Etype (R), N);
2161          Apply_Length_Check (R, Etype (L));
2162
2163          if Nkind (N) = N_Op_Xor then
2164             Silly_Boolean_Array_Xor_Test (N, Etype (L));
2165          end if;
2166
2167          if Nkind (Parent (N)) = N_Assignment_Statement
2168            and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
2169          then
2170             Build_Boolean_Array_Proc_Call (Parent (N), L, R);
2171
2172          elsif Nkind (Parent (N)) = N_Op_Not
2173            and then Nkind (N) = N_Op_And
2174            and then
2175              Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
2176          then
2177             return;
2178          else
2179
2180             Func_Body := Make_Boolean_Array_Op (Etype (L), N);
2181             Func_Name := Defining_Unit_Name (Specification (Func_Body));
2182             Insert_Action (N, Func_Body);
2183
2184             --  Now rewrite the expression with a call
2185
2186             Rewrite (N,
2187               Make_Function_Call (Loc,
2188                 Name                   => New_Reference_To (Func_Name, Loc),
2189                 Parameter_Associations =>
2190                   New_List (
2191                     L,
2192                     Make_Type_Conversion
2193                       (Loc, New_Reference_To (Etype (L), Loc), R))));
2194
2195             Analyze_And_Resolve (N, Typ);
2196          end if;
2197       end;
2198    end Expand_Boolean_Operator;
2199
2200    -------------------------------
2201    -- Expand_Composite_Equality --
2202    -------------------------------
2203
2204    --  This function is only called for comparing internal fields of composite
2205    --  types when these fields are themselves composites. This is a special
2206    --  case because it is not possible to respect normal Ada visibility rules.
2207
2208    function Expand_Composite_Equality
2209      (Nod    : Node_Id;
2210       Typ    : Entity_Id;
2211       Lhs    : Node_Id;
2212       Rhs    : Node_Id;
2213       Bodies : List_Id) return Node_Id
2214    is
2215       Loc       : constant Source_Ptr := Sloc (Nod);
2216       Full_Type : Entity_Id;
2217       Prim      : Elmt_Id;
2218       Eq_Op     : Entity_Id;
2219
2220       function Find_Primitive_Eq return Node_Id;
2221       --  AI05-0123: Locate primitive equality for type if it exists, and
2222       --  build the corresponding call. If operation is abstract, replace
2223       --  call with an explicit raise. Return Empty if there is no primitive.
2224
2225       -----------------------
2226       -- Find_Primitive_Eq --
2227       -----------------------
2228
2229       function Find_Primitive_Eq return Node_Id is
2230          Prim_E : Elmt_Id;
2231          Prim   : Node_Id;
2232
2233       begin
2234          Prim_E := First_Elmt (Collect_Primitive_Operations (Typ));
2235          while Present (Prim_E) loop
2236             Prim := Node (Prim_E);
2237
2238             --  Locate primitive equality with the right signature
2239
2240             if Chars (Prim) = Name_Op_Eq
2241               and then Etype (First_Formal (Prim)) =
2242                        Etype (Next_Formal (First_Formal (Prim)))
2243               and then Etype (Prim) = Standard_Boolean
2244             then
2245                if Is_Abstract_Subprogram (Prim) then
2246                   return
2247                     Make_Raise_Program_Error (Loc,
2248                       Reason => PE_Explicit_Raise);
2249
2250                else
2251                   return
2252                     Make_Function_Call (Loc,
2253                       Name                   => New_Reference_To (Prim, Loc),
2254                       Parameter_Associations => New_List (Lhs, Rhs));
2255                end if;
2256             end if;
2257
2258             Next_Elmt (Prim_E);
2259          end loop;
2260
2261          --  If not found, predefined operation will be used
2262
2263          return Empty;
2264       end Find_Primitive_Eq;
2265
2266    --  Start of processing for Expand_Composite_Equality
2267
2268    begin
2269       if Is_Private_Type (Typ) then
2270          Full_Type := Underlying_Type (Typ);
2271       else
2272          Full_Type := Typ;
2273       end if;
2274
2275       --  Defense against malformed private types with no completion the error
2276       --  will be diagnosed later by check_completion
2277
2278       if No (Full_Type) then
2279          return New_Reference_To (Standard_False, Loc);
2280       end if;
2281
2282       Full_Type := Base_Type (Full_Type);
2283
2284       if Is_Array_Type (Full_Type) then
2285
2286          --  If the operand is an elementary type other than a floating-point
2287          --  type, then we can simply use the built-in block bitwise equality,
2288          --  since the predefined equality operators always apply and bitwise
2289          --  equality is fine for all these cases.
2290
2291          if Is_Elementary_Type (Component_Type (Full_Type))
2292            and then not Is_Floating_Point_Type (Component_Type (Full_Type))
2293          then
2294             return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2295
2296          --  For composite component types, and floating-point types, use the
2297          --  expansion. This deals with tagged component types (where we use
2298          --  the applicable equality routine) and floating-point, (where we
2299          --  need to worry about negative zeroes), and also the case of any
2300          --  composite type recursively containing such fields.
2301
2302          else
2303             return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Full_Type);
2304          end if;
2305
2306       elsif Is_Tagged_Type (Full_Type) then
2307
2308          --  Call the primitive operation "=" of this type
2309
2310          if Is_Class_Wide_Type (Full_Type) then
2311             Full_Type := Root_Type (Full_Type);
2312          end if;
2313
2314          --  If this is derived from an untagged private type completed with a
2315          --  tagged type, it does not have a full view, so we use the primitive
2316          --  operations of the private type. This check should no longer be
2317          --  necessary when these types receive their full views ???
2318
2319          if Is_Private_Type (Typ)
2320            and then not Is_Tagged_Type (Typ)
2321            and then not Is_Controlled (Typ)
2322            and then Is_Derived_Type (Typ)
2323            and then No (Full_View (Typ))
2324          then
2325             Prim := First_Elmt (Collect_Primitive_Operations (Typ));
2326          else
2327             Prim := First_Elmt (Primitive_Operations (Full_Type));
2328          end if;
2329
2330          loop
2331             Eq_Op := Node (Prim);
2332             exit when Chars (Eq_Op) = Name_Op_Eq
2333               and then Etype (First_Formal (Eq_Op)) =
2334                        Etype (Next_Formal (First_Formal (Eq_Op)))
2335               and then Base_Type (Etype (Eq_Op)) = Standard_Boolean;
2336             Next_Elmt (Prim);
2337             pragma Assert (Present (Prim));
2338          end loop;
2339
2340          Eq_Op := Node (Prim);
2341
2342          return
2343            Make_Function_Call (Loc,
2344              Name => New_Reference_To (Eq_Op, Loc),
2345              Parameter_Associations =>
2346                New_List
2347                  (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2348                   Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2349
2350       elsif Is_Record_Type (Full_Type) then
2351          Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2352
2353          if Present (Eq_Op) then
2354             if Etype (First_Formal (Eq_Op)) /= Full_Type then
2355
2356                --  Inherited equality from parent type. Convert the actuals to
2357                --  match signature of operation.
2358
2359                declare
2360                   T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2361
2362                begin
2363                   return
2364                     Make_Function_Call (Loc,
2365                       Name                  => New_Reference_To (Eq_Op, Loc),
2366                       Parameter_Associations => New_List (
2367                         OK_Convert_To (T, Lhs),
2368                         OK_Convert_To (T, Rhs)));
2369                end;
2370
2371             else
2372                --  Comparison between Unchecked_Union components
2373
2374                if Is_Unchecked_Union (Full_Type) then
2375                   declare
2376                      Lhs_Type      : Node_Id := Full_Type;
2377                      Rhs_Type      : Node_Id := Full_Type;
2378                      Lhs_Discr_Val : Node_Id;
2379                      Rhs_Discr_Val : Node_Id;
2380
2381                   begin
2382                      --  Lhs subtype
2383
2384                      if Nkind (Lhs) = N_Selected_Component then
2385                         Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2386                      end if;
2387
2388                      --  Rhs subtype
2389
2390                      if Nkind (Rhs) = N_Selected_Component then
2391                         Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2392                      end if;
2393
2394                      --  Lhs of the composite equality
2395
2396                      if Is_Constrained (Lhs_Type) then
2397
2398                         --  Since the enclosing record type can never be an
2399                         --  Unchecked_Union (this code is executed for records
2400                         --  that do not have variants), we may reference its
2401                         --  discriminant(s).
2402
2403                         if Nkind (Lhs) = N_Selected_Component
2404                           and then Has_Per_Object_Constraint (
2405                                      Entity (Selector_Name (Lhs)))
2406                         then
2407                            Lhs_Discr_Val :=
2408                              Make_Selected_Component (Loc,
2409                                Prefix        => Prefix (Lhs),
2410                                Selector_Name =>
2411                                  New_Copy
2412                                    (Get_Discriminant_Value
2413                                       (First_Discriminant (Lhs_Type),
2414                                        Lhs_Type,
2415                                        Stored_Constraint (Lhs_Type))));
2416
2417                         else
2418                            Lhs_Discr_Val :=
2419                              New_Copy
2420                                (Get_Discriminant_Value
2421                                   (First_Discriminant (Lhs_Type),
2422                                    Lhs_Type,
2423                                    Stored_Constraint (Lhs_Type)));
2424
2425                         end if;
2426                      else
2427                         --  It is not possible to infer the discriminant since
2428                         --  the subtype is not constrained.
2429
2430                         return
2431                           Make_Raise_Program_Error (Loc,
2432                             Reason => PE_Unchecked_Union_Restriction);
2433                      end if;
2434
2435                      --  Rhs of the composite equality
2436
2437                      if Is_Constrained (Rhs_Type) then
2438                         if Nkind (Rhs) = N_Selected_Component
2439                           and then Has_Per_Object_Constraint
2440                                      (Entity (Selector_Name (Rhs)))
2441                         then
2442                            Rhs_Discr_Val :=
2443                              Make_Selected_Component (Loc,
2444                                Prefix        => Prefix (Rhs),
2445                                Selector_Name =>
2446                                  New_Copy
2447                                    (Get_Discriminant_Value
2448                                       (First_Discriminant (Rhs_Type),
2449                                        Rhs_Type,
2450                                        Stored_Constraint (Rhs_Type))));
2451
2452                         else
2453                            Rhs_Discr_Val :=
2454                              New_Copy
2455                                (Get_Discriminant_Value
2456                                   (First_Discriminant (Rhs_Type),
2457                                    Rhs_Type,
2458                                    Stored_Constraint (Rhs_Type)));
2459
2460                         end if;
2461                      else
2462                         return
2463                           Make_Raise_Program_Error (Loc,
2464                             Reason => PE_Unchecked_Union_Restriction);
2465                      end if;
2466
2467                      --  Call the TSS equality function with the inferred
2468                      --  discriminant values.
2469
2470                      return
2471                        Make_Function_Call (Loc,
2472                          Name => New_Reference_To (Eq_Op, Loc),
2473                          Parameter_Associations => New_List (
2474                            Lhs,
2475                            Rhs,
2476                            Lhs_Discr_Val,
2477                            Rhs_Discr_Val));
2478                   end;
2479
2480                else
2481                   return
2482                     Make_Function_Call (Loc,
2483                       Name                   => New_Reference_To (Eq_Op, Loc),
2484                       Parameter_Associations => New_List (Lhs, Rhs));
2485                end if;
2486             end if;
2487
2488          elsif Ada_Version >= Ada_2012 then
2489
2490             --  if no TSS has been created for the type, check whether there is
2491             --  a primitive equality declared for it.
2492
2493             declare
2494                Ada_2012_Op : constant Node_Id := Find_Primitive_Eq;
2495
2496             begin
2497                if Present (Ada_2012_Op) then
2498                   return Ada_2012_Op;
2499                else
2500
2501                --  Use predefined equality if no user-defined primitive exists
2502
2503                   return Make_Op_Eq (Loc, Lhs, Rhs);
2504                end if;
2505             end;
2506
2507          else
2508             return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2509          end if;
2510
2511       else
2512          --  If not array or record type, it is predefined equality.
2513
2514          return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2515       end if;
2516    end Expand_Composite_Equality;
2517
2518    ------------------------
2519    -- Expand_Concatenate --
2520    ------------------------
2521
2522    procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2523       Loc : constant Source_Ptr := Sloc (Cnode);
2524
2525       Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2526       --  Result type of concatenation
2527
2528       Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2529       --  Component type. Elements of this component type can appear as one
2530       --  of the operands of concatenation as well as arrays.
2531
2532       Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2533       --  Index subtype
2534
2535       Ityp : constant Entity_Id := Base_Type (Istyp);
2536       --  Index type. This is the base type of the index subtype, and is used
2537       --  for all computed bounds (which may be out of range of Istyp in the
2538       --  case of null ranges).
2539
2540       Artyp : Entity_Id;
2541       --  This is the type we use to do arithmetic to compute the bounds and
2542       --  lengths of operands. The choice of this type is a little subtle and
2543       --  is discussed in a separate section at the start of the body code.
2544
2545       Concatenation_Error : exception;
2546       --  Raised if concatenation is sure to raise a CE
2547
2548       Result_May_Be_Null : Boolean := True;
2549       --  Reset to False if at least one operand is encountered which is known
2550       --  at compile time to be non-null. Used for handling the special case
2551       --  of setting the high bound to the last operand high bound for a null
2552       --  result, thus ensuring a proper high bound in the super-flat case.
2553
2554       N : constant Nat := List_Length (Opnds);
2555       --  Number of concatenation operands including possibly null operands
2556
2557       NN : Nat := 0;
2558       --  Number of operands excluding any known to be null, except that the
2559       --  last operand is always retained, in case it provides the bounds for
2560       --  a null result.
2561
2562       Opnd : Node_Id;
2563       --  Current operand being processed in the loop through operands. After
2564       --  this loop is complete, always contains the last operand (which is not
2565       --  the same as Operands (NN), since null operands are skipped).
2566
2567       --  Arrays describing the operands, only the first NN entries of each
2568       --  array are set (NN < N when we exclude known null operands).
2569
2570       Is_Fixed_Length : array (1 .. N) of Boolean;
2571       --  True if length of corresponding operand known at compile time
2572
2573       Operands : array (1 .. N) of Node_Id;
2574       --  Set to the corresponding entry in the Opnds list (but note that null
2575       --  operands are excluded, so not all entries in the list are stored).
2576
2577       Fixed_Length : array (1 .. N) of Uint;
2578       --  Set to length of operand. Entries in this array are set only if the
2579       --  corresponding entry in Is_Fixed_Length is True.
2580
2581       Opnd_Low_Bound : array (1 .. N) of Node_Id;
2582       --  Set to lower bound of operand. Either an integer literal in the case
2583       --  where the bound is known at compile time, else actual lower bound.
2584       --  The operand low bound is of type Ityp.
2585
2586       Var_Length : array (1 .. N) of Entity_Id;
2587       --  Set to an entity of type Natural that contains the length of an
2588       --  operand whose length is not known at compile time. Entries in this
2589       --  array are set only if the corresponding entry in Is_Fixed_Length
2590       --  is False. The entity is of type Artyp.
2591
2592       Aggr_Length : array (0 .. N) of Node_Id;
2593       --  The J'th entry in an expression node that represents the total length
2594       --  of operands 1 through J. It is either an integer literal node, or a
2595       --  reference to a constant entity with the right value, so it is fine
2596       --  to just do a Copy_Node to get an appropriate copy. The extra zero'th
2597       --  entry always is set to zero. The length is of type Artyp.
2598
2599       Low_Bound : Node_Id;
2600       --  A tree node representing the low bound of the result (of type Ityp).
2601       --  This is either an integer literal node, or an identifier reference to
2602       --  a constant entity initialized to the appropriate value.
2603
2604       Last_Opnd_High_Bound : Node_Id;
2605       --  A tree node representing the high bound of the last operand. This
2606       --  need only be set if the result could be null. It is used for the
2607       --  special case of setting the right high bound for a null result.
2608       --  This is of type Ityp.
2609
2610       High_Bound : Node_Id;
2611       --  A tree node representing the high bound of the result (of type Ityp)
2612
2613       Result : Node_Id;
2614       --  Result of the concatenation (of type Ityp)
2615
2616       Actions : constant List_Id := New_List;
2617       --  Collect actions to be inserted
2618
2619       Known_Non_Null_Operand_Seen : Boolean;
2620       --  Set True during generation of the assignments of operands into
2621       --  result once an operand known to be non-null has been seen.
2622
2623       function Make_Artyp_Literal (Val : Nat) return Node_Id;
2624       --  This function makes an N_Integer_Literal node that is returned in
2625       --  analyzed form with the type set to Artyp. Importantly this literal
2626       --  is not flagged as static, so that if we do computations with it that
2627       --  result in statically detected out of range conditions, we will not
2628       --  generate error messages but instead warning messages.
2629
2630       function To_Artyp (X : Node_Id) return Node_Id;
2631       --  Given a node of type Ityp, returns the corresponding value of type
2632       --  Artyp. For non-enumeration types, this is a plain integer conversion.
2633       --  For enum types, the Pos of the value is returned.
2634
2635       function To_Ityp (X : Node_Id) return Node_Id;
2636       --  The inverse function (uses Val in the case of enumeration types)
2637
2638       ------------------------
2639       -- Make_Artyp_Literal --
2640       ------------------------
2641
2642       function Make_Artyp_Literal (Val : Nat) return Node_Id is
2643          Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
2644       begin
2645          Set_Etype (Result, Artyp);
2646          Set_Analyzed (Result, True);
2647          Set_Is_Static_Expression (Result, False);
2648          return Result;
2649       end Make_Artyp_Literal;
2650
2651       --------------
2652       -- To_Artyp --
2653       --------------
2654
2655       function To_Artyp (X : Node_Id) return Node_Id is
2656       begin
2657          if Ityp = Base_Type (Artyp) then
2658             return X;
2659
2660          elsif Is_Enumeration_Type (Ityp) then
2661             return
2662               Make_Attribute_Reference (Loc,
2663                 Prefix         => New_Occurrence_Of (Ityp, Loc),
2664                 Attribute_Name => Name_Pos,
2665                 Expressions    => New_List (X));
2666
2667          else
2668             return Convert_To (Artyp, X);
2669          end if;
2670       end To_Artyp;
2671
2672       -------------
2673       -- To_Ityp --
2674       -------------
2675
2676       function To_Ityp (X : Node_Id) return Node_Id is
2677       begin
2678          if Is_Enumeration_Type (Ityp) then
2679             return
2680               Make_Attribute_Reference (Loc,
2681                 Prefix         => New_Occurrence_Of (Ityp, Loc),
2682                 Attribute_Name => Name_Val,
2683                 Expressions    => New_List (X));
2684
2685          --  Case where we will do a type conversion
2686
2687          else
2688             if Ityp = Base_Type (Artyp) then
2689                return X;
2690             else
2691                return Convert_To (Ityp, X);
2692             end if;
2693          end if;
2694       end To_Ityp;
2695
2696       --  Local Declarations
2697
2698       Opnd_Typ : Entity_Id;
2699       Ent      : Entity_Id;
2700       Len      : Uint;
2701       J        : Nat;
2702       Clen     : Node_Id;
2703       Set      : Boolean;
2704
2705    --  Start of processing for Expand_Concatenate
2706
2707    begin
2708       --  Choose an appropriate computational type
2709
2710       --  We will be doing calculations of lengths and bounds in this routine
2711       --  and computing one from the other in some cases, e.g. getting the high
2712       --  bound by adding the length-1 to the low bound.
2713
2714       --  We can't just use the index type, or even its base type for this
2715       --  purpose for two reasons. First it might be an enumeration type which
2716       --  is not suitable for computations of any kind, and second it may
2717       --  simply not have enough range. For example if the index type is
2718       --  -128..+127 then lengths can be up to 256, which is out of range of
2719       --  the type.
2720
2721       --  For enumeration types, we can simply use Standard_Integer, this is
2722       --  sufficient since the actual number of enumeration literals cannot
2723       --  possibly exceed the range of integer (remember we will be doing the
2724       --  arithmetic with POS values, not representation values).
2725
2726       if Is_Enumeration_Type (Ityp) then
2727          Artyp := Standard_Integer;
2728
2729       --  If index type is Positive, we use the standard unsigned type, to give
2730       --  more room on the top of the range, obviating the need for an overflow
2731       --  check when creating the upper bound. This is needed to avoid junk
2732       --  overflow checks in the common case of String types.
2733
2734       --  ??? Disabled for now
2735
2736       --  elsif Istyp = Standard_Positive then
2737       --     Artyp := Standard_Unsigned;
2738
2739       --  For modular types, we use a 32-bit modular type for types whose size
2740       --  is in the range 1-31 bits. For 32-bit unsigned types, we use the
2741       --  identity type, and for larger unsigned types we use 64-bits.
2742
2743       elsif Is_Modular_Integer_Type (Ityp) then
2744          if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
2745             Artyp := Standard_Unsigned;
2746          elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
2747             Artyp := Ityp;
2748          else
2749             Artyp := RTE (RE_Long_Long_Unsigned);
2750          end if;
2751
2752       --  Similar treatment for signed types
2753
2754       else
2755          if RM_Size (Ityp) < RM_Size (Standard_Integer) then
2756             Artyp := Standard_Integer;
2757          elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
2758             Artyp := Ityp;
2759          else
2760             Artyp := Standard_Long_Long_Integer;
2761          end if;
2762       end if;
2763
2764       --  Supply dummy entry at start of length array
2765
2766       Aggr_Length (0) := Make_Artyp_Literal (0);
2767
2768       --  Go through operands setting up the above arrays
2769
2770       J := 1;
2771       while J <= N loop
2772          Opnd := Remove_Head (Opnds);
2773          Opnd_Typ := Etype (Opnd);
2774
2775          --  The parent got messed up when we put the operands in a list,
2776          --  so now put back the proper parent for the saved operand, that
2777          --  is to say the concatenation node, to make sure that each operand
2778          --  is seen as a subexpression, e.g. if actions must be inserted.
2779
2780          Set_Parent (Opnd, Cnode);
2781
2782          --  Set will be True when we have setup one entry in the array
2783
2784          Set := False;
2785
2786          --  Singleton element (or character literal) case
2787
2788          if Base_Type (Opnd_Typ) = Ctyp then
2789             NN := NN + 1;
2790             Operands (NN) := Opnd;
2791             Is_Fixed_Length (NN) := True;
2792             Fixed_Length (NN) := Uint_1;
2793             Result_May_Be_Null := False;
2794
2795             --  Set low bound of operand (no need to set Last_Opnd_High_Bound
2796             --  since we know that the result cannot be null).
2797
2798             Opnd_Low_Bound (NN) :=
2799               Make_Attribute_Reference (Loc,
2800                 Prefix         => New_Reference_To (Istyp, Loc),
2801                 Attribute_Name => Name_First);
2802
2803             Set := True;
2804
2805          --  String literal case (can only occur for strings of course)
2806
2807          elsif Nkind (Opnd) = N_String_Literal then
2808             Len := String_Literal_Length (Opnd_Typ);
2809
2810             if Len /= 0 then
2811                Result_May_Be_Null := False;
2812             end if;
2813
2814             --  Capture last operand high bound if result could be null
2815
2816             if J = N and then Result_May_Be_Null then
2817                Last_Opnd_High_Bound :=
2818                  Make_Op_Add (Loc,
2819                    Left_Opnd  =>
2820                      New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
2821                    Right_Opnd => Make_Integer_Literal (Loc, 1));
2822             end if;
2823
2824             --  Skip null string literal
2825
2826             if J < N and then Len = 0 then
2827                goto Continue;
2828             end if;
2829
2830             NN := NN + 1;
2831             Operands (NN) := Opnd;
2832             Is_Fixed_Length (NN) := True;
2833
2834             --  Set length and bounds
2835
2836             Fixed_Length (NN) := Len;
2837
2838             Opnd_Low_Bound (NN) :=
2839               New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
2840
2841             Set := True;
2842
2843          --  All other cases
2844
2845          else
2846             --  Check constrained case with known bounds
2847
2848             if Is_Constrained (Opnd_Typ) then
2849                declare
2850                   Index    : constant Node_Id   := First_Index (Opnd_Typ);
2851                   Indx_Typ : constant Entity_Id := Etype (Index);
2852                   Lo       : constant Node_Id   := Type_Low_Bound  (Indx_Typ);
2853                   Hi       : constant Node_Id   := Type_High_Bound (Indx_Typ);
2854
2855                begin
2856                   --  Fixed length constrained array type with known at compile
2857                   --  time bounds is last case of fixed length operand.
2858
2859                   if Compile_Time_Known_Value (Lo)
2860                        and then
2861                      Compile_Time_Known_Value (Hi)
2862                   then
2863                      declare
2864                         Loval : constant Uint := Expr_Value (Lo);
2865                         Hival : constant Uint := Expr_Value (Hi);
2866                         Len   : constant Uint :=
2867                                   UI_Max (Hival - Loval + 1, Uint_0);
2868
2869                      begin
2870                         if Len > 0 then
2871                            Result_May_Be_Null := False;
2872                         end if;
2873
2874                         --  Capture last operand bound if result could be null
2875
2876                         if J = N and then Result_May_Be_Null then
2877                            Last_Opnd_High_Bound :=
2878                              Convert_To (Ityp,
2879                                Make_Integer_Literal (Loc, Expr_Value (Hi)));
2880                         end if;
2881
2882                         --  Exclude null length case unless last operand
2883
2884                         if J < N and then Len = 0 then
2885                            goto Continue;
2886                         end if;
2887
2888                         NN := NN + 1;
2889                         Operands (NN) := Opnd;
2890                         Is_Fixed_Length (NN) := True;
2891                         Fixed_Length (NN)    := Len;
2892
2893                         Opnd_Low_Bound (NN) :=
2894                           To_Ityp
2895                             (Make_Integer_Literal (Loc, Expr_Value (Lo)));
2896                         Set := True;
2897                      end;
2898                   end if;
2899                end;
2900             end if;
2901
2902             --  All cases where the length is not known at compile time, or the
2903             --  special case of an operand which is known to be null but has a
2904             --  lower bound other than 1 or is other than a string type.
2905
2906             if not Set then
2907                NN := NN + 1;
2908
2909                --  Capture operand bounds
2910
2911                Opnd_Low_Bound (NN) :=
2912                  Make_Attribute_Reference (Loc,
2913                    Prefix         =>
2914                      Duplicate_Subexpr (Opnd, Name_Req => True),
2915                    Attribute_Name => Name_First);
2916
2917                if J = N and Result_May_Be_Null then
2918                   Last_Opnd_High_Bound :=
2919                     Convert_To (Ityp,
2920                       Make_Attribute_Reference (Loc,
2921                         Prefix         =>
2922                           Duplicate_Subexpr (Opnd, Name_Req => True),
2923                         Attribute_Name => Name_Last));
2924                end if;
2925
2926                --  Capture length of operand in entity
2927
2928                Operands (NN) := Opnd;
2929                Is_Fixed_Length (NN) := False;
2930
2931                Var_Length (NN) := Make_Temporary (Loc, 'L');
2932
2933                Append_To (Actions,
2934                  Make_Object_Declaration (Loc,
2935                    Defining_Identifier => Var_Length (NN),
2936                    Constant_Present    => True,
2937                    Object_Definition   => New_Occurrence_Of (Artyp, Loc),
2938                    Expression          =>
2939                      Make_Attribute_Reference (Loc,
2940                        Prefix         =>
2941                          Duplicate_Subexpr (Opnd, Name_Req => True),
2942                        Attribute_Name => Name_Length)));
2943             end if;
2944          end if;
2945
2946          --  Set next entry in aggregate length array
2947
2948          --  For first entry, make either integer literal for fixed length
2949          --  or a reference to the saved length for variable length.
2950
2951          if NN = 1 then
2952             if Is_Fixed_Length (1) then
2953                Aggr_Length (1) := Make_Integer_Literal (Loc, Fixed_Length (1));
2954             else
2955                Aggr_Length (1) := New_Reference_To (Var_Length (1), Loc);
2956             end if;
2957
2958          --  If entry is fixed length and only fixed lengths so far, make
2959          --  appropriate new integer literal adding new length.
2960
2961          elsif Is_Fixed_Length (NN)
2962            and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
2963          then
2964             Aggr_Length (NN) :=
2965               Make_Integer_Literal (Loc,
2966                 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
2967
2968          --  All other cases, construct an addition node for the length and
2969          --  create an entity initialized to this length.
2970
2971          else
2972             Ent := Make_Temporary (Loc, 'L');
2973
2974             if Is_Fixed_Length (NN) then
2975                Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
2976             else
2977                Clen := New_Reference_To (Var_Length (NN), Loc);
2978             end if;
2979
2980             Append_To (Actions,
2981               Make_Object_Declaration (Loc,
2982                 Defining_Identifier => Ent,
2983                 Constant_Present    => True,
2984                 Object_Definition   => New_Occurrence_Of (Artyp, Loc),
2985                 Expression          =>
2986                   Make_Op_Add (Loc,
2987                     Left_Opnd  => New_Copy (Aggr_Length (NN - 1)),
2988                     Right_Opnd => Clen)));
2989
2990             Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
2991          end if;
2992
2993       <<Continue>>
2994          J := J + 1;
2995       end loop;
2996
2997       --  If we have only skipped null operands, return the last operand
2998
2999       if NN = 0 then
3000          Result := Opnd;
3001          goto Done;
3002       end if;
3003
3004       --  If we have only one non-null operand, return it and we are done.
3005       --  There is one case in which this cannot be done, and that is when
3006       --  the sole operand is of the element type, in which case it must be
3007       --  converted to an array, and the easiest way of doing that is to go
3008       --  through the normal general circuit.
3009
3010       if NN = 1
3011         and then Base_Type (Etype (Operands (1))) /= Ctyp
3012       then
3013          Result := Operands (1);
3014          goto Done;
3015       end if;
3016
3017       --  Cases where we have a real concatenation
3018
3019       --  Next step is to find the low bound for the result array that we
3020       --  will allocate. The rules for this are in (RM 4.5.6(5-7)).
3021
3022       --  If the ultimate ancestor of the index subtype is a constrained array
3023       --  definition, then the lower bound is that of the index subtype as
3024       --  specified by (RM 4.5.3(6)).
3025
3026       --  The right test here is to go to the root type, and then the ultimate
3027       --  ancestor is the first subtype of this root type.
3028
3029       if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
3030          Low_Bound :=
3031            Make_Attribute_Reference (Loc,
3032              Prefix         =>
3033                New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
3034              Attribute_Name => Name_First);
3035
3036       --  If the first operand in the list has known length we know that
3037       --  the lower bound of the result is the lower bound of this operand.
3038
3039       elsif Is_Fixed_Length (1) then
3040          Low_Bound := Opnd_Low_Bound (1);
3041
3042       --  OK, we don't know the lower bound, we have to build a horrible
3043       --  expression actions node of the form
3044
3045       --     if Cond1'Length /= 0 then
3046       --        Opnd1 low bound
3047       --     else
3048       --        if Opnd2'Length /= 0 then
3049       --          Opnd2 low bound
3050       --        else
3051       --           ...
3052
3053       --  The nesting ends either when we hit an operand whose length is known
3054       --  at compile time, or on reaching the last operand, whose low bound we
3055       --  take unconditionally whether or not it is null. It's easiest to do
3056       --  this with a recursive procedure:
3057
3058       else
3059          declare
3060             function Get_Known_Bound (J : Nat) return Node_Id;
3061             --  Returns the lower bound determined by operands J .. NN
3062
3063             ---------------------
3064             -- Get_Known_Bound --
3065             ---------------------
3066
3067             function Get_Known_Bound (J : Nat) return Node_Id is
3068             begin
3069                if Is_Fixed_Length (J) or else J = NN then
3070                   return New_Copy (Opnd_Low_Bound (J));
3071
3072                else
3073                   return
3074                     Make_Conditional_Expression (Loc,
3075                       Expressions => New_List (
3076
3077                         Make_Op_Ne (Loc,
3078                           Left_Opnd  => New_Reference_To (Var_Length (J), Loc),
3079                           Right_Opnd => Make_Integer_Literal (Loc, 0)),
3080
3081                         New_Copy (Opnd_Low_Bound (J)),
3082                         Get_Known_Bound (J + 1)));
3083                end if;
3084             end Get_Known_Bound;
3085
3086          begin
3087             Ent := Make_Temporary (Loc, 'L');
3088
3089             Append_To (Actions,
3090               Make_Object_Declaration (Loc,
3091                 Defining_Identifier => Ent,
3092                 Constant_Present    => True,
3093                 Object_Definition   => New_Occurrence_Of (Ityp, Loc),
3094                 Expression          => Get_Known_Bound (1)));
3095
3096             Low_Bound := New_Reference_To (Ent, Loc);
3097          end;
3098       end if;
3099
3100       --  Now we can safely compute the upper bound, normally
3101       --  Low_Bound + Length - 1.
3102
3103       High_Bound :=
3104         To_Ityp (
3105           Make_Op_Add (Loc,
3106             Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
3107             Right_Opnd =>
3108               Make_Op_Subtract (Loc,
3109                 Left_Opnd  => New_Copy (Aggr_Length (NN)),
3110                 Right_Opnd => Make_Artyp_Literal (1))));
3111
3112       --  Note that calculation of the high bound may cause overflow in some
3113       --  very weird cases, so in the general case we need an overflow check on
3114       --  the high bound. We can avoid this for the common case of string types
3115       --  and other types whose index is Positive, since we chose a wider range
3116       --  for the arithmetic type.
3117
3118       if Istyp /= Standard_Positive then
3119          Activate_Overflow_Check (High_Bound);
3120       end if;
3121
3122       --  Handle the exceptional case where the result is null, in which case
3123       --  case the bounds come from the last operand (so that we get the proper
3124       --  bounds if the last operand is super-flat).
3125
3126       if Result_May_Be_Null then
3127          High_Bound :=
3128            Make_Conditional_Expression (Loc,
3129              Expressions => New_List (
3130                Make_Op_Eq (Loc,
3131                  Left_Opnd  => New_Copy (Aggr_Length (NN)),
3132                  Right_Opnd => Make_Artyp_Literal (0)),
3133                Last_Opnd_High_Bound,
3134                High_Bound));
3135       end if;
3136
3137       --  Here is where we insert the saved up actions
3138
3139       Insert_Actions (Cnode, Actions, Suppress => All_Checks);
3140
3141       --  Now we construct an array object with appropriate bounds. We mark
3142       --  the target as internal to prevent useless initialization when
3143       --  Initialize_Scalars is enabled. Also since this is the actual result
3144       --  entity, we make sure we have debug information for the result.
3145
3146       Ent := Make_Temporary (Loc, 'S');
3147       Set_Is_Internal (Ent);
3148       Set_Needs_Debug_Info (Ent);
3149
3150       --  If the bound is statically known to be out of range, we do not want
3151       --  to abort, we want a warning and a runtime constraint error. Note that
3152       --  we have arranged that the result will not be treated as a static
3153       --  constant, so we won't get an illegality during this insertion.
3154
3155       Insert_Action (Cnode,
3156         Make_Object_Declaration (Loc,
3157           Defining_Identifier => Ent,
3158           Object_Definition   =>
3159             Make_Subtype_Indication (Loc,
3160               Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
3161               Constraint   =>
3162                 Make_Index_Or_Discriminant_Constraint (Loc,
3163                   Constraints => New_List (
3164                     Make_Range (Loc,
3165                       Low_Bound  => Low_Bound,
3166                       High_Bound => High_Bound))))),
3167         Suppress => All_Checks);
3168
3169       --  If the result of the concatenation appears as the initializing
3170       --  expression of an object declaration, we can just rename the
3171       --  result, rather than copying it.
3172
3173       Set_OK_To_Rename (Ent);
3174
3175       --  Catch the static out of range case now
3176
3177       if Raises_Constraint_Error (High_Bound) then
3178          raise Concatenation_Error;
3179       end if;
3180
3181       --  Now we will generate the assignments to do the actual concatenation
3182
3183       --  There is one case in which we will not do this, namely when all the
3184       --  following conditions are met:
3185
3186       --    The result type is Standard.String
3187
3188       --    There are nine or fewer retained (non-null) operands
3189
3190       --    The optimization level is -O0
3191
3192       --    The corresponding System.Concat_n.Str_Concat_n routine is
3193       --    available in the run time.
3194
3195       --    The debug flag gnatd.c is not set
3196
3197       --  If all these conditions are met then we generate a call to the
3198       --  relevant concatenation routine. The purpose of this is to avoid
3199       --  undesirable code bloat at -O0.
3200
3201       if Atyp = Standard_String
3202         and then NN in 2 .. 9
3203         and then (Opt.Optimization_Level = 0 or else Debug_Flag_Dot_CC)
3204         and then not Debug_Flag_Dot_C
3205       then
3206          declare
3207             RR : constant array (Nat range 2 .. 9) of RE_Id :=
3208                    (RE_Str_Concat_2,
3209                     RE_Str_Concat_3,
3210                     RE_Str_Concat_4,
3211                     RE_Str_Concat_5,
3212                     RE_Str_Concat_6,
3213                     RE_Str_Concat_7,
3214                     RE_Str_Concat_8,
3215                     RE_Str_Concat_9);
3216
3217          begin
3218             if RTE_Available (RR (NN)) then
3219                declare
3220                   Opnds : constant List_Id :=
3221                             New_List (New_Occurrence_Of (Ent, Loc));
3222
3223                begin
3224                   for J in 1 .. NN loop
3225                      if Is_List_Member (Operands (J)) then
3226                         Remove (Operands (J));
3227                      end if;
3228
3229                      if Base_Type (Etype (Operands (J))) = Ctyp then
3230                         Append_To (Opnds,
3231                           Make_Aggregate (Loc,
3232                             Component_Associations => New_List (
3233                               Make_Component_Association (Loc,
3234                                 Choices => New_List (
3235                                   Make_Integer_Literal (Loc, 1)),
3236                                 Expression => Operands (J)))));
3237
3238                      else
3239                         Append_To (Opnds, Operands (J));
3240                      end if;
3241                   end loop;
3242
3243                   Insert_Action (Cnode,
3244                     Make_Procedure_Call_Statement (Loc,
3245                       Name => New_Reference_To (RTE (RR (NN)), Loc),
3246                       Parameter_Associations => Opnds));
3247
3248                   Result := New_Reference_To (Ent, Loc);
3249                   goto Done;
3250                end;
3251             end if;
3252          end;
3253       end if;
3254
3255       --  Not special case so generate the assignments
3256
3257       Known_Non_Null_Operand_Seen := False;
3258
3259       for J in 1 .. NN loop
3260          declare
3261             Lo : constant Node_Id :=
3262                    Make_Op_Add (Loc,
3263                      Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
3264                      Right_Opnd => Aggr_Length (J - 1));
3265
3266             Hi : constant Node_Id :=
3267                    Make_Op_Add (Loc,
3268                      Left_Opnd  => To_Artyp (New_Copy (Low_Bound)),
3269                      Right_Opnd =>
3270                        Make_Op_Subtract (Loc,
3271                          Left_Opnd  => Aggr_Length (J),
3272                          Right_Opnd => Make_Artyp_Literal (1)));
3273
3274          begin
3275             --  Singleton case, simple assignment
3276
3277             if Base_Type (Etype (Operands (J))) = Ctyp then
3278                Known_Non_Null_Operand_Seen := True;
3279                Insert_Action (Cnode,
3280                  Make_Assignment_Statement (Loc,
3281                    Name       =>
3282                      Make_Indexed_Component (Loc,
3283                        Prefix      => New_Occurrence_Of (Ent, Loc),
3284                        Expressions => New_List (To_Ityp (Lo))),
3285                    Expression => Operands (J)),
3286                  Suppress => All_Checks);
3287
3288             --  Array case, slice assignment, skipped when argument is fixed
3289             --  length and known to be null.
3290
3291             elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
3292                declare
3293                   Assign : Node_Id :=
3294                              Make_Assignment_Statement (Loc,
3295                                Name       =>
3296                                  Make_Slice (Loc,
3297                                    Prefix         =>
3298                                      New_Occurrence_Of (Ent, Loc),
3299                                    Discrete_Range =>
3300                                      Make_Range (Loc,
3301                                        Low_Bound  => To_Ityp (Lo),
3302                                        High_Bound => To_Ityp (Hi))),
3303                                Expression => Operands (J));
3304                begin
3305                   if Is_Fixed_Length (J) then
3306                      Known_Non_Null_Operand_Seen := True;
3307
3308                   elsif not Known_Non_Null_Operand_Seen then
3309
3310                      --  Here if operand length is not statically known and no
3311                      --  operand known to be non-null has been processed yet.
3312                      --  If operand length is 0, we do not need to perform the
3313                      --  assignment, and we must avoid the evaluation of the
3314                      --  high bound of the slice, since it may underflow if the
3315                      --  low bound is Ityp'First.
3316
3317                      Assign :=
3318                        Make_Implicit_If_Statement (Cnode,
3319                          Condition       =>
3320                            Make_Op_Ne (Loc,
3321                              Left_Opnd  =>
3322                                New_Occurrence_Of (Var_Length (J), Loc),
3323                              Right_Opnd => Make_Integer_Literal (Loc, 0)),
3324                          Then_Statements => New_List (Assign));
3325                   end if;
3326
3327                   Insert_Action (Cnode, Assign, Suppress => All_Checks);
3328                end;
3329             end if;
3330          end;
3331       end loop;
3332
3333       --  Finally we build the result, which is a reference to the array object
3334
3335       Result := New_Reference_To (Ent, Loc);
3336
3337    <<Done>>
3338       Rewrite (Cnode, Result);
3339       Analyze_And_Resolve (Cnode, Atyp);
3340
3341    exception
3342       when Concatenation_Error =>
3343
3344          --  Kill warning generated for the declaration of the static out of
3345          --  range high bound, and instead generate a Constraint_Error with
3346          --  an appropriate specific message.
3347
3348          Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3349          Apply_Compile_Time_Constraint_Error
3350            (N      => Cnode,
3351             Msg    => "concatenation result upper bound out of range?",
3352             Reason => CE_Range_Check_Failed);
3353          --  Set_Etype (Cnode, Atyp);
3354    end Expand_Concatenate;
3355
3356    ------------------------
3357    -- Expand_N_Allocator --
3358    ------------------------
3359
3360    procedure Expand_N_Allocator (N : Node_Id) is
3361       PtrT  : constant Entity_Id  := Etype (N);
3362       Dtyp  : constant Entity_Id  := Available_View (Designated_Type (PtrT));
3363       Etyp  : constant Entity_Id  := Etype (Expression (N));
3364       Loc   : constant Source_Ptr := Sloc (N);
3365       Desig : Entity_Id;
3366       Nod   : Node_Id;
3367       Pool  : Entity_Id;
3368       Temp  : Entity_Id;
3369
3370       procedure Rewrite_Coextension (N : Node_Id);
3371       --  Static coextensions have the same lifetime as the entity they
3372       --  constrain. Such occurrences can be rewritten as aliased objects
3373       --  and their unrestricted access used instead of the coextension.
3374
3375       function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
3376       --  Given a constrained array type E, returns a node representing the
3377       --  code to compute the size in storage elements for the given type.
3378       --  This is done without using the attribute (which malfunctions for
3379       --  large sizes ???)
3380
3381       -------------------------
3382       -- Rewrite_Coextension --
3383       -------------------------
3384
3385       procedure Rewrite_Coextension (N : Node_Id) is
3386          Temp_Id    : constant Node_Id := Make_Temporary (Loc, 'C');
3387          Temp_Decl  : Node_Id;
3388          Insert_Nod : Node_Id;
3389
3390       begin
3391          --  Generate:
3392          --    Cnn : aliased Etyp;
3393
3394          Temp_Decl :=
3395            Make_Object_Declaration (Loc,
3396              Defining_Identifier => Temp_Id,
3397              Aliased_Present     => True,
3398              Object_Definition   => New_Occurrence_Of (Etyp, Loc));
3399
3400          if Nkind (Expression (N)) = N_Qualified_Expression then
3401             Set_Expression (Temp_Decl, Expression (Expression (N)));
3402          end if;
3403
3404          --  Find the proper insertion node for the declaration
3405
3406          Insert_Nod := Parent (N);
3407          while Present (Insert_Nod) loop
3408             exit when
3409               Nkind (Insert_Nod) in N_Statement_Other_Than_Procedure_Call
3410                 or else Nkind (Insert_Nod) = N_Procedure_Call_Statement
3411                 or else Nkind (Insert_Nod) in N_Declaration;
3412
3413             Insert_Nod := Parent (Insert_Nod);
3414          end loop;
3415
3416          Insert_Before (Insert_Nod, Temp_Decl);
3417          Analyze (Temp_Decl);
3418
3419          Rewrite (N,
3420            Make_Attribute_Reference (Loc,
3421              Prefix         => New_Occurrence_Of (Temp_Id, Loc),
3422              Attribute_Name => Name_Unrestricted_Access));
3423
3424          Analyze_And_Resolve (N, PtrT);
3425       end Rewrite_Coextension;
3426
3427       ------------------------------
3428       -- Size_In_Storage_Elements --
3429       ------------------------------
3430
3431       function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
3432       begin
3433          --  Logically this just returns E'Max_Size_In_Storage_Elements.
3434          --  However, the reason for the existence of this function is
3435          --  to construct a test for sizes too large, which means near the
3436          --  32-bit limit on a 32-bit machine, and precisely the trouble
3437          --  is that we get overflows when sizes are greater than 2**31.
3438
3439          --  So what we end up doing for array types is to use the expression:
3440
3441          --    number-of-elements * component_type'Max_Size_In_Storage_Elements
3442
3443          --  which avoids this problem. All this is a bit bogus, but it does
3444          --  mean we catch common cases of trying to allocate arrays that
3445          --  are too large, and which in the absence of a check results in
3446          --  undetected chaos ???
3447
3448          declare
3449             Len : Node_Id;
3450             Res : Node_Id;
3451
3452          begin
3453             for J in 1 .. Number_Dimensions (E) loop
3454                Len :=
3455                  Make_Attribute_Reference (Loc,
3456                    Prefix         => New_Occurrence_Of (E, Loc),
3457                    Attribute_Name => Name_Length,
3458                    Expressions    => New_List (Make_Integer_Literal (Loc, J)));
3459
3460                if J = 1 then
3461                   Res := Len;
3462
3463                else
3464                   Res :=
3465                     Make_Op_Multiply (Loc,
3466                       Left_Opnd  => Res,
3467                       Right_Opnd => Len);
3468                end if;
3469             end loop;
3470
3471             return
3472               Make_Op_Multiply (Loc,
3473                 Left_Opnd  => Len,
3474                 Right_Opnd =>
3475                   Make_Attribute_Reference (Loc,
3476                     Prefix => New_Occurrence_Of (Component_Type (E), Loc),
3477                     Attribute_Name => Name_Max_Size_In_Storage_Elements));
3478          end;
3479       end Size_In_Storage_Elements;
3480
3481    --  Start of processing for Expand_N_Allocator
3482
3483    begin
3484       --  RM E.2.3(22). We enforce that the expected type of an allocator
3485       --  shall not be a remote access-to-class-wide-limited-private type
3486
3487       --  Why is this being done at expansion time, seems clearly wrong ???
3488
3489       Validate_Remote_Access_To_Class_Wide_Type (N);
3490
3491       --  Processing for anonymous access-to-controlled types. These access
3492       --  types receive a special finalization master which appears in the
3493       --  declarations of the enclosing semantic unit. This expansion is done
3494       --  now to ensure that any additional types generated by this routine
3495       --  or Expand_Allocator_Expression inherit the proper type attributes.
3496
3497       if Ekind (PtrT) = E_Anonymous_Access_Type
3498         and then Needs_Finalization (Dtyp)
3499       then
3500          --  Anonymous access-to-controlled types allocate on the global pool.
3501          --  Do not set this attribute on .NET/JVM since those targets do not
3502          --  support pools.
3503
3504          if No (Associated_Storage_Pool (PtrT))
3505            and then VM_Target = No_VM
3506          then
3507             Set_Associated_Storage_Pool
3508               (PtrT, Get_Global_Pool_For_Access_Type (PtrT));
3509          end if;
3510
3511          --  The finalization master must be inserted and analyzed as part of
3512          --  the current semantic unit. This form of expansion is not carried
3513          --  out in Alfa mode because it is useless. Note that the master is
3514          --  updated when analysis changes current units.
3515
3516          if not Alfa_Mode then
3517             Set_Finalization_Master (PtrT, Current_Anonymous_Master);
3518          end if;
3519       end if;
3520
3521       --  Set the storage pool and find the appropriate version of Allocate to
3522       --  call. Do not overwrite the storage pool if it is already set, which
3523       --  can happen for build-in-place function returns (see
3524       --  Exp_Ch4.Expand_N_Extended_Return_Statement).
3525
3526       if No (Storage_Pool (N)) then
3527          Pool := Associated_Storage_Pool (Root_Type (PtrT));
3528
3529          if Present (Pool) then
3530             Set_Storage_Pool (N, Pool);
3531
3532             if Is_RTE (Pool, RE_SS_Pool) then
3533                if VM_Target = No_VM then
3534                   Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
3535                end if;
3536
3537             elsif Is_Class_Wide_Type (Etype (Pool)) then
3538                Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
3539
3540             else
3541                Set_Procedure_To_Call (N,
3542                  Find_Prim_Op (Etype (Pool), Name_Allocate));
3543             end if;
3544          end if;
3545       end if;
3546
3547       --  Under certain circumstances we can replace an allocator by an access
3548       --  to statically allocated storage. The conditions, as noted in AARM
3549       --  3.10 (10c) are as follows:
3550
3551       --    Size and initial value is known at compile time
3552       --    Access type is access-to-constant
3553
3554       --  The allocator is not part of a constraint on a record component,
3555       --  because in that case the inserted actions are delayed until the
3556       --  record declaration is fully analyzed, which is too late for the
3557       --  analysis of the rewritten allocator.
3558
3559       if Is_Access_Constant (PtrT)
3560         and then Nkind (Expression (N)) = N_Qualified_Expression
3561         and then Compile_Time_Known_Value (Expression (Expression (N)))
3562         and then Size_Known_At_Compile_Time
3563                    (Etype (Expression (Expression (N))))
3564         and then not Is_Record_Type (Current_Scope)
3565       then
3566          --  Here we can do the optimization. For the allocator
3567
3568          --    new x'(y)
3569
3570          --  We insert an object declaration
3571
3572          --    Tnn : aliased x := y;
3573
3574          --  and replace the allocator by Tnn'Unrestricted_Access. Tnn is
3575          --  marked as requiring static allocation.
3576
3577          Temp  := Make_Temporary (Loc, 'T', Expression (Expression (N)));
3578          Desig := Subtype_Mark (Expression (N));
3579
3580          --  If context is constrained, use constrained subtype directly,
3581          --  so that the constant is not labelled as having a nominally
3582          --  unconstrained subtype.
3583
3584          if Entity (Desig) = Base_Type (Dtyp) then
3585             Desig := New_Occurrence_Of (Dtyp, Loc);
3586          end if;
3587
3588          Insert_Action (N,
3589            Make_Object_Declaration (Loc,
3590              Defining_Identifier => Temp,
3591              Aliased_Present     => True,
3592              Constant_Present    => Is_Access_Constant (PtrT),
3593              Object_Definition   => Desig,
3594              Expression          => Expression (Expression (N))));
3595
3596          Rewrite (N,
3597            Make_Attribute_Reference (Loc,
3598              Prefix         => New_Occurrence_Of (Temp, Loc),
3599              Attribute_Name => Name_Unrestricted_Access));
3600
3601          Analyze_And_Resolve (N, PtrT);
3602
3603          --  We set the variable as statically allocated, since we don't want
3604          --  it going on the stack of the current procedure!
3605
3606          Set_Is_Statically_Allocated (Temp);
3607          return;
3608       end if;
3609
3610       --  Same if the allocator is an access discriminant for a local object:
3611       --  instead of an allocator we create a local value and constrain the
3612       --  enclosing object with the corresponding access attribute.
3613
3614       if Is_Static_Coextension (N) then
3615          Rewrite_Coextension (N);
3616          return;
3617       end if;
3618
3619       --  Check for size too large, we do this because the back end misses
3620       --  proper checks here and can generate rubbish allocation calls when
3621       --  we are near the limit. We only do this for the 32-bit address case
3622       --  since that is from a practical point of view where we see a problem.
3623
3624       if System_Address_Size = 32
3625         and then not Storage_Checks_Suppressed (PtrT)
3626         and then not Storage_Checks_Suppressed (Dtyp)
3627         and then not Storage_Checks_Suppressed (Etyp)
3628       then
3629          --  The check we want to generate should look like
3630
3631          --  if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
3632          --    raise Storage_Error;
3633          --  end if;
3634
3635          --  where 3.5 gigabytes is a constant large enough to accommodate any
3636          --  reasonable request for. But we can't do it this way because at
3637          --  least at the moment we don't compute this attribute right, and
3638          --  can silently give wrong results when the result gets large. Since
3639          --  this is all about large results, that's bad, so instead we only
3640          --  apply the check for constrained arrays, and manually compute the
3641          --  value of the attribute ???
3642
3643          if Is_Array_Type (Etyp) and then Is_Constrained (Etyp) then
3644             Insert_Action (N,
3645               Make_Raise_Storage_Error (Loc,
3646                 Condition =>
3647                   Make_Op_Gt (Loc,
3648                     Left_Opnd  => Size_In_Storage_Elements (Etyp),
3649                     Right_Opnd =>
3650                       Make_Integer_Literal (Loc, Uint_7 * (Uint_2 ** 29))),
3651                 Reason    => SE_Object_Too_Large));
3652          end if;
3653       end if;
3654
3655       --  Handle case of qualified expression (other than optimization above)
3656       --  First apply constraint checks, because the bounds or discriminants
3657       --  in the aggregate might not match the subtype mark in the allocator.
3658
3659       if Nkind (Expression (N)) = N_Qualified_Expression then
3660          Apply_Constraint_Check
3661            (Expression (Expression (N)), Etype (Expression (N)));
3662
3663          Expand_Allocator_Expression (N);
3664          return;
3665       end if;
3666
3667       --  If the allocator is for a type which requires initialization, and
3668       --  there is no initial value (i.e. operand is a subtype indication
3669       --  rather than a qualified expression), then we must generate a call to
3670       --  the initialization routine using an expressions action node:
3671
3672       --     [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
3673
3674       --  Here ptr_T is the pointer type for the allocator, and T is the
3675       --  subtype of the allocator. A special case arises if the designated
3676       --  type of the access type is a task or contains tasks. In this case
3677       --  the call to Init (Temp.all ...) is replaced by code that ensures
3678       --  that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
3679       --  for details). In addition, if the type T is a task T, then the
3680       --  first argument to Init must be converted to the task record type.
3681
3682       declare
3683          T         : constant Entity_Id := Entity (Expression (N));
3684          Args      : List_Id;
3685          Decls     : List_Id;
3686          Decl      : Node_Id;
3687          Discr     : Elmt_Id;
3688          Init      : Entity_Id;
3689          Init_Arg1 : Node_Id;
3690          Temp_Decl : Node_Id;
3691          Temp_Type : Entity_Id;
3692
3693       begin
3694          if No_Initialization (N) then
3695
3696             --  Even though this might be a simple allocation, create a custom
3697             --  Allocate if the context requires it. Since .NET/JVM compilers
3698             --  do not support pools, this step is skipped.
3699
3700             if VM_Target = No_VM
3701               and then Present (Finalization_Master (PtrT))
3702             then
3703                Build_Allocate_Deallocate_Proc
3704                  (N           => N,
3705                   Is_Allocate => True);
3706             end if;
3707
3708          --  Case of no initialization procedure present
3709
3710          elsif not Has_Non_Null_Base_Init_Proc (T) then
3711
3712             --  Case of simple initialization required
3713
3714             if Needs_Simple_Initialization (T) then
3715                Check_Restriction (No_Default_Initialization, N);
3716                Rewrite (Expression (N),
3717                  Make_Qualified_Expression (Loc,
3718                    Subtype_Mark => New_Occurrence_Of (T, Loc),
3719                    Expression   => Get_Simple_Init_Val (T, N)));
3720
3721                Analyze_And_Resolve (Expression (Expression (N)), T);
3722                Analyze_And_Resolve (Expression (N), T);
3723                Set_Paren_Count     (Expression (Expression (N)), 1);
3724                Expand_N_Allocator  (N);
3725
3726             --  No initialization required
3727
3728             else
3729                null;
3730             end if;
3731
3732          --  Case of initialization procedure present, must be called
3733
3734          else
3735             Check_Restriction (No_Default_Initialization, N);
3736
3737             if not Restriction_Active (No_Default_Initialization) then
3738                Init := Base_Init_Proc (T);
3739                Nod  := N;
3740                Temp := Make_Temporary (Loc, 'P');
3741
3742                --  Construct argument list for the initialization routine call
3743
3744                Init_Arg1 :=
3745                  Make_Explicit_Dereference (Loc,
3746                    Prefix =>
3747                      New_Reference_To (Temp, Loc));
3748
3749                Set_Assignment_OK (Init_Arg1);
3750                Temp_Type := PtrT;
3751
3752                --  The initialization procedure expects a specific type. if the
3753                --  context is access to class wide, indicate that the object
3754                --  being allocated has the right specific type.
3755
3756                if Is_Class_Wide_Type (Dtyp) then
3757                   Init_Arg1 := Unchecked_Convert_To (T, Init_Arg1);
3758                end if;
3759
3760                --  If designated type is a concurrent type or if it is private
3761                --  type whose definition is a concurrent type, the first
3762                --  argument in the Init routine has to be unchecked conversion
3763                --  to the corresponding record type. If the designated type is
3764                --  a derived type, also convert the argument to its root type.
3765
3766                if Is_Concurrent_Type (T) then
3767                   Init_Arg1 :=
3768                     Unchecked_Convert_To (
3769                       Corresponding_Record_Type (T), Init_Arg1);
3770
3771                elsif Is_Private_Type (T)
3772                  and then Present (Full_View (T))
3773                  and then Is_Concurrent_Type (Full_View (T))
3774                then
3775                   Init_Arg1 :=
3776                     Unchecked_Convert_To
3777                       (Corresponding_Record_Type (Full_View (T)), Init_Arg1);
3778
3779                elsif Etype (First_Formal (Init)) /= Base_Type (T) then
3780                   declare
3781                      Ftyp : constant Entity_Id := Etype (First_Formal (Init));
3782
3783                   begin
3784                      Init_Arg1 := OK_Convert_To (Etype (Ftyp), Init_Arg1);
3785                      Set_Etype (Init_Arg1, Ftyp);
3786                   end;
3787                end if;
3788
3789                Args := New_List (Init_Arg1);
3790
3791                --  For the task case, pass the Master_Id of the access type as
3792                --  the value of the _Master parameter, and _Chain as the value
3793                --  of the _Chain parameter (_Chain will be defined as part of
3794                --  the generated code for the allocator).
3795
3796                --  In Ada 2005, the context may be a function that returns an
3797                --  anonymous access type. In that case the Master_Id has been
3798                --  created when expanding the function declaration.
3799
3800                if Has_Task (T) then
3801                   if No (Master_Id (Base_Type (PtrT))) then
3802
3803                      --  The designated type was an incomplete type, and the
3804                      --  access type did not get expanded. Salvage it now.
3805
3806                      if not Restriction_Active (No_Task_Hierarchy) then
3807                         pragma Assert (Present (Parent (Base_Type (PtrT))));
3808                         Expand_N_Full_Type_Declaration
3809                           (Parent (Base_Type (PtrT)));
3810                      end if;
3811                   end if;
3812
3813                   --  If the context of the allocator is a declaration or an
3814                   --  assignment, we can generate a meaningful image for it,
3815                   --  even though subsequent assignments might remove the
3816                   --  connection between task and entity. We build this image
3817                   --  when the left-hand side is a simple variable, a simple
3818                   --  indexed assignment or a simple selected component.
3819
3820                   if Nkind (Parent (N)) = N_Assignment_Statement then
3821                      declare
3822                         Nam : constant Node_Id := Name (Parent (N));
3823
3824                      begin
3825                         if Is_Entity_Name (Nam) then
3826                            Decls :=
3827                              Build_Task_Image_Decls
3828                                (Loc,
3829                                 New_Occurrence_Of
3830                                   (Entity (Nam), Sloc (Nam)), T);
3831
3832                         elsif Nkind_In (Nam, N_Indexed_Component,
3833                                              N_Selected_Component)
3834                           and then Is_Entity_Name (Prefix (Nam))
3835                         then
3836                            Decls :=
3837                              Build_Task_Image_Decls
3838                                (Loc, Nam, Etype (Prefix (Nam)));
3839                         else
3840                            Decls := Build_Task_Image_Decls (Loc, T, T);
3841                         end if;
3842                      end;
3843
3844                   elsif Nkind (Parent (N)) = N_Object_Declaration then
3845                      Decls :=
3846                        Build_Task_Image_Decls
3847                          (Loc, Defining_Identifier (Parent (N)), T);
3848
3849                   else
3850                      Decls := Build_Task_Image_Decls (Loc, T, T);
3851                   end if;
3852
3853                   if Restriction_Active (No_Task_Hierarchy) then
3854                      Append_To (Args,
3855                        New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
3856                   else
3857                      Append_To (Args,
3858                        New_Reference_To
3859                          (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
3860                   end if;
3861
3862                   Append_To (Args, Make_Identifier (Loc, Name_uChain));
3863
3864                   Decl := Last (Decls);
3865                   Append_To (Args,
3866                     New_Occurrence_Of (Defining_Identifier (Decl), Loc));
3867
3868                --  Has_Task is false, Decls not used
3869
3870                else
3871                   Decls := No_List;
3872                end if;
3873
3874                --  Add discriminants if discriminated type
3875
3876                declare
3877                   Dis : Boolean := False;
3878                   Typ : Entity_Id;
3879
3880                begin
3881                   if Has_Discriminants (T) then
3882                      Dis := True;
3883                      Typ := T;
3884
3885                   elsif Is_Private_Type (T)
3886                     and then Present (Full_View (T))
3887                     and then Has_Discriminants (Full_View (T))
3888                   then
3889                      Dis := True;
3890                      Typ := Full_View (T);
3891                   end if;
3892
3893                   if Dis then
3894
3895                      --  If the allocated object will be constrained by the
3896                      --  default values for discriminants, then build a subtype
3897                      --  with those defaults, and change the allocated subtype
3898                      --  to that. Note that this happens in fewer cases in Ada
3899                      --  2005 (AI-363).
3900
3901                      if not Is_Constrained (Typ)
3902                        and then Present (Discriminant_Default_Value
3903                                           (First_Discriminant (Typ)))
3904                        and then (Ada_Version < Ada_2005
3905                                   or else not
3906                                     Effectively_Has_Constrained_Partial_View
3907                                       (Typ  => Typ,
3908                                        Scop => Current_Scope))
3909                      then
3910                         Typ := Build_Default_Subtype (Typ, N);
3911                         Set_Expression (N, New_Reference_To (Typ, Loc));
3912                      end if;
3913
3914                      Discr := First_Elmt (Discriminant_Constraint (Typ));
3915                      while Present (Discr) loop
3916                         Nod := Node (Discr);
3917                         Append (New_Copy_Tree (Node (Discr)), Args);
3918
3919                         --  AI-416: when the discriminant constraint is an
3920                         --  anonymous access type make sure an accessibility
3921                         --  check is inserted if necessary (3.10.2(22.q/2))
3922
3923                         if Ada_Version >= Ada_2005
3924                           and then
3925                             Ekind (Etype (Nod)) = E_Anonymous_Access_Type
3926                         then
3927                            Apply_Accessibility_Check
3928                              (Nod, Typ, Insert_Node => Nod);
3929                         end if;
3930
3931                         Next_Elmt (Discr);
3932                      end loop;
3933                   end if;
3934                end;
3935
3936                --  We set the allocator as analyzed so that when we analyze the
3937                --  expression actions node, we do not get an unwanted recursive
3938                --  expansion of the allocator expression.
3939
3940                Set_Analyzed (N, True);
3941                Nod := Relocate_Node (N);
3942
3943                --  Here is the transformation:
3944                --    input:  new Ctrl_Typ
3945                --    output: Temp : constant Ctrl_Typ_Ptr := new Ctrl_Typ;
3946                --            Ctrl_TypIP (Temp.all, ...);
3947                --            [Deep_]Initialize (Temp.all);
3948
3949                --  Here Ctrl_Typ_Ptr is the pointer type for the allocator, and
3950                --  is the subtype of the allocator.
3951
3952                Temp_Decl :=
3953                  Make_Object_Declaration (Loc,
3954                    Defining_Identifier => Temp,
3955                    Constant_Present    => True,
3956                    Object_Definition   => New_Reference_To (Temp_Type, Loc),
3957                    Expression          => Nod);
3958
3959                Set_Assignment_OK (Temp_Decl);
3960                Insert_Action (N, Temp_Decl, Suppress => All_Checks);
3961
3962                Build_Allocate_Deallocate_Proc (Temp_Decl, True);
3963
3964                --  If the designated type is a task type or contains tasks,
3965                --  create block to activate created tasks, and insert
3966                --  declaration for Task_Image variable ahead of call.
3967
3968                if Has_Task (T) then
3969                   declare
3970                      L   : constant List_Id := New_List;
3971                      Blk : Node_Id;
3972                   begin
3973                      Build_Task_Allocate_Block (L, Nod, Args);
3974                      Blk := Last (L);
3975                      Insert_List_Before (First (Declarations (Blk)), Decls);
3976                      Insert_Actions (N, L);
3977                   end;
3978
3979                else
3980                   Insert_Action (N,
3981                     Make_Procedure_Call_Statement (Loc,
3982                       Name                   => New_Reference_To (Init, Loc),
3983                       Parameter_Associations => Args));
3984                end if;
3985
3986                if Needs_Finalization (T) then
3987
3988                   --  Generate:
3989                   --    [Deep_]Initialize (Init_Arg1);
3990
3991                   Insert_Action (N,
3992                     Make_Init_Call
3993                       (Obj_Ref => New_Copy_Tree (Init_Arg1),
3994                        Typ     => T));
3995
3996                   if Present (Finalization_Master (PtrT)) then
3997
3998                      --  Special processing for .NET/JVM, the allocated object
3999                      --  is attached to the finalization master. Generate:
4000
4001                      --    Attach (<PtrT>FM, Root_Controlled_Ptr (Init_Arg1));
4002
4003                      --  Types derived from [Limited_]Controlled are the only
4004                      --  ones considered since they have fields Prev and Next.
4005
4006                      if VM_Target /= No_VM then
4007                         if Is_Controlled (T) then
4008                            Insert_Action (N,
4009                              Make_Attach_Call
4010                                (Obj_Ref => New_Copy_Tree (Init_Arg1),
4011                                 Ptr_Typ => PtrT));
4012                         end if;
4013
4014                      --  Default case, generate:
4015
4016                      --    Set_Finalize_Address
4017                      --      (<PtrT>FM, <T>FD'Unrestricted_Access);
4018
4019                      --  Do not generate this call in the following cases:
4020                      --
4021                      --    * Alfa mode - the call is useless and results in
4022                      --    unwanted expansion.
4023                      --
4024                      --    * CodePeer mode - TSS primitive Finalize_Address is
4025                      --    not created in this mode.
4026
4027                      elsif not Alfa_Mode
4028                        and then not CodePeer_Mode
4029                      then
4030                         Insert_Action (N,
4031                           Make_Set_Finalize_Address_Call
4032                             (Loc     => Loc,
4033                              Typ     => T,
4034                              Ptr_Typ => PtrT));
4035                      end if;
4036                   end if;
4037                end if;
4038
4039                Rewrite (N, New_Reference_To (Temp, Loc));
4040                Analyze_And_Resolve (N, PtrT);
4041             end if;
4042          end if;
4043       end;
4044
4045       --  Ada 2005 (AI-251): If the allocator is for a class-wide interface
4046       --  object that has been rewritten as a reference, we displace "this"
4047       --  to reference properly its secondary dispatch table.
4048
4049       if Nkind (N) = N_Identifier
4050         and then Is_Interface (Dtyp)
4051       then
4052          Displace_Allocator_Pointer (N);
4053       end if;
4054
4055    exception
4056       when RE_Not_Available =>
4057          return;
4058    end Expand_N_Allocator;
4059
4060    -----------------------
4061    -- Expand_N_And_Then --
4062    -----------------------
4063
4064    procedure Expand_N_And_Then (N : Node_Id)
4065      renames Expand_Short_Circuit_Operator;
4066
4067    ------------------------------
4068    -- Expand_N_Case_Expression --
4069    ------------------------------
4070
4071    procedure Expand_N_Case_Expression (N : Node_Id) is
4072       Loc     : constant Source_Ptr := Sloc (N);
4073       Typ     : constant Entity_Id  := Etype (N);
4074       Cstmt   : Node_Id;
4075       Tnn     : Entity_Id;
4076       Pnn     : Entity_Id;
4077       Actions : List_Id;
4078       Ttyp    : Entity_Id;
4079       Alt     : Node_Id;
4080       Fexp    : Node_Id;
4081
4082    begin
4083       --  We expand
4084
4085       --    case X is when A => AX, when B => BX ...
4086
4087       --  to
4088
4089       --    do
4090       --       Tnn : typ;
4091       --       case X is
4092       --          when A =>
4093       --             Tnn := AX;
4094       --          when B =>
4095       --             Tnn := BX;
4096       --          ...
4097       --       end case;
4098       --    in Tnn end;
4099
4100       --  However, this expansion is wrong for limited types, and also
4101       --  wrong for unconstrained types (since the bounds may not be the
4102       --  same in all branches). Furthermore it involves an extra copy
4103       --  for large objects. So we take care of this by using the following
4104       --  modified expansion for non-scalar types:
4105
4106       --    do
4107       --       type Pnn is access all typ;
4108       --       Tnn : Pnn;
4109       --       case X is
4110       --          when A =>
4111       --             T := AX'Unrestricted_Access;
4112       --          when B =>
4113       --             T := BX'Unrestricted_Access;
4114       --          ...
4115       --       end case;
4116       --    in Tnn.all end;
4117
4118       Cstmt :=
4119         Make_Case_Statement (Loc,
4120           Expression   => Expression (N),
4121           Alternatives => New_List);
4122
4123       Actions := New_List;
4124
4125       --  Scalar case
4126
4127       if Is_Scalar_Type (Typ) then
4128          Ttyp := Typ;
4129
4130       else
4131          Pnn := Make_Temporary (Loc, 'P');
4132          Append_To (Actions,
4133            Make_Full_Type_Declaration (Loc,
4134              Defining_Identifier => Pnn,
4135              Type_Definition =>
4136                Make_Access_To_Object_Definition (Loc,
4137                  All_Present => True,
4138                  Subtype_Indication =>
4139                    New_Reference_To (Typ, Loc))));
4140          Ttyp := Pnn;
4141       end if;
4142
4143       Tnn := Make_Temporary (Loc, 'T');
4144       Append_To (Actions,
4145         Make_Object_Declaration (Loc,
4146           Defining_Identifier => Tnn,
4147           Object_Definition   => New_Occurrence_Of (Ttyp, Loc)));
4148
4149       --  Now process the alternatives
4150
4151       Alt := First (Alternatives (N));
4152       while Present (Alt) loop
4153          declare
4154             Aexp  : Node_Id             := Expression (Alt);
4155             Aloc  : constant Source_Ptr := Sloc (Aexp);
4156             Stats : List_Id;
4157
4158          begin
4159             --  As described above, take Unrestricted_Access for case of non-
4160             --  scalar types, to avoid big copies, and special cases.
4161
4162             if not Is_Scalar_Type (Typ) then
4163                Aexp :=
4164                  Make_Attribute_Reference (Aloc,
4165                    Prefix         => Relocate_Node (Aexp),
4166                    Attribute_Name => Name_Unrestricted_Access);
4167             end if;
4168
4169             Stats := New_List (
4170               Make_Assignment_Statement (Aloc,
4171                 Name       => New_Occurrence_Of (Tnn, Loc),
4172                 Expression => Aexp));
4173
4174             --  Propagate declarations inserted in the node by Insert_Actions
4175             --  (for example, temporaries generated to remove side effects).
4176             --  These actions must remain attached to the alternative, given
4177             --  that they are generated by the corresponding expression.
4178
4179             if Present (Sinfo.Actions (Alt)) then
4180                Prepend_List (Sinfo.Actions (Alt), Stats);
4181             end if;
4182
4183             Append_To
4184               (Alternatives (Cstmt),
4185                Make_Case_Statement_Alternative (Sloc (Alt),
4186                  Discrete_Choices => Discrete_Choices (Alt),
4187                  Statements       => Stats));
4188          end;
4189
4190          Next (Alt);
4191       end loop;
4192
4193       Append_To (Actions, Cstmt);
4194
4195       --  Construct and return final expression with actions
4196
4197       if Is_Scalar_Type (Typ) then
4198          Fexp := New_Occurrence_Of (Tnn, Loc);
4199       else
4200          Fexp :=
4201            Make_Explicit_Dereference (Loc,
4202              Prefix => New_Occurrence_Of (Tnn, Loc));
4203       end if;
4204
4205       Rewrite (N,
4206         Make_Expression_With_Actions (Loc,
4207           Expression => Fexp,
4208           Actions    => Actions));
4209
4210       Analyze_And_Resolve (N, Typ);
4211    end Expand_N_Case_Expression;
4212
4213    -------------------------------------
4214    -- Expand_N_Conditional_Expression --
4215    -------------------------------------
4216
4217    --  Deal with limited types and expression actions
4218
4219    procedure Expand_N_Conditional_Expression (N : Node_Id) is
4220       Loc    : constant Source_Ptr := Sloc (N);
4221       Cond   : constant Node_Id    := First (Expressions (N));
4222       Thenx  : constant Node_Id    := Next (Cond);
4223       Elsex  : constant Node_Id    := Next (Thenx);
4224       Typ    : constant Entity_Id  := Etype (N);
4225
4226       Cnn     : Entity_Id;
4227       Decl    : Node_Id;
4228       New_If  : Node_Id;
4229       New_N   : Node_Id;
4230       P_Decl  : Node_Id;
4231       Expr    : Node_Id;
4232       Actions : List_Id;
4233
4234    begin
4235       --  Fold at compile time if condition known. We have already folded
4236       --  static conditional expressions, but it is possible to fold any
4237       --  case in which the condition is known at compile time, even though
4238       --  the result is non-static.
4239
4240       --  Note that we don't do the fold of such cases in Sem_Elab because
4241       --  it can cause infinite loops with the expander adding a conditional
4242       --  expression, and Sem_Elab circuitry removing it repeatedly.
4243
4244       if Compile_Time_Known_Value (Cond) then
4245          if Is_True (Expr_Value (Cond)) then
4246             Expr := Thenx;
4247             Actions := Then_Actions (N);
4248          else
4249             Expr := Elsex;
4250             Actions := Else_Actions (N);
4251          end if;
4252
4253          Remove (Expr);
4254
4255          if Present (Actions) then
4256
4257             --  If we are not allowed to use Expression_With_Actions, just skip
4258             --  the optimization, it is not critical for correctness.
4259
4260             if not Use_Expression_With_Actions then
4261                goto Skip_Optimization;
4262             end if;
4263
4264             Rewrite (N,
4265               Make_Expression_With_Actions (Loc,
4266                 Expression => Relocate_Node (Expr),
4267                 Actions    => Actions));
4268             Analyze_And_Resolve (N, Typ);
4269
4270          else
4271             Rewrite (N, Relocate_Node (Expr));
4272          end if;
4273
4274          --  Note that the result is never static (legitimate cases of static
4275          --  conditional expressions were folded in Sem_Eval).
4276
4277          Set_Is_Static_Expression (N, False);
4278          return;
4279       end if;
4280
4281       <<Skip_Optimization>>
4282
4283       --  If the type is limited or unconstrained, we expand as follows to
4284       --  avoid any possibility of improper copies.
4285
4286       --  Note: it may be possible to avoid this special processing if the
4287       --  back end uses its own mechanisms for handling by-reference types ???
4288
4289       --      type Ptr is access all Typ;
4290       --      Cnn : Ptr;
4291       --      if cond then
4292       --         <<then actions>>
4293       --         Cnn := then-expr'Unrestricted_Access;
4294       --      else
4295       --         <<else actions>>
4296       --         Cnn := else-expr'Unrestricted_Access;
4297       --      end if;
4298
4299       --  and replace the conditional expression by a reference to Cnn.all.
4300
4301       --  This special case can be skipped if the back end handles limited
4302       --  types properly and ensures that no incorrect copies are made.
4303
4304       if Is_By_Reference_Type (Typ)
4305         and then not Back_End_Handles_Limited_Types
4306       then
4307          Cnn := Make_Temporary (Loc, 'C', N);
4308
4309          P_Decl :=
4310            Make_Full_Type_Declaration (Loc,
4311              Defining_Identifier =>
4312                Make_Temporary (Loc, 'A'),
4313              Type_Definition =>
4314                Make_Access_To_Object_Definition (Loc,
4315                  All_Present        => True,
4316                  Subtype_Indication => New_Reference_To (Typ, Loc)));
4317
4318          Insert_Action (N, P_Decl);
4319
4320          Decl :=
4321             Make_Object_Declaration (Loc,
4322               Defining_Identifier => Cnn,
4323               Object_Definition   =>
4324                    New_Occurrence_Of (Defining_Identifier (P_Decl), Loc));
4325
4326          New_If :=
4327            Make_Implicit_If_Statement (N,
4328              Condition => Relocate_Node (Cond),
4329
4330              Then_Statements => New_List (
4331                Make_Assignment_Statement (Sloc (Thenx),
4332                  Name       => New_Occurrence_Of (Cnn, Sloc (Thenx)),
4333                  Expression =>
4334                    Make_Attribute_Reference (Loc,
4335                      Attribute_Name => Name_Unrestricted_Access,
4336                      Prefix         =>  Relocate_Node (Thenx)))),
4337
4338              Else_Statements => New_List (
4339                Make_Assignment_Statement (Sloc (Elsex),
4340                  Name       => New_Occurrence_Of (Cnn, Sloc (Elsex)),
4341                  Expression =>
4342                    Make_Attribute_Reference (Loc,
4343                      Attribute_Name => Name_Unrestricted_Access,
4344                      Prefix         => Relocate_Node (Elsex)))));
4345
4346          New_N :=
4347            Make_Explicit_Dereference (Loc,
4348              Prefix => New_Occurrence_Of (Cnn, Loc));
4349
4350       --  For other types, we only need to expand if there are other actions
4351       --  associated with either branch.
4352
4353       elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
4354
4355          --  We have two approaches to handling this. If we are allowed to use
4356          --  N_Expression_With_Actions, then we can just wrap the actions into
4357          --  the appropriate expression.
4358
4359          if Use_Expression_With_Actions then
4360             if Present (Then_Actions (N)) then
4361                Rewrite (Thenx,
4362                  Make_Expression_With_Actions (Sloc (Thenx),
4363                    Actions    => Then_Actions (N),
4364                    Expression => Relocate_Node (Thenx)));
4365                Set_Then_Actions (N, No_List);
4366                Analyze_And_Resolve (Thenx, Typ);
4367             end if;
4368
4369             if Present (Else_Actions (N)) then
4370                Rewrite (Elsex,
4371                  Make_Expression_With_Actions (Sloc (Elsex),
4372                    Actions    => Else_Actions (N),
4373                    Expression => Relocate_Node (Elsex)));
4374                Set_Else_Actions (N, No_List);
4375                Analyze_And_Resolve (Elsex, Typ);
4376             end if;
4377
4378             return;
4379
4380             --  if we can't use N_Expression_With_Actions nodes, then we insert
4381             --  the following sequence of actions (using Insert_Actions):
4382
4383             --      Cnn : typ;
4384             --      if cond then
4385             --         <<then actions>>
4386             --         Cnn := then-expr;
4387             --      else
4388             --         <<else actions>>
4389             --         Cnn := else-expr
4390             --      end if;
4391
4392             --  and replace the conditional expression by a reference to Cnn
4393
4394          else
4395             Cnn := Make_Temporary (Loc, 'C', N);
4396
4397             Decl :=
4398               Make_Object_Declaration (Loc,
4399                 Defining_Identifier => Cnn,
4400                 Object_Definition   => New_Occurrence_Of (Typ, Loc));
4401
4402             New_If :=
4403               Make_Implicit_If_Statement (N,
4404                 Condition       => Relocate_Node (Cond),
4405
4406                 Then_Statements => New_List (
4407                   Make_Assignment_Statement (Sloc (Thenx),
4408                     Name       => New_Occurrence_Of (Cnn, Sloc (Thenx)),
4409                     Expression => Relocate_Node (Thenx))),
4410
4411                 Else_Statements => New_List (
4412                   Make_Assignment_Statement (Sloc (Elsex),
4413                     Name       => New_Occurrence_Of (Cnn, Sloc (Elsex)),
4414                     Expression => Relocate_Node (Elsex))));
4415
4416             Set_Assignment_OK (Name (First (Then_Statements (New_If))));
4417             Set_Assignment_OK (Name (First (Else_Statements (New_If))));
4418
4419             New_N := New_Occurrence_Of (Cnn, Loc);
4420          end if;
4421
4422          --  If no actions then no expansion needed, gigi will handle it using
4423          --  the same approach as a C conditional expression.
4424
4425       else
4426          return;
4427       end if;
4428
4429       --  Fall through here for either the limited expansion, or the case of
4430       --  inserting actions for non-limited types. In both these cases, we must
4431       --  move the SLOC of the parent If statement to the newly created one and
4432       --  change it to the SLOC of the expression which, after expansion, will
4433       --  correspond to what is being evaluated.
4434
4435       if Present (Parent (N))
4436         and then Nkind (Parent (N)) = N_If_Statement
4437       then
4438          Set_Sloc (New_If, Sloc (Parent (N)));
4439          Set_Sloc (Parent (N), Loc);
4440       end if;
4441
4442       --  Make sure Then_Actions and Else_Actions are appropriately moved
4443       --  to the new if statement.
4444
4445       if Present (Then_Actions (N)) then
4446          Insert_List_Before
4447            (First (Then_Statements (New_If)), Then_Actions (N));
4448       end if;
4449
4450       if Present (Else_Actions (N)) then
4451          Insert_List_Before
4452            (First (Else_Statements (New_If)), Else_Actions (N));
4453       end if;
4454
4455       Insert_Action (N, Decl);
4456       Insert_Action (N, New_If);
4457       Rewrite (N, New_N);
4458       Analyze_And_Resolve (N, Typ);
4459    end Expand_N_Conditional_Expression;
4460
4461    -----------------------------------
4462    -- Expand_N_Explicit_Dereference --
4463    -----------------------------------
4464
4465    procedure Expand_N_Explicit_Dereference (N : Node_Id) is
4466    begin
4467       --  Insert explicit dereference call for the checked storage pool case
4468
4469       Insert_Dereference_Action (Prefix (N));
4470
4471       --  If the type is an Atomic type for which Atomic_Sync is enabled, then
4472       --  we set the atomic sync flag.
4473
4474       if Is_Atomic (Etype (N))
4475         and then not Atomic_Synchronization_Disabled (Etype (N))
4476       then
4477          Activate_Atomic_Synchronization (N);
4478       end if;
4479    end Expand_N_Explicit_Dereference;
4480
4481    --------------------------------------
4482    -- Expand_N_Expression_With_Actions --
4483    --------------------------------------
4484
4485    procedure Expand_N_Expression_With_Actions (N : Node_Id) is
4486
4487       procedure Process_Transient_Object (Decl : Node_Id);
4488       --  Given the declaration of a controlled transient declared inside the
4489       --  Actions list of an Expression_With_Actions, generate all necessary
4490       --  types and hooks in order to properly finalize the transient. This
4491       --  mechanism works in conjunction with Build_Finalizer.
4492
4493       ------------------------------
4494       -- Process_Transient_Object --
4495       ------------------------------
4496
4497       procedure Process_Transient_Object (Decl : Node_Id) is
4498
4499          function Find_Insertion_Node return Node_Id;
4500          --  Complex conditions in if statements may be converted into nested
4501          --  EWAs. In this case, any generated code must be inserted before the
4502          --  if statement to ensure proper visibility of the hook objects. This
4503          --  routine returns the top most short circuit operator or the parent
4504          --  of the EWA if no nesting was detected.
4505
4506          -------------------------
4507          -- Find_Insertion_Node --
4508          -------------------------
4509
4510          function Find_Insertion_Node return Node_Id is
4511             Par : Node_Id;
4512
4513          begin
4514             --  Climb up the branches of a complex condition
4515
4516             Par := N;
4517             while Nkind_In (Parent (Par), N_And_Then, N_Op_Not, N_Or_Else) loop
4518                Par := Parent (Par);
4519             end loop;
4520
4521             return Par;
4522          end Find_Insertion_Node;
4523
4524          --  Local variables
4525
4526          Ins_Node  : constant Node_Id    := Find_Insertion_Node;
4527          Loc       : constant Source_Ptr := Sloc (Decl);
4528          Obj_Id    : constant Entity_Id  := Defining_Identifier (Decl);
4529          Obj_Typ   : constant Entity_Id  := Etype (Obj_Id);
4530          Desig_Typ : Entity_Id;
4531          Expr      : Node_Id;
4532          Ptr_Decl  : Node_Id;
4533          Ptr_Id    : Entity_Id;
4534          Temp_Decl : Node_Id;
4535          Temp_Id   : Node_Id;
4536
4537       --  Start of processing for Process_Transient_Object
4538
4539       begin
4540          --  Step 1: Create the access type which provides a reference to the
4541          --  transient object.
4542
4543          if Is_Access_Type (Obj_Typ) then
4544             Desig_Typ := Directly_Designated_Type (Obj_Typ);
4545          else
4546             Desig_Typ := Obj_Typ;
4547          end if;
4548
4549          --  Generate:
4550          --    Ann : access [all] <Desig_Typ>;
4551
4552          Ptr_Id := Make_Temporary (Loc, 'A');
4553
4554          Ptr_Decl :=
4555            Make_Full_Type_Declaration (Loc,
4556              Defining_Identifier => Ptr_Id,
4557              Type_Definition     =>
4558                Make_Access_To_Object_Definition (Loc,
4559                  All_Present        =>
4560                    Ekind (Obj_Typ) = E_General_Access_Type,
4561                  Subtype_Indication => New_Reference_To (Desig_Typ, Loc)));
4562
4563          Insert_Action (Ins_Node, Ptr_Decl);
4564          Analyze (Ptr_Decl);
4565
4566          --  Step 2: Create a temporary which acts as a hook to the transient
4567          --  object. Generate:
4568
4569          --    Temp : Ptr_Id := null;
4570
4571          Temp_Id := Make_Temporary (Loc, 'T');
4572
4573          Temp_Decl :=
4574            Make_Object_Declaration (Loc,
4575              Defining_Identifier => Temp_Id,
4576              Object_Definition   => New_Reference_To (Ptr_Id, Loc));
4577
4578          Insert_Action (Ins_Node, Temp_Decl);
4579          Analyze (Temp_Decl);
4580
4581          --  Mark this temporary as created for the purposes of exporting the
4582          --  transient declaration out of the Actions list. This signals the
4583          --  machinery in Build_Finalizer to recognize this special case.
4584
4585          Set_Return_Flag_Or_Transient_Decl (Temp_Id, Decl);
4586
4587          --  Step 3: Hook the transient object to the temporary
4588
4589          if Is_Access_Type (Obj_Typ) then
4590             Expr := Convert_To (Ptr_Id, New_Reference_To (Obj_Id, Loc));
4591          else
4592             Expr :=
4593               Make_Attribute_Reference (Loc,
4594                 Prefix         => New_Reference_To (Obj_Id, Loc),
4595                 Attribute_Name => Name_Unrestricted_Access);
4596          end if;
4597
4598          --  Generate:
4599          --    Temp := Ptr_Id (Obj_Id);
4600          --      <or>
4601          --    Temp := Obj_Id'Unrestricted_Access;
4602
4603          Insert_After_And_Analyze (Decl,
4604            Make_Assignment_Statement (Loc,
4605              Name       => New_Reference_To (Temp_Id, Loc),
4606              Expression => Expr));
4607       end Process_Transient_Object;
4608
4609       --  Local variables
4610
4611       Decl : Node_Id;
4612
4613    --  Start of processing for Expand_N_Expression_With_Actions
4614
4615    begin
4616       Decl := First (Actions (N));
4617       while Present (Decl) loop
4618          if Nkind (Decl) = N_Object_Declaration
4619            and then Is_Finalizable_Transient (Decl, N)
4620          then
4621             Process_Transient_Object (Decl);
4622          end if;
4623
4624          Next (Decl);
4625       end loop;
4626    end Expand_N_Expression_With_Actions;
4627
4628    -----------------
4629    -- Expand_N_In --
4630    -----------------
4631
4632    procedure Expand_N_In (N : Node_Id) is
4633       Loc    : constant Source_Ptr := Sloc (N);
4634       Restyp : constant Entity_Id  := Etype (N);
4635       Lop    : constant Node_Id    := Left_Opnd (N);
4636       Rop    : constant Node_Id    := Right_Opnd (N);
4637       Static : constant Boolean    := Is_OK_Static_Expression (N);
4638
4639       Ltyp  : Entity_Id;
4640       Rtyp  : Entity_Id;
4641
4642       procedure Substitute_Valid_Check;
4643       --  Replaces node N by Lop'Valid. This is done when we have an explicit
4644       --  test for the left operand being in range of its subtype.
4645
4646       ----------------------------
4647       -- Substitute_Valid_Check --
4648       ----------------------------
4649
4650       procedure Substitute_Valid_Check is
4651       begin
4652          Rewrite (N,
4653            Make_Attribute_Reference (Loc,
4654              Prefix         => Relocate_Node (Lop),
4655              Attribute_Name => Name_Valid));
4656
4657          Analyze_And_Resolve (N, Restyp);
4658
4659          Error_Msg_N ("?explicit membership test may be optimized away", N);
4660          Error_Msg_N -- CODEFIX
4661            ("\?use ''Valid attribute instead", N);
4662          return;
4663       end Substitute_Valid_Check;
4664
4665    --  Start of processing for Expand_N_In
4666
4667    begin
4668       --  If set membership case, expand with separate procedure
4669
4670       if Present (Alternatives (N)) then
4671          Expand_Set_Membership (N);
4672          return;
4673       end if;
4674
4675       --  Not set membership, proceed with expansion
4676
4677       Ltyp := Etype (Left_Opnd  (N));
4678       Rtyp := Etype (Right_Opnd (N));
4679
4680       --  Check case of explicit test for an expression in range of its
4681       --  subtype. This is suspicious usage and we replace it with a 'Valid
4682       --  test and give a warning. For floating point types however, this is a
4683       --  standard way to check for finite numbers, and using 'Valid would
4684       --  typically be a pessimization. Also skip this test for predicated
4685       --  types, since it is perfectly reasonable to check if a value meets
4686       --  its predicate.
4687
4688       if Is_Scalar_Type (Ltyp)
4689         and then not Is_Floating_Point_Type (Ltyp)
4690         and then Nkind (Rop) in N_Has_Entity
4691         and then Ltyp = Entity (Rop)
4692         and then Comes_From_Source (N)
4693         and then VM_Target = No_VM
4694         and then not (Is_Discrete_Type (Ltyp)
4695                        and then Present (Predicate_Function (Ltyp)))
4696       then
4697          Substitute_Valid_Check;
4698          return;
4699       end if;
4700
4701       --  Do validity check on operands
4702
4703       if Validity_Checks_On and Validity_Check_Operands then
4704          Ensure_Valid (Left_Opnd (N));
4705          Validity_Check_Range (Right_Opnd (N));
4706       end if;
4707
4708       --  Case of explicit range
4709
4710       if Nkind (Rop) = N_Range then
4711          declare
4712             Lo : constant Node_Id := Low_Bound (Rop);
4713             Hi : constant Node_Id := High_Bound (Rop);
4714
4715             Lo_Orig : constant Node_Id := Original_Node (Lo);
4716             Hi_Orig : constant Node_Id := Original_Node (Hi);
4717
4718             Lcheck : Compare_Result;
4719             Ucheck : Compare_Result;
4720
4721             Warn1 : constant Boolean :=
4722                       Constant_Condition_Warnings
4723                         and then Comes_From_Source (N)
4724                         and then not In_Instance;
4725             --  This must be true for any of the optimization warnings, we
4726             --  clearly want to give them only for source with the flag on. We
4727             --  also skip these warnings in an instance since it may be the
4728             --  case that different instantiations have different ranges.
4729
4730             Warn2 : constant Boolean :=
4731                       Warn1
4732                         and then Nkind (Original_Node (Rop)) = N_Range
4733                         and then Is_Integer_Type (Etype (Lo));
4734             --  For the case where only one bound warning is elided, we also
4735             --  insist on an explicit range and an integer type. The reason is
4736             --  that the use of enumeration ranges including an end point is
4737             --  common, as is the use of a subtype name, one of whose bounds is
4738             --  the same as the type of the expression.
4739
4740          begin
4741             --  If test is explicit x'First .. x'Last, replace by valid check
4742
4743             --  Could use some individual comments for this complex test ???
4744
4745             if Is_Scalar_Type (Ltyp)
4746               and then Nkind (Lo_Orig) = N_Attribute_Reference
4747               and then Attribute_Name (Lo_Orig) = Name_First
4748               and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
4749               and then Entity (Prefix (Lo_Orig)) = Ltyp
4750               and then Nkind (Hi_Orig) = N_Attribute_Reference
4751               and then Attribute_Name (Hi_Orig) = Name_Last
4752               and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
4753               and then Entity (Prefix (Hi_Orig)) = Ltyp
4754               and then Comes_From_Source (N)
4755               and then VM_Target = No_VM
4756             then
4757                Substitute_Valid_Check;
4758                goto Leave;
4759             end if;
4760
4761             --  If bounds of type are known at compile time, and the end points
4762             --  are known at compile time and identical, this is another case
4763             --  for substituting a valid test. We only do this for discrete
4764             --  types, since it won't arise in practice for float types.
4765
4766             if Comes_From_Source (N)
4767               and then Is_Discrete_Type (Ltyp)
4768               and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
4769               and then Compile_Time_Known_Value (Type_Low_Bound  (Ltyp))
4770               and then Compile_Time_Known_Value (Lo)
4771               and then Compile_Time_Known_Value (Hi)
4772               and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
4773               and then Expr_Value (Type_Low_Bound  (Ltyp)) = Expr_Value (Lo)
4774
4775                --  Kill warnings in instances, since they may be cases where we
4776                --  have a test in the generic that makes sense with some types
4777                --  and not with other types.
4778
4779               and then not In_Instance
4780             then
4781                Substitute_Valid_Check;
4782                goto Leave;
4783             end if;
4784
4785             --  If we have an explicit range, do a bit of optimization based on
4786             --  range analysis (we may be able to kill one or both checks).
4787
4788             Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
4789             Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
4790
4791             --  If either check is known to fail, replace result by False since
4792             --  the other check does not matter. Preserve the static flag for
4793             --  legality checks, because we are constant-folding beyond RM 4.9.
4794
4795             if Lcheck = LT or else Ucheck = GT then
4796                if Warn1 then
4797                   Error_Msg_N ("?range test optimized away", N);
4798                   Error_Msg_N ("\?value is known to be out of range", N);
4799                end if;
4800
4801                Rewrite (N, New_Reference_To (Standard_False, Loc));
4802                Analyze_And_Resolve (N, Restyp);
4803                Set_Is_Static_Expression (N, Static);
4804                goto Leave;
4805
4806             --  If both checks are known to succeed, replace result by True,
4807             --  since we know we are in range.
4808
4809             elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
4810                if Warn1 then
4811                   Error_Msg_N ("?range test optimized away", N);
4812                   Error_Msg_N ("\?value is known to be in range", N);
4813                end if;
4814
4815                Rewrite (N, New_Reference_To (Standard_True, Loc));
4816                Analyze_And_Resolve (N, Restyp);
4817                Set_Is_Static_Expression (N, Static);
4818                goto Leave;
4819
4820             --  If lower bound check succeeds and upper bound check is not
4821             --  known to succeed or fail, then replace the range check with
4822             --  a comparison against the upper bound.
4823
4824             elsif Lcheck in Compare_GE then
4825                if Warn2 and then not In_Instance then
4826                   Error_Msg_N ("?lower bound test optimized away", Lo);
4827                   Error_Msg_N ("\?value is known to be in range", Lo);
4828                end if;
4829
4830                Rewrite (N,
4831                  Make_Op_Le (Loc,
4832                    Left_Opnd  => Lop,
4833                    Right_Opnd => High_Bound (Rop)));
4834                Analyze_And_Resolve (N, Restyp);
4835                goto Leave;
4836
4837             --  If upper bound check succeeds and lower bound check is not
4838             --  known to succeed or fail, then replace the range check with
4839             --  a comparison against the lower bound.
4840
4841             elsif Ucheck in Compare_LE then
4842                if Warn2 and then not In_Instance then
4843                   Error_Msg_N ("?upper bound test optimized away", Hi);
4844                   Error_Msg_N ("\?value is known to be in range", Hi);
4845                end if;
4846
4847                Rewrite (N,
4848                  Make_Op_Ge (Loc,
4849                    Left_Opnd  => Lop,
4850                    Right_Opnd => Low_Bound (Rop)));
4851                Analyze_And_Resolve (N, Restyp);
4852                goto Leave;
4853             end if;
4854
4855             --  We couldn't optimize away the range check, but there is one
4856             --  more issue. If we are checking constant conditionals, then we
4857             --  see if we can determine the outcome assuming everything is
4858             --  valid, and if so give an appropriate warning.
4859
4860             if Warn1 and then not Assume_No_Invalid_Values then
4861                Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
4862                Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
4863
4864                --  Result is out of range for valid value
4865
4866                if Lcheck = LT or else Ucheck = GT then
4867                   Error_Msg_N
4868                     ("?value can only be in range if it is invalid", N);
4869
4870                --  Result is in range for valid value
4871
4872                elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
4873                   Error_Msg_N
4874                     ("?value can only be out of range if it is invalid", N);
4875
4876                --  Lower bound check succeeds if value is valid
4877
4878                elsif Warn2 and then Lcheck in Compare_GE then
4879                   Error_Msg_N
4880                     ("?lower bound check only fails if it is invalid", Lo);
4881
4882                --  Upper bound  check succeeds if value is valid
4883
4884                elsif Warn2 and then Ucheck in Compare_LE then
4885                   Error_Msg_N
4886                     ("?upper bound check only fails for invalid values", Hi);
4887                end if;
4888             end if;
4889          end;
4890
4891          --  For all other cases of an explicit range, nothing to be done
4892
4893          goto Leave;
4894
4895       --  Here right operand is a subtype mark
4896
4897       else
4898          declare
4899             Typ       : Entity_Id        := Etype (Rop);
4900             Is_Acc    : constant Boolean := Is_Access_Type (Typ);
4901             Cond      : Node_Id          := Empty;
4902             New_N     : Node_Id;
4903             Obj       : Node_Id          := Lop;
4904             SCIL_Node : Node_Id;
4905
4906          begin
4907             Remove_Side_Effects (Obj);
4908
4909             --  For tagged type, do tagged membership operation
4910
4911             if Is_Tagged_Type (Typ) then
4912
4913                --  No expansion will be performed when VM_Target, as the VM
4914                --  back-ends will handle the membership tests directly (tags
4915                --  are not explicitly represented in Java objects, so the
4916                --  normal tagged membership expansion is not what we want).
4917
4918                if Tagged_Type_Expansion then
4919                   Tagged_Membership (N, SCIL_Node, New_N);
4920                   Rewrite (N, New_N);
4921                   Analyze_And_Resolve (N, Restyp);
4922
4923                   --  Update decoration of relocated node referenced by the
4924                   --  SCIL node.
4925
4926                   if Generate_SCIL and then Present (SCIL_Node) then
4927                      Set_SCIL_Node (N, SCIL_Node);
4928                   end if;
4929                end if;
4930
4931                goto Leave;
4932
4933             --  If type is scalar type, rewrite as x in t'First .. t'Last.
4934             --  This reason we do this is that the bounds may have the wrong
4935             --  type if they come from the original type definition. Also this
4936             --  way we get all the processing above for an explicit range.
4937
4938                --  Don't do this for predicated types, since in this case we
4939                --  want to check the predicate!
4940
4941             elsif Is_Scalar_Type (Typ) then
4942                if No (Predicate_Function (Typ)) then
4943                   Rewrite (Rop,
4944                     Make_Range (Loc,
4945                       Low_Bound =>
4946                         Make_Attribute_Reference (Loc,
4947                           Attribute_Name => Name_First,
4948                           Prefix => New_Reference_To (Typ, Loc)),
4949
4950                       High_Bound =>
4951                         Make_Attribute_Reference (Loc,
4952                           Attribute_Name => Name_Last,
4953                           Prefix => New_Reference_To (Typ, Loc))));
4954                   Analyze_And_Resolve (N, Restyp);
4955                end if;
4956
4957                goto Leave;
4958
4959             --  Ada 2005 (AI-216): Program_Error is raised when evaluating
4960             --  a membership test if the subtype mark denotes a constrained
4961             --  Unchecked_Union subtype and the expression lacks inferable
4962             --  discriminants.
4963
4964             elsif Is_Unchecked_Union (Base_Type (Typ))
4965               and then Is_Constrained (Typ)
4966               and then not Has_Inferable_Discriminants (Lop)
4967             then
4968                Insert_Action (N,
4969                  Make_Raise_Program_Error (Loc,
4970                    Reason => PE_Unchecked_Union_Restriction));
4971
4972                --  Prevent Gigi from generating incorrect code by rewriting the
4973                --  test as False.
4974
4975                Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
4976                goto Leave;
4977             end if;
4978
4979             --  Here we have a non-scalar type
4980
4981             if Is_Acc then
4982                Typ := Designated_Type (Typ);
4983             end if;
4984
4985             if not Is_Constrained (Typ) then
4986                Rewrite (N, New_Reference_To (Standard_True, Loc));
4987                Analyze_And_Resolve (N, Restyp);
4988
4989             --  For the constrained array case, we have to check the subscripts
4990             --  for an exact match if the lengths are non-zero (the lengths
4991             --  must match in any case).
4992
4993             elsif Is_Array_Type (Typ) then
4994                Check_Subscripts : declare
4995                   function Build_Attribute_Reference
4996                     (E   : Node_Id;
4997                      Nam : Name_Id;
4998                      Dim : Nat) return Node_Id;
4999                   --  Build attribute reference E'Nam (Dim)
5000
5001                   -------------------------------
5002                   -- Build_Attribute_Reference --
5003                   -------------------------------
5004
5005                   function Build_Attribute_Reference
5006                     (E   : Node_Id;
5007                      Nam : Name_Id;
5008                      Dim : Nat) return Node_Id
5009                   is
5010                   begin
5011                      return
5012                        Make_Attribute_Reference (Loc,
5013                          Prefix         => E,
5014                          Attribute_Name => Nam,
5015                          Expressions    => New_List (
5016                            Make_Integer_Literal (Loc, Dim)));
5017                   end Build_Attribute_Reference;
5018
5019                --  Start of processing for Check_Subscripts
5020
5021                begin
5022                   for J in 1 .. Number_Dimensions (Typ) loop
5023                      Evolve_And_Then (Cond,
5024                        Make_Op_Eq (Loc,
5025                          Left_Opnd  =>
5026                            Build_Attribute_Reference
5027                              (Duplicate_Subexpr_No_Checks (Obj),
5028                               Name_First, J),
5029                          Right_Opnd =>
5030                            Build_Attribute_Reference
5031                              (New_Occurrence_Of (Typ, Loc), Name_First, J)));
5032
5033                      Evolve_And_Then (Cond,
5034                        Make_Op_Eq (Loc,
5035                          Left_Opnd  =>
5036                            Build_Attribute_Reference
5037                              (Duplicate_Subexpr_No_Checks (Obj),
5038                               Name_Last, J),
5039                          Right_Opnd =>
5040                            Build_Attribute_Reference
5041                              (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
5042                   end loop;
5043
5044                   if Is_Acc then
5045                      Cond :=
5046                        Make_Or_Else (Loc,
5047                          Left_Opnd =>
5048                            Make_Op_Eq (Loc,
5049                              Left_Opnd  => Obj,
5050                              Right_Opnd => Make_Null (Loc)),
5051                          Right_Opnd => Cond);
5052                   end if;
5053
5054                   Rewrite (N, Cond);
5055                   Analyze_And_Resolve (N, Restyp);
5056                end Check_Subscripts;
5057
5058             --  These are the cases where constraint checks may be required,
5059             --  e.g. records with possible discriminants
5060
5061             else
5062                --  Expand the test into a series of discriminant comparisons.
5063                --  The expression that is built is the negation of the one that
5064                --  is used for checking discriminant constraints.
5065
5066                Obj := Relocate_Node (Left_Opnd (N));
5067
5068                if Has_Discriminants (Typ) then
5069                   Cond := Make_Op_Not (Loc,
5070                     Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
5071
5072                   if Is_Acc then
5073                      Cond := Make_Or_Else (Loc,
5074                        Left_Opnd =>
5075                          Make_Op_Eq (Loc,
5076                            Left_Opnd  => Obj,
5077                            Right_Opnd => Make_Null (Loc)),
5078                        Right_Opnd => Cond);
5079                   end if;
5080
5081                else
5082                   Cond := New_Occurrence_Of (Standard_True, Loc);
5083                end if;
5084
5085                Rewrite (N, Cond);
5086                Analyze_And_Resolve (N, Restyp);
5087             end if;
5088
5089             --  Ada 2012 (AI05-0149): Handle membership tests applied to an
5090             --  expression of an anonymous access type. This can involve an
5091             --  accessibility test and a tagged type membership test in the
5092             --  case of tagged designated types.
5093
5094             if Ada_Version >= Ada_2012
5095               and then Is_Acc
5096               and then Ekind (Ltyp) = E_Anonymous_Access_Type
5097             then
5098                declare
5099                   Expr_Entity : Entity_Id := Empty;
5100                   New_N       : Node_Id;
5101                   Param_Level : Node_Id;
5102                   Type_Level  : Node_Id;
5103
5104                begin
5105                   if Is_Entity_Name (Lop) then
5106                      Expr_Entity := Param_Entity (Lop);
5107
5108                      if not Present (Expr_Entity) then
5109                         Expr_Entity := Entity (Lop);
5110                      end if;
5111                   end if;
5112
5113                   --  If a conversion of the anonymous access value to the
5114                   --  tested type would be illegal, then the result is False.
5115
5116                   if not Valid_Conversion
5117                            (Lop, Rtyp, Lop, Report_Errs => False)
5118                   then
5119                      Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
5120                      Analyze_And_Resolve (N, Restyp);
5121
5122                   --  Apply an accessibility check if the access object has an
5123                   --  associated access level and when the level of the type is
5124                   --  less deep than the level of the access parameter. This
5125                   --  only occur for access parameters and stand-alone objects
5126                   --  of an anonymous access type.
5127
5128                   else
5129                      if Present (Expr_Entity)
5130                        and then
5131                          Present
5132                            (Effective_Extra_Accessibility (Expr_Entity))
5133                        and then UI_Gt (Object_Access_Level (Lop),
5134                                        Type_Access_Level (Rtyp))
5135                      then
5136                         Param_Level :=
5137                           New_Occurrence_Of
5138                             (Effective_Extra_Accessibility (Expr_Entity), Loc);
5139
5140                         Type_Level :=
5141                           Make_Integer_Literal (Loc, Type_Access_Level (Rtyp));
5142
5143                         --  Return True only if the accessibility level of the
5144                         --  expression entity is not deeper than the level of
5145                         --  the tested access type.
5146
5147                         Rewrite (N,
5148                           Make_And_Then (Loc,
5149                             Left_Opnd  => Relocate_Node (N),
5150                             Right_Opnd => Make_Op_Le (Loc,
5151                                             Left_Opnd  => Param_Level,
5152                                             Right_Opnd => Type_Level)));
5153
5154                         Analyze_And_Resolve (N);
5155                      end if;
5156
5157                      --  If the designated type is tagged, do tagged membership
5158                      --  operation.
5159
5160                      --  *** NOTE: we have to check not null before doing the
5161                      --  tagged membership test (but maybe that can be done
5162                      --  inside Tagged_Membership?).
5163
5164                      if Is_Tagged_Type (Typ) then
5165                         Rewrite (N,
5166                           Make_And_Then (Loc,
5167                             Left_Opnd  => Relocate_Node (N),
5168                             Right_Opnd =>
5169                               Make_Op_Ne (Loc,
5170                                 Left_Opnd  => Obj,
5171                                 Right_Opnd => Make_Null (Loc))));
5172
5173                         --  No expansion will be performed when VM_Target, as
5174                         --  the VM back-ends will handle the membership tests
5175                         --  directly (tags are not explicitly represented in
5176                         --  Java objects, so the normal tagged membership
5177                         --  expansion is not what we want).
5178
5179                         if Tagged_Type_Expansion then
5180
5181                            --  Note that we have to pass Original_Node, because
5182                            --  the membership test might already have been
5183                            --  rewritten by earlier parts of membership test.
5184
5185                            Tagged_Membership
5186                              (Original_Node (N), SCIL_Node, New_N);
5187
5188                            --  Update decoration of relocated node referenced
5189                            --  by the SCIL node.
5190
5191                            if Generate_SCIL and then Present (SCIL_Node) then
5192                               Set_SCIL_Node (New_N, SCIL_Node);
5193                            end if;
5194
5195                            Rewrite (N,
5196                              Make_And_Then (Loc,
5197                                Left_Opnd  => Relocate_Node (N),
5198                                Right_Opnd => New_N));
5199
5200                            Analyze_And_Resolve (N, Restyp);
5201                         end if;
5202                      end if;
5203                   end if;
5204                end;
5205             end if;
5206          end;
5207       end if;
5208
5209    --  At this point, we have done the processing required for the basic
5210    --  membership test, but not yet dealt with the predicate.
5211
5212    <<Leave>>
5213
5214       --  If a predicate is present, then we do the predicate test, but we
5215       --  most certainly want to omit this if we are within the predicate
5216       --  function itself, since otherwise we have an infinite recursion!
5217
5218       declare
5219          PFunc : constant Entity_Id := Predicate_Function (Rtyp);
5220
5221       begin
5222          if Present (PFunc)
5223            and then Current_Scope /= PFunc
5224          then
5225             Rewrite (N,
5226               Make_And_Then (Loc,
5227                 Left_Opnd  => Relocate_Node (N),
5228                 Right_Opnd => Make_Predicate_Call (Rtyp, Lop)));
5229
5230             --  Analyze new expression, mark left operand as analyzed to
5231             --  avoid infinite recursion adding predicate calls. Similarly,
5232             --  suppress further range checks on the call.
5233
5234             Set_Analyzed (Left_Opnd (N));
5235             Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
5236
5237             --  All done, skip attempt at compile time determination of result
5238
5239             return;
5240          end if;
5241       end;
5242    end Expand_N_In;
5243
5244    --------------------------------
5245    -- Expand_N_Indexed_Component --
5246    --------------------------------
5247
5248    procedure Expand_N_Indexed_Component (N : Node_Id) is
5249       Loc : constant Source_Ptr := Sloc (N);
5250       Typ : constant Entity_Id  := Etype (N);
5251       P   : constant Node_Id    := Prefix (N);
5252       T   : constant Entity_Id  := Etype (P);
5253       Atp : Entity_Id;
5254
5255    begin
5256       --  A special optimization, if we have an indexed component that is
5257       --  selecting from a slice, then we can eliminate the slice, since, for
5258       --  example, x (i .. j)(k) is identical to x(k). The only difference is
5259       --  the range check required by the slice. The range check for the slice
5260       --  itself has already been generated. The range check for the
5261       --  subscripting operation is ensured by converting the subject to
5262       --  the subtype of the slice.
5263
5264       --  This optimization not only generates better code, avoiding slice
5265       --  messing especially in the packed case, but more importantly bypasses
5266       --  some problems in handling this peculiar case, for example, the issue
5267       --  of dealing specially with object renamings.
5268
5269       if Nkind (P) = N_Slice then
5270          Rewrite (N,
5271            Make_Indexed_Component (Loc,
5272              Prefix => Prefix (P),
5273              Expressions => New_List (
5274                Convert_To
5275                  (Etype (First_Index (Etype (P))),
5276                   First (Expressions (N))))));
5277          Analyze_And_Resolve (N, Typ);
5278          return;
5279       end if;
5280
5281       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
5282       --  function, then additional actuals must be passed.
5283
5284       if Ada_Version >= Ada_2005
5285         and then Is_Build_In_Place_Function_Call (P)
5286       then
5287          Make_Build_In_Place_Call_In_Anonymous_Context (P);
5288       end if;
5289
5290       --  If the prefix is an access type, then we unconditionally rewrite if
5291       --  as an explicit dereference. This simplifies processing for several
5292       --  cases, including packed array cases and certain cases in which checks
5293       --  must be generated. We used to try to do this only when it was
5294       --  necessary, but it cleans up the code to do it all the time.
5295
5296       if Is_Access_Type (T) then
5297          Insert_Explicit_Dereference (P);
5298          Analyze_And_Resolve (P, Designated_Type (T));
5299          Atp := Designated_Type (T);
5300       else
5301          Atp := T;
5302       end if;
5303
5304       --  Generate index and validity checks
5305
5306       Generate_Index_Checks (N);
5307
5308       if Validity_Checks_On and then Validity_Check_Subscripts then
5309          Apply_Subscript_Validity_Checks (N);
5310       end if;
5311
5312       --  If selecting from an array with atomic components, and atomic sync
5313       --  is not suppressed for this array type, set atomic sync flag.
5314
5315       if (Has_Atomic_Components (Atp)
5316            and then not Atomic_Synchronization_Disabled (Atp))
5317         or else (Is_Atomic (Typ)
5318                   and then not Atomic_Synchronization_Disabled (Typ))
5319       then
5320          Activate_Atomic_Synchronization (N);
5321       end if;
5322
5323       --  All done for the non-packed case
5324
5325       if not Is_Packed (Etype (Prefix (N))) then
5326          return;
5327       end if;
5328
5329       --  For packed arrays that are not bit-packed (i.e. the case of an array
5330       --  with one or more index types with a non-contiguous enumeration type),
5331       --  we can always use the normal packed element get circuit.
5332
5333       if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
5334          Expand_Packed_Element_Reference (N);
5335          return;
5336       end if;
5337
5338       --  For a reference to a component of a bit packed array, we have to
5339       --  convert it to a reference to the corresponding Packed_Array_Type.
5340       --  We only want to do this for simple references, and not for:
5341
5342       --    Left side of assignment, or prefix of left side of assignment, or
5343       --    prefix of the prefix, to handle packed arrays of packed arrays,
5344       --      This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
5345
5346       --    Renaming objects in renaming associations
5347       --      This case is handled when a use of the renamed variable occurs
5348
5349       --    Actual parameters for a procedure call
5350       --      This case is handled in Exp_Ch6.Expand_Actuals
5351
5352       --    The second expression in a 'Read attribute reference
5353
5354       --    The prefix of an address or bit or size attribute reference
5355
5356       --  The following circuit detects these exceptions
5357
5358       declare
5359          Child : Node_Id := N;
5360          Parnt : Node_Id := Parent (N);
5361
5362       begin
5363          loop
5364             if Nkind (Parnt) = N_Unchecked_Expression then
5365                null;
5366
5367             elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
5368                                    N_Procedure_Call_Statement)
5369               or else (Nkind (Parnt) = N_Parameter_Association
5370                         and then
5371                           Nkind (Parent (Parnt)) =  N_Procedure_Call_Statement)
5372             then
5373                return;
5374
5375             elsif Nkind (Parnt) = N_Attribute_Reference
5376               and then (Attribute_Name (Parnt) = Name_Address
5377                          or else
5378                         Attribute_Name (Parnt) = Name_Bit
5379                          or else
5380                         Attribute_Name (Parnt) = Name_Size)
5381               and then Prefix (Parnt) = Child
5382             then
5383                return;
5384
5385             elsif Nkind (Parnt) = N_Assignment_Statement
5386               and then Name (Parnt) = Child
5387             then
5388                return;
5389
5390             --  If the expression is an index of an indexed component, it must
5391             --  be expanded regardless of context.
5392
5393             elsif Nkind (Parnt) = N_Indexed_Component
5394               and then Child /= Prefix (Parnt)
5395             then
5396                Expand_Packed_Element_Reference (N);
5397                return;
5398
5399             elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
5400               and then Name (Parent (Parnt)) = Parnt
5401             then
5402                return;
5403
5404             elsif Nkind (Parnt) = N_Attribute_Reference
5405               and then Attribute_Name (Parnt) = Name_Read
5406               and then Next (First (Expressions (Parnt))) = Child
5407             then
5408                return;
5409
5410             elsif Nkind_In (Parnt, N_Indexed_Component, N_Selected_Component)
5411                and then Prefix (Parnt) = Child
5412             then
5413                null;
5414
5415             else
5416                Expand_Packed_Element_Reference (N);
5417                return;
5418             end if;
5419
5420             --  Keep looking up tree for unchecked expression, or if we are the
5421             --  prefix of a possible assignment left side.
5422
5423             Child := Parnt;
5424             Parnt := Parent (Child);
5425          end loop;
5426       end;
5427    end Expand_N_Indexed_Component;
5428
5429    ---------------------
5430    -- Expand_N_Not_In --
5431    ---------------------
5432
5433    --  Replace a not in b by not (a in b) so that the expansions for (a in b)
5434    --  can be done. This avoids needing to duplicate this expansion code.
5435
5436    procedure Expand_N_Not_In (N : Node_Id) is
5437       Loc : constant Source_Ptr := Sloc (N);
5438       Typ : constant Entity_Id  := Etype (N);
5439       Cfs : constant Boolean    := Comes_From_Source (N);
5440
5441    begin
5442       Rewrite (N,
5443         Make_Op_Not (Loc,
5444           Right_Opnd =>
5445             Make_In (Loc,
5446               Left_Opnd  => Left_Opnd (N),
5447               Right_Opnd => Right_Opnd (N))));
5448
5449       --  If this is a set membership, preserve list of alternatives
5450
5451       Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
5452
5453       --  We want this to appear as coming from source if original does (see
5454       --  transformations in Expand_N_In).
5455
5456       Set_Comes_From_Source (N, Cfs);
5457       Set_Comes_From_Source (Right_Opnd (N), Cfs);
5458
5459       --  Now analyze transformed node
5460
5461       Analyze_And_Resolve (N, Typ);
5462    end Expand_N_Not_In;
5463
5464    -------------------
5465    -- Expand_N_Null --
5466    -------------------
5467
5468    --  The only replacement required is for the case of a null of a type that
5469    --  is an access to protected subprogram, or a subtype thereof. We represent
5470    --  such access values as a record, and so we must replace the occurrence of
5471    --  null by the equivalent record (with a null address and a null pointer in
5472    --  it), so that the backend creates the proper value.
5473
5474    procedure Expand_N_Null (N : Node_Id) is
5475       Loc : constant Source_Ptr := Sloc (N);
5476       Typ : constant Entity_Id  := Base_Type (Etype (N));
5477       Agg : Node_Id;
5478
5479    begin
5480       if Is_Access_Protected_Subprogram_Type (Typ) then
5481          Agg :=
5482            Make_Aggregate (Loc,
5483              Expressions => New_List (
5484                New_Occurrence_Of (RTE (RE_Null_Address), Loc),
5485                Make_Null (Loc)));
5486
5487          Rewrite (N, Agg);
5488          Analyze_And_Resolve (N, Equivalent_Type (Typ));
5489
5490          --  For subsequent semantic analysis, the node must retain its type.
5491          --  Gigi in any case replaces this type by the corresponding record
5492          --  type before processing the node.
5493
5494          Set_Etype (N, Typ);
5495       end if;
5496
5497    exception
5498       when RE_Not_Available =>
5499          return;
5500    end Expand_N_Null;
5501
5502    ---------------------
5503    -- Expand_N_Op_Abs --
5504    ---------------------
5505
5506    procedure Expand_N_Op_Abs (N : Node_Id) is
5507       Loc  : constant Source_Ptr := Sloc (N);
5508       Expr : constant Node_Id := Right_Opnd (N);
5509
5510    begin
5511       Unary_Op_Validity_Checks (N);
5512
5513       --  Deal with software overflow checking
5514
5515       if not Backend_Overflow_Checks_On_Target
5516          and then Is_Signed_Integer_Type (Etype (N))
5517          and then Do_Overflow_Check (N)
5518       then
5519          --  The only case to worry about is when the argument is equal to the
5520          --  largest negative number, so what we do is to insert the check:
5521
5522          --     [constraint_error when Expr = typ'Base'First]
5523
5524          --  with the usual Duplicate_Subexpr use coding for expr
5525
5526          Insert_Action (N,
5527            Make_Raise_Constraint_Error (Loc,
5528              Condition =>
5529                Make_Op_Eq (Loc,
5530                  Left_Opnd  => Duplicate_Subexpr (Expr),
5531                  Right_Opnd =>
5532                    Make_Attribute_Reference (Loc,
5533                      Prefix =>
5534                        New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
5535                      Attribute_Name => Name_First)),
5536              Reason => CE_Overflow_Check_Failed));
5537       end if;
5538
5539       --  Vax floating-point types case
5540
5541       if Vax_Float (Etype (N)) then
5542          Expand_Vax_Arith (N);
5543       end if;
5544    end Expand_N_Op_Abs;
5545
5546    ---------------------
5547    -- Expand_N_Op_Add --
5548    ---------------------
5549
5550    procedure Expand_N_Op_Add (N : Node_Id) is
5551       Typ : constant Entity_Id := Etype (N);
5552
5553    begin
5554       Binary_Op_Validity_Checks (N);
5555
5556       --  N + 0 = 0 + N = N for integer types
5557
5558       if Is_Integer_Type (Typ) then
5559          if Compile_Time_Known_Value (Right_Opnd (N))
5560            and then Expr_Value (Right_Opnd (N)) = Uint_0
5561          then
5562             Rewrite (N, Left_Opnd (N));
5563             return;
5564
5565          elsif Compile_Time_Known_Value (Left_Opnd (N))
5566            and then Expr_Value (Left_Opnd (N)) = Uint_0
5567          then
5568             Rewrite (N, Right_Opnd (N));
5569             return;
5570          end if;
5571       end if;
5572
5573       --  Arithmetic overflow checks for signed integer/fixed point types
5574
5575       if Is_Signed_Integer_Type (Typ)
5576         or else Is_Fixed_Point_Type (Typ)
5577       then
5578          Apply_Arithmetic_Overflow_Check (N);
5579          return;
5580
5581       --  Vax floating-point types case
5582
5583       elsif Vax_Float (Typ) then
5584          Expand_Vax_Arith (N);
5585       end if;
5586    end Expand_N_Op_Add;
5587
5588    ---------------------
5589    -- Expand_N_Op_And --
5590    ---------------------
5591
5592    procedure Expand_N_Op_And (N : Node_Id) is
5593       Typ : constant Entity_Id := Etype (N);
5594
5595    begin
5596       Binary_Op_Validity_Checks (N);
5597
5598       if Is_Array_Type (Etype (N)) then
5599          Expand_Boolean_Operator (N);
5600
5601       elsif Is_Boolean_Type (Etype (N)) then
5602          Adjust_Condition (Left_Opnd (N));
5603          Adjust_Condition (Right_Opnd (N));
5604          Set_Etype (N, Standard_Boolean);
5605          Adjust_Result_Type (N, Typ);
5606
5607       elsif Is_Intrinsic_Subprogram (Entity (N)) then
5608          Expand_Intrinsic_Call (N, Entity (N));
5609
5610       end if;
5611    end Expand_N_Op_And;
5612
5613    ------------------------
5614    -- Expand_N_Op_Concat --
5615    ------------------------
5616
5617    procedure Expand_N_Op_Concat (N : Node_Id) is
5618       Opnds : List_Id;
5619       --  List of operands to be concatenated
5620
5621       Cnode : Node_Id;
5622       --  Node which is to be replaced by the result of concatenating the nodes
5623       --  in the list Opnds.
5624
5625    begin
5626       --  Ensure validity of both operands
5627
5628       Binary_Op_Validity_Checks (N);
5629
5630       --  If we are the left operand of a concatenation higher up the tree,
5631       --  then do nothing for now, since we want to deal with a series of
5632       --  concatenations as a unit.
5633
5634       if Nkind (Parent (N)) = N_Op_Concat
5635         and then N = Left_Opnd (Parent (N))
5636       then
5637          return;
5638       end if;
5639
5640       --  We get here with a concatenation whose left operand may be a
5641       --  concatenation itself with a consistent type. We need to process
5642       --  these concatenation operands from left to right, which means
5643       --  from the deepest node in the tree to the highest node.
5644
5645       Cnode := N;
5646       while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
5647          Cnode := Left_Opnd (Cnode);
5648       end loop;
5649
5650       --  Now Cnode is the deepest concatenation, and its parents are the
5651       --  concatenation nodes above, so now we process bottom up, doing the
5652       --  operations. We gather a string that is as long as possible up to five
5653       --  operands.
5654
5655       --  The outer loop runs more than once if more than one concatenation
5656       --  type is involved.
5657
5658       Outer : loop
5659          Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
5660          Set_Parent (Opnds, N);
5661
5662          --  The inner loop gathers concatenation operands
5663
5664          Inner : while Cnode /= N
5665                    and then Base_Type (Etype (Cnode)) =
5666                             Base_Type (Etype (Parent (Cnode)))
5667          loop
5668             Cnode := Parent (Cnode);
5669             Append (Right_Opnd (Cnode), Opnds);
5670          end loop Inner;
5671
5672          Expand_Concatenate (Cnode, Opnds);
5673
5674          exit Outer when Cnode = N;
5675          Cnode := Parent (Cnode);
5676       end loop Outer;
5677    end Expand_N_Op_Concat;
5678
5679    ------------------------
5680    -- Expand_N_Op_Divide --
5681    ------------------------
5682
5683    procedure Expand_N_Op_Divide (N : Node_Id) is
5684       Loc   : constant Source_Ptr := Sloc (N);
5685       Lopnd : constant Node_Id    := Left_Opnd (N);
5686       Ropnd : constant Node_Id    := Right_Opnd (N);
5687       Ltyp  : constant Entity_Id  := Etype (Lopnd);
5688       Rtyp  : constant Entity_Id  := Etype (Ropnd);
5689       Typ   : Entity_Id           := Etype (N);
5690       Rknow : constant Boolean    := Is_Integer_Type (Typ)
5691                                        and then
5692                                          Compile_Time_Known_Value (Ropnd);
5693       Rval  : Uint;
5694
5695    begin
5696       Binary_Op_Validity_Checks (N);
5697
5698       if Rknow then
5699          Rval := Expr_Value (Ropnd);
5700       end if;
5701
5702       --  N / 1 = N for integer types
5703
5704       if Rknow and then Rval = Uint_1 then
5705          Rewrite (N, Lopnd);
5706          return;
5707       end if;
5708
5709       --  Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
5710       --  Is_Power_Of_2_For_Shift is set means that we know that our left
5711       --  operand is an unsigned integer, as required for this to work.
5712
5713       if Nkind (Ropnd) = N_Op_Expon
5714         and then Is_Power_Of_2_For_Shift (Ropnd)
5715
5716       --  We cannot do this transformation in configurable run time mode if we
5717       --  have 64-bit integers and long shifts are not available.
5718
5719         and then
5720           (Esize (Ltyp) <= 32
5721              or else Support_Long_Shifts_On_Target)
5722       then
5723          Rewrite (N,
5724            Make_Op_Shift_Right (Loc,
5725              Left_Opnd  => Lopnd,
5726              Right_Opnd =>
5727                Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
5728          Analyze_And_Resolve (N, Typ);
5729          return;
5730       end if;
5731
5732       --  Do required fixup of universal fixed operation
5733
5734       if Typ = Universal_Fixed then
5735          Fixup_Universal_Fixed_Operation (N);
5736          Typ := Etype (N);
5737       end if;
5738
5739       --  Divisions with fixed-point results
5740
5741       if Is_Fixed_Point_Type (Typ) then
5742
5743          --  No special processing if Treat_Fixed_As_Integer is set, since
5744          --  from a semantic point of view such operations are simply integer
5745          --  operations and will be treated that way.
5746
5747          if not Treat_Fixed_As_Integer (N) then
5748             if Is_Integer_Type (Rtyp) then
5749                Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
5750             else
5751                Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
5752             end if;
5753          end if;
5754
5755       --  Other cases of division of fixed-point operands. Again we exclude the
5756       --  case where Treat_Fixed_As_Integer is set.
5757
5758       elsif (Is_Fixed_Point_Type (Ltyp) or else
5759              Is_Fixed_Point_Type (Rtyp))
5760         and then not Treat_Fixed_As_Integer (N)
5761       then
5762          if Is_Integer_Type (Typ) then
5763             Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
5764          else
5765             pragma Assert (Is_Floating_Point_Type (Typ));
5766             Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
5767          end if;
5768
5769       --  Mixed-mode operations can appear in a non-static universal context,
5770       --  in which case the integer argument must be converted explicitly.
5771
5772       elsif Typ = Universal_Real
5773         and then Is_Integer_Type (Rtyp)
5774       then
5775          Rewrite (Ropnd,
5776            Convert_To (Universal_Real, Relocate_Node (Ropnd)));
5777
5778          Analyze_And_Resolve (Ropnd, Universal_Real);
5779
5780       elsif Typ = Universal_Real
5781         and then Is_Integer_Type (Ltyp)
5782       then
5783          Rewrite (Lopnd,
5784            Convert_To (Universal_Real, Relocate_Node (Lopnd)));
5785
5786          Analyze_And_Resolve (Lopnd, Universal_Real);
5787
5788       --  Non-fixed point cases, do integer zero divide and overflow checks
5789
5790       elsif Is_Integer_Type (Typ) then
5791          Apply_Divide_Check (N);
5792
5793       --  Deal with Vax_Float
5794
5795       elsif Vax_Float (Typ) then
5796          Expand_Vax_Arith (N);
5797          return;
5798       end if;
5799    end Expand_N_Op_Divide;
5800
5801    --------------------
5802    -- Expand_N_Op_Eq --
5803    --------------------
5804
5805    procedure Expand_N_Op_Eq (N : Node_Id) is
5806       Loc    : constant Source_Ptr := Sloc (N);
5807       Typ    : constant Entity_Id  := Etype (N);
5808       Lhs    : constant Node_Id    := Left_Opnd (N);
5809       Rhs    : constant Node_Id    := Right_Opnd (N);
5810       Bodies : constant List_Id    := New_List;
5811       A_Typ  : constant Entity_Id  := Etype (Lhs);
5812
5813       Typl    : Entity_Id := A_Typ;
5814       Op_Name : Entity_Id;
5815       Prim    : Elmt_Id;
5816
5817       procedure Build_Equality_Call (Eq : Entity_Id);
5818       --  If a constructed equality exists for the type or for its parent,
5819       --  build and analyze call, adding conversions if the operation is
5820       --  inherited.
5821
5822       function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
5823       --  Determines whether a type has a subcomponent of an unconstrained
5824       --  Unchecked_Union subtype. Typ is a record type.
5825
5826       -------------------------
5827       -- Build_Equality_Call --
5828       -------------------------
5829
5830       procedure Build_Equality_Call (Eq : Entity_Id) is
5831          Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
5832          L_Exp   : Node_Id := Relocate_Node (Lhs);
5833          R_Exp   : Node_Id := Relocate_Node (Rhs);
5834
5835       begin
5836          if Base_Type (Op_Type) /= Base_Type (A_Typ)
5837            and then not Is_Class_Wide_Type (A_Typ)
5838          then
5839             L_Exp := OK_Convert_To (Op_Type, L_Exp);
5840             R_Exp := OK_Convert_To (Op_Type, R_Exp);
5841          end if;
5842
5843          --  If we have an Unchecked_Union, we need to add the inferred
5844          --  discriminant values as actuals in the function call. At this
5845          --  point, the expansion has determined that both operands have
5846          --  inferable discriminants.
5847
5848          if Is_Unchecked_Union (Op_Type) then
5849             declare
5850                Lhs_Type      : constant Node_Id := Etype (L_Exp);
5851                Rhs_Type      : constant Node_Id := Etype (R_Exp);
5852                Lhs_Discr_Val : Node_Id;
5853                Rhs_Discr_Val : Node_Id;
5854
5855             begin
5856                --  Per-object constrained selected components require special
5857                --  attention. If the enclosing scope of the component is an
5858                --  Unchecked_Union, we cannot reference its discriminants
5859                --  directly. This is why we use the two extra parameters of
5860                --  the equality function of the enclosing Unchecked_Union.
5861
5862                --  type UU_Type (Discr : Integer := 0) is
5863                --     . . .
5864                --  end record;
5865                --  pragma Unchecked_Union (UU_Type);
5866
5867                --  1. Unchecked_Union enclosing record:
5868
5869                --     type Enclosing_UU_Type (Discr : Integer := 0) is record
5870                --        . . .
5871                --        Comp : UU_Type (Discr);
5872                --        . . .
5873                --     end Enclosing_UU_Type;
5874                --     pragma Unchecked_Union (Enclosing_UU_Type);
5875
5876                --     Obj1 : Enclosing_UU_Type;
5877                --     Obj2 : Enclosing_UU_Type (1);
5878
5879                --     [. . .] Obj1 = Obj2 [. . .]
5880
5881                --     Generated code:
5882
5883                --     if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
5884
5885                --  A and B are the formal parameters of the equality function
5886                --  of Enclosing_UU_Type. The function always has two extra
5887                --  formals to capture the inferred discriminant values.
5888
5889                --  2. Non-Unchecked_Union enclosing record:
5890
5891                --     type
5892                --       Enclosing_Non_UU_Type (Discr : Integer := 0)
5893                --     is record
5894                --        . . .
5895                --        Comp : UU_Type (Discr);
5896                --        . . .
5897                --     end Enclosing_Non_UU_Type;
5898
5899                --     Obj1 : Enclosing_Non_UU_Type;
5900                --     Obj2 : Enclosing_Non_UU_Type (1);
5901
5902                --     ...  Obj1 = Obj2 ...
5903
5904                --     Generated code:
5905
5906                --     if not (uu_typeEQ (obj1.comp, obj2.comp,
5907                --                        obj1.discr, obj2.discr)) then
5908
5909                --  In this case we can directly reference the discriminants of
5910                --  the enclosing record.
5911
5912                --  Lhs of equality
5913
5914                if Nkind (Lhs) = N_Selected_Component
5915                  and then Has_Per_Object_Constraint
5916                             (Entity (Selector_Name (Lhs)))
5917                then
5918                   --  Enclosing record is an Unchecked_Union, use formal A
5919
5920                   if Is_Unchecked_Union
5921                        (Scope (Entity (Selector_Name (Lhs))))
5922                   then
5923                      Lhs_Discr_Val := Make_Identifier (Loc, Name_A);
5924
5925                   --  Enclosing record is of a non-Unchecked_Union type, it is
5926                   --  possible to reference the discriminant.
5927
5928                   else
5929                      Lhs_Discr_Val :=
5930                        Make_Selected_Component (Loc,
5931                          Prefix => Prefix (Lhs),
5932                          Selector_Name =>
5933                            New_Copy
5934                              (Get_Discriminant_Value
5935                                 (First_Discriminant (Lhs_Type),
5936                                  Lhs_Type,
5937                                  Stored_Constraint (Lhs_Type))));
5938                   end if;
5939
5940                --  Comment needed here ???
5941
5942                else
5943                   --  Infer the discriminant value
5944
5945                   Lhs_Discr_Val :=
5946                     New_Copy
5947                       (Get_Discriminant_Value
5948                          (First_Discriminant (Lhs_Type),
5949                           Lhs_Type,
5950                           Stored_Constraint (Lhs_Type)));
5951                end if;
5952
5953                --  Rhs of equality
5954
5955                if Nkind (Rhs) = N_Selected_Component
5956                  and then Has_Per_Object_Constraint
5957                             (Entity (Selector_Name (Rhs)))
5958                then
5959                   if Is_Unchecked_Union
5960                        (Scope (Entity (Selector_Name (Rhs))))
5961                   then
5962                      Rhs_Discr_Val := Make_Identifier (Loc, Name_B);
5963
5964                   else
5965                      Rhs_Discr_Val :=
5966                        Make_Selected_Component (Loc,
5967                          Prefix => Prefix (Rhs),
5968                          Selector_Name =>
5969                            New_Copy (Get_Discriminant_Value (
5970                              First_Discriminant (Rhs_Type),
5971                              Rhs_Type,
5972                              Stored_Constraint (Rhs_Type))));
5973
5974                   end if;
5975                else
5976                   Rhs_Discr_Val :=
5977                     New_Copy (Get_Discriminant_Value (
5978                       First_Discriminant (Rhs_Type),
5979                       Rhs_Type,
5980                       Stored_Constraint (Rhs_Type)));
5981
5982                end if;
5983
5984                Rewrite (N,
5985                  Make_Function_Call (Loc,
5986                    Name => New_Reference_To (Eq, Loc),
5987                    Parameter_Associations => New_List (
5988                      L_Exp,
5989                      R_Exp,
5990                      Lhs_Discr_Val,
5991                      Rhs_Discr_Val)));
5992             end;
5993
5994          --  Normal case, not an unchecked union
5995
5996          else
5997             Rewrite (N,
5998               Make_Function_Call (Loc,
5999                 Name => New_Reference_To (Eq, Loc),
6000                 Parameter_Associations => New_List (L_Exp, R_Exp)));
6001          end if;
6002
6003          Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6004       end Build_Equality_Call;
6005
6006       ------------------------------------
6007       -- Has_Unconstrained_UU_Component --
6008       ------------------------------------
6009
6010       function Has_Unconstrained_UU_Component
6011         (Typ : Node_Id) return Boolean
6012       is
6013          Tdef  : constant Node_Id :=
6014                    Type_Definition (Declaration_Node (Base_Type (Typ)));
6015          Clist : Node_Id;
6016          Vpart : Node_Id;
6017
6018          function Component_Is_Unconstrained_UU
6019            (Comp : Node_Id) return Boolean;
6020          --  Determines whether the subtype of the component is an
6021          --  unconstrained Unchecked_Union.
6022
6023          function Variant_Is_Unconstrained_UU
6024            (Variant : Node_Id) return Boolean;
6025          --  Determines whether a component of the variant has an unconstrained
6026          --  Unchecked_Union subtype.
6027
6028          -----------------------------------
6029          -- Component_Is_Unconstrained_UU --
6030          -----------------------------------
6031
6032          function Component_Is_Unconstrained_UU
6033            (Comp : Node_Id) return Boolean
6034          is
6035          begin
6036             if Nkind (Comp) /= N_Component_Declaration then
6037                return False;
6038             end if;
6039
6040             declare
6041                Sindic : constant Node_Id :=
6042                           Subtype_Indication (Component_Definition (Comp));
6043
6044             begin
6045                --  Unconstrained nominal type. In the case of a constraint
6046                --  present, the node kind would have been N_Subtype_Indication.
6047
6048                if Nkind (Sindic) = N_Identifier then
6049                   return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
6050                end if;
6051
6052                return False;
6053             end;
6054          end Component_Is_Unconstrained_UU;
6055
6056          ---------------------------------
6057          -- Variant_Is_Unconstrained_UU --
6058          ---------------------------------
6059
6060          function Variant_Is_Unconstrained_UU
6061            (Variant : Node_Id) return Boolean
6062          is
6063             Clist : constant Node_Id := Component_List (Variant);
6064
6065          begin
6066             if Is_Empty_List (Component_Items (Clist)) then
6067                return False;
6068             end if;
6069
6070             --  We only need to test one component
6071
6072             declare
6073                Comp : Node_Id := First (Component_Items (Clist));
6074
6075             begin
6076                while Present (Comp) loop
6077                   if Component_Is_Unconstrained_UU (Comp) then
6078                      return True;
6079                   end if;
6080
6081                   Next (Comp);
6082                end loop;
6083             end;
6084
6085             --  None of the components withing the variant were of
6086             --  unconstrained Unchecked_Union type.
6087
6088             return False;
6089          end Variant_Is_Unconstrained_UU;
6090
6091       --  Start of processing for Has_Unconstrained_UU_Component
6092
6093       begin
6094          if Null_Present (Tdef) then
6095             return False;
6096          end if;
6097
6098          Clist := Component_List (Tdef);
6099          Vpart := Variant_Part (Clist);
6100
6101          --  Inspect available components
6102
6103          if Present (Component_Items (Clist)) then
6104             declare
6105                Comp : Node_Id := First (Component_Items (Clist));
6106
6107             begin
6108                while Present (Comp) loop
6109
6110                   --  One component is sufficient
6111
6112                   if Component_Is_Unconstrained_UU (Comp) then
6113                      return True;
6114                   end if;
6115
6116                   Next (Comp);
6117                end loop;
6118             end;
6119          end if;
6120
6121          --  Inspect available components withing variants
6122
6123          if Present (Vpart) then
6124             declare
6125                Variant : Node_Id := First (Variants (Vpart));
6126
6127             begin
6128                while Present (Variant) loop
6129
6130                   --  One component within a variant is sufficient
6131
6132                   if Variant_Is_Unconstrained_UU (Variant) then
6133                      return True;
6134                   end if;
6135
6136                   Next (Variant);
6137                end loop;
6138             end;
6139          end if;
6140
6141          --  Neither the available components, nor the components inside the
6142          --  variant parts were of an unconstrained Unchecked_Union subtype.
6143
6144          return False;
6145       end Has_Unconstrained_UU_Component;
6146
6147    --  Start of processing for Expand_N_Op_Eq
6148
6149    begin
6150       Binary_Op_Validity_Checks (N);
6151
6152       if Ekind (Typl) = E_Private_Type then
6153          Typl := Underlying_Type (Typl);
6154       elsif Ekind (Typl) = E_Private_Subtype then
6155          Typl := Underlying_Type (Base_Type (Typl));
6156       else
6157          null;
6158       end if;
6159
6160       --  It may happen in error situations that the underlying type is not
6161       --  set. The error will be detected later, here we just defend the
6162       --  expander code.
6163
6164       if No (Typl) then
6165          return;
6166       end if;
6167
6168       Typl := Base_Type (Typl);
6169
6170       --  Boolean types (requiring handling of non-standard case)
6171
6172       if Is_Boolean_Type (Typl) then
6173          Adjust_Condition (Left_Opnd (N));
6174          Adjust_Condition (Right_Opnd (N));
6175          Set_Etype (N, Standard_Boolean);
6176          Adjust_Result_Type (N, Typ);
6177
6178       --  Array types
6179
6180       elsif Is_Array_Type (Typl) then
6181
6182          --  If we are doing full validity checking, and it is possible for the
6183          --  array elements to be invalid then expand out array comparisons to
6184          --  make sure that we check the array elements.
6185
6186          if Validity_Check_Operands
6187            and then not Is_Known_Valid (Component_Type (Typl))
6188          then
6189             declare
6190                Save_Force_Validity_Checks : constant Boolean :=
6191                                               Force_Validity_Checks;
6192             begin
6193                Force_Validity_Checks := True;
6194                Rewrite (N,
6195                  Expand_Array_Equality
6196                   (N,
6197                    Relocate_Node (Lhs),
6198                    Relocate_Node (Rhs),
6199                    Bodies,
6200                    Typl));
6201                Insert_Actions (N, Bodies);
6202                Analyze_And_Resolve (N, Standard_Boolean);
6203                Force_Validity_Checks := Save_Force_Validity_Checks;
6204             end;
6205
6206          --  Packed case where both operands are known aligned
6207
6208          elsif Is_Bit_Packed_Array (Typl)
6209            and then not Is_Possibly_Unaligned_Object (Lhs)
6210            and then not Is_Possibly_Unaligned_Object (Rhs)
6211          then
6212             Expand_Packed_Eq (N);
6213
6214          --  Where the component type is elementary we can use a block bit
6215          --  comparison (if supported on the target) exception in the case
6216          --  of floating-point (negative zero issues require element by
6217          --  element comparison), and atomic types (where we must be sure
6218          --  to load elements independently) and possibly unaligned arrays.
6219
6220          elsif Is_Elementary_Type (Component_Type (Typl))
6221            and then not Is_Floating_Point_Type (Component_Type (Typl))
6222            and then not Is_Atomic (Component_Type (Typl))
6223            and then not Is_Possibly_Unaligned_Object (Lhs)
6224            and then not Is_Possibly_Unaligned_Object (Rhs)
6225            and then Support_Composite_Compare_On_Target
6226          then
6227             null;
6228
6229          --  For composite and floating-point cases, expand equality loop to
6230          --  make sure of using proper comparisons for tagged types, and
6231          --  correctly handling the floating-point case.
6232
6233          else
6234             Rewrite (N,
6235               Expand_Array_Equality
6236                 (N,
6237                  Relocate_Node (Lhs),
6238                  Relocate_Node (Rhs),
6239                  Bodies,
6240                  Typl));
6241             Insert_Actions      (N, Bodies,           Suppress => All_Checks);
6242             Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6243          end if;
6244
6245       --  Record Types
6246
6247       elsif Is_Record_Type (Typl) then
6248
6249          --  For tagged types, use the primitive "="
6250
6251          if Is_Tagged_Type (Typl) then
6252
6253             --  No need to do anything else compiling under restriction
6254             --  No_Dispatching_Calls. During the semantic analysis we
6255             --  already notified such violation.
6256
6257             if Restriction_Active (No_Dispatching_Calls) then
6258                return;
6259             end if;
6260
6261             --  If this is derived from an untagged private type completed with
6262             --  a tagged type, it does not have a full view, so we use the
6263             --  primitive operations of the private type. This check should no
6264             --  longer be necessary when these types get their full views???
6265
6266             if Is_Private_Type (A_Typ)
6267               and then not Is_Tagged_Type (A_Typ)
6268               and then Is_Derived_Type (A_Typ)
6269               and then No (Full_View (A_Typ))
6270             then
6271                --  Search for equality operation, checking that the operands
6272                --  have the same type. Note that we must find a matching entry,
6273                --  or something is very wrong!
6274
6275                Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
6276
6277                while Present (Prim) loop
6278                   exit when Chars (Node (Prim)) = Name_Op_Eq
6279                     and then Etype (First_Formal (Node (Prim))) =
6280                              Etype (Next_Formal (First_Formal (Node (Prim))))
6281                     and then
6282                       Base_Type (Etype (Node (Prim))) = Standard_Boolean;
6283
6284                   Next_Elmt (Prim);
6285                end loop;
6286
6287                pragma Assert (Present (Prim));
6288                Op_Name := Node (Prim);
6289
6290             --  Find the type's predefined equality or an overriding
6291             --  user- defined equality. The reason for not simply calling
6292             --  Find_Prim_Op here is that there may be a user-defined
6293             --  overloaded equality op that precedes the equality that we want,
6294             --  so we have to explicitly search (e.g., there could be an
6295             --  equality with two different parameter types).
6296
6297             else
6298                if Is_Class_Wide_Type (Typl) then
6299                   Typl := Root_Type (Typl);
6300                end if;
6301
6302                Prim := First_Elmt (Primitive_Operations (Typl));
6303                while Present (Prim) loop
6304                   exit when Chars (Node (Prim)) = Name_Op_Eq
6305                     and then Etype (First_Formal (Node (Prim))) =
6306                              Etype (Next_Formal (First_Formal (Node (Prim))))
6307                     and then
6308                       Base_Type (Etype (Node (Prim))) = Standard_Boolean;
6309
6310                   Next_Elmt (Prim);
6311                end loop;
6312
6313                pragma Assert (Present (Prim));
6314                Op_Name := Node (Prim);
6315             end if;
6316
6317             Build_Equality_Call (Op_Name);
6318
6319          --  Ada 2005 (AI-216): Program_Error is raised when evaluating the
6320          --  predefined equality operator for a type which has a subcomponent
6321          --  of an Unchecked_Union type whose nominal subtype is unconstrained.
6322
6323          elsif Has_Unconstrained_UU_Component (Typl) then
6324             Insert_Action (N,
6325               Make_Raise_Program_Error (Loc,
6326                 Reason => PE_Unchecked_Union_Restriction));
6327
6328             --  Prevent Gigi from generating incorrect code by rewriting the
6329             --  equality as a standard False.
6330
6331             Rewrite (N,
6332               New_Occurrence_Of (Standard_False, Loc));
6333
6334          elsif Is_Unchecked_Union (Typl) then
6335
6336             --  If we can infer the discriminants of the operands, we make a
6337             --  call to the TSS equality function.
6338
6339             if Has_Inferable_Discriminants (Lhs)
6340                  and then
6341                Has_Inferable_Discriminants (Rhs)
6342             then
6343                Build_Equality_Call
6344                  (TSS (Root_Type (Typl), TSS_Composite_Equality));
6345
6346             else
6347                --  Ada 2005 (AI-216): Program_Error is raised when evaluating
6348                --  the predefined equality operator for an Unchecked_Union type
6349                --  if either of the operands lack inferable discriminants.
6350
6351                Insert_Action (N,
6352                  Make_Raise_Program_Error (Loc,
6353                    Reason => PE_Unchecked_Union_Restriction));
6354
6355                --  Prevent Gigi from generating incorrect code by rewriting
6356                --  the equality as a standard False.
6357
6358                Rewrite (N,
6359                  New_Occurrence_Of (Standard_False, Loc));
6360
6361             end if;
6362
6363          --  If a type support function is present (for complex cases), use it
6364
6365          elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
6366             Build_Equality_Call
6367               (TSS (Root_Type (Typl), TSS_Composite_Equality));
6368
6369          --  Otherwise expand the component by component equality. Note that
6370          --  we never use block-bit comparisons for records, because of the
6371          --  problems with gaps. The backend will often be able to recombine
6372          --  the separate comparisons that we generate here.
6373
6374          else
6375             Remove_Side_Effects (Lhs);
6376             Remove_Side_Effects (Rhs);
6377             Rewrite (N,
6378               Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
6379
6380             Insert_Actions      (N, Bodies,           Suppress => All_Checks);
6381             Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6382          end if;
6383       end if;
6384
6385       --  Test if result is known at compile time
6386
6387       Rewrite_Comparison (N);
6388
6389       --  If we still have comparison for Vax_Float, process it
6390
6391       if Vax_Float (Typl) and then Nkind (N) in N_Op_Compare  then
6392          Expand_Vax_Comparison (N);
6393          return;
6394       end if;
6395
6396       Optimize_Length_Comparison (N);
6397    end Expand_N_Op_Eq;
6398
6399    -----------------------
6400    -- Expand_N_Op_Expon --
6401    -----------------------
6402
6403    procedure Expand_N_Op_Expon (N : Node_Id) is
6404       Loc    : constant Source_Ptr := Sloc (N);
6405       Typ    : constant Entity_Id  := Etype (N);
6406       Rtyp   : constant Entity_Id  := Root_Type (Typ);
6407       Base   : constant Node_Id    := Relocate_Node (Left_Opnd (N));
6408       Bastyp : constant Node_Id    := Etype (Base);
6409       Exp    : constant Node_Id    := Relocate_Node (Right_Opnd (N));
6410       Exptyp : constant Entity_Id  := Etype (Exp);
6411       Ovflo  : constant Boolean    := Do_Overflow_Check (N);
6412       Expv   : Uint;
6413       Xnode  : Node_Id;
6414       Temp   : Node_Id;
6415       Rent   : RE_Id;
6416       Ent    : Entity_Id;
6417       Etyp   : Entity_Id;
6418
6419    begin
6420       Binary_Op_Validity_Checks (N);
6421
6422       --  CodePeer and GNATprove want to see the unexpanded N_Op_Expon node
6423
6424       if CodePeer_Mode or Alfa_Mode then
6425          return;
6426       end if;
6427
6428       --  If either operand is of a private type, then we have the use of an
6429       --  intrinsic operator, and we get rid of the privateness, by using root
6430       --  types of underlying types for the actual operation. Otherwise the
6431       --  private types will cause trouble if we expand multiplications or
6432       --  shifts etc. We also do this transformation if the result type is
6433       --  different from the base type.
6434
6435       if Is_Private_Type (Etype (Base))
6436         or else Is_Private_Type (Typ)
6437         or else Is_Private_Type (Exptyp)
6438         or else Rtyp /= Root_Type (Bastyp)
6439       then
6440          declare
6441             Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
6442             Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
6443
6444          begin
6445             Rewrite (N,
6446               Unchecked_Convert_To (Typ,
6447                 Make_Op_Expon (Loc,
6448                   Left_Opnd  => Unchecked_Convert_To (Bt, Base),
6449                   Right_Opnd => Unchecked_Convert_To (Et, Exp))));
6450             Analyze_And_Resolve (N, Typ);
6451             return;
6452          end;
6453       end if;
6454
6455       --  Test for case of known right argument
6456
6457       if Compile_Time_Known_Value (Exp) then
6458          Expv := Expr_Value (Exp);
6459
6460          --  We only fold small non-negative exponents. You might think we
6461          --  could fold small negative exponents for the real case, but we
6462          --  can't because we are required to raise Constraint_Error for
6463          --  the case of 0.0 ** (negative) even if Machine_Overflows = False.
6464          --  See ACVC test C4A012B.
6465
6466          if Expv >= 0 and then Expv <= 4 then
6467
6468             --  X ** 0 = 1 (or 1.0)
6469
6470             if Expv = 0 then
6471
6472                --  Call Remove_Side_Effects to ensure that any side effects
6473                --  in the ignored left operand (in particular function calls
6474                --  to user defined functions) are properly executed.
6475
6476                Remove_Side_Effects (Base);
6477
6478                if Ekind (Typ) in Integer_Kind then
6479                   Xnode := Make_Integer_Literal (Loc, Intval => 1);
6480                else
6481                   Xnode := Make_Real_Literal (Loc, Ureal_1);
6482                end if;
6483
6484             --  X ** 1 = X
6485
6486             elsif Expv = 1 then
6487                Xnode := Base;
6488
6489             --  X ** 2 = X * X
6490
6491             elsif Expv = 2 then
6492                Xnode :=
6493                  Make_Op_Multiply (Loc,
6494                    Left_Opnd  => Duplicate_Subexpr (Base),
6495                    Right_Opnd => Duplicate_Subexpr_No_Checks (Base));
6496
6497             --  X ** 3 = X * X * X
6498
6499             elsif Expv = 3 then
6500                Xnode :=
6501                  Make_Op_Multiply (Loc,
6502                    Left_Opnd =>
6503                      Make_Op_Multiply (Loc,
6504                        Left_Opnd  => Duplicate_Subexpr (Base),
6505                        Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
6506                    Right_Opnd  => Duplicate_Subexpr_No_Checks (Base));
6507
6508             --  X ** 4  ->
6509             --    En : constant base'type := base * base;
6510             --    ...
6511             --    En * En
6512
6513             else -- Expv = 4
6514                Temp := Make_Temporary (Loc, 'E', Base);
6515
6516                Insert_Actions (N, New_List (
6517                  Make_Object_Declaration (Loc,
6518                    Defining_Identifier => Temp,
6519                    Constant_Present    => True,
6520                    Object_Definition   => New_Reference_To (Typ, Loc),
6521                    Expression =>
6522                      Make_Op_Multiply (Loc,
6523                        Left_Opnd  => Duplicate_Subexpr (Base),
6524                        Right_Opnd => Duplicate_Subexpr_No_Checks (Base)))));
6525
6526                Xnode :=
6527                  Make_Op_Multiply (Loc,
6528                    Left_Opnd  => New_Reference_To (Temp, Loc),
6529                    Right_Opnd => New_Reference_To (Temp, Loc));
6530             end if;
6531
6532             Rewrite (N, Xnode);
6533             Analyze_And_Resolve (N, Typ);
6534             return;
6535          end if;
6536       end if;
6537
6538       --  Case of (2 ** expression) appearing as an argument of an integer
6539       --  multiplication, or as the right argument of a division of a non-
6540       --  negative integer. In such cases we leave the node untouched, setting
6541       --  the flag Is_Natural_Power_Of_2_for_Shift set, then the expansion
6542       --  of the higher level node converts it into a shift.
6543
6544       --  Another case is 2 ** N in any other context. We simply convert
6545       --  this to 1 * 2 ** N, and then the above transformation applies.
6546
6547       --  Note: this transformation is not applicable for a modular type with
6548       --  a non-binary modulus in the multiplication case, since we get a wrong
6549       --  result if the shift causes an overflow before the modular reduction.
6550
6551       if Nkind (Base) = N_Integer_Literal
6552         and then Intval (Base) = 2
6553         and then Is_Integer_Type (Root_Type (Exptyp))
6554         and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
6555         and then Is_Unsigned_Type (Exptyp)
6556         and then not Ovflo
6557       then
6558          --  First the multiply and divide cases
6559
6560          if Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply) then
6561             declare
6562                P : constant Node_Id := Parent (N);
6563                L : constant Node_Id := Left_Opnd (P);
6564                R : constant Node_Id := Right_Opnd (P);
6565
6566             begin
6567                if (Nkind (P) = N_Op_Multiply
6568                    and then not Non_Binary_Modulus (Typ)
6569                    and then
6570                      ((Is_Integer_Type (Etype (L)) and then R = N)
6571                          or else
6572                       (Is_Integer_Type (Etype (R)) and then L = N))
6573                    and then not Do_Overflow_Check (P))
6574                  or else
6575                   (Nkind (P) = N_Op_Divide
6576                      and then Is_Integer_Type (Etype (L))
6577                      and then Is_Unsigned_Type (Etype (L))
6578                      and then R = N
6579                      and then not Do_Overflow_Check (P))
6580                then
6581                   Set_Is_Power_Of_2_For_Shift (N);
6582                   return;
6583                end if;
6584             end;
6585
6586          --  Now the other cases
6587
6588          elsif not Non_Binary_Modulus (Typ) then
6589             Rewrite (N,
6590               Make_Op_Multiply (Loc,
6591                 Left_Opnd  => Make_Integer_Literal (Loc, 1),
6592                 Right_Opnd => Relocate_Node (N)));
6593             Analyze_And_Resolve (N, Typ);
6594             return;
6595          end if;
6596       end if;
6597
6598       --  Fall through if exponentiation must be done using a runtime routine
6599
6600       --  First deal with modular case
6601
6602       if Is_Modular_Integer_Type (Rtyp) then
6603
6604          --  Non-binary case, we call the special exponentiation routine for
6605          --  the non-binary case, converting the argument to Long_Long_Integer
6606          --  and passing the modulus value. Then the result is converted back
6607          --  to the base type.
6608
6609          if Non_Binary_Modulus (Rtyp) then
6610             Rewrite (N,
6611               Convert_To (Typ,
6612                 Make_Function_Call (Loc,
6613                   Name => New_Reference_To (RTE (RE_Exp_Modular), Loc),
6614                   Parameter_Associations => New_List (
6615                     Convert_To (Standard_Integer, Base),
6616                     Make_Integer_Literal (Loc, Modulus (Rtyp)),
6617                     Exp))));
6618
6619          --  Binary case, in this case, we call one of two routines, either the
6620          --  unsigned integer case, or the unsigned long long integer case,
6621          --  with a final "and" operation to do the required mod.
6622
6623          else
6624             if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
6625                Ent := RTE (RE_Exp_Unsigned);
6626             else
6627                Ent := RTE (RE_Exp_Long_Long_Unsigned);
6628             end if;
6629
6630             Rewrite (N,
6631               Convert_To (Typ,
6632                 Make_Op_And (Loc,
6633                   Left_Opnd =>
6634                     Make_Function_Call (Loc,
6635                       Name => New_Reference_To (Ent, Loc),
6636                       Parameter_Associations => New_List (
6637                         Convert_To (Etype (First_Formal (Ent)), Base),
6638                         Exp)),
6639                    Right_Opnd =>
6640                      Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
6641
6642          end if;
6643
6644          --  Common exit point for modular type case
6645
6646          Analyze_And_Resolve (N, Typ);
6647          return;
6648
6649       --  Signed integer cases, done using either Integer or Long_Long_Integer.
6650       --  It is not worth having routines for Short_[Short_]Integer, since for
6651       --  most machines it would not help, and it would generate more code that
6652       --  might need certification when a certified run time is required.
6653
6654       --  In the integer cases, we have two routines, one for when overflow
6655       --  checks are required, and one when they are not required, since there
6656       --  is a real gain in omitting checks on many machines.
6657
6658       elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
6659         or else (Rtyp = Base_Type (Standard_Long_Integer)
6660                    and then
6661                      Esize (Standard_Long_Integer) > Esize (Standard_Integer))
6662         or else (Rtyp = Universal_Integer)
6663       then
6664          Etyp := Standard_Long_Long_Integer;
6665
6666          if Ovflo then
6667             Rent := RE_Exp_Long_Long_Integer;
6668          else
6669             Rent := RE_Exn_Long_Long_Integer;
6670          end if;
6671
6672       elsif Is_Signed_Integer_Type (Rtyp) then
6673          Etyp := Standard_Integer;
6674
6675          if Ovflo then
6676             Rent := RE_Exp_Integer;
6677          else
6678             Rent := RE_Exn_Integer;
6679          end if;
6680
6681       --  Floating-point cases, always done using Long_Long_Float. We do not
6682       --  need separate routines for the overflow case here, since in the case
6683       --  of floating-point, we generate infinities anyway as a rule (either
6684       --  that or we automatically trap overflow), and if there is an infinity
6685       --  generated and a range check is required, the check will fail anyway.
6686
6687       else
6688          pragma Assert (Is_Floating_Point_Type (Rtyp));
6689          Etyp := Standard_Long_Long_Float;
6690          Rent := RE_Exn_Long_Long_Float;
6691       end if;
6692
6693       --  Common processing for integer cases and floating-point cases.
6694       --  If we are in the right type, we can call runtime routine directly
6695
6696       if Typ = Etyp
6697         and then Rtyp /= Universal_Integer
6698         and then Rtyp /= Universal_Real
6699       then
6700          Rewrite (N,
6701            Make_Function_Call (Loc,
6702              Name => New_Reference_To (RTE (Rent), Loc),
6703              Parameter_Associations => New_List (Base, Exp)));
6704
6705       --  Otherwise we have to introduce conversions (conversions are also
6706       --  required in the universal cases, since the runtime routine is
6707       --  typed using one of the standard types).
6708
6709       else
6710          Rewrite (N,
6711            Convert_To (Typ,
6712              Make_Function_Call (Loc,
6713                Name => New_Reference_To (RTE (Rent), Loc),
6714                Parameter_Associations => New_List (
6715                  Convert_To (Etyp, Base),
6716                  Exp))));
6717       end if;
6718
6719       Analyze_And_Resolve (N, Typ);
6720       return;
6721
6722    exception
6723       when RE_Not_Available =>
6724          return;
6725    end Expand_N_Op_Expon;
6726
6727    --------------------
6728    -- Expand_N_Op_Ge --
6729    --------------------
6730
6731    procedure Expand_N_Op_Ge (N : Node_Id) is
6732       Typ  : constant Entity_Id := Etype (N);
6733       Op1  : constant Node_Id   := Left_Opnd (N);
6734       Op2  : constant Node_Id   := Right_Opnd (N);
6735       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6736
6737    begin
6738       Binary_Op_Validity_Checks (N);
6739
6740       if Is_Array_Type (Typ1) then
6741          Expand_Array_Comparison (N);
6742          return;
6743       end if;
6744
6745       if Is_Boolean_Type (Typ1) then
6746          Adjust_Condition (Op1);
6747          Adjust_Condition (Op2);
6748          Set_Etype (N, Standard_Boolean);
6749          Adjust_Result_Type (N, Typ);
6750       end if;
6751
6752       Rewrite_Comparison (N);
6753
6754       --  If we still have comparison, and Vax_Float type, process it
6755
6756       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6757          Expand_Vax_Comparison (N);
6758          return;
6759       end if;
6760
6761       Optimize_Length_Comparison (N);
6762    end Expand_N_Op_Ge;
6763
6764    --------------------
6765    -- Expand_N_Op_Gt --
6766    --------------------
6767
6768    procedure Expand_N_Op_Gt (N : Node_Id) is
6769       Typ  : constant Entity_Id := Etype (N);
6770       Op1  : constant Node_Id   := Left_Opnd (N);
6771       Op2  : constant Node_Id   := Right_Opnd (N);
6772       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6773
6774    begin
6775       Binary_Op_Validity_Checks (N);
6776
6777       if Is_Array_Type (Typ1) then
6778          Expand_Array_Comparison (N);
6779          return;
6780       end if;
6781
6782       if Is_Boolean_Type (Typ1) then
6783          Adjust_Condition (Op1);
6784          Adjust_Condition (Op2);
6785          Set_Etype (N, Standard_Boolean);
6786          Adjust_Result_Type (N, Typ);
6787       end if;
6788
6789       Rewrite_Comparison (N);
6790
6791       --  If we still have comparison, and Vax_Float type, process it
6792
6793       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6794          Expand_Vax_Comparison (N);
6795          return;
6796       end if;
6797
6798       Optimize_Length_Comparison (N);
6799    end Expand_N_Op_Gt;
6800
6801    --------------------
6802    -- Expand_N_Op_Le --
6803    --------------------
6804
6805    procedure Expand_N_Op_Le (N : Node_Id) is
6806       Typ  : constant Entity_Id := Etype (N);
6807       Op1  : constant Node_Id   := Left_Opnd (N);
6808       Op2  : constant Node_Id   := Right_Opnd (N);
6809       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6810
6811    begin
6812       Binary_Op_Validity_Checks (N);
6813
6814       if Is_Array_Type (Typ1) then
6815          Expand_Array_Comparison (N);
6816          return;
6817       end if;
6818
6819       if Is_Boolean_Type (Typ1) then
6820          Adjust_Condition (Op1);
6821          Adjust_Condition (Op2);
6822          Set_Etype (N, Standard_Boolean);
6823          Adjust_Result_Type (N, Typ);
6824       end if;
6825
6826       Rewrite_Comparison (N);
6827
6828       --  If we still have comparison, and Vax_Float type, process it
6829
6830       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6831          Expand_Vax_Comparison (N);
6832          return;
6833       end if;
6834
6835       Optimize_Length_Comparison (N);
6836    end Expand_N_Op_Le;
6837
6838    --------------------
6839    -- Expand_N_Op_Lt --
6840    --------------------
6841
6842    procedure Expand_N_Op_Lt (N : Node_Id) is
6843       Typ  : constant Entity_Id := Etype (N);
6844       Op1  : constant Node_Id   := Left_Opnd (N);
6845       Op2  : constant Node_Id   := Right_Opnd (N);
6846       Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
6847
6848    begin
6849       Binary_Op_Validity_Checks (N);
6850
6851       if Is_Array_Type (Typ1) then
6852          Expand_Array_Comparison (N);
6853          return;
6854       end if;
6855
6856       if Is_Boolean_Type (Typ1) then
6857          Adjust_Condition (Op1);
6858          Adjust_Condition (Op2);
6859          Set_Etype (N, Standard_Boolean);
6860          Adjust_Result_Type (N, Typ);
6861       end if;
6862
6863       Rewrite_Comparison (N);
6864
6865       --  If we still have comparison, and Vax_Float type, process it
6866
6867       if Vax_Float (Typ1) and then Nkind (N) in N_Op_Compare then
6868          Expand_Vax_Comparison (N);
6869          return;
6870       end if;
6871
6872       Optimize_Length_Comparison (N);
6873    end Expand_N_Op_Lt;
6874
6875    -----------------------
6876    -- Expand_N_Op_Minus --
6877    -----------------------
6878
6879    procedure Expand_N_Op_Minus (N : Node_Id) is
6880       Loc : constant Source_Ptr := Sloc (N);
6881       Typ : constant Entity_Id  := Etype (N);
6882
6883    begin
6884       Unary_Op_Validity_Checks (N);
6885
6886       if not Backend_Overflow_Checks_On_Target
6887          and then Is_Signed_Integer_Type (Etype (N))
6888          and then Do_Overflow_Check (N)
6889       then
6890          --  Software overflow checking expands -expr into (0 - expr)
6891
6892          Rewrite (N,
6893            Make_Op_Subtract (Loc,
6894              Left_Opnd  => Make_Integer_Literal (Loc, 0),
6895              Right_Opnd => Right_Opnd (N)));
6896
6897          Analyze_And_Resolve (N, Typ);
6898
6899       --  Vax floating-point types case
6900
6901       elsif Vax_Float (Etype (N)) then
6902          Expand_Vax_Arith (N);
6903       end if;
6904    end Expand_N_Op_Minus;
6905
6906    ---------------------
6907    -- Expand_N_Op_Mod --
6908    ---------------------
6909
6910    procedure Expand_N_Op_Mod (N : Node_Id) is
6911       Loc   : constant Source_Ptr := Sloc (N);
6912       Typ   : constant Entity_Id  := Etype (N);
6913       Left  : constant Node_Id    := Left_Opnd (N);
6914       Right : constant Node_Id    := Right_Opnd (N);
6915       DOC   : constant Boolean    := Do_Overflow_Check (N);
6916       DDC   : constant Boolean    := Do_Division_Check (N);
6917
6918       LLB : Uint;
6919       Llo : Uint;
6920       Lhi : Uint;
6921       LOK : Boolean;
6922       Rlo : Uint;
6923       Rhi : Uint;
6924       ROK : Boolean;
6925
6926       pragma Warnings (Off, Lhi);
6927
6928    begin
6929       Binary_Op_Validity_Checks (N);
6930
6931       Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
6932       Determine_Range (Left,  LOK, Llo, Lhi, Assume_Valid => True);
6933
6934       --  Convert mod to rem if operands are known non-negative. We do this
6935       --  since it is quite likely that this will improve the quality of code,
6936       --  (the operation now corresponds to the hardware remainder), and it
6937       --  does not seem likely that it could be harmful.
6938
6939       if LOK and then Llo >= 0
6940            and then
6941          ROK and then Rlo >= 0
6942       then
6943          Rewrite (N,
6944            Make_Op_Rem (Sloc (N),
6945              Left_Opnd  => Left_Opnd (N),
6946              Right_Opnd => Right_Opnd (N)));
6947
6948          --  Instead of reanalyzing the node we do the analysis manually. This
6949          --  avoids anomalies when the replacement is done in an instance and
6950          --  is epsilon more efficient.
6951
6952          Set_Entity            (N, Standard_Entity (S_Op_Rem));
6953          Set_Etype             (N, Typ);
6954          Set_Do_Overflow_Check (N, DOC);
6955          Set_Do_Division_Check (N, DDC);
6956          Expand_N_Op_Rem (N);
6957          Set_Analyzed (N);
6958
6959       --  Otherwise, normal mod processing
6960
6961       else
6962          if Is_Integer_Type (Etype (N)) then
6963             Apply_Divide_Check (N);
6964          end if;
6965
6966          --  Apply optimization x mod 1 = 0. We don't really need that with
6967          --  gcc, but it is useful with other back ends (e.g. AAMP), and is
6968          --  certainly harmless.
6969
6970          if Is_Integer_Type (Etype (N))
6971            and then Compile_Time_Known_Value (Right)
6972            and then Expr_Value (Right) = Uint_1
6973          then
6974             --  Call Remove_Side_Effects to ensure that any side effects in
6975             --  the ignored left operand (in particular function calls to
6976             --  user defined functions) are properly executed.
6977
6978             Remove_Side_Effects (Left);
6979
6980             Rewrite (N, Make_Integer_Literal (Loc, 0));
6981             Analyze_And_Resolve (N, Typ);
6982             return;
6983          end if;
6984
6985          --  Deal with annoying case of largest negative number remainder
6986          --  minus one. Gigi does not handle this case correctly, because
6987          --  it generates a divide instruction which may trap in this case.
6988
6989          --  In fact the check is quite easy, if the right operand is -1, then
6990          --  the mod value is always 0, and we can just ignore the left operand
6991          --  completely in this case.
6992
6993          --  The operand type may be private (e.g. in the expansion of an
6994          --  intrinsic operation) so we must use the underlying type to get the
6995          --  bounds, and convert the literals explicitly.
6996
6997          LLB :=
6998            Expr_Value
6999              (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
7000
7001          if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
7002            and then
7003             ((not LOK) or else (Llo = LLB))
7004          then
7005             Rewrite (N,
7006               Make_Conditional_Expression (Loc,
7007                 Expressions => New_List (
7008                   Make_Op_Eq (Loc,
7009                     Left_Opnd => Duplicate_Subexpr (Right),
7010                     Right_Opnd =>
7011                       Unchecked_Convert_To (Typ,
7012                         Make_Integer_Literal (Loc, -1))),
7013                   Unchecked_Convert_To (Typ,
7014                     Make_Integer_Literal (Loc, Uint_0)),
7015                   Relocate_Node (N))));
7016
7017             Set_Analyzed (Next (Next (First (Expressions (N)))));
7018             Analyze_And_Resolve (N, Typ);
7019          end if;
7020       end if;
7021    end Expand_N_Op_Mod;
7022
7023    --------------------------
7024    -- Expand_N_Op_Multiply --
7025    --------------------------
7026
7027    procedure Expand_N_Op_Multiply (N : Node_Id) is
7028       Loc : constant Source_Ptr := Sloc (N);
7029       Lop : constant Node_Id    := Left_Opnd (N);
7030       Rop : constant Node_Id    := Right_Opnd (N);
7031
7032       Lp2 : constant Boolean :=
7033               Nkind (Lop) = N_Op_Expon
7034                 and then Is_Power_Of_2_For_Shift (Lop);
7035
7036       Rp2 : constant Boolean :=
7037               Nkind (Rop) = N_Op_Expon
7038                 and then Is_Power_Of_2_For_Shift (Rop);
7039
7040       Ltyp : constant Entity_Id  := Etype (Lop);
7041       Rtyp : constant Entity_Id  := Etype (Rop);
7042       Typ  : Entity_Id           := Etype (N);
7043
7044    begin
7045       Binary_Op_Validity_Checks (N);
7046
7047       --  Special optimizations for integer types
7048
7049       if Is_Integer_Type (Typ) then
7050
7051          --  N * 0 = 0 for integer types
7052
7053          if Compile_Time_Known_Value (Rop)
7054            and then Expr_Value (Rop) = Uint_0
7055          then
7056             --  Call Remove_Side_Effects to ensure that any side effects in
7057             --  the ignored left operand (in particular function calls to
7058             --  user defined functions) are properly executed.
7059
7060             Remove_Side_Effects (Lop);
7061
7062             Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
7063             Analyze_And_Resolve (N, Typ);
7064             return;
7065          end if;
7066
7067          --  Similar handling for 0 * N = 0
7068
7069          if Compile_Time_Known_Value (Lop)
7070            and then Expr_Value (Lop) = Uint_0
7071          then
7072             Remove_Side_Effects (Rop);
7073             Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
7074             Analyze_And_Resolve (N, Typ);
7075             return;
7076          end if;
7077
7078          --  N * 1 = 1 * N = N for integer types
7079
7080          --  This optimisation is not done if we are going to
7081          --  rewrite the product 1 * 2 ** N to a shift.
7082
7083          if Compile_Time_Known_Value (Rop)
7084            and then Expr_Value (Rop) = Uint_1
7085            and then not Lp2
7086          then
7087             Rewrite (N, Lop);
7088             return;
7089
7090          elsif Compile_Time_Known_Value (Lop)
7091            and then Expr_Value (Lop) = Uint_1
7092            and then not Rp2
7093          then
7094             Rewrite (N, Rop);
7095             return;
7096          end if;
7097       end if;
7098
7099       --  Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
7100       --  Is_Power_Of_2_For_Shift is set means that we know that our left
7101       --  operand is an integer, as required for this to work.
7102
7103       if Rp2 then
7104          if Lp2 then
7105
7106             --  Convert 2 ** A * 2 ** B into  2 ** (A + B)
7107
7108             Rewrite (N,
7109               Make_Op_Expon (Loc,
7110                 Left_Opnd => Make_Integer_Literal (Loc, 2),
7111                 Right_Opnd =>
7112                   Make_Op_Add (Loc,
7113                     Left_Opnd  => Right_Opnd (Lop),
7114                     Right_Opnd => Right_Opnd (Rop))));
7115             Analyze_And_Resolve (N, Typ);
7116             return;
7117
7118          else
7119             Rewrite (N,
7120               Make_Op_Shift_Left (Loc,
7121                 Left_Opnd  => Lop,
7122                 Right_Opnd =>
7123                   Convert_To (Standard_Natural, Right_Opnd (Rop))));
7124             Analyze_And_Resolve (N, Typ);
7125             return;
7126          end if;
7127
7128       --  Same processing for the operands the other way round
7129
7130       elsif Lp2 then
7131          Rewrite (N,
7132            Make_Op_Shift_Left (Loc,
7133              Left_Opnd  => Rop,
7134              Right_Opnd =>
7135                Convert_To (Standard_Natural, Right_Opnd (Lop))));
7136          Analyze_And_Resolve (N, Typ);
7137          return;
7138       end if;
7139
7140       --  Do required fixup of universal fixed operation
7141
7142       if Typ = Universal_Fixed then
7143          Fixup_Universal_Fixed_Operation (N);
7144          Typ := Etype (N);
7145       end if;
7146
7147       --  Multiplications with fixed-point results
7148
7149       if Is_Fixed_Point_Type (Typ) then
7150
7151          --  No special processing if Treat_Fixed_As_Integer is set, since from
7152          --  a semantic point of view such operations are simply integer
7153          --  operations and will be treated that way.
7154
7155          if not Treat_Fixed_As_Integer (N) then
7156
7157             --  Case of fixed * integer => fixed
7158
7159             if Is_Integer_Type (Rtyp) then
7160                Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
7161
7162             --  Case of integer * fixed => fixed
7163
7164             elsif Is_Integer_Type (Ltyp) then
7165                Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
7166
7167             --  Case of fixed * fixed => fixed
7168
7169             else
7170                Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
7171             end if;
7172          end if;
7173
7174       --  Other cases of multiplication of fixed-point operands. Again we
7175       --  exclude the cases where Treat_Fixed_As_Integer flag is set.
7176
7177       elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
7178         and then not Treat_Fixed_As_Integer (N)
7179       then
7180          if Is_Integer_Type (Typ) then
7181             Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
7182          else
7183             pragma Assert (Is_Floating_Point_Type (Typ));
7184             Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
7185          end if;
7186
7187       --  Mixed-mode operations can appear in a non-static universal context,
7188       --  in which case the integer argument must be converted explicitly.
7189
7190       elsif Typ = Universal_Real
7191         and then Is_Integer_Type (Rtyp)
7192       then
7193          Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
7194
7195          Analyze_And_Resolve (Rop, Universal_Real);
7196
7197       elsif Typ = Universal_Real
7198         and then Is_Integer_Type (Ltyp)
7199       then
7200          Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
7201
7202          Analyze_And_Resolve (Lop, Universal_Real);
7203
7204       --  Non-fixed point cases, check software overflow checking required
7205
7206       elsif Is_Signed_Integer_Type (Etype (N)) then
7207          Apply_Arithmetic_Overflow_Check (N);
7208
7209       --  Deal with VAX float case
7210
7211       elsif Vax_Float (Typ) then
7212          Expand_Vax_Arith (N);
7213          return;
7214       end if;
7215    end Expand_N_Op_Multiply;
7216
7217    --------------------
7218    -- Expand_N_Op_Ne --
7219    --------------------
7220
7221    procedure Expand_N_Op_Ne (N : Node_Id) is
7222       Typ : constant Entity_Id := Etype (Left_Opnd (N));
7223
7224    begin
7225       --  Case of elementary type with standard operator
7226
7227       if Is_Elementary_Type (Typ)
7228         and then Sloc (Entity (N)) = Standard_Location
7229       then
7230          Binary_Op_Validity_Checks (N);
7231
7232          --  Boolean types (requiring handling of non-standard case)
7233
7234          if Is_Boolean_Type (Typ) then
7235             Adjust_Condition (Left_Opnd (N));
7236             Adjust_Condition (Right_Opnd (N));
7237             Set_Etype (N, Standard_Boolean);
7238             Adjust_Result_Type (N, Typ);
7239          end if;
7240
7241          Rewrite_Comparison (N);
7242
7243          --  If we still have comparison for Vax_Float, process it
7244
7245          if Vax_Float (Typ) and then Nkind (N) in N_Op_Compare  then
7246             Expand_Vax_Comparison (N);
7247             return;
7248          end if;
7249
7250       --  For all cases other than elementary types, we rewrite node as the
7251       --  negation of an equality operation, and reanalyze. The equality to be
7252       --  used is defined in the same scope and has the same signature. This
7253       --  signature must be set explicitly since in an instance it may not have
7254       --  the same visibility as in the generic unit. This avoids duplicating
7255       --  or factoring the complex code for record/array equality tests etc.
7256
7257       else
7258          declare
7259             Loc : constant Source_Ptr := Sloc (N);
7260             Neg : Node_Id;
7261             Ne  : constant Entity_Id := Entity (N);
7262
7263          begin
7264             Binary_Op_Validity_Checks (N);
7265
7266             Neg :=
7267               Make_Op_Not (Loc,
7268                 Right_Opnd =>
7269                   Make_Op_Eq (Loc,
7270                     Left_Opnd =>  Left_Opnd (N),
7271                     Right_Opnd => Right_Opnd (N)));
7272             Set_Paren_Count (Right_Opnd (Neg), 1);
7273
7274             if Scope (Ne) /= Standard_Standard then
7275                Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
7276             end if;
7277
7278             --  For navigation purposes, we want to treat the inequality as an
7279             --  implicit reference to the corresponding equality. Preserve the
7280             --  Comes_From_ source flag to generate proper Xref entries.
7281
7282             Preserve_Comes_From_Source (Neg, N);
7283             Preserve_Comes_From_Source (Right_Opnd (Neg), N);
7284             Rewrite (N, Neg);
7285             Analyze_And_Resolve (N, Standard_Boolean);
7286          end;
7287       end if;
7288
7289       Optimize_Length_Comparison (N);
7290    end Expand_N_Op_Ne;
7291
7292    ---------------------
7293    -- Expand_N_Op_Not --
7294    ---------------------
7295
7296    --  If the argument is other than a Boolean array type, there is no special
7297    --  expansion required, except for VMS operations on signed integers.
7298
7299    --  For the packed case, we call the special routine in Exp_Pakd, except
7300    --  that if the component size is greater than one, we use the standard
7301    --  routine generating a gruesome loop (it is so peculiar to have packed
7302    --  arrays with non-standard Boolean representations anyway, so it does not
7303    --  matter that we do not handle this case efficiently).
7304
7305    --  For the unpacked case (and for the special packed case where we have non
7306    --  standard Booleans, as discussed above), we generate and insert into the
7307    --  tree the following function definition:
7308
7309    --     function Nnnn (A : arr) is
7310    --       B : arr;
7311    --     begin
7312    --       for J in a'range loop
7313    --          B (J) := not A (J);
7314    --       end loop;
7315    --       return B;
7316    --     end Nnnn;
7317
7318    --  Here arr is the actual subtype of the parameter (and hence always
7319    --  constrained). Then we replace the not with a call to this function.
7320
7321    procedure Expand_N_Op_Not (N : Node_Id) is
7322       Loc  : constant Source_Ptr := Sloc (N);
7323       Typ  : constant Entity_Id  := Etype (N);
7324       Opnd : Node_Id;
7325       Arr  : Entity_Id;
7326       A    : Entity_Id;
7327       B    : Entity_Id;
7328       J    : Entity_Id;
7329       A_J  : Node_Id;
7330       B_J  : Node_Id;
7331
7332       Func_Name      : Entity_Id;
7333       Loop_Statement : Node_Id;
7334
7335    begin
7336       Unary_Op_Validity_Checks (N);
7337
7338       --  For boolean operand, deal with non-standard booleans
7339
7340       if Is_Boolean_Type (Typ) then
7341          Adjust_Condition (Right_Opnd (N));
7342          Set_Etype (N, Standard_Boolean);
7343          Adjust_Result_Type (N, Typ);
7344          return;
7345       end if;
7346
7347       --  For the VMS "not" on signed integer types, use conversion to and from
7348       --  a predefined modular type.
7349
7350       if Is_VMS_Operator (Entity (N)) then
7351          declare
7352             Rtyp : Entity_Id;
7353             Utyp : Entity_Id;
7354
7355          begin
7356             --  If this is a derived type, retrieve original VMS type so that
7357             --  the proper sized type is used for intermediate values.
7358
7359             if Is_Derived_Type (Typ) then
7360                Rtyp := First_Subtype (Etype (Typ));
7361             else
7362                Rtyp := Typ;
7363             end if;
7364
7365             --  The proper unsigned type must have a size compatible with the
7366             --  operand, to prevent misalignment.
7367
7368             if RM_Size (Rtyp) <= 8 then
7369                Utyp := RTE (RE_Unsigned_8);
7370
7371             elsif RM_Size (Rtyp) <= 16 then
7372                Utyp := RTE (RE_Unsigned_16);
7373
7374             elsif RM_Size (Rtyp) = RM_Size (Standard_Unsigned) then
7375                Utyp := RTE (RE_Unsigned_32);
7376
7377             else
7378                Utyp := RTE (RE_Long_Long_Unsigned);
7379             end if;
7380
7381             Rewrite (N,
7382               Unchecked_Convert_To (Typ,
7383                 Make_Op_Not (Loc,
7384                   Unchecked_Convert_To (Utyp, Right_Opnd (N)))));
7385             Analyze_And_Resolve (N, Typ);
7386             return;
7387          end;
7388       end if;
7389
7390       --  Only array types need any other processing
7391
7392       if not Is_Array_Type (Typ) then
7393          return;
7394       end if;
7395
7396       --  Case of array operand. If bit packed with a component size of 1,
7397       --  handle it in Exp_Pakd if the operand is known to be aligned.
7398
7399       if Is_Bit_Packed_Array (Typ)
7400         and then Component_Size (Typ) = 1
7401         and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
7402       then
7403          Expand_Packed_Not (N);
7404          return;
7405       end if;
7406
7407       --  Case of array operand which is not bit-packed. If the context is
7408       --  a safe assignment, call in-place operation, If context is a larger
7409       --  boolean expression in the context of a safe assignment, expansion is
7410       --  done by enclosing operation.
7411
7412       Opnd := Relocate_Node (Right_Opnd (N));
7413       Convert_To_Actual_Subtype (Opnd);
7414       Arr := Etype (Opnd);
7415       Ensure_Defined (Arr, N);
7416       Silly_Boolean_Array_Not_Test (N, Arr);
7417
7418       if Nkind (Parent (N)) = N_Assignment_Statement then
7419          if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
7420             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
7421             return;
7422
7423          --  Special case the negation of a binary operation
7424
7425          elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
7426            and then Safe_In_Place_Array_Op
7427                       (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
7428          then
7429             Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
7430             return;
7431          end if;
7432
7433       elsif Nkind (Parent (N)) in N_Binary_Op
7434         and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
7435       then
7436          declare
7437             Op1 : constant Node_Id := Left_Opnd  (Parent (N));
7438             Op2 : constant Node_Id := Right_Opnd (Parent (N));
7439             Lhs : constant Node_Id := Name (Parent (Parent (N)));
7440
7441          begin
7442             if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
7443
7444                --  (not A) op (not B) can be reduced to a single call
7445
7446                if N = Op1 and then Nkind (Op2) = N_Op_Not then
7447                   return;
7448
7449                elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
7450                   return;
7451
7452                --  A xor (not B) can also be special-cased
7453
7454                elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
7455                   return;
7456                end if;
7457             end if;
7458          end;
7459       end if;
7460
7461       A := Make_Defining_Identifier (Loc, Name_uA);
7462       B := Make_Defining_Identifier (Loc, Name_uB);
7463       J := Make_Defining_Identifier (Loc, Name_uJ);
7464
7465       A_J :=
7466         Make_Indexed_Component (Loc,
7467           Prefix      => New_Reference_To (A, Loc),
7468           Expressions => New_List (New_Reference_To (J, Loc)));
7469
7470       B_J :=
7471         Make_Indexed_Component (Loc,
7472           Prefix      => New_Reference_To (B, Loc),
7473           Expressions => New_List (New_Reference_To (J, Loc)));
7474
7475       Loop_Statement :=
7476         Make_Implicit_Loop_Statement (N,
7477           Identifier => Empty,
7478
7479           Iteration_Scheme =>
7480             Make_Iteration_Scheme (Loc,
7481               Loop_Parameter_Specification =>
7482                 Make_Loop_Parameter_Specification (Loc,
7483                   Defining_Identifier         => J,
7484                   Discrete_Subtype_Definition =>
7485                     Make_Attribute_Reference (Loc,
7486                       Prefix         => Make_Identifier (Loc, Chars (A)),
7487                       Attribute_Name => Name_Range))),
7488
7489           Statements => New_List (
7490             Make_Assignment_Statement (Loc,
7491               Name       => B_J,
7492               Expression => Make_Op_Not (Loc, A_J))));
7493
7494       Func_Name := Make_Temporary (Loc, 'N');
7495       Set_Is_Inlined (Func_Name);
7496
7497       Insert_Action (N,
7498         Make_Subprogram_Body (Loc,
7499           Specification =>
7500             Make_Function_Specification (Loc,
7501               Defining_Unit_Name => Func_Name,
7502               Parameter_Specifications => New_List (
7503                 Make_Parameter_Specification (Loc,
7504                   Defining_Identifier => A,
7505                   Parameter_Type      => New_Reference_To (Typ, Loc))),
7506               Result_Definition => New_Reference_To (Typ, Loc)),
7507
7508           Declarations => New_List (
7509             Make_Object_Declaration (Loc,
7510               Defining_Identifier => B,
7511               Object_Definition   => New_Reference_To (Arr, Loc))),
7512
7513           Handled_Statement_Sequence =>
7514             Make_Handled_Sequence_Of_Statements (Loc,
7515               Statements => New_List (
7516                 Loop_Statement,
7517                 Make_Simple_Return_Statement (Loc,
7518                   Expression => Make_Identifier (Loc, Chars (B)))))));
7519
7520       Rewrite (N,
7521         Make_Function_Call (Loc,
7522           Name                   => New_Reference_To (Func_Name, Loc),
7523           Parameter_Associations => New_List (Opnd)));
7524
7525       Analyze_And_Resolve (N, Typ);
7526    end Expand_N_Op_Not;
7527
7528    --------------------
7529    -- Expand_N_Op_Or --
7530    --------------------
7531
7532    procedure Expand_N_Op_Or (N : Node_Id) is
7533       Typ : constant Entity_Id := Etype (N);
7534
7535    begin
7536       Binary_Op_Validity_Checks (N);
7537
7538       if Is_Array_Type (Etype (N)) then
7539          Expand_Boolean_Operator (N);
7540
7541       elsif Is_Boolean_Type (Etype (N)) then
7542          Adjust_Condition (Left_Opnd (N));
7543          Adjust_Condition (Right_Opnd (N));
7544          Set_Etype (N, Standard_Boolean);
7545          Adjust_Result_Type (N, Typ);
7546
7547       elsif Is_Intrinsic_Subprogram (Entity (N)) then
7548          Expand_Intrinsic_Call (N, Entity (N));
7549
7550       end if;
7551    end Expand_N_Op_Or;
7552
7553    ----------------------
7554    -- Expand_N_Op_Plus --
7555    ----------------------
7556
7557    procedure Expand_N_Op_Plus (N : Node_Id) is
7558    begin
7559       Unary_Op_Validity_Checks (N);
7560    end Expand_N_Op_Plus;
7561
7562    ---------------------
7563    -- Expand_N_Op_Rem --
7564    ---------------------
7565
7566    procedure Expand_N_Op_Rem (N : Node_Id) is
7567       Loc : constant Source_Ptr := Sloc (N);
7568       Typ : constant Entity_Id  := Etype (N);
7569
7570       Left  : constant Node_Id := Left_Opnd (N);
7571       Right : constant Node_Id := Right_Opnd (N);
7572
7573       Lo : Uint;
7574       Hi : Uint;
7575       OK : Boolean;
7576
7577       Lneg : Boolean;
7578       Rneg : Boolean;
7579       --  Set if corresponding operand can be negative
7580
7581       pragma Unreferenced (Hi);
7582
7583    begin
7584       Binary_Op_Validity_Checks (N);
7585
7586       if Is_Integer_Type (Etype (N)) then
7587          Apply_Divide_Check (N);
7588       end if;
7589
7590       --  Apply optimization x rem 1 = 0. We don't really need that with gcc,
7591       --  but it is useful with other back ends (e.g. AAMP), and is certainly
7592       --  harmless.
7593
7594       if Is_Integer_Type (Etype (N))
7595         and then Compile_Time_Known_Value (Right)
7596         and then Expr_Value (Right) = Uint_1
7597       then
7598          --  Call Remove_Side_Effects to ensure that any side effects in the
7599          --  ignored left operand (in particular function calls to user defined
7600          --  functions) are properly executed.
7601
7602          Remove_Side_Effects (Left);
7603
7604          Rewrite (N, Make_Integer_Literal (Loc, 0));
7605          Analyze_And_Resolve (N, Typ);
7606          return;
7607       end if;
7608
7609       --  Deal with annoying case of largest negative number remainder minus
7610       --  one. Gigi does not handle this case correctly, because it generates
7611       --  a divide instruction which may trap in this case.
7612
7613       --  In fact the check is quite easy, if the right operand is -1, then
7614       --  the remainder is always 0, and we can just ignore the left operand
7615       --  completely in this case.
7616
7617       Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
7618       Lneg := (not OK) or else Lo < 0;
7619
7620       Determine_Range (Left,  OK, Lo, Hi, Assume_Valid => True);
7621       Rneg := (not OK) or else Lo < 0;
7622
7623       --  We won't mess with trying to find out if the left operand can really
7624       --  be the largest negative number (that's a pain in the case of private
7625       --  types and this is really marginal). We will just assume that we need
7626       --  the test if the left operand can be negative at all.
7627
7628       if Lneg and Rneg then
7629          Rewrite (N,
7630            Make_Conditional_Expression (Loc,
7631              Expressions => New_List (
7632                Make_Op_Eq (Loc,
7633                  Left_Opnd  => Duplicate_Subexpr (Right),
7634                  Right_Opnd =>
7635                    Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
7636
7637                Unchecked_Convert_To (Typ,
7638                  Make_Integer_Literal (Loc, Uint_0)),
7639
7640                Relocate_Node (N))));
7641
7642          Set_Analyzed (Next (Next (First (Expressions (N)))));
7643          Analyze_And_Resolve (N, Typ);
7644       end if;
7645    end Expand_N_Op_Rem;
7646
7647    -----------------------------
7648    -- Expand_N_Op_Rotate_Left --
7649    -----------------------------
7650
7651    procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
7652    begin
7653       Binary_Op_Validity_Checks (N);
7654    end Expand_N_Op_Rotate_Left;
7655
7656    ------------------------------
7657    -- Expand_N_Op_Rotate_Right --
7658    ------------------------------
7659
7660    procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
7661    begin
7662       Binary_Op_Validity_Checks (N);
7663    end Expand_N_Op_Rotate_Right;
7664
7665    ----------------------------
7666    -- Expand_N_Op_Shift_Left --
7667    ----------------------------
7668
7669    procedure Expand_N_Op_Shift_Left (N : Node_Id) is
7670    begin
7671       Binary_Op_Validity_Checks (N);
7672    end Expand_N_Op_Shift_Left;
7673
7674    -----------------------------
7675    -- Expand_N_Op_Shift_Right --
7676    -----------------------------
7677
7678    procedure Expand_N_Op_Shift_Right (N : Node_Id) is
7679    begin
7680       Binary_Op_Validity_Checks (N);
7681    end Expand_N_Op_Shift_Right;
7682
7683    ----------------------------------------
7684    -- Expand_N_Op_Shift_Right_Arithmetic --
7685    ----------------------------------------
7686
7687    procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
7688    begin
7689       Binary_Op_Validity_Checks (N);
7690    end Expand_N_Op_Shift_Right_Arithmetic;
7691
7692    --------------------------
7693    -- Expand_N_Op_Subtract --
7694    --------------------------
7695
7696    procedure Expand_N_Op_Subtract (N : Node_Id) is
7697       Typ : constant Entity_Id := Etype (N);
7698
7699    begin
7700       Binary_Op_Validity_Checks (N);
7701
7702       --  N - 0 = N for integer types
7703
7704       if Is_Integer_Type (Typ)
7705         and then Compile_Time_Known_Value (Right_Opnd (N))
7706         and then Expr_Value (Right_Opnd (N)) = 0
7707       then
7708          Rewrite (N, Left_Opnd (N));
7709          return;
7710       end if;
7711
7712       --  Arithmetic overflow checks for signed integer/fixed point types
7713
7714       if Is_Signed_Integer_Type (Typ)
7715            or else
7716          Is_Fixed_Point_Type (Typ)
7717       then
7718          Apply_Arithmetic_Overflow_Check (N);
7719
7720       --  VAX floating-point types case
7721
7722       elsif Vax_Float (Typ) then
7723          Expand_Vax_Arith (N);
7724       end if;
7725    end Expand_N_Op_Subtract;
7726
7727    ---------------------
7728    -- Expand_N_Op_Xor --
7729    ---------------------
7730
7731    procedure Expand_N_Op_Xor (N : Node_Id) is
7732       Typ : constant Entity_Id := Etype (N);
7733
7734    begin
7735       Binary_Op_Validity_Checks (N);
7736
7737       if Is_Array_Type (Etype (N)) then
7738          Expand_Boolean_Operator (N);
7739
7740       elsif Is_Boolean_Type (Etype (N)) then
7741          Adjust_Condition (Left_Opnd (N));
7742          Adjust_Condition (Right_Opnd (N));
7743          Set_Etype (N, Standard_Boolean);
7744          Adjust_Result_Type (N, Typ);
7745
7746       elsif Is_Intrinsic_Subprogram (Entity (N)) then
7747          Expand_Intrinsic_Call (N, Entity (N));
7748
7749       end if;
7750    end Expand_N_Op_Xor;
7751
7752    ----------------------
7753    -- Expand_N_Or_Else --
7754    ----------------------
7755
7756    procedure Expand_N_Or_Else (N : Node_Id)
7757      renames Expand_Short_Circuit_Operator;
7758
7759    -----------------------------------
7760    -- Expand_N_Qualified_Expression --
7761    -----------------------------------
7762
7763    procedure Expand_N_Qualified_Expression (N : Node_Id) is
7764       Operand     : constant Node_Id   := Expression (N);
7765       Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
7766
7767    begin
7768       --  Do validity check if validity checking operands
7769
7770       if Validity_Checks_On
7771         and then Validity_Check_Operands
7772       then
7773          Ensure_Valid (Operand);
7774       end if;
7775
7776       --  Apply possible constraint check
7777
7778       Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
7779
7780       if Do_Range_Check (Operand) then
7781          Set_Do_Range_Check (Operand, False);
7782          Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
7783       end if;
7784    end Expand_N_Qualified_Expression;
7785
7786    ------------------------------------
7787    -- Expand_N_Quantified_Expression --
7788    ------------------------------------
7789
7790    --  We expand:
7791
7792    --    for all X in range => Cond
7793
7794    --  into:
7795
7796    --        T := True;
7797    --        for X in range loop
7798    --           if not Cond then
7799    --              T := False;
7800    --              exit;
7801    --           end if;
7802    --        end loop;
7803
7804    --  Conversely, an existentially quantified expression:
7805
7806    --    for some X in range => Cond
7807
7808    --  becomes:
7809
7810    --        T := False;
7811    --        for X in range loop
7812    --           if Cond then
7813    --              T := True;
7814    --              exit;
7815    --           end if;
7816    --        end loop;
7817
7818    --  In both cases, the iteration may be over a container in which case it is
7819    --  given by an iterator specification, not a loop parameter specification.
7820
7821    procedure Expand_N_Quantified_Expression (N : Node_Id) is
7822       Loc          : constant Source_Ptr := Sloc (N);
7823       Is_Universal : constant Boolean := All_Present (N);
7824       Actions      : constant List_Id := New_List;
7825       Tnn          : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7826       Cond         : Node_Id;
7827       Decl         : Node_Id;
7828       I_Scheme     : Node_Id;
7829       Test         : Node_Id;
7830
7831    begin
7832       Decl :=
7833         Make_Object_Declaration (Loc,
7834           Defining_Identifier => Tnn,
7835           Object_Definition   => New_Occurrence_Of (Standard_Boolean, Loc),
7836           Expression          =>
7837             New_Occurrence_Of (Boolean_Literals (Is_Universal), Loc));
7838       Append_To (Actions, Decl);
7839
7840       Cond := Relocate_Node (Condition (N));
7841
7842       --  Reset flag analyzed in the condition to force its analysis. Required
7843       --  since the previous analysis was done with expansion disabled (see
7844       --  Resolve_Quantified_Expression) and hence checks were not inserted
7845       --  and record comparisons have not been expanded.
7846
7847       Reset_Analyzed_Flags (Cond);
7848
7849       if Is_Universal then
7850          Cond := Make_Op_Not (Loc, Cond);
7851       end if;
7852
7853       Test :=
7854         Make_Implicit_If_Statement (N,
7855           Condition       => Cond,
7856           Then_Statements => New_List (
7857             Make_Assignment_Statement (Loc,
7858               Name       => New_Occurrence_Of (Tnn, Loc),
7859               Expression =>
7860                 New_Occurrence_Of (Boolean_Literals (not Is_Universal), Loc)),
7861             Make_Exit_Statement (Loc)));
7862
7863       if Present (Loop_Parameter_Specification (N)) then
7864          I_Scheme :=
7865            Make_Iteration_Scheme (Loc,
7866               Loop_Parameter_Specification =>
7867                 Loop_Parameter_Specification (N));
7868       else
7869          I_Scheme :=
7870            Make_Iteration_Scheme (Loc,
7871              Iterator_Specification => Iterator_Specification (N));
7872       end if;
7873
7874       Append_To (Actions,
7875         Make_Loop_Statement (Loc,
7876           Iteration_Scheme => I_Scheme,
7877           Statements       => New_List (Test),
7878           End_Label        => Empty));
7879
7880       Rewrite (N,
7881         Make_Expression_With_Actions (Loc,
7882           Expression => New_Occurrence_Of (Tnn, Loc),
7883           Actions    => Actions));
7884
7885       Analyze_And_Resolve (N, Standard_Boolean);
7886    end Expand_N_Quantified_Expression;
7887
7888    ---------------------------------
7889    -- Expand_N_Selected_Component --
7890    ---------------------------------
7891
7892    procedure Expand_N_Selected_Component (N : Node_Id) is
7893       Loc   : constant Source_Ptr := Sloc (N);
7894       Par   : constant Node_Id    := Parent (N);
7895       P     : constant Node_Id    := Prefix (N);
7896       Ptyp  : Entity_Id           := Underlying_Type (Etype (P));
7897       Disc  : Entity_Id;
7898       New_N : Node_Id;
7899       Dcon  : Elmt_Id;
7900       Dval  : Node_Id;
7901
7902       function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
7903       --  Gigi needs a temporary for prefixes that depend on a discriminant,
7904       --  unless the context of an assignment can provide size information.
7905       --  Don't we have a general routine that does this???
7906
7907       function Is_Subtype_Declaration return Boolean;
7908       --  The replacement of a discriminant reference by its value is required
7909       --  if this is part of the initialization of an temporary generated by a
7910       --  change of representation. This shows up as the construction of a
7911       --  discriminant constraint for a subtype declared at the same point as
7912       --  the entity in the prefix of the selected component. We recognize this
7913       --  case when the context of the reference is:
7914       --    subtype ST is T(Obj.D);
7915       --  where the entity for Obj comes from source, and ST has the same sloc.
7916
7917       -----------------------
7918       -- In_Left_Hand_Side --
7919       -----------------------
7920
7921       function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
7922       begin
7923          return (Nkind (Parent (Comp)) = N_Assignment_Statement
7924                   and then Comp = Name (Parent (Comp)))
7925            or else (Present (Parent (Comp))
7926                      and then Nkind (Parent (Comp)) in N_Subexpr
7927                      and then In_Left_Hand_Side (Parent (Comp)));
7928       end In_Left_Hand_Side;
7929
7930       -----------------------------
7931       --  Is_Subtype_Declaration --
7932       -----------------------------
7933
7934       function Is_Subtype_Declaration return Boolean is
7935          Par : constant Node_Id := Parent (N);
7936       begin
7937          return
7938            Nkind (Par) = N_Index_Or_Discriminant_Constraint
7939              and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
7940              and then Comes_From_Source (Entity (Prefix (N)))
7941              and then Sloc (Par) = Sloc (Entity (Prefix (N)));
7942       end Is_Subtype_Declaration;
7943
7944    --  Start of processing for Expand_N_Selected_Component
7945
7946    begin
7947       --  Insert explicit dereference if required
7948
7949       if Is_Access_Type (Ptyp) then
7950
7951          --  First set prefix type to proper access type, in case it currently
7952          --  has a private (non-access) view of this type.
7953
7954          Set_Etype (P, Ptyp);
7955
7956          Insert_Explicit_Dereference (P);
7957          Analyze_And_Resolve (P, Designated_Type (Ptyp));
7958
7959          if Ekind (Etype (P)) = E_Private_Subtype
7960            and then Is_For_Access_Subtype (Etype (P))
7961          then
7962             Set_Etype (P, Base_Type (Etype (P)));
7963          end if;
7964
7965          Ptyp := Etype (P);
7966       end if;
7967
7968       --  Deal with discriminant check required
7969
7970       if Do_Discriminant_Check (N) then
7971
7972          --  Present the discriminant checking function to the backend, so that
7973          --  it can inline the call to the function.
7974
7975          Add_Inlined_Body
7976            (Discriminant_Checking_Func
7977              (Original_Record_Component (Entity (Selector_Name (N)))));
7978
7979          --  Now reset the flag and generate the call
7980
7981          Set_Do_Discriminant_Check (N, False);
7982          Generate_Discriminant_Check (N);
7983       end if;
7984
7985       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
7986       --  function, then additional actuals must be passed.
7987
7988       if Ada_Version >= Ada_2005
7989         and then Is_Build_In_Place_Function_Call (P)
7990       then
7991          Make_Build_In_Place_Call_In_Anonymous_Context (P);
7992       end if;
7993
7994       --  Gigi cannot handle unchecked conversions that are the prefix of a
7995       --  selected component with discriminants. This must be checked during
7996       --  expansion, because during analysis the type of the selector is not
7997       --  known at the point the prefix is analyzed. If the conversion is the
7998       --  target of an assignment, then we cannot force the evaluation.
7999
8000       if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
8001         and then Has_Discriminants (Etype (N))
8002         and then not In_Left_Hand_Side (N)
8003       then
8004          Force_Evaluation (Prefix (N));
8005       end if;
8006
8007       --  Remaining processing applies only if selector is a discriminant
8008
8009       if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
8010
8011          --  If the selector is a discriminant of a constrained record type,
8012          --  we may be able to rewrite the expression with the actual value
8013          --  of the discriminant, a useful optimization in some cases.
8014
8015          if Is_Record_Type (Ptyp)
8016            and then Has_Discriminants (Ptyp)
8017            and then Is_Constrained (Ptyp)
8018          then
8019             --  Do this optimization for discrete types only, and not for
8020             --  access types (access discriminants get us into trouble!)
8021
8022             if not Is_Discrete_Type (Etype (N)) then
8023                null;
8024
8025             --  Don't do this on the left hand of an assignment statement.
8026             --  Normally one would think that references like this would not
8027             --  occur, but they do in generated code, and mean that we really
8028             --  do want to assign the discriminant!
8029
8030             elsif Nkind (Par) = N_Assignment_Statement
8031               and then Name (Par) = N
8032             then
8033                null;
8034
8035             --  Don't do this optimization for the prefix of an attribute or
8036             --  the name of an object renaming declaration since these are
8037             --  contexts where we do not want the value anyway.
8038
8039             elsif (Nkind (Par) = N_Attribute_Reference
8040                      and then Prefix (Par) = N)
8041               or else Is_Renamed_Object (N)
8042             then
8043                null;
8044
8045             --  Don't do this optimization if we are within the code for a
8046             --  discriminant check, since the whole point of such a check may
8047             --  be to verify the condition on which the code below depends!
8048
8049             elsif Is_In_Discriminant_Check (N) then
8050                null;
8051
8052             --  Green light to see if we can do the optimization. There is
8053             --  still one condition that inhibits the optimization below but
8054             --  now is the time to check the particular discriminant.
8055
8056             else
8057                --  Loop through discriminants to find the matching discriminant
8058                --  constraint to see if we can copy it.
8059
8060                Disc := First_Discriminant (Ptyp);
8061                Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
8062                Discr_Loop : while Present (Dcon) loop
8063                   Dval := Node (Dcon);
8064
8065                   --  Check if this is the matching discriminant and if the
8066                   --  discriminant value is simple enough to make sense to
8067                   --  copy. We don't want to copy complex expressions, and
8068                   --  indeed to do so can cause trouble (before we put in
8069                   --  this guard, a discriminant expression containing an
8070                   --  AND THEN was copied, causing problems for coverage
8071                   --  analysis tools).
8072
8073                   --  However, if the reference is part of the initialization
8074                   --  code generated for an object declaration, we must use
8075                   --  the discriminant value from the subtype constraint,
8076                   --  because the selected component may be a reference to the
8077                   --  object being initialized, whose discriminant is not yet
8078                   --  set. This only happens in complex cases involving changes
8079                   --  or representation.
8080
8081                   if Disc = Entity (Selector_Name (N))
8082                     and then (Is_Entity_Name (Dval)
8083                                or else Compile_Time_Known_Value (Dval)
8084                                or else Is_Subtype_Declaration)
8085                   then
8086                      --  Here we have the matching discriminant. Check for
8087                      --  the case of a discriminant of a component that is
8088                      --  constrained by an outer discriminant, which cannot
8089                      --  be optimized away.
8090
8091                      if Denotes_Discriminant
8092                           (Dval, Check_Concurrent => True)
8093                      then
8094                         exit Discr_Loop;
8095
8096                      elsif Nkind (Original_Node (Dval)) = N_Selected_Component
8097                        and then
8098                          Denotes_Discriminant
8099                            (Selector_Name (Original_Node (Dval)), True)
8100                      then
8101                         exit Discr_Loop;
8102
8103                      --  Do not retrieve value if constraint is not static. It
8104                      --  is generally not useful, and the constraint may be a
8105                      --  rewritten outer discriminant in which case it is in
8106                      --  fact incorrect.
8107
8108                      elsif Is_Entity_Name (Dval)
8109                        and then Nkind (Parent (Entity (Dval))) =
8110                                                       N_Object_Declaration
8111                        and then Present (Expression (Parent (Entity (Dval))))
8112                        and then
8113                          not Is_Static_Expression
8114                            (Expression (Parent (Entity (Dval))))
8115                      then
8116                         exit Discr_Loop;
8117
8118                      --  In the context of a case statement, the expression may
8119                      --  have the base type of the discriminant, and we need to
8120                      --  preserve the constraint to avoid spurious errors on
8121                      --  missing cases.
8122
8123                      elsif Nkind (Parent (N)) = N_Case_Statement
8124                        and then Etype (Dval) /= Etype (Disc)
8125                      then
8126                         Rewrite (N,
8127                           Make_Qualified_Expression (Loc,
8128                             Subtype_Mark =>
8129                               New_Occurrence_Of (Etype (Disc), Loc),
8130                             Expression   =>
8131                               New_Copy_Tree (Dval)));
8132                         Analyze_And_Resolve (N, Etype (Disc));
8133
8134                         --  In case that comes out as a static expression,
8135                         --  reset it (a selected component is never static).
8136
8137                         Set_Is_Static_Expression (N, False);
8138                         return;
8139
8140                      --  Otherwise we can just copy the constraint, but the
8141                      --  result is certainly not static! In some cases the
8142                      --  discriminant constraint has been analyzed in the
8143                      --  context of the original subtype indication, but for
8144                      --  itypes the constraint might not have been analyzed
8145                      --  yet, and this must be done now.
8146
8147                      else
8148                         Rewrite (N, New_Copy_Tree (Dval));
8149                         Analyze_And_Resolve (N);
8150                         Set_Is_Static_Expression (N, False);
8151                         return;
8152                      end if;
8153                   end if;
8154
8155                   Next_Elmt (Dcon);
8156                   Next_Discriminant (Disc);
8157                end loop Discr_Loop;
8158
8159                --  Note: the above loop should always find a matching
8160                --  discriminant, but if it does not, we just missed an
8161                --  optimization due to some glitch (perhaps a previous
8162                --  error), so ignore.
8163
8164             end if;
8165          end if;
8166
8167          --  The only remaining processing is in the case of a discriminant of
8168          --  a concurrent object, where we rewrite the prefix to denote the
8169          --  corresponding record type. If the type is derived and has renamed
8170          --  discriminants, use corresponding discriminant, which is the one
8171          --  that appears in the corresponding record.
8172
8173          if not Is_Concurrent_Type (Ptyp) then
8174             return;
8175          end if;
8176
8177          Disc := Entity (Selector_Name (N));
8178
8179          if Is_Derived_Type (Ptyp)
8180            and then Present (Corresponding_Discriminant (Disc))
8181          then
8182             Disc := Corresponding_Discriminant (Disc);
8183          end if;
8184
8185          New_N :=
8186            Make_Selected_Component (Loc,
8187              Prefix =>
8188                Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
8189                  New_Copy_Tree (P)),
8190              Selector_Name => Make_Identifier (Loc, Chars (Disc)));
8191
8192          Rewrite (N, New_N);
8193          Analyze (N);
8194       end if;
8195
8196       --  Set Atomic_Sync_Required if necessary for atomic component
8197
8198       if Nkind (N) = N_Selected_Component then
8199          declare
8200             E   : constant Entity_Id := Entity (Selector_Name (N));
8201             Set : Boolean;
8202
8203          begin
8204             --  If component is atomic, but type is not, setting depends on
8205             --  disable/enable state for the component.
8206
8207             if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
8208                Set := not Atomic_Synchronization_Disabled (E);
8209
8210             --  If component is not atomic, but its type is atomic, setting
8211             --  depends on disable/enable state for the type.
8212
8213             elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
8214                Set := not Atomic_Synchronization_Disabled (Etype (E));
8215
8216             --  If both component and type are atomic, we disable if either
8217             --  component or its type have sync disabled.
8218
8219             elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
8220                Set := (not Atomic_Synchronization_Disabled (E))
8221                         and then
8222                       (not Atomic_Synchronization_Disabled (Etype (E)));
8223
8224             else
8225                Set := False;
8226             end if;
8227
8228             --  Set flag if required
8229
8230             if Set then
8231                Activate_Atomic_Synchronization (N);
8232             end if;
8233          end;
8234       end if;
8235    end Expand_N_Selected_Component;
8236
8237    --------------------
8238    -- Expand_N_Slice --
8239    --------------------
8240
8241    procedure Expand_N_Slice (N : Node_Id) is
8242       Loc  : constant Source_Ptr := Sloc (N);
8243       Typ  : constant Entity_Id  := Etype (N);
8244       Pfx  : constant Node_Id    := Prefix (N);
8245       Ptp  : Entity_Id           := Etype (Pfx);
8246
8247       function Is_Procedure_Actual (N : Node_Id) return Boolean;
8248       --  Check whether the argument is an actual for a procedure call, in
8249       --  which case the expansion of a bit-packed slice is deferred until the
8250       --  call itself is expanded. The reason this is required is that we might
8251       --  have an IN OUT or OUT parameter, and the copy out is essential, and
8252       --  that copy out would be missed if we created a temporary here in
8253       --  Expand_N_Slice. Note that we don't bother to test specifically for an
8254       --  IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
8255       --  is harmless to defer expansion in the IN case, since the call
8256       --  processing will still generate the appropriate copy in operation,
8257       --  which will take care of the slice.
8258
8259       procedure Make_Temporary_For_Slice;
8260       --  Create a named variable for the value of the slice, in cases where
8261       --  the back-end cannot handle it properly, e.g. when packed types or
8262       --  unaligned slices are involved.
8263
8264       -------------------------
8265       -- Is_Procedure_Actual --
8266       -------------------------
8267
8268       function Is_Procedure_Actual (N : Node_Id) return Boolean is
8269          Par : Node_Id := Parent (N);
8270
8271       begin
8272          loop
8273             --  If our parent is a procedure call we can return
8274
8275             if Nkind (Par) = N_Procedure_Call_Statement then
8276                return True;
8277
8278             --  If our parent is a type conversion, keep climbing the tree,
8279             --  since a type conversion can be a procedure actual. Also keep
8280             --  climbing if parameter association or a qualified expression,
8281             --  since these are additional cases that do can appear on
8282             --  procedure actuals.
8283
8284             elsif Nkind_In (Par, N_Type_Conversion,
8285                                  N_Parameter_Association,
8286                                  N_Qualified_Expression)
8287             then
8288                Par := Parent (Par);
8289
8290                --  Any other case is not what we are looking for
8291
8292             else
8293                return False;
8294             end if;
8295          end loop;
8296       end Is_Procedure_Actual;
8297
8298       ------------------------------
8299       -- Make_Temporary_For_Slice --
8300       ------------------------------
8301
8302       procedure Make_Temporary_For_Slice is
8303          Decl : Node_Id;
8304          Ent  : constant Entity_Id := Make_Temporary (Loc, 'T', N);
8305
8306       begin
8307          Decl :=
8308            Make_Object_Declaration (Loc,
8309              Defining_Identifier => Ent,
8310              Object_Definition   => New_Occurrence_Of (Typ, Loc));
8311
8312          Set_No_Initialization (Decl);
8313
8314          Insert_Actions (N, New_List (
8315            Decl,
8316            Make_Assignment_Statement (Loc,
8317              Name => New_Occurrence_Of (Ent, Loc),
8318              Expression => Relocate_Node (N))));
8319
8320          Rewrite (N, New_Occurrence_Of (Ent, Loc));
8321          Analyze_And_Resolve (N, Typ);
8322       end Make_Temporary_For_Slice;
8323
8324    --  Start of processing for Expand_N_Slice
8325
8326    begin
8327       --  Special handling for access types
8328
8329       if Is_Access_Type (Ptp) then
8330
8331          Ptp := Designated_Type (Ptp);
8332
8333          Rewrite (Pfx,
8334            Make_Explicit_Dereference (Sloc (N),
8335             Prefix => Relocate_Node (Pfx)));
8336
8337          Analyze_And_Resolve (Pfx, Ptp);
8338       end if;
8339
8340       --  Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
8341       --  function, then additional actuals must be passed.
8342
8343       if Ada_Version >= Ada_2005
8344         and then Is_Build_In_Place_Function_Call (Pfx)
8345       then
8346          Make_Build_In_Place_Call_In_Anonymous_Context (Pfx);
8347       end if;
8348
8349       --  The remaining case to be handled is packed slices. We can leave
8350       --  packed slices as they are in the following situations:
8351
8352       --    1. Right or left side of an assignment (we can handle this
8353       --       situation correctly in the assignment statement expansion).
8354
8355       --    2. Prefix of indexed component (the slide is optimized away in this
8356       --       case, see the start of Expand_N_Slice.)
8357
8358       --    3. Object renaming declaration, since we want the name of the
8359       --       slice, not the value.
8360
8361       --    4. Argument to procedure call, since copy-in/copy-out handling may
8362       --       be required, and this is handled in the expansion of call
8363       --       itself.
8364
8365       --    5. Prefix of an address attribute (this is an error which is caught
8366       --       elsewhere, and the expansion would interfere with generating the
8367       --       error message).
8368
8369       if not Is_Packed (Typ) then
8370
8371          --  Apply transformation for actuals of a function call, where
8372          --  Expand_Actuals is not used.
8373
8374          if Nkind (Parent (N)) = N_Function_Call
8375            and then Is_Possibly_Unaligned_Slice (N)
8376          then
8377             Make_Temporary_For_Slice;
8378          end if;
8379
8380       elsif Nkind (Parent (N)) = N_Assignment_Statement
8381         or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
8382                    and then Parent (N) = Name (Parent (Parent (N))))
8383       then
8384          return;
8385
8386       elsif Nkind (Parent (N)) = N_Indexed_Component
8387         or else Is_Renamed_Object (N)
8388         or else Is_Procedure_Actual (N)
8389       then
8390          return;
8391
8392       elsif Nkind (Parent (N)) = N_Attribute_Reference
8393         and then Attribute_Name (Parent (N)) = Name_Address
8394       then
8395          return;
8396
8397       else
8398          Make_Temporary_For_Slice;
8399       end if;
8400    end Expand_N_Slice;
8401
8402    ------------------------------
8403    -- Expand_N_Type_Conversion --
8404    ------------------------------
8405
8406    procedure Expand_N_Type_Conversion (N : Node_Id) is
8407       Loc          : constant Source_Ptr := Sloc (N);
8408       Operand      : constant Node_Id    := Expression (N);
8409       Target_Type  : constant Entity_Id  := Etype (N);
8410       Operand_Type : Entity_Id           := Etype (Operand);
8411
8412       procedure Handle_Changed_Representation;
8413       --  This is called in the case of record and array type conversions to
8414       --  see if there is a change of representation to be handled. Change of
8415       --  representation is actually handled at the assignment statement level,
8416       --  and what this procedure does is rewrite node N conversion as an
8417       --  assignment to temporary. If there is no change of representation,
8418       --  then the conversion node is unchanged.
8419
8420       procedure Raise_Accessibility_Error;
8421       --  Called when we know that an accessibility check will fail. Rewrites
8422       --  node N to an appropriate raise statement and outputs warning msgs.
8423       --  The Etype of the raise node is set to Target_Type.
8424
8425       procedure Real_Range_Check;
8426       --  Handles generation of range check for real target value
8427
8428       function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
8429       --  True iff Present (Effective_Extra_Accessibility (Id)) successfully
8430       --  evaluates to True.
8431
8432       -----------------------------------
8433       -- Handle_Changed_Representation --
8434       -----------------------------------
8435
8436       procedure Handle_Changed_Representation is
8437          Temp : Entity_Id;
8438          Decl : Node_Id;
8439          Odef : Node_Id;
8440          Disc : Node_Id;
8441          N_Ix : Node_Id;
8442          Cons : List_Id;
8443
8444       begin
8445          --  Nothing else to do if no change of representation
8446
8447          if Same_Representation (Operand_Type, Target_Type) then
8448             return;
8449
8450          --  The real change of representation work is done by the assignment
8451          --  statement processing. So if this type conversion is appearing as
8452          --  the expression of an assignment statement, nothing needs to be
8453          --  done to the conversion.
8454
8455          elsif Nkind (Parent (N)) = N_Assignment_Statement then
8456             return;
8457
8458          --  Otherwise we need to generate a temporary variable, and do the
8459          --  change of representation assignment into that temporary variable.
8460          --  The conversion is then replaced by a reference to this variable.
8461
8462          else
8463             Cons := No_List;
8464
8465             --  If type is unconstrained we have to add a constraint, copied
8466             --  from the actual value of the left hand side.
8467
8468             if not Is_Constrained (Target_Type) then
8469                if Has_Discriminants (Operand_Type) then
8470                   Disc := First_Discriminant (Operand_Type);
8471
8472                   if Disc /= First_Stored_Discriminant (Operand_Type) then
8473                      Disc := First_Stored_Discriminant (Operand_Type);
8474                   end if;
8475
8476                   Cons := New_List;
8477                   while Present (Disc) loop
8478                      Append_To (Cons,
8479                        Make_Selected_Component (Loc,
8480                          Prefix        =>
8481                            Duplicate_Subexpr_Move_Checks (Operand),
8482                          Selector_Name =>
8483                            Make_Identifier (Loc, Chars (Disc))));
8484                      Next_Discriminant (Disc);
8485                   end loop;
8486
8487                elsif Is_Array_Type (Operand_Type) then
8488                   N_Ix := First_Index (Target_Type);
8489                   Cons := New_List;
8490
8491                   for J in 1 .. Number_Dimensions (Operand_Type) loop
8492
8493                      --  We convert the bounds explicitly. We use an unchecked
8494                      --  conversion because bounds checks are done elsewhere.
8495
8496                      Append_To (Cons,
8497                        Make_Range (Loc,
8498                          Low_Bound =>
8499                            Unchecked_Convert_To (Etype (N_Ix),
8500                              Make_Attribute_Reference (Loc,
8501                                Prefix =>
8502                                  Duplicate_Subexpr_No_Checks
8503                                    (Operand, Name_Req => True),
8504                                Attribute_Name => Name_First,
8505                                Expressions    => New_List (
8506                                  Make_Integer_Literal (Loc, J)))),
8507
8508                          High_Bound =>
8509                            Unchecked_Convert_To (Etype (N_Ix),
8510                              Make_Attribute_Reference (Loc,
8511                                Prefix =>
8512                                  Duplicate_Subexpr_No_Checks
8513                                    (Operand, Name_Req => True),
8514                                Attribute_Name => Name_Last,
8515                                Expressions    => New_List (
8516                                  Make_Integer_Literal (Loc, J))))));
8517
8518                      Next_Index (N_Ix);
8519                   end loop;
8520                end if;
8521             end if;
8522
8523             Odef := New_Occurrence_Of (Target_Type, Loc);
8524
8525             if Present (Cons) then
8526                Odef :=
8527                  Make_Subtype_Indication (Loc,
8528                    Subtype_Mark => Odef,
8529                    Constraint =>
8530                      Make_Index_Or_Discriminant_Constraint (Loc,
8531                        Constraints => Cons));
8532             end if;
8533
8534             Temp := Make_Temporary (Loc, 'C');
8535             Decl :=
8536               Make_Object_Declaration (Loc,
8537                 Defining_Identifier => Temp,
8538                 Object_Definition   => Odef);
8539
8540             Set_No_Initialization (Decl, True);
8541
8542             --  Insert required actions. It is essential to suppress checks
8543             --  since we have suppressed default initialization, which means
8544             --  that the variable we create may have no discriminants.
8545
8546             Insert_Actions (N,
8547               New_List (
8548                 Decl,
8549                 Make_Assignment_Statement (Loc,
8550                   Name => New_Occurrence_Of (Temp, Loc),
8551                   Expression => Relocate_Node (N))),
8552                 Suppress => All_Checks);
8553
8554             Rewrite (N, New_Occurrence_Of (Temp, Loc));
8555             return;
8556          end if;
8557       end Handle_Changed_Representation;
8558
8559       -------------------------------
8560       -- Raise_Accessibility_Error --
8561       -------------------------------
8562
8563       procedure Raise_Accessibility_Error is
8564       begin
8565          Rewrite (N,
8566            Make_Raise_Program_Error (Sloc (N),
8567              Reason => PE_Accessibility_Check_Failed));
8568          Set_Etype (N, Target_Type);
8569
8570          Error_Msg_N ("?accessibility check failure", N);
8571          Error_Msg_NE
8572            ("\?& will be raised at run time", N, Standard_Program_Error);
8573       end Raise_Accessibility_Error;
8574
8575       ----------------------
8576       -- Real_Range_Check --
8577       ----------------------
8578
8579       --  Case of conversions to floating-point or fixed-point. If range checks
8580       --  are enabled and the target type has a range constraint, we convert:
8581
8582       --     typ (x)
8583
8584       --       to
8585
8586       --     Tnn : typ'Base := typ'Base (x);
8587       --     [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
8588       --     Tnn
8589
8590       --  This is necessary when there is a conversion of integer to float or
8591       --  to fixed-point to ensure that the correct checks are made. It is not
8592       --  necessary for float to float where it is enough to simply set the
8593       --  Do_Range_Check flag.
8594
8595       procedure Real_Range_Check is
8596          Btyp : constant Entity_Id := Base_Type (Target_Type);
8597          Lo   : constant Node_Id   := Type_Low_Bound  (Target_Type);
8598          Hi   : constant Node_Id   := Type_High_Bound (Target_Type);
8599          Xtyp : constant Entity_Id := Etype (Operand);
8600          Conv : Node_Id;
8601          Tnn  : Entity_Id;
8602
8603       begin
8604          --  Nothing to do if conversion was rewritten
8605
8606          if Nkind (N) /= N_Type_Conversion then
8607             return;
8608          end if;
8609
8610          --  Nothing to do if range checks suppressed, or target has the same
8611          --  range as the base type (or is the base type).
8612
8613          if Range_Checks_Suppressed (Target_Type)
8614            or else (Lo = Type_Low_Bound (Btyp)
8615                       and then
8616                     Hi = Type_High_Bound (Btyp))
8617          then
8618             return;
8619          end if;
8620
8621          --  Nothing to do if expression is an entity on which checks have been
8622          --  suppressed.
8623
8624          if Is_Entity_Name (Operand)
8625            and then Range_Checks_Suppressed (Entity (Operand))
8626          then
8627             return;
8628          end if;
8629
8630          --  Nothing to do if bounds are all static and we can tell that the
8631          --  expression is within the bounds of the target. Note that if the
8632          --  operand is of an unconstrained floating-point type, then we do
8633          --  not trust it to be in range (might be infinite)
8634
8635          declare
8636             S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
8637             S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
8638
8639          begin
8640             if (not Is_Floating_Point_Type (Xtyp)
8641                  or else Is_Constrained (Xtyp))
8642               and then Compile_Time_Known_Value (S_Lo)
8643               and then Compile_Time_Known_Value (S_Hi)
8644               and then Compile_Time_Known_Value (Hi)
8645               and then Compile_Time_Known_Value (Lo)
8646             then
8647                declare
8648                   D_Lov : constant Ureal := Expr_Value_R (Lo);
8649                   D_Hiv : constant Ureal := Expr_Value_R (Hi);
8650                   S_Lov : Ureal;
8651                   S_Hiv : Ureal;
8652
8653                begin
8654                   if Is_Real_Type (Xtyp) then
8655                      S_Lov := Expr_Value_R (S_Lo);
8656                      S_Hiv := Expr_Value_R (S_Hi);
8657                   else
8658                      S_Lov := UR_From_Uint (Expr_Value (S_Lo));
8659                      S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
8660                   end if;
8661
8662                   if D_Hiv > D_Lov
8663                     and then S_Lov >= D_Lov
8664                     and then S_Hiv <= D_Hiv
8665                   then
8666                      Set_Do_Range_Check (Operand, False);
8667                      return;
8668                   end if;
8669                end;
8670             end if;
8671          end;
8672
8673          --  For float to float conversions, we are done
8674
8675          if Is_Floating_Point_Type (Xtyp)
8676               and then
8677             Is_Floating_Point_Type (Btyp)
8678          then
8679             return;
8680          end if;
8681
8682          --  Otherwise rewrite the conversion as described above
8683
8684          Conv := Relocate_Node (N);
8685          Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
8686          Set_Etype (Conv, Btyp);
8687
8688          --  Enable overflow except for case of integer to float conversions,
8689          --  where it is never required, since we can never have overflow in
8690          --  this case.
8691
8692          if not Is_Integer_Type (Etype (Operand)) then
8693             Enable_Overflow_Check (Conv);
8694          end if;
8695
8696          Tnn := Make_Temporary (Loc, 'T', Conv);
8697
8698          Insert_Actions (N, New_List (
8699            Make_Object_Declaration (Loc,
8700              Defining_Identifier => Tnn,
8701              Object_Definition   => New_Occurrence_Of (Btyp, Loc),
8702              Constant_Present    => True,
8703              Expression          => Conv),
8704
8705            Make_Raise_Constraint_Error (Loc,
8706              Condition =>
8707               Make_Or_Else (Loc,
8708                 Left_Opnd =>
8709                   Make_Op_Lt (Loc,
8710                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
8711                     Right_Opnd =>
8712                       Make_Attribute_Reference (Loc,
8713                         Attribute_Name => Name_First,
8714                         Prefix =>
8715                           New_Occurrence_Of (Target_Type, Loc))),
8716
8717                 Right_Opnd =>
8718                   Make_Op_Gt (Loc,
8719                     Left_Opnd  => New_Occurrence_Of (Tnn, Loc),
8720                     Right_Opnd =>
8721                       Make_Attribute_Reference (Loc,
8722                         Attribute_Name => Name_Last,
8723                         Prefix =>
8724                           New_Occurrence_Of (Target_Type, Loc)))),
8725              Reason => CE_Range_Check_Failed)));
8726
8727          Rewrite (N, New_Occurrence_Of (Tnn, Loc));
8728          Analyze_And_Resolve (N, Btyp);
8729       end Real_Range_Check;
8730
8731       -----------------------------
8732       -- Has_Extra_Accessibility --
8733       -----------------------------
8734
8735       --  Returns true for a formal of an anonymous access type or for
8736       --  an Ada 2012-style stand-alone object of an anonymous access type.
8737
8738       function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
8739       begin
8740          if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
8741             return Present (Effective_Extra_Accessibility (Id));
8742          else
8743             return False;
8744          end if;
8745       end Has_Extra_Accessibility;
8746
8747    --  Start of processing for Expand_N_Type_Conversion
8748
8749    begin
8750       --  Nothing at all to do if conversion is to the identical type so remove
8751       --  the conversion completely, it is useless, except that it may carry
8752       --  an Assignment_OK attribute, which must be propagated to the operand.
8753
8754       if Operand_Type = Target_Type then
8755          if Assignment_OK (N) then
8756             Set_Assignment_OK (Operand);
8757          end if;
8758
8759          Rewrite (N, Relocate_Node (Operand));
8760          goto Done;
8761       end if;
8762
8763       --  Nothing to do if this is the second argument of read. This is a
8764       --  "backwards" conversion that will be handled by the specialized code
8765       --  in attribute processing.
8766
8767       if Nkind (Parent (N)) = N_Attribute_Reference
8768         and then Attribute_Name (Parent (N)) = Name_Read
8769         and then Next (First (Expressions (Parent (N)))) = N
8770       then
8771          goto Done;
8772       end if;
8773
8774       --  Check for case of converting to a type that has an invariant
8775       --  associated with it. This required an invariant check. We convert
8776
8777       --    typ (expr)
8778
8779       --  into
8780
8781       --    do invariant_check (typ (expr)) in typ (expr);
8782
8783       --  using Duplicate_Subexpr to avoid multiple side effects
8784
8785       --  Note: the Comes_From_Source check, and then the resetting of this
8786       --  flag prevents what would otherwise be an infinite recursion.
8787
8788       if Has_Invariants (Target_Type)
8789         and then Present (Invariant_Procedure (Target_Type))
8790         and then Comes_From_Source (N)
8791       then
8792          Set_Comes_From_Source (N, False);
8793          Rewrite (N,
8794            Make_Expression_With_Actions (Loc,
8795              Actions    => New_List (
8796                Make_Invariant_Call (Duplicate_Subexpr (N))),
8797              Expression => Duplicate_Subexpr_No_Checks (N)));
8798          Analyze_And_Resolve (N, Target_Type);
8799          goto Done;
8800       end if;
8801
8802       --  Here if we may need to expand conversion
8803
8804       --  If the operand of the type conversion is an arithmetic operation on
8805       --  signed integers, and the based type of the signed integer type in
8806       --  question is smaller than Standard.Integer, we promote both of the
8807       --  operands to type Integer.
8808
8809       --  For example, if we have
8810
8811       --     target-type (opnd1 + opnd2)
8812
8813       --  and opnd1 and opnd2 are of type short integer, then we rewrite
8814       --  this as:
8815
8816       --     target-type (integer(opnd1) + integer(opnd2))
8817
8818       --  We do this because we are always allowed to compute in a larger type
8819       --  if we do the right thing with the result, and in this case we are
8820       --  going to do a conversion which will do an appropriate check to make
8821       --  sure that things are in range of the target type in any case. This
8822       --  avoids some unnecessary intermediate overflows.
8823
8824       --  We might consider a similar transformation in the case where the
8825       --  target is a real type or a 64-bit integer type, and the operand
8826       --  is an arithmetic operation using a 32-bit integer type. However,
8827       --  we do not bother with this case, because it could cause significant
8828       --  inefficiencies on 32-bit machines. On a 64-bit machine it would be
8829       --  much cheaper, but we don't want different behavior on 32-bit and
8830       --  64-bit machines. Note that the exclusion of the 64-bit case also
8831       --  handles the configurable run-time cases where 64-bit arithmetic
8832       --  may simply be unavailable.
8833
8834       --  Note: this circuit is partially redundant with respect to the circuit
8835       --  in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
8836       --  the processing here. Also we still need the Checks circuit, since we
8837       --  have to be sure not to generate junk overflow checks in the first
8838       --  place, since it would be trick to remove them here!
8839
8840       if Integer_Promotion_Possible (N) then
8841
8842          --  All conditions met, go ahead with transformation
8843
8844          declare
8845             Opnd : Node_Id;
8846             L, R : Node_Id;
8847
8848          begin
8849             R :=
8850               Make_Type_Conversion (Loc,
8851                 Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
8852                 Expression   => Relocate_Node (Right_Opnd (Operand)));
8853
8854             Opnd := New_Op_Node (Nkind (Operand), Loc);
8855             Set_Right_Opnd (Opnd, R);
8856
8857             if Nkind (Operand) in N_Binary_Op then
8858                L :=
8859                  Make_Type_Conversion (Loc,
8860                    Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
8861                    Expression   => Relocate_Node (Left_Opnd (Operand)));
8862
8863                Set_Left_Opnd  (Opnd, L);
8864             end if;
8865
8866             Rewrite (N,
8867               Make_Type_Conversion (Loc,
8868                 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
8869                 Expression   => Opnd));
8870
8871             Analyze_And_Resolve (N, Target_Type);
8872             goto Done;
8873          end;
8874       end if;
8875
8876       --  Do validity check if validity checking operands
8877
8878       if Validity_Checks_On
8879         and then Validity_Check_Operands
8880       then
8881          Ensure_Valid (Operand);
8882       end if;
8883
8884       --  Special case of converting from non-standard boolean type
8885
8886       if Is_Boolean_Type (Operand_Type)
8887         and then (Nonzero_Is_True (Operand_Type))
8888       then
8889          Adjust_Condition (Operand);
8890          Set_Etype (Operand, Standard_Boolean);
8891          Operand_Type := Standard_Boolean;
8892       end if;
8893
8894       --  Case of converting to an access type
8895
8896       if Is_Access_Type (Target_Type) then
8897
8898          --  Apply an accessibility check when the conversion operand is an
8899          --  access parameter (or a renaming thereof), unless conversion was
8900          --  expanded from an Unchecked_ or Unrestricted_Access attribute.
8901          --  Note that other checks may still need to be applied below (such
8902          --  as tagged type checks).
8903
8904          if Is_Entity_Name (Operand)
8905            and then Has_Extra_Accessibility (Entity (Operand))
8906            and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
8907            and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
8908                       or else Attribute_Name (Original_Node (N)) = Name_Access)
8909          then
8910             Apply_Accessibility_Check
8911               (Operand, Target_Type, Insert_Node => Operand);
8912
8913          --  If the level of the operand type is statically deeper than the
8914          --  level of the target type, then force Program_Error. Note that this
8915          --  can only occur for cases where the attribute is within the body of
8916          --  an instantiation (otherwise the conversion will already have been
8917          --  rejected as illegal). Note: warnings are issued by the analyzer
8918          --  for the instance cases.
8919
8920          elsif In_Instance_Body
8921            and then Type_Access_Level (Operand_Type) >
8922                     Type_Access_Level (Target_Type)
8923          then
8924             Raise_Accessibility_Error;
8925
8926          --  When the operand is a selected access discriminant the check needs
8927          --  to be made against the level of the object denoted by the prefix
8928          --  of the selected name. Force Program_Error for this case as well
8929          --  (this accessibility violation can only happen if within the body
8930          --  of an instantiation).
8931
8932          elsif In_Instance_Body
8933            and then Ekind (Operand_Type) = E_Anonymous_Access_Type
8934            and then Nkind (Operand) = N_Selected_Component
8935            and then Object_Access_Level (Operand) >
8936                       Type_Access_Level (Target_Type)
8937          then
8938             Raise_Accessibility_Error;
8939             goto Done;
8940          end if;
8941       end if;
8942
8943       --  Case of conversions of tagged types and access to tagged types
8944
8945       --  When needed, that is to say when the expression is class-wide, Add
8946       --  runtime a tag check for (strict) downward conversion by using the
8947       --  membership test, generating:
8948
8949       --      [constraint_error when Operand not in Target_Type'Class]
8950
8951       --  or in the access type case
8952
8953       --      [constraint_error
8954       --        when Operand /= null
8955       --          and then Operand.all not in
8956       --            Designated_Type (Target_Type)'Class]
8957
8958       if (Is_Access_Type (Target_Type)
8959            and then Is_Tagged_Type (Designated_Type (Target_Type)))
8960         or else Is_Tagged_Type (Target_Type)
8961       then
8962          --  Do not do any expansion in the access type case if the parent is a
8963          --  renaming, since this is an error situation which will be caught by
8964          --  Sem_Ch8, and the expansion can interfere with this error check.
8965
8966          if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
8967             goto Done;
8968          end if;
8969
8970          --  Otherwise, proceed with processing tagged conversion
8971
8972          Tagged_Conversion : declare
8973             Actual_Op_Typ   : Entity_Id;
8974             Actual_Targ_Typ : Entity_Id;
8975             Make_Conversion : Boolean := False;
8976             Root_Op_Typ     : Entity_Id;
8977
8978             procedure Make_Tag_Check (Targ_Typ : Entity_Id);
8979             --  Create a membership check to test whether Operand is a member
8980             --  of Targ_Typ. If the original Target_Type is an access, include
8981             --  a test for null value. The check is inserted at N.
8982
8983             --------------------
8984             -- Make_Tag_Check --
8985             --------------------
8986
8987             procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
8988                Cond : Node_Id;
8989
8990             begin
8991                --  Generate:
8992                --    [Constraint_Error
8993                --       when Operand /= null
8994                --         and then Operand.all not in Targ_Typ]
8995
8996                if Is_Access_Type (Target_Type) then
8997                   Cond :=
8998                     Make_And_Then (Loc,
8999                       Left_Opnd =>
9000                         Make_Op_Ne (Loc,
9001                           Left_Opnd  => Duplicate_Subexpr_No_Checks (Operand),
9002                           Right_Opnd => Make_Null (Loc)),
9003
9004                       Right_Opnd =>
9005                         Make_Not_In (Loc,
9006                           Left_Opnd  =>
9007                             Make_Explicit_Dereference (Loc,
9008                               Prefix => Duplicate_Subexpr_No_Checks (Operand)),
9009                           Right_Opnd => New_Reference_To (Targ_Typ, Loc)));
9010
9011                --  Generate:
9012                --    [Constraint_Error when Operand not in Targ_Typ]
9013
9014                else
9015                   Cond :=
9016                     Make_Not_In (Loc,
9017                       Left_Opnd  => Duplicate_Subexpr_No_Checks (Operand),
9018                       Right_Opnd => New_Reference_To (Targ_Typ, Loc));
9019                end if;
9020
9021                Insert_Action (N,
9022                  Make_Raise_Constraint_Error (Loc,
9023                    Condition => Cond,
9024                    Reason    => CE_Tag_Check_Failed));
9025             end Make_Tag_Check;
9026
9027          --  Start of processing for Tagged_Conversion
9028
9029          begin
9030             --  Handle entities from the limited view
9031
9032             if Is_Access_Type (Operand_Type) then
9033                Actual_Op_Typ :=
9034                  Available_View (Designated_Type (Operand_Type));
9035             else
9036                Actual_Op_Typ := Operand_Type;
9037             end if;
9038
9039             if Is_Access_Type (Target_Type) then
9040                Actual_Targ_Typ :=
9041                  Available_View (Designated_Type (Target_Type));
9042             else
9043                Actual_Targ_Typ := Target_Type;
9044             end if;
9045
9046             Root_Op_Typ := Root_Type (Actual_Op_Typ);
9047
9048             --  Ada 2005 (AI-251): Handle interface type conversion
9049
9050             if Is_Interface (Actual_Op_Typ) then
9051                Expand_Interface_Conversion (N, Is_Static => False);
9052                goto Done;
9053             end if;
9054
9055             if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
9056
9057                --  Create a runtime tag check for a downward class-wide type
9058                --  conversion.
9059
9060                if Is_Class_Wide_Type (Actual_Op_Typ)
9061                  and then Actual_Op_Typ /= Actual_Targ_Typ
9062                  and then Root_Op_Typ /= Actual_Targ_Typ
9063                  and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
9064                                        Use_Full_View => True)
9065                then
9066                   Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
9067                   Make_Conversion := True;
9068                end if;
9069
9070                --  AI05-0073: If the result subtype of the function is defined
9071                --  by an access_definition designating a specific tagged type
9072                --  T, a check is made that the result value is null or the tag
9073                --  of the object designated by the result value identifies T.
9074                --  Constraint_Error is raised if this check fails.
9075
9076                if Nkind (Parent (N)) = Sinfo.N_Return_Statement then
9077                   declare
9078                      Func     : Entity_Id;
9079                      Func_Typ : Entity_Id;
9080
9081                   begin
9082                      --  Climb scope stack looking for the enclosing function
9083
9084                      Func := Current_Scope;
9085                      while Present (Func)
9086                        and then Ekind (Func) /= E_Function
9087                      loop
9088                         Func := Scope (Func);
9089                      end loop;
9090
9091                      --  The function's return subtype must be defined using
9092                      --  an access definition.
9093
9094                      if Nkind (Result_Definition (Parent (Func))) =
9095                           N_Access_Definition
9096                      then
9097                         Func_Typ := Directly_Designated_Type (Etype (Func));
9098
9099                         --  The return subtype denotes a specific tagged type,
9100                         --  in other words, a non class-wide type.
9101
9102                         if Is_Tagged_Type (Func_Typ)
9103                           and then not Is_Class_Wide_Type (Func_Typ)
9104                         then
9105                            Make_Tag_Check (Actual_Targ_Typ);
9106                            Make_Conversion := True;
9107                         end if;
9108                      end if;
9109                   end;
9110                end if;
9111
9112                --  We have generated a tag check for either a class-wide type
9113                --  conversion or for AI05-0073.
9114
9115                if Make_Conversion then
9116                   declare
9117                      Conv : Node_Id;
9118                   begin
9119                      Conv :=
9120                        Make_Unchecked_Type_Conversion (Loc,
9121                          Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
9122                          Expression   => Relocate_Node (Expression (N)));
9123                      Rewrite (N, Conv);
9124                      Analyze_And_Resolve (N, Target_Type);
9125                   end;
9126                end if;
9127             end if;
9128          end Tagged_Conversion;
9129
9130       --  Case of other access type conversions
9131
9132       elsif Is_Access_Type (Target_Type) then
9133          Apply_Constraint_Check (Operand, Target_Type);
9134
9135       --  Case of conversions from a fixed-point type
9136
9137       --  These conversions require special expansion and processing, found in
9138       --  the Exp_Fixd package. We ignore cases where Conversion_OK is set,
9139       --  since from a semantic point of view, these are simple integer
9140       --  conversions, which do not need further processing.
9141
9142       elsif Is_Fixed_Point_Type (Operand_Type)
9143         and then not Conversion_OK (N)
9144       then
9145          --  We should never see universal fixed at this case, since the
9146          --  expansion of the constituent divide or multiply should have
9147          --  eliminated the explicit mention of universal fixed.
9148
9149          pragma Assert (Operand_Type /= Universal_Fixed);
9150
9151          --  Check for special case of the conversion to universal real that
9152          --  occurs as a result of the use of a round attribute. In this case,
9153          --  the real type for the conversion is taken from the target type of
9154          --  the Round attribute and the result must be marked as rounded.
9155
9156          if Target_Type = Universal_Real
9157            and then Nkind (Parent (N)) = N_Attribute_Reference
9158            and then Attribute_Name (Parent (N)) = Name_Round
9159          then
9160             Set_Rounded_Result (N);
9161             Set_Etype (N, Etype (Parent (N)));
9162          end if;
9163
9164          --  Otherwise do correct fixed-conversion, but skip these if the
9165          --  Conversion_OK flag is set, because from a semantic point of view
9166          --  these are simple integer conversions needing no further processing
9167          --  (the backend will simply treat them as integers).
9168
9169          if not Conversion_OK (N) then
9170             if Is_Fixed_Point_Type (Etype (N)) then
9171                Expand_Convert_Fixed_To_Fixed (N);
9172                Real_Range_Check;
9173
9174             elsif Is_Integer_Type (Etype (N)) then
9175                Expand_Convert_Fixed_To_Integer (N);
9176
9177             else
9178                pragma Assert (Is_Floating_Point_Type (Etype (N)));
9179                Expand_Convert_Fixed_To_Float (N);
9180                Real_Range_Check;
9181             end if;
9182          end if;
9183
9184       --  Case of conversions to a fixed-point type
9185
9186       --  These conversions require special expansion and processing, found in
9187       --  the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
9188       --  since from a semantic point of view, these are simple integer
9189       --  conversions, which do not need further processing.
9190
9191       elsif Is_Fixed_Point_Type (Target_Type)
9192         and then not Conversion_OK (N)
9193       then
9194          if Is_Integer_Type (Operand_Type) then
9195             Expand_Convert_Integer_To_Fixed (N);
9196             Real_Range_Check;
9197          else
9198             pragma Assert (Is_Floating_Point_Type (Operand_Type));
9199             Expand_Convert_Float_To_Fixed (N);
9200             Real_Range_Check;
9201          end if;
9202
9203       --  Case of float-to-integer conversions
9204
9205       --  We also handle float-to-fixed conversions with Conversion_OK set
9206       --  since semantically the fixed-point target is treated as though it
9207       --  were an integer in such cases.
9208
9209       elsif Is_Floating_Point_Type (Operand_Type)
9210         and then
9211           (Is_Integer_Type (Target_Type)
9212             or else
9213           (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
9214       then
9215          --  One more check here, gcc is still not able to do conversions of
9216          --  this type with proper overflow checking, and so gigi is doing an
9217          --  approximation of what is required by doing floating-point compares
9218          --  with the end-point. But that can lose precision in some cases, and
9219          --  give a wrong result. Converting the operand to Universal_Real is
9220          --  helpful, but still does not catch all cases with 64-bit integers
9221          --  on targets with only 64-bit floats.
9222
9223          --  The above comment seems obsoleted by Apply_Float_Conversion_Check
9224          --  Can this code be removed ???
9225
9226          if Do_Range_Check (Operand) then
9227             Rewrite (Operand,
9228               Make_Type_Conversion (Loc,
9229                 Subtype_Mark =>
9230                   New_Occurrence_Of (Universal_Real, Loc),
9231                 Expression =>
9232                   Relocate_Node (Operand)));
9233
9234             Set_Etype (Operand, Universal_Real);
9235             Enable_Range_Check (Operand);
9236             Set_Do_Range_Check (Expression (Operand), False);
9237          end if;
9238
9239       --  Case of array conversions
9240
9241       --  Expansion of array conversions, add required length/range checks but
9242       --  only do this if there is no change of representation. For handling of
9243       --  this case, see Handle_Changed_Representation.
9244
9245       elsif Is_Array_Type (Target_Type) then
9246          if Is_Constrained (Target_Type) then
9247             Apply_Length_Check (Operand, Target_Type);
9248          else
9249             Apply_Range_Check (Operand, Target_Type);
9250          end if;
9251
9252          Handle_Changed_Representation;
9253
9254       --  Case of conversions of discriminated types
9255
9256       --  Add required discriminant checks if target is constrained. Again this
9257       --  change is skipped if we have a change of representation.
9258
9259       elsif Has_Discriminants (Target_Type)
9260         and then Is_Constrained (Target_Type)
9261       then
9262          Apply_Discriminant_Check (Operand, Target_Type);
9263          Handle_Changed_Representation;
9264
9265       --  Case of all other record conversions. The only processing required
9266       --  is to check for a change of representation requiring the special
9267       --  assignment processing.
9268
9269       elsif Is_Record_Type (Target_Type) then
9270
9271          --  Ada 2005 (AI-216): Program_Error is raised when converting from
9272          --  a derived Unchecked_Union type to an unconstrained type that is
9273          --  not Unchecked_Union if the operand lacks inferable discriminants.
9274
9275          if Is_Derived_Type (Operand_Type)
9276            and then Is_Unchecked_Union (Base_Type (Operand_Type))
9277            and then not Is_Constrained (Target_Type)
9278            and then not Is_Unchecked_Union (Base_Type (Target_Type))
9279            and then not Has_Inferable_Discriminants (Operand)
9280          then
9281             --  To prevent Gigi from generating illegal code, we generate a
9282             --  Program_Error node, but we give it the target type of the
9283             --  conversion.
9284
9285             declare
9286                PE : constant Node_Id := Make_Raise_Program_Error (Loc,
9287                       Reason => PE_Unchecked_Union_Restriction);
9288
9289             begin
9290                Set_Etype (PE, Target_Type);
9291                Rewrite (N, PE);
9292
9293             end;
9294          else
9295             Handle_Changed_Representation;
9296          end if;
9297
9298       --  Case of conversions of enumeration types
9299
9300       elsif Is_Enumeration_Type (Target_Type) then
9301
9302          --  Special processing is required if there is a change of
9303          --  representation (from enumeration representation clauses).
9304
9305          if not Same_Representation (Target_Type, Operand_Type) then
9306
9307             --  Convert: x(y) to x'val (ytyp'val (y))
9308
9309             Rewrite (N,
9310                Make_Attribute_Reference (Loc,
9311                  Prefix => New_Occurrence_Of (Target_Type, Loc),
9312                  Attribute_Name => Name_Val,
9313                  Expressions => New_List (
9314                    Make_Attribute_Reference (Loc,
9315                      Prefix => New_Occurrence_Of (Operand_Type, Loc),
9316                      Attribute_Name => Name_Pos,
9317                      Expressions => New_List (Operand)))));
9318
9319             Analyze_And_Resolve (N, Target_Type);
9320          end if;
9321
9322       --  Case of conversions to floating-point
9323
9324       elsif Is_Floating_Point_Type (Target_Type) then
9325          Real_Range_Check;
9326       end if;
9327
9328       --  At this stage, either the conversion node has been transformed into
9329       --  some other equivalent expression, or left as a conversion that can be
9330       --  handled by Gigi, in the following cases:
9331
9332       --    Conversions with no change of representation or type
9333
9334       --    Numeric conversions involving integer, floating- and fixed-point
9335       --    values. Fixed-point values are allowed only if Conversion_OK is
9336       --    set, i.e. if the fixed-point values are to be treated as integers.
9337
9338       --  No other conversions should be passed to Gigi
9339
9340       --  Check: are these rules stated in sinfo??? if so, why restate here???
9341
9342       --  The only remaining step is to generate a range check if we still have
9343       --  a type conversion at this stage and Do_Range_Check is set. For now we
9344       --  do this only for conversions of discrete types.
9345
9346       if Nkind (N) = N_Type_Conversion
9347         and then Is_Discrete_Type (Etype (N))
9348       then
9349          declare
9350             Expr : constant Node_Id := Expression (N);
9351             Ftyp : Entity_Id;
9352             Ityp : Entity_Id;
9353
9354          begin
9355             if Do_Range_Check (Expr)
9356               and then Is_Discrete_Type (Etype (Expr))
9357             then
9358                Set_Do_Range_Check (Expr, False);
9359
9360                --  Before we do a range check, we have to deal with treating a
9361                --  fixed-point operand as an integer. The way we do this is
9362                --  simply to do an unchecked conversion to an appropriate
9363                --  integer type large enough to hold the result.
9364
9365                --  This code is not active yet, because we are only dealing
9366                --  with discrete types so far ???
9367
9368                if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
9369                  and then Treat_Fixed_As_Integer (Expr)
9370                then
9371                   Ftyp := Base_Type (Etype (Expr));
9372
9373                   if Esize (Ftyp) >= Esize (Standard_Integer) then
9374                      Ityp := Standard_Long_Long_Integer;
9375                   else
9376                      Ityp := Standard_Integer;
9377                   end if;
9378
9379                   Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
9380                end if;
9381
9382                --  Reset overflow flag, since the range check will include
9383                --  dealing with possible overflow, and generate the check. If
9384                --  Address is either a source type or target type, suppress
9385                --  range check to avoid typing anomalies when it is a visible
9386                --  integer type.
9387
9388                Set_Do_Overflow_Check (N, False);
9389                if not Is_Descendent_Of_Address (Etype (Expr))
9390                  and then not Is_Descendent_Of_Address (Target_Type)
9391                then
9392                   Generate_Range_Check
9393                     (Expr, Target_Type, CE_Range_Check_Failed);
9394                end if;
9395             end if;
9396          end;
9397       end if;
9398
9399       --  Final step, if the result is a type conversion involving Vax_Float
9400       --  types, then it is subject for further special processing.
9401
9402       if Nkind (N) = N_Type_Conversion
9403         and then (Vax_Float (Operand_Type) or else Vax_Float (Target_Type))
9404       then
9405          Expand_Vax_Conversion (N);
9406          goto Done;
9407       end if;
9408
9409       --  Here at end of processing
9410
9411    <<Done>>
9412       --  Apply predicate check if required. Note that we can't just call
9413       --  Apply_Predicate_Check here, because the type looks right after
9414       --  the conversion and it would omit the check. The Comes_From_Source
9415       --  guard is necessary to prevent infinite recursions when we generate
9416       --  internal conversions for the purpose of checking predicates.
9417
9418       if Present (Predicate_Function (Target_Type))
9419         and then Target_Type /= Operand_Type
9420         and then Comes_From_Source (N)
9421       then
9422          declare
9423             New_Expr : constant Node_Id := Duplicate_Subexpr (N);
9424
9425          begin
9426             --  Avoid infinite recursion on the subsequent expansion of
9427             --  of the copy of the original type conversion.
9428
9429             Set_Comes_From_Source (New_Expr, False);
9430             Insert_Action (N, Make_Predicate_Check (Target_Type, New_Expr));
9431          end;
9432       end if;
9433    end Expand_N_Type_Conversion;
9434
9435    -----------------------------------
9436    -- Expand_N_Unchecked_Expression --
9437    -----------------------------------
9438
9439    --  Remove the unchecked expression node from the tree. Its job was simply
9440    --  to make sure that its constituent expression was handled with checks
9441    --  off, and now that that is done, we can remove it from the tree, and
9442    --  indeed must, since Gigi does not expect to see these nodes.
9443
9444    procedure Expand_N_Unchecked_Expression (N : Node_Id) is
9445       Exp : constant Node_Id := Expression (N);
9446    begin
9447       Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
9448       Rewrite (N, Exp);
9449    end Expand_N_Unchecked_Expression;
9450
9451    ----------------------------------------
9452    -- Expand_N_Unchecked_Type_Conversion --
9453    ----------------------------------------
9454
9455    --  If this cannot be handled by Gigi and we haven't already made a
9456    --  temporary for it, do it now.
9457
9458    procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
9459       Target_Type  : constant Entity_Id := Etype (N);
9460       Operand      : constant Node_Id   := Expression (N);
9461       Operand_Type : constant Entity_Id := Etype (Operand);
9462
9463    begin
9464       --  Nothing at all to do if conversion is to the identical type so remove
9465       --  the conversion completely, it is useless, except that it may carry
9466       --  an Assignment_OK indication which must be propagated to the operand.
9467
9468       if Operand_Type = Target_Type then
9469
9470          --  Code duplicates Expand_N_Unchecked_Expression above, factor???
9471
9472          if Assignment_OK (N) then
9473             Set_Assignment_OK (Operand);
9474          end if;
9475
9476          Rewrite (N, Relocate_Node (Operand));
9477          return;
9478       end if;
9479
9480       --  If we have a conversion of a compile time known value to a target
9481       --  type and the value is in range of the target type, then we can simply
9482       --  replace the construct by an integer literal of the correct type. We
9483       --  only apply this to integer types being converted. Possibly it may
9484       --  apply in other cases, but it is too much trouble to worry about.
9485
9486       --  Note that we do not do this transformation if the Kill_Range_Check
9487       --  flag is set, since then the value may be outside the expected range.
9488       --  This happens in the Normalize_Scalars case.
9489
9490       --  We also skip this if either the target or operand type is biased
9491       --  because in this case, the unchecked conversion is supposed to
9492       --  preserve the bit pattern, not the integer value.
9493
9494       if Is_Integer_Type (Target_Type)
9495         and then not Has_Biased_Representation (Target_Type)
9496         and then Is_Integer_Type (Operand_Type)
9497         and then not Has_Biased_Representation (Operand_Type)
9498         and then Compile_Time_Known_Value (Operand)
9499         and then not Kill_Range_Check (N)
9500       then
9501          declare
9502             Val : constant Uint := Expr_Value (Operand);
9503
9504          begin
9505             if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
9506                  and then
9507                Compile_Time_Known_Value (Type_High_Bound (Target_Type))
9508                  and then
9509                Val >= Expr_Value (Type_Low_Bound (Target_Type))
9510                  and then
9511                Val <= Expr_Value (Type_High_Bound (Target_Type))
9512             then
9513                Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
9514
9515                --  If Address is the target type, just set the type to avoid a
9516                --  spurious type error on the literal when Address is a visible
9517                --  integer type.
9518
9519                if Is_Descendent_Of_Address (Target_Type) then
9520                   Set_Etype (N, Target_Type);
9521                else
9522                   Analyze_And_Resolve (N, Target_Type);
9523                end if;
9524
9525                return;
9526             end if;
9527          end;
9528       end if;
9529
9530       --  Nothing to do if conversion is safe
9531
9532       if Safe_Unchecked_Type_Conversion (N) then
9533          return;
9534       end if;
9535
9536       --  Otherwise force evaluation unless Assignment_OK flag is set (this
9537       --  flag indicates ??? -- more comments needed here)
9538
9539       if Assignment_OK (N) then
9540          null;
9541       else
9542          Force_Evaluation (N);
9543       end if;
9544    end Expand_N_Unchecked_Type_Conversion;
9545
9546    ----------------------------
9547    -- Expand_Record_Equality --
9548    ----------------------------
9549
9550    --  For non-variant records, Equality is expanded when needed into:
9551
9552    --      and then Lhs.Discr1 = Rhs.Discr1
9553    --      and then ...
9554    --      and then Lhs.Discrn = Rhs.Discrn
9555    --      and then Lhs.Cmp1 = Rhs.Cmp1
9556    --      and then ...
9557    --      and then Lhs.Cmpn = Rhs.Cmpn
9558
9559    --  The expression is folded by the back-end for adjacent fields. This
9560    --  function is called for tagged record in only one occasion: for imple-
9561    --  menting predefined primitive equality (see Predefined_Primitives_Bodies)
9562    --  otherwise the primitive "=" is used directly.
9563
9564    function Expand_Record_Equality
9565      (Nod    : Node_Id;
9566       Typ    : Entity_Id;
9567       Lhs    : Node_Id;
9568       Rhs    : Node_Id;
9569       Bodies : List_Id) return Node_Id
9570    is
9571       Loc : constant Source_Ptr := Sloc (Nod);
9572
9573       Result : Node_Id;
9574       C      : Entity_Id;
9575
9576       First_Time : Boolean := True;
9577
9578       function Suitable_Element (C : Entity_Id) return Entity_Id;
9579       --  Return the first field to compare beginning with C, skipping the
9580       --  inherited components.
9581
9582       ----------------------
9583       -- Suitable_Element --
9584       ----------------------
9585
9586       function Suitable_Element (C : Entity_Id) return Entity_Id is
9587       begin
9588          if No (C) then
9589             return Empty;
9590
9591          elsif Ekind (C) /= E_Discriminant
9592            and then Ekind (C) /= E_Component
9593          then
9594             return Suitable_Element (Next_Entity (C));
9595
9596          elsif Is_Tagged_Type (Typ)
9597            and then C /= Original_Record_Component (C)
9598          then
9599             return Suitable_Element (Next_Entity (C));
9600
9601          elsif Chars (C) = Name_uTag then
9602             return Suitable_Element (Next_Entity (C));
9603
9604          --  The .NET/JVM version of type Root_Controlled contains two fields
9605          --  which should not be considered part of the object. To achieve
9606          --  proper equiality between two controlled objects on .NET/JVM, skip
9607          --  field _parent whenever it is of type Root_Controlled.
9608
9609          elsif Chars (C) = Name_uParent
9610            and then VM_Target /= No_VM
9611            and then Etype (C) = RTE (RE_Root_Controlled)
9612          then
9613             return Suitable_Element (Next_Entity (C));
9614
9615          elsif Is_Interface (Etype (C)) then
9616             return Suitable_Element (Next_Entity (C));
9617
9618          else
9619             return C;
9620          end if;
9621       end Suitable_Element;
9622
9623    --  Start of processing for Expand_Record_Equality
9624
9625    begin
9626       --  Generates the following code: (assuming that Typ has one Discr and
9627       --  component C2 is also a record)
9628
9629       --   True
9630       --     and then Lhs.Discr1 = Rhs.Discr1
9631       --     and then Lhs.C1 = Rhs.C1
9632       --     and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
9633       --     and then ...
9634       --     and then Lhs.Cmpn = Rhs.Cmpn
9635
9636       Result := New_Reference_To (Standard_True, Loc);
9637       C := Suitable_Element (First_Entity (Typ));
9638       while Present (C) loop
9639          declare
9640             New_Lhs : Node_Id;
9641             New_Rhs : Node_Id;
9642             Check   : Node_Id;
9643
9644          begin
9645             if First_Time then
9646                First_Time := False;
9647                New_Lhs := Lhs;
9648                New_Rhs := Rhs;
9649             else
9650                New_Lhs := New_Copy_Tree (Lhs);
9651                New_Rhs := New_Copy_Tree (Rhs);
9652             end if;
9653
9654             Check :=
9655               Expand_Composite_Equality (Nod, Etype (C),
9656                Lhs =>
9657                  Make_Selected_Component (Loc,
9658                    Prefix => New_Lhs,
9659                    Selector_Name => New_Reference_To (C, Loc)),
9660                Rhs =>
9661                  Make_Selected_Component (Loc,
9662                    Prefix => New_Rhs,
9663                    Selector_Name => New_Reference_To (C, Loc)),
9664                Bodies => Bodies);
9665
9666             --  If some (sub)component is an unchecked_union, the whole
9667             --  operation will raise program error.
9668
9669             if Nkind (Check) = N_Raise_Program_Error then
9670                Result := Check;
9671                Set_Etype (Result, Standard_Boolean);
9672                exit;
9673             else
9674                Result :=
9675                  Make_And_Then (Loc,
9676                    Left_Opnd  => Result,
9677                    Right_Opnd => Check);
9678             end if;
9679          end;
9680
9681          C := Suitable_Element (Next_Entity (C));
9682       end loop;
9683
9684       return Result;
9685    end Expand_Record_Equality;
9686
9687    ---------------------------
9688    -- Expand_Set_Membership --
9689    ---------------------------
9690
9691    procedure Expand_Set_Membership (N : Node_Id) is
9692       Lop : constant Node_Id := Left_Opnd (N);
9693       Alt : Node_Id;
9694       Res : Node_Id;
9695
9696       function Make_Cond (Alt : Node_Id) return Node_Id;
9697       --  If the alternative is a subtype mark, create a simple membership
9698       --  test. Otherwise create an equality test for it.
9699
9700       ---------------
9701       -- Make_Cond --
9702       ---------------
9703
9704       function Make_Cond (Alt : Node_Id) return Node_Id is
9705          Cond : Node_Id;
9706          L    : constant Node_Id := New_Copy (Lop);
9707          R    : constant Node_Id := Relocate_Node (Alt);
9708
9709       begin
9710          if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
9711            or else Nkind (Alt) = N_Range
9712          then
9713             Cond :=
9714               Make_In (Sloc (Alt),
9715                 Left_Opnd  => L,
9716                 Right_Opnd => R);
9717          else
9718             Cond :=
9719               Make_Op_Eq (Sloc (Alt),
9720                 Left_Opnd  => L,
9721                 Right_Opnd => R);
9722          end if;
9723
9724          return Cond;
9725       end Make_Cond;
9726
9727    --  Start of processing for Expand_Set_Membership
9728
9729    begin
9730       Remove_Side_Effects (Lop);
9731
9732       Alt := Last (Alternatives (N));
9733       Res := Make_Cond (Alt);
9734
9735       Prev (Alt);
9736       while Present (Alt) loop
9737          Res :=
9738            Make_Or_Else (Sloc (Alt),
9739              Left_Opnd  => Make_Cond (Alt),
9740              Right_Opnd => Res);
9741          Prev (Alt);
9742       end loop;
9743
9744       Rewrite (N, Res);
9745       Analyze_And_Resolve (N, Standard_Boolean);
9746    end Expand_Set_Membership;
9747
9748    -----------------------------------
9749    -- Expand_Short_Circuit_Operator --
9750    -----------------------------------
9751
9752    --  Deal with special expansion if actions are present for the right operand
9753    --  and deal with optimizing case of arguments being True or False. We also
9754    --  deal with the special case of non-standard boolean values.
9755
9756    procedure Expand_Short_Circuit_Operator (N : Node_Id) is
9757       Loc     : constant Source_Ptr := Sloc (N);
9758       Typ     : constant Entity_Id  := Etype (N);
9759       Left    : constant Node_Id    := Left_Opnd (N);
9760       Right   : constant Node_Id    := Right_Opnd (N);
9761       LocR    : constant Source_Ptr := Sloc (Right);
9762       Actlist : List_Id;
9763
9764       Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
9765       Shortcut_Ent   : constant Entity_Id := Boolean_Literals (Shortcut_Value);
9766       --  If Left = Shortcut_Value then Right need not be evaluated
9767
9768       function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
9769       --  For Opnd a boolean expression, return a Boolean expression equivalent
9770       --  to Opnd /= Shortcut_Value.
9771
9772       --------------------
9773       -- Make_Test_Expr --
9774       --------------------
9775
9776       function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
9777       begin
9778          if Shortcut_Value then
9779             return Make_Op_Not (Sloc (Opnd), Opnd);
9780          else
9781             return Opnd;
9782          end if;
9783       end Make_Test_Expr;
9784
9785       Op_Var : Entity_Id;
9786       --  Entity for a temporary variable holding the value of the operator,
9787       --  used for expansion in the case where actions are present.
9788
9789    --  Start of processing for Expand_Short_Circuit_Operator
9790
9791    begin
9792       --  Deal with non-standard booleans
9793
9794       if Is_Boolean_Type (Typ) then
9795          Adjust_Condition (Left);
9796          Adjust_Condition (Right);
9797          Set_Etype (N, Standard_Boolean);
9798       end if;
9799
9800       --  Check for cases where left argument is known to be True or False
9801
9802       if Compile_Time_Known_Value (Left) then
9803
9804          --  Mark SCO for left condition as compile time known
9805
9806          if Generate_SCO and then Comes_From_Source (Left) then
9807             Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
9808          end if;
9809
9810          --  Rewrite True AND THEN Right / False OR ELSE Right to Right.
9811          --  Any actions associated with Right will be executed unconditionally
9812          --  and can thus be inserted into the tree unconditionally.
9813
9814          if Expr_Value_E (Left) /= Shortcut_Ent then
9815             if Present (Actions (N)) then
9816                Insert_Actions (N, Actions (N));
9817             end if;
9818
9819             Rewrite (N, Right);
9820
9821          --  Rewrite False AND THEN Right / True OR ELSE Right to Left.
9822          --  In this case we can forget the actions associated with Right,
9823          --  since they will never be executed.
9824
9825          else
9826             Kill_Dead_Code (Right);
9827             Kill_Dead_Code (Actions (N));
9828             Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
9829          end if;
9830
9831          Adjust_Result_Type (N, Typ);
9832          return;
9833       end if;
9834
9835       --  If Actions are present for the right operand, we have to do some
9836       --  special processing. We can't just let these actions filter back into
9837       --  code preceding the short circuit (which is what would have happened
9838       --  if we had not trapped them in the short-circuit form), since they
9839       --  must only be executed if the right operand of the short circuit is
9840       --  executed and not otherwise.
9841
9842       --  the temporary variable C.
9843
9844       if Present (Actions (N)) then
9845          Actlist := Actions (N);
9846
9847          --  The old approach is to expand:
9848
9849          --     left AND THEN right
9850
9851          --  into
9852
9853          --     C : Boolean := False;
9854          --     IF left THEN
9855          --        Actions;
9856          --        IF right THEN
9857          --           C := True;
9858          --        END IF;
9859          --     END IF;
9860
9861          --  and finally rewrite the operator into a reference to C. Similarly
9862          --  for left OR ELSE right, with negated values. Note that this
9863          --  rewrite causes some difficulties for coverage analysis because
9864          --  of the introduction of the new variable C, which obscures the
9865          --  structure of the test.
9866
9867          --  We use this "old approach" if use of N_Expression_With_Actions
9868          --  is False (see description in Opt of when this is or is not set).
9869
9870          if not Use_Expression_With_Actions then
9871             Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
9872
9873             Insert_Action (N,
9874               Make_Object_Declaration (Loc,
9875                 Defining_Identifier =>
9876                   Op_Var,
9877                 Object_Definition   =>
9878                   New_Occurrence_Of (Standard_Boolean, Loc),
9879                 Expression          =>
9880                   New_Occurrence_Of (Shortcut_Ent, Loc)));
9881
9882             Append_To (Actlist,
9883               Make_Implicit_If_Statement (Right,
9884                 Condition       => Make_Test_Expr (Right),
9885                 Then_Statements => New_List (
9886                   Make_Assignment_Statement (LocR,
9887                     Name       => New_Occurrence_Of (Op_Var, LocR),
9888                     Expression =>
9889                       New_Occurrence_Of
9890                         (Boolean_Literals (not Shortcut_Value), LocR)))));
9891
9892             Insert_Action (N,
9893               Make_Implicit_If_Statement (Left,
9894                 Condition       => Make_Test_Expr (Left),
9895                 Then_Statements => Actlist));
9896
9897             Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
9898             Analyze_And_Resolve (N, Standard_Boolean);
9899
9900          --  The new approach, activated for now by the use of debug flag
9901          --  -gnatd.X is to use the new Expression_With_Actions node for the
9902          --  right operand of the short-circuit form. This should solve the
9903          --  traceability problems for coverage analysis.
9904
9905          else
9906             Rewrite (Right,
9907               Make_Expression_With_Actions (LocR,
9908                 Expression => Relocate_Node (Right),
9909                 Actions    => Actlist));
9910             Set_Actions (N, No_List);
9911             Analyze_And_Resolve (Right, Standard_Boolean);
9912          end if;
9913
9914          Adjust_Result_Type (N, Typ);
9915          return;
9916       end if;
9917
9918       --  No actions present, check for cases of right argument True/False
9919
9920       if Compile_Time_Known_Value (Right) then
9921
9922          --  Mark SCO for left condition as compile time known
9923
9924          if Generate_SCO and then Comes_From_Source (Right) then
9925             Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
9926          end if;
9927
9928          --  Change (Left and then True), (Left or else False) to Left.
9929          --  Note that we know there are no actions associated with the right
9930          --  operand, since we just checked for this case above.
9931
9932          if Expr_Value_E (Right) /= Shortcut_Ent then
9933             Rewrite (N, Left);
9934
9935          --  Change (Left and then False), (Left or else True) to Right,
9936          --  making sure to preserve any side effects associated with the Left
9937          --  operand.
9938
9939          else
9940             Remove_Side_Effects (Left);
9941             Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
9942          end if;
9943       end if;
9944
9945       Adjust_Result_Type (N, Typ);
9946    end Expand_Short_Circuit_Operator;
9947
9948    -------------------------------------
9949    -- Fixup_Universal_Fixed_Operation --
9950    -------------------------------------
9951
9952    procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
9953       Conv : constant Node_Id := Parent (N);
9954
9955    begin
9956       --  We must have a type conversion immediately above us
9957
9958       pragma Assert (Nkind (Conv) = N_Type_Conversion);
9959
9960       --  Normally the type conversion gives our target type. The exception
9961       --  occurs in the case of the Round attribute, where the conversion
9962       --  will be to universal real, and our real type comes from the Round
9963       --  attribute (as well as an indication that we must round the result)
9964
9965       if Nkind (Parent (Conv)) = N_Attribute_Reference
9966         and then Attribute_Name (Parent (Conv)) = Name_Round
9967       then
9968          Set_Etype (N, Etype (Parent (Conv)));
9969          Set_Rounded_Result (N);
9970
9971       --  Normal case where type comes from conversion above us
9972
9973       else
9974          Set_Etype (N, Etype (Conv));
9975       end if;
9976    end Fixup_Universal_Fixed_Operation;
9977
9978    ---------------------------------
9979    -- Has_Inferable_Discriminants --
9980    ---------------------------------
9981
9982    function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
9983
9984       function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
9985       --  Determines whether the left-most prefix of a selected component is a
9986       --  formal parameter in a subprogram. Assumes N is a selected component.
9987
9988       --------------------------------
9989       -- Prefix_Is_Formal_Parameter --
9990       --------------------------------
9991
9992       function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
9993          Sel_Comp : Node_Id := N;
9994
9995       begin
9996          --  Move to the left-most prefix by climbing up the tree
9997
9998          while Present (Parent (Sel_Comp))
9999            and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
10000          loop
10001             Sel_Comp := Parent (Sel_Comp);
10002          end loop;
10003
10004          return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
10005       end Prefix_Is_Formal_Parameter;
10006
10007    --  Start of processing for Has_Inferable_Discriminants
10008
10009    begin
10010       --  For identifiers and indexed components, it is sufficient to have a
10011       --  constrained Unchecked_Union nominal subtype.
10012
10013       if Nkind_In (N, N_Identifier, N_Indexed_Component) then
10014          return Is_Unchecked_Union (Base_Type (Etype (N)))
10015                   and then
10016                 Is_Constrained (Etype (N));
10017
10018       --  For selected components, the subtype of the selector must be a
10019       --  constrained Unchecked_Union. If the component is subject to a
10020       --  per-object constraint, then the enclosing object must have inferable
10021       --  discriminants.
10022
10023       elsif Nkind (N) = N_Selected_Component then
10024          if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
10025
10026             --  A small hack. If we have a per-object constrained selected
10027             --  component of a formal parameter, return True since we do not
10028             --  know the actual parameter association yet.
10029
10030             if Prefix_Is_Formal_Parameter (N) then
10031                return True;
10032             end if;
10033
10034             --  Otherwise, check the enclosing object and the selector
10035
10036             return Has_Inferable_Discriminants (Prefix (N))
10037                      and then
10038                    Has_Inferable_Discriminants (Selector_Name (N));
10039          end if;
10040
10041          --  The call to Has_Inferable_Discriminants will determine whether
10042          --  the selector has a constrained Unchecked_Union nominal type.
10043
10044          return Has_Inferable_Discriminants (Selector_Name (N));
10045
10046       --  A qualified expression has inferable discriminants if its subtype
10047       --  mark is a constrained Unchecked_Union subtype.
10048
10049       elsif Nkind (N) = N_Qualified_Expression then
10050          return Is_Unchecked_Union (Subtype_Mark (N))
10051                   and then
10052                 Is_Constrained (Subtype_Mark (N));
10053
10054       end if;
10055
10056       return False;
10057    end Has_Inferable_Discriminants;
10058
10059    -------------------------------
10060    -- Insert_Dereference_Action --
10061    -------------------------------
10062
10063    procedure Insert_Dereference_Action (N : Node_Id) is
10064       Loc  : constant Source_Ptr := Sloc (N);
10065       Typ  : constant Entity_Id  := Etype (N);
10066       Pool : constant Entity_Id  := Associated_Storage_Pool (Typ);
10067       Pnod : constant Node_Id    := Parent (N);
10068
10069       function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
10070       --  Return true if type of P is derived from Checked_Pool;
10071
10072       -----------------------------
10073       -- Is_Checked_Storage_Pool --
10074       -----------------------------
10075
10076       function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
10077          T : Entity_Id;
10078
10079       begin
10080          if No (P) then
10081             return False;
10082          end if;
10083
10084          T := Etype (P);
10085          while T /= Etype (T) loop
10086             if Is_RTE (T, RE_Checked_Pool) then
10087                return True;
10088             else
10089                T := Etype (T);
10090             end if;
10091          end loop;
10092
10093          return False;
10094       end Is_Checked_Storage_Pool;
10095
10096    --  Start of processing for Insert_Dereference_Action
10097
10098    begin
10099       pragma Assert (Nkind (Pnod) = N_Explicit_Dereference);
10100
10101       if not (Is_Checked_Storage_Pool (Pool)
10102               and then Comes_From_Source (Original_Node (Pnod)))
10103       then
10104          return;
10105       end if;
10106
10107       Insert_Action (N,
10108         Make_Procedure_Call_Statement (Loc,
10109           Name => New_Reference_To (
10110             Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
10111
10112           Parameter_Associations => New_List (
10113
10114             --  Pool
10115
10116              New_Reference_To (Pool, Loc),
10117
10118             --  Storage_Address. We use the attribute Pool_Address, which uses
10119             --  the pointer itself to find the address of the object, and which
10120             --  handles unconstrained arrays properly by computing the address
10121             --  of the template. i.e. the correct address of the corresponding
10122             --  allocation.
10123
10124              Make_Attribute_Reference (Loc,
10125                Prefix         => Duplicate_Subexpr_Move_Checks (N),
10126                Attribute_Name => Name_Pool_Address),
10127
10128             --  Size_In_Storage_Elements
10129
10130              Make_Op_Divide (Loc,
10131                Left_Opnd  =>
10132                 Make_Attribute_Reference (Loc,
10133                   Prefix         =>
10134                     Make_Explicit_Dereference (Loc,
10135                       Duplicate_Subexpr_Move_Checks (N)),
10136                   Attribute_Name => Name_Size),
10137                Right_Opnd =>
10138                  Make_Integer_Literal (Loc, System_Storage_Unit)),
10139
10140             --  Alignment
10141
10142              Make_Attribute_Reference (Loc,
10143                Prefix         =>
10144                  Make_Explicit_Dereference (Loc,
10145                    Duplicate_Subexpr_Move_Checks (N)),
10146                Attribute_Name => Name_Alignment))));
10147
10148    exception
10149       when RE_Not_Available =>
10150          return;
10151    end Insert_Dereference_Action;
10152
10153    --------------------------------
10154    -- Integer_Promotion_Possible --
10155    --------------------------------
10156
10157    function Integer_Promotion_Possible (N : Node_Id) return Boolean is
10158       Operand           : constant Node_Id   := Expression (N);
10159       Operand_Type      : constant Entity_Id := Etype (Operand);
10160       Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
10161
10162    begin
10163       pragma Assert (Nkind (N) = N_Type_Conversion);
10164
10165       return
10166
10167            --  We only do the transformation for source constructs. We assume
10168            --  that the expander knows what it is doing when it generates code.
10169
10170            Comes_From_Source (N)
10171
10172            --  If the operand type is Short_Integer or Short_Short_Integer,
10173            --  then we will promote to Integer, which is available on all
10174            --  targets, and is sufficient to ensure no intermediate overflow.
10175            --  Furthermore it is likely to be as efficient or more efficient
10176            --  than using the smaller type for the computation so we do this
10177            --  unconditionally.
10178
10179            and then
10180              (Root_Operand_Type = Base_Type (Standard_Short_Integer)
10181                or else
10182               Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
10183
10184            --  Test for interesting operation, which includes addition,
10185            --  division, exponentiation, multiplication, subtraction, absolute
10186            --  value and unary negation. Unary "+" is omitted since it is a
10187            --  no-op and thus can't overflow.
10188
10189            and then Nkind_In (Operand, N_Op_Abs,
10190                                        N_Op_Add,
10191                                        N_Op_Divide,
10192                                        N_Op_Expon,
10193                                        N_Op_Minus,
10194                                        N_Op_Multiply,
10195                                        N_Op_Subtract);
10196    end Integer_Promotion_Possible;
10197
10198    ------------------------------
10199    -- Make_Array_Comparison_Op --
10200    ------------------------------
10201
10202    --  This is a hand-coded expansion of the following generic function:
10203
10204    --  generic
10205    --    type elem is  (<>);
10206    --    type index is (<>);
10207    --    type a is array (index range <>) of elem;
10208
10209    --  function Gnnn (X : a; Y: a) return boolean is
10210    --    J : index := Y'first;
10211
10212    --  begin
10213    --    if X'length = 0 then
10214    --       return false;
10215
10216    --    elsif Y'length = 0 then
10217    --       return true;
10218
10219    --    else
10220    --      for I in X'range loop
10221    --        if X (I) = Y (J) then
10222    --          if J = Y'last then
10223    --            exit;
10224    --          else
10225    --            J := index'succ (J);
10226    --          end if;
10227
10228    --        else
10229    --           return X (I) > Y (J);
10230    --        end if;
10231    --      end loop;
10232
10233    --      return X'length > Y'length;
10234    --    end if;
10235    --  end Gnnn;
10236
10237    --  Note that since we are essentially doing this expansion by hand, we
10238    --  do not need to generate an actual or formal generic part, just the
10239    --  instantiated function itself.
10240
10241    function Make_Array_Comparison_Op
10242      (Typ : Entity_Id;
10243       Nod : Node_Id) return Node_Id
10244    is
10245       Loc : constant Source_Ptr := Sloc (Nod);
10246
10247       X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
10248       Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
10249       I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
10250       J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
10251
10252       Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
10253
10254       Loop_Statement : Node_Id;
10255       Loop_Body      : Node_Id;
10256       If_Stat        : Node_Id;
10257       Inner_If       : Node_Id;
10258       Final_Expr     : Node_Id;
10259       Func_Body      : Node_Id;
10260       Func_Name      : Entity_Id;
10261       Formals        : List_Id;
10262       Length1        : Node_Id;
10263       Length2        : Node_Id;
10264
10265    begin
10266       --  if J = Y'last then
10267       --     exit;
10268       --  else
10269       --     J := index'succ (J);
10270       --  end if;
10271
10272       Inner_If :=
10273         Make_Implicit_If_Statement (Nod,
10274           Condition =>
10275             Make_Op_Eq (Loc,
10276               Left_Opnd => New_Reference_To (J, Loc),
10277               Right_Opnd =>
10278                 Make_Attribute_Reference (Loc,
10279                   Prefix => New_Reference_To (Y, Loc),
10280                   Attribute_Name => Name_Last)),
10281
10282           Then_Statements => New_List (
10283                 Make_Exit_Statement (Loc)),
10284
10285           Else_Statements =>
10286             New_List (
10287               Make_Assignment_Statement (Loc,
10288                 Name => New_Reference_To (J, Loc),
10289                 Expression =>
10290                   Make_Attribute_Reference (Loc,
10291                     Prefix => New_Reference_To (Index, Loc),
10292                     Attribute_Name => Name_Succ,
10293                     Expressions => New_List (New_Reference_To (J, Loc))))));
10294
10295       --  if X (I) = Y (J) then
10296       --     if ... end if;
10297       --  else
10298       --     return X (I) > Y (J);
10299       --  end if;
10300
10301       Loop_Body :=
10302         Make_Implicit_If_Statement (Nod,
10303           Condition =>
10304             Make_Op_Eq (Loc,
10305               Left_Opnd =>
10306                 Make_Indexed_Component (Loc,
10307                   Prefix      => New_Reference_To (X, Loc),
10308                   Expressions => New_List (New_Reference_To (I, Loc))),
10309
10310               Right_Opnd =>
10311                 Make_Indexed_Component (Loc,
10312                   Prefix      => New_Reference_To (Y, Loc),
10313                   Expressions => New_List (New_Reference_To (J, Loc)))),
10314
10315           Then_Statements => New_List (Inner_If),
10316
10317           Else_Statements => New_List (
10318             Make_Simple_Return_Statement (Loc,
10319               Expression =>
10320                 Make_Op_Gt (Loc,
10321                   Left_Opnd =>
10322                     Make_Indexed_Component (Loc,
10323                       Prefix      => New_Reference_To (X, Loc),
10324                       Expressions => New_List (New_Reference_To (I, Loc))),
10325
10326                   Right_Opnd =>
10327                     Make_Indexed_Component (Loc,
10328                       Prefix      => New_Reference_To (Y, Loc),
10329                       Expressions => New_List (
10330                         New_Reference_To (J, Loc)))))));
10331
10332       --  for I in X'range loop
10333       --     if ... end if;
10334       --  end loop;
10335
10336       Loop_Statement :=
10337         Make_Implicit_Loop_Statement (Nod,
10338           Identifier => Empty,
10339
10340           Iteration_Scheme =>
10341             Make_Iteration_Scheme (Loc,
10342               Loop_Parameter_Specification =>
10343                 Make_Loop_Parameter_Specification (Loc,
10344                   Defining_Identifier => I,
10345                   Discrete_Subtype_Definition =>
10346                     Make_Attribute_Reference (Loc,
10347                       Prefix => New_Reference_To (X, Loc),
10348                       Attribute_Name => Name_Range))),
10349
10350           Statements => New_List (Loop_Body));
10351
10352       --    if X'length = 0 then
10353       --       return false;
10354       --    elsif Y'length = 0 then
10355       --       return true;
10356       --    else
10357       --      for ... loop ... end loop;
10358       --      return X'length > Y'length;
10359       --    end if;
10360
10361       Length1 :=
10362         Make_Attribute_Reference (Loc,
10363           Prefix => New_Reference_To (X, Loc),
10364           Attribute_Name => Name_Length);
10365
10366       Length2 :=
10367         Make_Attribute_Reference (Loc,
10368           Prefix => New_Reference_To (Y, Loc),
10369           Attribute_Name => Name_Length);
10370
10371       Final_Expr :=
10372         Make_Op_Gt (Loc,
10373           Left_Opnd  => Length1,
10374           Right_Opnd => Length2);
10375
10376       If_Stat :=
10377         Make_Implicit_If_Statement (Nod,
10378           Condition =>
10379             Make_Op_Eq (Loc,
10380               Left_Opnd =>
10381                 Make_Attribute_Reference (Loc,
10382                   Prefix => New_Reference_To (X, Loc),
10383                   Attribute_Name => Name_Length),
10384               Right_Opnd =>
10385                 Make_Integer_Literal (Loc, 0)),
10386
10387           Then_Statements =>
10388             New_List (
10389               Make_Simple_Return_Statement (Loc,
10390                 Expression => New_Reference_To (Standard_False, Loc))),
10391
10392           Elsif_Parts => New_List (
10393             Make_Elsif_Part (Loc,
10394               Condition =>
10395                 Make_Op_Eq (Loc,
10396                   Left_Opnd =>
10397                     Make_Attribute_Reference (Loc,
10398                       Prefix => New_Reference_To (Y, Loc),
10399                       Attribute_Name => Name_Length),
10400                   Right_Opnd =>
10401                     Make_Integer_Literal (Loc, 0)),
10402
10403               Then_Statements =>
10404                 New_List (
10405                   Make_Simple_Return_Statement (Loc,
10406                      Expression => New_Reference_To (Standard_True, Loc))))),
10407
10408           Else_Statements => New_List (
10409             Loop_Statement,
10410             Make_Simple_Return_Statement (Loc,
10411               Expression => Final_Expr)));
10412
10413       --  (X : a; Y: a)
10414
10415       Formals := New_List (
10416         Make_Parameter_Specification (Loc,
10417           Defining_Identifier => X,
10418           Parameter_Type      => New_Reference_To (Typ, Loc)),
10419
10420         Make_Parameter_Specification (Loc,
10421           Defining_Identifier => Y,
10422           Parameter_Type      => New_Reference_To (Typ, Loc)));
10423
10424       --  function Gnnn (...) return boolean is
10425       --    J : index := Y'first;
10426       --  begin
10427       --    if ... end if;
10428       --  end Gnnn;
10429
10430       Func_Name := Make_Temporary (Loc, 'G');
10431
10432       Func_Body :=
10433         Make_Subprogram_Body (Loc,
10434           Specification =>
10435             Make_Function_Specification (Loc,
10436               Defining_Unit_Name       => Func_Name,
10437               Parameter_Specifications => Formals,
10438               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
10439
10440           Declarations => New_List (
10441             Make_Object_Declaration (Loc,
10442               Defining_Identifier => J,
10443               Object_Definition   => New_Reference_To (Index, Loc),
10444               Expression =>
10445                 Make_Attribute_Reference (Loc,
10446                   Prefix => New_Reference_To (Y, Loc),
10447                   Attribute_Name => Name_First))),
10448
10449           Handled_Statement_Sequence =>
10450             Make_Handled_Sequence_Of_Statements (Loc,
10451               Statements => New_List (If_Stat)));
10452
10453       return Func_Body;
10454    end Make_Array_Comparison_Op;
10455
10456    ---------------------------
10457    -- Make_Boolean_Array_Op --
10458    ---------------------------
10459
10460    --  For logical operations on boolean arrays, expand in line the following,
10461    --  replacing 'and' with 'or' or 'xor' where needed:
10462
10463    --    function Annn (A : typ; B: typ) return typ is
10464    --       C : typ;
10465    --    begin
10466    --       for J in A'range loop
10467    --          C (J) := A (J) op B (J);
10468    --       end loop;
10469    --       return C;
10470    --    end Annn;
10471
10472    --  Here typ is the boolean array type
10473
10474    function Make_Boolean_Array_Op
10475      (Typ : Entity_Id;
10476       N   : Node_Id) return Node_Id
10477    is
10478       Loc : constant Source_Ptr := Sloc (N);
10479
10480       A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
10481       B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
10482       C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
10483       J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
10484
10485       A_J : Node_Id;
10486       B_J : Node_Id;
10487       C_J : Node_Id;
10488       Op  : Node_Id;
10489
10490       Formals        : List_Id;
10491       Func_Name      : Entity_Id;
10492       Func_Body      : Node_Id;
10493       Loop_Statement : Node_Id;
10494
10495    begin
10496       A_J :=
10497         Make_Indexed_Component (Loc,
10498           Prefix      => New_Reference_To (A, Loc),
10499           Expressions => New_List (New_Reference_To (J, Loc)));
10500
10501       B_J :=
10502         Make_Indexed_Component (Loc,
10503           Prefix      => New_Reference_To (B, Loc),
10504           Expressions => New_List (New_Reference_To (J, Loc)));
10505
10506       C_J :=
10507         Make_Indexed_Component (Loc,
10508           Prefix      => New_Reference_To (C, Loc),
10509           Expressions => New_List (New_Reference_To (J, Loc)));
10510
10511       if Nkind (N) = N_Op_And then
10512          Op :=
10513            Make_Op_And (Loc,
10514              Left_Opnd  => A_J,
10515              Right_Opnd => B_J);
10516
10517       elsif Nkind (N) = N_Op_Or then
10518          Op :=
10519            Make_Op_Or (Loc,
10520              Left_Opnd  => A_J,
10521              Right_Opnd => B_J);
10522
10523       else
10524          Op :=
10525            Make_Op_Xor (Loc,
10526              Left_Opnd  => A_J,
10527              Right_Opnd => B_J);
10528       end if;
10529
10530       Loop_Statement :=
10531         Make_Implicit_Loop_Statement (N,
10532           Identifier => Empty,
10533
10534           Iteration_Scheme =>
10535             Make_Iteration_Scheme (Loc,
10536               Loop_Parameter_Specification =>
10537                 Make_Loop_Parameter_Specification (Loc,
10538                   Defining_Identifier => J,
10539                   Discrete_Subtype_Definition =>
10540                     Make_Attribute_Reference (Loc,
10541                       Prefix => New_Reference_To (A, Loc),
10542                       Attribute_Name => Name_Range))),
10543
10544           Statements => New_List (
10545             Make_Assignment_Statement (Loc,
10546               Name       => C_J,
10547               Expression => Op)));
10548
10549       Formals := New_List (
10550         Make_Parameter_Specification (Loc,
10551           Defining_Identifier => A,
10552           Parameter_Type      => New_Reference_To (Typ, Loc)),
10553
10554         Make_Parameter_Specification (Loc,
10555           Defining_Identifier => B,
10556           Parameter_Type      => New_Reference_To (Typ, Loc)));
10557
10558       Func_Name := Make_Temporary (Loc, 'A');
10559       Set_Is_Inlined (Func_Name);
10560
10561       Func_Body :=
10562         Make_Subprogram_Body (Loc,
10563           Specification =>
10564             Make_Function_Specification (Loc,
10565               Defining_Unit_Name       => Func_Name,
10566               Parameter_Specifications => Formals,
10567               Result_Definition        => New_Reference_To (Typ, Loc)),
10568
10569           Declarations => New_List (
10570             Make_Object_Declaration (Loc,
10571               Defining_Identifier => C,
10572               Object_Definition   => New_Reference_To (Typ, Loc))),
10573
10574           Handled_Statement_Sequence =>
10575             Make_Handled_Sequence_Of_Statements (Loc,
10576               Statements => New_List (
10577                 Loop_Statement,
10578                 Make_Simple_Return_Statement (Loc,
10579                   Expression => New_Reference_To (C, Loc)))));
10580
10581       return Func_Body;
10582    end Make_Boolean_Array_Op;
10583
10584    --------------------------------
10585    -- Optimize_Length_Comparison --
10586    --------------------------------
10587
10588    procedure Optimize_Length_Comparison (N : Node_Id) is
10589       Loc    : constant Source_Ptr := Sloc (N);
10590       Typ    : constant Entity_Id  := Etype (N);
10591       Result : Node_Id;
10592
10593       Left  : Node_Id;
10594       Right : Node_Id;
10595       --  First and Last attribute reference nodes, which end up as left and
10596       --  right operands of the optimized result.
10597
10598       Is_Zero : Boolean;
10599       --  True for comparison operand of zero
10600
10601       Comp : Node_Id;
10602       --  Comparison operand, set only if Is_Zero is false
10603
10604       Ent : Entity_Id;
10605       --  Entity whose length is being compared
10606
10607       Index : Node_Id;
10608       --  Integer_Literal node for length attribute expression, or Empty
10609       --  if there is no such expression present.
10610
10611       Ityp  : Entity_Id;
10612       --  Type of array index to which 'Length is applied
10613
10614       Op : Node_Kind := Nkind (N);
10615       --  Kind of comparison operator, gets flipped if operands backwards
10616
10617       function Is_Optimizable (N : Node_Id) return Boolean;
10618       --  Tests N to see if it is an optimizable comparison value (defined as
10619       --  constant zero or one, or something else where the value is known to
10620       --  be positive and in the range of 32-bits, and where the corresponding
10621       --  Length value is also known to be 32-bits. If result is true, sets
10622       --  Is_Zero, Ityp, and Comp accordingly.
10623
10624       function Is_Entity_Length (N : Node_Id) return Boolean;
10625       --  Tests if N is a length attribute applied to a simple entity. If so,
10626       --  returns True, and sets Ent to the entity, and Index to the integer
10627       --  literal provided as an attribute expression, or to Empty if none.
10628       --  Also returns True if the expression is a generated type conversion
10629       --  whose expression is of the desired form. This latter case arises
10630       --  when Apply_Universal_Integer_Attribute_Check installs a conversion
10631       --  to check for being in range, which is not needed in this context.
10632       --  Returns False if neither condition holds.
10633
10634       function Prepare_64 (N : Node_Id) return Node_Id;
10635       --  Given a discrete expression, returns a Long_Long_Integer typed
10636       --  expression representing the underlying value of the expression.
10637       --  This is done with an unchecked conversion to the result type. We
10638       --  use unchecked conversion to handle the enumeration type case.
10639
10640       ----------------------
10641       -- Is_Entity_Length --
10642       ----------------------
10643
10644       function Is_Entity_Length (N : Node_Id) return Boolean is
10645       begin
10646          if Nkind (N) = N_Attribute_Reference
10647            and then Attribute_Name (N) = Name_Length
10648            and then Is_Entity_Name (Prefix (N))
10649          then
10650             Ent := Entity (Prefix (N));
10651
10652             if Present (Expressions (N)) then
10653                Index := First (Expressions (N));
10654             else
10655                Index := Empty;
10656             end if;
10657
10658             return True;
10659
10660          elsif Nkind (N) = N_Type_Conversion
10661            and then not Comes_From_Source (N)
10662          then
10663             return Is_Entity_Length (Expression (N));
10664
10665          else
10666             return False;
10667          end if;
10668       end Is_Entity_Length;
10669
10670       --------------------
10671       -- Is_Optimizable --
10672       --------------------
10673
10674       function Is_Optimizable (N : Node_Id) return Boolean is
10675          Val  : Uint;
10676          OK   : Boolean;
10677          Lo   : Uint;
10678          Hi   : Uint;
10679          Indx : Node_Id;
10680
10681       begin
10682          if Compile_Time_Known_Value (N) then
10683             Val := Expr_Value (N);
10684
10685             if Val = Uint_0 then
10686                Is_Zero := True;
10687                Comp    := Empty;
10688                return True;
10689
10690             elsif Val = Uint_1 then
10691                Is_Zero := False;
10692                Comp    := Empty;
10693                return True;
10694             end if;
10695          end if;
10696
10697          --  Here we have to make sure of being within 32-bits
10698
10699          Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
10700
10701          if not OK
10702            or else Lo < Uint_1
10703            or else Hi > UI_From_Int (Int'Last)
10704          then
10705             return False;
10706          end if;
10707
10708          --  Comparison value was within range, so now we must check the index
10709          --  value to make sure it is also within 32-bits.
10710
10711          Indx := First_Index (Etype (Ent));
10712
10713          if Present (Index) then
10714             for J in 2 .. UI_To_Int (Intval (Index)) loop
10715                Next_Index (Indx);
10716             end loop;
10717          end if;
10718
10719          Ityp := Etype (Indx);
10720
10721          if Esize (Ityp) > 32 then
10722             return False;
10723          end if;
10724
10725          Is_Zero := False;
10726          Comp := N;
10727          return True;
10728       end Is_Optimizable;
10729
10730       ----------------
10731       -- Prepare_64 --
10732       ----------------
10733
10734       function Prepare_64 (N : Node_Id) return Node_Id is
10735       begin
10736          return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
10737       end Prepare_64;
10738
10739    --  Start of processing for Optimize_Length_Comparison
10740
10741    begin
10742       --  Nothing to do if not a comparison
10743
10744       if Op not in N_Op_Compare then
10745          return;
10746       end if;
10747
10748       --  Nothing to do if special -gnatd.P debug flag set
10749
10750       if Debug_Flag_Dot_PP then
10751          return;
10752       end if;
10753
10754       --  Ent'Length op 0/1
10755
10756       if Is_Entity_Length (Left_Opnd (N))
10757         and then Is_Optimizable (Right_Opnd (N))
10758       then
10759          null;
10760
10761       --  0/1 op Ent'Length
10762
10763       elsif Is_Entity_Length (Right_Opnd (N))
10764         and then Is_Optimizable (Left_Opnd (N))
10765       then
10766          --  Flip comparison to opposite sense
10767
10768          case Op is
10769             when N_Op_Lt => Op := N_Op_Gt;
10770             when N_Op_Le => Op := N_Op_Ge;
10771             when N_Op_Gt => Op := N_Op_Lt;
10772             when N_Op_Ge => Op := N_Op_Le;
10773             when others  => null;
10774          end case;
10775
10776       --  Else optimization not possible
10777
10778       else
10779          return;
10780       end if;
10781
10782       --  Fall through if we will do the optimization
10783
10784       --  Cases to handle:
10785
10786       --    X'Length = 0  => X'First > X'Last
10787       --    X'Length = 1  => X'First = X'Last
10788       --    X'Length = n  => X'First + (n - 1) = X'Last
10789
10790       --    X'Length /= 0 => X'First <= X'Last
10791       --    X'Length /= 1 => X'First /= X'Last
10792       --    X'Length /= n => X'First + (n - 1) /= X'Last
10793
10794       --    X'Length >= 0 => always true, warn
10795       --    X'Length >= 1 => X'First <= X'Last
10796       --    X'Length >= n => X'First + (n - 1) <= X'Last
10797
10798       --    X'Length > 0  => X'First <= X'Last
10799       --    X'Length > 1  => X'First < X'Last
10800       --    X'Length > n  => X'First + (n - 1) < X'Last
10801
10802       --    X'Length <= 0 => X'First > X'Last (warn, could be =)
10803       --    X'Length <= 1 => X'First >= X'Last
10804       --    X'Length <= n => X'First + (n - 1) >= X'Last
10805
10806       --    X'Length < 0  => always false (warn)
10807       --    X'Length < 1  => X'First > X'Last
10808       --    X'Length < n  => X'First + (n - 1) > X'Last
10809
10810       --  Note: for the cases of n (not constant 0,1), we require that the
10811       --  corresponding index type be integer or shorter (i.e. not 64-bit),
10812       --  and the same for the comparison value. Then we do the comparison
10813       --  using 64-bit arithmetic (actually long long integer), so that we
10814       --  cannot have overflow intefering with the result.
10815
10816       --  First deal with warning cases
10817
10818       if Is_Zero then
10819          case Op is
10820
10821             --  X'Length >= 0
10822
10823             when N_Op_Ge =>
10824                Rewrite (N,
10825                  Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
10826                Analyze_And_Resolve (N, Typ);
10827                Warn_On_Known_Condition (N);
10828                return;
10829
10830             --  X'Length < 0
10831
10832             when N_Op_Lt =>
10833                Rewrite (N,
10834                  Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
10835                Analyze_And_Resolve (N, Typ);
10836                Warn_On_Known_Condition (N);
10837                return;
10838
10839             when N_Op_Le =>
10840                if Constant_Condition_Warnings
10841                  and then Comes_From_Source (Original_Node (N))
10842                then
10843                   Error_Msg_N ("could replace by ""'=""?", N);
10844                end if;
10845
10846                Op := N_Op_Eq;
10847
10848             when others =>
10849                null;
10850          end case;
10851       end if;
10852
10853       --  Build the First reference we will use
10854
10855       Left :=
10856         Make_Attribute_Reference (Loc,
10857           Prefix         => New_Occurrence_Of (Ent, Loc),
10858           Attribute_Name => Name_First);
10859
10860       if Present (Index) then
10861          Set_Expressions (Left, New_List (New_Copy (Index)));
10862       end if;
10863
10864       --  If general value case, then do the addition of (n - 1), and
10865       --  also add the needed conversions to type Long_Long_Integer.
10866
10867       if Present (Comp) then
10868          Left :=
10869            Make_Op_Add (Loc,
10870              Left_Opnd  => Prepare_64 (Left),
10871              Right_Opnd =>
10872                Make_Op_Subtract (Loc,
10873                  Left_Opnd  => Prepare_64 (Comp),
10874                  Right_Opnd => Make_Integer_Literal (Loc, 1)));
10875       end if;
10876
10877       --  Build the Last reference we will use
10878
10879       Right :=
10880         Make_Attribute_Reference (Loc,
10881           Prefix         => New_Occurrence_Of (Ent, Loc),
10882           Attribute_Name => Name_Last);
10883
10884       if Present (Index) then
10885          Set_Expressions (Right, New_List (New_Copy (Index)));
10886       end if;
10887
10888       --  If general operand, convert Last reference to Long_Long_Integer
10889
10890       if Present (Comp) then
10891          Right := Prepare_64 (Right);
10892       end if;
10893
10894       --  Check for cases to optimize
10895
10896       --  X'Length = 0  => X'First > X'Last
10897       --  X'Length < 1  => X'First > X'Last
10898       --  X'Length < n  => X'First + (n - 1) > X'Last
10899
10900       if (Is_Zero and then Op = N_Op_Eq)
10901         or else (not Is_Zero and then Op = N_Op_Lt)
10902       then
10903          Result :=
10904            Make_Op_Gt (Loc,
10905              Left_Opnd  => Left,
10906              Right_Opnd => Right);
10907
10908       --  X'Length = 1  => X'First = X'Last
10909       --  X'Length = n  => X'First + (n - 1) = X'Last
10910
10911       elsif not Is_Zero and then Op = N_Op_Eq then
10912          Result :=
10913            Make_Op_Eq (Loc,
10914              Left_Opnd  => Left,
10915              Right_Opnd => Right);
10916
10917       --  X'Length /= 0 => X'First <= X'Last
10918       --  X'Length > 0  => X'First <= X'Last
10919
10920       elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
10921          Result :=
10922            Make_Op_Le (Loc,
10923              Left_Opnd  => Left,
10924              Right_Opnd => Right);
10925
10926       --  X'Length /= 1 => X'First /= X'Last
10927       --  X'Length /= n => X'First + (n - 1) /= X'Last
10928
10929       elsif not Is_Zero and then Op = N_Op_Ne then
10930          Result :=
10931            Make_Op_Ne (Loc,
10932              Left_Opnd  => Left,
10933              Right_Opnd => Right);
10934
10935       --  X'Length >= 1 => X'First <= X'Last
10936       --  X'Length >= n => X'First + (n - 1) <= X'Last
10937
10938       elsif not Is_Zero and then Op = N_Op_Ge then
10939          Result :=
10940            Make_Op_Le (Loc,
10941              Left_Opnd  => Left,
10942                        Right_Opnd => Right);
10943
10944       --  X'Length > 1  => X'First < X'Last
10945       --  X'Length > n  => X'First + (n = 1) < X'Last
10946
10947       elsif not Is_Zero and then Op = N_Op_Gt then
10948          Result :=
10949            Make_Op_Lt (Loc,
10950              Left_Opnd  => Left,
10951              Right_Opnd => Right);
10952
10953       --  X'Length <= 1 => X'First >= X'Last
10954       --  X'Length <= n => X'First + (n - 1) >= X'Last
10955
10956       elsif not Is_Zero and then Op = N_Op_Le then
10957          Result :=
10958            Make_Op_Ge (Loc,
10959              Left_Opnd  => Left,
10960              Right_Opnd => Right);
10961
10962       --  Should not happen at this stage
10963
10964       else
10965          raise Program_Error;
10966       end if;
10967
10968       --  Rewrite and finish up
10969
10970       Rewrite (N, Result);
10971       Analyze_And_Resolve (N, Typ);
10972       return;
10973    end Optimize_Length_Comparison;
10974
10975    ------------------------
10976    -- Rewrite_Comparison --
10977    ------------------------
10978
10979    procedure Rewrite_Comparison (N : Node_Id) is
10980       Warning_Generated : Boolean := False;
10981       --  Set to True if first pass with Assume_Valid generates a warning in
10982       --  which case we skip the second pass to avoid warning overloaded.
10983
10984       Result : Node_Id;
10985       --  Set to Standard_True or Standard_False
10986
10987    begin
10988       if Nkind (N) = N_Type_Conversion then
10989          Rewrite_Comparison (Expression (N));
10990          return;
10991
10992       elsif Nkind (N) not in N_Op_Compare then
10993          return;
10994       end if;
10995
10996       --  Now start looking at the comparison in detail. We potentially go
10997       --  through this loop twice. The first time, Assume_Valid is set False
10998       --  in the call to Compile_Time_Compare. If this call results in a
10999       --  clear result of always True or Always False, that's decisive and
11000       --  we are done. Otherwise we repeat the processing with Assume_Valid
11001       --  set to True to generate additional warnings. We can skip that step
11002       --  if Constant_Condition_Warnings is False.
11003
11004       for AV in False .. True loop
11005          declare
11006             Typ : constant Entity_Id := Etype (N);
11007             Op1 : constant Node_Id   := Left_Opnd (N);
11008             Op2 : constant Node_Id   := Right_Opnd (N);
11009
11010             Res : constant Compare_Result :=
11011                     Compile_Time_Compare (Op1, Op2, Assume_Valid => AV);
11012             --  Res indicates if compare outcome can be compile time determined
11013
11014             True_Result  : Boolean;
11015             False_Result : Boolean;
11016
11017          begin
11018             case N_Op_Compare (Nkind (N)) is
11019             when N_Op_Eq =>
11020                True_Result  := Res = EQ;
11021                False_Result := Res = LT or else Res = GT or else Res = NE;
11022
11023             when N_Op_Ge =>
11024                True_Result  := Res in Compare_GE;
11025                False_Result := Res = LT;
11026
11027                if Res = LE
11028                  and then Constant_Condition_Warnings
11029                  and then Comes_From_Source (Original_Node (N))
11030                  and then Nkind (Original_Node (N)) = N_Op_Ge
11031                  and then not In_Instance
11032                  and then Is_Integer_Type (Etype (Left_Opnd (N)))
11033                  and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
11034                then
11035                   Error_Msg_N
11036                     ("can never be greater than, could replace by ""'=""?", N);
11037                   Warning_Generated := True;
11038                end if;
11039
11040             when N_Op_Gt =>
11041                True_Result  := Res = GT;
11042                False_Result := Res in Compare_LE;
11043
11044             when N_Op_Lt =>
11045                True_Result  := Res = LT;
11046                False_Result := Res in Compare_GE;
11047
11048             when N_Op_Le =>
11049                True_Result  := Res in Compare_LE;
11050                False_Result := Res = GT;
11051
11052                if Res = GE
11053                  and then Constant_Condition_Warnings
11054                  and then Comes_From_Source (Original_Node (N))
11055                  and then Nkind (Original_Node (N)) = N_Op_Le
11056                  and then not In_Instance
11057                  and then Is_Integer_Type (Etype (Left_Opnd (N)))
11058                  and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
11059                then
11060                   Error_Msg_N
11061                     ("can never be less than, could replace by ""'=""?", N);
11062                   Warning_Generated := True;
11063                end if;
11064
11065             when N_Op_Ne =>
11066                True_Result  := Res = NE or else Res = GT or else Res = LT;
11067                False_Result := Res = EQ;
11068             end case;
11069
11070             --  If this is the first iteration, then we actually convert the
11071             --  comparison into True or False, if the result is certain.
11072
11073             if AV = False then
11074                if True_Result or False_Result then
11075                   if True_Result then
11076                      Result := Standard_True;
11077                   else
11078                      Result := Standard_False;
11079                   end if;
11080
11081                   Rewrite (N,
11082                     Convert_To (Typ,
11083                       New_Occurrence_Of (Result, Sloc (N))));
11084                   Analyze_And_Resolve (N, Typ);
11085                   Warn_On_Known_Condition (N);
11086                   return;
11087                end if;
11088
11089             --  If this is the second iteration (AV = True), and the original
11090             --  node comes from source and we are not in an instance, then give
11091             --  a warning if we know result would be True or False. Note: we
11092             --  know Constant_Condition_Warnings is set if we get here.
11093
11094             elsif Comes_From_Source (Original_Node (N))
11095               and then not In_Instance
11096             then
11097                if True_Result then
11098                   Error_Msg_N
11099                     ("condition can only be False if invalid values present?",
11100                      N);
11101                elsif False_Result then
11102                   Error_Msg_N
11103                     ("condition can only be True if invalid values present?",
11104                      N);
11105                end if;
11106             end if;
11107          end;
11108
11109          --  Skip second iteration if not warning on constant conditions or
11110          --  if the first iteration already generated a warning of some kind or
11111          --  if we are in any case assuming all values are valid (so that the
11112          --  first iteration took care of the valid case).
11113
11114          exit when not Constant_Condition_Warnings;
11115          exit when Warning_Generated;
11116          exit when Assume_No_Invalid_Values;
11117       end loop;
11118    end Rewrite_Comparison;
11119
11120    ----------------------------
11121    -- Safe_In_Place_Array_Op --
11122    ----------------------------
11123
11124    function Safe_In_Place_Array_Op
11125      (Lhs : Node_Id;
11126       Op1 : Node_Id;
11127       Op2 : Node_Id) return Boolean
11128    is
11129       Target : Entity_Id;
11130
11131       function Is_Safe_Operand (Op : Node_Id) return Boolean;
11132       --  Operand is safe if it cannot overlap part of the target of the
11133       --  operation. If the operand and the target are identical, the operand
11134       --  is safe. The operand can be empty in the case of negation.
11135
11136       function Is_Unaliased (N : Node_Id) return Boolean;
11137       --  Check that N is a stand-alone entity
11138
11139       ------------------
11140       -- Is_Unaliased --
11141       ------------------
11142
11143       function Is_Unaliased (N : Node_Id) return Boolean is
11144       begin
11145          return
11146            Is_Entity_Name (N)
11147              and then No (Address_Clause (Entity (N)))
11148              and then No (Renamed_Object (Entity (N)));
11149       end Is_Unaliased;
11150
11151       ---------------------
11152       -- Is_Safe_Operand --
11153       ---------------------
11154
11155       function Is_Safe_Operand (Op : Node_Id) return Boolean is
11156       begin
11157          if No (Op) then
11158             return True;
11159
11160          elsif Is_Entity_Name (Op) then
11161             return Is_Unaliased (Op);
11162
11163          elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
11164             return Is_Unaliased (Prefix (Op));
11165
11166          elsif Nkind (Op) = N_Slice then
11167             return
11168               Is_Unaliased (Prefix (Op))
11169                 and then Entity (Prefix (Op)) /= Target;
11170
11171          elsif Nkind (Op) = N_Op_Not then
11172             return Is_Safe_Operand (Right_Opnd (Op));
11173
11174          else
11175             return False;
11176          end if;
11177       end Is_Safe_Operand;
11178
11179    --  Start of processing for Is_Safe_In_Place_Array_Op
11180
11181    begin
11182       --  Skip this processing if the component size is different from system
11183       --  storage unit (since at least for NOT this would cause problems).
11184
11185       if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
11186          return False;
11187
11188       --  Cannot do in place stuff on VM_Target since cannot pass addresses
11189
11190       elsif VM_Target /= No_VM then
11191          return False;
11192
11193       --  Cannot do in place stuff if non-standard Boolean representation
11194
11195       elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
11196          return False;
11197
11198       elsif not Is_Unaliased (Lhs) then
11199          return False;
11200
11201       else
11202          Target := Entity (Lhs);
11203          return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
11204       end if;
11205    end Safe_In_Place_Array_Op;
11206
11207    -----------------------
11208    -- Tagged_Membership --
11209    -----------------------
11210
11211    --  There are two different cases to consider depending on whether the right
11212    --  operand is a class-wide type or not. If not we just compare the actual
11213    --  tag of the left expr to the target type tag:
11214    --
11215    --     Left_Expr.Tag = Right_Type'Tag;
11216    --
11217    --  If it is a class-wide type we use the RT function CW_Membership which is
11218    --  usually implemented by looking in the ancestor tables contained in the
11219    --  dispatch table pointed by Left_Expr.Tag for Typ'Tag
11220
11221    --  Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
11222    --  function IW_Membership which is usually implemented by looking in the
11223    --  table of abstract interface types plus the ancestor table contained in
11224    --  the dispatch table pointed by Left_Expr.Tag for Typ'Tag
11225
11226    procedure Tagged_Membership
11227      (N         : Node_Id;
11228       SCIL_Node : out Node_Id;
11229       Result    : out Node_Id)
11230    is
11231       Left  : constant Node_Id    := Left_Opnd  (N);
11232       Right : constant Node_Id    := Right_Opnd (N);
11233       Loc   : constant Source_Ptr := Sloc (N);
11234
11235       Full_R_Typ : Entity_Id;
11236       Left_Type  : Entity_Id;
11237       New_Node   : Node_Id;
11238       Right_Type : Entity_Id;
11239       Obj_Tag    : Node_Id;
11240
11241    begin
11242       SCIL_Node := Empty;
11243
11244       --  Handle entities from the limited view
11245
11246       Left_Type  := Available_View (Etype (Left));
11247       Right_Type := Available_View (Etype (Right));
11248
11249       --  In the case where the type is an access type, the test is applied
11250       --  using the designated types (needed in Ada 2012 for implicit anonymous
11251       --  access conversions, for AI05-0149).
11252
11253       if Is_Access_Type (Right_Type) then
11254          Left_Type  := Designated_Type (Left_Type);
11255          Right_Type := Designated_Type (Right_Type);
11256       end if;
11257
11258       if Is_Class_Wide_Type (Left_Type) then
11259          Left_Type := Root_Type (Left_Type);
11260       end if;
11261
11262       if Is_Class_Wide_Type (Right_Type) then
11263          Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
11264       else
11265          Full_R_Typ := Underlying_Type (Right_Type);
11266       end if;
11267
11268       Obj_Tag :=
11269         Make_Selected_Component (Loc,
11270           Prefix        => Relocate_Node (Left),
11271           Selector_Name =>
11272             New_Reference_To (First_Tag_Component (Left_Type), Loc));
11273
11274       if Is_Class_Wide_Type (Right_Type) then
11275
11276          --  No need to issue a run-time check if we statically know that the
11277          --  result of this membership test is always true. For example,
11278          --  considering the following declarations:
11279
11280          --    type Iface is interface;
11281          --    type T     is tagged null record;
11282          --    type DT    is new T and Iface with null record;
11283
11284          --    Obj1 : T;
11285          --    Obj2 : DT;
11286
11287          --  These membership tests are always true:
11288
11289          --    Obj1 in T'Class
11290          --    Obj2 in T'Class;
11291          --    Obj2 in Iface'Class;
11292
11293          --  We do not need to handle cases where the membership is illegal.
11294          --  For example:
11295
11296          --    Obj1 in DT'Class;     --  Compile time error
11297          --    Obj1 in Iface'Class;  --  Compile time error
11298
11299          if not Is_Class_Wide_Type (Left_Type)
11300            and then (Is_Ancestor (Etype (Right_Type), Left_Type,
11301                                   Use_Full_View => True)
11302                        or else (Is_Interface (Etype (Right_Type))
11303                                  and then Interface_Present_In_Ancestor
11304                                            (Typ   => Left_Type,
11305                                             Iface => Etype (Right_Type))))
11306          then
11307             Result := New_Reference_To (Standard_True, Loc);
11308             return;
11309          end if;
11310
11311          --  Ada 2005 (AI-251): Class-wide applied to interfaces
11312
11313          if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
11314
11315             --   Support to: "Iface_CW_Typ in Typ'Class"
11316
11317            or else Is_Interface (Left_Type)
11318          then
11319             --  Issue error if IW_Membership operation not available in a
11320             --  configurable run time setting.
11321
11322             if not RTE_Available (RE_IW_Membership) then
11323                Error_Msg_CRT
11324                  ("dynamic membership test on interface types", N);
11325                Result := Empty;
11326                return;
11327             end if;
11328
11329             Result :=
11330               Make_Function_Call (Loc,
11331                  Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
11332                  Parameter_Associations => New_List (
11333                    Make_Attribute_Reference (Loc,
11334                      Prefix => Obj_Tag,
11335                      Attribute_Name => Name_Address),
11336                    New_Reference_To (
11337                      Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
11338                      Loc)));
11339
11340          --  Ada 95: Normal case
11341
11342          else
11343             Build_CW_Membership (Loc,
11344               Obj_Tag_Node => Obj_Tag,
11345               Typ_Tag_Node =>
11346                  New_Reference_To (
11347                    Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),  Loc),
11348               Related_Nod => N,
11349               New_Node    => New_Node);
11350
11351             --  Generate the SCIL node for this class-wide membership test.
11352             --  Done here because the previous call to Build_CW_Membership
11353             --  relocates Obj_Tag.
11354
11355             if Generate_SCIL then
11356                SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
11357                Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
11358                Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
11359             end if;
11360
11361             Result := New_Node;
11362          end if;
11363
11364       --  Right_Type is not a class-wide type
11365
11366       else
11367          --  No need to check the tag of the object if Right_Typ is abstract
11368
11369          if Is_Abstract_Type (Right_Type) then
11370             Result := New_Reference_To (Standard_False, Loc);
11371
11372          else
11373             Result :=
11374               Make_Op_Eq (Loc,
11375                 Left_Opnd  => Obj_Tag,
11376                 Right_Opnd =>
11377                   New_Reference_To
11378                     (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
11379          end if;
11380       end if;
11381    end Tagged_Membership;
11382
11383    ------------------------------
11384    -- Unary_Op_Validity_Checks --
11385    ------------------------------
11386
11387    procedure Unary_Op_Validity_Checks (N : Node_Id) is
11388    begin
11389       if Validity_Checks_On and Validity_Check_Operands then
11390          Ensure_Valid (Right_Opnd (N));
11391       end if;
11392    end Unary_Op_Validity_Checks;
11393
11394 end Exp_Ch4;