OpenCores
URL https://opencores.org/ocsvn/openrisc_me/openrisc_me/trunk

Subversion Repositories openrisc_me

[/] [openrisc/] [trunk/] [gnu-src/] [gcc-4.5.1/] [gcc/] [ada/] [exp_ch4.adb] - Blame information for rev 414

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.