OSDN Git Service

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