[Ada] Plug small loophole in Generate_Range_Check
[official-gcc.git] / gcc / ada / exp_ch4.adb
blobe4dc06b5d6a896beedef5c67750f7d2f432482fa
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 4 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2019, 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 ------------------------------------------------------------------------------
26 with Atree; use Atree;
27 with Checks; use Checks;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Errout; use Errout;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Atag; use Exp_Atag;
34 with Exp_Ch2; use Exp_Ch2;
35 with Exp_Ch3; use Exp_Ch3;
36 with Exp_Ch6; use Exp_Ch6;
37 with Exp_Ch7; use Exp_Ch7;
38 with Exp_Ch9; use Exp_Ch9;
39 with Exp_Disp; use Exp_Disp;
40 with Exp_Fixd; use Exp_Fixd;
41 with Exp_Intr; use Exp_Intr;
42 with Exp_Pakd; use Exp_Pakd;
43 with Exp_Tss; use Exp_Tss;
44 with Exp_Util; use Exp_Util;
45 with Freeze; use Freeze;
46 with Inline; use Inline;
47 with Namet; use Namet;
48 with Nlists; use Nlists;
49 with Nmake; use Nmake;
50 with Opt; use Opt;
51 with Par_SCO; use Par_SCO;
52 with Restrict; use Restrict;
53 with Rident; use Rident;
54 with Rtsfind; use Rtsfind;
55 with Sem; use Sem;
56 with Sem_Aux; use Sem_Aux;
57 with Sem_Cat; use Sem_Cat;
58 with Sem_Ch3; use Sem_Ch3;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Eval; use Sem_Eval;
61 with Sem_Res; use Sem_Res;
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 SCIL_LL; use SCIL_LL;
69 with Targparm; use Targparm;
70 with Tbuild; use Tbuild;
71 with Ttypes; use Ttypes;
72 with Uintp; use Uintp;
73 with Urealp; use Urealp;
74 with Validsw; use Validsw;
75 with Warnsw; use Warnsw;
77 package body Exp_Ch4 is
79 -----------------------
80 -- Local Subprograms --
81 -----------------------
83 procedure Binary_Op_Validity_Checks (N : Node_Id);
84 pragma Inline (Binary_Op_Validity_Checks);
85 -- Performs validity checks for a binary operator
87 procedure Build_Boolean_Array_Proc_Call
88 (N : Node_Id;
89 Op1 : Node_Id;
90 Op2 : Node_Id);
91 -- If a boolean array assignment can be done in place, build call to
92 -- corresponding library procedure.
94 procedure Displace_Allocator_Pointer (N : Node_Id);
95 -- Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
96 -- Expand_Allocator_Expression. Allocating class-wide interface objects
97 -- this routine displaces the pointer to the allocated object to reference
98 -- the component referencing the corresponding secondary dispatch table.
100 procedure Expand_Allocator_Expression (N : Node_Id);
101 -- Subsidiary to Expand_N_Allocator, for the case when the expression
102 -- is a qualified expression or an aggregate.
104 procedure Expand_Array_Comparison (N : Node_Id);
105 -- This routine handles expansion of the comparison operators (N_Op_Lt,
106 -- N_Op_Le, N_Op_Gt, N_Op_Ge) when operating on an array type. The basic
107 -- code for these operators is similar, differing only in the details of
108 -- the actual comparison call that is made. Special processing (call a
109 -- run-time routine)
111 function Expand_Array_Equality
112 (Nod : Node_Id;
113 Lhs : Node_Id;
114 Rhs : Node_Id;
115 Bodies : List_Id;
116 Typ : Entity_Id) return Node_Id;
117 -- Expand an array equality into a call to a function implementing this
118 -- equality, and a call to it. Loc is the location for the generated nodes.
119 -- Lhs and Rhs are the array expressions to be compared. Bodies is a list
120 -- on which to attach bodies of local functions that are created in the
121 -- process. It is the responsibility of the caller to insert those bodies
122 -- at the right place. Nod provides the Sloc value for the generated code.
123 -- Normally the types used for the generated equality routine are taken
124 -- from Lhs and Rhs. However, in some situations of generated code, the
125 -- Etype fields of Lhs and Rhs are not set yet. In such cases, Typ supplies
126 -- the type to be used for the formal parameters.
128 procedure Expand_Boolean_Operator (N : Node_Id);
129 -- Common expansion processing for Boolean operators (And, Or, Xor) for the
130 -- case of array type arguments.
132 procedure Expand_Nonbinary_Modular_Op (N : Node_Id);
133 -- When generating C code, convert nonbinary modular arithmetic operations
134 -- into code that relies on the front-end expansion of operator Mod. No
135 -- expansion is performed if N is not a nonbinary modular operand.
137 procedure Expand_Short_Circuit_Operator (N : Node_Id);
138 -- Common expansion processing for short-circuit boolean operators
140 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id);
141 -- Deal with comparison in MINIMIZED/ELIMINATED overflow mode. This is
142 -- where we allow comparison of "out of range" values.
144 function Expand_Composite_Equality
145 (Nod : Node_Id;
146 Typ : Entity_Id;
147 Lhs : Node_Id;
148 Rhs : Node_Id;
149 Bodies : List_Id) return Node_Id;
150 -- Local recursive function used to expand equality for nested composite
151 -- types. Used by Expand_Record/Array_Equality, Bodies is a list on which
152 -- to attach bodies of local functions that are created in the process. It
153 -- is the responsibility of the caller to insert those bodies at the right
154 -- place. Nod provides the Sloc value for generated code. Lhs and Rhs are
155 -- the left and right sides for the comparison, and Typ is the type of the
156 -- objects to compare.
158 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id);
159 -- Routine to expand concatenation of a sequence of two or more operands
160 -- (in the list Operands) and replace node Cnode with the result of the
161 -- concatenation. The operands can be of any appropriate type, and can
162 -- include both arrays and singleton elements.
164 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id);
165 -- N is an N_In membership test mode, with the overflow check mode set to
166 -- MINIMIZED or ELIMINATED, and the type of the left operand is a signed
167 -- integer type. This is a case where top level processing is required to
168 -- handle overflow checks in subtrees.
170 procedure Fixup_Universal_Fixed_Operation (N : Node_Id);
171 -- N is a N_Op_Divide or N_Op_Multiply node whose result is universal
172 -- fixed. We do not have such a type at runtime, so the purpose of this
173 -- routine is to find the real type by looking up the tree. We also
174 -- determine if the operation must be rounded.
176 function Has_Inferable_Discriminants (N : Node_Id) return Boolean;
177 -- Ada 2005 (AI-216): A view of an Unchecked_Union object has inferable
178 -- discriminants if it has a constrained nominal type, unless the object
179 -- is a component of an enclosing Unchecked_Union object that is subject
180 -- to a per-object constraint and the enclosing object lacks inferable
181 -- discriminants.
183 -- An expression of an Unchecked_Union type has inferable discriminants
184 -- if it is either a name of an object with inferable discriminants or a
185 -- qualified expression whose subtype mark denotes a constrained subtype.
187 procedure Insert_Dereference_Action (N : Node_Id);
188 -- N is an expression whose type is an access. When the type of the
189 -- associated storage pool is derived from Checked_Pool, generate a
190 -- call to the 'Dereference' primitive operation.
192 function Make_Array_Comparison_Op
193 (Typ : Entity_Id;
194 Nod : Node_Id) return Node_Id;
195 -- Comparisons between arrays are expanded in line. This function produces
196 -- the body of the implementation of (a > b), where a and b are one-
197 -- dimensional arrays of some discrete type. The original node is then
198 -- expanded into the appropriate call to this function. Nod provides the
199 -- Sloc value for the generated code.
201 function Make_Boolean_Array_Op
202 (Typ : Entity_Id;
203 N : Node_Id) return Node_Id;
204 -- Boolean operations on boolean arrays are expanded in line. This function
205 -- produce the body for the node N, which is (a and b), (a or b), or (a xor
206 -- b). It is used only the normal case and not the packed case. The type
207 -- involved, Typ, is the Boolean array type, and the logical operations in
208 -- the body are simple boolean operations. Note that Typ is always a
209 -- constrained type (the caller has ensured this by using
210 -- Convert_To_Actual_Subtype if necessary).
212 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean;
213 -- For signed arithmetic operations when the current overflow mode is
214 -- MINIMIZED or ELIMINATED, we must call Apply_Arithmetic_Overflow_Checks
215 -- as the first thing we do. We then return. We count on the recursive
216 -- apparatus for overflow checks to call us back with an equivalent
217 -- operation that is in CHECKED mode, avoiding a recursive entry into this
218 -- routine, and that is when we will proceed with the expansion of the
219 -- operator (e.g. converting X+0 to X, or X**2 to X*X). We cannot do
220 -- these optimizations without first making this check, since there may be
221 -- operands further down the tree that are relying on the recursive calls
222 -- triggered by the top level nodes to properly process overflow checking
223 -- and remaining expansion on these nodes. Note that this call back may be
224 -- skipped if the operation is done in Bignum mode but that's fine, since
225 -- the Bignum call takes care of everything.
227 procedure Optimize_Length_Comparison (N : Node_Id);
228 -- Given an expression, if it is of the form X'Length op N (or the other
229 -- way round), where N is known at compile time to be 0 or 1, and X is a
230 -- simple entity, and op is a comparison operator, optimizes it into a
231 -- comparison of First and Last.
233 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id);
234 -- Inspect and process statement list Stmt of if or case expression N for
235 -- transient objects. If such objects are found, the routine generates code
236 -- to clean them up when the context of the expression is evaluated.
238 procedure Process_Transient_In_Expression
239 (Obj_Decl : Node_Id;
240 Expr : Node_Id;
241 Stmts : List_Id);
242 -- Subsidiary routine to the expansion of expression_with_actions, if and
243 -- case expressions. Generate all necessary code to finalize a transient
244 -- object when the enclosing context is elaborated or evaluated. Obj_Decl
245 -- denotes the declaration of the transient object, which is usually the
246 -- result of a controlled function call. Expr denotes the expression with
247 -- actions, if expression, or case expression node. Stmts denotes the
248 -- statement list which contains Decl, either at the top level or within a
249 -- nested construct.
251 procedure Rewrite_Comparison (N : Node_Id);
252 -- If N is the node for a comparison whose outcome can be determined at
253 -- compile time, then the node N can be rewritten with True or False. If
254 -- the outcome cannot be determined at compile time, the call has no
255 -- effect. If N is a type conversion, then this processing is applied to
256 -- its expression. If N is neither comparison nor a type conversion, the
257 -- call has no effect.
259 procedure Tagged_Membership
260 (N : Node_Id;
261 SCIL_Node : out Node_Id;
262 Result : out Node_Id);
263 -- Construct the expression corresponding to the tagged membership test.
264 -- Deals with a second operand being (or not) a class-wide type.
266 function Safe_In_Place_Array_Op
267 (Lhs : Node_Id;
268 Op1 : Node_Id;
269 Op2 : Node_Id) return Boolean;
270 -- In the context of an assignment, where the right-hand side is a boolean
271 -- operation on arrays, check whether operation can be performed in place.
273 procedure Unary_Op_Validity_Checks (N : Node_Id);
274 pragma Inline (Unary_Op_Validity_Checks);
275 -- Performs validity checks for a unary operator
277 -------------------------------
278 -- Binary_Op_Validity_Checks --
279 -------------------------------
281 procedure Binary_Op_Validity_Checks (N : Node_Id) is
282 begin
283 if Validity_Checks_On and Validity_Check_Operands then
284 Ensure_Valid (Left_Opnd (N));
285 Ensure_Valid (Right_Opnd (N));
286 end if;
287 end Binary_Op_Validity_Checks;
289 ------------------------------------
290 -- Build_Boolean_Array_Proc_Call --
291 ------------------------------------
293 procedure Build_Boolean_Array_Proc_Call
294 (N : Node_Id;
295 Op1 : Node_Id;
296 Op2 : Node_Id)
298 Loc : constant Source_Ptr := Sloc (N);
299 Kind : constant Node_Kind := Nkind (Expression (N));
300 Target : constant Node_Id :=
301 Make_Attribute_Reference (Loc,
302 Prefix => Name (N),
303 Attribute_Name => Name_Address);
305 Arg1 : Node_Id := Op1;
306 Arg2 : Node_Id := Op2;
307 Call_Node : Node_Id;
308 Proc_Name : Entity_Id;
310 begin
311 if Kind = N_Op_Not then
312 if Nkind (Op1) in N_Binary_Op then
314 -- Use negated version of the binary operators
316 if Nkind (Op1) = N_Op_And then
317 Proc_Name := RTE (RE_Vector_Nand);
319 elsif Nkind (Op1) = N_Op_Or then
320 Proc_Name := RTE (RE_Vector_Nor);
322 else pragma Assert (Nkind (Op1) = N_Op_Xor);
323 Proc_Name := RTE (RE_Vector_Xor);
324 end if;
326 Call_Node :=
327 Make_Procedure_Call_Statement (Loc,
328 Name => New_Occurrence_Of (Proc_Name, Loc),
330 Parameter_Associations => New_List (
331 Target,
332 Make_Attribute_Reference (Loc,
333 Prefix => Left_Opnd (Op1),
334 Attribute_Name => Name_Address),
336 Make_Attribute_Reference (Loc,
337 Prefix => Right_Opnd (Op1),
338 Attribute_Name => Name_Address),
340 Make_Attribute_Reference (Loc,
341 Prefix => Left_Opnd (Op1),
342 Attribute_Name => Name_Length)));
344 else
345 Proc_Name := RTE (RE_Vector_Not);
347 Call_Node :=
348 Make_Procedure_Call_Statement (Loc,
349 Name => New_Occurrence_Of (Proc_Name, Loc),
350 Parameter_Associations => New_List (
351 Target,
353 Make_Attribute_Reference (Loc,
354 Prefix => Op1,
355 Attribute_Name => Name_Address),
357 Make_Attribute_Reference (Loc,
358 Prefix => Op1,
359 Attribute_Name => Name_Length)));
360 end if;
362 else
363 -- We use the following equivalences:
365 -- (not X) or (not Y) = not (X and Y) = Nand (X, Y)
366 -- (not X) and (not Y) = not (X or Y) = Nor (X, Y)
367 -- (not X) xor (not Y) = X xor Y
368 -- X xor (not Y) = not (X xor Y) = Nxor (X, Y)
370 if Nkind (Op1) = N_Op_Not then
371 Arg1 := Right_Opnd (Op1);
372 Arg2 := Right_Opnd (Op2);
374 if Kind = N_Op_And then
375 Proc_Name := RTE (RE_Vector_Nor);
376 elsif Kind = N_Op_Or then
377 Proc_Name := RTE (RE_Vector_Nand);
378 else
379 Proc_Name := RTE (RE_Vector_Xor);
380 end if;
382 else
383 if Kind = N_Op_And then
384 Proc_Name := RTE (RE_Vector_And);
385 elsif Kind = N_Op_Or then
386 Proc_Name := RTE (RE_Vector_Or);
387 elsif Nkind (Op2) = N_Op_Not then
388 Proc_Name := RTE (RE_Vector_Nxor);
389 Arg2 := Right_Opnd (Op2);
390 else
391 Proc_Name := RTE (RE_Vector_Xor);
392 end if;
393 end if;
395 Call_Node :=
396 Make_Procedure_Call_Statement (Loc,
397 Name => New_Occurrence_Of (Proc_Name, Loc),
398 Parameter_Associations => New_List (
399 Target,
400 Make_Attribute_Reference (Loc,
401 Prefix => Arg1,
402 Attribute_Name => Name_Address),
403 Make_Attribute_Reference (Loc,
404 Prefix => Arg2,
405 Attribute_Name => Name_Address),
406 Make_Attribute_Reference (Loc,
407 Prefix => Arg1,
408 Attribute_Name => Name_Length)));
409 end if;
411 Rewrite (N, Call_Node);
412 Analyze (N);
414 exception
415 when RE_Not_Available =>
416 return;
417 end Build_Boolean_Array_Proc_Call;
419 -----------------------
420 -- Build_Eq_Call --
421 -----------------------
423 function Build_Eq_Call
424 (Typ : Entity_Id;
425 Loc : Source_Ptr;
426 Lhs : Node_Id;
427 Rhs : Node_Id) return Node_Id
429 Prim : Node_Id;
430 Prim_E : Elmt_Id;
432 begin
433 Prim_E := First_Elmt (Collect_Primitive_Operations (Typ));
434 while Present (Prim_E) loop
435 Prim := Node (Prim_E);
437 -- Locate primitive equality with the right signature
439 if Chars (Prim) = Name_Op_Eq
440 and then Etype (First_Formal (Prim)) =
441 Etype (Next_Formal (First_Formal (Prim)))
442 and then Etype (Prim) = Standard_Boolean
443 then
444 if Is_Abstract_Subprogram (Prim) then
445 return
446 Make_Raise_Program_Error (Loc,
447 Reason => PE_Explicit_Raise);
449 else
450 return
451 Make_Function_Call (Loc,
452 Name => New_Occurrence_Of (Prim, Loc),
453 Parameter_Associations => New_List (Lhs, Rhs));
454 end if;
455 end if;
457 Next_Elmt (Prim_E);
458 end loop;
460 -- If not found, predefined operation will be used
462 return Empty;
463 end Build_Eq_Call;
465 --------------------------------
466 -- Displace_Allocator_Pointer --
467 --------------------------------
469 procedure Displace_Allocator_Pointer (N : Node_Id) is
470 Loc : constant Source_Ptr := Sloc (N);
471 Orig_Node : constant Node_Id := Original_Node (N);
472 Dtyp : Entity_Id;
473 Etyp : Entity_Id;
474 PtrT : Entity_Id;
476 begin
477 -- Do nothing in case of VM targets: the virtual machine will handle
478 -- interfaces directly.
480 if not Tagged_Type_Expansion then
481 return;
482 end if;
484 pragma Assert (Nkind (N) = N_Identifier
485 and then Nkind (Orig_Node) = N_Allocator);
487 PtrT := Etype (Orig_Node);
488 Dtyp := Available_View (Designated_Type (PtrT));
489 Etyp := Etype (Expression (Orig_Node));
491 if Is_Class_Wide_Type (Dtyp) and then Is_Interface (Dtyp) then
493 -- If the type of the allocator expression is not an interface type
494 -- we can generate code to reference the record component containing
495 -- the pointer to the secondary dispatch table.
497 if not Is_Interface (Etyp) then
498 declare
499 Saved_Typ : constant Entity_Id := Etype (Orig_Node);
501 begin
502 -- 1) Get access to the allocated object
504 Rewrite (N,
505 Make_Explicit_Dereference (Loc, Relocate_Node (N)));
506 Set_Etype (N, Etyp);
507 Set_Analyzed (N);
509 -- 2) Add the conversion to displace the pointer to reference
510 -- the secondary dispatch table.
512 Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
513 Analyze_And_Resolve (N, Dtyp);
515 -- 3) The 'access to the secondary dispatch table will be used
516 -- as the value returned by the allocator.
518 Rewrite (N,
519 Make_Attribute_Reference (Loc,
520 Prefix => Relocate_Node (N),
521 Attribute_Name => Name_Access));
522 Set_Etype (N, Saved_Typ);
523 Set_Analyzed (N);
524 end;
526 -- If the type of the allocator expression is an interface type we
527 -- generate a run-time call to displace "this" to reference the
528 -- component containing the pointer to the secondary dispatch table
529 -- or else raise Constraint_Error if the actual object does not
530 -- implement the target interface. This case corresponds to the
531 -- following example:
533 -- function Op (Obj : Iface_1'Class) return access Iface_2'Class is
534 -- begin
535 -- return new Iface_2'Class'(Obj);
536 -- end Op;
538 else
539 Rewrite (N,
540 Unchecked_Convert_To (PtrT,
541 Make_Function_Call (Loc,
542 Name => New_Occurrence_Of (RTE (RE_Displace), Loc),
543 Parameter_Associations => New_List (
544 Unchecked_Convert_To (RTE (RE_Address),
545 Relocate_Node (N)),
547 New_Occurrence_Of
548 (Elists.Node
549 (First_Elmt
550 (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
551 Loc)))));
552 Analyze_And_Resolve (N, PtrT);
553 end if;
554 end if;
555 end Displace_Allocator_Pointer;
557 ---------------------------------
558 -- Expand_Allocator_Expression --
559 ---------------------------------
561 procedure Expand_Allocator_Expression (N : Node_Id) is
562 Loc : constant Source_Ptr := Sloc (N);
563 Exp : constant Node_Id := Expression (Expression (N));
564 PtrT : constant Entity_Id := Etype (N);
565 DesigT : constant Entity_Id := Designated_Type (PtrT);
567 procedure Apply_Accessibility_Check
568 (Ref : Node_Id;
569 Built_In_Place : Boolean := False);
570 -- Ada 2005 (AI-344): For an allocator with a class-wide designated
571 -- type, generate an accessibility check to verify that the level of the
572 -- type of the created object is not deeper than the level of the access
573 -- type. If the type of the qualified expression is class-wide, then
574 -- always generate the check (except in the case where it is known to be
575 -- unnecessary, see comment below). Otherwise, only generate the check
576 -- if the level of the qualified expression type is statically deeper
577 -- than the access type.
579 -- Although the static accessibility will generally have been performed
580 -- as a legality check, it won't have been done in cases where the
581 -- allocator appears in generic body, so a run-time check is needed in
582 -- general. One special case is when the access type is declared in the
583 -- same scope as the class-wide allocator, in which case the check can
584 -- never fail, so it need not be generated.
586 -- As an open issue, there seem to be cases where the static level
587 -- associated with the class-wide object's underlying type is not
588 -- sufficient to perform the proper accessibility check, such as for
589 -- allocators in nested subprograms or accept statements initialized by
590 -- class-wide formals when the actual originates outside at a deeper
591 -- static level. The nested subprogram case might require passing
592 -- accessibility levels along with class-wide parameters, and the task
593 -- case seems to be an actual gap in the language rules that needs to
594 -- be fixed by the ARG. ???
596 -------------------------------
597 -- Apply_Accessibility_Check --
598 -------------------------------
600 procedure Apply_Accessibility_Check
601 (Ref : Node_Id;
602 Built_In_Place : Boolean := False)
604 Pool_Id : constant Entity_Id := Associated_Storage_Pool (PtrT);
605 Cond : Node_Id;
606 Fin_Call : Node_Id;
607 Free_Stmt : Node_Id;
608 Obj_Ref : Node_Id;
609 Stmts : List_Id;
611 begin
612 if Ada_Version >= Ada_2005
613 and then Is_Class_Wide_Type (DesigT)
614 and then Tagged_Type_Expansion
615 and then not Scope_Suppress.Suppress (Accessibility_Check)
616 and then
617 (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
618 or else
619 (Is_Class_Wide_Type (Etype (Exp))
620 and then Scope (PtrT) /= Current_Scope))
621 then
622 -- If the allocator was built in place, Ref is already a reference
623 -- to the access object initialized to the result of the allocator
624 -- (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). We call
625 -- Remove_Side_Effects for cases where the build-in-place call may
626 -- still be the prefix of the reference (to avoid generating
627 -- duplicate calls). Otherwise, it is the entity associated with
628 -- the object containing the address of the allocated object.
630 if Built_In_Place then
631 Remove_Side_Effects (Ref);
632 Obj_Ref := New_Copy_Tree (Ref);
633 else
634 Obj_Ref := New_Occurrence_Of (Ref, Loc);
635 end if;
637 -- For access to interface types we must generate code to displace
638 -- the pointer to the base of the object since the subsequent code
639 -- references components located in the TSD of the object (which
640 -- is associated with the primary dispatch table --see a-tags.ads)
641 -- and also generates code invoking Free, which requires also a
642 -- reference to the base of the unallocated object.
644 if Is_Interface (DesigT) and then Tagged_Type_Expansion then
645 Obj_Ref :=
646 Unchecked_Convert_To (Etype (Obj_Ref),
647 Make_Function_Call (Loc,
648 Name =>
649 New_Occurrence_Of (RTE (RE_Base_Address), Loc),
650 Parameter_Associations => New_List (
651 Unchecked_Convert_To (RTE (RE_Address),
652 New_Copy_Tree (Obj_Ref)))));
653 end if;
655 -- Step 1: Create the object clean up code
657 Stmts := New_List;
659 -- Deallocate the object if the accessibility check fails. This
660 -- is done only on targets or profiles that support deallocation.
662 -- Free (Obj_Ref);
664 if RTE_Available (RE_Free) then
665 Free_Stmt := Make_Free_Statement (Loc, New_Copy_Tree (Obj_Ref));
666 Set_Storage_Pool (Free_Stmt, Pool_Id);
668 Append_To (Stmts, Free_Stmt);
670 -- The target or profile cannot deallocate objects
672 else
673 Free_Stmt := Empty;
674 end if;
676 -- Finalize the object if applicable. Generate:
678 -- [Deep_]Finalize (Obj_Ref.all);
680 if Needs_Finalization (DesigT)
681 and then not No_Heap_Finalization (PtrT)
682 then
683 Fin_Call :=
684 Make_Final_Call
685 (Obj_Ref =>
686 Make_Explicit_Dereference (Loc, New_Copy (Obj_Ref)),
687 Typ => DesigT);
689 -- Guard against a missing [Deep_]Finalize when the designated
690 -- type was not properly frozen.
692 if No (Fin_Call) then
693 Fin_Call := Make_Null_Statement (Loc);
694 end if;
696 -- When the target or profile supports deallocation, wrap the
697 -- finalization call in a block to ensure proper deallocation
698 -- even if finalization fails. Generate:
700 -- begin
701 -- <Fin_Call>
702 -- exception
703 -- when others =>
704 -- <Free_Stmt>
705 -- raise;
706 -- end;
708 if Present (Free_Stmt) then
709 Fin_Call :=
710 Make_Block_Statement (Loc,
711 Handled_Statement_Sequence =>
712 Make_Handled_Sequence_Of_Statements (Loc,
713 Statements => New_List (Fin_Call),
715 Exception_Handlers => New_List (
716 Make_Exception_Handler (Loc,
717 Exception_Choices => New_List (
718 Make_Others_Choice (Loc)),
719 Statements => New_List (
720 New_Copy_Tree (Free_Stmt),
721 Make_Raise_Statement (Loc))))));
722 end if;
724 Prepend_To (Stmts, Fin_Call);
725 end if;
727 -- Signal the accessibility failure through a Program_Error
729 Append_To (Stmts,
730 Make_Raise_Program_Error (Loc,
731 Condition => New_Occurrence_Of (Standard_True, Loc),
732 Reason => PE_Accessibility_Check_Failed));
734 -- Step 2: Create the accessibility comparison
736 -- Generate:
737 -- Ref'Tag
739 Obj_Ref :=
740 Make_Attribute_Reference (Loc,
741 Prefix => Obj_Ref,
742 Attribute_Name => Name_Tag);
744 -- For tagged types, determine the accessibility level by looking
745 -- at the type specific data of the dispatch table. Generate:
747 -- Type_Specific_Data (Address (Ref'Tag)).Access_Level
749 if Tagged_Type_Expansion then
750 Cond := Build_Get_Access_Level (Loc, Obj_Ref);
752 -- Use a runtime call to determine the accessibility level when
753 -- compiling on virtual machine targets. Generate:
755 -- Get_Access_Level (Ref'Tag)
757 else
758 Cond :=
759 Make_Function_Call (Loc,
760 Name =>
761 New_Occurrence_Of (RTE (RE_Get_Access_Level), Loc),
762 Parameter_Associations => New_List (Obj_Ref));
763 end if;
765 Cond :=
766 Make_Op_Gt (Loc,
767 Left_Opnd => Cond,
768 Right_Opnd =>
769 Make_Integer_Literal (Loc, Type_Access_Level (PtrT)));
771 -- Due to the complexity and side effects of the check, utilize an
772 -- if statement instead of the regular Program_Error circuitry.
774 Insert_Action (N,
775 Make_Implicit_If_Statement (N,
776 Condition => Cond,
777 Then_Statements => Stmts));
778 end if;
779 end Apply_Accessibility_Check;
781 -- Local variables
783 Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
784 Indic : constant Node_Id := Subtype_Mark (Expression (N));
785 T : constant Entity_Id := Entity (Indic);
786 Adj_Call : Node_Id;
787 Node : Node_Id;
788 Tag_Assign : Node_Id;
789 Temp : Entity_Id;
790 Temp_Decl : Node_Id;
792 TagT : Entity_Id := Empty;
793 -- Type used as source for tag assignment
795 TagR : Node_Id := Empty;
796 -- Target reference for tag assignment
798 -- Start of processing for Expand_Allocator_Expression
800 begin
801 -- Handle call to C++ constructor
803 if Is_CPP_Constructor_Call (Exp) then
804 Make_CPP_Constructor_Call_In_Allocator
805 (Allocator => N,
806 Function_Call => Exp);
807 return;
808 end if;
810 -- In the case of an Ada 2012 allocator whose initial value comes from a
811 -- function call, pass "the accessibility level determined by the point
812 -- of call" (AI05-0234) to the function. Conceptually, this belongs in
813 -- Expand_Call but it couldn't be done there (because the Etype of the
814 -- allocator wasn't set then) so we generate the parameter here. See
815 -- the Boolean variable Defer in (a block within) Expand_Call.
817 if Ada_Version >= Ada_2012 and then Nkind (Exp) = N_Function_Call then
818 declare
819 Subp : Entity_Id;
821 begin
822 if Nkind (Name (Exp)) = N_Explicit_Dereference then
823 Subp := Designated_Type (Etype (Prefix (Name (Exp))));
824 else
825 Subp := Entity (Name (Exp));
826 end if;
828 Subp := Ultimate_Alias (Subp);
830 if Present (Extra_Accessibility_Of_Result (Subp)) then
831 Add_Extra_Actual_To_Call
832 (Subprogram_Call => Exp,
833 Extra_Formal => Extra_Accessibility_Of_Result (Subp),
834 Extra_Actual => Dynamic_Accessibility_Level (PtrT));
835 end if;
836 end;
837 end if;
839 -- Case of tagged type or type requiring finalization
841 if Is_Tagged_Type (T) or else Needs_Finalization (T) then
843 -- Ada 2005 (AI-318-02): If the initialization expression is a call
844 -- to a build-in-place function, then access to the allocated object
845 -- must be passed to the function.
847 if Is_Build_In_Place_Function_Call (Exp) then
848 Make_Build_In_Place_Call_In_Allocator (N, Exp);
849 Apply_Accessibility_Check (N, Built_In_Place => True);
850 return;
852 -- Ada 2005 (AI-318-02): Specialization of the previous case for
853 -- expressions containing a build-in-place function call whose
854 -- returned object covers interface types, and Expr has calls to
855 -- Ada.Tags.Displace to displace the pointer to the returned build-
856 -- in-place object to reference the secondary dispatch table of a
857 -- covered interface type.
859 elsif Present (Unqual_BIP_Iface_Function_Call (Exp)) then
860 Make_Build_In_Place_Iface_Call_In_Allocator (N, Exp);
861 Apply_Accessibility_Check (N, Built_In_Place => True);
862 return;
863 end if;
865 -- Actions inserted before:
866 -- Temp : constant ptr_T := new T'(Expression);
867 -- Temp._tag = T'tag; -- when not class-wide
868 -- [Deep_]Adjust (Temp.all);
870 -- We analyze by hand the new internal allocator to avoid any
871 -- recursion and inappropriate call to Initialize.
873 -- We don't want to remove side effects when the expression must be
874 -- built in place. In the case of a build-in-place function call,
875 -- that could lead to a duplication of the call, which was already
876 -- substituted for the allocator.
878 if not Aggr_In_Place then
879 Remove_Side_Effects (Exp);
880 end if;
882 Temp := Make_Temporary (Loc, 'P', N);
884 -- For a class wide allocation generate the following code:
886 -- type Equiv_Record is record ... end record;
887 -- implicit subtype CW is <Class_Wide_Subytpe>;
888 -- temp : PtrT := new CW'(CW!(expr));
890 if Is_Class_Wide_Type (T) then
891 Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
893 -- Ada 2005 (AI-251): If the expression is a class-wide interface
894 -- object we generate code to move up "this" to reference the
895 -- base of the object before allocating the new object.
897 -- Note that Exp'Address is recursively expanded into a call
898 -- to Base_Address (Exp.Tag)
900 if Is_Class_Wide_Type (Etype (Exp))
901 and then Is_Interface (Etype (Exp))
902 and then Tagged_Type_Expansion
903 then
904 Set_Expression
905 (Expression (N),
906 Unchecked_Convert_To (Entity (Indic),
907 Make_Explicit_Dereference (Loc,
908 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
909 Make_Attribute_Reference (Loc,
910 Prefix => Exp,
911 Attribute_Name => Name_Address)))));
912 else
913 Set_Expression
914 (Expression (N),
915 Unchecked_Convert_To (Entity (Indic), Exp));
916 end if;
918 Analyze_And_Resolve (Expression (N), Entity (Indic));
919 end if;
921 -- Processing for allocators returning non-interface types
923 if not Is_Interface (Directly_Designated_Type (PtrT)) then
924 if Aggr_In_Place then
925 Temp_Decl :=
926 Make_Object_Declaration (Loc,
927 Defining_Identifier => Temp,
928 Object_Definition => New_Occurrence_Of (PtrT, Loc),
929 Expression =>
930 Make_Allocator (Loc,
931 Expression =>
932 New_Occurrence_Of (Etype (Exp), Loc)));
934 -- Copy the Comes_From_Source flag for the allocator we just
935 -- built, since logically this allocator is a replacement of
936 -- the original allocator node. This is for proper handling of
937 -- restriction No_Implicit_Heap_Allocations.
939 Set_Comes_From_Source
940 (Expression (Temp_Decl), Comes_From_Source (N));
942 Set_No_Initialization (Expression (Temp_Decl));
943 Insert_Action (N, Temp_Decl);
945 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
946 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
948 else
949 Node := Relocate_Node (N);
950 Set_Analyzed (Node);
952 Temp_Decl :=
953 Make_Object_Declaration (Loc,
954 Defining_Identifier => Temp,
955 Constant_Present => True,
956 Object_Definition => New_Occurrence_Of (PtrT, Loc),
957 Expression => Node);
959 Insert_Action (N, Temp_Decl);
960 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
961 end if;
963 -- Ada 2005 (AI-251): Handle allocators whose designated type is an
964 -- interface type. In this case we use the type of the qualified
965 -- expression to allocate the object.
967 else
968 declare
969 Def_Id : constant Entity_Id := Make_Temporary (Loc, 'T');
970 New_Decl : Node_Id;
972 begin
973 New_Decl :=
974 Make_Full_Type_Declaration (Loc,
975 Defining_Identifier => Def_Id,
976 Type_Definition =>
977 Make_Access_To_Object_Definition (Loc,
978 All_Present => True,
979 Null_Exclusion_Present => False,
980 Constant_Present =>
981 Is_Access_Constant (Etype (N)),
982 Subtype_Indication =>
983 New_Occurrence_Of (Etype (Exp), Loc)));
985 Insert_Action (N, New_Decl);
987 -- Inherit the allocation-related attributes from the original
988 -- access type.
990 Set_Finalization_Master
991 (Def_Id, Finalization_Master (PtrT));
993 Set_Associated_Storage_Pool
994 (Def_Id, Associated_Storage_Pool (PtrT));
996 -- Declare the object using the previous type declaration
998 if Aggr_In_Place then
999 Temp_Decl :=
1000 Make_Object_Declaration (Loc,
1001 Defining_Identifier => Temp,
1002 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
1003 Expression =>
1004 Make_Allocator (Loc,
1005 New_Occurrence_Of (Etype (Exp), Loc)));
1007 -- Copy the Comes_From_Source flag for the allocator we just
1008 -- built, since logically this allocator is a replacement of
1009 -- the original allocator node. This is for proper handling
1010 -- of restriction No_Implicit_Heap_Allocations.
1012 Set_Comes_From_Source
1013 (Expression (Temp_Decl), Comes_From_Source (N));
1015 Set_No_Initialization (Expression (Temp_Decl));
1016 Insert_Action (N, Temp_Decl);
1018 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1019 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1021 else
1022 Node := Relocate_Node (N);
1023 Set_Analyzed (Node);
1025 Temp_Decl :=
1026 Make_Object_Declaration (Loc,
1027 Defining_Identifier => Temp,
1028 Constant_Present => True,
1029 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
1030 Expression => Node);
1032 Insert_Action (N, Temp_Decl);
1033 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1034 end if;
1036 -- Generate an additional object containing the address of the
1037 -- returned object. The type of this second object declaration
1038 -- is the correct type required for the common processing that
1039 -- is still performed by this subprogram. The displacement of
1040 -- this pointer to reference the component associated with the
1041 -- interface type will be done at the end of common processing.
1043 New_Decl :=
1044 Make_Object_Declaration (Loc,
1045 Defining_Identifier => Make_Temporary (Loc, 'P'),
1046 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1047 Expression =>
1048 Unchecked_Convert_To (PtrT,
1049 New_Occurrence_Of (Temp, Loc)));
1051 Insert_Action (N, New_Decl);
1053 Temp_Decl := New_Decl;
1054 Temp := Defining_Identifier (New_Decl);
1055 end;
1056 end if;
1058 -- Generate the tag assignment
1060 -- Suppress the tag assignment for VM targets because VM tags are
1061 -- represented implicitly in objects.
1063 if not Tagged_Type_Expansion then
1064 null;
1066 -- Ada 2005 (AI-251): Suppress the tag assignment with class-wide
1067 -- interface objects because in this case the tag does not change.
1069 elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
1070 pragma Assert (Is_Class_Wide_Type
1071 (Directly_Designated_Type (Etype (N))));
1072 null;
1074 elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
1075 TagT := T;
1076 TagR := New_Occurrence_Of (Temp, Loc);
1078 elsif Is_Private_Type (T)
1079 and then Is_Tagged_Type (Underlying_Type (T))
1080 then
1081 TagT := Underlying_Type (T);
1082 TagR :=
1083 Unchecked_Convert_To (Underlying_Type (T),
1084 Make_Explicit_Dereference (Loc,
1085 Prefix => New_Occurrence_Of (Temp, Loc)));
1086 end if;
1088 if Present (TagT) then
1089 declare
1090 Full_T : constant Entity_Id := Underlying_Type (TagT);
1092 begin
1093 Tag_Assign :=
1094 Make_Assignment_Statement (Loc,
1095 Name =>
1096 Make_Selected_Component (Loc,
1097 Prefix => TagR,
1098 Selector_Name =>
1099 New_Occurrence_Of
1100 (First_Tag_Component (Full_T), Loc)),
1102 Expression =>
1103 Unchecked_Convert_To (RTE (RE_Tag),
1104 New_Occurrence_Of
1105 (Elists.Node
1106 (First_Elmt (Access_Disp_Table (Full_T))), Loc)));
1107 end;
1109 -- The previous assignment has to be done in any case
1111 Set_Assignment_OK (Name (Tag_Assign));
1112 Insert_Action (N, Tag_Assign);
1113 end if;
1115 -- Generate an Adjust call if the object will be moved. In Ada 2005,
1116 -- the object may be inherently limited, in which case there is no
1117 -- Adjust procedure, and the object is built in place. In Ada 95, the
1118 -- object can be limited but not inherently limited if this allocator
1119 -- came from a return statement (we're allocating the result on the
1120 -- secondary stack). In that case, the object will be moved, so we do
1121 -- want to Adjust. However, if it's a nonlimited build-in-place
1122 -- function call, Adjust is not wanted.
1124 if Needs_Finalization (DesigT)
1125 and then Needs_Finalization (T)
1126 and then not Aggr_In_Place
1127 and then not Is_Limited_View (T)
1128 and then not Alloc_For_BIP_Return (N)
1129 and then not Is_Build_In_Place_Function_Call (Expression (N))
1130 then
1131 -- An unchecked conversion is needed in the classwide case because
1132 -- the designated type can be an ancestor of the subtype mark of
1133 -- the allocator.
1135 Adj_Call :=
1136 Make_Adjust_Call
1137 (Obj_Ref =>
1138 Unchecked_Convert_To (T,
1139 Make_Explicit_Dereference (Loc,
1140 Prefix => New_Occurrence_Of (Temp, Loc))),
1141 Typ => T);
1143 if Present (Adj_Call) then
1144 Insert_Action (N, Adj_Call);
1145 end if;
1146 end if;
1148 -- Note: the accessibility check must be inserted after the call to
1149 -- [Deep_]Adjust to ensure proper completion of the assignment.
1151 Apply_Accessibility_Check (Temp);
1153 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1154 Analyze_And_Resolve (N, PtrT);
1156 -- Ada 2005 (AI-251): Displace the pointer to reference the record
1157 -- component containing the secondary dispatch table of the interface
1158 -- type.
1160 if Is_Interface (Directly_Designated_Type (PtrT)) then
1161 Displace_Allocator_Pointer (N);
1162 end if;
1164 -- Always force the generation of a temporary for aggregates when
1165 -- generating C code, to simplify the work in the code generator.
1167 elsif Aggr_In_Place
1168 or else (Modify_Tree_For_C and then Nkind (Exp) = N_Aggregate)
1169 then
1170 Temp := Make_Temporary (Loc, 'P', N);
1171 Temp_Decl :=
1172 Make_Object_Declaration (Loc,
1173 Defining_Identifier => Temp,
1174 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1175 Expression =>
1176 Make_Allocator (Loc,
1177 Expression => New_Occurrence_Of (Etype (Exp), Loc)));
1179 -- Copy the Comes_From_Source flag for the allocator we just built,
1180 -- since logically this allocator is a replacement of the original
1181 -- allocator node. This is for proper handling of restriction
1182 -- No_Implicit_Heap_Allocations.
1184 Set_Comes_From_Source
1185 (Expression (Temp_Decl), Comes_From_Source (N));
1187 Set_No_Initialization (Expression (Temp_Decl));
1188 Insert_Action (N, Temp_Decl);
1190 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1191 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1193 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1194 Analyze_And_Resolve (N, PtrT);
1196 elsif Is_Access_Type (T) and then Can_Never_Be_Null (T) then
1197 Install_Null_Excluding_Check (Exp);
1199 elsif Is_Access_Type (DesigT)
1200 and then Nkind (Exp) = N_Allocator
1201 and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1202 then
1203 -- Apply constraint to designated subtype indication
1205 Apply_Constraint_Check
1206 (Expression (Exp), Designated_Type (DesigT), No_Sliding => True);
1208 if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1210 -- Propagate constraint_error to enclosing allocator
1212 Rewrite (Exp, New_Copy (Expression (Exp)));
1213 end if;
1215 else
1216 Build_Allocate_Deallocate_Proc (N, True);
1218 -- If we have:
1219 -- type A is access T1;
1220 -- X : A := new T2'(...);
1221 -- T1 and T2 can be different subtypes, and we might need to check
1222 -- both constraints. First check against the type of the qualified
1223 -- expression.
1225 Apply_Constraint_Check (Exp, T, No_Sliding => True);
1227 if Do_Range_Check (Exp) then
1228 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1229 end if;
1231 -- A check is also needed in cases where the designated subtype is
1232 -- constrained and differs from the subtype given in the qualified
1233 -- expression. Note that the check on the qualified expression does
1234 -- not allow sliding, but this check does (a relaxation from Ada 83).
1236 if Is_Constrained (DesigT)
1237 and then not Subtypes_Statically_Match (T, DesigT)
1238 then
1239 Apply_Constraint_Check
1240 (Exp, DesigT, No_Sliding => False);
1242 if Do_Range_Check (Exp) then
1243 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1244 end if;
1245 end if;
1247 -- For an access to unconstrained packed array, GIGI needs to see an
1248 -- expression with a constrained subtype in order to compute the
1249 -- proper size for the allocator.
1251 if Is_Array_Type (T)
1252 and then not Is_Constrained (T)
1253 and then Is_Packed (T)
1254 then
1255 declare
1256 ConstrT : constant Entity_Id := Make_Temporary (Loc, 'A');
1257 Internal_Exp : constant Node_Id := Relocate_Node (Exp);
1258 begin
1259 Insert_Action (Exp,
1260 Make_Subtype_Declaration (Loc,
1261 Defining_Identifier => ConstrT,
1262 Subtype_Indication =>
1263 Make_Subtype_From_Expr (Internal_Exp, T)));
1264 Freeze_Itype (ConstrT, Exp);
1265 Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1266 end;
1267 end if;
1269 -- Ada 2005 (AI-318-02): If the initialization expression is a call
1270 -- to a build-in-place function, then access to the allocated object
1271 -- must be passed to the function.
1273 if Is_Build_In_Place_Function_Call (Exp) then
1274 Make_Build_In_Place_Call_In_Allocator (N, Exp);
1275 end if;
1276 end if;
1278 exception
1279 when RE_Not_Available =>
1280 return;
1281 end Expand_Allocator_Expression;
1283 -----------------------------
1284 -- Expand_Array_Comparison --
1285 -----------------------------
1287 -- Expansion is only required in the case of array types. For the unpacked
1288 -- case, an appropriate runtime routine is called. For packed cases, and
1289 -- also in some other cases where a runtime routine cannot be called, the
1290 -- form of the expansion is:
1292 -- [body for greater_nn; boolean_expression]
1294 -- The body is built by Make_Array_Comparison_Op, and the form of the
1295 -- Boolean expression depends on the operator involved.
1297 procedure Expand_Array_Comparison (N : Node_Id) is
1298 Loc : constant Source_Ptr := Sloc (N);
1299 Op1 : Node_Id := Left_Opnd (N);
1300 Op2 : Node_Id := Right_Opnd (N);
1301 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
1302 Ctyp : constant Entity_Id := Component_Type (Typ1);
1304 Expr : Node_Id;
1305 Func_Body : Node_Id;
1306 Func_Name : Entity_Id;
1308 Comp : RE_Id;
1310 Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1311 -- True for byte addressable target
1313 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1314 -- Returns True if the length of the given operand is known to be less
1315 -- than 4. Returns False if this length is known to be four or greater
1316 -- or is not known at compile time.
1318 ------------------------
1319 -- Length_Less_Than_4 --
1320 ------------------------
1322 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1323 Otyp : constant Entity_Id := Etype (Opnd);
1325 begin
1326 if Ekind (Otyp) = E_String_Literal_Subtype then
1327 return String_Literal_Length (Otyp) < 4;
1329 else
1330 declare
1331 Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1332 Lo : constant Node_Id := Type_Low_Bound (Ityp);
1333 Hi : constant Node_Id := Type_High_Bound (Ityp);
1334 Lov : Uint;
1335 Hiv : Uint;
1337 begin
1338 if Compile_Time_Known_Value (Lo) then
1339 Lov := Expr_Value (Lo);
1340 else
1341 return False;
1342 end if;
1344 if Compile_Time_Known_Value (Hi) then
1345 Hiv := Expr_Value (Hi);
1346 else
1347 return False;
1348 end if;
1350 return Hiv < Lov + 3;
1351 end;
1352 end if;
1353 end Length_Less_Than_4;
1355 -- Start of processing for Expand_Array_Comparison
1357 begin
1358 -- Deal first with unpacked case, where we can call a runtime routine
1359 -- except that we avoid this for targets for which are not addressable
1360 -- by bytes.
1362 if not Is_Bit_Packed_Array (Typ1)
1363 and then Byte_Addressable
1364 then
1365 -- The call we generate is:
1367 -- Compare_Array_xn[_Unaligned]
1368 -- (left'address, right'address, left'length, right'length) <op> 0
1370 -- x = U for unsigned, S for signed
1371 -- n = 8,16,32,64 for component size
1372 -- Add _Unaligned if length < 4 and component size is 8.
1373 -- <op> is the standard comparison operator
1375 if Component_Size (Typ1) = 8 then
1376 if Length_Less_Than_4 (Op1)
1377 or else
1378 Length_Less_Than_4 (Op2)
1379 then
1380 if Is_Unsigned_Type (Ctyp) then
1381 Comp := RE_Compare_Array_U8_Unaligned;
1382 else
1383 Comp := RE_Compare_Array_S8_Unaligned;
1384 end if;
1386 else
1387 if Is_Unsigned_Type (Ctyp) then
1388 Comp := RE_Compare_Array_U8;
1389 else
1390 Comp := RE_Compare_Array_S8;
1391 end if;
1392 end if;
1394 elsif Component_Size (Typ1) = 16 then
1395 if Is_Unsigned_Type (Ctyp) then
1396 Comp := RE_Compare_Array_U16;
1397 else
1398 Comp := RE_Compare_Array_S16;
1399 end if;
1401 elsif Component_Size (Typ1) = 32 then
1402 if Is_Unsigned_Type (Ctyp) then
1403 Comp := RE_Compare_Array_U32;
1404 else
1405 Comp := RE_Compare_Array_S32;
1406 end if;
1408 else pragma Assert (Component_Size (Typ1) = 64);
1409 if Is_Unsigned_Type (Ctyp) then
1410 Comp := RE_Compare_Array_U64;
1411 else
1412 Comp := RE_Compare_Array_S64;
1413 end if;
1414 end if;
1416 if RTE_Available (Comp) then
1418 -- Expand to a call only if the runtime function is available,
1419 -- otherwise fall back to inline code.
1421 Remove_Side_Effects (Op1, Name_Req => True);
1422 Remove_Side_Effects (Op2, Name_Req => True);
1424 Rewrite (Op1,
1425 Make_Function_Call (Sloc (Op1),
1426 Name => New_Occurrence_Of (RTE (Comp), Loc),
1428 Parameter_Associations => New_List (
1429 Make_Attribute_Reference (Loc,
1430 Prefix => Relocate_Node (Op1),
1431 Attribute_Name => Name_Address),
1433 Make_Attribute_Reference (Loc,
1434 Prefix => Relocate_Node (Op2),
1435 Attribute_Name => Name_Address),
1437 Make_Attribute_Reference (Loc,
1438 Prefix => Relocate_Node (Op1),
1439 Attribute_Name => Name_Length),
1441 Make_Attribute_Reference (Loc,
1442 Prefix => Relocate_Node (Op2),
1443 Attribute_Name => Name_Length))));
1445 Rewrite (Op2,
1446 Make_Integer_Literal (Sloc (Op2),
1447 Intval => Uint_0));
1449 Analyze_And_Resolve (Op1, Standard_Integer);
1450 Analyze_And_Resolve (Op2, Standard_Integer);
1451 return;
1452 end if;
1453 end if;
1455 -- Cases where we cannot make runtime call
1457 -- For (a <= b) we convert to not (a > b)
1459 if Chars (N) = Name_Op_Le then
1460 Rewrite (N,
1461 Make_Op_Not (Loc,
1462 Right_Opnd =>
1463 Make_Op_Gt (Loc,
1464 Left_Opnd => Op1,
1465 Right_Opnd => Op2)));
1466 Analyze_And_Resolve (N, Standard_Boolean);
1467 return;
1469 -- For < the Boolean expression is
1470 -- greater__nn (op2, op1)
1472 elsif Chars (N) = Name_Op_Lt then
1473 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1475 -- Switch operands
1477 Op1 := Right_Opnd (N);
1478 Op2 := Left_Opnd (N);
1480 -- For (a >= b) we convert to not (a < b)
1482 elsif Chars (N) = Name_Op_Ge then
1483 Rewrite (N,
1484 Make_Op_Not (Loc,
1485 Right_Opnd =>
1486 Make_Op_Lt (Loc,
1487 Left_Opnd => Op1,
1488 Right_Opnd => Op2)));
1489 Analyze_And_Resolve (N, Standard_Boolean);
1490 return;
1492 -- For > the Boolean expression is
1493 -- greater__nn (op1, op2)
1495 else
1496 pragma Assert (Chars (N) = Name_Op_Gt);
1497 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1498 end if;
1500 Func_Name := Defining_Unit_Name (Specification (Func_Body));
1501 Expr :=
1502 Make_Function_Call (Loc,
1503 Name => New_Occurrence_Of (Func_Name, Loc),
1504 Parameter_Associations => New_List (Op1, Op2));
1506 Insert_Action (N, Func_Body);
1507 Rewrite (N, Expr);
1508 Analyze_And_Resolve (N, Standard_Boolean);
1509 end Expand_Array_Comparison;
1511 ---------------------------
1512 -- Expand_Array_Equality --
1513 ---------------------------
1515 -- Expand an equality function for multi-dimensional arrays. Here is an
1516 -- example of such a function for Nb_Dimension = 2
1518 -- function Enn (A : atyp; B : btyp) return boolean is
1519 -- begin
1520 -- if (A'length (1) = 0 or else A'length (2) = 0)
1521 -- and then
1522 -- (B'length (1) = 0 or else B'length (2) = 0)
1523 -- then
1524 -- return True; -- RM 4.5.2(22)
1525 -- end if;
1527 -- if A'length (1) /= B'length (1)
1528 -- or else
1529 -- A'length (2) /= B'length (2)
1530 -- then
1531 -- return False; -- RM 4.5.2(23)
1532 -- end if;
1534 -- declare
1535 -- A1 : Index_T1 := A'first (1);
1536 -- B1 : Index_T1 := B'first (1);
1537 -- begin
1538 -- loop
1539 -- declare
1540 -- A2 : Index_T2 := A'first (2);
1541 -- B2 : Index_T2 := B'first (2);
1542 -- begin
1543 -- loop
1544 -- if A (A1, A2) /= B (B1, B2) then
1545 -- return False;
1546 -- end if;
1548 -- exit when A2 = A'last (2);
1549 -- A2 := Index_T2'succ (A2);
1550 -- B2 := Index_T2'succ (B2);
1551 -- end loop;
1552 -- end;
1554 -- exit when A1 = A'last (1);
1555 -- A1 := Index_T1'succ (A1);
1556 -- B1 := Index_T1'succ (B1);
1557 -- end loop;
1558 -- end;
1560 -- return true;
1561 -- end Enn;
1563 -- Note on the formal types used (atyp and btyp). If either of the arrays
1564 -- is of a private type, we use the underlying type, and do an unchecked
1565 -- conversion of the actual. If either of the arrays has a bound depending
1566 -- on a discriminant, then we use the base type since otherwise we have an
1567 -- escaped discriminant in the function.
1569 -- If both arrays are constrained and have the same bounds, we can generate
1570 -- a loop with an explicit iteration scheme using a 'Range attribute over
1571 -- the first array.
1573 function Expand_Array_Equality
1574 (Nod : Node_Id;
1575 Lhs : Node_Id;
1576 Rhs : Node_Id;
1577 Bodies : List_Id;
1578 Typ : Entity_Id) return Node_Id
1580 Loc : constant Source_Ptr := Sloc (Nod);
1581 Decls : constant List_Id := New_List;
1582 Index_List1 : constant List_Id := New_List;
1583 Index_List2 : constant List_Id := New_List;
1585 Actuals : List_Id;
1586 Formals : List_Id;
1587 Func_Name : Entity_Id;
1588 Func_Body : Node_Id;
1590 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1591 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1593 Ltyp : Entity_Id;
1594 Rtyp : Entity_Id;
1595 -- The parameter types to be used for the formals
1597 function Arr_Attr
1598 (Arr : Entity_Id;
1599 Nam : Name_Id;
1600 Num : Int) return Node_Id;
1601 -- This builds the attribute reference Arr'Nam (Expr)
1603 function Component_Equality (Typ : Entity_Id) return Node_Id;
1604 -- Create one statement to compare corresponding components, designated
1605 -- by a full set of indexes.
1607 function Get_Arg_Type (N : Node_Id) return Entity_Id;
1608 -- Given one of the arguments, computes the appropriate type to be used
1609 -- for that argument in the corresponding function formal
1611 function Handle_One_Dimension
1612 (N : Int;
1613 Index : Node_Id) return Node_Id;
1614 -- This procedure returns the following code
1616 -- declare
1617 -- Bn : Index_T := B'First (N);
1618 -- begin
1619 -- loop
1620 -- xxx
1621 -- exit when An = A'Last (N);
1622 -- An := Index_T'Succ (An)
1623 -- Bn := Index_T'Succ (Bn)
1624 -- end loop;
1625 -- end;
1627 -- If both indexes are constrained and identical, the procedure
1628 -- returns a simpler loop:
1630 -- for An in A'Range (N) loop
1631 -- xxx
1632 -- end loop
1634 -- N is the dimension for which we are generating a loop. Index is the
1635 -- N'th index node, whose Etype is Index_Type_n in the above code. The
1636 -- xxx statement is either the loop or declare for the next dimension
1637 -- or if this is the last dimension the comparison of corresponding
1638 -- components of the arrays.
1640 -- The actual way the code works is to return the comparison of
1641 -- corresponding components for the N+1 call. That's neater.
1643 function Test_Empty_Arrays return Node_Id;
1644 -- This function constructs the test for both arrays being empty
1645 -- (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1646 -- and then
1647 -- (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1649 function Test_Lengths_Correspond return Node_Id;
1650 -- This function constructs the test for arrays having different lengths
1651 -- in at least one index position, in which case the resulting code is:
1653 -- A'length (1) /= B'length (1)
1654 -- or else
1655 -- A'length (2) /= B'length (2)
1656 -- or else
1657 -- ...
1659 --------------
1660 -- Arr_Attr --
1661 --------------
1663 function Arr_Attr
1664 (Arr : Entity_Id;
1665 Nam : Name_Id;
1666 Num : Int) return Node_Id
1668 begin
1669 return
1670 Make_Attribute_Reference (Loc,
1671 Attribute_Name => Nam,
1672 Prefix => New_Occurrence_Of (Arr, Loc),
1673 Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1674 end Arr_Attr;
1676 ------------------------
1677 -- Component_Equality --
1678 ------------------------
1680 function Component_Equality (Typ : Entity_Id) return Node_Id is
1681 Test : Node_Id;
1682 L, R : Node_Id;
1684 begin
1685 -- if a(i1...) /= b(j1...) then return false; end if;
1687 L :=
1688 Make_Indexed_Component (Loc,
1689 Prefix => Make_Identifier (Loc, Chars (A)),
1690 Expressions => Index_List1);
1692 R :=
1693 Make_Indexed_Component (Loc,
1694 Prefix => Make_Identifier (Loc, Chars (B)),
1695 Expressions => Index_List2);
1697 Test := Expand_Composite_Equality
1698 (Nod, Component_Type (Typ), L, R, Decls);
1700 -- If some (sub)component is an unchecked_union, the whole operation
1701 -- will raise program error.
1703 if Nkind (Test) = N_Raise_Program_Error then
1705 -- This node is going to be inserted at a location where a
1706 -- statement is expected: clear its Etype so analysis will set
1707 -- it to the expected Standard_Void_Type.
1709 Set_Etype (Test, Empty);
1710 return Test;
1712 else
1713 return
1714 Make_Implicit_If_Statement (Nod,
1715 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1716 Then_Statements => New_List (
1717 Make_Simple_Return_Statement (Loc,
1718 Expression => New_Occurrence_Of (Standard_False, Loc))));
1719 end if;
1720 end Component_Equality;
1722 ------------------
1723 -- Get_Arg_Type --
1724 ------------------
1726 function Get_Arg_Type (N : Node_Id) return Entity_Id is
1727 T : Entity_Id;
1728 X : Node_Id;
1730 begin
1731 T := Etype (N);
1733 if No (T) then
1734 return Typ;
1736 else
1737 T := Underlying_Type (T);
1739 X := First_Index (T);
1740 while Present (X) loop
1741 if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1742 or else
1743 Denotes_Discriminant (Type_High_Bound (Etype (X)))
1744 then
1745 T := Base_Type (T);
1746 exit;
1747 end if;
1749 Next_Index (X);
1750 end loop;
1752 return T;
1753 end if;
1754 end Get_Arg_Type;
1756 --------------------------
1757 -- Handle_One_Dimension --
1758 ---------------------------
1760 function Handle_One_Dimension
1761 (N : Int;
1762 Index : Node_Id) return Node_Id
1764 Need_Separate_Indexes : constant Boolean :=
1765 Ltyp /= Rtyp or else not Is_Constrained (Ltyp);
1766 -- If the index types are identical, and we are working with
1767 -- constrained types, then we can use the same index for both
1768 -- of the arrays.
1770 An : constant Entity_Id := Make_Temporary (Loc, 'A');
1772 Bn : Entity_Id;
1773 Index_T : Entity_Id;
1774 Stm_List : List_Id;
1775 Loop_Stm : Node_Id;
1777 begin
1778 if N > Number_Dimensions (Ltyp) then
1779 return Component_Equality (Ltyp);
1780 end if;
1782 -- Case where we generate a loop
1784 Index_T := Base_Type (Etype (Index));
1786 if Need_Separate_Indexes then
1787 Bn := Make_Temporary (Loc, 'B');
1788 else
1789 Bn := An;
1790 end if;
1792 Append (New_Occurrence_Of (An, Loc), Index_List1);
1793 Append (New_Occurrence_Of (Bn, Loc), Index_List2);
1795 Stm_List := New_List (
1796 Handle_One_Dimension (N + 1, Next_Index (Index)));
1798 if Need_Separate_Indexes then
1800 -- Generate guard for loop, followed by increments of indexes
1802 Append_To (Stm_List,
1803 Make_Exit_Statement (Loc,
1804 Condition =>
1805 Make_Op_Eq (Loc,
1806 Left_Opnd => New_Occurrence_Of (An, Loc),
1807 Right_Opnd => Arr_Attr (A, Name_Last, N))));
1809 Append_To (Stm_List,
1810 Make_Assignment_Statement (Loc,
1811 Name => New_Occurrence_Of (An, Loc),
1812 Expression =>
1813 Make_Attribute_Reference (Loc,
1814 Prefix => New_Occurrence_Of (Index_T, Loc),
1815 Attribute_Name => Name_Succ,
1816 Expressions => New_List (
1817 New_Occurrence_Of (An, Loc)))));
1819 Append_To (Stm_List,
1820 Make_Assignment_Statement (Loc,
1821 Name => New_Occurrence_Of (Bn, Loc),
1822 Expression =>
1823 Make_Attribute_Reference (Loc,
1824 Prefix => New_Occurrence_Of (Index_T, Loc),
1825 Attribute_Name => Name_Succ,
1826 Expressions => New_List (
1827 New_Occurrence_Of (Bn, Loc)))));
1828 end if;
1830 -- If separate indexes, we need a declare block for An and Bn, and a
1831 -- loop without an iteration scheme.
1833 if Need_Separate_Indexes then
1834 Loop_Stm :=
1835 Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
1837 return
1838 Make_Block_Statement (Loc,
1839 Declarations => New_List (
1840 Make_Object_Declaration (Loc,
1841 Defining_Identifier => An,
1842 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1843 Expression => Arr_Attr (A, Name_First, N)),
1845 Make_Object_Declaration (Loc,
1846 Defining_Identifier => Bn,
1847 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1848 Expression => Arr_Attr (B, Name_First, N))),
1850 Handled_Statement_Sequence =>
1851 Make_Handled_Sequence_Of_Statements (Loc,
1852 Statements => New_List (Loop_Stm)));
1854 -- If no separate indexes, return loop statement with explicit
1855 -- iteration scheme on its own
1857 else
1858 Loop_Stm :=
1859 Make_Implicit_Loop_Statement (Nod,
1860 Statements => Stm_List,
1861 Iteration_Scheme =>
1862 Make_Iteration_Scheme (Loc,
1863 Loop_Parameter_Specification =>
1864 Make_Loop_Parameter_Specification (Loc,
1865 Defining_Identifier => An,
1866 Discrete_Subtype_Definition =>
1867 Arr_Attr (A, Name_Range, N))));
1868 return Loop_Stm;
1869 end if;
1870 end Handle_One_Dimension;
1872 -----------------------
1873 -- Test_Empty_Arrays --
1874 -----------------------
1876 function Test_Empty_Arrays return Node_Id is
1877 Alist : Node_Id;
1878 Blist : Node_Id;
1880 Atest : Node_Id;
1881 Btest : Node_Id;
1883 begin
1884 Alist := Empty;
1885 Blist := Empty;
1886 for J in 1 .. Number_Dimensions (Ltyp) loop
1887 Atest :=
1888 Make_Op_Eq (Loc,
1889 Left_Opnd => Arr_Attr (A, Name_Length, J),
1890 Right_Opnd => Make_Integer_Literal (Loc, 0));
1892 Btest :=
1893 Make_Op_Eq (Loc,
1894 Left_Opnd => Arr_Attr (B, Name_Length, J),
1895 Right_Opnd => Make_Integer_Literal (Loc, 0));
1897 if No (Alist) then
1898 Alist := Atest;
1899 Blist := Btest;
1901 else
1902 Alist :=
1903 Make_Or_Else (Loc,
1904 Left_Opnd => Relocate_Node (Alist),
1905 Right_Opnd => Atest);
1907 Blist :=
1908 Make_Or_Else (Loc,
1909 Left_Opnd => Relocate_Node (Blist),
1910 Right_Opnd => Btest);
1911 end if;
1912 end loop;
1914 return
1915 Make_And_Then (Loc,
1916 Left_Opnd => Alist,
1917 Right_Opnd => Blist);
1918 end Test_Empty_Arrays;
1920 -----------------------------
1921 -- Test_Lengths_Correspond --
1922 -----------------------------
1924 function Test_Lengths_Correspond return Node_Id is
1925 Result : Node_Id;
1926 Rtest : Node_Id;
1928 begin
1929 Result := Empty;
1930 for J in 1 .. Number_Dimensions (Ltyp) loop
1931 Rtest :=
1932 Make_Op_Ne (Loc,
1933 Left_Opnd => Arr_Attr (A, Name_Length, J),
1934 Right_Opnd => Arr_Attr (B, Name_Length, J));
1936 if No (Result) then
1937 Result := Rtest;
1938 else
1939 Result :=
1940 Make_Or_Else (Loc,
1941 Left_Opnd => Relocate_Node (Result),
1942 Right_Opnd => Rtest);
1943 end if;
1944 end loop;
1946 return Result;
1947 end Test_Lengths_Correspond;
1949 -- Start of processing for Expand_Array_Equality
1951 begin
1952 Ltyp := Get_Arg_Type (Lhs);
1953 Rtyp := Get_Arg_Type (Rhs);
1955 -- For now, if the argument types are not the same, go to the base type,
1956 -- since the code assumes that the formals have the same type. This is
1957 -- fixable in future ???
1959 if Ltyp /= Rtyp then
1960 Ltyp := Base_Type (Ltyp);
1961 Rtyp := Base_Type (Rtyp);
1962 pragma Assert (Ltyp = Rtyp);
1963 end if;
1965 -- Build list of formals for function
1967 Formals := New_List (
1968 Make_Parameter_Specification (Loc,
1969 Defining_Identifier => A,
1970 Parameter_Type => New_Occurrence_Of (Ltyp, Loc)),
1972 Make_Parameter_Specification (Loc,
1973 Defining_Identifier => B,
1974 Parameter_Type => New_Occurrence_Of (Rtyp, Loc)));
1976 Func_Name := Make_Temporary (Loc, 'E');
1978 -- Build statement sequence for function
1980 Func_Body :=
1981 Make_Subprogram_Body (Loc,
1982 Specification =>
1983 Make_Function_Specification (Loc,
1984 Defining_Unit_Name => Func_Name,
1985 Parameter_Specifications => Formals,
1986 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
1988 Declarations => Decls,
1990 Handled_Statement_Sequence =>
1991 Make_Handled_Sequence_Of_Statements (Loc,
1992 Statements => New_List (
1994 Make_Implicit_If_Statement (Nod,
1995 Condition => Test_Empty_Arrays,
1996 Then_Statements => New_List (
1997 Make_Simple_Return_Statement (Loc,
1998 Expression =>
1999 New_Occurrence_Of (Standard_True, Loc)))),
2001 Make_Implicit_If_Statement (Nod,
2002 Condition => Test_Lengths_Correspond,
2003 Then_Statements => New_List (
2004 Make_Simple_Return_Statement (Loc,
2005 Expression => New_Occurrence_Of (Standard_False, Loc)))),
2007 Handle_One_Dimension (1, First_Index (Ltyp)),
2009 Make_Simple_Return_Statement (Loc,
2010 Expression => New_Occurrence_Of (Standard_True, Loc)))));
2012 Set_Has_Completion (Func_Name, True);
2013 Set_Is_Inlined (Func_Name);
2015 -- If the array type is distinct from the type of the arguments, it
2016 -- is the full view of a private type. Apply an unchecked conversion
2017 -- to insure that analysis of the call succeeds.
2019 declare
2020 L, R : Node_Id;
2022 begin
2023 L := Lhs;
2024 R := Rhs;
2026 if No (Etype (Lhs))
2027 or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
2028 then
2029 L := OK_Convert_To (Ltyp, Lhs);
2030 end if;
2032 if No (Etype (Rhs))
2033 or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
2034 then
2035 R := OK_Convert_To (Rtyp, Rhs);
2036 end if;
2038 Actuals := New_List (L, R);
2039 end;
2041 Append_To (Bodies, Func_Body);
2043 return
2044 Make_Function_Call (Loc,
2045 Name => New_Occurrence_Of (Func_Name, Loc),
2046 Parameter_Associations => Actuals);
2047 end Expand_Array_Equality;
2049 -----------------------------
2050 -- Expand_Boolean_Operator --
2051 -----------------------------
2053 -- Note that we first get the actual subtypes of the operands, since we
2054 -- always want to deal with types that have bounds.
2056 procedure Expand_Boolean_Operator (N : Node_Id) is
2057 Typ : constant Entity_Id := Etype (N);
2059 begin
2060 -- Special case of bit packed array where both operands are known to be
2061 -- properly aligned. In this case we use an efficient run time routine
2062 -- to carry out the operation (see System.Bit_Ops).
2064 if Is_Bit_Packed_Array (Typ)
2065 and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
2066 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
2067 then
2068 Expand_Packed_Boolean_Operator (N);
2069 return;
2070 end if;
2072 -- For the normal non-packed case, the general expansion is to build
2073 -- function for carrying out the comparison (use Make_Boolean_Array_Op)
2074 -- and then inserting it into the tree. The original operator node is
2075 -- then rewritten as a call to this function. We also use this in the
2076 -- packed case if either operand is a possibly unaligned object.
2078 declare
2079 Loc : constant Source_Ptr := Sloc (N);
2080 L : constant Node_Id := Relocate_Node (Left_Opnd (N));
2081 R : Node_Id := Relocate_Node (Right_Opnd (N));
2082 Func_Body : Node_Id;
2083 Func_Name : Entity_Id;
2085 begin
2086 Convert_To_Actual_Subtype (L);
2087 Convert_To_Actual_Subtype (R);
2088 Ensure_Defined (Etype (L), N);
2089 Ensure_Defined (Etype (R), N);
2090 Apply_Length_Check (R, Etype (L));
2092 if Nkind (N) = N_Op_Xor then
2093 R := Duplicate_Subexpr (R);
2094 Silly_Boolean_Array_Xor_Test (N, R, Etype (L));
2095 end if;
2097 if Nkind (Parent (N)) = N_Assignment_Statement
2098 and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
2099 then
2100 Build_Boolean_Array_Proc_Call (Parent (N), L, R);
2102 elsif Nkind (Parent (N)) = N_Op_Not
2103 and then Nkind (N) = N_Op_And
2104 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2105 and then Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
2106 then
2107 return;
2108 else
2110 Func_Body := Make_Boolean_Array_Op (Etype (L), N);
2111 Func_Name := Defining_Unit_Name (Specification (Func_Body));
2112 Insert_Action (N, Func_Body);
2114 -- Now rewrite the expression with a call
2116 Rewrite (N,
2117 Make_Function_Call (Loc,
2118 Name => New_Occurrence_Of (Func_Name, Loc),
2119 Parameter_Associations =>
2120 New_List (
2122 Make_Type_Conversion
2123 (Loc, New_Occurrence_Of (Etype (L), Loc), R))));
2125 Analyze_And_Resolve (N, Typ);
2126 end if;
2127 end;
2128 end Expand_Boolean_Operator;
2130 ------------------------------------------------
2131 -- Expand_Compare_Minimize_Eliminate_Overflow --
2132 ------------------------------------------------
2134 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id) is
2135 Loc : constant Source_Ptr := Sloc (N);
2137 Result_Type : constant Entity_Id := Etype (N);
2138 -- Capture result type (could be a derived boolean type)
2140 Llo, Lhi : Uint;
2141 Rlo, Rhi : Uint;
2143 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
2144 -- Entity for Long_Long_Integer'Base
2146 Check : constant Overflow_Mode_Type := Overflow_Check_Mode;
2147 -- Current overflow checking mode
2149 procedure Set_True;
2150 procedure Set_False;
2151 -- These procedures rewrite N with an occurrence of Standard_True or
2152 -- Standard_False, and then makes a call to Warn_On_Known_Condition.
2154 ---------------
2155 -- Set_False --
2156 ---------------
2158 procedure Set_False is
2159 begin
2160 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
2161 Warn_On_Known_Condition (N);
2162 end Set_False;
2164 --------------
2165 -- Set_True --
2166 --------------
2168 procedure Set_True is
2169 begin
2170 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
2171 Warn_On_Known_Condition (N);
2172 end Set_True;
2174 -- Start of processing for Expand_Compare_Minimize_Eliminate_Overflow
2176 begin
2177 -- Nothing to do unless we have a comparison operator with operands
2178 -- that are signed integer types, and we are operating in either
2179 -- MINIMIZED or ELIMINATED overflow checking mode.
2181 if Nkind (N) not in N_Op_Compare
2182 or else Check not in Minimized_Or_Eliminated
2183 or else not Is_Signed_Integer_Type (Etype (Left_Opnd (N)))
2184 then
2185 return;
2186 end if;
2188 -- OK, this is the case we are interested in. First step is to process
2189 -- our operands using the Minimize_Eliminate circuitry which applies
2190 -- this processing to the two operand subtrees.
2192 Minimize_Eliminate_Overflows
2193 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
2194 Minimize_Eliminate_Overflows
2195 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
2197 -- See if the range information decides the result of the comparison.
2198 -- We can only do this if we in fact have full range information (which
2199 -- won't be the case if either operand is bignum at this stage).
2201 if Llo /= No_Uint and then Rlo /= No_Uint then
2202 case N_Op_Compare (Nkind (N)) is
2203 when N_Op_Eq =>
2204 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2205 Set_True;
2206 elsif Llo > Rhi or else Lhi < Rlo then
2207 Set_False;
2208 end if;
2210 when N_Op_Ge =>
2211 if Llo >= Rhi then
2212 Set_True;
2213 elsif Lhi < Rlo then
2214 Set_False;
2215 end if;
2217 when N_Op_Gt =>
2218 if Llo > Rhi then
2219 Set_True;
2220 elsif Lhi <= Rlo then
2221 Set_False;
2222 end if;
2224 when N_Op_Le =>
2225 if Llo > Rhi then
2226 Set_False;
2227 elsif Lhi <= Rlo then
2228 Set_True;
2229 end if;
2231 when N_Op_Lt =>
2232 if Llo >= Rhi then
2233 Set_False;
2234 elsif Lhi < Rlo then
2235 Set_True;
2236 end if;
2238 when N_Op_Ne =>
2239 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2240 Set_False;
2241 elsif Llo > Rhi or else Lhi < Rlo then
2242 Set_True;
2243 end if;
2244 end case;
2246 -- All done if we did the rewrite
2248 if Nkind (N) not in N_Op_Compare then
2249 return;
2250 end if;
2251 end if;
2253 -- Otherwise, time to do the comparison
2255 declare
2256 Ltype : constant Entity_Id := Etype (Left_Opnd (N));
2257 Rtype : constant Entity_Id := Etype (Right_Opnd (N));
2259 begin
2260 -- If the two operands have the same signed integer type we are
2261 -- all set, nothing more to do. This is the case where either
2262 -- both operands were unchanged, or we rewrote both of them to
2263 -- be Long_Long_Integer.
2265 -- Note: Entity for the comparison may be wrong, but it's not worth
2266 -- the effort to change it, since the back end does not use it.
2268 if Is_Signed_Integer_Type (Ltype)
2269 and then Base_Type (Ltype) = Base_Type (Rtype)
2270 then
2271 return;
2273 -- Here if bignums are involved (can only happen in ELIMINATED mode)
2275 elsif Is_RTE (Ltype, RE_Bignum) or else Is_RTE (Rtype, RE_Bignum) then
2276 declare
2277 Left : Node_Id := Left_Opnd (N);
2278 Right : Node_Id := Right_Opnd (N);
2279 -- Bignum references for left and right operands
2281 begin
2282 if not Is_RTE (Ltype, RE_Bignum) then
2283 Left := Convert_To_Bignum (Left);
2284 elsif not Is_RTE (Rtype, RE_Bignum) then
2285 Right := Convert_To_Bignum (Right);
2286 end if;
2288 -- We rewrite our node with:
2290 -- do
2291 -- Bnn : Result_Type;
2292 -- declare
2293 -- M : Mark_Id := SS_Mark;
2294 -- begin
2295 -- Bnn := Big_xx (Left, Right); (xx = EQ, NT etc)
2296 -- SS_Release (M);
2297 -- end;
2298 -- in
2299 -- Bnn
2300 -- end
2302 declare
2303 Blk : constant Node_Id := Make_Bignum_Block (Loc);
2304 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
2305 Ent : RE_Id;
2307 begin
2308 case N_Op_Compare (Nkind (N)) is
2309 when N_Op_Eq => Ent := RE_Big_EQ;
2310 when N_Op_Ge => Ent := RE_Big_GE;
2311 when N_Op_Gt => Ent := RE_Big_GT;
2312 when N_Op_Le => Ent := RE_Big_LE;
2313 when N_Op_Lt => Ent := RE_Big_LT;
2314 when N_Op_Ne => Ent := RE_Big_NE;
2315 end case;
2317 -- Insert assignment to Bnn into the bignum block
2319 Insert_Before
2320 (First (Statements (Handled_Statement_Sequence (Blk))),
2321 Make_Assignment_Statement (Loc,
2322 Name => New_Occurrence_Of (Bnn, Loc),
2323 Expression =>
2324 Make_Function_Call (Loc,
2325 Name =>
2326 New_Occurrence_Of (RTE (Ent), Loc),
2327 Parameter_Associations => New_List (Left, Right))));
2329 -- Now do the rewrite with expression actions
2331 Rewrite (N,
2332 Make_Expression_With_Actions (Loc,
2333 Actions => New_List (
2334 Make_Object_Declaration (Loc,
2335 Defining_Identifier => Bnn,
2336 Object_Definition =>
2337 New_Occurrence_Of (Result_Type, Loc)),
2338 Blk),
2339 Expression => New_Occurrence_Of (Bnn, Loc)));
2340 Analyze_And_Resolve (N, Result_Type);
2341 end;
2342 end;
2344 -- No bignums involved, but types are different, so we must have
2345 -- rewritten one of the operands as a Long_Long_Integer but not
2346 -- the other one.
2348 -- If left operand is Long_Long_Integer, convert right operand
2349 -- and we are done (with a comparison of two Long_Long_Integers).
2351 elsif Ltype = LLIB then
2352 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
2353 Analyze_And_Resolve (Right_Opnd (N), LLIB, Suppress => All_Checks);
2354 return;
2356 -- If right operand is Long_Long_Integer, convert left operand
2357 -- and we are done (with a comparison of two Long_Long_Integers).
2359 -- This is the only remaining possibility
2361 else pragma Assert (Rtype = LLIB);
2362 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
2363 Analyze_And_Resolve (Left_Opnd (N), LLIB, Suppress => All_Checks);
2364 return;
2365 end if;
2366 end;
2367 end Expand_Compare_Minimize_Eliminate_Overflow;
2369 -------------------------------
2370 -- Expand_Composite_Equality --
2371 -------------------------------
2373 -- This function is only called for comparing internal fields of composite
2374 -- types when these fields are themselves composites. This is a special
2375 -- case because it is not possible to respect normal Ada visibility rules.
2377 function Expand_Composite_Equality
2378 (Nod : Node_Id;
2379 Typ : Entity_Id;
2380 Lhs : Node_Id;
2381 Rhs : Node_Id;
2382 Bodies : List_Id) return Node_Id
2384 Loc : constant Source_Ptr := Sloc (Nod);
2385 Full_Type : Entity_Id;
2386 Eq_Op : Entity_Id;
2388 -- Start of processing for Expand_Composite_Equality
2390 begin
2391 if Is_Private_Type (Typ) then
2392 Full_Type := Underlying_Type (Typ);
2393 else
2394 Full_Type := Typ;
2395 end if;
2397 -- If the private type has no completion the context may be the
2398 -- expansion of a composite equality for a composite type with some
2399 -- still incomplete components. The expression will not be analyzed
2400 -- until the enclosing type is completed, at which point this will be
2401 -- properly expanded, unless there is a bona fide completion error.
2403 if No (Full_Type) then
2404 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2405 end if;
2407 Full_Type := Base_Type (Full_Type);
2409 -- When the base type itself is private, use the full view to expand
2410 -- the composite equality.
2412 if Is_Private_Type (Full_Type) then
2413 Full_Type := Underlying_Type (Full_Type);
2414 end if;
2416 -- Case of array types
2418 if Is_Array_Type (Full_Type) then
2420 -- If the operand is an elementary type other than a floating-point
2421 -- type, then we can simply use the built-in block bitwise equality,
2422 -- since the predefined equality operators always apply and bitwise
2423 -- equality is fine for all these cases.
2425 if Is_Elementary_Type (Component_Type (Full_Type))
2426 and then not Is_Floating_Point_Type (Component_Type (Full_Type))
2427 then
2428 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2430 -- For composite component types, and floating-point types, use the
2431 -- expansion. This deals with tagged component types (where we use
2432 -- the applicable equality routine) and floating-point (where we
2433 -- need to worry about negative zeroes), and also the case of any
2434 -- composite type recursively containing such fields.
2436 else
2437 declare
2438 Comp_Typ : Entity_Id;
2439 Hi : Node_Id;
2440 Indx : Node_Id;
2441 Ityp : Entity_Id;
2442 Lo : Node_Id;
2444 begin
2445 -- Do the comparison in the type (or its full view) and not in
2446 -- its unconstrained base type, because the latter operation is
2447 -- more complex and would also require an unchecked conversion.
2449 if Is_Private_Type (Typ) then
2450 Comp_Typ := Underlying_Type (Typ);
2451 else
2452 Comp_Typ := Typ;
2453 end if;
2455 -- Except for the case where the bounds of the type depend on a
2456 -- discriminant, or else we would run into scoping issues.
2458 Indx := First_Index (Comp_Typ);
2459 while Present (Indx) loop
2460 Ityp := Etype (Indx);
2462 Lo := Type_Low_Bound (Ityp);
2463 Hi := Type_High_Bound (Ityp);
2465 if (Nkind (Lo) = N_Identifier
2466 and then Ekind (Entity (Lo)) = E_Discriminant)
2467 or else
2468 (Nkind (Hi) = N_Identifier
2469 and then Ekind (Entity (Hi)) = E_Discriminant)
2470 then
2471 Comp_Typ := Full_Type;
2472 exit;
2473 end if;
2475 Next_Index (Indx);
2476 end loop;
2478 return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Comp_Typ);
2479 end;
2480 end if;
2482 -- Case of tagged record types
2484 elsif Is_Tagged_Type (Full_Type) then
2485 Eq_Op := Find_Primitive_Eq (Typ);
2486 pragma Assert (Present (Eq_Op));
2488 return
2489 Make_Function_Call (Loc,
2490 Name => New_Occurrence_Of (Eq_Op, Loc),
2491 Parameter_Associations =>
2492 New_List
2493 (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2494 Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2496 -- Case of untagged record types
2498 elsif Is_Record_Type (Full_Type) then
2499 Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2501 if Present (Eq_Op) then
2502 if Etype (First_Formal (Eq_Op)) /= Full_Type then
2504 -- Inherited equality from parent type. Convert the actuals to
2505 -- match signature of operation.
2507 declare
2508 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2510 begin
2511 return
2512 Make_Function_Call (Loc,
2513 Name => New_Occurrence_Of (Eq_Op, Loc),
2514 Parameter_Associations => New_List (
2515 OK_Convert_To (T, Lhs),
2516 OK_Convert_To (T, Rhs)));
2517 end;
2519 else
2520 -- Comparison between Unchecked_Union components
2522 if Is_Unchecked_Union (Full_Type) then
2523 declare
2524 Lhs_Type : Node_Id := Full_Type;
2525 Rhs_Type : Node_Id := Full_Type;
2526 Lhs_Discr_Val : Node_Id;
2527 Rhs_Discr_Val : Node_Id;
2529 begin
2530 -- Lhs subtype
2532 if Nkind (Lhs) = N_Selected_Component then
2533 Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2534 end if;
2536 -- Rhs subtype
2538 if Nkind (Rhs) = N_Selected_Component then
2539 Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2540 end if;
2542 -- Lhs of the composite equality
2544 if Is_Constrained (Lhs_Type) then
2546 -- Since the enclosing record type can never be an
2547 -- Unchecked_Union (this code is executed for records
2548 -- that do not have variants), we may reference its
2549 -- discriminant(s).
2551 if Nkind (Lhs) = N_Selected_Component
2552 and then Has_Per_Object_Constraint
2553 (Entity (Selector_Name (Lhs)))
2554 then
2555 Lhs_Discr_Val :=
2556 Make_Selected_Component (Loc,
2557 Prefix => Prefix (Lhs),
2558 Selector_Name =>
2559 New_Copy
2560 (Get_Discriminant_Value
2561 (First_Discriminant (Lhs_Type),
2562 Lhs_Type,
2563 Stored_Constraint (Lhs_Type))));
2565 else
2566 Lhs_Discr_Val :=
2567 New_Copy
2568 (Get_Discriminant_Value
2569 (First_Discriminant (Lhs_Type),
2570 Lhs_Type,
2571 Stored_Constraint (Lhs_Type)));
2573 end if;
2574 else
2575 -- It is not possible to infer the discriminant since
2576 -- the subtype is not constrained.
2578 return
2579 Make_Raise_Program_Error (Loc,
2580 Reason => PE_Unchecked_Union_Restriction);
2581 end if;
2583 -- Rhs of the composite equality
2585 if Is_Constrained (Rhs_Type) then
2586 if Nkind (Rhs) = N_Selected_Component
2587 and then Has_Per_Object_Constraint
2588 (Entity (Selector_Name (Rhs)))
2589 then
2590 Rhs_Discr_Val :=
2591 Make_Selected_Component (Loc,
2592 Prefix => Prefix (Rhs),
2593 Selector_Name =>
2594 New_Copy
2595 (Get_Discriminant_Value
2596 (First_Discriminant (Rhs_Type),
2597 Rhs_Type,
2598 Stored_Constraint (Rhs_Type))));
2600 else
2601 Rhs_Discr_Val :=
2602 New_Copy
2603 (Get_Discriminant_Value
2604 (First_Discriminant (Rhs_Type),
2605 Rhs_Type,
2606 Stored_Constraint (Rhs_Type)));
2608 end if;
2609 else
2610 return
2611 Make_Raise_Program_Error (Loc,
2612 Reason => PE_Unchecked_Union_Restriction);
2613 end if;
2615 -- Call the TSS equality function with the inferred
2616 -- discriminant values.
2618 return
2619 Make_Function_Call (Loc,
2620 Name => New_Occurrence_Of (Eq_Op, Loc),
2621 Parameter_Associations => New_List (
2622 Lhs,
2623 Rhs,
2624 Lhs_Discr_Val,
2625 Rhs_Discr_Val));
2626 end;
2628 -- All cases other than comparing Unchecked_Union types
2630 else
2631 declare
2632 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2633 begin
2634 return
2635 Make_Function_Call (Loc,
2636 Name =>
2637 New_Occurrence_Of (Eq_Op, Loc),
2638 Parameter_Associations => New_List (
2639 OK_Convert_To (T, Lhs),
2640 OK_Convert_To (T, Rhs)));
2641 end;
2642 end if;
2643 end if;
2645 -- Equality composes in Ada 2012 for untagged record types. It also
2646 -- composes for bounded strings, because they are part of the
2647 -- predefined environment. We could make it compose for bounded
2648 -- strings by making them tagged, or by making sure all subcomponents
2649 -- are set to the same value, even when not used. Instead, we have
2650 -- this special case in the compiler, because it's more efficient.
2652 elsif Ada_Version >= Ada_2012 or else Is_Bounded_String (Typ) then
2654 -- If no TSS has been created for the type, check whether there is
2655 -- a primitive equality declared for it.
2657 declare
2658 Op : constant Node_Id := Build_Eq_Call (Typ, Loc, Lhs, Rhs);
2660 begin
2661 -- Use user-defined primitive if it exists, otherwise use
2662 -- predefined equality.
2664 if Present (Op) then
2665 return Op;
2666 else
2667 return Make_Op_Eq (Loc, Lhs, Rhs);
2668 end if;
2669 end;
2671 else
2672 return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2673 end if;
2675 -- Non-composite types (always use predefined equality)
2677 else
2678 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2679 end if;
2680 end Expand_Composite_Equality;
2682 ------------------------
2683 -- Expand_Concatenate --
2684 ------------------------
2686 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2687 Loc : constant Source_Ptr := Sloc (Cnode);
2689 Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2690 -- Result type of concatenation
2692 Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2693 -- Component type. Elements of this component type can appear as one
2694 -- of the operands of concatenation as well as arrays.
2696 Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2697 -- Index subtype
2699 Ityp : constant Entity_Id := Base_Type (Istyp);
2700 -- Index type. This is the base type of the index subtype, and is used
2701 -- for all computed bounds (which may be out of range of Istyp in the
2702 -- case of null ranges).
2704 Artyp : Entity_Id;
2705 -- This is the type we use to do arithmetic to compute the bounds and
2706 -- lengths of operands. The choice of this type is a little subtle and
2707 -- is discussed in a separate section at the start of the body code.
2709 Concatenation_Error : exception;
2710 -- Raised if concatenation is sure to raise a CE
2712 Result_May_Be_Null : Boolean := True;
2713 -- Reset to False if at least one operand is encountered which is known
2714 -- at compile time to be non-null. Used for handling the special case
2715 -- of setting the high bound to the last operand high bound for a null
2716 -- result, thus ensuring a proper high bound in the super-flat case.
2718 N : constant Nat := List_Length (Opnds);
2719 -- Number of concatenation operands including possibly null operands
2721 NN : Nat := 0;
2722 -- Number of operands excluding any known to be null, except that the
2723 -- last operand is always retained, in case it provides the bounds for
2724 -- a null result.
2726 Opnd : Node_Id := Empty;
2727 -- Current operand being processed in the loop through operands. After
2728 -- this loop is complete, always contains the last operand (which is not
2729 -- the same as Operands (NN), since null operands are skipped).
2731 -- Arrays describing the operands, only the first NN entries of each
2732 -- array are set (NN < N when we exclude known null operands).
2734 Is_Fixed_Length : array (1 .. N) of Boolean;
2735 -- True if length of corresponding operand known at compile time
2737 Operands : array (1 .. N) of Node_Id;
2738 -- Set to the corresponding entry in the Opnds list (but note that null
2739 -- operands are excluded, so not all entries in the list are stored).
2741 Fixed_Length : array (1 .. N) of Uint;
2742 -- Set to length of operand. Entries in this array are set only if the
2743 -- corresponding entry in Is_Fixed_Length is True.
2745 Opnd_Low_Bound : array (1 .. N) of Node_Id;
2746 -- Set to lower bound of operand. Either an integer literal in the case
2747 -- where the bound is known at compile time, else actual lower bound.
2748 -- The operand low bound is of type Ityp.
2750 Var_Length : array (1 .. N) of Entity_Id;
2751 -- Set to an entity of type Natural that contains the length of an
2752 -- operand whose length is not known at compile time. Entries in this
2753 -- array are set only if the corresponding entry in Is_Fixed_Length
2754 -- is False. The entity is of type Artyp.
2756 Aggr_Length : array (0 .. N) of Node_Id;
2757 -- The J'th entry in an expression node that represents the total length
2758 -- of operands 1 through J. It is either an integer literal node, or a
2759 -- reference to a constant entity with the right value, so it is fine
2760 -- to just do a Copy_Node to get an appropriate copy. The extra zero'th
2761 -- entry always is set to zero. The length is of type Artyp.
2763 Low_Bound : Node_Id;
2764 -- A tree node representing the low bound of the result (of type Ityp).
2765 -- This is either an integer literal node, or an identifier reference to
2766 -- a constant entity initialized to the appropriate value.
2768 Last_Opnd_Low_Bound : Node_Id := Empty;
2769 -- A tree node representing the low bound of the last operand. This
2770 -- need only be set if the result could be null. It is used for the
2771 -- special case of setting the right low bound for a null result.
2772 -- This is of type Ityp.
2774 Last_Opnd_High_Bound : Node_Id := Empty;
2775 -- A tree node representing the high bound of the last operand. This
2776 -- need only be set if the result could be null. It is used for the
2777 -- special case of setting the right high bound for a null result.
2778 -- This is of type Ityp.
2780 High_Bound : Node_Id := Empty;
2781 -- A tree node representing the high bound of the result (of type Ityp)
2783 Result : Node_Id;
2784 -- Result of the concatenation (of type Ityp)
2786 Actions : constant List_Id := New_List;
2787 -- Collect actions to be inserted
2789 Known_Non_Null_Operand_Seen : Boolean;
2790 -- Set True during generation of the assignments of operands into
2791 -- result once an operand known to be non-null has been seen.
2793 function Library_Level_Target return Boolean;
2794 -- Return True if the concatenation is within the expression of the
2795 -- declaration of a library-level object.
2797 function Make_Artyp_Literal (Val : Nat) return Node_Id;
2798 -- This function makes an N_Integer_Literal node that is returned in
2799 -- analyzed form with the type set to Artyp. Importantly this literal
2800 -- is not flagged as static, so that if we do computations with it that
2801 -- result in statically detected out of range conditions, we will not
2802 -- generate error messages but instead warning messages.
2804 function To_Artyp (X : Node_Id) return Node_Id;
2805 -- Given a node of type Ityp, returns the corresponding value of type
2806 -- Artyp. For non-enumeration types, this is a plain integer conversion.
2807 -- For enum types, the Pos of the value is returned.
2809 function To_Ityp (X : Node_Id) return Node_Id;
2810 -- The inverse function (uses Val in the case of enumeration types)
2812 --------------------------
2813 -- Library_Level_Target --
2814 --------------------------
2816 function Library_Level_Target return Boolean is
2817 P : Node_Id := Parent (Cnode);
2819 begin
2820 while Present (P) loop
2821 if Nkind (P) = N_Object_Declaration then
2822 return Is_Library_Level_Entity (Defining_Identifier (P));
2824 -- Prevent the search from going too far
2826 elsif Is_Body_Or_Package_Declaration (P) then
2827 return False;
2828 end if;
2830 P := Parent (P);
2831 end loop;
2833 return False;
2834 end Library_Level_Target;
2836 ------------------------
2837 -- Make_Artyp_Literal --
2838 ------------------------
2840 function Make_Artyp_Literal (Val : Nat) return Node_Id is
2841 Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
2842 begin
2843 Set_Etype (Result, Artyp);
2844 Set_Analyzed (Result, True);
2845 Set_Is_Static_Expression (Result, False);
2846 return Result;
2847 end Make_Artyp_Literal;
2849 --------------
2850 -- To_Artyp --
2851 --------------
2853 function To_Artyp (X : Node_Id) return Node_Id is
2854 begin
2855 if Ityp = Base_Type (Artyp) then
2856 return X;
2858 elsif Is_Enumeration_Type (Ityp) then
2859 return
2860 Make_Attribute_Reference (Loc,
2861 Prefix => New_Occurrence_Of (Ityp, Loc),
2862 Attribute_Name => Name_Pos,
2863 Expressions => New_List (X));
2865 else
2866 return Convert_To (Artyp, X);
2867 end if;
2868 end To_Artyp;
2870 -------------
2871 -- To_Ityp --
2872 -------------
2874 function To_Ityp (X : Node_Id) return Node_Id is
2875 begin
2876 if Is_Enumeration_Type (Ityp) then
2877 return
2878 Make_Attribute_Reference (Loc,
2879 Prefix => New_Occurrence_Of (Ityp, Loc),
2880 Attribute_Name => Name_Val,
2881 Expressions => New_List (X));
2883 -- Case where we will do a type conversion
2885 else
2886 if Ityp = Base_Type (Artyp) then
2887 return X;
2888 else
2889 return Convert_To (Ityp, X);
2890 end if;
2891 end if;
2892 end To_Ityp;
2894 -- Local Declarations
2896 Opnd_Typ : Entity_Id;
2897 Ent : Entity_Id;
2898 Len : Uint;
2899 J : Nat;
2900 Clen : Node_Id;
2901 Set : Boolean;
2903 -- Start of processing for Expand_Concatenate
2905 begin
2906 -- Choose an appropriate computational type
2908 -- We will be doing calculations of lengths and bounds in this routine
2909 -- and computing one from the other in some cases, e.g. getting the high
2910 -- bound by adding the length-1 to the low bound.
2912 -- We can't just use the index type, or even its base type for this
2913 -- purpose for two reasons. First it might be an enumeration type which
2914 -- is not suitable for computations of any kind, and second it may
2915 -- simply not have enough range. For example if the index type is
2916 -- -128..+127 then lengths can be up to 256, which is out of range of
2917 -- the type.
2919 -- For enumeration types, we can simply use Standard_Integer, this is
2920 -- sufficient since the actual number of enumeration literals cannot
2921 -- possibly exceed the range of integer (remember we will be doing the
2922 -- arithmetic with POS values, not representation values).
2924 if Is_Enumeration_Type (Ityp) then
2925 Artyp := Standard_Integer;
2927 -- If index type is Positive, we use the standard unsigned type, to give
2928 -- more room on the top of the range, obviating the need for an overflow
2929 -- check when creating the upper bound. This is needed to avoid junk
2930 -- overflow checks in the common case of String types.
2932 -- ??? Disabled for now
2934 -- elsif Istyp = Standard_Positive then
2935 -- Artyp := Standard_Unsigned;
2937 -- For modular types, we use a 32-bit modular type for types whose size
2938 -- is in the range 1-31 bits. For 32-bit unsigned types, we use the
2939 -- identity type, and for larger unsigned types we use 64-bits.
2941 elsif Is_Modular_Integer_Type (Ityp) then
2942 if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
2943 Artyp := Standard_Unsigned;
2944 elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
2945 Artyp := Ityp;
2946 else
2947 Artyp := RTE (RE_Long_Long_Unsigned);
2948 end if;
2950 -- Similar treatment for signed types
2952 else
2953 if RM_Size (Ityp) < RM_Size (Standard_Integer) then
2954 Artyp := Standard_Integer;
2955 elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
2956 Artyp := Ityp;
2957 else
2958 Artyp := Standard_Long_Long_Integer;
2959 end if;
2960 end if;
2962 -- Supply dummy entry at start of length array
2964 Aggr_Length (0) := Make_Artyp_Literal (0);
2966 -- Go through operands setting up the above arrays
2968 J := 1;
2969 while J <= N loop
2970 Opnd := Remove_Head (Opnds);
2971 Opnd_Typ := Etype (Opnd);
2973 -- The parent got messed up when we put the operands in a list,
2974 -- so now put back the proper parent for the saved operand, that
2975 -- is to say the concatenation node, to make sure that each operand
2976 -- is seen as a subexpression, e.g. if actions must be inserted.
2978 Set_Parent (Opnd, Cnode);
2980 -- Set will be True when we have setup one entry in the array
2982 Set := False;
2984 -- Singleton element (or character literal) case
2986 if Base_Type (Opnd_Typ) = Ctyp then
2987 NN := NN + 1;
2988 Operands (NN) := Opnd;
2989 Is_Fixed_Length (NN) := True;
2990 Fixed_Length (NN) := Uint_1;
2991 Result_May_Be_Null := False;
2993 -- Set low bound of operand (no need to set Last_Opnd_High_Bound
2994 -- since we know that the result cannot be null).
2996 Opnd_Low_Bound (NN) :=
2997 Make_Attribute_Reference (Loc,
2998 Prefix => New_Occurrence_Of (Istyp, Loc),
2999 Attribute_Name => Name_First);
3001 Set := True;
3003 -- String literal case (can only occur for strings of course)
3005 elsif Nkind (Opnd) = N_String_Literal then
3006 Len := String_Literal_Length (Opnd_Typ);
3008 if Len /= 0 then
3009 Result_May_Be_Null := False;
3010 end if;
3012 -- Capture last operand low and high bound if result could be null
3014 if J = N and then Result_May_Be_Null then
3015 Last_Opnd_Low_Bound :=
3016 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3018 Last_Opnd_High_Bound :=
3019 Make_Op_Subtract (Loc,
3020 Left_Opnd =>
3021 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
3022 Right_Opnd => Make_Integer_Literal (Loc, 1));
3023 end if;
3025 -- Skip null string literal
3027 if J < N and then Len = 0 then
3028 goto Continue;
3029 end if;
3031 NN := NN + 1;
3032 Operands (NN) := Opnd;
3033 Is_Fixed_Length (NN) := True;
3035 -- Set length and bounds
3037 Fixed_Length (NN) := Len;
3039 Opnd_Low_Bound (NN) :=
3040 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3042 Set := True;
3044 -- All other cases
3046 else
3047 -- Check constrained case with known bounds
3049 if Is_Constrained (Opnd_Typ) then
3050 declare
3051 Index : constant Node_Id := First_Index (Opnd_Typ);
3052 Indx_Typ : constant Entity_Id := Etype (Index);
3053 Lo : constant Node_Id := Type_Low_Bound (Indx_Typ);
3054 Hi : constant Node_Id := Type_High_Bound (Indx_Typ);
3056 begin
3057 -- Fixed length constrained array type with known at compile
3058 -- time bounds is last case of fixed length operand.
3060 if Compile_Time_Known_Value (Lo)
3061 and then
3062 Compile_Time_Known_Value (Hi)
3063 then
3064 declare
3065 Loval : constant Uint := Expr_Value (Lo);
3066 Hival : constant Uint := Expr_Value (Hi);
3067 Len : constant Uint :=
3068 UI_Max (Hival - Loval + 1, Uint_0);
3070 begin
3071 if Len > 0 then
3072 Result_May_Be_Null := False;
3073 end if;
3075 -- Capture last operand bounds if result could be null
3077 if J = N and then Result_May_Be_Null then
3078 Last_Opnd_Low_Bound :=
3079 Convert_To (Ityp,
3080 Make_Integer_Literal (Loc, Expr_Value (Lo)));
3082 Last_Opnd_High_Bound :=
3083 Convert_To (Ityp,
3084 Make_Integer_Literal (Loc, Expr_Value (Hi)));
3085 end if;
3087 -- Exclude null length case unless last operand
3089 if J < N and then Len = 0 then
3090 goto Continue;
3091 end if;
3093 NN := NN + 1;
3094 Operands (NN) := Opnd;
3095 Is_Fixed_Length (NN) := True;
3096 Fixed_Length (NN) := Len;
3098 Opnd_Low_Bound (NN) :=
3099 To_Ityp
3100 (Make_Integer_Literal (Loc, Expr_Value (Lo)));
3101 Set := True;
3102 end;
3103 end if;
3104 end;
3105 end if;
3107 -- All cases where the length is not known at compile time, or the
3108 -- special case of an operand which is known to be null but has a
3109 -- lower bound other than 1 or is other than a string type.
3111 if not Set then
3112 NN := NN + 1;
3114 -- Capture operand bounds
3116 Opnd_Low_Bound (NN) :=
3117 Make_Attribute_Reference (Loc,
3118 Prefix =>
3119 Duplicate_Subexpr (Opnd, Name_Req => True),
3120 Attribute_Name => Name_First);
3122 -- Capture last operand bounds if result could be null
3124 if J = N and Result_May_Be_Null then
3125 Last_Opnd_Low_Bound :=
3126 Convert_To (Ityp,
3127 Make_Attribute_Reference (Loc,
3128 Prefix =>
3129 Duplicate_Subexpr (Opnd, Name_Req => True),
3130 Attribute_Name => Name_First));
3132 Last_Opnd_High_Bound :=
3133 Convert_To (Ityp,
3134 Make_Attribute_Reference (Loc,
3135 Prefix =>
3136 Duplicate_Subexpr (Opnd, Name_Req => True),
3137 Attribute_Name => Name_Last));
3138 end if;
3140 -- Capture length of operand in entity
3142 Operands (NN) := Opnd;
3143 Is_Fixed_Length (NN) := False;
3145 Var_Length (NN) := Make_Temporary (Loc, 'L');
3147 Append_To (Actions,
3148 Make_Object_Declaration (Loc,
3149 Defining_Identifier => Var_Length (NN),
3150 Constant_Present => True,
3151 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3152 Expression =>
3153 Make_Attribute_Reference (Loc,
3154 Prefix =>
3155 Duplicate_Subexpr (Opnd, Name_Req => True),
3156 Attribute_Name => Name_Length)));
3157 end if;
3158 end if;
3160 -- Set next entry in aggregate length array
3162 -- For first entry, make either integer literal for fixed length
3163 -- or a reference to the saved length for variable length.
3165 if NN = 1 then
3166 if Is_Fixed_Length (1) then
3167 Aggr_Length (1) := Make_Integer_Literal (Loc, Fixed_Length (1));
3168 else
3169 Aggr_Length (1) := New_Occurrence_Of (Var_Length (1), Loc);
3170 end if;
3172 -- If entry is fixed length and only fixed lengths so far, make
3173 -- appropriate new integer literal adding new length.
3175 elsif Is_Fixed_Length (NN)
3176 and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
3177 then
3178 Aggr_Length (NN) :=
3179 Make_Integer_Literal (Loc,
3180 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
3182 -- All other cases, construct an addition node for the length and
3183 -- create an entity initialized to this length.
3185 else
3186 Ent := Make_Temporary (Loc, 'L');
3188 if Is_Fixed_Length (NN) then
3189 Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
3190 else
3191 Clen := New_Occurrence_Of (Var_Length (NN), Loc);
3192 end if;
3194 Append_To (Actions,
3195 Make_Object_Declaration (Loc,
3196 Defining_Identifier => Ent,
3197 Constant_Present => True,
3198 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3199 Expression =>
3200 Make_Op_Add (Loc,
3201 Left_Opnd => New_Copy_Tree (Aggr_Length (NN - 1)),
3202 Right_Opnd => Clen)));
3204 Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
3205 end if;
3207 <<Continue>>
3208 J := J + 1;
3209 end loop;
3211 -- If we have only skipped null operands, return the last operand
3213 if NN = 0 then
3214 Result := Opnd;
3215 goto Done;
3216 end if;
3218 -- If we have only one non-null operand, return it and we are done.
3219 -- There is one case in which this cannot be done, and that is when
3220 -- the sole operand is of the element type, in which case it must be
3221 -- converted to an array, and the easiest way of doing that is to go
3222 -- through the normal general circuit.
3224 if NN = 1 and then Base_Type (Etype (Operands (1))) /= Ctyp then
3225 Result := Operands (1);
3226 goto Done;
3227 end if;
3229 -- Cases where we have a real concatenation
3231 -- Next step is to find the low bound for the result array that we
3232 -- will allocate. The rules for this are in (RM 4.5.6(5-7)).
3234 -- If the ultimate ancestor of the index subtype is a constrained array
3235 -- definition, then the lower bound is that of the index subtype as
3236 -- specified by (RM 4.5.3(6)).
3238 -- The right test here is to go to the root type, and then the ultimate
3239 -- ancestor is the first subtype of this root type.
3241 if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
3242 Low_Bound :=
3243 Make_Attribute_Reference (Loc,
3244 Prefix =>
3245 New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
3246 Attribute_Name => Name_First);
3248 -- If the first operand in the list has known length we know that
3249 -- the lower bound of the result is the lower bound of this operand.
3251 elsif Is_Fixed_Length (1) then
3252 Low_Bound := Opnd_Low_Bound (1);
3254 -- OK, we don't know the lower bound, we have to build a horrible
3255 -- if expression node of the form
3257 -- if Cond1'Length /= 0 then
3258 -- Opnd1 low bound
3259 -- else
3260 -- if Opnd2'Length /= 0 then
3261 -- Opnd2 low bound
3262 -- else
3263 -- ...
3265 -- The nesting ends either when we hit an operand whose length is known
3266 -- at compile time, or on reaching the last operand, whose low bound we
3267 -- take unconditionally whether or not it is null. It's easiest to do
3268 -- this with a recursive procedure:
3270 else
3271 declare
3272 function Get_Known_Bound (J : Nat) return Node_Id;
3273 -- Returns the lower bound determined by operands J .. NN
3275 ---------------------
3276 -- Get_Known_Bound --
3277 ---------------------
3279 function Get_Known_Bound (J : Nat) return Node_Id is
3280 begin
3281 if Is_Fixed_Length (J) or else J = NN then
3282 return New_Copy_Tree (Opnd_Low_Bound (J));
3284 else
3285 return
3286 Make_If_Expression (Loc,
3287 Expressions => New_List (
3289 Make_Op_Ne (Loc,
3290 Left_Opnd =>
3291 New_Occurrence_Of (Var_Length (J), Loc),
3292 Right_Opnd =>
3293 Make_Integer_Literal (Loc, 0)),
3295 New_Copy_Tree (Opnd_Low_Bound (J)),
3296 Get_Known_Bound (J + 1)));
3297 end if;
3298 end Get_Known_Bound;
3300 begin
3301 Ent := Make_Temporary (Loc, 'L');
3303 Append_To (Actions,
3304 Make_Object_Declaration (Loc,
3305 Defining_Identifier => Ent,
3306 Constant_Present => True,
3307 Object_Definition => New_Occurrence_Of (Ityp, Loc),
3308 Expression => Get_Known_Bound (1)));
3310 Low_Bound := New_Occurrence_Of (Ent, Loc);
3311 end;
3312 end if;
3314 -- Now we can safely compute the upper bound, normally
3315 -- Low_Bound + Length - 1.
3317 High_Bound :=
3318 To_Ityp
3319 (Make_Op_Add (Loc,
3320 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3321 Right_Opnd =>
3322 Make_Op_Subtract (Loc,
3323 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3324 Right_Opnd => Make_Artyp_Literal (1))));
3326 -- Note that calculation of the high bound may cause overflow in some
3327 -- very weird cases, so in the general case we need an overflow check on
3328 -- the high bound. We can avoid this for the common case of string types
3329 -- and other types whose index is Positive, since we chose a wider range
3330 -- for the arithmetic type. If checks are suppressed we do not set the
3331 -- flag, and possibly superfluous warnings will be omitted.
3333 if Istyp /= Standard_Positive
3334 and then not Overflow_Checks_Suppressed (Istyp)
3335 then
3336 Activate_Overflow_Check (High_Bound);
3337 end if;
3339 -- Handle the exceptional case where the result is null, in which case
3340 -- case the bounds come from the last operand (so that we get the proper
3341 -- bounds if the last operand is super-flat).
3343 if Result_May_Be_Null then
3344 Low_Bound :=
3345 Make_If_Expression (Loc,
3346 Expressions => New_List (
3347 Make_Op_Eq (Loc,
3348 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3349 Right_Opnd => Make_Artyp_Literal (0)),
3350 Last_Opnd_Low_Bound,
3351 Low_Bound));
3353 High_Bound :=
3354 Make_If_Expression (Loc,
3355 Expressions => New_List (
3356 Make_Op_Eq (Loc,
3357 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3358 Right_Opnd => Make_Artyp_Literal (0)),
3359 Last_Opnd_High_Bound,
3360 High_Bound));
3361 end if;
3363 -- Here is where we insert the saved up actions
3365 Insert_Actions (Cnode, Actions, Suppress => All_Checks);
3367 -- Now we construct an array object with appropriate bounds. We mark
3368 -- the target as internal to prevent useless initialization when
3369 -- Initialize_Scalars is enabled. Also since this is the actual result
3370 -- entity, we make sure we have debug information for the result.
3372 Ent := Make_Temporary (Loc, 'S');
3373 Set_Is_Internal (Ent);
3374 Set_Debug_Info_Needed (Ent);
3376 -- If the bound is statically known to be out of range, we do not want
3377 -- to abort, we want a warning and a runtime constraint error. Note that
3378 -- we have arranged that the result will not be treated as a static
3379 -- constant, so we won't get an illegality during this insertion.
3381 Insert_Action (Cnode,
3382 Make_Object_Declaration (Loc,
3383 Defining_Identifier => Ent,
3384 Object_Definition =>
3385 Make_Subtype_Indication (Loc,
3386 Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
3387 Constraint =>
3388 Make_Index_Or_Discriminant_Constraint (Loc,
3389 Constraints => New_List (
3390 Make_Range (Loc,
3391 Low_Bound => Low_Bound,
3392 High_Bound => High_Bound))))),
3393 Suppress => All_Checks);
3395 -- If the result of the concatenation appears as the initializing
3396 -- expression of an object declaration, we can just rename the
3397 -- result, rather than copying it.
3399 Set_OK_To_Rename (Ent);
3401 -- Catch the static out of range case now
3403 if Raises_Constraint_Error (High_Bound) then
3404 raise Concatenation_Error;
3405 end if;
3407 -- Now we will generate the assignments to do the actual concatenation
3409 -- There is one case in which we will not do this, namely when all the
3410 -- following conditions are met:
3412 -- The result type is Standard.String
3414 -- There are nine or fewer retained (non-null) operands
3416 -- The optimization level is -O0 or the debug flag gnatd.C is set,
3417 -- and the debug flag gnatd.c is not set.
3419 -- The corresponding System.Concat_n.Str_Concat_n routine is
3420 -- available in the run time.
3422 -- If all these conditions are met then we generate a call to the
3423 -- relevant concatenation routine. The purpose of this is to avoid
3424 -- undesirable code bloat at -O0.
3426 -- If the concatenation is within the declaration of a library-level
3427 -- object, we call the built-in concatenation routines to prevent code
3428 -- bloat, regardless of the optimization level. This is space efficient
3429 -- and prevents linking problems when units are compiled with different
3430 -- optimization levels.
3432 if Atyp = Standard_String
3433 and then NN in 2 .. 9
3434 and then (((Optimization_Level = 0 or else Debug_Flag_Dot_CC)
3435 and then not Debug_Flag_Dot_C)
3436 or else Library_Level_Target)
3437 then
3438 declare
3439 RR : constant array (Nat range 2 .. 9) of RE_Id :=
3440 (RE_Str_Concat_2,
3441 RE_Str_Concat_3,
3442 RE_Str_Concat_4,
3443 RE_Str_Concat_5,
3444 RE_Str_Concat_6,
3445 RE_Str_Concat_7,
3446 RE_Str_Concat_8,
3447 RE_Str_Concat_9);
3449 begin
3450 if RTE_Available (RR (NN)) then
3451 declare
3452 Opnds : constant List_Id :=
3453 New_List (New_Occurrence_Of (Ent, Loc));
3455 begin
3456 for J in 1 .. NN loop
3457 if Is_List_Member (Operands (J)) then
3458 Remove (Operands (J));
3459 end if;
3461 if Base_Type (Etype (Operands (J))) = Ctyp then
3462 Append_To (Opnds,
3463 Make_Aggregate (Loc,
3464 Component_Associations => New_List (
3465 Make_Component_Association (Loc,
3466 Choices => New_List (
3467 Make_Integer_Literal (Loc, 1)),
3468 Expression => Operands (J)))));
3470 else
3471 Append_To (Opnds, Operands (J));
3472 end if;
3473 end loop;
3475 Insert_Action (Cnode,
3476 Make_Procedure_Call_Statement (Loc,
3477 Name => New_Occurrence_Of (RTE (RR (NN)), Loc),
3478 Parameter_Associations => Opnds));
3480 Result := New_Occurrence_Of (Ent, Loc);
3481 goto Done;
3482 end;
3483 end if;
3484 end;
3485 end if;
3487 -- Not special case so generate the assignments
3489 Known_Non_Null_Operand_Seen := False;
3491 for J in 1 .. NN loop
3492 declare
3493 Lo : constant Node_Id :=
3494 Make_Op_Add (Loc,
3495 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3496 Right_Opnd => Aggr_Length (J - 1));
3498 Hi : constant Node_Id :=
3499 Make_Op_Add (Loc,
3500 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3501 Right_Opnd =>
3502 Make_Op_Subtract (Loc,
3503 Left_Opnd => Aggr_Length (J),
3504 Right_Opnd => Make_Artyp_Literal (1)));
3506 begin
3507 -- Singleton case, simple assignment
3509 if Base_Type (Etype (Operands (J))) = Ctyp then
3510 Known_Non_Null_Operand_Seen := True;
3511 Insert_Action (Cnode,
3512 Make_Assignment_Statement (Loc,
3513 Name =>
3514 Make_Indexed_Component (Loc,
3515 Prefix => New_Occurrence_Of (Ent, Loc),
3516 Expressions => New_List (To_Ityp (Lo))),
3517 Expression => Operands (J)),
3518 Suppress => All_Checks);
3520 -- Array case, slice assignment, skipped when argument is fixed
3521 -- length and known to be null.
3523 elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
3524 declare
3525 Assign : Node_Id :=
3526 Make_Assignment_Statement (Loc,
3527 Name =>
3528 Make_Slice (Loc,
3529 Prefix =>
3530 New_Occurrence_Of (Ent, Loc),
3531 Discrete_Range =>
3532 Make_Range (Loc,
3533 Low_Bound => To_Ityp (Lo),
3534 High_Bound => To_Ityp (Hi))),
3535 Expression => Operands (J));
3536 begin
3537 if Is_Fixed_Length (J) then
3538 Known_Non_Null_Operand_Seen := True;
3540 elsif not Known_Non_Null_Operand_Seen then
3542 -- Here if operand length is not statically known and no
3543 -- operand known to be non-null has been processed yet.
3544 -- If operand length is 0, we do not need to perform the
3545 -- assignment, and we must avoid the evaluation of the
3546 -- high bound of the slice, since it may underflow if the
3547 -- low bound is Ityp'First.
3549 Assign :=
3550 Make_Implicit_If_Statement (Cnode,
3551 Condition =>
3552 Make_Op_Ne (Loc,
3553 Left_Opnd =>
3554 New_Occurrence_Of (Var_Length (J), Loc),
3555 Right_Opnd => Make_Integer_Literal (Loc, 0)),
3556 Then_Statements => New_List (Assign));
3557 end if;
3559 Insert_Action (Cnode, Assign, Suppress => All_Checks);
3560 end;
3561 end if;
3562 end;
3563 end loop;
3565 -- Finally we build the result, which is a reference to the array object
3567 Result := New_Occurrence_Of (Ent, Loc);
3569 <<Done>>
3570 Rewrite (Cnode, Result);
3571 Analyze_And_Resolve (Cnode, Atyp);
3573 exception
3574 when Concatenation_Error =>
3576 -- Kill warning generated for the declaration of the static out of
3577 -- range high bound, and instead generate a Constraint_Error with
3578 -- an appropriate specific message.
3580 Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3581 Apply_Compile_Time_Constraint_Error
3582 (N => Cnode,
3583 Msg => "concatenation result upper bound out of range??",
3584 Reason => CE_Range_Check_Failed);
3585 end Expand_Concatenate;
3587 ---------------------------------------------------
3588 -- Expand_Membership_Minimize_Eliminate_Overflow --
3589 ---------------------------------------------------
3591 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id) is
3592 pragma Assert (Nkind (N) = N_In);
3593 -- Despite the name, this routine applies only to N_In, not to
3594 -- N_Not_In. The latter is always rewritten as not (X in Y).
3596 Result_Type : constant Entity_Id := Etype (N);
3597 -- Capture result type, may be a derived boolean type
3599 Loc : constant Source_Ptr := Sloc (N);
3600 Lop : constant Node_Id := Left_Opnd (N);
3601 Rop : constant Node_Id := Right_Opnd (N);
3603 -- Note: there are many referencs to Etype (Lop) and Etype (Rop). It
3604 -- is thus tempting to capture these values, but due to the rewrites
3605 -- that occur as a result of overflow checking, these values change
3606 -- as we go along, and it is safe just to always use Etype explicitly.
3608 Restype : constant Entity_Id := Etype (N);
3609 -- Save result type
3611 Lo, Hi : Uint;
3612 -- Bounds in Minimize calls, not used currently
3614 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
3615 -- Entity for Long_Long_Integer'Base (Standard should export this???)
3617 begin
3618 Minimize_Eliminate_Overflows (Lop, Lo, Hi, Top_Level => False);
3620 -- If right operand is a subtype name, and the subtype name has no
3621 -- predicate, then we can just replace the right operand with an
3622 -- explicit range T'First .. T'Last, and use the explicit range code.
3624 if Nkind (Rop) /= N_Range
3625 and then No (Predicate_Function (Etype (Rop)))
3626 then
3627 declare
3628 Rtyp : constant Entity_Id := Etype (Rop);
3629 begin
3630 Rewrite (Rop,
3631 Make_Range (Loc,
3632 Low_Bound =>
3633 Make_Attribute_Reference (Loc,
3634 Attribute_Name => Name_First,
3635 Prefix => New_Occurrence_Of (Rtyp, Loc)),
3636 High_Bound =>
3637 Make_Attribute_Reference (Loc,
3638 Attribute_Name => Name_Last,
3639 Prefix => New_Occurrence_Of (Rtyp, Loc))));
3640 Analyze_And_Resolve (Rop, Rtyp, Suppress => All_Checks);
3641 end;
3642 end if;
3644 -- Here for the explicit range case. Note that the bounds of the range
3645 -- have not been processed for minimized or eliminated checks.
3647 if Nkind (Rop) = N_Range then
3648 Minimize_Eliminate_Overflows
3649 (Low_Bound (Rop), Lo, Hi, Top_Level => False);
3650 Minimize_Eliminate_Overflows
3651 (High_Bound (Rop), Lo, Hi, Top_Level => False);
3653 -- We have A in B .. C, treated as A >= B and then A <= C
3655 -- Bignum case
3657 if Is_RTE (Etype (Lop), RE_Bignum)
3658 or else Is_RTE (Etype (Low_Bound (Rop)), RE_Bignum)
3659 or else Is_RTE (Etype (High_Bound (Rop)), RE_Bignum)
3660 then
3661 declare
3662 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3663 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3664 L : constant Entity_Id :=
3665 Make_Defining_Identifier (Loc, Name_uL);
3666 Lopnd : constant Node_Id := Convert_To_Bignum (Lop);
3667 Lbound : constant Node_Id :=
3668 Convert_To_Bignum (Low_Bound (Rop));
3669 Hbound : constant Node_Id :=
3670 Convert_To_Bignum (High_Bound (Rop));
3672 -- Now we rewrite the membership test node to look like
3674 -- do
3675 -- Bnn : Result_Type;
3676 -- declare
3677 -- M : Mark_Id := SS_Mark;
3678 -- L : Bignum := Lopnd;
3679 -- begin
3680 -- Bnn := Big_GE (L, Lbound) and then Big_LE (L, Hbound)
3681 -- SS_Release (M);
3682 -- end;
3683 -- in
3684 -- Bnn
3685 -- end
3687 begin
3688 -- Insert declaration of L into declarations of bignum block
3690 Insert_After
3691 (Last (Declarations (Blk)),
3692 Make_Object_Declaration (Loc,
3693 Defining_Identifier => L,
3694 Object_Definition =>
3695 New_Occurrence_Of (RTE (RE_Bignum), Loc),
3696 Expression => Lopnd));
3698 -- Insert assignment to Bnn into expressions of bignum block
3700 Insert_Before
3701 (First (Statements (Handled_Statement_Sequence (Blk))),
3702 Make_Assignment_Statement (Loc,
3703 Name => New_Occurrence_Of (Bnn, Loc),
3704 Expression =>
3705 Make_And_Then (Loc,
3706 Left_Opnd =>
3707 Make_Function_Call (Loc,
3708 Name =>
3709 New_Occurrence_Of (RTE (RE_Big_GE), Loc),
3710 Parameter_Associations => New_List (
3711 New_Occurrence_Of (L, Loc),
3712 Lbound)),
3714 Right_Opnd =>
3715 Make_Function_Call (Loc,
3716 Name =>
3717 New_Occurrence_Of (RTE (RE_Big_LE), Loc),
3718 Parameter_Associations => New_List (
3719 New_Occurrence_Of (L, Loc),
3720 Hbound)))));
3722 -- Now rewrite the node
3724 Rewrite (N,
3725 Make_Expression_With_Actions (Loc,
3726 Actions => New_List (
3727 Make_Object_Declaration (Loc,
3728 Defining_Identifier => Bnn,
3729 Object_Definition =>
3730 New_Occurrence_Of (Result_Type, Loc)),
3731 Blk),
3732 Expression => New_Occurrence_Of (Bnn, Loc)));
3733 Analyze_And_Resolve (N, Result_Type);
3734 return;
3735 end;
3737 -- Here if no bignums around
3739 else
3740 -- Case where types are all the same
3742 if Base_Type (Etype (Lop)) = Base_Type (Etype (Low_Bound (Rop)))
3743 and then
3744 Base_Type (Etype (Lop)) = Base_Type (Etype (High_Bound (Rop)))
3745 then
3746 null;
3748 -- If types are not all the same, it means that we have rewritten
3749 -- at least one of them to be of type Long_Long_Integer, and we
3750 -- will convert the other operands to Long_Long_Integer.
3752 else
3753 Convert_To_And_Rewrite (LLIB, Lop);
3754 Set_Analyzed (Lop, False);
3755 Analyze_And_Resolve (Lop, LLIB);
3757 -- For the right operand, avoid unnecessary recursion into
3758 -- this routine, we know that overflow is not possible.
3760 Convert_To_And_Rewrite (LLIB, Low_Bound (Rop));
3761 Convert_To_And_Rewrite (LLIB, High_Bound (Rop));
3762 Set_Analyzed (Rop, False);
3763 Analyze_And_Resolve (Rop, LLIB, Suppress => Overflow_Check);
3764 end if;
3766 -- Now the three operands are of the same signed integer type,
3767 -- so we can use the normal expansion routine for membership,
3768 -- setting the flag to prevent recursion into this procedure.
3770 Set_No_Minimize_Eliminate (N);
3771 Expand_N_In (N);
3772 end if;
3774 -- Right operand is a subtype name and the subtype has a predicate. We
3775 -- have to make sure the predicate is checked, and for that we need to
3776 -- use the standard N_In circuitry with appropriate types.
3778 else
3779 pragma Assert (Present (Predicate_Function (Etype (Rop))));
3781 -- If types are "right", just call Expand_N_In preventing recursion
3783 if Base_Type (Etype (Lop)) = Base_Type (Etype (Rop)) then
3784 Set_No_Minimize_Eliminate (N);
3785 Expand_N_In (N);
3787 -- Bignum case
3789 elsif Is_RTE (Etype (Lop), RE_Bignum) then
3791 -- For X in T, we want to rewrite our node as
3793 -- do
3794 -- Bnn : Result_Type;
3796 -- declare
3797 -- M : Mark_Id := SS_Mark;
3798 -- Lnn : Long_Long_Integer'Base
3799 -- Nnn : Bignum;
3801 -- begin
3802 -- Nnn := X;
3804 -- if not Bignum_In_LLI_Range (Nnn) then
3805 -- Bnn := False;
3806 -- else
3807 -- Lnn := From_Bignum (Nnn);
3808 -- Bnn :=
3809 -- Lnn in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3810 -- and then T'Base (Lnn) in T;
3811 -- end if;
3813 -- SS_Release (M);
3814 -- end
3815 -- in
3816 -- Bnn
3817 -- end
3819 -- A bit gruesome, but there doesn't seem to be a simpler way
3821 declare
3822 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3823 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3824 Lnn : constant Entity_Id := Make_Temporary (Loc, 'L', N);
3825 Nnn : constant Entity_Id := Make_Temporary (Loc, 'N', N);
3826 T : constant Entity_Id := Etype (Rop);
3827 TB : constant Entity_Id := Base_Type (T);
3828 Nin : Node_Id;
3830 begin
3831 -- Mark the last membership operation to prevent recursion
3833 Nin :=
3834 Make_In (Loc,
3835 Left_Opnd => Convert_To (TB, New_Occurrence_Of (Lnn, Loc)),
3836 Right_Opnd => New_Occurrence_Of (T, Loc));
3837 Set_No_Minimize_Eliminate (Nin);
3839 -- Now decorate the block
3841 Insert_After
3842 (Last (Declarations (Blk)),
3843 Make_Object_Declaration (Loc,
3844 Defining_Identifier => Lnn,
3845 Object_Definition => New_Occurrence_Of (LLIB, Loc)));
3847 Insert_After
3848 (Last (Declarations (Blk)),
3849 Make_Object_Declaration (Loc,
3850 Defining_Identifier => Nnn,
3851 Object_Definition =>
3852 New_Occurrence_Of (RTE (RE_Bignum), Loc)));
3854 Insert_List_Before
3855 (First (Statements (Handled_Statement_Sequence (Blk))),
3856 New_List (
3857 Make_Assignment_Statement (Loc,
3858 Name => New_Occurrence_Of (Nnn, Loc),
3859 Expression => Relocate_Node (Lop)),
3861 Make_Implicit_If_Statement (N,
3862 Condition =>
3863 Make_Op_Not (Loc,
3864 Right_Opnd =>
3865 Make_Function_Call (Loc,
3866 Name =>
3867 New_Occurrence_Of
3868 (RTE (RE_Bignum_In_LLI_Range), Loc),
3869 Parameter_Associations => New_List (
3870 New_Occurrence_Of (Nnn, Loc)))),
3872 Then_Statements => New_List (
3873 Make_Assignment_Statement (Loc,
3874 Name => New_Occurrence_Of (Bnn, Loc),
3875 Expression =>
3876 New_Occurrence_Of (Standard_False, Loc))),
3878 Else_Statements => New_List (
3879 Make_Assignment_Statement (Loc,
3880 Name => New_Occurrence_Of (Lnn, Loc),
3881 Expression =>
3882 Make_Function_Call (Loc,
3883 Name =>
3884 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
3885 Parameter_Associations => New_List (
3886 New_Occurrence_Of (Nnn, Loc)))),
3888 Make_Assignment_Statement (Loc,
3889 Name => New_Occurrence_Of (Bnn, Loc),
3890 Expression =>
3891 Make_And_Then (Loc,
3892 Left_Opnd =>
3893 Make_In (Loc,
3894 Left_Opnd => New_Occurrence_Of (Lnn, Loc),
3895 Right_Opnd =>
3896 Make_Range (Loc,
3897 Low_Bound =>
3898 Convert_To (LLIB,
3899 Make_Attribute_Reference (Loc,
3900 Attribute_Name => Name_First,
3901 Prefix =>
3902 New_Occurrence_Of (TB, Loc))),
3904 High_Bound =>
3905 Convert_To (LLIB,
3906 Make_Attribute_Reference (Loc,
3907 Attribute_Name => Name_Last,
3908 Prefix =>
3909 New_Occurrence_Of (TB, Loc))))),
3911 Right_Opnd => Nin))))));
3913 -- Now we can do the rewrite
3915 Rewrite (N,
3916 Make_Expression_With_Actions (Loc,
3917 Actions => New_List (
3918 Make_Object_Declaration (Loc,
3919 Defining_Identifier => Bnn,
3920 Object_Definition =>
3921 New_Occurrence_Of (Result_Type, Loc)),
3922 Blk),
3923 Expression => New_Occurrence_Of (Bnn, Loc)));
3924 Analyze_And_Resolve (N, Result_Type);
3925 return;
3926 end;
3928 -- Not bignum case, but types don't match (this means we rewrote the
3929 -- left operand to be Long_Long_Integer).
3931 else
3932 pragma Assert (Base_Type (Etype (Lop)) = LLIB);
3934 -- We rewrite the membership test as (where T is the type with
3935 -- the predicate, i.e. the type of the right operand)
3937 -- Lop in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3938 -- and then T'Base (Lop) in T
3940 declare
3941 T : constant Entity_Id := Etype (Rop);
3942 TB : constant Entity_Id := Base_Type (T);
3943 Nin : Node_Id;
3945 begin
3946 -- The last membership test is marked to prevent recursion
3948 Nin :=
3949 Make_In (Loc,
3950 Left_Opnd => Convert_To (TB, Duplicate_Subexpr (Lop)),
3951 Right_Opnd => New_Occurrence_Of (T, Loc));
3952 Set_No_Minimize_Eliminate (Nin);
3954 -- Now do the rewrite
3956 Rewrite (N,
3957 Make_And_Then (Loc,
3958 Left_Opnd =>
3959 Make_In (Loc,
3960 Left_Opnd => Lop,
3961 Right_Opnd =>
3962 Make_Range (Loc,
3963 Low_Bound =>
3964 Convert_To (LLIB,
3965 Make_Attribute_Reference (Loc,
3966 Attribute_Name => Name_First,
3967 Prefix =>
3968 New_Occurrence_Of (TB, Loc))),
3969 High_Bound =>
3970 Convert_To (LLIB,
3971 Make_Attribute_Reference (Loc,
3972 Attribute_Name => Name_Last,
3973 Prefix =>
3974 New_Occurrence_Of (TB, Loc))))),
3975 Right_Opnd => Nin));
3976 Set_Analyzed (N, False);
3977 Analyze_And_Resolve (N, Restype);
3978 end;
3979 end if;
3980 end if;
3981 end Expand_Membership_Minimize_Eliminate_Overflow;
3983 ---------------------------------
3984 -- Expand_Nonbinary_Modular_Op --
3985 ---------------------------------
3987 procedure Expand_Nonbinary_Modular_Op (N : Node_Id) is
3988 Loc : constant Source_Ptr := Sloc (N);
3989 Typ : constant Entity_Id := Etype (N);
3991 procedure Expand_Modular_Addition;
3992 -- Expand the modular addition, handling the special case of adding a
3993 -- constant.
3995 procedure Expand_Modular_Op;
3996 -- Compute the general rule: (lhs OP rhs) mod Modulus
3998 procedure Expand_Modular_Subtraction;
3999 -- Expand the modular addition, handling the special case of subtracting
4000 -- a constant.
4002 -----------------------------
4003 -- Expand_Modular_Addition --
4004 -----------------------------
4006 procedure Expand_Modular_Addition is
4007 begin
4008 -- If this is not the addition of a constant then compute it using
4009 -- the general rule: (lhs + rhs) mod Modulus
4011 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
4012 Expand_Modular_Op;
4014 -- If this is an addition of a constant, convert it to a subtraction
4015 -- plus a conditional expression since we can compute it faster than
4016 -- computing the modulus.
4018 -- modMinusRhs = Modulus - rhs
4019 -- if lhs < modMinusRhs then lhs + rhs
4020 -- else lhs - modMinusRhs
4022 else
4023 declare
4024 Mod_Minus_Right : constant Uint :=
4025 Modulus (Typ) - Intval (Right_Opnd (N));
4027 Exprs : constant List_Id := New_List;
4028 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4029 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4030 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4031 Loc);
4032 begin
4033 -- To prevent spurious visibility issues, convert all
4034 -- operands to Standard.Unsigned.
4036 Set_Left_Opnd (Cond_Expr,
4037 Unchecked_Convert_To (Standard_Unsigned,
4038 New_Copy_Tree (Left_Opnd (N))));
4039 Set_Right_Opnd (Cond_Expr,
4040 Make_Integer_Literal (Loc, Mod_Minus_Right));
4041 Append_To (Exprs, Cond_Expr);
4043 Set_Left_Opnd (Then_Expr,
4044 Unchecked_Convert_To (Standard_Unsigned,
4045 New_Copy_Tree (Left_Opnd (N))));
4046 Set_Right_Opnd (Then_Expr,
4047 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4048 Append_To (Exprs, Then_Expr);
4050 Set_Left_Opnd (Else_Expr,
4051 Unchecked_Convert_To (Standard_Unsigned,
4052 New_Copy_Tree (Left_Opnd (N))));
4053 Set_Right_Opnd (Else_Expr,
4054 Make_Integer_Literal (Loc, Mod_Minus_Right));
4055 Append_To (Exprs, Else_Expr);
4057 Rewrite (N,
4058 Unchecked_Convert_To (Typ,
4059 Make_If_Expression (Loc, Expressions => Exprs)));
4060 end;
4061 end if;
4062 end Expand_Modular_Addition;
4064 -----------------------
4065 -- Expand_Modular_Op --
4066 -----------------------
4068 procedure Expand_Modular_Op is
4069 Op_Expr : constant Node_Id := New_Op_Node (Nkind (N), Loc);
4070 Mod_Expr : constant Node_Id := New_Op_Node (N_Op_Mod, Loc);
4072 Target_Type : Entity_Id;
4074 begin
4075 -- Convert nonbinary modular type operands into integer values. Thus
4076 -- we avoid never-ending loops expanding them, and we also ensure
4077 -- the back end never receives nonbinary modular type expressions.
4079 if Nkind_In (Nkind (N), N_Op_And, N_Op_Or, N_Op_Xor) then
4080 Set_Left_Opnd (Op_Expr,
4081 Unchecked_Convert_To (Standard_Unsigned,
4082 New_Copy_Tree (Left_Opnd (N))));
4083 Set_Right_Opnd (Op_Expr,
4084 Unchecked_Convert_To (Standard_Unsigned,
4085 New_Copy_Tree (Right_Opnd (N))));
4086 Set_Left_Opnd (Mod_Expr,
4087 Unchecked_Convert_To (Standard_Integer, Op_Expr));
4089 else
4090 -- If the modulus of the type is larger than Integer'Last use a
4091 -- larger type for the operands, to prevent spurious constraint
4092 -- errors on large legal literals of the type.
4094 if Modulus (Etype (N)) > UI_From_Int (Int (Integer'Last)) then
4095 Target_Type := Standard_Long_Integer;
4096 else
4097 Target_Type := Standard_Integer;
4098 end if;
4100 Set_Left_Opnd (Op_Expr,
4101 Unchecked_Convert_To (Target_Type,
4102 New_Copy_Tree (Left_Opnd (N))));
4103 Set_Right_Opnd (Op_Expr,
4104 Unchecked_Convert_To (Target_Type,
4105 New_Copy_Tree (Right_Opnd (N))));
4107 -- Link this node to the tree to analyze it
4109 -- If the parent node is an expression with actions we link it to
4110 -- N since otherwise Force_Evaluation cannot identify if this node
4111 -- comes from the Expression and rejects generating the temporary.
4113 if Nkind (Parent (N)) = N_Expression_With_Actions then
4114 Set_Parent (Op_Expr, N);
4116 -- Common case
4118 else
4119 Set_Parent (Op_Expr, Parent (N));
4120 end if;
4122 Analyze (Op_Expr);
4124 -- Force generating a temporary because in the expansion of this
4125 -- expression we may generate code that performs this computation
4126 -- several times.
4128 Force_Evaluation (Op_Expr, Mode => Strict);
4130 Set_Left_Opnd (Mod_Expr, Op_Expr);
4131 end if;
4133 Set_Right_Opnd (Mod_Expr,
4134 Make_Integer_Literal (Loc, Modulus (Typ)));
4136 Rewrite (N,
4137 Unchecked_Convert_To (Typ, Mod_Expr));
4138 end Expand_Modular_Op;
4140 --------------------------------
4141 -- Expand_Modular_Subtraction --
4142 --------------------------------
4144 procedure Expand_Modular_Subtraction is
4145 begin
4146 -- If this is not the addition of a constant then compute it using
4147 -- the general rule: (lhs + rhs) mod Modulus
4149 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
4150 Expand_Modular_Op;
4152 -- If this is an addition of a constant, convert it to a subtraction
4153 -- plus a conditional expression since we can compute it faster than
4154 -- computing the modulus.
4156 -- modMinusRhs = Modulus - rhs
4157 -- if lhs < rhs then lhs + modMinusRhs
4158 -- else lhs - rhs
4160 else
4161 declare
4162 Mod_Minus_Right : constant Uint :=
4163 Modulus (Typ) - Intval (Right_Opnd (N));
4165 Exprs : constant List_Id := New_List;
4166 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4167 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4168 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4169 Loc);
4170 begin
4171 Set_Left_Opnd (Cond_Expr,
4172 Unchecked_Convert_To (Standard_Unsigned,
4173 New_Copy_Tree (Left_Opnd (N))));
4174 Set_Right_Opnd (Cond_Expr,
4175 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4176 Append_To (Exprs, Cond_Expr);
4178 Set_Left_Opnd (Then_Expr,
4179 Unchecked_Convert_To (Standard_Unsigned,
4180 New_Copy_Tree (Left_Opnd (N))));
4181 Set_Right_Opnd (Then_Expr,
4182 Make_Integer_Literal (Loc, Mod_Minus_Right));
4183 Append_To (Exprs, Then_Expr);
4185 Set_Left_Opnd (Else_Expr,
4186 Unchecked_Convert_To (Standard_Unsigned,
4187 New_Copy_Tree (Left_Opnd (N))));
4188 Set_Right_Opnd (Else_Expr,
4189 Unchecked_Convert_To (Standard_Unsigned,
4190 New_Copy_Tree (Right_Opnd (N))));
4191 Append_To (Exprs, Else_Expr);
4193 Rewrite (N,
4194 Unchecked_Convert_To (Typ,
4195 Make_If_Expression (Loc, Expressions => Exprs)));
4196 end;
4197 end if;
4198 end Expand_Modular_Subtraction;
4200 -- Start of processing for Expand_Nonbinary_Modular_Op
4202 begin
4203 -- No action needed if front-end expansion is not required or if we
4204 -- have a binary modular operand.
4206 if not Expand_Nonbinary_Modular_Ops
4207 or else not Non_Binary_Modulus (Typ)
4208 then
4209 return;
4210 end if;
4212 case Nkind (N) is
4213 when N_Op_Add =>
4214 Expand_Modular_Addition;
4216 when N_Op_Subtract =>
4217 Expand_Modular_Subtraction;
4219 when N_Op_Minus =>
4221 -- Expand -expr into (0 - expr)
4223 Rewrite (N,
4224 Make_Op_Subtract (Loc,
4225 Left_Opnd => Make_Integer_Literal (Loc, 0),
4226 Right_Opnd => Right_Opnd (N)));
4227 Analyze_And_Resolve (N, Typ);
4229 when others =>
4230 Expand_Modular_Op;
4231 end case;
4233 Analyze_And_Resolve (N, Typ);
4234 end Expand_Nonbinary_Modular_Op;
4236 ------------------------
4237 -- Expand_N_Allocator --
4238 ------------------------
4240 procedure Expand_N_Allocator (N : Node_Id) is
4241 Etyp : constant Entity_Id := Etype (Expression (N));
4242 Loc : constant Source_Ptr := Sloc (N);
4243 PtrT : constant Entity_Id := Etype (N);
4245 procedure Rewrite_Coextension (N : Node_Id);
4246 -- Static coextensions have the same lifetime as the entity they
4247 -- constrain. Such occurrences can be rewritten as aliased objects
4248 -- and their unrestricted access used instead of the coextension.
4250 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
4251 -- Given a constrained array type E, returns a node representing the
4252 -- code to compute a close approximation of the size in storage elements
4253 -- for the given type; for indexes that are modular types we compute
4254 -- 'Last - First (instead of 'Length) because for large arrays computing
4255 -- 'Last -'First + 1 causes overflow. This is done without using the
4256 -- attribute 'Size_In_Storage_Elements (which malfunctions for large
4257 -- sizes ???)
4259 -------------------------
4260 -- Rewrite_Coextension --
4261 -------------------------
4263 procedure Rewrite_Coextension (N : Node_Id) is
4264 Temp_Id : constant Node_Id := Make_Temporary (Loc, 'C');
4265 Temp_Decl : Node_Id;
4267 begin
4268 -- Generate:
4269 -- Cnn : aliased Etyp;
4271 Temp_Decl :=
4272 Make_Object_Declaration (Loc,
4273 Defining_Identifier => Temp_Id,
4274 Aliased_Present => True,
4275 Object_Definition => New_Occurrence_Of (Etyp, Loc));
4277 if Nkind (Expression (N)) = N_Qualified_Expression then
4278 Set_Expression (Temp_Decl, Expression (Expression (N)));
4279 end if;
4281 Insert_Action (N, Temp_Decl);
4282 Rewrite (N,
4283 Make_Attribute_Reference (Loc,
4284 Prefix => New_Occurrence_Of (Temp_Id, Loc),
4285 Attribute_Name => Name_Unrestricted_Access));
4287 Analyze_And_Resolve (N, PtrT);
4288 end Rewrite_Coextension;
4290 ------------------------------
4291 -- Size_In_Storage_Elements --
4292 ------------------------------
4294 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
4295 begin
4296 -- Logically this just returns E'Max_Size_In_Storage_Elements.
4297 -- However, the reason for the existence of this function is
4298 -- to construct a test for sizes too large, which means near the
4299 -- 32-bit limit on a 32-bit machine, and precisely the trouble
4300 -- is that we get overflows when sizes are greater than 2**31.
4302 -- So what we end up doing for array types is to use the expression:
4304 -- number-of-elements * component_type'Max_Size_In_Storage_Elements
4306 -- which avoids this problem. All this is a bit bogus, but it does
4307 -- mean we catch common cases of trying to allocate arrays that
4308 -- are too large, and which in the absence of a check results in
4309 -- undetected chaos ???
4311 -- Note in particular that this is a pessimistic estimate in the
4312 -- case of packed array types, where an array element might occupy
4313 -- just a fraction of a storage element???
4315 declare
4316 Idx : Node_Id := First_Index (E);
4317 Len : Node_Id;
4318 Res : Node_Id;
4319 pragma Warnings (Off, Res);
4321 begin
4322 for J in 1 .. Number_Dimensions (E) loop
4324 if not Is_Modular_Integer_Type (Etype (Idx)) then
4325 Len :=
4326 Make_Attribute_Reference (Loc,
4327 Prefix => New_Occurrence_Of (E, Loc),
4328 Attribute_Name => Name_Length,
4329 Expressions => New_List
4330 (Make_Integer_Literal (Loc, J)));
4332 -- For indexes that are modular types we cannot generate code
4333 -- to compute 'Length since for large arrays 'Last -'First + 1
4334 -- causes overflow; therefore we compute 'Last - 'First (which
4335 -- is not the exact number of components but it is valid for
4336 -- the purpose of this runtime check on 32-bit targets)
4338 else
4339 declare
4340 Len_Minus_1_Expr : Node_Id;
4341 Test_Gt : Node_Id;
4343 begin
4344 Test_Gt :=
4345 Make_Op_Gt (Loc,
4346 Make_Attribute_Reference (Loc,
4347 Prefix => New_Occurrence_Of (E, Loc),
4348 Attribute_Name => Name_Last,
4349 Expressions =>
4350 New_List (Make_Integer_Literal (Loc, J))),
4351 Make_Attribute_Reference (Loc,
4352 Prefix => New_Occurrence_Of (E, Loc),
4353 Attribute_Name => Name_First,
4354 Expressions =>
4355 New_List (Make_Integer_Literal (Loc, J))));
4357 Len_Minus_1_Expr :=
4358 Convert_To (Standard_Unsigned,
4359 Make_Op_Subtract (Loc,
4360 Make_Attribute_Reference (Loc,
4361 Prefix => New_Occurrence_Of (E, Loc),
4362 Attribute_Name => Name_Last,
4363 Expressions =>
4364 New_List
4365 (Make_Integer_Literal (Loc, J))),
4366 Make_Attribute_Reference (Loc,
4367 Prefix => New_Occurrence_Of (E, Loc),
4368 Attribute_Name => Name_First,
4369 Expressions =>
4370 New_List
4371 (Make_Integer_Literal (Loc, J)))));
4373 -- Handle superflat arrays, i.e. arrays with such bounds
4374 -- as 4 .. 2, to insure that the result is correct.
4376 -- Generate:
4377 -- (if X'Last > X'First then X'Last - X'First else 0)
4379 Len :=
4380 Make_If_Expression (Loc,
4381 Expressions => New_List (
4382 Test_Gt,
4383 Len_Minus_1_Expr,
4384 Make_Integer_Literal (Loc, Uint_0)));
4385 end;
4386 end if;
4388 if J = 1 then
4389 Res := Len;
4391 else
4392 Res :=
4393 Make_Op_Multiply (Loc,
4394 Left_Opnd => Res,
4395 Right_Opnd => Len);
4396 end if;
4398 Next_Index (Idx);
4399 end loop;
4401 return
4402 Make_Op_Multiply (Loc,
4403 Left_Opnd => Len,
4404 Right_Opnd =>
4405 Make_Attribute_Reference (Loc,
4406 Prefix => New_Occurrence_Of (Component_Type (E), Loc),
4407 Attribute_Name => Name_Max_Size_In_Storage_Elements));
4408 end;
4409 end Size_In_Storage_Elements;
4411 -- Local variables
4413 Dtyp : constant Entity_Id := Available_View (Designated_Type (PtrT));
4414 Desig : Entity_Id;
4415 Nod : Node_Id;
4416 Pool : Entity_Id;
4417 Rel_Typ : Entity_Id;
4418 Temp : Entity_Id;
4420 -- Start of processing for Expand_N_Allocator
4422 begin
4423 -- Warn on the presence of an allocator of an anonymous access type when
4424 -- enabled.
4426 if Warn_On_Anonymous_Allocators
4427 and then Ekind (PtrT) = E_Anonymous_Access_Type
4428 then
4429 Error_Msg_N ("?use of an anonymous access type allocator", N);
4430 end if;
4432 -- RM E.2.3(22). We enforce that the expected type of an allocator
4433 -- shall not be a remote access-to-class-wide-limited-private type
4435 -- Why is this being done at expansion time, seems clearly wrong ???
4437 Validate_Remote_Access_To_Class_Wide_Type (N);
4439 -- Processing for anonymous access-to-controlled types. These access
4440 -- types receive a special finalization master which appears in the
4441 -- declarations of the enclosing semantic unit. This expansion is done
4442 -- now to ensure that any additional types generated by this routine or
4443 -- Expand_Allocator_Expression inherit the proper type attributes.
4445 if (Ekind (PtrT) = E_Anonymous_Access_Type
4446 or else (Is_Itype (PtrT) and then No (Finalization_Master (PtrT))))
4447 and then Needs_Finalization (Dtyp)
4448 then
4449 -- Detect the allocation of an anonymous controlled object where the
4450 -- type of the context is named. For example:
4452 -- procedure Proc (Ptr : Named_Access_Typ);
4453 -- Proc (new Designated_Typ);
4455 -- Regardless of the anonymous-to-named access type conversion, the
4456 -- lifetime of the object must be associated with the named access
4457 -- type. Use the finalization-related attributes of this type.
4459 if Nkind_In (Parent (N), N_Type_Conversion,
4460 N_Unchecked_Type_Conversion)
4461 and then Ekind_In (Etype (Parent (N)), E_Access_Subtype,
4462 E_Access_Type,
4463 E_General_Access_Type)
4464 then
4465 Rel_Typ := Etype (Parent (N));
4466 else
4467 Rel_Typ := Empty;
4468 end if;
4470 -- Anonymous access-to-controlled types allocate on the global pool.
4471 -- Note that this is a "root type only" attribute.
4473 if No (Associated_Storage_Pool (PtrT)) then
4474 if Present (Rel_Typ) then
4475 Set_Associated_Storage_Pool
4476 (Root_Type (PtrT), Associated_Storage_Pool (Rel_Typ));
4477 else
4478 Set_Associated_Storage_Pool
4479 (Root_Type (PtrT), RTE (RE_Global_Pool_Object));
4480 end if;
4481 end if;
4483 -- The finalization master must be inserted and analyzed as part of
4484 -- the current semantic unit. Note that the master is updated when
4485 -- analysis changes current units. Note that this is a "root type
4486 -- only" attribute.
4488 if Present (Rel_Typ) then
4489 Set_Finalization_Master
4490 (Root_Type (PtrT), Finalization_Master (Rel_Typ));
4491 else
4492 Build_Anonymous_Master (Root_Type (PtrT));
4493 end if;
4494 end if;
4496 -- Set the storage pool and find the appropriate version of Allocate to
4497 -- call. Do not overwrite the storage pool if it is already set, which
4498 -- can happen for build-in-place function returns (see
4499 -- Exp_Ch4.Expand_N_Extended_Return_Statement).
4501 if No (Storage_Pool (N)) then
4502 Pool := Associated_Storage_Pool (Root_Type (PtrT));
4504 if Present (Pool) then
4505 Set_Storage_Pool (N, Pool);
4507 if Is_RTE (Pool, RE_SS_Pool) then
4508 Check_Restriction (No_Secondary_Stack, N);
4509 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
4511 -- In the case of an allocator for a simple storage pool, locate
4512 -- and save a reference to the pool type's Allocate routine.
4514 elsif Present (Get_Rep_Pragma
4515 (Etype (Pool), Name_Simple_Storage_Pool_Type))
4516 then
4517 declare
4518 Pool_Type : constant Entity_Id := Base_Type (Etype (Pool));
4519 Alloc_Op : Entity_Id;
4520 begin
4521 Alloc_Op := Get_Name_Entity_Id (Name_Allocate);
4522 while Present (Alloc_Op) loop
4523 if Scope (Alloc_Op) = Scope (Pool_Type)
4524 and then Present (First_Formal (Alloc_Op))
4525 and then Etype (First_Formal (Alloc_Op)) = Pool_Type
4526 then
4527 Set_Procedure_To_Call (N, Alloc_Op);
4528 exit;
4529 else
4530 Alloc_Op := Homonym (Alloc_Op);
4531 end if;
4532 end loop;
4533 end;
4535 elsif Is_Class_Wide_Type (Etype (Pool)) then
4536 Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
4538 else
4539 Set_Procedure_To_Call (N,
4540 Find_Prim_Op (Etype (Pool), Name_Allocate));
4541 end if;
4542 end if;
4543 end if;
4545 -- Under certain circumstances we can replace an allocator by an access
4546 -- to statically allocated storage. The conditions, as noted in AARM
4547 -- 3.10 (10c) are as follows:
4549 -- Size and initial value is known at compile time
4550 -- Access type is access-to-constant
4552 -- The allocator is not part of a constraint on a record component,
4553 -- because in that case the inserted actions are delayed until the
4554 -- record declaration is fully analyzed, which is too late for the
4555 -- analysis of the rewritten allocator.
4557 if Is_Access_Constant (PtrT)
4558 and then Nkind (Expression (N)) = N_Qualified_Expression
4559 and then Compile_Time_Known_Value (Expression (Expression (N)))
4560 and then Size_Known_At_Compile_Time
4561 (Etype (Expression (Expression (N))))
4562 and then not Is_Record_Type (Current_Scope)
4563 then
4564 -- Here we can do the optimization. For the allocator
4566 -- new x'(y)
4568 -- We insert an object declaration
4570 -- Tnn : aliased x := y;
4572 -- and replace the allocator by Tnn'Unrestricted_Access. Tnn is
4573 -- marked as requiring static allocation.
4575 Temp := Make_Temporary (Loc, 'T', Expression (Expression (N)));
4576 Desig := Subtype_Mark (Expression (N));
4578 -- If context is constrained, use constrained subtype directly,
4579 -- so that the constant is not labelled as having a nominally
4580 -- unconstrained subtype.
4582 if Entity (Desig) = Base_Type (Dtyp) then
4583 Desig := New_Occurrence_Of (Dtyp, Loc);
4584 end if;
4586 Insert_Action (N,
4587 Make_Object_Declaration (Loc,
4588 Defining_Identifier => Temp,
4589 Aliased_Present => True,
4590 Constant_Present => Is_Access_Constant (PtrT),
4591 Object_Definition => Desig,
4592 Expression => Expression (Expression (N))));
4594 Rewrite (N,
4595 Make_Attribute_Reference (Loc,
4596 Prefix => New_Occurrence_Of (Temp, Loc),
4597 Attribute_Name => Name_Unrestricted_Access));
4599 Analyze_And_Resolve (N, PtrT);
4601 -- We set the variable as statically allocated, since we don't want
4602 -- it going on the stack of the current procedure.
4604 Set_Is_Statically_Allocated (Temp);
4605 return;
4606 end if;
4608 -- Same if the allocator is an access discriminant for a local object:
4609 -- instead of an allocator we create a local value and constrain the
4610 -- enclosing object with the corresponding access attribute.
4612 if Is_Static_Coextension (N) then
4613 Rewrite_Coextension (N);
4614 return;
4615 end if;
4617 -- Check for size too large, we do this because the back end misses
4618 -- proper checks here and can generate rubbish allocation calls when
4619 -- we are near the limit. We only do this for the 32-bit address case
4620 -- since that is from a practical point of view where we see a problem.
4622 if System_Address_Size = 32
4623 and then not Storage_Checks_Suppressed (PtrT)
4624 and then not Storage_Checks_Suppressed (Dtyp)
4625 and then not Storage_Checks_Suppressed (Etyp)
4626 then
4627 -- The check we want to generate should look like
4629 -- if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
4630 -- raise Storage_Error;
4631 -- end if;
4633 -- where 3.5 gigabytes is a constant large enough to accommodate any
4634 -- reasonable request for. But we can't do it this way because at
4635 -- least at the moment we don't compute this attribute right, and
4636 -- can silently give wrong results when the result gets large. Since
4637 -- this is all about large results, that's bad, so instead we only
4638 -- apply the check for constrained arrays, and manually compute the
4639 -- value of the attribute ???
4641 -- The check on No_Initialization is used here to prevent generating
4642 -- this runtime check twice when the allocator is locally replaced by
4643 -- the expander by another one.
4645 if Is_Array_Type (Etyp) and then not No_Initialization (N) then
4646 declare
4647 Cond : Node_Id;
4648 Ins_Nod : Node_Id := N;
4649 Siz_Typ : Entity_Id := Etyp;
4650 Expr : Node_Id;
4652 begin
4653 -- For unconstrained array types initialized with a qualified
4654 -- expression we use its type to perform this check
4656 if not Is_Constrained (Etyp)
4657 and then not No_Initialization (N)
4658 and then Nkind (Expression (N)) = N_Qualified_Expression
4659 then
4660 Expr := Expression (Expression (N));
4661 Siz_Typ := Etype (Expression (Expression (N)));
4663 -- If the qualified expression has been moved to an internal
4664 -- temporary (to remove side effects) then we must insert
4665 -- the runtime check before its declaration to ensure that
4666 -- the check is performed before the execution of the code
4667 -- computing the qualified expression.
4669 if Nkind (Expr) = N_Identifier
4670 and then Is_Internal_Name (Chars (Expr))
4671 and then
4672 Nkind (Parent (Entity (Expr))) = N_Object_Declaration
4673 then
4674 Ins_Nod := Parent (Entity (Expr));
4675 else
4676 Ins_Nod := Expr;
4677 end if;
4678 end if;
4680 if Is_Constrained (Siz_Typ)
4681 and then Ekind (Siz_Typ) /= E_String_Literal_Subtype
4682 then
4683 -- For CCG targets the largest array may have up to 2**31-1
4684 -- components (i.e. 2 Gigabytes if each array component is
4685 -- 1-byte). This insures that fat pointer fields do not
4686 -- overflow, since they are 32-bit integer types, and also
4687 -- insures that 'Length can be computed at run time.
4689 if Modify_Tree_For_C then
4690 Cond :=
4691 Make_Op_Gt (Loc,
4692 Left_Opnd => Size_In_Storage_Elements (Siz_Typ),
4693 Right_Opnd => Make_Integer_Literal (Loc,
4694 Uint_2 ** 31 - Uint_1));
4696 -- For native targets the largest object is 3.5 gigabytes
4698 else
4699 Cond :=
4700 Make_Op_Gt (Loc,
4701 Left_Opnd => Size_In_Storage_Elements (Siz_Typ),
4702 Right_Opnd => Make_Integer_Literal (Loc,
4703 Uint_7 * (Uint_2 ** 29)));
4704 end if;
4706 Insert_Action (Ins_Nod,
4707 Make_Raise_Storage_Error (Loc,
4708 Condition => Cond,
4709 Reason => SE_Object_Too_Large));
4711 if Entity (Cond) = Standard_True then
4712 Error_Msg_N
4713 ("object too large: Storage_Error will be raised at "
4714 & "run time??", N);
4715 end if;
4716 end if;
4717 end;
4718 end if;
4719 end if;
4721 -- If no storage pool has been specified, or the storage pool
4722 -- is System.Pool_Global.Global_Pool_Object, and the restriction
4723 -- No_Standard_Allocators_After_Elaboration is present, then generate
4724 -- a call to Elaboration_Allocators.Check_Standard_Allocator.
4726 if Nkind (N) = N_Allocator
4727 and then (No (Storage_Pool (N))
4728 or else Is_RTE (Storage_Pool (N), RE_Global_Pool_Object))
4729 and then Restriction_Active (No_Standard_Allocators_After_Elaboration)
4730 then
4731 Insert_Action (N,
4732 Make_Procedure_Call_Statement (Loc,
4733 Name =>
4734 New_Occurrence_Of (RTE (RE_Check_Standard_Allocator), Loc)));
4735 end if;
4737 -- Handle case of qualified expression (other than optimization above)
4738 -- First apply constraint checks, because the bounds or discriminants
4739 -- in the aggregate might not match the subtype mark in the allocator.
4741 if Nkind (Expression (N)) = N_Qualified_Expression then
4742 declare
4743 Exp : constant Node_Id := Expression (Expression (N));
4744 Typ : constant Entity_Id := Etype (Expression (N));
4746 begin
4747 Apply_Constraint_Check (Exp, Typ);
4748 Apply_Predicate_Check (Exp, Typ);
4749 end;
4751 Expand_Allocator_Expression (N);
4752 return;
4753 end if;
4755 -- If the allocator is for a type which requires initialization, and
4756 -- there is no initial value (i.e. operand is a subtype indication
4757 -- rather than a qualified expression), then we must generate a call to
4758 -- the initialization routine using an expressions action node:
4760 -- [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
4762 -- Here ptr_T is the pointer type for the allocator, and T is the
4763 -- subtype of the allocator. A special case arises if the designated
4764 -- type of the access type is a task or contains tasks. In this case
4765 -- the call to Init (Temp.all ...) is replaced by code that ensures
4766 -- that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
4767 -- for details). In addition, if the type T is a task type, then the
4768 -- first argument to Init must be converted to the task record type.
4770 declare
4771 T : constant Entity_Id := Etype (Expression (N));
4772 Args : List_Id;
4773 Decls : List_Id;
4774 Decl : Node_Id;
4775 Discr : Elmt_Id;
4776 Init : Entity_Id;
4777 Init_Arg1 : Node_Id;
4778 Init_Call : Node_Id;
4779 Temp_Decl : Node_Id;
4780 Temp_Type : Entity_Id;
4782 begin
4783 if No_Initialization (N) then
4785 -- Even though this might be a simple allocation, create a custom
4786 -- Allocate if the context requires it.
4788 if Present (Finalization_Master (PtrT)) then
4789 Build_Allocate_Deallocate_Proc
4790 (N => N,
4791 Is_Allocate => True);
4792 end if;
4794 -- Optimize the default allocation of an array object when pragma
4795 -- Initialize_Scalars or Normalize_Scalars is in effect. Construct an
4796 -- in-place initialization aggregate which may be convert into a fast
4797 -- memset by the backend.
4799 elsif Init_Or_Norm_Scalars
4800 and then Is_Array_Type (T)
4802 -- The array must lack atomic components because they are treated
4803 -- as non-static, and as a result the backend will not initialize
4804 -- the memory in one go.
4806 and then not Has_Atomic_Components (T)
4808 -- The array must not be packed because the invalid values in
4809 -- System.Scalar_Values are multiples of Storage_Unit.
4811 and then not Is_Packed (T)
4813 -- The array must have static non-empty ranges, otherwise the
4814 -- backend cannot initialize the memory in one go.
4816 and then Has_Static_Non_Empty_Array_Bounds (T)
4818 -- The optimization is only relevant for arrays of scalar types
4820 and then Is_Scalar_Type (Component_Type (T))
4822 -- Similar to regular array initialization using a type init proc,
4823 -- predicate checks are not performed because the initialization
4824 -- values are intentionally invalid, and may violate the predicate.
4826 and then not Has_Predicates (Component_Type (T))
4828 -- The component type must have a single initialization value
4830 and then Needs_Simple_Initialization
4831 (Typ => Component_Type (T),
4832 Consider_IS => True)
4833 then
4834 Set_Analyzed (N);
4835 Temp := Make_Temporary (Loc, 'P');
4837 -- Generate:
4838 -- Temp : Ptr_Typ := new ...;
4840 Insert_Action
4841 (Assoc_Node => N,
4842 Ins_Action =>
4843 Make_Object_Declaration (Loc,
4844 Defining_Identifier => Temp,
4845 Object_Definition => New_Occurrence_Of (PtrT, Loc),
4846 Expression => Relocate_Node (N)),
4847 Suppress => All_Checks);
4849 -- Generate:
4850 -- Temp.all := (others => ...);
4852 Insert_Action
4853 (Assoc_Node => N,
4854 Ins_Action =>
4855 Make_Assignment_Statement (Loc,
4856 Name =>
4857 Make_Explicit_Dereference (Loc,
4858 Prefix => New_Occurrence_Of (Temp, Loc)),
4859 Expression =>
4860 Get_Simple_Init_Val
4861 (Typ => T,
4862 N => N,
4863 Size => Esize (Component_Type (T)))),
4864 Suppress => All_Checks);
4866 Rewrite (N, New_Occurrence_Of (Temp, Loc));
4867 Analyze_And_Resolve (N, PtrT);
4869 -- Case of no initialization procedure present
4871 elsif not Has_Non_Null_Base_Init_Proc (T) then
4873 -- Case of simple initialization required
4875 if Needs_Simple_Initialization (T) then
4876 Check_Restriction (No_Default_Initialization, N);
4877 Rewrite (Expression (N),
4878 Make_Qualified_Expression (Loc,
4879 Subtype_Mark => New_Occurrence_Of (T, Loc),
4880 Expression => Get_Simple_Init_Val (T, N)));
4882 Analyze_And_Resolve (Expression (Expression (N)), T);
4883 Analyze_And_Resolve (Expression (N), T);
4884 Set_Paren_Count (Expression (Expression (N)), 1);
4885 Expand_N_Allocator (N);
4887 -- No initialization required
4889 else
4890 Build_Allocate_Deallocate_Proc
4891 (N => N,
4892 Is_Allocate => True);
4893 end if;
4895 -- Case of initialization procedure present, must be called
4897 -- NOTE: There is a *huge* amount of code duplication here from
4898 -- Build_Initialization_Call. We should probably refactor???
4900 else
4901 Check_Restriction (No_Default_Initialization, N);
4903 if not Restriction_Active (No_Default_Initialization) then
4904 Init := Base_Init_Proc (T);
4905 Nod := N;
4906 Temp := Make_Temporary (Loc, 'P');
4908 -- Construct argument list for the initialization routine call
4910 Init_Arg1 :=
4911 Make_Explicit_Dereference (Loc,
4912 Prefix =>
4913 New_Occurrence_Of (Temp, Loc));
4915 Set_Assignment_OK (Init_Arg1);
4916 Temp_Type := PtrT;
4918 -- The initialization procedure expects a specific type. if the
4919 -- context is access to class wide, indicate that the object
4920 -- being allocated has the right specific type.
4922 if Is_Class_Wide_Type (Dtyp) then
4923 Init_Arg1 := Unchecked_Convert_To (T, Init_Arg1);
4924 end if;
4926 -- If designated type is a concurrent type or if it is private
4927 -- type whose definition is a concurrent type, the first
4928 -- argument in the Init routine has to be unchecked conversion
4929 -- to the corresponding record type. If the designated type is
4930 -- a derived type, also convert the argument to its root type.
4932 if Is_Concurrent_Type (T) then
4933 Init_Arg1 :=
4934 Unchecked_Convert_To (
4935 Corresponding_Record_Type (T), Init_Arg1);
4937 elsif Is_Private_Type (T)
4938 and then Present (Full_View (T))
4939 and then Is_Concurrent_Type (Full_View (T))
4940 then
4941 Init_Arg1 :=
4942 Unchecked_Convert_To
4943 (Corresponding_Record_Type (Full_View (T)), Init_Arg1);
4945 elsif Etype (First_Formal (Init)) /= Base_Type (T) then
4946 declare
4947 Ftyp : constant Entity_Id := Etype (First_Formal (Init));
4949 begin
4950 Init_Arg1 := OK_Convert_To (Etype (Ftyp), Init_Arg1);
4951 Set_Etype (Init_Arg1, Ftyp);
4952 end;
4953 end if;
4955 Args := New_List (Init_Arg1);
4957 -- For the task case, pass the Master_Id of the access type as
4958 -- the value of the _Master parameter, and _Chain as the value
4959 -- of the _Chain parameter (_Chain will be defined as part of
4960 -- the generated code for the allocator).
4962 -- In Ada 2005, the context may be a function that returns an
4963 -- anonymous access type. In that case the Master_Id has been
4964 -- created when expanding the function declaration.
4966 if Has_Task (T) then
4967 if No (Master_Id (Base_Type (PtrT))) then
4969 -- The designated type was an incomplete type, and the
4970 -- access type did not get expanded. Salvage it now.
4972 if not Restriction_Active (No_Task_Hierarchy) then
4973 if Present (Parent (Base_Type (PtrT))) then
4974 Expand_N_Full_Type_Declaration
4975 (Parent (Base_Type (PtrT)));
4977 -- The only other possibility is an itype. For this
4978 -- case, the master must exist in the context. This is
4979 -- the case when the allocator initializes an access
4980 -- component in an init-proc.
4982 else
4983 pragma Assert (Is_Itype (PtrT));
4984 Build_Master_Renaming (PtrT, N);
4985 end if;
4986 end if;
4987 end if;
4989 -- If the context of the allocator is a declaration or an
4990 -- assignment, we can generate a meaningful image for it,
4991 -- even though subsequent assignments might remove the
4992 -- connection between task and entity. We build this image
4993 -- when the left-hand side is a simple variable, a simple
4994 -- indexed assignment or a simple selected component.
4996 if Nkind (Parent (N)) = N_Assignment_Statement then
4997 declare
4998 Nam : constant Node_Id := Name (Parent (N));
5000 begin
5001 if Is_Entity_Name (Nam) then
5002 Decls :=
5003 Build_Task_Image_Decls
5004 (Loc,
5005 New_Occurrence_Of
5006 (Entity (Nam), Sloc (Nam)), T);
5008 elsif Nkind_In (Nam, N_Indexed_Component,
5009 N_Selected_Component)
5010 and then Is_Entity_Name (Prefix (Nam))
5011 then
5012 Decls :=
5013 Build_Task_Image_Decls
5014 (Loc, Nam, Etype (Prefix (Nam)));
5015 else
5016 Decls := Build_Task_Image_Decls (Loc, T, T);
5017 end if;
5018 end;
5020 elsif Nkind (Parent (N)) = N_Object_Declaration then
5021 Decls :=
5022 Build_Task_Image_Decls
5023 (Loc, Defining_Identifier (Parent (N)), T);
5025 else
5026 Decls := Build_Task_Image_Decls (Loc, T, T);
5027 end if;
5029 if Restriction_Active (No_Task_Hierarchy) then
5030 Append_To (Args,
5031 New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
5032 else
5033 Append_To (Args,
5034 New_Occurrence_Of
5035 (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
5036 end if;
5038 Append_To (Args, Make_Identifier (Loc, Name_uChain));
5040 Decl := Last (Decls);
5041 Append_To (Args,
5042 New_Occurrence_Of (Defining_Identifier (Decl), Loc));
5044 -- Has_Task is false, Decls not used
5046 else
5047 Decls := No_List;
5048 end if;
5050 -- Add discriminants if discriminated type
5052 declare
5053 Dis : Boolean := False;
5054 Typ : Entity_Id := Empty;
5056 begin
5057 if Has_Discriminants (T) then
5058 Dis := True;
5059 Typ := T;
5061 -- Type may be a private type with no visible discriminants
5062 -- in which case check full view if in scope, or the
5063 -- underlying_full_view if dealing with a type whose full
5064 -- view may be derived from a private type whose own full
5065 -- view has discriminants.
5067 elsif Is_Private_Type (T) then
5068 if Present (Full_View (T))
5069 and then Has_Discriminants (Full_View (T))
5070 then
5071 Dis := True;
5072 Typ := Full_View (T);
5074 elsif Present (Underlying_Full_View (T))
5075 and then Has_Discriminants (Underlying_Full_View (T))
5076 then
5077 Dis := True;
5078 Typ := Underlying_Full_View (T);
5079 end if;
5080 end if;
5082 if Dis then
5084 -- If the allocated object will be constrained by the
5085 -- default values for discriminants, then build a subtype
5086 -- with those defaults, and change the allocated subtype
5087 -- to that. Note that this happens in fewer cases in Ada
5088 -- 2005 (AI-363).
5090 if not Is_Constrained (Typ)
5091 and then Present (Discriminant_Default_Value
5092 (First_Discriminant (Typ)))
5093 and then (Ada_Version < Ada_2005
5094 or else not
5095 Object_Type_Has_Constrained_Partial_View
5096 (Typ, Current_Scope))
5097 then
5098 Typ := Build_Default_Subtype (Typ, N);
5099 Set_Expression (N, New_Occurrence_Of (Typ, Loc));
5100 end if;
5102 Discr := First_Elmt (Discriminant_Constraint (Typ));
5103 while Present (Discr) loop
5104 Nod := Node (Discr);
5105 Append (New_Copy_Tree (Node (Discr)), Args);
5107 -- AI-416: when the discriminant constraint is an
5108 -- anonymous access type make sure an accessibility
5109 -- check is inserted if necessary (3.10.2(22.q/2))
5111 if Ada_Version >= Ada_2005
5112 and then
5113 Ekind (Etype (Nod)) = E_Anonymous_Access_Type
5114 then
5115 Apply_Accessibility_Check
5116 (Nod, Typ, Insert_Node => Nod);
5117 end if;
5119 Next_Elmt (Discr);
5120 end loop;
5121 end if;
5122 end;
5124 -- We set the allocator as analyzed so that when we analyze
5125 -- the if expression node, we do not get an unwanted recursive
5126 -- expansion of the allocator expression.
5128 Set_Analyzed (N, True);
5129 Nod := Relocate_Node (N);
5131 -- Here is the transformation:
5132 -- input: new Ctrl_Typ
5133 -- output: Temp : constant Ctrl_Typ_Ptr := new Ctrl_Typ;
5134 -- Ctrl_TypIP (Temp.all, ...);
5135 -- [Deep_]Initialize (Temp.all);
5137 -- Here Ctrl_Typ_Ptr is the pointer type for the allocator, and
5138 -- is the subtype of the allocator.
5140 Temp_Decl :=
5141 Make_Object_Declaration (Loc,
5142 Defining_Identifier => Temp,
5143 Constant_Present => True,
5144 Object_Definition => New_Occurrence_Of (Temp_Type, Loc),
5145 Expression => Nod);
5147 Set_Assignment_OK (Temp_Decl);
5148 Insert_Action (N, Temp_Decl, Suppress => All_Checks);
5150 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
5152 -- If the designated type is a task type or contains tasks,
5153 -- create block to activate created tasks, and insert
5154 -- declaration for Task_Image variable ahead of call.
5156 if Has_Task (T) then
5157 declare
5158 L : constant List_Id := New_List;
5159 Blk : Node_Id;
5160 begin
5161 Build_Task_Allocate_Block (L, Nod, Args);
5162 Blk := Last (L);
5163 Insert_List_Before (First (Declarations (Blk)), Decls);
5164 Insert_Actions (N, L);
5165 end;
5167 else
5168 Insert_Action (N,
5169 Make_Procedure_Call_Statement (Loc,
5170 Name => New_Occurrence_Of (Init, Loc),
5171 Parameter_Associations => Args));
5172 end if;
5174 if Needs_Finalization (T) then
5176 -- Generate:
5177 -- [Deep_]Initialize (Init_Arg1);
5179 Init_Call :=
5180 Make_Init_Call
5181 (Obj_Ref => New_Copy_Tree (Init_Arg1),
5182 Typ => T);
5184 -- Guard against a missing [Deep_]Initialize when the
5185 -- designated type was not properly frozen.
5187 if Present (Init_Call) then
5188 Insert_Action (N, Init_Call);
5189 end if;
5190 end if;
5192 Rewrite (N, New_Occurrence_Of (Temp, Loc));
5193 Analyze_And_Resolve (N, PtrT);
5194 end if;
5195 end if;
5196 end;
5198 -- Ada 2005 (AI-251): If the allocator is for a class-wide interface
5199 -- object that has been rewritten as a reference, we displace "this"
5200 -- to reference properly its secondary dispatch table.
5202 if Nkind (N) = N_Identifier and then Is_Interface (Dtyp) then
5203 Displace_Allocator_Pointer (N);
5204 end if;
5206 exception
5207 when RE_Not_Available =>
5208 return;
5209 end Expand_N_Allocator;
5211 -----------------------
5212 -- Expand_N_And_Then --
5213 -----------------------
5215 procedure Expand_N_And_Then (N : Node_Id)
5216 renames Expand_Short_Circuit_Operator;
5218 ------------------------------
5219 -- Expand_N_Case_Expression --
5220 ------------------------------
5222 procedure Expand_N_Case_Expression (N : Node_Id) is
5223 function Is_Copy_Type (Typ : Entity_Id) return Boolean;
5224 -- Return True if we can copy objects of this type when expanding a case
5225 -- expression.
5227 ------------------
5228 -- Is_Copy_Type --
5229 ------------------
5231 function Is_Copy_Type (Typ : Entity_Id) return Boolean is
5232 begin
5233 -- If Minimize_Expression_With_Actions is True, we can afford to copy
5234 -- large objects, as long as they are constrained and not limited.
5236 return
5237 Is_Elementary_Type (Underlying_Type (Typ))
5238 or else
5239 (Minimize_Expression_With_Actions
5240 and then Is_Constrained (Underlying_Type (Typ))
5241 and then not Is_Limited_Type (Underlying_Type (Typ)));
5242 end Is_Copy_Type;
5244 -- Local variables
5246 Loc : constant Source_Ptr := Sloc (N);
5247 Par : constant Node_Id := Parent (N);
5248 Typ : constant Entity_Id := Etype (N);
5250 Acts : List_Id;
5251 Alt : Node_Id;
5252 Case_Stmt : Node_Id;
5253 Decl : Node_Id;
5254 Expr : Node_Id;
5255 Target : Entity_Id;
5256 Target_Typ : Entity_Id;
5258 In_Predicate : Boolean := False;
5259 -- Flag set when the case expression appears within a predicate
5261 Optimize_Return_Stmt : Boolean := False;
5262 -- Flag set when the case expression can be optimized in the context of
5263 -- a simple return statement.
5265 -- Start of processing for Expand_N_Case_Expression
5267 begin
5268 -- Check for MINIMIZED/ELIMINATED overflow mode
5270 if Minimized_Eliminated_Overflow_Check (N) then
5271 Apply_Arithmetic_Overflow_Check (N);
5272 return;
5273 end if;
5275 -- If the case expression is a predicate specification, and the type
5276 -- to which it applies has a static predicate aspect, do not expand,
5277 -- because it will be converted to the proper predicate form later.
5279 if Ekind_In (Current_Scope, E_Function, E_Procedure)
5280 and then Is_Predicate_Function (Current_Scope)
5281 then
5282 In_Predicate := True;
5284 if Has_Static_Predicate_Aspect (Etype (First_Entity (Current_Scope)))
5285 then
5286 return;
5287 end if;
5288 end if;
5290 -- When the type of the case expression is elementary, expand
5292 -- (case X is when A => AX, when B => BX ...)
5294 -- into
5296 -- do
5297 -- Target : Typ;
5298 -- case X is
5299 -- when A =>
5300 -- Target := AX;
5301 -- when B =>
5302 -- Target := BX;
5303 -- ...
5304 -- end case;
5305 -- in Target end;
5307 -- In all other cases expand into
5309 -- do
5310 -- type Ptr_Typ is access all Typ;
5311 -- Target : Ptr_Typ;
5312 -- case X is
5313 -- when A =>
5314 -- Target := AX'Unrestricted_Access;
5315 -- when B =>
5316 -- Target := BX'Unrestricted_Access;
5317 -- ...
5318 -- end case;
5319 -- in Target.all end;
5321 -- This approach avoids extra copies of potentially large objects. It
5322 -- also allows handling of values of limited or unconstrained types.
5323 -- Note that we do the copy also for constrained, nonlimited types
5324 -- when minimizing expressions with actions (e.g. when generating C
5325 -- code) since it allows us to do the optimization below in more cases.
5327 -- Small optimization: when the case expression appears in the context
5328 -- of a simple return statement, expand into
5330 -- case X is
5331 -- when A =>
5332 -- return AX;
5333 -- when B =>
5334 -- return BX;
5335 -- ...
5336 -- end case;
5338 Case_Stmt :=
5339 Make_Case_Statement (Loc,
5340 Expression => Expression (N),
5341 Alternatives => New_List);
5343 -- Preserve the original context for which the case statement is being
5344 -- generated. This is needed by the finalization machinery to prevent
5345 -- the premature finalization of controlled objects found within the
5346 -- case statement.
5348 Set_From_Conditional_Expression (Case_Stmt);
5349 Acts := New_List;
5351 -- Scalar/Copy case
5353 if Is_Copy_Type (Typ) then
5354 Target_Typ := Typ;
5356 -- ??? Do not perform the optimization when the return statement is
5357 -- within a predicate function, as this causes spurious errors. Could
5358 -- this be a possible mismatch in handling this case somewhere else
5359 -- in semantic analysis?
5361 Optimize_Return_Stmt :=
5362 Nkind (Par) = N_Simple_Return_Statement and then not In_Predicate;
5364 -- Otherwise create an access type to handle the general case using
5365 -- 'Unrestricted_Access.
5367 -- Generate:
5368 -- type Ptr_Typ is access all Typ;
5370 else
5371 if Generate_C_Code then
5373 -- We cannot ensure that correct C code will be generated if any
5374 -- temporary is created down the line (to e.g. handle checks or
5375 -- capture values) since we might end up with dangling references
5376 -- to local variables, so better be safe and reject the construct.
5378 Error_Msg_N
5379 ("case expression too complex, use case statement instead", N);
5380 end if;
5382 Target_Typ := Make_Temporary (Loc, 'P');
5384 Append_To (Acts,
5385 Make_Full_Type_Declaration (Loc,
5386 Defining_Identifier => Target_Typ,
5387 Type_Definition =>
5388 Make_Access_To_Object_Definition (Loc,
5389 All_Present => True,
5390 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5391 end if;
5393 -- Create the declaration of the target which captures the value of the
5394 -- expression.
5396 -- Generate:
5397 -- Target : [Ptr_]Typ;
5399 if not Optimize_Return_Stmt then
5400 Target := Make_Temporary (Loc, 'T');
5402 Decl :=
5403 Make_Object_Declaration (Loc,
5404 Defining_Identifier => Target,
5405 Object_Definition => New_Occurrence_Of (Target_Typ, Loc));
5406 Set_No_Initialization (Decl);
5408 Append_To (Acts, Decl);
5409 end if;
5411 -- Process the alternatives
5413 Alt := First (Alternatives (N));
5414 while Present (Alt) loop
5415 declare
5416 Alt_Expr : Node_Id := Expression (Alt);
5417 Alt_Loc : constant Source_Ptr := Sloc (Alt_Expr);
5418 LHS : Node_Id;
5419 Stmts : List_Id;
5421 begin
5422 -- Take the unrestricted access of the expression value for non-
5423 -- scalar types. This approach avoids big copies and covers the
5424 -- limited and unconstrained cases.
5426 -- Generate:
5427 -- AX'Unrestricted_Access
5429 if not Is_Copy_Type (Typ) then
5430 Alt_Expr :=
5431 Make_Attribute_Reference (Alt_Loc,
5432 Prefix => Relocate_Node (Alt_Expr),
5433 Attribute_Name => Name_Unrestricted_Access);
5434 end if;
5436 -- Generate:
5437 -- return AX['Unrestricted_Access];
5439 if Optimize_Return_Stmt then
5440 Stmts := New_List (
5441 Make_Simple_Return_Statement (Alt_Loc,
5442 Expression => Alt_Expr));
5444 -- Generate:
5445 -- Target := AX['Unrestricted_Access];
5447 else
5448 LHS := New_Occurrence_Of (Target, Loc);
5449 Set_Assignment_OK (LHS);
5451 Stmts := New_List (
5452 Make_Assignment_Statement (Alt_Loc,
5453 Name => LHS,
5454 Expression => Alt_Expr));
5455 end if;
5457 -- Propagate declarations inserted in the node by Insert_Actions
5458 -- (for example, temporaries generated to remove side effects).
5459 -- These actions must remain attached to the alternative, given
5460 -- that they are generated by the corresponding expression.
5462 if Present (Actions (Alt)) then
5463 Prepend_List (Actions (Alt), Stmts);
5464 end if;
5466 -- Finalize any transient objects on exit from the alternative.
5467 -- This is done only in the return optimization case because
5468 -- otherwise the case expression is converted into an expression
5469 -- with actions which already contains this form of processing.
5471 if Optimize_Return_Stmt then
5472 Process_If_Case_Statements (N, Stmts);
5473 end if;
5475 Append_To
5476 (Alternatives (Case_Stmt),
5477 Make_Case_Statement_Alternative (Sloc (Alt),
5478 Discrete_Choices => Discrete_Choices (Alt),
5479 Statements => Stmts));
5480 end;
5482 Next (Alt);
5483 end loop;
5485 -- Rewrite the parent return statement as a case statement
5487 if Optimize_Return_Stmt then
5488 Rewrite (Par, Case_Stmt);
5489 Analyze (Par);
5491 -- Otherwise convert the case expression into an expression with actions
5493 else
5494 Append_To (Acts, Case_Stmt);
5496 if Is_Copy_Type (Typ) then
5497 Expr := New_Occurrence_Of (Target, Loc);
5499 else
5500 Expr :=
5501 Make_Explicit_Dereference (Loc,
5502 Prefix => New_Occurrence_Of (Target, Loc));
5503 end if;
5505 -- Generate:
5506 -- do
5507 -- ...
5508 -- in Target[.all] end;
5510 Rewrite (N,
5511 Make_Expression_With_Actions (Loc,
5512 Expression => Expr,
5513 Actions => Acts));
5515 Analyze_And_Resolve (N, Typ);
5516 end if;
5517 end Expand_N_Case_Expression;
5519 -----------------------------------
5520 -- Expand_N_Explicit_Dereference --
5521 -----------------------------------
5523 procedure Expand_N_Explicit_Dereference (N : Node_Id) is
5524 begin
5525 -- Insert explicit dereference call for the checked storage pool case
5527 Insert_Dereference_Action (Prefix (N));
5529 -- If the type is an Atomic type for which Atomic_Sync is enabled, then
5530 -- we set the atomic sync flag.
5532 if Is_Atomic (Etype (N))
5533 and then not Atomic_Synchronization_Disabled (Etype (N))
5534 then
5535 Activate_Atomic_Synchronization (N);
5536 end if;
5537 end Expand_N_Explicit_Dereference;
5539 --------------------------------------
5540 -- Expand_N_Expression_With_Actions --
5541 --------------------------------------
5543 procedure Expand_N_Expression_With_Actions (N : Node_Id) is
5544 Acts : constant List_Id := Actions (N);
5546 procedure Force_Boolean_Evaluation (Expr : Node_Id);
5547 -- Force the evaluation of Boolean expression Expr
5549 function Process_Action (Act : Node_Id) return Traverse_Result;
5550 -- Inspect and process a single action of an expression_with_actions for
5551 -- transient objects. If such objects are found, the routine generates
5552 -- code to clean them up when the context of the expression is evaluated
5553 -- or elaborated.
5555 ------------------------------
5556 -- Force_Boolean_Evaluation --
5557 ------------------------------
5559 procedure Force_Boolean_Evaluation (Expr : Node_Id) is
5560 Loc : constant Source_Ptr := Sloc (N);
5561 Flag_Decl : Node_Id;
5562 Flag_Id : Entity_Id;
5564 begin
5565 -- Relocate the expression to the actions list by capturing its value
5566 -- in a Boolean flag. Generate:
5567 -- Flag : constant Boolean := Expr;
5569 Flag_Id := Make_Temporary (Loc, 'F');
5571 Flag_Decl :=
5572 Make_Object_Declaration (Loc,
5573 Defining_Identifier => Flag_Id,
5574 Constant_Present => True,
5575 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
5576 Expression => Relocate_Node (Expr));
5578 Append (Flag_Decl, Acts);
5579 Analyze (Flag_Decl);
5581 -- Replace the expression with a reference to the flag
5583 Rewrite (Expression (N), New_Occurrence_Of (Flag_Id, Loc));
5584 Analyze (Expression (N));
5585 end Force_Boolean_Evaluation;
5587 --------------------
5588 -- Process_Action --
5589 --------------------
5591 function Process_Action (Act : Node_Id) return Traverse_Result is
5592 begin
5593 if Nkind (Act) = N_Object_Declaration
5594 and then Is_Finalizable_Transient (Act, N)
5595 then
5596 Process_Transient_In_Expression (Act, N, Acts);
5597 return Skip;
5599 -- Avoid processing temporary function results multiple times when
5600 -- dealing with nested expression_with_actions.
5602 elsif Nkind (Act) = N_Expression_With_Actions then
5603 return Abandon;
5605 -- Do not process temporary function results in loops. This is done
5606 -- by Expand_N_Loop_Statement and Build_Finalizer.
5608 elsif Nkind (Act) = N_Loop_Statement then
5609 return Abandon;
5610 end if;
5612 return OK;
5613 end Process_Action;
5615 procedure Process_Single_Action is new Traverse_Proc (Process_Action);
5617 -- Local variables
5619 Act : Node_Id;
5621 -- Start of processing for Expand_N_Expression_With_Actions
5623 begin
5624 -- Do not evaluate the expression when it denotes an entity because the
5625 -- expression_with_actions node will be replaced by the reference.
5627 if Is_Entity_Name (Expression (N)) then
5628 null;
5630 -- Do not evaluate the expression when there are no actions because the
5631 -- expression_with_actions node will be replaced by the expression.
5633 elsif No (Acts) or else Is_Empty_List (Acts) then
5634 null;
5636 -- Force the evaluation of the expression by capturing its value in a
5637 -- temporary. This ensures that aliases of transient objects do not leak
5638 -- to the expression of the expression_with_actions node:
5640 -- do
5641 -- Trans_Id : Ctrl_Typ := ...;
5642 -- Alias : ... := Trans_Id;
5643 -- in ... Alias ... end;
5645 -- In the example above, Trans_Id cannot be finalized at the end of the
5646 -- actions list because this may affect the alias and the final value of
5647 -- the expression_with_actions. Forcing the evaluation encapsulates the
5648 -- reference to the Alias within the actions list:
5650 -- do
5651 -- Trans_Id : Ctrl_Typ := ...;
5652 -- Alias : ... := Trans_Id;
5653 -- Val : constant Boolean := ... Alias ...;
5654 -- <finalize Trans_Id>
5655 -- in Val end;
5657 -- Once this transformation is performed, it is safe to finalize the
5658 -- transient object at the end of the actions list.
5660 -- Note that Force_Evaluation does not remove side effects in operators
5661 -- because it assumes that all operands are evaluated and side effect
5662 -- free. This is not the case when an operand depends implicitly on the
5663 -- transient object through the use of access types.
5665 elsif Is_Boolean_Type (Etype (Expression (N))) then
5666 Force_Boolean_Evaluation (Expression (N));
5668 -- The expression of an expression_with_actions node may not necessarily
5669 -- be Boolean when the node appears in an if expression. In this case do
5670 -- the usual forced evaluation to encapsulate potential aliasing.
5672 else
5673 Force_Evaluation (Expression (N));
5674 end if;
5676 -- Process all transient objects found within the actions of the EWA
5677 -- node.
5679 Act := First (Acts);
5680 while Present (Act) loop
5681 Process_Single_Action (Act);
5682 Next (Act);
5683 end loop;
5685 -- Deal with case where there are no actions. In this case we simply
5686 -- rewrite the node with its expression since we don't need the actions
5687 -- and the specification of this node does not allow a null action list.
5689 -- Note: we use Rewrite instead of Replace, because Codepeer is using
5690 -- the expanded tree and relying on being able to retrieve the original
5691 -- tree in cases like this. This raises a whole lot of issues of whether
5692 -- we have problems elsewhere, which will be addressed in the future???
5694 if Is_Empty_List (Acts) then
5695 Rewrite (N, Relocate_Node (Expression (N)));
5696 end if;
5697 end Expand_N_Expression_With_Actions;
5699 ----------------------------
5700 -- Expand_N_If_Expression --
5701 ----------------------------
5703 -- Deal with limited types and condition actions
5705 procedure Expand_N_If_Expression (N : Node_Id) is
5706 Cond : constant Node_Id := First (Expressions (N));
5707 Loc : constant Source_Ptr := Sloc (N);
5708 Thenx : constant Node_Id := Next (Cond);
5709 Elsex : constant Node_Id := Next (Thenx);
5710 Typ : constant Entity_Id := Etype (N);
5712 Actions : List_Id;
5713 Decl : Node_Id;
5714 Expr : Node_Id;
5715 New_If : Node_Id;
5716 New_N : Node_Id;
5718 begin
5719 -- Check for MINIMIZED/ELIMINATED overflow mode
5721 if Minimized_Eliminated_Overflow_Check (N) then
5722 Apply_Arithmetic_Overflow_Check (N);
5723 return;
5724 end if;
5726 -- Fold at compile time if condition known. We have already folded
5727 -- static if expressions, but it is possible to fold any case in which
5728 -- the condition is known at compile time, even though the result is
5729 -- non-static.
5731 -- Note that we don't do the fold of such cases in Sem_Elab because
5732 -- it can cause infinite loops with the expander adding a conditional
5733 -- expression, and Sem_Elab circuitry removing it repeatedly.
5735 if Compile_Time_Known_Value (Cond) then
5736 declare
5737 function Fold_Known_Value (Cond : Node_Id) return Boolean;
5738 -- Fold at compile time. Assumes condition known. Return True if
5739 -- folding occurred, meaning we're done.
5741 ----------------------
5742 -- Fold_Known_Value --
5743 ----------------------
5745 function Fold_Known_Value (Cond : Node_Id) return Boolean is
5746 begin
5747 if Is_True (Expr_Value (Cond)) then
5748 Expr := Thenx;
5749 Actions := Then_Actions (N);
5750 else
5751 Expr := Elsex;
5752 Actions := Else_Actions (N);
5753 end if;
5755 Remove (Expr);
5757 if Present (Actions) then
5759 -- To minimize the use of Expression_With_Actions, just skip
5760 -- the optimization as it is not critical for correctness.
5762 if Minimize_Expression_With_Actions then
5763 return False;
5764 end if;
5766 Rewrite (N,
5767 Make_Expression_With_Actions (Loc,
5768 Expression => Relocate_Node (Expr),
5769 Actions => Actions));
5770 Analyze_And_Resolve (N, Typ);
5772 else
5773 Rewrite (N, Relocate_Node (Expr));
5774 end if;
5776 -- Note that the result is never static (legitimate cases of
5777 -- static if expressions were folded in Sem_Eval).
5779 Set_Is_Static_Expression (N, False);
5780 return True;
5781 end Fold_Known_Value;
5783 begin
5784 if Fold_Known_Value (Cond) then
5785 return;
5786 end if;
5787 end;
5788 end if;
5790 -- If the type is limited, and the back end does not handle limited
5791 -- types, then we expand as follows to avoid the possibility of
5792 -- improper copying.
5794 -- type Ptr is access all Typ;
5795 -- Cnn : Ptr;
5796 -- if cond then
5797 -- <<then actions>>
5798 -- Cnn := then-expr'Unrestricted_Access;
5799 -- else
5800 -- <<else actions>>
5801 -- Cnn := else-expr'Unrestricted_Access;
5802 -- end if;
5804 -- and replace the if expression by a reference to Cnn.all.
5806 -- This special case can be skipped if the back end handles limited
5807 -- types properly and ensures that no incorrect copies are made.
5809 if Is_By_Reference_Type (Typ)
5810 and then not Back_End_Handles_Limited_Types
5811 then
5812 -- When the "then" or "else" expressions involve controlled function
5813 -- calls, generated temporaries are chained on the corresponding list
5814 -- of actions. These temporaries need to be finalized after the if
5815 -- expression is evaluated.
5817 Process_If_Case_Statements (N, Then_Actions (N));
5818 Process_If_Case_Statements (N, Else_Actions (N));
5820 declare
5821 Cnn : constant Entity_Id := Make_Temporary (Loc, 'C', N);
5822 Ptr_Typ : constant Entity_Id := Make_Temporary (Loc, 'A');
5824 begin
5825 -- Generate:
5826 -- type Ann is access all Typ;
5828 Insert_Action (N,
5829 Make_Full_Type_Declaration (Loc,
5830 Defining_Identifier => Ptr_Typ,
5831 Type_Definition =>
5832 Make_Access_To_Object_Definition (Loc,
5833 All_Present => True,
5834 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5836 -- Generate:
5837 -- Cnn : Ann;
5839 Decl :=
5840 Make_Object_Declaration (Loc,
5841 Defining_Identifier => Cnn,
5842 Object_Definition => New_Occurrence_Of (Ptr_Typ, Loc));
5844 -- Generate:
5845 -- if Cond then
5846 -- Cnn := <Thenx>'Unrestricted_Access;
5847 -- else
5848 -- Cnn := <Elsex>'Unrestricted_Access;
5849 -- end if;
5851 New_If :=
5852 Make_Implicit_If_Statement (N,
5853 Condition => Relocate_Node (Cond),
5854 Then_Statements => New_List (
5855 Make_Assignment_Statement (Sloc (Thenx),
5856 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5857 Expression =>
5858 Make_Attribute_Reference (Loc,
5859 Prefix => Relocate_Node (Thenx),
5860 Attribute_Name => Name_Unrestricted_Access))),
5862 Else_Statements => New_List (
5863 Make_Assignment_Statement (Sloc (Elsex),
5864 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5865 Expression =>
5866 Make_Attribute_Reference (Loc,
5867 Prefix => Relocate_Node (Elsex),
5868 Attribute_Name => Name_Unrestricted_Access))));
5870 -- Preserve the original context for which the if statement is
5871 -- being generated. This is needed by the finalization machinery
5872 -- to prevent the premature finalization of controlled objects
5873 -- found within the if statement.
5875 Set_From_Conditional_Expression (New_If);
5877 New_N :=
5878 Make_Explicit_Dereference (Loc,
5879 Prefix => New_Occurrence_Of (Cnn, Loc));
5880 end;
5882 -- If the result is an unconstrained array and the if expression is in a
5883 -- context other than the initializing expression of the declaration of
5884 -- an object, then we pull out the if expression as follows:
5886 -- Cnn : constant typ := if-expression
5888 -- and then replace the if expression with an occurrence of Cnn. This
5889 -- avoids the need in the back end to create on-the-fly variable length
5890 -- temporaries (which it cannot do!)
5892 -- Note that the test for being in an object declaration avoids doing an
5893 -- unnecessary expansion, and also avoids infinite recursion.
5895 elsif Is_Array_Type (Typ) and then not Is_Constrained (Typ)
5896 and then (Nkind (Parent (N)) /= N_Object_Declaration
5897 or else Expression (Parent (N)) /= N)
5898 then
5899 declare
5900 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5902 begin
5903 Insert_Action (N,
5904 Make_Object_Declaration (Loc,
5905 Defining_Identifier => Cnn,
5906 Constant_Present => True,
5907 Object_Definition => New_Occurrence_Of (Typ, Loc),
5908 Expression => Relocate_Node (N),
5909 Has_Init_Expression => True));
5911 Rewrite (N, New_Occurrence_Of (Cnn, Loc));
5912 return;
5913 end;
5915 -- For other types, we only need to expand if there are other actions
5916 -- associated with either branch.
5918 elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
5920 -- We now wrap the actions into the appropriate expression
5922 if Minimize_Expression_With_Actions
5923 and then (Is_Elementary_Type (Underlying_Type (Typ))
5924 or else Is_Constrained (Underlying_Type (Typ)))
5925 then
5926 -- If we can't use N_Expression_With_Actions nodes, then we insert
5927 -- the following sequence of actions (using Insert_Actions):
5929 -- Cnn : typ;
5930 -- if cond then
5931 -- <<then actions>>
5932 -- Cnn := then-expr;
5933 -- else
5934 -- <<else actions>>
5935 -- Cnn := else-expr
5936 -- end if;
5938 -- and replace the if expression by a reference to Cnn
5940 declare
5941 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5943 begin
5944 Decl :=
5945 Make_Object_Declaration (Loc,
5946 Defining_Identifier => Cnn,
5947 Object_Definition => New_Occurrence_Of (Typ, Loc));
5949 New_If :=
5950 Make_Implicit_If_Statement (N,
5951 Condition => Relocate_Node (Cond),
5953 Then_Statements => New_List (
5954 Make_Assignment_Statement (Sloc (Thenx),
5955 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5956 Expression => Relocate_Node (Thenx))),
5958 Else_Statements => New_List (
5959 Make_Assignment_Statement (Sloc (Elsex),
5960 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5961 Expression => Relocate_Node (Elsex))));
5963 Set_Assignment_OK (Name (First (Then_Statements (New_If))));
5964 Set_Assignment_OK (Name (First (Else_Statements (New_If))));
5966 New_N := New_Occurrence_Of (Cnn, Loc);
5967 end;
5969 -- Regular path using Expression_With_Actions
5971 else
5972 if Present (Then_Actions (N)) then
5973 Rewrite (Thenx,
5974 Make_Expression_With_Actions (Sloc (Thenx),
5975 Actions => Then_Actions (N),
5976 Expression => Relocate_Node (Thenx)));
5978 Set_Then_Actions (N, No_List);
5979 Analyze_And_Resolve (Thenx, Typ);
5980 end if;
5982 if Present (Else_Actions (N)) then
5983 Rewrite (Elsex,
5984 Make_Expression_With_Actions (Sloc (Elsex),
5985 Actions => Else_Actions (N),
5986 Expression => Relocate_Node (Elsex)));
5988 Set_Else_Actions (N, No_List);
5989 Analyze_And_Resolve (Elsex, Typ);
5990 end if;
5992 return;
5993 end if;
5995 -- If no actions then no expansion needed, gigi will handle it using the
5996 -- same approach as a C conditional expression.
5998 else
5999 return;
6000 end if;
6002 -- Fall through here for either the limited expansion, or the case of
6003 -- inserting actions for nonlimited types. In both these cases, we must
6004 -- move the SLOC of the parent If statement to the newly created one and
6005 -- change it to the SLOC of the expression which, after expansion, will
6006 -- correspond to what is being evaluated.
6008 if Present (Parent (N)) and then Nkind (Parent (N)) = N_If_Statement then
6009 Set_Sloc (New_If, Sloc (Parent (N)));
6010 Set_Sloc (Parent (N), Loc);
6011 end if;
6013 -- Make sure Then_Actions and Else_Actions are appropriately moved
6014 -- to the new if statement.
6016 if Present (Then_Actions (N)) then
6017 Insert_List_Before
6018 (First (Then_Statements (New_If)), Then_Actions (N));
6019 end if;
6021 if Present (Else_Actions (N)) then
6022 Insert_List_Before
6023 (First (Else_Statements (New_If)), Else_Actions (N));
6024 end if;
6026 Insert_Action (N, Decl);
6027 Insert_Action (N, New_If);
6028 Rewrite (N, New_N);
6029 Analyze_And_Resolve (N, Typ);
6030 end Expand_N_If_Expression;
6032 -----------------
6033 -- Expand_N_In --
6034 -----------------
6036 procedure Expand_N_In (N : Node_Id) is
6037 Loc : constant Source_Ptr := Sloc (N);
6038 Restyp : constant Entity_Id := Etype (N);
6039 Lop : constant Node_Id := Left_Opnd (N);
6040 Rop : constant Node_Id := Right_Opnd (N);
6041 Static : constant Boolean := Is_OK_Static_Expression (N);
6043 procedure Substitute_Valid_Check;
6044 -- Replaces node N by Lop'Valid. This is done when we have an explicit
6045 -- test for the left operand being in range of its subtype.
6047 ----------------------------
6048 -- Substitute_Valid_Check --
6049 ----------------------------
6051 procedure Substitute_Valid_Check is
6052 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean;
6053 -- Determine whether arbitrary node Nod denotes a source object that
6054 -- may safely act as prefix of attribute 'Valid.
6056 ----------------------------
6057 -- Is_OK_Object_Reference --
6058 ----------------------------
6060 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean is
6061 Obj_Ref : Node_Id;
6063 begin
6064 -- Inspect the original operand
6066 Obj_Ref := Original_Node (Nod);
6068 -- The object reference must be a source construct, otherwise the
6069 -- codefix suggestion may refer to nonexistent code from a user
6070 -- perspective.
6072 if Comes_From_Source (Obj_Ref) then
6074 -- Recover the actual object reference. There may be more cases
6075 -- to consider???
6077 loop
6078 if Nkind_In (Obj_Ref, N_Type_Conversion,
6079 N_Unchecked_Type_Conversion)
6080 then
6081 Obj_Ref := Expression (Obj_Ref);
6082 else
6083 exit;
6084 end if;
6085 end loop;
6087 return Is_Object_Reference (Obj_Ref);
6088 end if;
6090 return False;
6091 end Is_OK_Object_Reference;
6093 -- Start of processing for Substitute_Valid_Check
6095 begin
6096 Rewrite (N,
6097 Make_Attribute_Reference (Loc,
6098 Prefix => Relocate_Node (Lop),
6099 Attribute_Name => Name_Valid));
6101 Analyze_And_Resolve (N, Restyp);
6103 -- Emit a warning when the left-hand operand of the membership test
6104 -- is a source object, otherwise the use of attribute 'Valid would be
6105 -- illegal. The warning is not given when overflow checking is either
6106 -- MINIMIZED or ELIMINATED, as the danger of optimization has been
6107 -- eliminated above.
6109 if Is_OK_Object_Reference (Lop)
6110 and then Overflow_Check_Mode not in Minimized_Or_Eliminated
6111 then
6112 Error_Msg_N
6113 ("??explicit membership test may be optimized away", N);
6114 Error_Msg_N -- CODEFIX
6115 ("\??use ''Valid attribute instead", N);
6116 end if;
6117 end Substitute_Valid_Check;
6119 -- Local variables
6121 Ltyp : Entity_Id;
6122 Rtyp : Entity_Id;
6124 -- Start of processing for Expand_N_In
6126 begin
6127 -- If set membership case, expand with separate procedure
6129 if Present (Alternatives (N)) then
6130 Expand_Set_Membership (N);
6131 return;
6132 end if;
6134 -- Not set membership, proceed with expansion
6136 Ltyp := Etype (Left_Opnd (N));
6137 Rtyp := Etype (Right_Opnd (N));
6139 -- If MINIMIZED/ELIMINATED overflow mode and type is a signed integer
6140 -- type, then expand with a separate procedure. Note the use of the
6141 -- flag No_Minimize_Eliminate to prevent infinite recursion.
6143 if Overflow_Check_Mode in Minimized_Or_Eliminated
6144 and then Is_Signed_Integer_Type (Ltyp)
6145 and then not No_Minimize_Eliminate (N)
6146 then
6147 Expand_Membership_Minimize_Eliminate_Overflow (N);
6148 return;
6149 end if;
6151 -- Check case of explicit test for an expression in range of its
6152 -- subtype. This is suspicious usage and we replace it with a 'Valid
6153 -- test and give a warning for scalar types.
6155 if Is_Scalar_Type (Ltyp)
6157 -- Only relevant for source comparisons
6159 and then Comes_From_Source (N)
6161 -- In floating-point this is a standard way to check for finite values
6162 -- and using 'Valid would typically be a pessimization.
6164 and then not Is_Floating_Point_Type (Ltyp)
6166 -- Don't give the message unless right operand is a type entity and
6167 -- the type of the left operand matches this type. Note that this
6168 -- eliminates the cases where MINIMIZED/ELIMINATED mode overflow
6169 -- checks have changed the type of the left operand.
6171 and then Nkind (Rop) in N_Has_Entity
6172 and then Ltyp = Entity (Rop)
6174 -- Skip this for predicated types, where such expressions are a
6175 -- reasonable way of testing if something meets the predicate.
6177 and then not Present (Predicate_Function (Ltyp))
6178 then
6179 Substitute_Valid_Check;
6180 return;
6181 end if;
6183 -- Do validity check on operands
6185 if Validity_Checks_On and Validity_Check_Operands then
6186 Ensure_Valid (Left_Opnd (N));
6187 Validity_Check_Range (Right_Opnd (N));
6188 end if;
6190 -- Case of explicit range
6192 if Nkind (Rop) = N_Range then
6193 declare
6194 Lo : constant Node_Id := Low_Bound (Rop);
6195 Hi : constant Node_Id := High_Bound (Rop);
6197 Lo_Orig : constant Node_Id := Original_Node (Lo);
6198 Hi_Orig : constant Node_Id := Original_Node (Hi);
6200 Lcheck : Compare_Result;
6201 Ucheck : Compare_Result;
6203 Warn1 : constant Boolean :=
6204 Constant_Condition_Warnings
6205 and then Comes_From_Source (N)
6206 and then not In_Instance;
6207 -- This must be true for any of the optimization warnings, we
6208 -- clearly want to give them only for source with the flag on. We
6209 -- also skip these warnings in an instance since it may be the
6210 -- case that different instantiations have different ranges.
6212 Warn2 : constant Boolean :=
6213 Warn1
6214 and then Nkind (Original_Node (Rop)) = N_Range
6215 and then Is_Integer_Type (Etype (Lo));
6216 -- For the case where only one bound warning is elided, we also
6217 -- insist on an explicit range and an integer type. The reason is
6218 -- that the use of enumeration ranges including an end point is
6219 -- common, as is the use of a subtype name, one of whose bounds is
6220 -- the same as the type of the expression.
6222 begin
6223 -- If test is explicit x'First .. x'Last, replace by valid check
6225 -- Could use some individual comments for this complex test ???
6227 if Is_Scalar_Type (Ltyp)
6229 -- And left operand is X'First where X matches left operand
6230 -- type (this eliminates cases of type mismatch, including
6231 -- the cases where ELIMINATED/MINIMIZED mode has changed the
6232 -- type of the left operand.
6234 and then Nkind (Lo_Orig) = N_Attribute_Reference
6235 and then Attribute_Name (Lo_Orig) = Name_First
6236 and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
6237 and then Entity (Prefix (Lo_Orig)) = Ltyp
6239 -- Same tests for right operand
6241 and then Nkind (Hi_Orig) = N_Attribute_Reference
6242 and then Attribute_Name (Hi_Orig) = Name_Last
6243 and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
6244 and then Entity (Prefix (Hi_Orig)) = Ltyp
6246 -- Relevant only for source cases
6248 and then Comes_From_Source (N)
6249 then
6250 Substitute_Valid_Check;
6251 goto Leave;
6252 end if;
6254 -- If bounds of type are known at compile time, and the end points
6255 -- are known at compile time and identical, this is another case
6256 -- for substituting a valid test. We only do this for discrete
6257 -- types, since it won't arise in practice for float types.
6259 if Comes_From_Source (N)
6260 and then Is_Discrete_Type (Ltyp)
6261 and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
6262 and then Compile_Time_Known_Value (Type_Low_Bound (Ltyp))
6263 and then Compile_Time_Known_Value (Lo)
6264 and then Compile_Time_Known_Value (Hi)
6265 and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
6266 and then Expr_Value (Type_Low_Bound (Ltyp)) = Expr_Value (Lo)
6268 -- Kill warnings in instances, since they may be cases where we
6269 -- have a test in the generic that makes sense with some types
6270 -- and not with other types.
6272 -- Similarly, do not rewrite membership as a validity check if
6273 -- within the predicate function for the type.
6275 -- Finally, if the original bounds are type conversions, even
6276 -- if they have been folded into constants, there are different
6277 -- types involved and 'Valid is not appropriate.
6279 then
6280 if In_Instance
6281 or else (Ekind (Current_Scope) = E_Function
6282 and then Is_Predicate_Function (Current_Scope))
6283 then
6284 null;
6286 elsif Nkind (Lo_Orig) = N_Type_Conversion
6287 or else Nkind (Hi_Orig) = N_Type_Conversion
6288 then
6289 null;
6291 else
6292 Substitute_Valid_Check;
6293 goto Leave;
6294 end if;
6295 end if;
6297 -- If we have an explicit range, do a bit of optimization based on
6298 -- range analysis (we may be able to kill one or both checks).
6300 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
6301 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
6303 -- If either check is known to fail, replace result by False since
6304 -- the other check does not matter. Preserve the static flag for
6305 -- legality checks, because we are constant-folding beyond RM 4.9.
6307 if Lcheck = LT or else Ucheck = GT then
6308 if Warn1 then
6309 Error_Msg_N ("?c?range test optimized away", N);
6310 Error_Msg_N ("\?c?value is known to be out of range", N);
6311 end if;
6313 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6314 Analyze_And_Resolve (N, Restyp);
6315 Set_Is_Static_Expression (N, Static);
6316 goto Leave;
6318 -- If both checks are known to succeed, replace result by True,
6319 -- since we know we are in range.
6321 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6322 if Warn1 then
6323 Error_Msg_N ("?c?range test optimized away", N);
6324 Error_Msg_N ("\?c?value is known to be in range", N);
6325 end if;
6327 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6328 Analyze_And_Resolve (N, Restyp);
6329 Set_Is_Static_Expression (N, Static);
6330 goto Leave;
6332 -- If lower bound check succeeds and upper bound check is not
6333 -- known to succeed or fail, then replace the range check with
6334 -- a comparison against the upper bound.
6336 elsif Lcheck in Compare_GE then
6337 if Warn2 and then not In_Instance then
6338 Error_Msg_N ("??lower bound test optimized away", Lo);
6339 Error_Msg_N ("\??value is known to be in range", Lo);
6340 end if;
6342 Rewrite (N,
6343 Make_Op_Le (Loc,
6344 Left_Opnd => Lop,
6345 Right_Opnd => High_Bound (Rop)));
6346 Analyze_And_Resolve (N, Restyp);
6347 goto Leave;
6349 -- If upper bound check succeeds and lower bound check is not
6350 -- known to succeed or fail, then replace the range check with
6351 -- a comparison against the lower bound.
6353 elsif Ucheck in Compare_LE then
6354 if Warn2 and then not In_Instance then
6355 Error_Msg_N ("??upper bound test optimized away", Hi);
6356 Error_Msg_N ("\??value is known to be in range", Hi);
6357 end if;
6359 Rewrite (N,
6360 Make_Op_Ge (Loc,
6361 Left_Opnd => Lop,
6362 Right_Opnd => Low_Bound (Rop)));
6363 Analyze_And_Resolve (N, Restyp);
6364 goto Leave;
6365 end if;
6367 -- We couldn't optimize away the range check, but there is one
6368 -- more issue. If we are checking constant conditionals, then we
6369 -- see if we can determine the outcome assuming everything is
6370 -- valid, and if so give an appropriate warning.
6372 if Warn1 and then not Assume_No_Invalid_Values then
6373 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
6374 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
6376 -- Result is out of range for valid value
6378 if Lcheck = LT or else Ucheck = GT then
6379 Error_Msg_N
6380 ("?c?value can only be in range if it is invalid", N);
6382 -- Result is in range for valid value
6384 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6385 Error_Msg_N
6386 ("?c?value can only be out of range if it is invalid", N);
6388 -- Lower bound check succeeds if value is valid
6390 elsif Warn2 and then Lcheck in Compare_GE then
6391 Error_Msg_N
6392 ("?c?lower bound check only fails if it is invalid", Lo);
6394 -- Upper bound check succeeds if value is valid
6396 elsif Warn2 and then Ucheck in Compare_LE then
6397 Error_Msg_N
6398 ("?c?upper bound check only fails for invalid values", Hi);
6399 end if;
6400 end if;
6401 end;
6403 -- For all other cases of an explicit range, nothing to be done
6405 goto Leave;
6407 -- Here right operand is a subtype mark
6409 else
6410 declare
6411 Typ : Entity_Id := Etype (Rop);
6412 Is_Acc : constant Boolean := Is_Access_Type (Typ);
6413 Cond : Node_Id := Empty;
6414 New_N : Node_Id;
6415 Obj : Node_Id := Lop;
6416 SCIL_Node : Node_Id;
6418 begin
6419 Remove_Side_Effects (Obj);
6421 -- For tagged type, do tagged membership operation
6423 if Is_Tagged_Type (Typ) then
6425 -- No expansion will be performed for VM targets, as the VM
6426 -- back ends will handle the membership tests directly.
6428 if Tagged_Type_Expansion then
6429 Tagged_Membership (N, SCIL_Node, New_N);
6430 Rewrite (N, New_N);
6431 Analyze_And_Resolve (N, Restyp, Suppress => All_Checks);
6433 -- Update decoration of relocated node referenced by the
6434 -- SCIL node.
6436 if Generate_SCIL and then Present (SCIL_Node) then
6437 Set_SCIL_Node (N, SCIL_Node);
6438 end if;
6439 end if;
6441 goto Leave;
6443 -- If type is scalar type, rewrite as x in t'First .. t'Last.
6444 -- This reason we do this is that the bounds may have the wrong
6445 -- type if they come from the original type definition. Also this
6446 -- way we get all the processing above for an explicit range.
6448 -- Don't do this for predicated types, since in this case we
6449 -- want to check the predicate.
6451 elsif Is_Scalar_Type (Typ) then
6452 if No (Predicate_Function (Typ)) then
6453 Rewrite (Rop,
6454 Make_Range (Loc,
6455 Low_Bound =>
6456 Make_Attribute_Reference (Loc,
6457 Attribute_Name => Name_First,
6458 Prefix => New_Occurrence_Of (Typ, Loc)),
6460 High_Bound =>
6461 Make_Attribute_Reference (Loc,
6462 Attribute_Name => Name_Last,
6463 Prefix => New_Occurrence_Of (Typ, Loc))));
6464 Analyze_And_Resolve (N, Restyp);
6465 end if;
6467 goto Leave;
6469 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
6470 -- a membership test if the subtype mark denotes a constrained
6471 -- Unchecked_Union subtype and the expression lacks inferable
6472 -- discriminants.
6474 elsif Is_Unchecked_Union (Base_Type (Typ))
6475 and then Is_Constrained (Typ)
6476 and then not Has_Inferable_Discriminants (Lop)
6477 then
6478 Insert_Action (N,
6479 Make_Raise_Program_Error (Loc,
6480 Reason => PE_Unchecked_Union_Restriction));
6482 -- Prevent Gigi from generating incorrect code by rewriting the
6483 -- test as False. What is this undocumented thing about ???
6485 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6486 goto Leave;
6487 end if;
6489 -- Here we have a non-scalar type
6491 if Is_Acc then
6492 Typ := Designated_Type (Typ);
6493 end if;
6495 if not Is_Constrained (Typ) then
6496 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6497 Analyze_And_Resolve (N, Restyp);
6499 -- For the constrained array case, we have to check the subscripts
6500 -- for an exact match if the lengths are non-zero (the lengths
6501 -- must match in any case).
6503 elsif Is_Array_Type (Typ) then
6504 Check_Subscripts : declare
6505 function Build_Attribute_Reference
6506 (E : Node_Id;
6507 Nam : Name_Id;
6508 Dim : Nat) return Node_Id;
6509 -- Build attribute reference E'Nam (Dim)
6511 -------------------------------
6512 -- Build_Attribute_Reference --
6513 -------------------------------
6515 function Build_Attribute_Reference
6516 (E : Node_Id;
6517 Nam : Name_Id;
6518 Dim : Nat) return Node_Id
6520 begin
6521 return
6522 Make_Attribute_Reference (Loc,
6523 Prefix => E,
6524 Attribute_Name => Nam,
6525 Expressions => New_List (
6526 Make_Integer_Literal (Loc, Dim)));
6527 end Build_Attribute_Reference;
6529 -- Start of processing for Check_Subscripts
6531 begin
6532 for J in 1 .. Number_Dimensions (Typ) loop
6533 Evolve_And_Then (Cond,
6534 Make_Op_Eq (Loc,
6535 Left_Opnd =>
6536 Build_Attribute_Reference
6537 (Duplicate_Subexpr_No_Checks (Obj),
6538 Name_First, J),
6539 Right_Opnd =>
6540 Build_Attribute_Reference
6541 (New_Occurrence_Of (Typ, Loc), Name_First, J)));
6543 Evolve_And_Then (Cond,
6544 Make_Op_Eq (Loc,
6545 Left_Opnd =>
6546 Build_Attribute_Reference
6547 (Duplicate_Subexpr_No_Checks (Obj),
6548 Name_Last, J),
6549 Right_Opnd =>
6550 Build_Attribute_Reference
6551 (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
6552 end loop;
6554 if Is_Acc then
6555 Cond :=
6556 Make_Or_Else (Loc,
6557 Left_Opnd =>
6558 Make_Op_Eq (Loc,
6559 Left_Opnd => Obj,
6560 Right_Opnd => Make_Null (Loc)),
6561 Right_Opnd => Cond);
6562 end if;
6564 Rewrite (N, Cond);
6565 Analyze_And_Resolve (N, Restyp);
6566 end Check_Subscripts;
6568 -- These are the cases where constraint checks may be required,
6569 -- e.g. records with possible discriminants
6571 else
6572 -- Expand the test into a series of discriminant comparisons.
6573 -- The expression that is built is the negation of the one that
6574 -- is used for checking discriminant constraints.
6576 Obj := Relocate_Node (Left_Opnd (N));
6578 if Has_Discriminants (Typ) then
6579 Cond := Make_Op_Not (Loc,
6580 Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
6582 if Is_Acc then
6583 Cond := Make_Or_Else (Loc,
6584 Left_Opnd =>
6585 Make_Op_Eq (Loc,
6586 Left_Opnd => Obj,
6587 Right_Opnd => Make_Null (Loc)),
6588 Right_Opnd => Cond);
6589 end if;
6591 else
6592 Cond := New_Occurrence_Of (Standard_True, Loc);
6593 end if;
6595 Rewrite (N, Cond);
6596 Analyze_And_Resolve (N, Restyp);
6597 end if;
6599 -- Ada 2012 (AI05-0149): Handle membership tests applied to an
6600 -- expression of an anonymous access type. This can involve an
6601 -- accessibility test and a tagged type membership test in the
6602 -- case of tagged designated types.
6604 if Ada_Version >= Ada_2012
6605 and then Is_Acc
6606 and then Ekind (Ltyp) = E_Anonymous_Access_Type
6607 then
6608 declare
6609 Expr_Entity : Entity_Id := Empty;
6610 New_N : Node_Id;
6611 Param_Level : Node_Id;
6612 Type_Level : Node_Id;
6614 begin
6615 if Is_Entity_Name (Lop) then
6616 Expr_Entity := Param_Entity (Lop);
6618 if not Present (Expr_Entity) then
6619 Expr_Entity := Entity (Lop);
6620 end if;
6621 end if;
6623 -- If a conversion of the anonymous access value to the
6624 -- tested type would be illegal, then the result is False.
6626 if not Valid_Conversion
6627 (Lop, Rtyp, Lop, Report_Errs => False)
6628 then
6629 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6630 Analyze_And_Resolve (N, Restyp);
6632 -- Apply an accessibility check if the access object has an
6633 -- associated access level and when the level of the type is
6634 -- less deep than the level of the access parameter. This
6635 -- only occur for access parameters and stand-alone objects
6636 -- of an anonymous access type.
6638 else
6639 if Present (Expr_Entity)
6640 and then
6641 Present
6642 (Effective_Extra_Accessibility (Expr_Entity))
6643 and then UI_Gt (Object_Access_Level (Lop),
6644 Type_Access_Level (Rtyp))
6645 then
6646 Param_Level :=
6647 New_Occurrence_Of
6648 (Effective_Extra_Accessibility (Expr_Entity), Loc);
6650 Type_Level :=
6651 Make_Integer_Literal (Loc, Type_Access_Level (Rtyp));
6653 -- Return True only if the accessibility level of the
6654 -- expression entity is not deeper than the level of
6655 -- the tested access type.
6657 Rewrite (N,
6658 Make_And_Then (Loc,
6659 Left_Opnd => Relocate_Node (N),
6660 Right_Opnd => Make_Op_Le (Loc,
6661 Left_Opnd => Param_Level,
6662 Right_Opnd => Type_Level)));
6664 Analyze_And_Resolve (N);
6665 end if;
6667 -- If the designated type is tagged, do tagged membership
6668 -- operation.
6670 -- *** NOTE: we have to check not null before doing the
6671 -- tagged membership test (but maybe that can be done
6672 -- inside Tagged_Membership?).
6674 if Is_Tagged_Type (Typ) then
6675 Rewrite (N,
6676 Make_And_Then (Loc,
6677 Left_Opnd => Relocate_Node (N),
6678 Right_Opnd =>
6679 Make_Op_Ne (Loc,
6680 Left_Opnd => Obj,
6681 Right_Opnd => Make_Null (Loc))));
6683 -- No expansion will be performed for VM targets, as
6684 -- the VM back ends will handle the membership tests
6685 -- directly.
6687 if Tagged_Type_Expansion then
6689 -- Note that we have to pass Original_Node, because
6690 -- the membership test might already have been
6691 -- rewritten by earlier parts of membership test.
6693 Tagged_Membership
6694 (Original_Node (N), SCIL_Node, New_N);
6696 -- Update decoration of relocated node referenced
6697 -- by the SCIL node.
6699 if Generate_SCIL and then Present (SCIL_Node) then
6700 Set_SCIL_Node (New_N, SCIL_Node);
6701 end if;
6703 Rewrite (N,
6704 Make_And_Then (Loc,
6705 Left_Opnd => Relocate_Node (N),
6706 Right_Opnd => New_N));
6708 Analyze_And_Resolve (N, Restyp);
6709 end if;
6710 end if;
6711 end if;
6712 end;
6713 end if;
6714 end;
6715 end if;
6717 -- At this point, we have done the processing required for the basic
6718 -- membership test, but not yet dealt with the predicate.
6720 <<Leave>>
6722 -- If a predicate is present, then we do the predicate test, but we
6723 -- most certainly want to omit this if we are within the predicate
6724 -- function itself, since otherwise we have an infinite recursion.
6725 -- The check should also not be emitted when testing against a range
6726 -- (the check is only done when the right operand is a subtype; see
6727 -- RM12-4.5.2 (28.1/3-30/3)).
6729 Predicate_Check : declare
6730 function In_Range_Check return Boolean;
6731 -- Within an expanded range check that may raise Constraint_Error do
6732 -- not generate a predicate check as well. It is redundant because
6733 -- the context will add an explicit predicate check, and it will
6734 -- raise the wrong exception if it fails.
6736 --------------------
6737 -- In_Range_Check --
6738 --------------------
6740 function In_Range_Check return Boolean is
6741 P : Node_Id;
6742 begin
6743 P := Parent (N);
6744 while Present (P) loop
6745 if Nkind (P) = N_Raise_Constraint_Error then
6746 return True;
6748 elsif Nkind (P) in N_Statement_Other_Than_Procedure_Call
6749 or else Nkind (P) = N_Procedure_Call_Statement
6750 or else Nkind (P) in N_Declaration
6751 then
6752 return False;
6753 end if;
6755 P := Parent (P);
6756 end loop;
6758 return False;
6759 end In_Range_Check;
6761 -- Local variables
6763 PFunc : constant Entity_Id := Predicate_Function (Rtyp);
6764 R_Op : Node_Id;
6766 -- Start of processing for Predicate_Check
6768 begin
6769 if Present (PFunc)
6770 and then Current_Scope /= PFunc
6771 and then Nkind (Rop) /= N_Range
6772 then
6773 if not In_Range_Check then
6774 R_Op := Make_Predicate_Call (Rtyp, Lop, Mem => True);
6775 else
6776 R_Op := New_Occurrence_Of (Standard_True, Loc);
6777 end if;
6779 Rewrite (N,
6780 Make_And_Then (Loc,
6781 Left_Opnd => Relocate_Node (N),
6782 Right_Opnd => R_Op));
6784 -- Analyze new expression, mark left operand as analyzed to
6785 -- avoid infinite recursion adding predicate calls. Similarly,
6786 -- suppress further range checks on the call.
6788 Set_Analyzed (Left_Opnd (N));
6789 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6791 -- All done, skip attempt at compile time determination of result
6793 return;
6794 end if;
6795 end Predicate_Check;
6796 end Expand_N_In;
6798 --------------------------------
6799 -- Expand_N_Indexed_Component --
6800 --------------------------------
6802 procedure Expand_N_Indexed_Component (N : Node_Id) is
6803 Loc : constant Source_Ptr := Sloc (N);
6804 Typ : constant Entity_Id := Etype (N);
6805 P : constant Node_Id := Prefix (N);
6806 T : constant Entity_Id := Etype (P);
6807 Atp : Entity_Id;
6809 begin
6810 -- A special optimization, if we have an indexed component that is
6811 -- selecting from a slice, then we can eliminate the slice, since, for
6812 -- example, x (i .. j)(k) is identical to x(k). The only difference is
6813 -- the range check required by the slice. The range check for the slice
6814 -- itself has already been generated. The range check for the
6815 -- subscripting operation is ensured by converting the subject to
6816 -- the subtype of the slice.
6818 -- This optimization not only generates better code, avoiding slice
6819 -- messing especially in the packed case, but more importantly bypasses
6820 -- some problems in handling this peculiar case, for example, the issue
6821 -- of dealing specially with object renamings.
6823 if Nkind (P) = N_Slice
6825 -- This optimization is disabled for CodePeer because it can transform
6826 -- an index-check constraint_error into a range-check constraint_error
6827 -- and CodePeer cares about that distinction.
6829 and then not CodePeer_Mode
6830 then
6831 Rewrite (N,
6832 Make_Indexed_Component (Loc,
6833 Prefix => Prefix (P),
6834 Expressions => New_List (
6835 Convert_To
6836 (Etype (First_Index (Etype (P))),
6837 First (Expressions (N))))));
6838 Analyze_And_Resolve (N, Typ);
6839 return;
6840 end if;
6842 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
6843 -- function, then additional actuals must be passed.
6845 if Is_Build_In_Place_Function_Call (P) then
6846 Make_Build_In_Place_Call_In_Anonymous_Context (P);
6848 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
6849 -- containing build-in-place function calls whose returned object covers
6850 -- interface types.
6852 elsif Present (Unqual_BIP_Iface_Function_Call (P)) then
6853 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (P);
6854 end if;
6856 -- If the prefix is an access type, then we unconditionally rewrite if
6857 -- as an explicit dereference. This simplifies processing for several
6858 -- cases, including packed array cases and certain cases in which checks
6859 -- must be generated. We used to try to do this only when it was
6860 -- necessary, but it cleans up the code to do it all the time.
6862 if Is_Access_Type (T) then
6863 Insert_Explicit_Dereference (P);
6864 Analyze_And_Resolve (P, Designated_Type (T));
6865 Atp := Designated_Type (T);
6866 else
6867 Atp := T;
6868 end if;
6870 -- Generate index and validity checks
6872 Generate_Index_Checks (N);
6874 if Validity_Checks_On and then Validity_Check_Subscripts then
6875 Apply_Subscript_Validity_Checks (N);
6876 end if;
6878 -- If selecting from an array with atomic components, and atomic sync
6879 -- is not suppressed for this array type, set atomic sync flag.
6881 if (Has_Atomic_Components (Atp)
6882 and then not Atomic_Synchronization_Disabled (Atp))
6883 or else (Is_Atomic (Typ)
6884 and then not Atomic_Synchronization_Disabled (Typ))
6885 or else (Is_Entity_Name (P)
6886 and then Has_Atomic_Components (Entity (P))
6887 and then not Atomic_Synchronization_Disabled (Entity (P)))
6888 then
6889 Activate_Atomic_Synchronization (N);
6890 end if;
6892 -- All done if the prefix is not a packed array implemented specially
6894 if not (Is_Packed (Etype (Prefix (N)))
6895 and then Present (Packed_Array_Impl_Type (Etype (Prefix (N)))))
6896 then
6897 return;
6898 end if;
6900 -- For packed arrays that are not bit-packed (i.e. the case of an array
6901 -- with one or more index types with a non-contiguous enumeration type),
6902 -- we can always use the normal packed element get circuit.
6904 if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
6905 Expand_Packed_Element_Reference (N);
6906 return;
6907 end if;
6909 -- For a reference to a component of a bit packed array, we convert it
6910 -- to a reference to the corresponding Packed_Array_Impl_Type. We only
6911 -- want to do this for simple references, and not for:
6913 -- Left side of assignment, or prefix of left side of assignment, or
6914 -- prefix of the prefix, to handle packed arrays of packed arrays,
6915 -- This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
6917 -- Renaming objects in renaming associations
6918 -- This case is handled when a use of the renamed variable occurs
6920 -- Actual parameters for a subprogram call
6921 -- This case is handled in Exp_Ch6.Expand_Actuals
6923 -- The second expression in a 'Read attribute reference
6925 -- The prefix of an address or bit or size attribute reference
6927 -- The following circuit detects these exceptions. Note that we need to
6928 -- deal with implicit dereferences when climbing up the parent chain,
6929 -- with the additional difficulty that the type of parents may have yet
6930 -- to be resolved since prefixes are usually resolved first.
6932 declare
6933 Child : Node_Id := N;
6934 Parnt : Node_Id := Parent (N);
6936 begin
6937 loop
6938 if Nkind (Parnt) = N_Unchecked_Expression then
6939 null;
6941 elsif Nkind (Parnt) = N_Object_Renaming_Declaration then
6942 return;
6944 elsif Nkind (Parnt) in N_Subprogram_Call
6945 or else (Nkind (Parnt) = N_Parameter_Association
6946 and then Nkind (Parent (Parnt)) in N_Subprogram_Call)
6947 then
6948 return;
6950 elsif Nkind (Parnt) = N_Attribute_Reference
6951 and then Nam_In (Attribute_Name (Parnt), Name_Address,
6952 Name_Bit,
6953 Name_Size)
6954 and then Prefix (Parnt) = Child
6955 then
6956 return;
6958 elsif Nkind (Parnt) = N_Assignment_Statement
6959 and then Name (Parnt) = Child
6960 then
6961 return;
6963 -- If the expression is an index of an indexed component, it must
6964 -- be expanded regardless of context.
6966 elsif Nkind (Parnt) = N_Indexed_Component
6967 and then Child /= Prefix (Parnt)
6968 then
6969 Expand_Packed_Element_Reference (N);
6970 return;
6972 elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
6973 and then Name (Parent (Parnt)) = Parnt
6974 then
6975 return;
6977 elsif Nkind (Parnt) = N_Attribute_Reference
6978 and then Attribute_Name (Parnt) = Name_Read
6979 and then Next (First (Expressions (Parnt))) = Child
6980 then
6981 return;
6983 elsif Nkind (Parnt) = N_Indexed_Component
6984 and then Prefix (Parnt) = Child
6985 then
6986 null;
6988 elsif Nkind (Parnt) = N_Selected_Component
6989 and then Prefix (Parnt) = Child
6990 and then not (Present (Etype (Selector_Name (Parnt)))
6991 and then
6992 Is_Access_Type (Etype (Selector_Name (Parnt))))
6993 then
6994 null;
6996 -- If the parent is a dereference, either implicit or explicit,
6997 -- then the packed reference needs to be expanded.
6999 else
7000 Expand_Packed_Element_Reference (N);
7001 return;
7002 end if;
7004 -- Keep looking up tree for unchecked expression, or if we are the
7005 -- prefix of a possible assignment left side.
7007 Child := Parnt;
7008 Parnt := Parent (Child);
7009 end loop;
7010 end;
7011 end Expand_N_Indexed_Component;
7013 ---------------------
7014 -- Expand_N_Not_In --
7015 ---------------------
7017 -- Replace a not in b by not (a in b) so that the expansions for (a in b)
7018 -- can be done. This avoids needing to duplicate this expansion code.
7020 procedure Expand_N_Not_In (N : Node_Id) is
7021 Loc : constant Source_Ptr := Sloc (N);
7022 Typ : constant Entity_Id := Etype (N);
7023 Cfs : constant Boolean := Comes_From_Source (N);
7025 begin
7026 Rewrite (N,
7027 Make_Op_Not (Loc,
7028 Right_Opnd =>
7029 Make_In (Loc,
7030 Left_Opnd => Left_Opnd (N),
7031 Right_Opnd => Right_Opnd (N))));
7033 -- If this is a set membership, preserve list of alternatives
7035 Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
7037 -- We want this to appear as coming from source if original does (see
7038 -- transformations in Expand_N_In).
7040 Set_Comes_From_Source (N, Cfs);
7041 Set_Comes_From_Source (Right_Opnd (N), Cfs);
7043 -- Now analyze transformed node
7045 Analyze_And_Resolve (N, Typ);
7046 end Expand_N_Not_In;
7048 -------------------
7049 -- Expand_N_Null --
7050 -------------------
7052 -- The only replacement required is for the case of a null of a type that
7053 -- is an access to protected subprogram, or a subtype thereof. We represent
7054 -- such access values as a record, and so we must replace the occurrence of
7055 -- null by the equivalent record (with a null address and a null pointer in
7056 -- it), so that the back end creates the proper value.
7058 procedure Expand_N_Null (N : Node_Id) is
7059 Loc : constant Source_Ptr := Sloc (N);
7060 Typ : constant Entity_Id := Base_Type (Etype (N));
7061 Agg : Node_Id;
7063 begin
7064 if Is_Access_Protected_Subprogram_Type (Typ) then
7065 Agg :=
7066 Make_Aggregate (Loc,
7067 Expressions => New_List (
7068 New_Occurrence_Of (RTE (RE_Null_Address), Loc),
7069 Make_Null (Loc)));
7071 Rewrite (N, Agg);
7072 Analyze_And_Resolve (N, Equivalent_Type (Typ));
7074 -- For subsequent semantic analysis, the node must retain its type.
7075 -- Gigi in any case replaces this type by the corresponding record
7076 -- type before processing the node.
7078 Set_Etype (N, Typ);
7079 end if;
7081 exception
7082 when RE_Not_Available =>
7083 return;
7084 end Expand_N_Null;
7086 ---------------------
7087 -- Expand_N_Op_Abs --
7088 ---------------------
7090 procedure Expand_N_Op_Abs (N : Node_Id) is
7091 Loc : constant Source_Ptr := Sloc (N);
7092 Expr : constant Node_Id := Right_Opnd (N);
7094 begin
7095 Unary_Op_Validity_Checks (N);
7097 -- Check for MINIMIZED/ELIMINATED overflow mode
7099 if Minimized_Eliminated_Overflow_Check (N) then
7100 Apply_Arithmetic_Overflow_Check (N);
7101 return;
7102 end if;
7104 -- Deal with software overflow checking
7106 if Is_Signed_Integer_Type (Etype (N))
7107 and then Do_Overflow_Check (N)
7108 then
7109 -- The only case to worry about is when the argument is equal to the
7110 -- largest negative number, so what we do is to insert the check:
7112 -- [constraint_error when Expr = typ'Base'First]
7114 -- with the usual Duplicate_Subexpr use coding for expr
7116 Insert_Action (N,
7117 Make_Raise_Constraint_Error (Loc,
7118 Condition =>
7119 Make_Op_Eq (Loc,
7120 Left_Opnd => Duplicate_Subexpr (Expr),
7121 Right_Opnd =>
7122 Make_Attribute_Reference (Loc,
7123 Prefix =>
7124 New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
7125 Attribute_Name => Name_First)),
7126 Reason => CE_Overflow_Check_Failed));
7128 Set_Do_Overflow_Check (N, False);
7129 end if;
7130 end Expand_N_Op_Abs;
7132 ---------------------
7133 -- Expand_N_Op_Add --
7134 ---------------------
7136 procedure Expand_N_Op_Add (N : Node_Id) is
7137 Typ : constant Entity_Id := Etype (N);
7139 begin
7140 Binary_Op_Validity_Checks (N);
7142 -- Check for MINIMIZED/ELIMINATED overflow mode
7144 if Minimized_Eliminated_Overflow_Check (N) then
7145 Apply_Arithmetic_Overflow_Check (N);
7146 return;
7147 end if;
7149 -- N + 0 = 0 + N = N for integer types
7151 if Is_Integer_Type (Typ) then
7152 if Compile_Time_Known_Value (Right_Opnd (N))
7153 and then Expr_Value (Right_Opnd (N)) = Uint_0
7154 then
7155 Rewrite (N, Left_Opnd (N));
7156 return;
7158 elsif Compile_Time_Known_Value (Left_Opnd (N))
7159 and then Expr_Value (Left_Opnd (N)) = Uint_0
7160 then
7161 Rewrite (N, Right_Opnd (N));
7162 return;
7163 end if;
7164 end if;
7166 -- Arithmetic overflow checks for signed integer/fixed point types
7168 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
7169 Apply_Arithmetic_Overflow_Check (N);
7170 return;
7171 end if;
7173 -- Overflow checks for floating-point if -gnateF mode active
7175 Check_Float_Op_Overflow (N);
7177 Expand_Nonbinary_Modular_Op (N);
7178 end Expand_N_Op_Add;
7180 ---------------------
7181 -- Expand_N_Op_And --
7182 ---------------------
7184 procedure Expand_N_Op_And (N : Node_Id) is
7185 Typ : constant Entity_Id := Etype (N);
7187 begin
7188 Binary_Op_Validity_Checks (N);
7190 if Is_Array_Type (Etype (N)) then
7191 Expand_Boolean_Operator (N);
7193 elsif Is_Boolean_Type (Etype (N)) then
7194 Adjust_Condition (Left_Opnd (N));
7195 Adjust_Condition (Right_Opnd (N));
7196 Set_Etype (N, Standard_Boolean);
7197 Adjust_Result_Type (N, Typ);
7199 elsif Is_Intrinsic_Subprogram (Entity (N)) then
7200 Expand_Intrinsic_Call (N, Entity (N));
7201 end if;
7203 Expand_Nonbinary_Modular_Op (N);
7204 end Expand_N_Op_And;
7206 ------------------------
7207 -- Expand_N_Op_Concat --
7208 ------------------------
7210 procedure Expand_N_Op_Concat (N : Node_Id) is
7211 Opnds : List_Id;
7212 -- List of operands to be concatenated
7214 Cnode : Node_Id;
7215 -- Node which is to be replaced by the result of concatenating the nodes
7216 -- in the list Opnds.
7218 begin
7219 -- Ensure validity of both operands
7221 Binary_Op_Validity_Checks (N);
7223 -- If we are the left operand of a concatenation higher up the tree,
7224 -- then do nothing for now, since we want to deal with a series of
7225 -- concatenations as a unit.
7227 if Nkind (Parent (N)) = N_Op_Concat
7228 and then N = Left_Opnd (Parent (N))
7229 then
7230 return;
7231 end if;
7233 -- We get here with a concatenation whose left operand may be a
7234 -- concatenation itself with a consistent type. We need to process
7235 -- these concatenation operands from left to right, which means
7236 -- from the deepest node in the tree to the highest node.
7238 Cnode := N;
7239 while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
7240 Cnode := Left_Opnd (Cnode);
7241 end loop;
7243 -- Now Cnode is the deepest concatenation, and its parents are the
7244 -- concatenation nodes above, so now we process bottom up, doing the
7245 -- operands.
7247 -- The outer loop runs more than once if more than one concatenation
7248 -- type is involved.
7250 Outer : loop
7251 Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
7252 Set_Parent (Opnds, N);
7254 -- The inner loop gathers concatenation operands
7256 Inner : while Cnode /= N
7257 and then Base_Type (Etype (Cnode)) =
7258 Base_Type (Etype (Parent (Cnode)))
7259 loop
7260 Cnode := Parent (Cnode);
7261 Append (Right_Opnd (Cnode), Opnds);
7262 end loop Inner;
7264 -- Note: The following code is a temporary workaround for N731-034
7265 -- and N829-028 and will be kept until the general issue of internal
7266 -- symbol serialization is addressed. The workaround is kept under a
7267 -- debug switch to avoid permiating into the general case.
7269 -- Wrap the node to concatenate into an expression actions node to
7270 -- keep it nicely packaged. This is useful in the case of an assert
7271 -- pragma with a concatenation where we want to be able to delete
7272 -- the concatenation and all its expansion stuff.
7274 if Debug_Flag_Dot_H then
7275 declare
7276 Cnod : constant Node_Id := New_Copy_Tree (Cnode);
7277 Typ : constant Entity_Id := Base_Type (Etype (Cnode));
7279 begin
7280 -- Note: use Rewrite rather than Replace here, so that for
7281 -- example Why_Not_Static can find the original concatenation
7282 -- node OK!
7284 Rewrite (Cnode,
7285 Make_Expression_With_Actions (Sloc (Cnode),
7286 Actions => New_List (Make_Null_Statement (Sloc (Cnode))),
7287 Expression => Cnod));
7289 Expand_Concatenate (Cnod, Opnds);
7290 Analyze_And_Resolve (Cnode, Typ);
7291 end;
7293 -- Default case
7295 else
7296 Expand_Concatenate (Cnode, Opnds);
7297 end if;
7299 exit Outer when Cnode = N;
7300 Cnode := Parent (Cnode);
7301 end loop Outer;
7302 end Expand_N_Op_Concat;
7304 ------------------------
7305 -- Expand_N_Op_Divide --
7306 ------------------------
7308 procedure Expand_N_Op_Divide (N : Node_Id) is
7309 Loc : constant Source_Ptr := Sloc (N);
7310 Lopnd : constant Node_Id := Left_Opnd (N);
7311 Ropnd : constant Node_Id := Right_Opnd (N);
7312 Ltyp : constant Entity_Id := Etype (Lopnd);
7313 Rtyp : constant Entity_Id := Etype (Ropnd);
7314 Typ : Entity_Id := Etype (N);
7315 Rknow : constant Boolean := Is_Integer_Type (Typ)
7316 and then
7317 Compile_Time_Known_Value (Ropnd);
7318 Rval : Uint;
7320 begin
7321 Binary_Op_Validity_Checks (N);
7323 -- Check for MINIMIZED/ELIMINATED overflow mode
7325 if Minimized_Eliminated_Overflow_Check (N) then
7326 Apply_Arithmetic_Overflow_Check (N);
7327 return;
7328 end if;
7330 -- Otherwise proceed with expansion of division
7332 if Rknow then
7333 Rval := Expr_Value (Ropnd);
7334 end if;
7336 -- N / 1 = N for integer types
7338 if Rknow and then Rval = Uint_1 then
7339 Rewrite (N, Lopnd);
7340 return;
7341 end if;
7343 -- Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
7344 -- Is_Power_Of_2_For_Shift is set means that we know that our left
7345 -- operand is an unsigned integer, as required for this to work.
7347 if Nkind (Ropnd) = N_Op_Expon
7348 and then Is_Power_Of_2_For_Shift (Ropnd)
7350 -- We cannot do this transformation in configurable run time mode if we
7351 -- have 64-bit integers and long shifts are not available.
7353 and then (Esize (Ltyp) <= 32 or else Support_Long_Shifts_On_Target)
7354 then
7355 Rewrite (N,
7356 Make_Op_Shift_Right (Loc,
7357 Left_Opnd => Lopnd,
7358 Right_Opnd =>
7359 Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
7360 Analyze_And_Resolve (N, Typ);
7361 return;
7362 end if;
7364 -- Do required fixup of universal fixed operation
7366 if Typ = Universal_Fixed then
7367 Fixup_Universal_Fixed_Operation (N);
7368 Typ := Etype (N);
7369 end if;
7371 -- Divisions with fixed-point results
7373 if Is_Fixed_Point_Type (Typ) then
7375 -- No special processing if Treat_Fixed_As_Integer is set, since
7376 -- from a semantic point of view such operations are simply integer
7377 -- operations and will be treated that way.
7379 if not Treat_Fixed_As_Integer (N) then
7380 if Is_Integer_Type (Rtyp) then
7381 Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
7382 else
7383 Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
7384 end if;
7385 end if;
7387 -- Deal with divide-by-zero check if back end cannot handle them
7388 -- and the flag is set indicating that we need such a check. Note
7389 -- that we don't need to bother here with the case of mixed-mode
7390 -- (Right operand an integer type), since these will be rewritten
7391 -- with conversions to a divide with a fixed-point right operand.
7393 if Nkind (N) = N_Op_Divide
7394 and then Do_Division_Check (N)
7395 and then not Backend_Divide_Checks_On_Target
7396 and then not Is_Integer_Type (Rtyp)
7397 then
7398 Set_Do_Division_Check (N, False);
7399 Insert_Action (N,
7400 Make_Raise_Constraint_Error (Loc,
7401 Condition =>
7402 Make_Op_Eq (Loc,
7403 Left_Opnd => Duplicate_Subexpr_Move_Checks (Ropnd),
7404 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
7405 Reason => CE_Divide_By_Zero));
7406 end if;
7408 -- Other cases of division of fixed-point operands. Again we exclude the
7409 -- case where Treat_Fixed_As_Integer is set.
7411 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
7412 and then not Treat_Fixed_As_Integer (N)
7413 then
7414 if Is_Integer_Type (Typ) then
7415 Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
7416 else
7417 pragma Assert (Is_Floating_Point_Type (Typ));
7418 Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
7419 end if;
7421 -- Mixed-mode operations can appear in a non-static universal context,
7422 -- in which case the integer argument must be converted explicitly.
7424 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
7425 Rewrite (Ropnd,
7426 Convert_To (Universal_Real, Relocate_Node (Ropnd)));
7428 Analyze_And_Resolve (Ropnd, Universal_Real);
7430 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
7431 Rewrite (Lopnd,
7432 Convert_To (Universal_Real, Relocate_Node (Lopnd)));
7434 Analyze_And_Resolve (Lopnd, Universal_Real);
7436 -- Non-fixed point cases, do integer zero divide and overflow checks
7438 elsif Is_Integer_Type (Typ) then
7439 Apply_Divide_Checks (N);
7440 end if;
7442 -- Overflow checks for floating-point if -gnateF mode active
7444 Check_Float_Op_Overflow (N);
7446 Expand_Nonbinary_Modular_Op (N);
7447 end Expand_N_Op_Divide;
7449 --------------------
7450 -- Expand_N_Op_Eq --
7451 --------------------
7453 procedure Expand_N_Op_Eq (N : Node_Id) is
7454 Loc : constant Source_Ptr := Sloc (N);
7455 Typ : constant Entity_Id := Etype (N);
7456 Lhs : constant Node_Id := Left_Opnd (N);
7457 Rhs : constant Node_Id := Right_Opnd (N);
7458 Bodies : constant List_Id := New_List;
7459 A_Typ : constant Entity_Id := Etype (Lhs);
7461 procedure Build_Equality_Call (Eq : Entity_Id);
7462 -- If a constructed equality exists for the type or for its parent,
7463 -- build and analyze call, adding conversions if the operation is
7464 -- inherited.
7466 function Find_Equality (Prims : Elist_Id) return Entity_Id;
7467 -- Find a primitive equality function within primitive operation list
7468 -- Prims.
7470 function Has_Unconstrained_UU_Component (Typ : Entity_Id) return Boolean;
7471 -- Determines whether a type has a subcomponent of an unconstrained
7472 -- Unchecked_Union subtype. Typ is a record type.
7474 -------------------------
7475 -- Build_Equality_Call --
7476 -------------------------
7478 procedure Build_Equality_Call (Eq : Entity_Id) is
7479 Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
7480 L_Exp : Node_Id := Relocate_Node (Lhs);
7481 R_Exp : Node_Id := Relocate_Node (Rhs);
7483 begin
7484 -- Adjust operands if necessary to comparison type
7486 if Base_Type (Op_Type) /= Base_Type (A_Typ)
7487 and then not Is_Class_Wide_Type (A_Typ)
7488 then
7489 L_Exp := OK_Convert_To (Op_Type, L_Exp);
7490 R_Exp := OK_Convert_To (Op_Type, R_Exp);
7491 end if;
7493 -- If we have an Unchecked_Union, we need to add the inferred
7494 -- discriminant values as actuals in the function call. At this
7495 -- point, the expansion has determined that both operands have
7496 -- inferable discriminants.
7498 if Is_Unchecked_Union (Op_Type) then
7499 declare
7500 Lhs_Type : constant Node_Id := Etype (L_Exp);
7501 Rhs_Type : constant Node_Id := Etype (R_Exp);
7503 Lhs_Discr_Vals : Elist_Id;
7504 -- List of inferred discriminant values for left operand.
7506 Rhs_Discr_Vals : Elist_Id;
7507 -- List of inferred discriminant values for right operand.
7509 Discr : Entity_Id;
7511 begin
7512 Lhs_Discr_Vals := New_Elmt_List;
7513 Rhs_Discr_Vals := New_Elmt_List;
7515 -- Per-object constrained selected components require special
7516 -- attention. If the enclosing scope of the component is an
7517 -- Unchecked_Union, we cannot reference its discriminants
7518 -- directly. This is why we use the extra parameters of the
7519 -- equality function of the enclosing Unchecked_Union.
7521 -- type UU_Type (Discr : Integer := 0) is
7522 -- . . .
7523 -- end record;
7524 -- pragma Unchecked_Union (UU_Type);
7526 -- 1. Unchecked_Union enclosing record:
7528 -- type Enclosing_UU_Type (Discr : Integer := 0) is record
7529 -- . . .
7530 -- Comp : UU_Type (Discr);
7531 -- . . .
7532 -- end Enclosing_UU_Type;
7533 -- pragma Unchecked_Union (Enclosing_UU_Type);
7535 -- Obj1 : Enclosing_UU_Type;
7536 -- Obj2 : Enclosing_UU_Type (1);
7538 -- [. . .] Obj1 = Obj2 [. . .]
7540 -- Generated code:
7542 -- if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
7544 -- A and B are the formal parameters of the equality function
7545 -- of Enclosing_UU_Type. The function always has two extra
7546 -- formals to capture the inferred discriminant values for
7547 -- each discriminant of the type.
7549 -- 2. Non-Unchecked_Union enclosing record:
7551 -- type
7552 -- Enclosing_Non_UU_Type (Discr : Integer := 0)
7553 -- is record
7554 -- . . .
7555 -- Comp : UU_Type (Discr);
7556 -- . . .
7557 -- end Enclosing_Non_UU_Type;
7559 -- Obj1 : Enclosing_Non_UU_Type;
7560 -- Obj2 : Enclosing_Non_UU_Type (1);
7562 -- ... Obj1 = Obj2 ...
7564 -- Generated code:
7566 -- if not (uu_typeEQ (obj1.comp, obj2.comp,
7567 -- obj1.discr, obj2.discr)) then
7569 -- In this case we can directly reference the discriminants of
7570 -- the enclosing record.
7572 -- Process left operand of equality
7574 if Nkind (Lhs) = N_Selected_Component
7575 and then
7576 Has_Per_Object_Constraint (Entity (Selector_Name (Lhs)))
7577 then
7578 -- If enclosing record is an Unchecked_Union, use formals
7579 -- corresponding to each discriminant. The name of the
7580 -- formal is that of the discriminant, with added suffix,
7581 -- see Exp_Ch3.Build_Record_Equality for details.
7583 if Is_Unchecked_Union (Scope (Entity (Selector_Name (Lhs))))
7584 then
7585 Discr :=
7586 First_Discriminant
7587 (Scope (Entity (Selector_Name (Lhs))));
7588 while Present (Discr) loop
7589 Append_Elmt
7590 (Make_Identifier (Loc,
7591 Chars => New_External_Name (Chars (Discr), 'A')),
7592 To => Lhs_Discr_Vals);
7593 Next_Discriminant (Discr);
7594 end loop;
7596 -- If enclosing record is of a non-Unchecked_Union type, it
7597 -- is possible to reference its discriminants directly.
7599 else
7600 Discr := First_Discriminant (Lhs_Type);
7601 while Present (Discr) loop
7602 Append_Elmt
7603 (Make_Selected_Component (Loc,
7604 Prefix => Prefix (Lhs),
7605 Selector_Name =>
7606 New_Copy
7607 (Get_Discriminant_Value (Discr,
7608 Lhs_Type,
7609 Stored_Constraint (Lhs_Type)))),
7610 To => Lhs_Discr_Vals);
7611 Next_Discriminant (Discr);
7612 end loop;
7613 end if;
7615 -- Otherwise operand is on object with a constrained type.
7616 -- Infer the discriminant values from the constraint.
7618 else
7619 Discr := First_Discriminant (Lhs_Type);
7620 while Present (Discr) loop
7621 Append_Elmt
7622 (New_Copy
7623 (Get_Discriminant_Value (Discr,
7624 Lhs_Type,
7625 Stored_Constraint (Lhs_Type))),
7626 To => Lhs_Discr_Vals);
7627 Next_Discriminant (Discr);
7628 end loop;
7629 end if;
7631 -- Similar processing for right operand of equality
7633 if Nkind (Rhs) = N_Selected_Component
7634 and then
7635 Has_Per_Object_Constraint (Entity (Selector_Name (Rhs)))
7636 then
7637 if Is_Unchecked_Union
7638 (Scope (Entity (Selector_Name (Rhs))))
7639 then
7640 Discr :=
7641 First_Discriminant
7642 (Scope (Entity (Selector_Name (Rhs))));
7643 while Present (Discr) loop
7644 Append_Elmt
7645 (Make_Identifier (Loc,
7646 Chars => New_External_Name (Chars (Discr), 'B')),
7647 To => Rhs_Discr_Vals);
7648 Next_Discriminant (Discr);
7649 end loop;
7651 else
7652 Discr := First_Discriminant (Rhs_Type);
7653 while Present (Discr) loop
7654 Append_Elmt
7655 (Make_Selected_Component (Loc,
7656 Prefix => Prefix (Rhs),
7657 Selector_Name =>
7658 New_Copy (Get_Discriminant_Value
7659 (Discr,
7660 Rhs_Type,
7661 Stored_Constraint (Rhs_Type)))),
7662 To => Rhs_Discr_Vals);
7663 Next_Discriminant (Discr);
7664 end loop;
7665 end if;
7667 else
7668 Discr := First_Discriminant (Rhs_Type);
7669 while Present (Discr) loop
7670 Append_Elmt
7671 (New_Copy (Get_Discriminant_Value
7672 (Discr,
7673 Rhs_Type,
7674 Stored_Constraint (Rhs_Type))),
7675 To => Rhs_Discr_Vals);
7676 Next_Discriminant (Discr);
7677 end loop;
7678 end if;
7680 -- Now merge the list of discriminant values so that values
7681 -- of corresponding discriminants are adjacent.
7683 declare
7684 Params : List_Id;
7685 L_Elmt : Elmt_Id;
7686 R_Elmt : Elmt_Id;
7688 begin
7689 Params := New_List (L_Exp, R_Exp);
7690 L_Elmt := First_Elmt (Lhs_Discr_Vals);
7691 R_Elmt := First_Elmt (Rhs_Discr_Vals);
7692 while Present (L_Elmt) loop
7693 Append_To (Params, Node (L_Elmt));
7694 Append_To (Params, Node (R_Elmt));
7695 Next_Elmt (L_Elmt);
7696 Next_Elmt (R_Elmt);
7697 end loop;
7699 Rewrite (N,
7700 Make_Function_Call (Loc,
7701 Name => New_Occurrence_Of (Eq, Loc),
7702 Parameter_Associations => Params));
7703 end;
7704 end;
7706 -- Normal case, not an unchecked union
7708 else
7709 Rewrite (N,
7710 Make_Function_Call (Loc,
7711 Name => New_Occurrence_Of (Eq, Loc),
7712 Parameter_Associations => New_List (L_Exp, R_Exp)));
7713 end if;
7715 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7716 end Build_Equality_Call;
7718 -------------------
7719 -- Find_Equality --
7720 -------------------
7722 function Find_Equality (Prims : Elist_Id) return Entity_Id is
7723 function Find_Aliased_Equality (Prim : Entity_Id) return Entity_Id;
7724 -- Find an equality in a possible alias chain starting from primitive
7725 -- operation Prim.
7727 function Is_Equality (Id : Entity_Id) return Boolean;
7728 -- Determine whether arbitrary entity Id denotes an equality
7730 ---------------------------
7731 -- Find_Aliased_Equality --
7732 ---------------------------
7734 function Find_Aliased_Equality (Prim : Entity_Id) return Entity_Id is
7735 Candid : Entity_Id;
7737 begin
7738 -- Inspect each candidate in the alias chain, checking whether it
7739 -- denotes an equality.
7741 Candid := Prim;
7742 while Present (Candid) loop
7743 if Is_Equality (Candid) then
7744 return Candid;
7745 end if;
7747 Candid := Alias (Candid);
7748 end loop;
7750 return Empty;
7751 end Find_Aliased_Equality;
7753 -----------------
7754 -- Is_Equality --
7755 -----------------
7757 function Is_Equality (Id : Entity_Id) return Boolean is
7758 Formal_1 : Entity_Id;
7759 Formal_2 : Entity_Id;
7761 begin
7762 -- The equality function carries name "=", returns Boolean, and
7763 -- has exactly two formal parameters of an identical type.
7765 if Ekind (Id) = E_Function
7766 and then Chars (Id) = Name_Op_Eq
7767 and then Base_Type (Etype (Id)) = Standard_Boolean
7768 then
7769 Formal_1 := First_Formal (Id);
7770 Formal_2 := Empty;
7772 if Present (Formal_1) then
7773 Formal_2 := Next_Formal (Formal_1);
7774 end if;
7776 return
7777 Present (Formal_1)
7778 and then Present (Formal_2)
7779 and then Etype (Formal_1) = Etype (Formal_2)
7780 and then No (Next_Formal (Formal_2));
7781 end if;
7783 return False;
7784 end Is_Equality;
7786 -- Local variables
7788 Eq_Prim : Entity_Id;
7789 Prim_Elmt : Elmt_Id;
7791 -- Start of processing for Find_Equality
7793 begin
7794 -- Assume that the tagged type lacks an equality
7796 Eq_Prim := Empty;
7798 -- Inspect the list of primitives looking for a suitable equality
7799 -- within a possible chain of aliases.
7801 Prim_Elmt := First_Elmt (Prims);
7802 while Present (Prim_Elmt) and then No (Eq_Prim) loop
7803 Eq_Prim := Find_Aliased_Equality (Node (Prim_Elmt));
7805 Next_Elmt (Prim_Elmt);
7806 end loop;
7808 -- A tagged type should always have an equality
7810 pragma Assert (Present (Eq_Prim));
7812 return Eq_Prim;
7813 end Find_Equality;
7815 ------------------------------------
7816 -- Has_Unconstrained_UU_Component --
7817 ------------------------------------
7819 function Has_Unconstrained_UU_Component
7820 (Typ : Entity_Id) return Boolean
7822 Tdef : constant Node_Id :=
7823 Type_Definition (Declaration_Node (Base_Type (Typ)));
7824 Clist : Node_Id;
7825 Vpart : Node_Id;
7827 function Component_Is_Unconstrained_UU
7828 (Comp : Node_Id) return Boolean;
7829 -- Determines whether the subtype of the component is an
7830 -- unconstrained Unchecked_Union.
7832 function Variant_Is_Unconstrained_UU
7833 (Variant : Node_Id) return Boolean;
7834 -- Determines whether a component of the variant has an unconstrained
7835 -- Unchecked_Union subtype.
7837 -----------------------------------
7838 -- Component_Is_Unconstrained_UU --
7839 -----------------------------------
7841 function Component_Is_Unconstrained_UU
7842 (Comp : Node_Id) return Boolean
7844 begin
7845 if Nkind (Comp) /= N_Component_Declaration then
7846 return False;
7847 end if;
7849 declare
7850 Sindic : constant Node_Id :=
7851 Subtype_Indication (Component_Definition (Comp));
7853 begin
7854 -- Unconstrained nominal type. In the case of a constraint
7855 -- present, the node kind would have been N_Subtype_Indication.
7857 if Nkind (Sindic) = N_Identifier then
7858 return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
7859 end if;
7861 return False;
7862 end;
7863 end Component_Is_Unconstrained_UU;
7865 ---------------------------------
7866 -- Variant_Is_Unconstrained_UU --
7867 ---------------------------------
7869 function Variant_Is_Unconstrained_UU
7870 (Variant : Node_Id) return Boolean
7872 Clist : constant Node_Id := Component_List (Variant);
7874 begin
7875 if Is_Empty_List (Component_Items (Clist)) then
7876 return False;
7877 end if;
7879 -- We only need to test one component
7881 declare
7882 Comp : Node_Id := First (Component_Items (Clist));
7884 begin
7885 while Present (Comp) loop
7886 if Component_Is_Unconstrained_UU (Comp) then
7887 return True;
7888 end if;
7890 Next (Comp);
7891 end loop;
7892 end;
7894 -- None of the components withing the variant were of
7895 -- unconstrained Unchecked_Union type.
7897 return False;
7898 end Variant_Is_Unconstrained_UU;
7900 -- Start of processing for Has_Unconstrained_UU_Component
7902 begin
7903 if Null_Present (Tdef) then
7904 return False;
7905 end if;
7907 Clist := Component_List (Tdef);
7908 Vpart := Variant_Part (Clist);
7910 -- Inspect available components
7912 if Present (Component_Items (Clist)) then
7913 declare
7914 Comp : Node_Id := First (Component_Items (Clist));
7916 begin
7917 while Present (Comp) loop
7919 -- One component is sufficient
7921 if Component_Is_Unconstrained_UU (Comp) then
7922 return True;
7923 end if;
7925 Next (Comp);
7926 end loop;
7927 end;
7928 end if;
7930 -- Inspect available components withing variants
7932 if Present (Vpart) then
7933 declare
7934 Variant : Node_Id := First (Variants (Vpart));
7936 begin
7937 while Present (Variant) loop
7939 -- One component within a variant is sufficient
7941 if Variant_Is_Unconstrained_UU (Variant) then
7942 return True;
7943 end if;
7945 Next (Variant);
7946 end loop;
7947 end;
7948 end if;
7950 -- Neither the available components, nor the components inside the
7951 -- variant parts were of an unconstrained Unchecked_Union subtype.
7953 return False;
7954 end Has_Unconstrained_UU_Component;
7956 -- Local variables
7958 Typl : Entity_Id;
7960 -- Start of processing for Expand_N_Op_Eq
7962 begin
7963 Binary_Op_Validity_Checks (N);
7965 -- Deal with private types
7967 Typl := A_Typ;
7969 if Ekind (Typl) = E_Private_Type then
7970 Typl := Underlying_Type (Typl);
7972 elsif Ekind (Typl) = E_Private_Subtype then
7973 Typl := Underlying_Type (Base_Type (Typl));
7974 end if;
7976 -- It may happen in error situations that the underlying type is not
7977 -- set. The error will be detected later, here we just defend the
7978 -- expander code.
7980 if No (Typl) then
7981 return;
7982 end if;
7984 -- Now get the implementation base type (note that plain Base_Type here
7985 -- might lead us back to the private type, which is not what we want!)
7987 Typl := Implementation_Base_Type (Typl);
7989 -- Equality between variant records results in a call to a routine
7990 -- that has conditional tests of the discriminant value(s), and hence
7991 -- violates the No_Implicit_Conditionals restriction.
7993 if Has_Variant_Part (Typl) then
7994 declare
7995 Msg : Boolean;
7997 begin
7998 Check_Restriction (Msg, No_Implicit_Conditionals, N);
8000 if Msg then
8001 Error_Msg_N
8002 ("\comparison of variant records tests discriminants", N);
8003 return;
8004 end if;
8005 end;
8006 end if;
8008 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8009 -- means we no longer have a comparison operation, we are all done.
8011 Expand_Compare_Minimize_Eliminate_Overflow (N);
8013 if Nkind (N) /= N_Op_Eq then
8014 return;
8015 end if;
8017 -- Boolean types (requiring handling of non-standard case)
8019 if Is_Boolean_Type (Typl) then
8020 Adjust_Condition (Left_Opnd (N));
8021 Adjust_Condition (Right_Opnd (N));
8022 Set_Etype (N, Standard_Boolean);
8023 Adjust_Result_Type (N, Typ);
8025 -- Array types
8027 elsif Is_Array_Type (Typl) then
8029 -- If we are doing full validity checking, and it is possible for the
8030 -- array elements to be invalid then expand out array comparisons to
8031 -- make sure that we check the array elements.
8033 if Validity_Check_Operands
8034 and then not Is_Known_Valid (Component_Type (Typl))
8035 then
8036 declare
8037 Save_Force_Validity_Checks : constant Boolean :=
8038 Force_Validity_Checks;
8039 begin
8040 Force_Validity_Checks := True;
8041 Rewrite (N,
8042 Expand_Array_Equality
8044 Relocate_Node (Lhs),
8045 Relocate_Node (Rhs),
8046 Bodies,
8047 Typl));
8048 Insert_Actions (N, Bodies);
8049 Analyze_And_Resolve (N, Standard_Boolean);
8050 Force_Validity_Checks := Save_Force_Validity_Checks;
8051 end;
8053 -- Packed case where both operands are known aligned
8055 elsif Is_Bit_Packed_Array (Typl)
8056 and then not Is_Possibly_Unaligned_Object (Lhs)
8057 and then not Is_Possibly_Unaligned_Object (Rhs)
8058 then
8059 Expand_Packed_Eq (N);
8061 -- Where the component type is elementary we can use a block bit
8062 -- comparison (if supported on the target) exception in the case
8063 -- of floating-point (negative zero issues require element by
8064 -- element comparison), and atomic/VFA types (where we must be sure
8065 -- to load elements independently) and possibly unaligned arrays.
8067 elsif Is_Elementary_Type (Component_Type (Typl))
8068 and then not Is_Floating_Point_Type (Component_Type (Typl))
8069 and then not Is_Atomic_Or_VFA (Component_Type (Typl))
8070 and then not Is_Possibly_Unaligned_Object (Lhs)
8071 and then not Is_Possibly_Unaligned_Object (Rhs)
8072 and then Support_Composite_Compare_On_Target
8073 then
8074 null;
8076 -- For composite and floating-point cases, expand equality loop to
8077 -- make sure of using proper comparisons for tagged types, and
8078 -- correctly handling the floating-point case.
8080 else
8081 Rewrite (N,
8082 Expand_Array_Equality
8084 Relocate_Node (Lhs),
8085 Relocate_Node (Rhs),
8086 Bodies,
8087 Typl));
8088 Insert_Actions (N, Bodies, Suppress => All_Checks);
8089 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
8090 end if;
8092 -- Record Types
8094 elsif Is_Record_Type (Typl) then
8096 -- For tagged types, use the primitive "="
8098 if Is_Tagged_Type (Typl) then
8100 -- No need to do anything else compiling under restriction
8101 -- No_Dispatching_Calls. During the semantic analysis we
8102 -- already notified such violation.
8104 if Restriction_Active (No_Dispatching_Calls) then
8105 return;
8106 end if;
8108 -- If this is an untagged private type completed with a derivation
8109 -- of an untagged private type whose full view is a tagged type,
8110 -- we use the primitive operations of the private type (since it
8111 -- does not have a full view, and also because its equality
8112 -- primitive may have been overridden in its untagged full view).
8114 if Inherits_From_Tagged_Full_View (A_Typ) then
8115 Build_Equality_Call
8116 (Find_Equality (Collect_Primitive_Operations (A_Typ)));
8118 -- Find the type's predefined equality or an overriding
8119 -- user-defined equality. The reason for not simply calling
8120 -- Find_Prim_Op here is that there may be a user-defined
8121 -- overloaded equality op that precedes the equality that we
8122 -- want, so we have to explicitly search (e.g., there could be
8123 -- an equality with two different parameter types).
8125 else
8126 if Is_Class_Wide_Type (Typl) then
8127 Typl := Find_Specific_Type (Typl);
8128 end if;
8130 Build_Equality_Call
8131 (Find_Equality (Primitive_Operations (Typl)));
8132 end if;
8134 -- Ada 2005 (AI-216): Program_Error is raised when evaluating the
8135 -- predefined equality operator for a type which has a subcomponent
8136 -- of an Unchecked_Union type whose nominal subtype is unconstrained.
8138 elsif Has_Unconstrained_UU_Component (Typl) then
8139 Insert_Action (N,
8140 Make_Raise_Program_Error (Loc,
8141 Reason => PE_Unchecked_Union_Restriction));
8143 -- Prevent Gigi from generating incorrect code by rewriting the
8144 -- equality as a standard False. (is this documented somewhere???)
8146 Rewrite (N,
8147 New_Occurrence_Of (Standard_False, Loc));
8149 elsif Is_Unchecked_Union (Typl) then
8151 -- If we can infer the discriminants of the operands, we make a
8152 -- call to the TSS equality function.
8154 if Has_Inferable_Discriminants (Lhs)
8155 and then
8156 Has_Inferable_Discriminants (Rhs)
8157 then
8158 Build_Equality_Call
8159 (TSS (Root_Type (Typl), TSS_Composite_Equality));
8161 else
8162 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
8163 -- the predefined equality operator for an Unchecked_Union type
8164 -- if either of the operands lack inferable discriminants.
8166 Insert_Action (N,
8167 Make_Raise_Program_Error (Loc,
8168 Reason => PE_Unchecked_Union_Restriction));
8170 -- Emit a warning on source equalities only, otherwise the
8171 -- message may appear out of place due to internal use. The
8172 -- warning is unconditional because it is required by the
8173 -- language.
8175 if Comes_From_Source (N) then
8176 Error_Msg_N
8177 ("Unchecked_Union discriminants cannot be determined??",
8179 Error_Msg_N
8180 ("\Program_Error will be raised for equality operation??",
8182 end if;
8184 -- Prevent Gigi from generating incorrect code by rewriting
8185 -- the equality as a standard False (documented where???).
8187 Rewrite (N,
8188 New_Occurrence_Of (Standard_False, Loc));
8189 end if;
8191 -- If a type support function is present (for complex cases), use it
8193 elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
8194 Build_Equality_Call
8195 (TSS (Root_Type (Typl), TSS_Composite_Equality));
8197 -- When comparing two Bounded_Strings, use the primitive equality of
8198 -- the root Super_String type.
8200 elsif Is_Bounded_String (Typl) then
8201 Build_Equality_Call
8202 (Find_Equality
8203 (Collect_Primitive_Operations (Root_Type (Typl))));
8205 -- Otherwise expand the component by component equality. Note that
8206 -- we never use block-bit comparisons for records, because of the
8207 -- problems with gaps. The back end will often be able to recombine
8208 -- the separate comparisons that we generate here.
8210 else
8211 Remove_Side_Effects (Lhs);
8212 Remove_Side_Effects (Rhs);
8213 Rewrite (N,
8214 Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
8216 Insert_Actions (N, Bodies, Suppress => All_Checks);
8217 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
8218 end if;
8219 end if;
8221 -- Test if result is known at compile time
8223 Rewrite_Comparison (N);
8225 -- Special optimization of length comparison
8227 Optimize_Length_Comparison (N);
8229 -- One more special case: if we have a comparison of X'Result = expr
8230 -- in floating-point, then if not already there, change expr to be
8231 -- f'Machine (expr) to eliminate surprise from extra precision.
8233 if Is_Floating_Point_Type (Typl)
8234 and then Nkind (Original_Node (Lhs)) = N_Attribute_Reference
8235 and then Attribute_Name (Original_Node (Lhs)) = Name_Result
8236 then
8237 -- Stick in the Typ'Machine call if not already there
8239 if Nkind (Rhs) /= N_Attribute_Reference
8240 or else Attribute_Name (Rhs) /= Name_Machine
8241 then
8242 Rewrite (Rhs,
8243 Make_Attribute_Reference (Loc,
8244 Prefix => New_Occurrence_Of (Typl, Loc),
8245 Attribute_Name => Name_Machine,
8246 Expressions => New_List (Relocate_Node (Rhs))));
8247 Analyze_And_Resolve (Rhs, Typl);
8248 end if;
8249 end if;
8250 end Expand_N_Op_Eq;
8252 -----------------------
8253 -- Expand_N_Op_Expon --
8254 -----------------------
8256 procedure Expand_N_Op_Expon (N : Node_Id) is
8257 Loc : constant Source_Ptr := Sloc (N);
8258 Ovflo : constant Boolean := Do_Overflow_Check (N);
8259 Typ : constant Entity_Id := Etype (N);
8260 Rtyp : constant Entity_Id := Root_Type (Typ);
8262 Bastyp : Entity_Id;
8264 function Wrap_MA (Exp : Node_Id) return Node_Id;
8265 -- Given an expression Exp, if the root type is Float or Long_Float,
8266 -- then wrap the expression in a call of Bastyp'Machine, to stop any
8267 -- extra precision. This is done to ensure that X**A = X**B when A is
8268 -- a static constant and B is a variable with the same value. For any
8269 -- other type, the node Exp is returned unchanged.
8271 -------------
8272 -- Wrap_MA --
8273 -------------
8275 function Wrap_MA (Exp : Node_Id) return Node_Id is
8276 Loc : constant Source_Ptr := Sloc (Exp);
8278 begin
8279 if Rtyp = Standard_Float or else Rtyp = Standard_Long_Float then
8280 return
8281 Make_Attribute_Reference (Loc,
8282 Attribute_Name => Name_Machine,
8283 Prefix => New_Occurrence_Of (Bastyp, Loc),
8284 Expressions => New_List (Relocate_Node (Exp)));
8285 else
8286 return Exp;
8287 end if;
8288 end Wrap_MA;
8290 -- Local variables
8292 Base : Node_Id;
8293 Ent : Entity_Id;
8294 Etyp : Entity_Id;
8295 Exp : Node_Id;
8296 Exptyp : Entity_Id;
8297 Expv : Uint;
8298 Rent : RE_Id;
8299 Temp : Node_Id;
8300 Xnode : Node_Id;
8302 -- Start of processing for Expand_N_Op_Expon
8304 begin
8305 Binary_Op_Validity_Checks (N);
8307 -- CodePeer wants to see the unexpanded N_Op_Expon node
8309 if CodePeer_Mode then
8310 return;
8311 end if;
8313 -- Relocation of left and right operands must be done after performing
8314 -- the validity checks since the generation of validation checks may
8315 -- remove side effects.
8317 Base := Relocate_Node (Left_Opnd (N));
8318 Bastyp := Etype (Base);
8319 Exp := Relocate_Node (Right_Opnd (N));
8320 Exptyp := Etype (Exp);
8322 -- If either operand is of a private type, then we have the use of an
8323 -- intrinsic operator, and we get rid of the privateness, by using root
8324 -- types of underlying types for the actual operation. Otherwise the
8325 -- private types will cause trouble if we expand multiplications or
8326 -- shifts etc. We also do this transformation if the result type is
8327 -- different from the base type.
8329 if Is_Private_Type (Etype (Base))
8330 or else Is_Private_Type (Typ)
8331 or else Is_Private_Type (Exptyp)
8332 or else Rtyp /= Root_Type (Bastyp)
8333 then
8334 declare
8335 Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
8336 Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
8337 begin
8338 Rewrite (N,
8339 Unchecked_Convert_To (Typ,
8340 Make_Op_Expon (Loc,
8341 Left_Opnd => Unchecked_Convert_To (Bt, Base),
8342 Right_Opnd => Unchecked_Convert_To (Et, Exp))));
8343 Analyze_And_Resolve (N, Typ);
8344 return;
8345 end;
8346 end if;
8348 -- Check for MINIMIZED/ELIMINATED overflow mode
8350 if Minimized_Eliminated_Overflow_Check (N) then
8351 Apply_Arithmetic_Overflow_Check (N);
8352 return;
8353 end if;
8355 -- Test for case of known right argument where we can replace the
8356 -- exponentiation by an equivalent expression using multiplication.
8358 -- Note: use CRT_Safe version of Compile_Time_Known_Value because in
8359 -- configurable run-time mode, we may not have the exponentiation
8360 -- routine available, and we don't want the legality of the program
8361 -- to depend on how clever the compiler is in knowing values.
8363 if CRT_Safe_Compile_Time_Known_Value (Exp) then
8364 Expv := Expr_Value (Exp);
8366 -- We only fold small non-negative exponents. You might think we
8367 -- could fold small negative exponents for the real case, but we
8368 -- can't because we are required to raise Constraint_Error for
8369 -- the case of 0.0 ** (negative) even if Machine_Overflows = False.
8370 -- See ACVC test C4A012B, and it is not worth generating the test.
8372 -- For small negative exponents, we return the reciprocal of
8373 -- the folding of the exponentiation for the opposite (positive)
8374 -- exponent, as required by Ada RM 4.5.6(11/3).
8376 if abs Expv <= 4 then
8378 -- X ** 0 = 1 (or 1.0)
8380 if Expv = 0 then
8382 -- Call Remove_Side_Effects to ensure that any side effects
8383 -- in the ignored left operand (in particular function calls
8384 -- to user defined functions) are properly executed.
8386 Remove_Side_Effects (Base);
8388 if Ekind (Typ) in Integer_Kind then
8389 Xnode := Make_Integer_Literal (Loc, Intval => 1);
8390 else
8391 Xnode := Make_Real_Literal (Loc, Ureal_1);
8392 end if;
8394 -- X ** 1 = X
8396 elsif Expv = 1 then
8397 Xnode := Base;
8399 -- X ** 2 = X * X
8401 elsif Expv = 2 then
8402 Xnode :=
8403 Wrap_MA (
8404 Make_Op_Multiply (Loc,
8405 Left_Opnd => Duplicate_Subexpr (Base),
8406 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8408 -- X ** 3 = X * X * X
8410 elsif Expv = 3 then
8411 Xnode :=
8412 Wrap_MA (
8413 Make_Op_Multiply (Loc,
8414 Left_Opnd =>
8415 Make_Op_Multiply (Loc,
8416 Left_Opnd => Duplicate_Subexpr (Base),
8417 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
8418 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8420 -- X ** 4 ->
8422 -- do
8423 -- En : constant base'type := base * base;
8424 -- in
8425 -- En * En
8427 elsif Expv = 4 then
8428 Temp := Make_Temporary (Loc, 'E', Base);
8430 Xnode :=
8431 Make_Expression_With_Actions (Loc,
8432 Actions => New_List (
8433 Make_Object_Declaration (Loc,
8434 Defining_Identifier => Temp,
8435 Constant_Present => True,
8436 Object_Definition => New_Occurrence_Of (Typ, Loc),
8437 Expression =>
8438 Wrap_MA (
8439 Make_Op_Multiply (Loc,
8440 Left_Opnd =>
8441 Duplicate_Subexpr (Base),
8442 Right_Opnd =>
8443 Duplicate_Subexpr_No_Checks (Base))))),
8445 Expression =>
8446 Wrap_MA (
8447 Make_Op_Multiply (Loc,
8448 Left_Opnd => New_Occurrence_Of (Temp, Loc),
8449 Right_Opnd => New_Occurrence_Of (Temp, Loc))));
8451 -- X ** N = 1.0 / X ** (-N)
8452 -- N in -4 .. -1
8454 else
8455 pragma Assert
8456 (Expv = -1 or Expv = -2 or Expv = -3 or Expv = -4);
8458 Xnode :=
8459 Make_Op_Divide (Loc,
8460 Left_Opnd =>
8461 Make_Float_Literal (Loc,
8462 Radix => Uint_1,
8463 Significand => Uint_1,
8464 Exponent => Uint_0),
8465 Right_Opnd =>
8466 Make_Op_Expon (Loc,
8467 Left_Opnd => Duplicate_Subexpr (Base),
8468 Right_Opnd =>
8469 Make_Integer_Literal (Loc,
8470 Intval => -Expv)));
8471 end if;
8473 Rewrite (N, Xnode);
8474 Analyze_And_Resolve (N, Typ);
8475 return;
8476 end if;
8477 end if;
8479 -- Deal with optimizing 2 ** expression to shift where possible
8481 -- Note: we used to check that Exptyp was an unsigned type. But that is
8482 -- an unnecessary check, since if Exp is negative, we have a run-time
8483 -- error that is either caught (so we get the right result) or we have
8484 -- suppressed the check, in which case the code is erroneous anyway.
8486 if Is_Integer_Type (Rtyp)
8488 -- The base value must be "safe compile-time known", and exactly 2
8490 and then Nkind (Base) = N_Integer_Literal
8491 and then CRT_Safe_Compile_Time_Known_Value (Base)
8492 and then Expr_Value (Base) = Uint_2
8494 -- We only handle cases where the right type is a integer
8496 and then Is_Integer_Type (Root_Type (Exptyp))
8497 and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
8499 -- This transformation is not applicable for a modular type with a
8500 -- nonbinary modulus because we do not handle modular reduction in
8501 -- a correct manner if we attempt this transformation in this case.
8503 and then not Non_Binary_Modulus (Typ)
8504 then
8505 -- Handle the cases where our parent is a division or multiplication
8506 -- specially. In these cases we can convert to using a shift at the
8507 -- parent level if we are not doing overflow checking, since it is
8508 -- too tricky to combine the overflow check at the parent level.
8510 if not Ovflo
8511 and then Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply)
8512 then
8513 declare
8514 P : constant Node_Id := Parent (N);
8515 L : constant Node_Id := Left_Opnd (P);
8516 R : constant Node_Id := Right_Opnd (P);
8518 begin
8519 if (Nkind (P) = N_Op_Multiply
8520 and then
8521 ((Is_Integer_Type (Etype (L)) and then R = N)
8522 or else
8523 (Is_Integer_Type (Etype (R)) and then L = N))
8524 and then not Do_Overflow_Check (P))
8526 or else
8527 (Nkind (P) = N_Op_Divide
8528 and then Is_Integer_Type (Etype (L))
8529 and then Is_Unsigned_Type (Etype (L))
8530 and then R = N
8531 and then not Do_Overflow_Check (P))
8532 then
8533 Set_Is_Power_Of_2_For_Shift (N);
8534 return;
8535 end if;
8536 end;
8538 -- Here we just have 2 ** N on its own, so we can convert this to a
8539 -- shift node. We are prepared to deal with overflow here, and we
8540 -- also have to handle proper modular reduction for binary modular.
8542 else
8543 declare
8544 OK : Boolean;
8545 Lo : Uint;
8546 Hi : Uint;
8548 MaxS : Uint;
8549 -- Maximum shift count with no overflow
8551 TestS : Boolean;
8552 -- Set True if we must test the shift count
8554 Test_Gt : Node_Id;
8555 -- Node for test against TestS
8557 begin
8558 -- Compute maximum shift based on the underlying size. For a
8559 -- modular type this is one less than the size.
8561 if Is_Modular_Integer_Type (Typ) then
8563 -- For modular integer types, this is the size of the value
8564 -- being shifted minus one. Any larger values will cause
8565 -- modular reduction to a result of zero. Note that we do
8566 -- want the RM_Size here (e.g. mod 2 ** 7, we want a result
8567 -- of 6, since 2**7 should be reduced to zero).
8569 MaxS := RM_Size (Rtyp) - 1;
8571 -- For signed integer types, we use the size of the value
8572 -- being shifted minus 2. Larger values cause overflow.
8574 else
8575 MaxS := Esize (Rtyp) - 2;
8576 end if;
8578 -- Determine range to see if it can be larger than MaxS
8580 Determine_Range
8581 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
8582 TestS := (not OK) or else Hi > MaxS;
8584 -- Signed integer case
8586 if Is_Signed_Integer_Type (Typ) then
8588 -- Generate overflow check if overflow is active. Note that
8589 -- we can simply ignore the possibility of overflow if the
8590 -- flag is not set (means that overflow cannot happen or
8591 -- that overflow checks are suppressed).
8593 if Ovflo and TestS then
8594 Insert_Action (N,
8595 Make_Raise_Constraint_Error (Loc,
8596 Condition =>
8597 Make_Op_Gt (Loc,
8598 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8599 Right_Opnd => Make_Integer_Literal (Loc, MaxS)),
8600 Reason => CE_Overflow_Check_Failed));
8601 end if;
8603 -- Now rewrite node as Shift_Left (1, right-operand)
8605 Rewrite (N,
8606 Make_Op_Shift_Left (Loc,
8607 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8608 Right_Opnd => Right_Opnd (N)));
8610 -- Modular integer case
8612 else pragma Assert (Is_Modular_Integer_Type (Typ));
8614 -- If shift count can be greater than MaxS, we need to wrap
8615 -- the shift in a test that will reduce the result value to
8616 -- zero if this shift count is exceeded.
8618 if TestS then
8620 -- Note: build node for the comparison first, before we
8621 -- reuse the Right_Opnd, so that we have proper parents
8622 -- in place for the Duplicate_Subexpr call.
8624 Test_Gt :=
8625 Make_Op_Gt (Loc,
8626 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8627 Right_Opnd => Make_Integer_Literal (Loc, MaxS));
8629 Rewrite (N,
8630 Make_If_Expression (Loc,
8631 Expressions => New_List (
8632 Test_Gt,
8633 Make_Integer_Literal (Loc, Uint_0),
8634 Make_Op_Shift_Left (Loc,
8635 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8636 Right_Opnd => Right_Opnd (N)))));
8638 -- If we know shift count cannot be greater than MaxS, then
8639 -- it is safe to just rewrite as a shift with no test.
8641 else
8642 Rewrite (N,
8643 Make_Op_Shift_Left (Loc,
8644 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8645 Right_Opnd => Right_Opnd (N)));
8646 end if;
8647 end if;
8649 Analyze_And_Resolve (N, Typ);
8650 return;
8651 end;
8652 end if;
8653 end if;
8655 -- Fall through if exponentiation must be done using a runtime routine
8657 -- First deal with modular case
8659 if Is_Modular_Integer_Type (Rtyp) then
8661 -- Nonbinary modular case, we call the special exponentiation
8662 -- routine for the nonbinary case, converting the argument to
8663 -- Long_Long_Integer and passing the modulus value. Then the
8664 -- result is converted back to the base type.
8666 if Non_Binary_Modulus (Rtyp) then
8667 Rewrite (N,
8668 Convert_To (Typ,
8669 Make_Function_Call (Loc,
8670 Name =>
8671 New_Occurrence_Of (RTE (RE_Exp_Modular), Loc),
8672 Parameter_Associations => New_List (
8673 Convert_To (RTE (RE_Unsigned), Base),
8674 Make_Integer_Literal (Loc, Modulus (Rtyp)),
8675 Exp))));
8677 -- Binary modular case, in this case, we call one of two routines,
8678 -- either the unsigned integer case, or the unsigned long long
8679 -- integer case, with a final "and" operation to do the required mod.
8681 else
8682 if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
8683 Ent := RTE (RE_Exp_Unsigned);
8684 else
8685 Ent := RTE (RE_Exp_Long_Long_Unsigned);
8686 end if;
8688 Rewrite (N,
8689 Convert_To (Typ,
8690 Make_Op_And (Loc,
8691 Left_Opnd =>
8692 Make_Function_Call (Loc,
8693 Name => New_Occurrence_Of (Ent, Loc),
8694 Parameter_Associations => New_List (
8695 Convert_To (Etype (First_Formal (Ent)), Base),
8696 Exp)),
8697 Right_Opnd =>
8698 Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
8700 end if;
8702 -- Common exit point for modular type case
8704 Analyze_And_Resolve (N, Typ);
8705 return;
8707 -- Signed integer cases, done using either Integer or Long_Long_Integer.
8708 -- It is not worth having routines for Short_[Short_]Integer, since for
8709 -- most machines it would not help, and it would generate more code that
8710 -- might need certification when a certified run time is required.
8712 -- In the integer cases, we have two routines, one for when overflow
8713 -- checks are required, and one when they are not required, since there
8714 -- is a real gain in omitting checks on many machines.
8716 elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
8717 or else (Rtyp = Base_Type (Standard_Long_Integer)
8718 and then
8719 Esize (Standard_Long_Integer) > Esize (Standard_Integer))
8720 or else Rtyp = Universal_Integer
8721 then
8722 Etyp := Standard_Long_Long_Integer;
8724 if Ovflo then
8725 Rent := RE_Exp_Long_Long_Integer;
8726 else
8727 Rent := RE_Exn_Long_Long_Integer;
8728 end if;
8730 elsif Is_Signed_Integer_Type (Rtyp) then
8731 Etyp := Standard_Integer;
8733 if Ovflo then
8734 Rent := RE_Exp_Integer;
8735 else
8736 Rent := RE_Exn_Integer;
8737 end if;
8739 -- Floating-point cases. We do not need separate routines for the
8740 -- overflow case here, since in the case of floating-point, we generate
8741 -- infinities anyway as a rule (either that or we automatically trap
8742 -- overflow), and if there is an infinity generated and a range check
8743 -- is required, the check will fail anyway.
8745 -- Historical note: we used to convert everything to Long_Long_Float
8746 -- and call a single common routine, but this had the undesirable effect
8747 -- of giving different results for small static exponent values and the
8748 -- same dynamic values.
8750 else
8751 pragma Assert (Is_Floating_Point_Type (Rtyp));
8753 if Rtyp = Standard_Float then
8754 Etyp := Standard_Float;
8755 Rent := RE_Exn_Float;
8757 elsif Rtyp = Standard_Long_Float then
8758 Etyp := Standard_Long_Float;
8759 Rent := RE_Exn_Long_Float;
8761 else
8762 Etyp := Standard_Long_Long_Float;
8763 Rent := RE_Exn_Long_Long_Float;
8764 end if;
8765 end if;
8767 -- Common processing for integer cases and floating-point cases.
8768 -- If we are in the right type, we can call runtime routine directly
8770 if Typ = Etyp
8771 and then Rtyp /= Universal_Integer
8772 and then Rtyp /= Universal_Real
8773 then
8774 Rewrite (N,
8775 Wrap_MA (
8776 Make_Function_Call (Loc,
8777 Name => New_Occurrence_Of (RTE (Rent), Loc),
8778 Parameter_Associations => New_List (Base, Exp))));
8780 -- Otherwise we have to introduce conversions (conversions are also
8781 -- required in the universal cases, since the runtime routine is
8782 -- typed using one of the standard types).
8784 else
8785 Rewrite (N,
8786 Convert_To (Typ,
8787 Make_Function_Call (Loc,
8788 Name => New_Occurrence_Of (RTE (Rent), Loc),
8789 Parameter_Associations => New_List (
8790 Convert_To (Etyp, Base),
8791 Exp))));
8792 end if;
8794 Analyze_And_Resolve (N, Typ);
8795 return;
8797 exception
8798 when RE_Not_Available =>
8799 return;
8800 end Expand_N_Op_Expon;
8802 --------------------
8803 -- Expand_N_Op_Ge --
8804 --------------------
8806 procedure Expand_N_Op_Ge (N : Node_Id) is
8807 Typ : constant Entity_Id := Etype (N);
8808 Op1 : constant Node_Id := Left_Opnd (N);
8809 Op2 : constant Node_Id := Right_Opnd (N);
8810 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8812 begin
8813 Binary_Op_Validity_Checks (N);
8815 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8816 -- means we no longer have a comparison operation, we are all done.
8818 Expand_Compare_Minimize_Eliminate_Overflow (N);
8820 if Nkind (N) /= N_Op_Ge then
8821 return;
8822 end if;
8824 -- Array type case
8826 if Is_Array_Type (Typ1) then
8827 Expand_Array_Comparison (N);
8828 return;
8829 end if;
8831 -- Deal with boolean operands
8833 if Is_Boolean_Type (Typ1) then
8834 Adjust_Condition (Op1);
8835 Adjust_Condition (Op2);
8836 Set_Etype (N, Standard_Boolean);
8837 Adjust_Result_Type (N, Typ);
8838 end if;
8840 Rewrite_Comparison (N);
8842 Optimize_Length_Comparison (N);
8843 end Expand_N_Op_Ge;
8845 --------------------
8846 -- Expand_N_Op_Gt --
8847 --------------------
8849 procedure Expand_N_Op_Gt (N : Node_Id) is
8850 Typ : constant Entity_Id := Etype (N);
8851 Op1 : constant Node_Id := Left_Opnd (N);
8852 Op2 : constant Node_Id := Right_Opnd (N);
8853 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8855 begin
8856 Binary_Op_Validity_Checks (N);
8858 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8859 -- means we no longer have a comparison operation, we are all done.
8861 Expand_Compare_Minimize_Eliminate_Overflow (N);
8863 if Nkind (N) /= N_Op_Gt then
8864 return;
8865 end if;
8867 -- Deal with array type operands
8869 if Is_Array_Type (Typ1) then
8870 Expand_Array_Comparison (N);
8871 return;
8872 end if;
8874 -- Deal with boolean type operands
8876 if Is_Boolean_Type (Typ1) then
8877 Adjust_Condition (Op1);
8878 Adjust_Condition (Op2);
8879 Set_Etype (N, Standard_Boolean);
8880 Adjust_Result_Type (N, Typ);
8881 end if;
8883 Rewrite_Comparison (N);
8885 Optimize_Length_Comparison (N);
8886 end Expand_N_Op_Gt;
8888 --------------------
8889 -- Expand_N_Op_Le --
8890 --------------------
8892 procedure Expand_N_Op_Le (N : Node_Id) is
8893 Typ : constant Entity_Id := Etype (N);
8894 Op1 : constant Node_Id := Left_Opnd (N);
8895 Op2 : constant Node_Id := Right_Opnd (N);
8896 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8898 begin
8899 Binary_Op_Validity_Checks (N);
8901 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8902 -- means we no longer have a comparison operation, we are all done.
8904 Expand_Compare_Minimize_Eliminate_Overflow (N);
8906 if Nkind (N) /= N_Op_Le then
8907 return;
8908 end if;
8910 -- Deal with array type operands
8912 if Is_Array_Type (Typ1) then
8913 Expand_Array_Comparison (N);
8914 return;
8915 end if;
8917 -- Deal with Boolean type operands
8919 if Is_Boolean_Type (Typ1) then
8920 Adjust_Condition (Op1);
8921 Adjust_Condition (Op2);
8922 Set_Etype (N, Standard_Boolean);
8923 Adjust_Result_Type (N, Typ);
8924 end if;
8926 Rewrite_Comparison (N);
8928 Optimize_Length_Comparison (N);
8929 end Expand_N_Op_Le;
8931 --------------------
8932 -- Expand_N_Op_Lt --
8933 --------------------
8935 procedure Expand_N_Op_Lt (N : Node_Id) is
8936 Typ : constant Entity_Id := Etype (N);
8937 Op1 : constant Node_Id := Left_Opnd (N);
8938 Op2 : constant Node_Id := Right_Opnd (N);
8939 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8941 begin
8942 Binary_Op_Validity_Checks (N);
8944 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8945 -- means we no longer have a comparison operation, we are all done.
8947 Expand_Compare_Minimize_Eliminate_Overflow (N);
8949 if Nkind (N) /= N_Op_Lt then
8950 return;
8951 end if;
8953 -- Deal with array type operands
8955 if Is_Array_Type (Typ1) then
8956 Expand_Array_Comparison (N);
8957 return;
8958 end if;
8960 -- Deal with Boolean type operands
8962 if Is_Boolean_Type (Typ1) then
8963 Adjust_Condition (Op1);
8964 Adjust_Condition (Op2);
8965 Set_Etype (N, Standard_Boolean);
8966 Adjust_Result_Type (N, Typ);
8967 end if;
8969 Rewrite_Comparison (N);
8971 Optimize_Length_Comparison (N);
8972 end Expand_N_Op_Lt;
8974 -----------------------
8975 -- Expand_N_Op_Minus --
8976 -----------------------
8978 procedure Expand_N_Op_Minus (N : Node_Id) is
8979 Loc : constant Source_Ptr := Sloc (N);
8980 Typ : constant Entity_Id := Etype (N);
8982 begin
8983 Unary_Op_Validity_Checks (N);
8985 -- Check for MINIMIZED/ELIMINATED overflow mode
8987 if Minimized_Eliminated_Overflow_Check (N) then
8988 Apply_Arithmetic_Overflow_Check (N);
8989 return;
8990 end if;
8992 if not Backend_Overflow_Checks_On_Target
8993 and then Is_Signed_Integer_Type (Etype (N))
8994 and then Do_Overflow_Check (N)
8995 then
8996 -- Software overflow checking expands -expr into (0 - expr)
8998 Rewrite (N,
8999 Make_Op_Subtract (Loc,
9000 Left_Opnd => Make_Integer_Literal (Loc, 0),
9001 Right_Opnd => Right_Opnd (N)));
9003 Analyze_And_Resolve (N, Typ);
9004 end if;
9006 Expand_Nonbinary_Modular_Op (N);
9007 end Expand_N_Op_Minus;
9009 ---------------------
9010 -- Expand_N_Op_Mod --
9011 ---------------------
9013 procedure Expand_N_Op_Mod (N : Node_Id) is
9014 Loc : constant Source_Ptr := Sloc (N);
9015 Typ : constant Entity_Id := Etype (N);
9016 DDC : constant Boolean := Do_Division_Check (N);
9018 Left : Node_Id;
9019 Right : Node_Id;
9021 LLB : Uint;
9022 Llo : Uint;
9023 Lhi : Uint;
9024 LOK : Boolean;
9025 Rlo : Uint;
9026 Rhi : Uint;
9027 ROK : Boolean;
9029 pragma Warnings (Off, Lhi);
9031 begin
9032 Binary_Op_Validity_Checks (N);
9034 -- Check for MINIMIZED/ELIMINATED overflow mode
9036 if Minimized_Eliminated_Overflow_Check (N) then
9037 Apply_Arithmetic_Overflow_Check (N);
9038 return;
9039 end if;
9041 if Is_Integer_Type (Etype (N)) then
9042 Apply_Divide_Checks (N);
9044 -- All done if we don't have a MOD any more, which can happen as a
9045 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
9047 if Nkind (N) /= N_Op_Mod then
9048 return;
9049 end if;
9050 end if;
9052 -- Proceed with expansion of mod operator
9054 Left := Left_Opnd (N);
9055 Right := Right_Opnd (N);
9057 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
9058 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
9060 -- Convert mod to rem if operands are both known to be non-negative, or
9061 -- both known to be non-positive (these are the cases in which rem and
9062 -- mod are the same, see (RM 4.5.5(28-30)). We do this since it is quite
9063 -- likely that this will improve the quality of code, (the operation now
9064 -- corresponds to the hardware remainder), and it does not seem likely
9065 -- that it could be harmful. It also avoids some cases of the elaborate
9066 -- expansion in Modify_Tree_For_C mode below (since Ada rem = C %).
9068 if (LOK and ROK)
9069 and then ((Llo >= 0 and then Rlo >= 0)
9070 or else
9071 (Lhi <= 0 and then Rhi <= 0))
9072 then
9073 Rewrite (N,
9074 Make_Op_Rem (Sloc (N),
9075 Left_Opnd => Left_Opnd (N),
9076 Right_Opnd => Right_Opnd (N)));
9078 -- Instead of reanalyzing the node we do the analysis manually. This
9079 -- avoids anomalies when the replacement is done in an instance and
9080 -- is epsilon more efficient.
9082 Set_Entity (N, Standard_Entity (S_Op_Rem));
9083 Set_Etype (N, Typ);
9084 Set_Do_Division_Check (N, DDC);
9085 Expand_N_Op_Rem (N);
9086 Set_Analyzed (N);
9087 return;
9089 -- Otherwise, normal mod processing
9091 else
9092 -- Apply optimization x mod 1 = 0. We don't really need that with
9093 -- gcc, but it is useful with other back ends and is certainly
9094 -- harmless.
9096 if Is_Integer_Type (Etype (N))
9097 and then Compile_Time_Known_Value (Right)
9098 and then Expr_Value (Right) = Uint_1
9099 then
9100 -- Call Remove_Side_Effects to ensure that any side effects in
9101 -- the ignored left operand (in particular function calls to
9102 -- user defined functions) are properly executed.
9104 Remove_Side_Effects (Left);
9106 Rewrite (N, Make_Integer_Literal (Loc, 0));
9107 Analyze_And_Resolve (N, Typ);
9108 return;
9109 end if;
9111 -- If we still have a mod operator and we are in Modify_Tree_For_C
9112 -- mode, and we have a signed integer type, then here is where we do
9113 -- the rewrite in terms of Rem. Note this rewrite bypasses the need
9114 -- for the special handling of the annoying case of largest negative
9115 -- number mod minus one.
9117 if Nkind (N) = N_Op_Mod
9118 and then Is_Signed_Integer_Type (Typ)
9119 and then Modify_Tree_For_C
9120 then
9121 -- In the general case, we expand A mod B as
9123 -- Tnn : constant typ := A rem B;
9124 -- ..
9125 -- (if (A >= 0) = (B >= 0) then Tnn
9126 -- elsif Tnn = 0 then 0
9127 -- else Tnn + B)
9129 -- The comparison can be written simply as A >= 0 if we know that
9130 -- B >= 0 which is a very common case.
9132 -- An important optimization is when B is known at compile time
9133 -- to be 2**K for some constant. In this case we can simply AND
9134 -- the left operand with the bit string 2**K-1 (i.e. K 1-bits)
9135 -- and that works for both the positive and negative cases.
9137 declare
9138 P2 : constant Nat := Power_Of_Two (Right);
9140 begin
9141 if P2 /= 0 then
9142 Rewrite (N,
9143 Unchecked_Convert_To (Typ,
9144 Make_Op_And (Loc,
9145 Left_Opnd =>
9146 Unchecked_Convert_To
9147 (Corresponding_Unsigned_Type (Typ), Left),
9148 Right_Opnd =>
9149 Make_Integer_Literal (Loc, 2 ** P2 - 1))));
9150 Analyze_And_Resolve (N, Typ);
9151 return;
9152 end if;
9153 end;
9155 -- Here for the full rewrite
9157 declare
9158 Tnn : constant Entity_Id := Make_Temporary (Sloc (N), 'T', N);
9159 Cmp : Node_Id;
9161 begin
9162 Cmp :=
9163 Make_Op_Ge (Loc,
9164 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
9165 Right_Opnd => Make_Integer_Literal (Loc, 0));
9167 if not LOK or else Rlo < 0 then
9168 Cmp :=
9169 Make_Op_Eq (Loc,
9170 Left_Opnd => Cmp,
9171 Right_Opnd =>
9172 Make_Op_Ge (Loc,
9173 Left_Opnd => Duplicate_Subexpr_No_Checks (Right),
9174 Right_Opnd => Make_Integer_Literal (Loc, 0)));
9175 end if;
9177 Insert_Action (N,
9178 Make_Object_Declaration (Loc,
9179 Defining_Identifier => Tnn,
9180 Constant_Present => True,
9181 Object_Definition => New_Occurrence_Of (Typ, Loc),
9182 Expression =>
9183 Make_Op_Rem (Loc,
9184 Left_Opnd => Left,
9185 Right_Opnd => Right)));
9187 Rewrite (N,
9188 Make_If_Expression (Loc,
9189 Expressions => New_List (
9190 Cmp,
9191 New_Occurrence_Of (Tnn, Loc),
9192 Make_If_Expression (Loc,
9193 Is_Elsif => True,
9194 Expressions => New_List (
9195 Make_Op_Eq (Loc,
9196 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
9197 Right_Opnd => Make_Integer_Literal (Loc, 0)),
9198 Make_Integer_Literal (Loc, 0),
9199 Make_Op_Add (Loc,
9200 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
9201 Right_Opnd =>
9202 Duplicate_Subexpr_No_Checks (Right)))))));
9204 Analyze_And_Resolve (N, Typ);
9205 return;
9206 end;
9207 end if;
9209 -- Deal with annoying case of largest negative number mod minus one.
9210 -- Gigi may not handle this case correctly, because on some targets,
9211 -- the mod value is computed using a divide instruction which gives
9212 -- an overflow trap for this case.
9214 -- It would be a bit more efficient to figure out which targets
9215 -- this is really needed for, but in practice it is reasonable
9216 -- to do the following special check in all cases, since it means
9217 -- we get a clearer message, and also the overhead is minimal given
9218 -- that division is expensive in any case.
9220 -- In fact the check is quite easy, if the right operand is -1, then
9221 -- the mod value is always 0, and we can just ignore the left operand
9222 -- completely in this case.
9224 -- This only applies if we still have a mod operator. Skip if we
9225 -- have already rewritten this (e.g. in the case of eliminated
9226 -- overflow checks which have driven us into bignum mode).
9228 if Nkind (N) = N_Op_Mod then
9230 -- The operand type may be private (e.g. in the expansion of an
9231 -- intrinsic operation) so we must use the underlying type to get
9232 -- the bounds, and convert the literals explicitly.
9234 LLB :=
9235 Expr_Value
9236 (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
9238 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
9239 and then ((not LOK) or else (Llo = LLB))
9240 then
9241 Rewrite (N,
9242 Make_If_Expression (Loc,
9243 Expressions => New_List (
9244 Make_Op_Eq (Loc,
9245 Left_Opnd => Duplicate_Subexpr (Right),
9246 Right_Opnd =>
9247 Unchecked_Convert_To (Typ,
9248 Make_Integer_Literal (Loc, -1))),
9249 Unchecked_Convert_To (Typ,
9250 Make_Integer_Literal (Loc, Uint_0)),
9251 Relocate_Node (N))));
9253 Set_Analyzed (Next (Next (First (Expressions (N)))));
9254 Analyze_And_Resolve (N, Typ);
9255 end if;
9256 end if;
9257 end if;
9258 end Expand_N_Op_Mod;
9260 --------------------------
9261 -- Expand_N_Op_Multiply --
9262 --------------------------
9264 procedure Expand_N_Op_Multiply (N : Node_Id) is
9265 Loc : constant Source_Ptr := Sloc (N);
9266 Lop : constant Node_Id := Left_Opnd (N);
9267 Rop : constant Node_Id := Right_Opnd (N);
9269 Lp2 : constant Boolean :=
9270 Nkind (Lop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Lop);
9271 Rp2 : constant Boolean :=
9272 Nkind (Rop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Rop);
9274 Ltyp : constant Entity_Id := Etype (Lop);
9275 Rtyp : constant Entity_Id := Etype (Rop);
9276 Typ : Entity_Id := Etype (N);
9278 begin
9279 Binary_Op_Validity_Checks (N);
9281 -- Check for MINIMIZED/ELIMINATED overflow mode
9283 if Minimized_Eliminated_Overflow_Check (N) then
9284 Apply_Arithmetic_Overflow_Check (N);
9285 return;
9286 end if;
9288 -- Special optimizations for integer types
9290 if Is_Integer_Type (Typ) then
9292 -- N * 0 = 0 for integer types
9294 if Compile_Time_Known_Value (Rop)
9295 and then Expr_Value (Rop) = Uint_0
9296 then
9297 -- Call Remove_Side_Effects to ensure that any side effects in
9298 -- the ignored left operand (in particular function calls to
9299 -- user defined functions) are properly executed.
9301 Remove_Side_Effects (Lop);
9303 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
9304 Analyze_And_Resolve (N, Typ);
9305 return;
9306 end if;
9308 -- Similar handling for 0 * N = 0
9310 if Compile_Time_Known_Value (Lop)
9311 and then Expr_Value (Lop) = Uint_0
9312 then
9313 Remove_Side_Effects (Rop);
9314 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
9315 Analyze_And_Resolve (N, Typ);
9316 return;
9317 end if;
9319 -- N * 1 = 1 * N = N for integer types
9321 -- This optimisation is not done if we are going to
9322 -- rewrite the product 1 * 2 ** N to a shift.
9324 if Compile_Time_Known_Value (Rop)
9325 and then Expr_Value (Rop) = Uint_1
9326 and then not Lp2
9327 then
9328 Rewrite (N, Lop);
9329 return;
9331 elsif Compile_Time_Known_Value (Lop)
9332 and then Expr_Value (Lop) = Uint_1
9333 and then not Rp2
9334 then
9335 Rewrite (N, Rop);
9336 return;
9337 end if;
9338 end if;
9340 -- Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
9341 -- Is_Power_Of_2_For_Shift is set means that we know that our left
9342 -- operand is an integer, as required for this to work.
9344 if Rp2 then
9345 if Lp2 then
9347 -- Convert 2 ** A * 2 ** B into 2 ** (A + B)
9349 Rewrite (N,
9350 Make_Op_Expon (Loc,
9351 Left_Opnd => Make_Integer_Literal (Loc, 2),
9352 Right_Opnd =>
9353 Make_Op_Add (Loc,
9354 Left_Opnd => Right_Opnd (Lop),
9355 Right_Opnd => Right_Opnd (Rop))));
9356 Analyze_And_Resolve (N, Typ);
9357 return;
9359 else
9360 -- If the result is modular, perform the reduction of the result
9361 -- appropriately.
9363 if Is_Modular_Integer_Type (Typ)
9364 and then not Non_Binary_Modulus (Typ)
9365 then
9366 Rewrite (N,
9367 Make_Op_And (Loc,
9368 Left_Opnd =>
9369 Make_Op_Shift_Left (Loc,
9370 Left_Opnd => Lop,
9371 Right_Opnd =>
9372 Convert_To (Standard_Natural, Right_Opnd (Rop))),
9373 Right_Opnd =>
9374 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9376 else
9377 Rewrite (N,
9378 Make_Op_Shift_Left (Loc,
9379 Left_Opnd => Lop,
9380 Right_Opnd =>
9381 Convert_To (Standard_Natural, Right_Opnd (Rop))));
9382 end if;
9384 Analyze_And_Resolve (N, Typ);
9385 return;
9386 end if;
9388 -- Same processing for the operands the other way round
9390 elsif Lp2 then
9391 if Is_Modular_Integer_Type (Typ)
9392 and then not Non_Binary_Modulus (Typ)
9393 then
9394 Rewrite (N,
9395 Make_Op_And (Loc,
9396 Left_Opnd =>
9397 Make_Op_Shift_Left (Loc,
9398 Left_Opnd => Rop,
9399 Right_Opnd =>
9400 Convert_To (Standard_Natural, Right_Opnd (Lop))),
9401 Right_Opnd =>
9402 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9404 else
9405 Rewrite (N,
9406 Make_Op_Shift_Left (Loc,
9407 Left_Opnd => Rop,
9408 Right_Opnd =>
9409 Convert_To (Standard_Natural, Right_Opnd (Lop))));
9410 end if;
9412 Analyze_And_Resolve (N, Typ);
9413 return;
9414 end if;
9416 -- Do required fixup of universal fixed operation
9418 if Typ = Universal_Fixed then
9419 Fixup_Universal_Fixed_Operation (N);
9420 Typ := Etype (N);
9421 end if;
9423 -- Multiplications with fixed-point results
9425 if Is_Fixed_Point_Type (Typ) then
9427 -- No special processing if Treat_Fixed_As_Integer is set, since from
9428 -- a semantic point of view such operations are simply integer
9429 -- operations and will be treated that way.
9431 if not Treat_Fixed_As_Integer (N) then
9433 -- Case of fixed * integer => fixed
9435 if Is_Integer_Type (Rtyp) then
9436 Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
9438 -- Case of integer * fixed => fixed
9440 elsif Is_Integer_Type (Ltyp) then
9441 Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
9443 -- Case of fixed * fixed => fixed
9445 else
9446 Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
9447 end if;
9448 end if;
9450 -- Other cases of multiplication of fixed-point operands. Again we
9451 -- exclude the cases where Treat_Fixed_As_Integer flag is set.
9453 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
9454 and then not Treat_Fixed_As_Integer (N)
9455 then
9456 if Is_Integer_Type (Typ) then
9457 Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
9458 else
9459 pragma Assert (Is_Floating_Point_Type (Typ));
9460 Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
9461 end if;
9463 -- Mixed-mode operations can appear in a non-static universal context,
9464 -- in which case the integer argument must be converted explicitly.
9466 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
9467 Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
9468 Analyze_And_Resolve (Rop, Universal_Real);
9470 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
9471 Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
9472 Analyze_And_Resolve (Lop, Universal_Real);
9474 -- Non-fixed point cases, check software overflow checking required
9476 elsif Is_Signed_Integer_Type (Etype (N)) then
9477 Apply_Arithmetic_Overflow_Check (N);
9478 end if;
9480 -- Overflow checks for floating-point if -gnateF mode active
9482 Check_Float_Op_Overflow (N);
9484 Expand_Nonbinary_Modular_Op (N);
9485 end Expand_N_Op_Multiply;
9487 --------------------
9488 -- Expand_N_Op_Ne --
9489 --------------------
9491 procedure Expand_N_Op_Ne (N : Node_Id) is
9492 Typ : constant Entity_Id := Etype (Left_Opnd (N));
9494 begin
9495 -- Case of elementary type with standard operator
9497 if Is_Elementary_Type (Typ)
9498 and then Sloc (Entity (N)) = Standard_Location
9499 then
9500 Binary_Op_Validity_Checks (N);
9502 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if
9503 -- means we no longer have a /= operation, we are all done.
9505 Expand_Compare_Minimize_Eliminate_Overflow (N);
9507 if Nkind (N) /= N_Op_Ne then
9508 return;
9509 end if;
9511 -- Boolean types (requiring handling of non-standard case)
9513 if Is_Boolean_Type (Typ) then
9514 Adjust_Condition (Left_Opnd (N));
9515 Adjust_Condition (Right_Opnd (N));
9516 Set_Etype (N, Standard_Boolean);
9517 Adjust_Result_Type (N, Typ);
9518 end if;
9520 Rewrite_Comparison (N);
9522 -- For all cases other than elementary types, we rewrite node as the
9523 -- negation of an equality operation, and reanalyze. The equality to be
9524 -- used is defined in the same scope and has the same signature. This
9525 -- signature must be set explicitly since in an instance it may not have
9526 -- the same visibility as in the generic unit. This avoids duplicating
9527 -- or factoring the complex code for record/array equality tests etc.
9529 -- This case is also used for the minimal expansion performed in
9530 -- GNATprove mode.
9532 else
9533 declare
9534 Loc : constant Source_Ptr := Sloc (N);
9535 Neg : Node_Id;
9536 Ne : constant Entity_Id := Entity (N);
9538 begin
9539 Binary_Op_Validity_Checks (N);
9541 Neg :=
9542 Make_Op_Not (Loc,
9543 Right_Opnd =>
9544 Make_Op_Eq (Loc,
9545 Left_Opnd => Left_Opnd (N),
9546 Right_Opnd => Right_Opnd (N)));
9548 -- The level of parentheses is useless in GNATprove mode, and
9549 -- bumping its level here leads to wrong columns being used in
9550 -- check messages, hence skip it in this mode.
9552 if not GNATprove_Mode then
9553 Set_Paren_Count (Right_Opnd (Neg), 1);
9554 end if;
9556 if Scope (Ne) /= Standard_Standard then
9557 Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
9558 end if;
9560 -- For navigation purposes, we want to treat the inequality as an
9561 -- implicit reference to the corresponding equality. Preserve the
9562 -- Comes_From_ source flag to generate proper Xref entries.
9564 Preserve_Comes_From_Source (Neg, N);
9565 Preserve_Comes_From_Source (Right_Opnd (Neg), N);
9566 Rewrite (N, Neg);
9567 Analyze_And_Resolve (N, Standard_Boolean);
9568 end;
9569 end if;
9571 -- No need for optimization in GNATprove mode, where we would rather see
9572 -- the original source expression.
9574 if not GNATprove_Mode then
9575 Optimize_Length_Comparison (N);
9576 end if;
9577 end Expand_N_Op_Ne;
9579 ---------------------
9580 -- Expand_N_Op_Not --
9581 ---------------------
9583 -- If the argument is other than a Boolean array type, there is no special
9584 -- expansion required, except for dealing with validity checks, and non-
9585 -- standard boolean representations.
9587 -- For the packed array case, we call the special routine in Exp_Pakd,
9588 -- except that if the component size is greater than one, we use the
9589 -- standard routine generating a gruesome loop (it is so peculiar to have
9590 -- packed arrays with non-standard Boolean representations anyway, so it
9591 -- does not matter that we do not handle this case efficiently).
9593 -- For the unpacked array case (and for the special packed case where we
9594 -- have non standard Booleans, as discussed above), we generate and insert
9595 -- into the tree the following function definition:
9597 -- function Nnnn (A : arr) is
9598 -- B : arr;
9599 -- begin
9600 -- for J in a'range loop
9601 -- B (J) := not A (J);
9602 -- end loop;
9603 -- return B;
9604 -- end Nnnn;
9606 -- Here arr is the actual subtype of the parameter (and hence always
9607 -- constrained). Then we replace the not with a call to this function.
9609 procedure Expand_N_Op_Not (N : Node_Id) is
9610 Loc : constant Source_Ptr := Sloc (N);
9611 Typ : constant Entity_Id := Etype (N);
9612 Opnd : Node_Id;
9613 Arr : Entity_Id;
9614 A : Entity_Id;
9615 B : Entity_Id;
9616 J : Entity_Id;
9617 A_J : Node_Id;
9618 B_J : Node_Id;
9620 Func_Name : Entity_Id;
9621 Loop_Statement : Node_Id;
9623 begin
9624 Unary_Op_Validity_Checks (N);
9626 -- For boolean operand, deal with non-standard booleans
9628 if Is_Boolean_Type (Typ) then
9629 Adjust_Condition (Right_Opnd (N));
9630 Set_Etype (N, Standard_Boolean);
9631 Adjust_Result_Type (N, Typ);
9632 return;
9633 end if;
9635 -- Only array types need any other processing
9637 if not Is_Array_Type (Typ) then
9638 return;
9639 end if;
9641 -- Case of array operand. If bit packed with a component size of 1,
9642 -- handle it in Exp_Pakd if the operand is known to be aligned.
9644 if Is_Bit_Packed_Array (Typ)
9645 and then Component_Size (Typ) = 1
9646 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
9647 then
9648 Expand_Packed_Not (N);
9649 return;
9650 end if;
9652 -- Case of array operand which is not bit-packed. If the context is
9653 -- a safe assignment, call in-place operation, If context is a larger
9654 -- boolean expression in the context of a safe assignment, expansion is
9655 -- done by enclosing operation.
9657 Opnd := Relocate_Node (Right_Opnd (N));
9658 Convert_To_Actual_Subtype (Opnd);
9659 Arr := Etype (Opnd);
9660 Ensure_Defined (Arr, N);
9661 Silly_Boolean_Array_Not_Test (N, Arr);
9663 if Nkind (Parent (N)) = N_Assignment_Statement then
9664 if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
9665 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9666 return;
9668 -- Special case the negation of a binary operation
9670 elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
9671 and then Safe_In_Place_Array_Op
9672 (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
9673 then
9674 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9675 return;
9676 end if;
9678 elsif Nkind (Parent (N)) in N_Binary_Op
9679 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
9680 then
9681 declare
9682 Op1 : constant Node_Id := Left_Opnd (Parent (N));
9683 Op2 : constant Node_Id := Right_Opnd (Parent (N));
9684 Lhs : constant Node_Id := Name (Parent (Parent (N)));
9686 begin
9687 if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
9689 -- (not A) op (not B) can be reduced to a single call
9691 if N = Op1 and then Nkind (Op2) = N_Op_Not then
9692 return;
9694 elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
9695 return;
9697 -- A xor (not B) can also be special-cased
9699 elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
9700 return;
9701 end if;
9702 end if;
9703 end;
9704 end if;
9706 A := Make_Defining_Identifier (Loc, Name_uA);
9707 B := Make_Defining_Identifier (Loc, Name_uB);
9708 J := Make_Defining_Identifier (Loc, Name_uJ);
9710 A_J :=
9711 Make_Indexed_Component (Loc,
9712 Prefix => New_Occurrence_Of (A, Loc),
9713 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9715 B_J :=
9716 Make_Indexed_Component (Loc,
9717 Prefix => New_Occurrence_Of (B, Loc),
9718 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9720 Loop_Statement :=
9721 Make_Implicit_Loop_Statement (N,
9722 Identifier => Empty,
9724 Iteration_Scheme =>
9725 Make_Iteration_Scheme (Loc,
9726 Loop_Parameter_Specification =>
9727 Make_Loop_Parameter_Specification (Loc,
9728 Defining_Identifier => J,
9729 Discrete_Subtype_Definition =>
9730 Make_Attribute_Reference (Loc,
9731 Prefix => Make_Identifier (Loc, Chars (A)),
9732 Attribute_Name => Name_Range))),
9734 Statements => New_List (
9735 Make_Assignment_Statement (Loc,
9736 Name => B_J,
9737 Expression => Make_Op_Not (Loc, A_J))));
9739 Func_Name := Make_Temporary (Loc, 'N');
9740 Set_Is_Inlined (Func_Name);
9742 Insert_Action (N,
9743 Make_Subprogram_Body (Loc,
9744 Specification =>
9745 Make_Function_Specification (Loc,
9746 Defining_Unit_Name => Func_Name,
9747 Parameter_Specifications => New_List (
9748 Make_Parameter_Specification (Loc,
9749 Defining_Identifier => A,
9750 Parameter_Type => New_Occurrence_Of (Typ, Loc))),
9751 Result_Definition => New_Occurrence_Of (Typ, Loc)),
9753 Declarations => New_List (
9754 Make_Object_Declaration (Loc,
9755 Defining_Identifier => B,
9756 Object_Definition => New_Occurrence_Of (Arr, Loc))),
9758 Handled_Statement_Sequence =>
9759 Make_Handled_Sequence_Of_Statements (Loc,
9760 Statements => New_List (
9761 Loop_Statement,
9762 Make_Simple_Return_Statement (Loc,
9763 Expression => Make_Identifier (Loc, Chars (B)))))));
9765 Rewrite (N,
9766 Make_Function_Call (Loc,
9767 Name => New_Occurrence_Of (Func_Name, Loc),
9768 Parameter_Associations => New_List (Opnd)));
9770 Analyze_And_Resolve (N, Typ);
9771 end Expand_N_Op_Not;
9773 --------------------
9774 -- Expand_N_Op_Or --
9775 --------------------
9777 procedure Expand_N_Op_Or (N : Node_Id) is
9778 Typ : constant Entity_Id := Etype (N);
9780 begin
9781 Binary_Op_Validity_Checks (N);
9783 if Is_Array_Type (Etype (N)) then
9784 Expand_Boolean_Operator (N);
9786 elsif Is_Boolean_Type (Etype (N)) then
9787 Adjust_Condition (Left_Opnd (N));
9788 Adjust_Condition (Right_Opnd (N));
9789 Set_Etype (N, Standard_Boolean);
9790 Adjust_Result_Type (N, Typ);
9792 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9793 Expand_Intrinsic_Call (N, Entity (N));
9794 end if;
9796 Expand_Nonbinary_Modular_Op (N);
9797 end Expand_N_Op_Or;
9799 ----------------------
9800 -- Expand_N_Op_Plus --
9801 ----------------------
9803 procedure Expand_N_Op_Plus (N : Node_Id) is
9804 begin
9805 Unary_Op_Validity_Checks (N);
9807 -- Check for MINIMIZED/ELIMINATED overflow mode
9809 if Minimized_Eliminated_Overflow_Check (N) then
9810 Apply_Arithmetic_Overflow_Check (N);
9811 return;
9812 end if;
9813 end Expand_N_Op_Plus;
9815 ---------------------
9816 -- Expand_N_Op_Rem --
9817 ---------------------
9819 procedure Expand_N_Op_Rem (N : Node_Id) is
9820 Loc : constant Source_Ptr := Sloc (N);
9821 Typ : constant Entity_Id := Etype (N);
9823 Left : Node_Id;
9824 Right : Node_Id;
9826 Lo : Uint;
9827 Hi : Uint;
9828 OK : Boolean;
9830 Lneg : Boolean;
9831 Rneg : Boolean;
9832 -- Set if corresponding operand can be negative
9834 pragma Unreferenced (Hi);
9836 begin
9837 Binary_Op_Validity_Checks (N);
9839 -- Check for MINIMIZED/ELIMINATED overflow mode
9841 if Minimized_Eliminated_Overflow_Check (N) then
9842 Apply_Arithmetic_Overflow_Check (N);
9843 return;
9844 end if;
9846 if Is_Integer_Type (Etype (N)) then
9847 Apply_Divide_Checks (N);
9849 -- All done if we don't have a REM any more, which can happen as a
9850 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
9852 if Nkind (N) /= N_Op_Rem then
9853 return;
9854 end if;
9855 end if;
9857 -- Proceed with expansion of REM
9859 Left := Left_Opnd (N);
9860 Right := Right_Opnd (N);
9862 -- Apply optimization x rem 1 = 0. We don't really need that with gcc,
9863 -- but it is useful with other back ends, and is certainly harmless.
9865 if Is_Integer_Type (Etype (N))
9866 and then Compile_Time_Known_Value (Right)
9867 and then Expr_Value (Right) = Uint_1
9868 then
9869 -- Call Remove_Side_Effects to ensure that any side effects in the
9870 -- ignored left operand (in particular function calls to user defined
9871 -- functions) are properly executed.
9873 Remove_Side_Effects (Left);
9875 Rewrite (N, Make_Integer_Literal (Loc, 0));
9876 Analyze_And_Resolve (N, Typ);
9877 return;
9878 end if;
9880 -- Deal with annoying case of largest negative number remainder minus
9881 -- one. Gigi may not handle this case correctly, because on some
9882 -- targets, the mod value is computed using a divide instruction
9883 -- which gives an overflow trap for this case.
9885 -- It would be a bit more efficient to figure out which targets this
9886 -- is really needed for, but in practice it is reasonable to do the
9887 -- following special check in all cases, since it means we get a clearer
9888 -- message, and also the overhead is minimal given that division is
9889 -- expensive in any case.
9891 -- In fact the check is quite easy, if the right operand is -1, then
9892 -- the remainder is always 0, and we can just ignore the left operand
9893 -- completely in this case.
9895 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9896 Lneg := (not OK) or else Lo < 0;
9898 Determine_Range (Left, OK, Lo, Hi, Assume_Valid => True);
9899 Rneg := (not OK) or else Lo < 0;
9901 -- We won't mess with trying to find out if the left operand can really
9902 -- be the largest negative number (that's a pain in the case of private
9903 -- types and this is really marginal). We will just assume that we need
9904 -- the test if the left operand can be negative at all.
9906 if Lneg and Rneg then
9907 Rewrite (N,
9908 Make_If_Expression (Loc,
9909 Expressions => New_List (
9910 Make_Op_Eq (Loc,
9911 Left_Opnd => Duplicate_Subexpr (Right),
9912 Right_Opnd =>
9913 Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
9915 Unchecked_Convert_To (Typ,
9916 Make_Integer_Literal (Loc, Uint_0)),
9918 Relocate_Node (N))));
9920 Set_Analyzed (Next (Next (First (Expressions (N)))));
9921 Analyze_And_Resolve (N, Typ);
9922 end if;
9923 end Expand_N_Op_Rem;
9925 -----------------------------
9926 -- Expand_N_Op_Rotate_Left --
9927 -----------------------------
9929 procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
9930 begin
9931 Binary_Op_Validity_Checks (N);
9933 -- If we are in Modify_Tree_For_C mode, there is no rotate left in C,
9934 -- so we rewrite in terms of logical shifts
9936 -- Shift_Left (Num, Bits) or Shift_Right (num, Esize - Bits)
9938 -- where Bits is the shift count mod Esize (the mod operation here
9939 -- deals with ludicrous large shift counts, which are apparently OK).
9941 -- What about nonbinary modulus ???
9943 declare
9944 Loc : constant Source_Ptr := Sloc (N);
9945 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9946 Typ : constant Entity_Id := Etype (N);
9948 begin
9949 if Modify_Tree_For_C then
9950 Rewrite (Right_Opnd (N),
9951 Make_Op_Rem (Loc,
9952 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9953 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9955 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9957 Rewrite (N,
9958 Make_Op_Or (Loc,
9959 Left_Opnd =>
9960 Make_Op_Shift_Left (Loc,
9961 Left_Opnd => Left_Opnd (N),
9962 Right_Opnd => Right_Opnd (N)),
9964 Right_Opnd =>
9965 Make_Op_Shift_Right (Loc,
9966 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9967 Right_Opnd =>
9968 Make_Op_Subtract (Loc,
9969 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9970 Right_Opnd =>
9971 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9973 Analyze_And_Resolve (N, Typ);
9974 end if;
9975 end;
9976 end Expand_N_Op_Rotate_Left;
9978 ------------------------------
9979 -- Expand_N_Op_Rotate_Right --
9980 ------------------------------
9982 procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
9983 begin
9984 Binary_Op_Validity_Checks (N);
9986 -- If we are in Modify_Tree_For_C mode, there is no rotate right in C,
9987 -- so we rewrite in terms of logical shifts
9989 -- Shift_Right (Num, Bits) or Shift_Left (num, Esize - Bits)
9991 -- where Bits is the shift count mod Esize (the mod operation here
9992 -- deals with ludicrous large shift counts, which are apparently OK).
9994 -- What about nonbinary modulus ???
9996 declare
9997 Loc : constant Source_Ptr := Sloc (N);
9998 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9999 Typ : constant Entity_Id := Etype (N);
10001 begin
10002 Rewrite (Right_Opnd (N),
10003 Make_Op_Rem (Loc,
10004 Left_Opnd => Relocate_Node (Right_Opnd (N)),
10005 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
10007 Analyze_And_Resolve (Right_Opnd (N), Rtp);
10009 if Modify_Tree_For_C then
10010 Rewrite (N,
10011 Make_Op_Or (Loc,
10012 Left_Opnd =>
10013 Make_Op_Shift_Right (Loc,
10014 Left_Opnd => Left_Opnd (N),
10015 Right_Opnd => Right_Opnd (N)),
10017 Right_Opnd =>
10018 Make_Op_Shift_Left (Loc,
10019 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
10020 Right_Opnd =>
10021 Make_Op_Subtract (Loc,
10022 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
10023 Right_Opnd =>
10024 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
10026 Analyze_And_Resolve (N, Typ);
10027 end if;
10028 end;
10029 end Expand_N_Op_Rotate_Right;
10031 ----------------------------
10032 -- Expand_N_Op_Shift_Left --
10033 ----------------------------
10035 -- Note: nothing in this routine depends on left as opposed to right shifts
10036 -- so we share the routine for expanding shift right operations.
10038 procedure Expand_N_Op_Shift_Left (N : Node_Id) is
10039 begin
10040 Binary_Op_Validity_Checks (N);
10042 -- If we are in Modify_Tree_For_C mode, then ensure that the right
10043 -- operand is not greater than the word size (since that would not
10044 -- be defined properly by the corresponding C shift operator).
10046 if Modify_Tree_For_C then
10047 declare
10048 Right : constant Node_Id := Right_Opnd (N);
10049 Loc : constant Source_Ptr := Sloc (Right);
10050 Typ : constant Entity_Id := Etype (N);
10051 Siz : constant Uint := Esize (Typ);
10052 Orig : Node_Id;
10053 OK : Boolean;
10054 Lo : Uint;
10055 Hi : Uint;
10057 begin
10058 if Compile_Time_Known_Value (Right) then
10059 if Expr_Value (Right) >= Siz then
10060 Rewrite (N, Make_Integer_Literal (Loc, 0));
10061 Analyze_And_Resolve (N, Typ);
10062 end if;
10064 -- Not compile time known, find range
10066 else
10067 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
10069 -- Nothing to do if known to be OK range, otherwise expand
10071 if not OK or else Hi >= Siz then
10073 -- Prevent recursion on copy of shift node
10075 Orig := Relocate_Node (N);
10076 Set_Analyzed (Orig);
10078 -- Now do the rewrite
10080 Rewrite (N,
10081 Make_If_Expression (Loc,
10082 Expressions => New_List (
10083 Make_Op_Ge (Loc,
10084 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
10085 Right_Opnd => Make_Integer_Literal (Loc, Siz)),
10086 Make_Integer_Literal (Loc, 0),
10087 Orig)));
10088 Analyze_And_Resolve (N, Typ);
10089 end if;
10090 end if;
10091 end;
10092 end if;
10093 end Expand_N_Op_Shift_Left;
10095 -----------------------------
10096 -- Expand_N_Op_Shift_Right --
10097 -----------------------------
10099 procedure Expand_N_Op_Shift_Right (N : Node_Id) is
10100 begin
10101 -- Share shift left circuit
10103 Expand_N_Op_Shift_Left (N);
10104 end Expand_N_Op_Shift_Right;
10106 ----------------------------------------
10107 -- Expand_N_Op_Shift_Right_Arithmetic --
10108 ----------------------------------------
10110 procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
10111 begin
10112 Binary_Op_Validity_Checks (N);
10114 -- If we are in Modify_Tree_For_C mode, there is no shift right
10115 -- arithmetic in C, so we rewrite in terms of logical shifts.
10117 -- Shift_Right (Num, Bits) or
10118 -- (if Num >= Sign
10119 -- then not (Shift_Right (Mask, bits))
10120 -- else 0)
10122 -- Here Mask is all 1 bits (2**size - 1), and Sign is 2**(size - 1)
10124 -- Note: in almost all C compilers it would work to just shift a
10125 -- signed integer right, but it's undefined and we cannot rely on it.
10127 -- Note: the above works fine for shift counts greater than or equal
10128 -- to the word size, since in this case (not (Shift_Right (Mask, bits)))
10129 -- generates all 1'bits.
10131 -- What about nonbinary modulus ???
10133 declare
10134 Loc : constant Source_Ptr := Sloc (N);
10135 Typ : constant Entity_Id := Etype (N);
10136 Sign : constant Uint := 2 ** (Esize (Typ) - 1);
10137 Mask : constant Uint := (2 ** Esize (Typ)) - 1;
10138 Left : constant Node_Id := Left_Opnd (N);
10139 Right : constant Node_Id := Right_Opnd (N);
10140 Maskx : Node_Id;
10142 begin
10143 if Modify_Tree_For_C then
10145 -- Here if not (Shift_Right (Mask, bits)) can be computed at
10146 -- compile time as a single constant.
10148 if Compile_Time_Known_Value (Right) then
10149 declare
10150 Val : constant Uint := Expr_Value (Right);
10152 begin
10153 if Val >= Esize (Typ) then
10154 Maskx := Make_Integer_Literal (Loc, Mask);
10156 else
10157 Maskx :=
10158 Make_Integer_Literal (Loc,
10159 Intval => Mask - (Mask / (2 ** Expr_Value (Right))));
10160 end if;
10161 end;
10163 else
10164 Maskx :=
10165 Make_Op_Not (Loc,
10166 Right_Opnd =>
10167 Make_Op_Shift_Right (Loc,
10168 Left_Opnd => Make_Integer_Literal (Loc, Mask),
10169 Right_Opnd => Duplicate_Subexpr_No_Checks (Right)));
10170 end if;
10172 -- Now do the rewrite
10174 Rewrite (N,
10175 Make_Op_Or (Loc,
10176 Left_Opnd =>
10177 Make_Op_Shift_Right (Loc,
10178 Left_Opnd => Left,
10179 Right_Opnd => Right),
10180 Right_Opnd =>
10181 Make_If_Expression (Loc,
10182 Expressions => New_List (
10183 Make_Op_Ge (Loc,
10184 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
10185 Right_Opnd => Make_Integer_Literal (Loc, Sign)),
10186 Maskx,
10187 Make_Integer_Literal (Loc, 0)))));
10188 Analyze_And_Resolve (N, Typ);
10189 end if;
10190 end;
10191 end Expand_N_Op_Shift_Right_Arithmetic;
10193 --------------------------
10194 -- Expand_N_Op_Subtract --
10195 --------------------------
10197 procedure Expand_N_Op_Subtract (N : Node_Id) is
10198 Typ : constant Entity_Id := Etype (N);
10200 begin
10201 Binary_Op_Validity_Checks (N);
10203 -- Check for MINIMIZED/ELIMINATED overflow mode
10205 if Minimized_Eliminated_Overflow_Check (N) then
10206 Apply_Arithmetic_Overflow_Check (N);
10207 return;
10208 end if;
10210 -- N - 0 = N for integer types
10212 if Is_Integer_Type (Typ)
10213 and then Compile_Time_Known_Value (Right_Opnd (N))
10214 and then Expr_Value (Right_Opnd (N)) = 0
10215 then
10216 Rewrite (N, Left_Opnd (N));
10217 return;
10218 end if;
10220 -- Arithmetic overflow checks for signed integer/fixed point types
10222 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
10223 Apply_Arithmetic_Overflow_Check (N);
10224 end if;
10226 -- Overflow checks for floating-point if -gnateF mode active
10228 Check_Float_Op_Overflow (N);
10230 Expand_Nonbinary_Modular_Op (N);
10231 end Expand_N_Op_Subtract;
10233 ---------------------
10234 -- Expand_N_Op_Xor --
10235 ---------------------
10237 procedure Expand_N_Op_Xor (N : Node_Id) is
10238 Typ : constant Entity_Id := Etype (N);
10240 begin
10241 Binary_Op_Validity_Checks (N);
10243 if Is_Array_Type (Etype (N)) then
10244 Expand_Boolean_Operator (N);
10246 elsif Is_Boolean_Type (Etype (N)) then
10247 Adjust_Condition (Left_Opnd (N));
10248 Adjust_Condition (Right_Opnd (N));
10249 Set_Etype (N, Standard_Boolean);
10250 Adjust_Result_Type (N, Typ);
10252 elsif Is_Intrinsic_Subprogram (Entity (N)) then
10253 Expand_Intrinsic_Call (N, Entity (N));
10254 end if;
10256 Expand_Nonbinary_Modular_Op (N);
10257 end Expand_N_Op_Xor;
10259 ----------------------
10260 -- Expand_N_Or_Else --
10261 ----------------------
10263 procedure Expand_N_Or_Else (N : Node_Id)
10264 renames Expand_Short_Circuit_Operator;
10266 -----------------------------------
10267 -- Expand_N_Qualified_Expression --
10268 -----------------------------------
10270 procedure Expand_N_Qualified_Expression (N : Node_Id) is
10271 Operand : constant Node_Id := Expression (N);
10272 Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
10274 begin
10275 -- Do validity check if validity checking operands
10277 if Validity_Checks_On and Validity_Check_Operands then
10278 Ensure_Valid (Operand);
10279 end if;
10281 -- Apply possible constraint check
10283 Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
10285 if Do_Range_Check (Operand) then
10286 Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
10287 end if;
10288 end Expand_N_Qualified_Expression;
10290 ------------------------------------
10291 -- Expand_N_Quantified_Expression --
10292 ------------------------------------
10294 -- We expand:
10296 -- for all X in range => Cond
10298 -- into:
10300 -- T := True;
10301 -- for X in range loop
10302 -- if not Cond then
10303 -- T := False;
10304 -- exit;
10305 -- end if;
10306 -- end loop;
10308 -- Similarly, an existentially quantified expression:
10310 -- for some X in range => Cond
10312 -- becomes:
10314 -- T := False;
10315 -- for X in range loop
10316 -- if Cond then
10317 -- T := True;
10318 -- exit;
10319 -- end if;
10320 -- end loop;
10322 -- In both cases, the iteration may be over a container in which case it is
10323 -- given by an iterator specification, not a loop parameter specification.
10325 procedure Expand_N_Quantified_Expression (N : Node_Id) is
10326 Actions : constant List_Id := New_List;
10327 For_All : constant Boolean := All_Present (N);
10328 Iter_Spec : constant Node_Id := Iterator_Specification (N);
10329 Loc : constant Source_Ptr := Sloc (N);
10330 Loop_Spec : constant Node_Id := Loop_Parameter_Specification (N);
10331 Cond : Node_Id;
10332 Flag : Entity_Id;
10333 Scheme : Node_Id;
10334 Stmts : List_Id;
10336 begin
10337 -- Create the declaration of the flag which tracks the status of the
10338 -- quantified expression. Generate:
10340 -- Flag : Boolean := (True | False);
10342 Flag := Make_Temporary (Loc, 'T', N);
10344 Append_To (Actions,
10345 Make_Object_Declaration (Loc,
10346 Defining_Identifier => Flag,
10347 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
10348 Expression =>
10349 New_Occurrence_Of (Boolean_Literals (For_All), Loc)));
10351 -- Construct the circuitry which tracks the status of the quantified
10352 -- expression. Generate:
10354 -- if [not] Cond then
10355 -- Flag := (False | True);
10356 -- exit;
10357 -- end if;
10359 Cond := Relocate_Node (Condition (N));
10361 if For_All then
10362 Cond := Make_Op_Not (Loc, Cond);
10363 end if;
10365 Stmts := New_List (
10366 Make_Implicit_If_Statement (N,
10367 Condition => Cond,
10368 Then_Statements => New_List (
10369 Make_Assignment_Statement (Loc,
10370 Name => New_Occurrence_Of (Flag, Loc),
10371 Expression =>
10372 New_Occurrence_Of (Boolean_Literals (not For_All), Loc)),
10373 Make_Exit_Statement (Loc))));
10375 -- Build the loop equivalent of the quantified expression
10377 if Present (Iter_Spec) then
10378 Scheme :=
10379 Make_Iteration_Scheme (Loc,
10380 Iterator_Specification => Iter_Spec);
10381 else
10382 Scheme :=
10383 Make_Iteration_Scheme (Loc,
10384 Loop_Parameter_Specification => Loop_Spec);
10385 end if;
10387 Append_To (Actions,
10388 Make_Loop_Statement (Loc,
10389 Iteration_Scheme => Scheme,
10390 Statements => Stmts,
10391 End_Label => Empty));
10393 -- Transform the quantified expression
10395 Rewrite (N,
10396 Make_Expression_With_Actions (Loc,
10397 Expression => New_Occurrence_Of (Flag, Loc),
10398 Actions => Actions));
10399 Analyze_And_Resolve (N, Standard_Boolean);
10400 end Expand_N_Quantified_Expression;
10402 ---------------------------------
10403 -- Expand_N_Selected_Component --
10404 ---------------------------------
10406 procedure Expand_N_Selected_Component (N : Node_Id) is
10407 Loc : constant Source_Ptr := Sloc (N);
10408 Par : constant Node_Id := Parent (N);
10409 P : constant Node_Id := Prefix (N);
10410 S : constant Node_Id := Selector_Name (N);
10411 Ptyp : Entity_Id := Underlying_Type (Etype (P));
10412 Disc : Entity_Id;
10413 New_N : Node_Id;
10414 Dcon : Elmt_Id;
10415 Dval : Node_Id;
10417 function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
10418 -- Gigi needs a temporary for prefixes that depend on a discriminant,
10419 -- unless the context of an assignment can provide size information.
10420 -- Don't we have a general routine that does this???
10422 function Is_Subtype_Declaration return Boolean;
10423 -- The replacement of a discriminant reference by its value is required
10424 -- if this is part of the initialization of an temporary generated by a
10425 -- change of representation. This shows up as the construction of a
10426 -- discriminant constraint for a subtype declared at the same point as
10427 -- the entity in the prefix of the selected component. We recognize this
10428 -- case when the context of the reference is:
10429 -- subtype ST is T(Obj.D);
10430 -- where the entity for Obj comes from source, and ST has the same sloc.
10432 -----------------------
10433 -- In_Left_Hand_Side --
10434 -----------------------
10436 function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
10437 begin
10438 return (Nkind (Parent (Comp)) = N_Assignment_Statement
10439 and then Comp = Name (Parent (Comp)))
10440 or else (Present (Parent (Comp))
10441 and then Nkind (Parent (Comp)) in N_Subexpr
10442 and then In_Left_Hand_Side (Parent (Comp)));
10443 end In_Left_Hand_Side;
10445 -----------------------------
10446 -- Is_Subtype_Declaration --
10447 -----------------------------
10449 function Is_Subtype_Declaration return Boolean is
10450 Par : constant Node_Id := Parent (N);
10451 begin
10452 return
10453 Nkind (Par) = N_Index_Or_Discriminant_Constraint
10454 and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
10455 and then Comes_From_Source (Entity (Prefix (N)))
10456 and then Sloc (Par) = Sloc (Entity (Prefix (N)));
10457 end Is_Subtype_Declaration;
10459 -- Start of processing for Expand_N_Selected_Component
10461 begin
10462 -- Insert explicit dereference if required
10464 if Is_Access_Type (Ptyp) then
10466 -- First set prefix type to proper access type, in case it currently
10467 -- has a private (non-access) view of this type.
10469 Set_Etype (P, Ptyp);
10471 Insert_Explicit_Dereference (P);
10472 Analyze_And_Resolve (P, Designated_Type (Ptyp));
10474 Ptyp := Etype (P);
10475 end if;
10477 -- Deal with discriminant check required
10479 if Do_Discriminant_Check (N) then
10480 if Present (Discriminant_Checking_Func
10481 (Original_Record_Component (Entity (S))))
10482 then
10483 -- Present the discriminant checking function to the backend, so
10484 -- that it can inline the call to the function.
10486 Add_Inlined_Body
10487 (Discriminant_Checking_Func
10488 (Original_Record_Component (Entity (S))),
10491 -- Now reset the flag and generate the call
10493 Set_Do_Discriminant_Check (N, False);
10494 Generate_Discriminant_Check (N);
10496 -- In the case of Unchecked_Union, no discriminant checking is
10497 -- actually performed.
10499 else
10500 Set_Do_Discriminant_Check (N, False);
10501 end if;
10502 end if;
10504 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10505 -- function, then additional actuals must be passed.
10507 if Is_Build_In_Place_Function_Call (P) then
10508 Make_Build_In_Place_Call_In_Anonymous_Context (P);
10510 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10511 -- containing build-in-place function calls whose returned object covers
10512 -- interface types.
10514 elsif Present (Unqual_BIP_Iface_Function_Call (P)) then
10515 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (P);
10516 end if;
10518 -- Gigi cannot handle unchecked conversions that are the prefix of a
10519 -- selected component with discriminants. This must be checked during
10520 -- expansion, because during analysis the type of the selector is not
10521 -- known at the point the prefix is analyzed. If the conversion is the
10522 -- target of an assignment, then we cannot force the evaluation.
10524 if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
10525 and then Has_Discriminants (Etype (N))
10526 and then not In_Left_Hand_Side (N)
10527 then
10528 Force_Evaluation (Prefix (N));
10529 end if;
10531 -- Remaining processing applies only if selector is a discriminant
10533 if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
10535 -- If the selector is a discriminant of a constrained record type,
10536 -- we may be able to rewrite the expression with the actual value
10537 -- of the discriminant, a useful optimization in some cases.
10539 if Is_Record_Type (Ptyp)
10540 and then Has_Discriminants (Ptyp)
10541 and then Is_Constrained (Ptyp)
10542 then
10543 -- Do this optimization for discrete types only, and not for
10544 -- access types (access discriminants get us into trouble).
10546 if not Is_Discrete_Type (Etype (N)) then
10547 null;
10549 -- Don't do this on the left-hand side of an assignment statement.
10550 -- Normally one would think that references like this would not
10551 -- occur, but they do in generated code, and mean that we really
10552 -- do want to assign the discriminant.
10554 elsif Nkind (Par) = N_Assignment_Statement
10555 and then Name (Par) = N
10556 then
10557 null;
10559 -- Don't do this optimization for the prefix of an attribute or
10560 -- the name of an object renaming declaration since these are
10561 -- contexts where we do not want the value anyway.
10563 elsif (Nkind (Par) = N_Attribute_Reference
10564 and then Prefix (Par) = N)
10565 or else Is_Renamed_Object (N)
10566 then
10567 null;
10569 -- Don't do this optimization if we are within the code for a
10570 -- discriminant check, since the whole point of such a check may
10571 -- be to verify the condition on which the code below depends.
10573 elsif Is_In_Discriminant_Check (N) then
10574 null;
10576 -- Green light to see if we can do the optimization. There is
10577 -- still one condition that inhibits the optimization below but
10578 -- now is the time to check the particular discriminant.
10580 else
10581 -- Loop through discriminants to find the matching discriminant
10582 -- constraint to see if we can copy it.
10584 Disc := First_Discriminant (Ptyp);
10585 Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
10586 Discr_Loop : while Present (Dcon) loop
10587 Dval := Node (Dcon);
10589 -- Check if this is the matching discriminant and if the
10590 -- discriminant value is simple enough to make sense to
10591 -- copy. We don't want to copy complex expressions, and
10592 -- indeed to do so can cause trouble (before we put in
10593 -- this guard, a discriminant expression containing an
10594 -- AND THEN was copied, causing problems for coverage
10595 -- analysis tools).
10597 -- However, if the reference is part of the initialization
10598 -- code generated for an object declaration, we must use
10599 -- the discriminant value from the subtype constraint,
10600 -- because the selected component may be a reference to the
10601 -- object being initialized, whose discriminant is not yet
10602 -- set. This only happens in complex cases involving changes
10603 -- or representation.
10605 if Disc = Entity (Selector_Name (N))
10606 and then (Is_Entity_Name (Dval)
10607 or else Compile_Time_Known_Value (Dval)
10608 or else Is_Subtype_Declaration)
10609 then
10610 -- Here we have the matching discriminant. Check for
10611 -- the case of a discriminant of a component that is
10612 -- constrained by an outer discriminant, which cannot
10613 -- be optimized away.
10615 if Denotes_Discriminant
10616 (Dval, Check_Concurrent => True)
10617 then
10618 exit Discr_Loop;
10620 elsif Nkind (Original_Node (Dval)) = N_Selected_Component
10621 and then
10622 Denotes_Discriminant
10623 (Selector_Name (Original_Node (Dval)), True)
10624 then
10625 exit Discr_Loop;
10627 -- Do not retrieve value if constraint is not static. It
10628 -- is generally not useful, and the constraint may be a
10629 -- rewritten outer discriminant in which case it is in
10630 -- fact incorrect.
10632 elsif Is_Entity_Name (Dval)
10633 and then
10634 Nkind (Parent (Entity (Dval))) = N_Object_Declaration
10635 and then Present (Expression (Parent (Entity (Dval))))
10636 and then not
10637 Is_OK_Static_Expression
10638 (Expression (Parent (Entity (Dval))))
10639 then
10640 exit Discr_Loop;
10642 -- In the context of a case statement, the expression may
10643 -- have the base type of the discriminant, and we need to
10644 -- preserve the constraint to avoid spurious errors on
10645 -- missing cases.
10647 elsif Nkind (Parent (N)) = N_Case_Statement
10648 and then Etype (Dval) /= Etype (Disc)
10649 then
10650 Rewrite (N,
10651 Make_Qualified_Expression (Loc,
10652 Subtype_Mark =>
10653 New_Occurrence_Of (Etype (Disc), Loc),
10654 Expression =>
10655 New_Copy_Tree (Dval)));
10656 Analyze_And_Resolve (N, Etype (Disc));
10658 -- In case that comes out as a static expression,
10659 -- reset it (a selected component is never static).
10661 Set_Is_Static_Expression (N, False);
10662 return;
10664 -- Otherwise we can just copy the constraint, but the
10665 -- result is certainly not static. In some cases the
10666 -- discriminant constraint has been analyzed in the
10667 -- context of the original subtype indication, but for
10668 -- itypes the constraint might not have been analyzed
10669 -- yet, and this must be done now.
10671 else
10672 Rewrite (N, New_Copy_Tree (Dval));
10673 Analyze_And_Resolve (N);
10674 Set_Is_Static_Expression (N, False);
10675 return;
10676 end if;
10677 end if;
10679 Next_Elmt (Dcon);
10680 Next_Discriminant (Disc);
10681 end loop Discr_Loop;
10683 -- Note: the above loop should always find a matching
10684 -- discriminant, but if it does not, we just missed an
10685 -- optimization due to some glitch (perhaps a previous
10686 -- error), so ignore.
10688 end if;
10689 end if;
10691 -- The only remaining processing is in the case of a discriminant of
10692 -- a concurrent object, where we rewrite the prefix to denote the
10693 -- corresponding record type. If the type is derived and has renamed
10694 -- discriminants, use corresponding discriminant, which is the one
10695 -- that appears in the corresponding record.
10697 if not Is_Concurrent_Type (Ptyp) then
10698 return;
10699 end if;
10701 Disc := Entity (Selector_Name (N));
10703 if Is_Derived_Type (Ptyp)
10704 and then Present (Corresponding_Discriminant (Disc))
10705 then
10706 Disc := Corresponding_Discriminant (Disc);
10707 end if;
10709 New_N :=
10710 Make_Selected_Component (Loc,
10711 Prefix =>
10712 Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
10713 New_Copy_Tree (P)),
10714 Selector_Name => Make_Identifier (Loc, Chars (Disc)));
10716 Rewrite (N, New_N);
10717 Analyze (N);
10718 end if;
10720 -- Set Atomic_Sync_Required if necessary for atomic component
10722 if Nkind (N) = N_Selected_Component then
10723 declare
10724 E : constant Entity_Id := Entity (Selector_Name (N));
10725 Set : Boolean;
10727 begin
10728 -- If component is atomic, but type is not, setting depends on
10729 -- disable/enable state for the component.
10731 if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
10732 Set := not Atomic_Synchronization_Disabled (E);
10734 -- If component is not atomic, but its type is atomic, setting
10735 -- depends on disable/enable state for the type.
10737 elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10738 Set := not Atomic_Synchronization_Disabled (Etype (E));
10740 -- If both component and type are atomic, we disable if either
10741 -- component or its type have sync disabled.
10743 elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10744 Set := (not Atomic_Synchronization_Disabled (E))
10745 and then
10746 (not Atomic_Synchronization_Disabled (Etype (E)));
10748 else
10749 Set := False;
10750 end if;
10752 -- Set flag if required
10754 if Set then
10755 Activate_Atomic_Synchronization (N);
10756 end if;
10757 end;
10758 end if;
10759 end Expand_N_Selected_Component;
10761 --------------------
10762 -- Expand_N_Slice --
10763 --------------------
10765 procedure Expand_N_Slice (N : Node_Id) is
10766 Loc : constant Source_Ptr := Sloc (N);
10767 Typ : constant Entity_Id := Etype (N);
10769 function Is_Procedure_Actual (N : Node_Id) return Boolean;
10770 -- Check whether the argument is an actual for a procedure call, in
10771 -- which case the expansion of a bit-packed slice is deferred until the
10772 -- call itself is expanded. The reason this is required is that we might
10773 -- have an IN OUT or OUT parameter, and the copy out is essential, and
10774 -- that copy out would be missed if we created a temporary here in
10775 -- Expand_N_Slice. Note that we don't bother to test specifically for an
10776 -- IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
10777 -- is harmless to defer expansion in the IN case, since the call
10778 -- processing will still generate the appropriate copy in operation,
10779 -- which will take care of the slice.
10781 procedure Make_Temporary_For_Slice;
10782 -- Create a named variable for the value of the slice, in cases where
10783 -- the back end cannot handle it properly, e.g. when packed types or
10784 -- unaligned slices are involved.
10786 -------------------------
10787 -- Is_Procedure_Actual --
10788 -------------------------
10790 function Is_Procedure_Actual (N : Node_Id) return Boolean is
10791 Par : Node_Id := Parent (N);
10793 begin
10794 loop
10795 -- If our parent is a procedure call we can return
10797 if Nkind (Par) = N_Procedure_Call_Statement then
10798 return True;
10800 -- If our parent is a type conversion, keep climbing the tree,
10801 -- since a type conversion can be a procedure actual. Also keep
10802 -- climbing if parameter association or a qualified expression,
10803 -- since these are additional cases that do can appear on
10804 -- procedure actuals.
10806 elsif Nkind_In (Par, N_Type_Conversion,
10807 N_Parameter_Association,
10808 N_Qualified_Expression)
10809 then
10810 Par := Parent (Par);
10812 -- Any other case is not what we are looking for
10814 else
10815 return False;
10816 end if;
10817 end loop;
10818 end Is_Procedure_Actual;
10820 ------------------------------
10821 -- Make_Temporary_For_Slice --
10822 ------------------------------
10824 procedure Make_Temporary_For_Slice is
10825 Ent : constant Entity_Id := Make_Temporary (Loc, 'T', N);
10826 Decl : Node_Id;
10828 begin
10829 Decl :=
10830 Make_Object_Declaration (Loc,
10831 Defining_Identifier => Ent,
10832 Object_Definition => New_Occurrence_Of (Typ, Loc));
10834 Set_No_Initialization (Decl);
10836 Insert_Actions (N, New_List (
10837 Decl,
10838 Make_Assignment_Statement (Loc,
10839 Name => New_Occurrence_Of (Ent, Loc),
10840 Expression => Relocate_Node (N))));
10842 Rewrite (N, New_Occurrence_Of (Ent, Loc));
10843 Analyze_And_Resolve (N, Typ);
10844 end Make_Temporary_For_Slice;
10846 -- Local variables
10848 Pref : constant Node_Id := Prefix (N);
10849 Pref_Typ : Entity_Id := Etype (Pref);
10851 -- Start of processing for Expand_N_Slice
10853 begin
10854 -- Special handling for access types
10856 if Is_Access_Type (Pref_Typ) then
10857 Pref_Typ := Designated_Type (Pref_Typ);
10859 Rewrite (Pref,
10860 Make_Explicit_Dereference (Sloc (N),
10861 Prefix => Relocate_Node (Pref)));
10863 Analyze_And_Resolve (Pref, Pref_Typ);
10864 end if;
10866 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10867 -- function, then additional actuals must be passed.
10869 if Is_Build_In_Place_Function_Call (Pref) then
10870 Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
10872 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10873 -- containing build-in-place function calls whose returned object covers
10874 -- interface types.
10876 elsif Present (Unqual_BIP_Iface_Function_Call (Pref)) then
10877 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (Pref);
10878 end if;
10880 -- The remaining case to be handled is packed slices. We can leave
10881 -- packed slices as they are in the following situations:
10883 -- 1. Right or left side of an assignment (we can handle this
10884 -- situation correctly in the assignment statement expansion).
10886 -- 2. Prefix of indexed component (the slide is optimized away in this
10887 -- case, see the start of Expand_N_Slice.)
10889 -- 3. Object renaming declaration, since we want the name of the
10890 -- slice, not the value.
10892 -- 4. Argument to procedure call, since copy-in/copy-out handling may
10893 -- be required, and this is handled in the expansion of call
10894 -- itself.
10896 -- 5. Prefix of an address attribute (this is an error which is caught
10897 -- elsewhere, and the expansion would interfere with generating the
10898 -- error message).
10900 if not Is_Packed (Typ) then
10902 -- Apply transformation for actuals of a function call, where
10903 -- Expand_Actuals is not used.
10905 if Nkind (Parent (N)) = N_Function_Call
10906 and then Is_Possibly_Unaligned_Slice (N)
10907 then
10908 Make_Temporary_For_Slice;
10909 end if;
10911 elsif Nkind (Parent (N)) = N_Assignment_Statement
10912 or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
10913 and then Parent (N) = Name (Parent (Parent (N))))
10914 then
10915 return;
10917 elsif Nkind (Parent (N)) = N_Indexed_Component
10918 or else Is_Renamed_Object (N)
10919 or else Is_Procedure_Actual (N)
10920 then
10921 return;
10923 elsif Nkind (Parent (N)) = N_Attribute_Reference
10924 and then Attribute_Name (Parent (N)) = Name_Address
10925 then
10926 return;
10928 else
10929 Make_Temporary_For_Slice;
10930 end if;
10931 end Expand_N_Slice;
10933 ------------------------------
10934 -- Expand_N_Type_Conversion --
10935 ------------------------------
10937 procedure Expand_N_Type_Conversion (N : Node_Id) is
10938 Loc : constant Source_Ptr := Sloc (N);
10939 Operand : constant Node_Id := Expression (N);
10940 Target_Type : Entity_Id := Etype (N);
10941 Operand_Type : Entity_Id := Etype (Operand);
10943 procedure Discrete_Range_Check;
10944 -- Handles generation of range check for discrete target value
10946 procedure Handle_Changed_Representation;
10947 -- This is called in the case of record and array type conversions to
10948 -- see if there is a change of representation to be handled. Change of
10949 -- representation is actually handled at the assignment statement level,
10950 -- and what this procedure does is rewrite node N conversion as an
10951 -- assignment to temporary. If there is no change of representation,
10952 -- then the conversion node is unchanged.
10954 procedure Raise_Accessibility_Error;
10955 -- Called when we know that an accessibility check will fail. Rewrites
10956 -- node N to an appropriate raise statement and outputs warning msgs.
10957 -- The Etype of the raise node is set to Target_Type. Note that in this
10958 -- case the rest of the processing should be skipped (i.e. the call to
10959 -- this procedure will be followed by "goto Done").
10961 procedure Real_Range_Check;
10962 -- Handles generation of range check for real target value
10964 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
10965 -- True iff Present (Effective_Extra_Accessibility (Id)) successfully
10966 -- evaluates to True.
10968 --------------------------
10969 -- Discrete_Range_Check --
10970 --------------------------
10972 -- Case of conversions to a discrete type
10974 procedure Discrete_Range_Check is
10975 Expr : Node_Id;
10976 Ityp : Entity_Id;
10978 begin
10979 -- Nothing to do if conversion was rewritten
10981 if Nkind (N) /= N_Type_Conversion then
10982 return;
10983 end if;
10985 Expr := Expression (N);
10987 -- Before we do a range check, we have to deal with treating
10988 -- a fixed-point operand as an integer. The way we do this
10989 -- is simply to do an unchecked conversion to an appropriate
10990 -- integer type large enough to hold the result.
10992 if Is_Fixed_Point_Type (Etype (Expr)) then
10993 if Esize (Base_Type (Etype (Expr))) > Esize (Standard_Integer) then
10994 Ityp := Standard_Long_Long_Integer;
10995 else
10996 Ityp := Standard_Integer;
10997 end if;
10999 Set_Do_Range_Check (Expr, False);
11000 Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
11001 end if;
11003 -- Reset overflow flag, since the range check will include
11004 -- dealing with possible overflow, and generate the check.
11006 Set_Do_Overflow_Check (N, False);
11008 Generate_Range_Check (Expr, Target_Type, CE_Range_Check_Failed);
11009 end Discrete_Range_Check;
11011 -----------------------------------
11012 -- Handle_Changed_Representation --
11013 -----------------------------------
11015 procedure Handle_Changed_Representation is
11016 Temp : Entity_Id;
11017 Decl : Node_Id;
11018 Odef : Node_Id;
11019 N_Ix : Node_Id;
11020 Cons : List_Id;
11022 begin
11023 -- Nothing else to do if no change of representation
11025 if Same_Representation (Operand_Type, Target_Type) then
11026 return;
11028 -- The real change of representation work is done by the assignment
11029 -- statement processing. So if this type conversion is appearing as
11030 -- the expression of an assignment statement, nothing needs to be
11031 -- done to the conversion.
11033 elsif Nkind (Parent (N)) = N_Assignment_Statement then
11034 return;
11036 -- Otherwise we need to generate a temporary variable, and do the
11037 -- change of representation assignment into that temporary variable.
11038 -- The conversion is then replaced by a reference to this variable.
11040 else
11041 Cons := No_List;
11043 -- If type is unconstrained we have to add a constraint, copied
11044 -- from the actual value of the left-hand side.
11046 if not Is_Constrained (Target_Type) then
11047 if Has_Discriminants (Operand_Type) then
11049 -- A change of representation can only apply to untagged
11050 -- types. We need to build the constraint that applies to
11051 -- the target type, using the constraints of the operand.
11052 -- The analysis is complicated if there are both inherited
11053 -- discriminants and constrained discriminants.
11054 -- We iterate over the discriminants of the target, and
11055 -- find the discriminant of the same name:
11057 -- a) If there is a corresponding discriminant in the object
11058 -- then the value is a selected component of the operand.
11060 -- b) Otherwise the value of a constrained discriminant is
11061 -- found in the stored constraint of the operand.
11063 declare
11064 Stored : constant Elist_Id :=
11065 Stored_Constraint (Operand_Type);
11067 Elmt : Elmt_Id;
11069 Disc_O : Entity_Id;
11070 -- Discriminant of the operand type. Its value in the
11071 -- object is captured in a selected component.
11073 Disc_S : Entity_Id;
11074 -- Stored discriminant of the operand. If present, it
11075 -- corresponds to a constrained discriminant of the
11076 -- parent type.
11078 Disc_T : Entity_Id;
11079 -- Discriminant of the target type
11081 begin
11082 Disc_T := First_Discriminant (Target_Type);
11083 Disc_O := First_Discriminant (Operand_Type);
11084 Disc_S := First_Stored_Discriminant (Operand_Type);
11086 if Present (Stored) then
11087 Elmt := First_Elmt (Stored);
11088 else
11089 Elmt := No_Elmt; -- init to avoid warning
11090 end if;
11092 Cons := New_List;
11093 while Present (Disc_T) loop
11094 if Present (Disc_O)
11095 and then Chars (Disc_T) = Chars (Disc_O)
11096 then
11097 Append_To (Cons,
11098 Make_Selected_Component (Loc,
11099 Prefix =>
11100 Duplicate_Subexpr_Move_Checks (Operand),
11101 Selector_Name =>
11102 Make_Identifier (Loc, Chars (Disc_O))));
11103 Next_Discriminant (Disc_O);
11105 elsif Present (Disc_S) then
11106 Append_To (Cons, New_Copy_Tree (Node (Elmt)));
11107 Next_Elmt (Elmt);
11108 end if;
11110 Next_Discriminant (Disc_T);
11111 end loop;
11112 end;
11114 elsif Is_Array_Type (Operand_Type) then
11115 N_Ix := First_Index (Target_Type);
11116 Cons := New_List;
11118 for J in 1 .. Number_Dimensions (Operand_Type) loop
11120 -- We convert the bounds explicitly. We use an unchecked
11121 -- conversion because bounds checks are done elsewhere.
11123 Append_To (Cons,
11124 Make_Range (Loc,
11125 Low_Bound =>
11126 Unchecked_Convert_To (Etype (N_Ix),
11127 Make_Attribute_Reference (Loc,
11128 Prefix =>
11129 Duplicate_Subexpr_No_Checks
11130 (Operand, Name_Req => True),
11131 Attribute_Name => Name_First,
11132 Expressions => New_List (
11133 Make_Integer_Literal (Loc, J)))),
11135 High_Bound =>
11136 Unchecked_Convert_To (Etype (N_Ix),
11137 Make_Attribute_Reference (Loc,
11138 Prefix =>
11139 Duplicate_Subexpr_No_Checks
11140 (Operand, Name_Req => True),
11141 Attribute_Name => Name_Last,
11142 Expressions => New_List (
11143 Make_Integer_Literal (Loc, J))))));
11145 Next_Index (N_Ix);
11146 end loop;
11147 end if;
11148 end if;
11150 Odef := New_Occurrence_Of (Target_Type, Loc);
11152 if Present (Cons) then
11153 Odef :=
11154 Make_Subtype_Indication (Loc,
11155 Subtype_Mark => Odef,
11156 Constraint =>
11157 Make_Index_Or_Discriminant_Constraint (Loc,
11158 Constraints => Cons));
11159 end if;
11161 Temp := Make_Temporary (Loc, 'C');
11162 Decl :=
11163 Make_Object_Declaration (Loc,
11164 Defining_Identifier => Temp,
11165 Object_Definition => Odef);
11167 Set_No_Initialization (Decl, True);
11169 -- Insert required actions. It is essential to suppress checks
11170 -- since we have suppressed default initialization, which means
11171 -- that the variable we create may have no discriminants.
11173 Insert_Actions (N,
11174 New_List (
11175 Decl,
11176 Make_Assignment_Statement (Loc,
11177 Name => New_Occurrence_Of (Temp, Loc),
11178 Expression => Relocate_Node (N))),
11179 Suppress => All_Checks);
11181 Rewrite (N, New_Occurrence_Of (Temp, Loc));
11182 return;
11183 end if;
11184 end Handle_Changed_Representation;
11186 -------------------------------
11187 -- Raise_Accessibility_Error --
11188 -------------------------------
11190 procedure Raise_Accessibility_Error is
11191 begin
11192 Error_Msg_Warn := SPARK_Mode /= On;
11193 Rewrite (N,
11194 Make_Raise_Program_Error (Sloc (N),
11195 Reason => PE_Accessibility_Check_Failed));
11196 Set_Etype (N, Target_Type);
11198 Error_Msg_N ("<<accessibility check failure", N);
11199 Error_Msg_NE ("\<<& [", N, Standard_Program_Error);
11200 end Raise_Accessibility_Error;
11202 ----------------------
11203 -- Real_Range_Check --
11204 ----------------------
11206 -- Case of conversions to floating-point or fixed-point. If range checks
11207 -- are enabled and the target type has a range constraint, we convert:
11209 -- typ (x)
11211 -- to
11213 -- Tnn : typ'Base := typ'Base (x);
11214 -- [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
11215 -- Tnn
11217 -- This is necessary when there is a conversion of integer to float or
11218 -- to fixed-point to ensure that the correct checks are made. It is not
11219 -- necessary for float to float where it is enough to simply set the
11220 -- Do_Range_Check flag.
11222 procedure Real_Range_Check is
11223 Btyp : constant Entity_Id := Base_Type (Target_Type);
11224 Lo : constant Node_Id := Type_Low_Bound (Target_Type);
11225 Hi : constant Node_Id := Type_High_Bound (Target_Type);
11227 Conv : Node_Id;
11228 Hi_Arg : Node_Id;
11229 Hi_Val : Node_Id;
11230 Lo_Arg : Node_Id;
11231 Lo_Val : Node_Id;
11232 Tnn : Entity_Id;
11234 begin
11235 -- Nothing to do if conversion was rewritten
11237 if Nkind (N) /= N_Type_Conversion then
11238 return;
11239 end if;
11241 -- Nothing to do if range checks suppressed, or target has the same
11242 -- range as the base type (or is the base type).
11244 if Range_Checks_Suppressed (Target_Type)
11245 or else (Lo = Type_Low_Bound (Btyp)
11246 and then
11247 Hi = Type_High_Bound (Btyp))
11248 then
11249 -- Unset the range check flag on the current value of
11250 -- Expression (N), since the captured Operand may have
11251 -- been rewritten (such as for the case of a conversion
11252 -- to a fixed-point type).
11254 Set_Do_Range_Check (Expression (N), False);
11255 return;
11256 end if;
11258 -- Nothing to do if expression is an entity on which checks have been
11259 -- suppressed.
11261 if Is_Entity_Name (Operand)
11262 and then Range_Checks_Suppressed (Entity (Operand))
11263 then
11264 Set_Do_Range_Check (Expression (N), False);
11265 return;
11266 end if;
11268 -- Nothing to do if bounds are all static and we can tell that the
11269 -- expression is within the bounds of the target. Note that if the
11270 -- operand is of an unconstrained floating-point type, then we do
11271 -- not trust it to be in range (might be infinite)
11273 declare
11274 S_Lo : constant Node_Id := Type_Low_Bound (Operand_Type);
11275 S_Hi : constant Node_Id := Type_High_Bound (Operand_Type);
11277 begin
11278 if (not Is_Floating_Point_Type (Operand_Type)
11279 or else Is_Constrained (Operand_Type))
11280 and then Compile_Time_Known_Value (S_Lo)
11281 and then Compile_Time_Known_Value (S_Hi)
11282 and then Compile_Time_Known_Value (Hi)
11283 and then Compile_Time_Known_Value (Lo)
11284 then
11285 declare
11286 D_Lov : constant Ureal := Expr_Value_R (Lo);
11287 D_Hiv : constant Ureal := Expr_Value_R (Hi);
11288 S_Lov : Ureal;
11289 S_Hiv : Ureal;
11291 begin
11292 if Is_Real_Type (Operand_Type) then
11293 S_Lov := Expr_Value_R (S_Lo);
11294 S_Hiv := Expr_Value_R (S_Hi);
11295 else
11296 S_Lov := UR_From_Uint (Expr_Value (S_Lo));
11297 S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
11298 end if;
11300 if D_Hiv > D_Lov
11301 and then S_Lov >= D_Lov
11302 and then S_Hiv <= D_Hiv
11303 then
11304 Set_Do_Range_Check (Expression (N), False);
11305 return;
11306 end if;
11307 end;
11308 end if;
11309 end;
11311 -- Otherwise rewrite the conversion as described above
11313 Set_Do_Range_Check (Expression (N), False);
11315 Conv := Relocate_Node (N);
11316 Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
11317 Set_Etype (Conv, Btyp);
11319 -- Enable overflow except for case of integer to float conversions,
11320 -- where it is never required, since we can never have overflow in
11321 -- this case.
11323 if not Is_Integer_Type (Operand_Type) then
11324 Enable_Overflow_Check (Conv);
11325 end if;
11327 Tnn := Make_Temporary (Loc, 'T', Conv);
11329 -- For a conversion from Float to Fixed where the bounds of the
11330 -- fixed-point type are static, we can obtain a more accurate
11331 -- fixed-point value by converting the result of the floating-
11332 -- point expression to an appropriate integer type, and then
11333 -- performing an unchecked conversion to the target fixed-point
11334 -- type. The range check can then use the corresponding integer
11335 -- value of the bounds instead of requiring further conversions.
11336 -- This preserves the identity:
11338 -- Fix_Val = Fixed_Type (Float_Type (Fix_Val))
11340 -- which used to fail when Fix_Val was a bound of the type and
11341 -- the 'Small was not a representable number.
11342 -- This transformation requires an integer type large enough to
11343 -- accommodate a fixed-point value. This will not be the case
11344 -- in systems where Duration is larger than Long_Integer.
11346 if Is_Ordinary_Fixed_Point_Type (Target_Type)
11347 and then Is_Floating_Point_Type (Operand_Type)
11348 and then RM_Size (Base_Type (Target_Type)) <=
11349 RM_Size (Standard_Long_Integer)
11350 and then Nkind (Lo) = N_Real_Literal
11351 and then Nkind (Hi) = N_Real_Literal
11352 then
11353 -- Find the integer type of the right size to perform an unchecked
11354 -- conversion to the target fixed-point type.
11356 declare
11357 Bfx_Type : constant Entity_Id := Base_Type (Target_Type);
11358 Expr_Id : constant Entity_Id :=
11359 Make_Temporary (Loc, 'T', Conv);
11360 Int_Type : Entity_Id;
11362 begin
11363 if RM_Size (Bfx_Type) > RM_Size (Standard_Integer) then
11364 Int_Type := Standard_Long_Integer;
11366 elsif RM_Size (Bfx_Type) > RM_Size (Standard_Short_Integer) then
11367 Int_Type := Standard_Integer;
11369 else
11370 Int_Type := Standard_Short_Integer;
11371 end if;
11373 -- Generate a temporary with the integer value. Required in the
11374 -- CCG compiler to ensure that runtime checks reference this
11375 -- integer expression (instead of the resulting fixed-point
11376 -- value) because fixed-point values are handled by means of
11377 -- unsigned integer types).
11379 Insert_Action (N,
11380 Make_Object_Declaration (Loc,
11381 Defining_Identifier => Expr_Id,
11382 Object_Definition => New_Occurrence_Of (Int_Type, Loc),
11383 Constant_Present => True,
11384 Expression =>
11385 Convert_To (Int_Type, Expression (Conv))));
11387 -- Create integer objects for range checking of result.
11389 Lo_Arg :=
11390 Unchecked_Convert_To
11391 (Int_Type, New_Occurrence_Of (Expr_Id, Loc));
11393 Lo_Val :=
11394 Make_Integer_Literal (Loc, Corresponding_Integer_Value (Lo));
11396 Hi_Arg :=
11397 Unchecked_Convert_To
11398 (Int_Type, New_Occurrence_Of (Expr_Id, Loc));
11400 Hi_Val :=
11401 Make_Integer_Literal (Loc, Corresponding_Integer_Value (Hi));
11403 -- Rewrite conversion as an integer conversion of the
11404 -- original floating-point expression, followed by an
11405 -- unchecked conversion to the target fixed-point type.
11407 Conv :=
11408 Make_Unchecked_Type_Conversion (Loc,
11409 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
11410 Expression => New_Occurrence_Of (Expr_Id, Loc));
11411 end;
11413 -- All other conversions
11415 else
11416 Lo_Arg := New_Occurrence_Of (Tnn, Loc);
11417 Lo_Val :=
11418 Make_Attribute_Reference (Loc,
11419 Prefix => New_Occurrence_Of (Target_Type, Loc),
11420 Attribute_Name => Name_First);
11422 Hi_Arg := New_Occurrence_Of (Tnn, Loc);
11423 Hi_Val :=
11424 Make_Attribute_Reference (Loc,
11425 Prefix => New_Occurrence_Of (Target_Type, Loc),
11426 Attribute_Name => Name_Last);
11427 end if;
11429 -- Build code for range checking
11431 Insert_Actions (N, New_List (
11432 Make_Object_Declaration (Loc,
11433 Defining_Identifier => Tnn,
11434 Object_Definition => New_Occurrence_Of (Btyp, Loc),
11435 Constant_Present => True,
11436 Expression => Conv),
11438 Make_Raise_Constraint_Error (Loc,
11439 Condition =>
11440 Make_Or_Else (Loc,
11441 Left_Opnd =>
11442 Make_Op_Lt (Loc,
11443 Left_Opnd => Lo_Arg,
11444 Right_Opnd => Lo_Val),
11446 Right_Opnd =>
11447 Make_Op_Gt (Loc,
11448 Left_Opnd => Hi_Arg,
11449 Right_Opnd => Hi_Val)),
11450 Reason => CE_Range_Check_Failed)));
11452 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
11453 Analyze_And_Resolve (N, Btyp);
11454 end Real_Range_Check;
11456 -----------------------------
11457 -- Has_Extra_Accessibility --
11458 -----------------------------
11460 -- Returns true for a formal of an anonymous access type or for an Ada
11461 -- 2012-style stand-alone object of an anonymous access type.
11463 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
11464 begin
11465 if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
11466 return Present (Effective_Extra_Accessibility (Id));
11467 else
11468 return False;
11469 end if;
11470 end Has_Extra_Accessibility;
11472 -- Start of processing for Expand_N_Type_Conversion
11474 begin
11475 -- First remove check marks put by the semantic analysis on the type
11476 -- conversion between array types. We need these checks, and they will
11477 -- be generated by this expansion routine, but we do not depend on these
11478 -- flags being set, and since we do intend to expand the checks in the
11479 -- front end, we don't want them on the tree passed to the back end.
11481 if Is_Array_Type (Target_Type) then
11482 if Is_Constrained (Target_Type) then
11483 Set_Do_Length_Check (N, False);
11484 else
11485 Set_Do_Range_Check (Operand, False);
11486 end if;
11487 end if;
11489 -- Nothing at all to do if conversion is to the identical type so remove
11490 -- the conversion completely, it is useless, except that it may carry
11491 -- an Assignment_OK attribute, which must be propagated to the operand.
11493 if Operand_Type = Target_Type then
11494 if Assignment_OK (N) then
11495 Set_Assignment_OK (Operand);
11496 end if;
11498 Rewrite (N, Relocate_Node (Operand));
11499 goto Done;
11500 end if;
11502 -- Nothing to do if this is the second argument of read. This is a
11503 -- "backwards" conversion that will be handled by the specialized code
11504 -- in attribute processing.
11506 if Nkind (Parent (N)) = N_Attribute_Reference
11507 and then Attribute_Name (Parent (N)) = Name_Read
11508 and then Next (First (Expressions (Parent (N)))) = N
11509 then
11510 goto Done;
11511 end if;
11513 -- Check for case of converting to a type that has an invariant
11514 -- associated with it. This requires an invariant check. We insert
11515 -- a call:
11517 -- invariant_check (typ (expr))
11519 -- in the code, after removing side effects from the expression.
11520 -- This is clearer than replacing the conversion into an expression
11521 -- with actions, because the context may impose additional actions
11522 -- (tag checks, membership tests, etc.) that conflict with this
11523 -- rewriting (used previously).
11525 -- Note: the Comes_From_Source check, and then the resetting of this
11526 -- flag prevents what would otherwise be an infinite recursion.
11528 if Has_Invariants (Target_Type)
11529 and then Present (Invariant_Procedure (Target_Type))
11530 and then Comes_From_Source (N)
11531 then
11532 Set_Comes_From_Source (N, False);
11533 Remove_Side_Effects (N);
11534 Insert_Action (N, Make_Invariant_Call (Duplicate_Subexpr (N)));
11535 goto Done;
11536 end if;
11538 -- Here if we may need to expand conversion
11540 -- If the operand of the type conversion is an arithmetic operation on
11541 -- signed integers, and the based type of the signed integer type in
11542 -- question is smaller than Standard.Integer, we promote both of the
11543 -- operands to type Integer.
11545 -- For example, if we have
11547 -- target-type (opnd1 + opnd2)
11549 -- and opnd1 and opnd2 are of type short integer, then we rewrite
11550 -- this as:
11552 -- target-type (integer(opnd1) + integer(opnd2))
11554 -- We do this because we are always allowed to compute in a larger type
11555 -- if we do the right thing with the result, and in this case we are
11556 -- going to do a conversion which will do an appropriate check to make
11557 -- sure that things are in range of the target type in any case. This
11558 -- avoids some unnecessary intermediate overflows.
11560 -- We might consider a similar transformation in the case where the
11561 -- target is a real type or a 64-bit integer type, and the operand
11562 -- is an arithmetic operation using a 32-bit integer type. However,
11563 -- we do not bother with this case, because it could cause significant
11564 -- inefficiencies on 32-bit machines. On a 64-bit machine it would be
11565 -- much cheaper, but we don't want different behavior on 32-bit and
11566 -- 64-bit machines. Note that the exclusion of the 64-bit case also
11567 -- handles the configurable run-time cases where 64-bit arithmetic
11568 -- may simply be unavailable.
11570 -- Note: this circuit is partially redundant with respect to the circuit
11571 -- in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
11572 -- the processing here. Also we still need the Checks circuit, since we
11573 -- have to be sure not to generate junk overflow checks in the first
11574 -- place, since it would be trick to remove them here.
11576 if Integer_Promotion_Possible (N) then
11578 -- All conditions met, go ahead with transformation
11580 declare
11581 Opnd : Node_Id;
11582 L, R : Node_Id;
11584 begin
11585 R :=
11586 Make_Type_Conversion (Loc,
11587 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11588 Expression => Relocate_Node (Right_Opnd (Operand)));
11590 Opnd := New_Op_Node (Nkind (Operand), Loc);
11591 Set_Right_Opnd (Opnd, R);
11593 if Nkind (Operand) in N_Binary_Op then
11594 L :=
11595 Make_Type_Conversion (Loc,
11596 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11597 Expression => Relocate_Node (Left_Opnd (Operand)));
11599 Set_Left_Opnd (Opnd, L);
11600 end if;
11602 Rewrite (N,
11603 Make_Type_Conversion (Loc,
11604 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
11605 Expression => Opnd));
11607 Analyze_And_Resolve (N, Target_Type);
11608 goto Done;
11609 end;
11610 end if;
11612 -- Do validity check if validity checking operands
11614 if Validity_Checks_On and Validity_Check_Operands then
11615 Ensure_Valid (Operand);
11616 end if;
11618 -- Special case of converting from non-standard boolean type
11620 if Is_Boolean_Type (Operand_Type)
11621 and then (Nonzero_Is_True (Operand_Type))
11622 then
11623 Adjust_Condition (Operand);
11624 Set_Etype (Operand, Standard_Boolean);
11625 Operand_Type := Standard_Boolean;
11626 end if;
11628 -- Case of converting to an access type
11630 if Is_Access_Type (Target_Type) then
11632 -- If this type conversion was internally generated by the front end
11633 -- to displace the pointer to the object to reference an interface
11634 -- type and the original node was an Unrestricted_Access attribute,
11635 -- then skip applying accessibility checks (because, according to the
11636 -- GNAT Reference Manual, this attribute is similar to 'Access except
11637 -- that all accessibility and aliased view checks are omitted).
11639 if not Comes_From_Source (N)
11640 and then Is_Interface (Designated_Type (Target_Type))
11641 and then Nkind (Original_Node (N)) = N_Attribute_Reference
11642 and then Attribute_Name (Original_Node (N)) =
11643 Name_Unrestricted_Access
11644 then
11645 null;
11647 -- Apply an accessibility check when the conversion operand is an
11648 -- access parameter (or a renaming thereof), unless conversion was
11649 -- expanded from an Unchecked_ or Unrestricted_Access attribute,
11650 -- or for the actual of a class-wide interface parameter. Note that
11651 -- other checks may still need to be applied below (such as tagged
11652 -- type checks).
11654 elsif Is_Entity_Name (Operand)
11655 and then Has_Extra_Accessibility (Entity (Operand))
11656 and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
11657 and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
11658 or else Attribute_Name (Original_Node (N)) = Name_Access)
11659 then
11660 if not Comes_From_Source (N)
11661 and then Nkind_In (Parent (N), N_Function_Call,
11662 N_Parameter_Association,
11663 N_Procedure_Call_Statement)
11664 and then Is_Interface (Designated_Type (Target_Type))
11665 and then Is_Class_Wide_Type (Designated_Type (Target_Type))
11666 then
11667 null;
11669 else
11670 Apply_Accessibility_Check
11671 (Operand, Target_Type, Insert_Node => Operand);
11672 end if;
11674 -- If the level of the operand type is statically deeper than the
11675 -- level of the target type, then force Program_Error. Note that this
11676 -- can only occur for cases where the attribute is within the body of
11677 -- an instantiation, otherwise the conversion will already have been
11678 -- rejected as illegal.
11680 -- Note: warnings are issued by the analyzer for the instance cases
11682 elsif In_Instance_Body
11684 -- The case where the target type is an anonymous access type of
11685 -- a discriminant is excluded, because the level of such a type
11686 -- depends on the context and currently the level returned for such
11687 -- types is zero, resulting in warnings about about check failures
11688 -- in certain legal cases involving class-wide interfaces as the
11689 -- designated type (some cases, such as return statements, are
11690 -- checked at run time, but not clear if these are handled right
11691 -- in general, see 3.10.2(12/2-12.5/3) ???).
11693 and then
11694 not (Ekind (Target_Type) = E_Anonymous_Access_Type
11695 and then Present (Associated_Node_For_Itype (Target_Type))
11696 and then Nkind (Associated_Node_For_Itype (Target_Type)) =
11697 N_Discriminant_Specification)
11698 and then
11699 Type_Access_Level (Operand_Type) > Type_Access_Level (Target_Type)
11700 then
11701 Raise_Accessibility_Error;
11702 goto Done;
11704 -- When the operand is a selected access discriminant the check needs
11705 -- to be made against the level of the object denoted by the prefix
11706 -- of the selected name. Force Program_Error for this case as well
11707 -- (this accessibility violation can only happen if within the body
11708 -- of an instantiation).
11710 elsif In_Instance_Body
11711 and then Ekind (Operand_Type) = E_Anonymous_Access_Type
11712 and then Nkind (Operand) = N_Selected_Component
11713 and then Ekind (Entity (Selector_Name (Operand))) = E_Discriminant
11714 and then Object_Access_Level (Operand) >
11715 Type_Access_Level (Target_Type)
11716 then
11717 Raise_Accessibility_Error;
11718 goto Done;
11719 end if;
11720 end if;
11722 -- Case of conversions of tagged types and access to tagged types
11724 -- When needed, that is to say when the expression is class-wide, Add
11725 -- runtime a tag check for (strict) downward conversion by using the
11726 -- membership test, generating:
11728 -- [constraint_error when Operand not in Target_Type'Class]
11730 -- or in the access type case
11732 -- [constraint_error
11733 -- when Operand /= null
11734 -- and then Operand.all not in
11735 -- Designated_Type (Target_Type)'Class]
11737 if (Is_Access_Type (Target_Type)
11738 and then Is_Tagged_Type (Designated_Type (Target_Type)))
11739 or else Is_Tagged_Type (Target_Type)
11740 then
11741 -- Do not do any expansion in the access type case if the parent is a
11742 -- renaming, since this is an error situation which will be caught by
11743 -- Sem_Ch8, and the expansion can interfere with this error check.
11745 if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
11746 goto Done;
11747 end if;
11749 -- Otherwise, proceed with processing tagged conversion
11751 Tagged_Conversion : declare
11752 Actual_Op_Typ : Entity_Id;
11753 Actual_Targ_Typ : Entity_Id;
11754 Make_Conversion : Boolean := False;
11755 Root_Op_Typ : Entity_Id;
11757 procedure Make_Tag_Check (Targ_Typ : Entity_Id);
11758 -- Create a membership check to test whether Operand is a member
11759 -- of Targ_Typ. If the original Target_Type is an access, include
11760 -- a test for null value. The check is inserted at N.
11762 --------------------
11763 -- Make_Tag_Check --
11764 --------------------
11766 procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
11767 Cond : Node_Id;
11769 begin
11770 -- Generate:
11771 -- [Constraint_Error
11772 -- when Operand /= null
11773 -- and then Operand.all not in Targ_Typ]
11775 if Is_Access_Type (Target_Type) then
11776 Cond :=
11777 Make_And_Then (Loc,
11778 Left_Opnd =>
11779 Make_Op_Ne (Loc,
11780 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11781 Right_Opnd => Make_Null (Loc)),
11783 Right_Opnd =>
11784 Make_Not_In (Loc,
11785 Left_Opnd =>
11786 Make_Explicit_Dereference (Loc,
11787 Prefix => Duplicate_Subexpr_No_Checks (Operand)),
11788 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc)));
11790 -- Generate:
11791 -- [Constraint_Error when Operand not in Targ_Typ]
11793 else
11794 Cond :=
11795 Make_Not_In (Loc,
11796 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11797 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc));
11798 end if;
11800 Insert_Action (N,
11801 Make_Raise_Constraint_Error (Loc,
11802 Condition => Cond,
11803 Reason => CE_Tag_Check_Failed),
11804 Suppress => All_Checks);
11805 end Make_Tag_Check;
11807 -- Start of processing for Tagged_Conversion
11809 begin
11810 -- Handle entities from the limited view
11812 if Is_Access_Type (Operand_Type) then
11813 Actual_Op_Typ :=
11814 Available_View (Designated_Type (Operand_Type));
11815 else
11816 Actual_Op_Typ := Operand_Type;
11817 end if;
11819 if Is_Access_Type (Target_Type) then
11820 Actual_Targ_Typ :=
11821 Available_View (Designated_Type (Target_Type));
11822 else
11823 Actual_Targ_Typ := Target_Type;
11824 end if;
11826 Root_Op_Typ := Root_Type (Actual_Op_Typ);
11828 -- Ada 2005 (AI-251): Handle interface type conversion
11830 if Is_Interface (Actual_Op_Typ)
11831 or else
11832 Is_Interface (Actual_Targ_Typ)
11833 then
11834 Expand_Interface_Conversion (N);
11835 goto Done;
11836 end if;
11838 if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
11840 -- Create a runtime tag check for a downward class-wide type
11841 -- conversion.
11843 if Is_Class_Wide_Type (Actual_Op_Typ)
11844 and then Actual_Op_Typ /= Actual_Targ_Typ
11845 and then Root_Op_Typ /= Actual_Targ_Typ
11846 and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
11847 Use_Full_View => True)
11848 then
11849 Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
11850 Make_Conversion := True;
11851 end if;
11853 -- AI05-0073: If the result subtype of the function is defined
11854 -- by an access_definition designating a specific tagged type
11855 -- T, a check is made that the result value is null or the tag
11856 -- of the object designated by the result value identifies T.
11857 -- Constraint_Error is raised if this check fails.
11859 if Nkind (Parent (N)) = N_Simple_Return_Statement then
11860 declare
11861 Func : Entity_Id;
11862 Func_Typ : Entity_Id;
11864 begin
11865 -- Climb scope stack looking for the enclosing function
11867 Func := Current_Scope;
11868 while Present (Func)
11869 and then Ekind (Func) /= E_Function
11870 loop
11871 Func := Scope (Func);
11872 end loop;
11874 -- The function's return subtype must be defined using
11875 -- an access definition.
11877 if Nkind (Result_Definition (Parent (Func))) =
11878 N_Access_Definition
11879 then
11880 Func_Typ := Directly_Designated_Type (Etype (Func));
11882 -- The return subtype denotes a specific tagged type,
11883 -- in other words, a non class-wide type.
11885 if Is_Tagged_Type (Func_Typ)
11886 and then not Is_Class_Wide_Type (Func_Typ)
11887 then
11888 Make_Tag_Check (Actual_Targ_Typ);
11889 Make_Conversion := True;
11890 end if;
11891 end if;
11892 end;
11893 end if;
11895 -- We have generated a tag check for either a class-wide type
11896 -- conversion or for AI05-0073.
11898 if Make_Conversion then
11899 declare
11900 Conv : Node_Id;
11901 begin
11902 Conv :=
11903 Make_Unchecked_Type_Conversion (Loc,
11904 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
11905 Expression => Relocate_Node (Expression (N)));
11906 Rewrite (N, Conv);
11907 Analyze_And_Resolve (N, Target_Type);
11908 end;
11909 end if;
11910 end if;
11911 end Tagged_Conversion;
11913 -- Case of other access type conversions
11915 elsif Is_Access_Type (Target_Type) then
11916 Apply_Constraint_Check (Operand, Target_Type);
11918 -- Case of conversions from a fixed-point type
11920 -- These conversions require special expansion and processing, found in
11921 -- the Exp_Fixd package. We ignore cases where Conversion_OK is set,
11922 -- since from a semantic point of view, these are simple integer
11923 -- conversions, which do not need further processing.
11925 elsif Is_Fixed_Point_Type (Operand_Type)
11926 and then not Conversion_OK (N)
11927 then
11928 -- We should never see universal fixed at this case, since the
11929 -- expansion of the constituent divide or multiply should have
11930 -- eliminated the explicit mention of universal fixed.
11932 pragma Assert (Operand_Type /= Universal_Fixed);
11934 -- Check for special case of the conversion to universal real that
11935 -- occurs as a result of the use of a round attribute. In this case,
11936 -- the real type for the conversion is taken from the target type of
11937 -- the Round attribute and the result must be marked as rounded.
11939 if Target_Type = Universal_Real
11940 and then Nkind (Parent (N)) = N_Attribute_Reference
11941 and then Attribute_Name (Parent (N)) = Name_Round
11942 then
11943 Set_Rounded_Result (N);
11944 Set_Etype (N, Etype (Parent (N)));
11945 Target_Type := Etype (N);
11946 end if;
11948 if Is_Fixed_Point_Type (Target_Type) then
11949 Expand_Convert_Fixed_To_Fixed (N);
11950 Real_Range_Check;
11952 elsif Is_Integer_Type (Target_Type) then
11953 Expand_Convert_Fixed_To_Integer (N);
11954 Discrete_Range_Check;
11956 else
11957 pragma Assert (Is_Floating_Point_Type (Target_Type));
11958 Expand_Convert_Fixed_To_Float (N);
11959 Real_Range_Check;
11960 end if;
11962 -- Case of conversions to a fixed-point type
11964 -- These conversions require special expansion and processing, found in
11965 -- the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
11966 -- since from a semantic point of view, these are simple integer
11967 -- conversions, which do not need further processing.
11969 elsif Is_Fixed_Point_Type (Target_Type)
11970 and then not Conversion_OK (N)
11971 then
11972 if Is_Integer_Type (Operand_Type) then
11973 Expand_Convert_Integer_To_Fixed (N);
11974 Real_Range_Check;
11975 else
11976 pragma Assert (Is_Floating_Point_Type (Operand_Type));
11977 Expand_Convert_Float_To_Fixed (N);
11978 Real_Range_Check;
11979 end if;
11981 -- Case of array conversions
11983 -- Expansion of array conversions, add required length/range checks but
11984 -- only do this if there is no change of representation. For handling of
11985 -- this case, see Handle_Changed_Representation.
11987 elsif Is_Array_Type (Target_Type) then
11988 if Is_Constrained (Target_Type) then
11989 Apply_Length_Check (Operand, Target_Type);
11990 else
11991 Apply_Range_Check (Operand, Target_Type);
11992 end if;
11994 Handle_Changed_Representation;
11996 -- Case of conversions of discriminated types
11998 -- Add required discriminant checks if target is constrained. Again this
11999 -- change is skipped if we have a change of representation.
12001 elsif Has_Discriminants (Target_Type)
12002 and then Is_Constrained (Target_Type)
12003 then
12004 Apply_Discriminant_Check (Operand, Target_Type);
12005 Handle_Changed_Representation;
12007 -- Case of all other record conversions. The only processing required
12008 -- is to check for a change of representation requiring the special
12009 -- assignment processing.
12011 elsif Is_Record_Type (Target_Type) then
12013 -- Ada 2005 (AI-216): Program_Error is raised when converting from
12014 -- a derived Unchecked_Union type to an unconstrained type that is
12015 -- not Unchecked_Union if the operand lacks inferable discriminants.
12017 if Is_Derived_Type (Operand_Type)
12018 and then Is_Unchecked_Union (Base_Type (Operand_Type))
12019 and then not Is_Constrained (Target_Type)
12020 and then not Is_Unchecked_Union (Base_Type (Target_Type))
12021 and then not Has_Inferable_Discriminants (Operand)
12022 then
12023 -- To prevent Gigi from generating illegal code, we generate a
12024 -- Program_Error node, but we give it the target type of the
12025 -- conversion (is this requirement documented somewhere ???)
12027 declare
12028 PE : constant Node_Id := Make_Raise_Program_Error (Loc,
12029 Reason => PE_Unchecked_Union_Restriction);
12031 begin
12032 Set_Etype (PE, Target_Type);
12033 Rewrite (N, PE);
12035 end;
12036 else
12037 Handle_Changed_Representation;
12038 end if;
12040 -- Case of conversions of enumeration types
12042 elsif Is_Enumeration_Type (Target_Type) then
12044 -- Special processing is required if there is a change of
12045 -- representation (from enumeration representation clauses).
12047 if not Same_Representation (Target_Type, Operand_Type) then
12049 -- Convert: x(y) to x'val (ytyp'val (y))
12051 Rewrite (N,
12052 Make_Attribute_Reference (Loc,
12053 Prefix => New_Occurrence_Of (Target_Type, Loc),
12054 Attribute_Name => Name_Val,
12055 Expressions => New_List (
12056 Make_Attribute_Reference (Loc,
12057 Prefix => New_Occurrence_Of (Operand_Type, Loc),
12058 Attribute_Name => Name_Pos,
12059 Expressions => New_List (Operand)))));
12061 Analyze_And_Resolve (N, Target_Type);
12062 end if;
12063 end if;
12065 -- At this stage, either the conversion node has been transformed into
12066 -- some other equivalent expression, or left as a conversion that can be
12067 -- handled by Gigi, in the following cases:
12069 -- Conversions with no change of representation or type
12071 -- Numeric conversions involving integer, floating- and fixed-point
12072 -- values. Fixed-point values are allowed only if Conversion_OK is
12073 -- set, i.e. if the fixed-point values are to be treated as integers.
12075 -- No other conversions should be passed to Gigi
12077 -- Check: are these rules stated in sinfo??? if so, why restate here???
12079 -- The only remaining step is to generate a range check if we still have
12080 -- a type conversion at this stage and Do_Range_Check is set. Note that
12081 -- we need to deal with at most 8 out of the 9 possible cases of numeric
12082 -- conversions here, because the float-to-integer case is entirely dealt
12083 -- with by Apply_Float_Conversion_Check.
12085 if Nkind (N) = N_Type_Conversion
12086 and then Do_Range_Check (Expression (N))
12087 then
12088 -- Float-to-float conversions
12090 if Is_Floating_Point_Type (Target_Type)
12091 and then Is_Floating_Point_Type (Etype (Expression (N)))
12092 then
12093 -- Reset overflow flag, since the range check will include
12094 -- dealing with possible overflow, and generate the check.
12096 Set_Do_Overflow_Check (N, False);
12098 Generate_Range_Check
12099 (Expression (N), Target_Type, CE_Range_Check_Failed);
12101 -- Discrete-to-discrete conversions or fixed-point-to-discrete
12102 -- conversions when Conversion_OK is set.
12104 elsif Is_Discrete_Type (Target_Type)
12105 and then (Is_Discrete_Type (Etype (Expression (N)))
12106 or else (Is_Fixed_Point_Type (Etype (Expression (N)))
12107 and then Conversion_OK (N)))
12108 then
12109 -- If Address is either a source type or target type,
12110 -- suppress range check to avoid typing anomalies when
12111 -- it is a visible integer type.
12113 if Is_Descendant_Of_Address (Etype (Expression (N)))
12114 or else Is_Descendant_Of_Address (Target_Type)
12115 then
12116 Set_Do_Range_Check (Expression (N), False);
12117 else
12118 Discrete_Range_Check;
12119 end if;
12121 -- Conversions to floating- or fixed-point when Conversion_OK is set
12123 elsif Is_Floating_Point_Type (Target_Type)
12124 or else (Is_Fixed_Point_Type (Target_Type)
12125 and then Conversion_OK (N))
12126 then
12127 Real_Range_Check;
12128 end if;
12129 end if;
12131 -- Here at end of processing
12133 <<Done>>
12134 -- Apply predicate check if required. Note that we can't just call
12135 -- Apply_Predicate_Check here, because the type looks right after
12136 -- the conversion and it would omit the check. The Comes_From_Source
12137 -- guard is necessary to prevent infinite recursions when we generate
12138 -- internal conversions for the purpose of checking predicates.
12140 if Present (Predicate_Function (Target_Type))
12141 and then not Predicates_Ignored (Target_Type)
12142 and then Target_Type /= Operand_Type
12143 and then Comes_From_Source (N)
12144 then
12145 declare
12146 New_Expr : constant Node_Id := Duplicate_Subexpr (N);
12148 begin
12149 -- Avoid infinite recursion on the subsequent expansion of
12150 -- of the copy of the original type conversion. When needed,
12151 -- a range check has already been applied to the expression.
12153 Set_Comes_From_Source (New_Expr, False);
12154 Insert_Action (N,
12155 Make_Predicate_Check (Target_Type, New_Expr),
12156 Suppress => Range_Check);
12157 end;
12158 end if;
12159 end Expand_N_Type_Conversion;
12161 -----------------------------------
12162 -- Expand_N_Unchecked_Expression --
12163 -----------------------------------
12165 -- Remove the unchecked expression node from the tree. Its job was simply
12166 -- to make sure that its constituent expression was handled with checks
12167 -- off, and now that that is done, we can remove it from the tree, and
12168 -- indeed must, since Gigi does not expect to see these nodes.
12170 procedure Expand_N_Unchecked_Expression (N : Node_Id) is
12171 Exp : constant Node_Id := Expression (N);
12172 begin
12173 Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
12174 Rewrite (N, Exp);
12175 end Expand_N_Unchecked_Expression;
12177 ----------------------------------------
12178 -- Expand_N_Unchecked_Type_Conversion --
12179 ----------------------------------------
12181 -- If this cannot be handled by Gigi and we haven't already made a
12182 -- temporary for it, do it now.
12184 procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
12185 Target_Type : constant Entity_Id := Etype (N);
12186 Operand : constant Node_Id := Expression (N);
12187 Operand_Type : constant Entity_Id := Etype (Operand);
12189 begin
12190 -- Nothing at all to do if conversion is to the identical type so remove
12191 -- the conversion completely, it is useless, except that it may carry
12192 -- an Assignment_OK indication which must be propagated to the operand.
12194 if Operand_Type = Target_Type then
12196 -- Code duplicates Expand_N_Unchecked_Expression above, factor???
12198 if Assignment_OK (N) then
12199 Set_Assignment_OK (Operand);
12200 end if;
12202 Rewrite (N, Relocate_Node (Operand));
12203 return;
12204 end if;
12206 -- If we have a conversion of a compile time known value to a target
12207 -- type and the value is in range of the target type, then we can simply
12208 -- replace the construct by an integer literal of the correct type. We
12209 -- only apply this to integer types being converted. Possibly it may
12210 -- apply in other cases, but it is too much trouble to worry about.
12212 -- Note that we do not do this transformation if the Kill_Range_Check
12213 -- flag is set, since then the value may be outside the expected range.
12214 -- This happens in the Normalize_Scalars case.
12216 -- We also skip this if either the target or operand type is biased
12217 -- because in this case, the unchecked conversion is supposed to
12218 -- preserve the bit pattern, not the integer value.
12220 if Is_Integer_Type (Target_Type)
12221 and then not Has_Biased_Representation (Target_Type)
12222 and then Is_Integer_Type (Operand_Type)
12223 and then not Has_Biased_Representation (Operand_Type)
12224 and then Compile_Time_Known_Value (Operand)
12225 and then not Kill_Range_Check (N)
12226 then
12227 declare
12228 Val : constant Uint := Expr_Value (Operand);
12230 begin
12231 if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
12232 and then
12233 Compile_Time_Known_Value (Type_High_Bound (Target_Type))
12234 and then
12235 Val >= Expr_Value (Type_Low_Bound (Target_Type))
12236 and then
12237 Val <= Expr_Value (Type_High_Bound (Target_Type))
12238 then
12239 Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
12241 -- If Address is the target type, just set the type to avoid a
12242 -- spurious type error on the literal when Address is a visible
12243 -- integer type.
12245 if Is_Descendant_Of_Address (Target_Type) then
12246 Set_Etype (N, Target_Type);
12247 else
12248 Analyze_And_Resolve (N, Target_Type);
12249 end if;
12251 return;
12252 end if;
12253 end;
12254 end if;
12256 -- Nothing to do if conversion is safe
12258 if Safe_Unchecked_Type_Conversion (N) then
12259 return;
12260 end if;
12262 -- Otherwise force evaluation unless Assignment_OK flag is set (this
12263 -- flag indicates ??? More comments needed here)
12265 if Assignment_OK (N) then
12266 null;
12267 else
12268 Force_Evaluation (N);
12269 end if;
12270 end Expand_N_Unchecked_Type_Conversion;
12272 ----------------------------
12273 -- Expand_Record_Equality --
12274 ----------------------------
12276 -- For non-variant records, Equality is expanded when needed into:
12278 -- and then Lhs.Discr1 = Rhs.Discr1
12279 -- and then ...
12280 -- and then Lhs.Discrn = Rhs.Discrn
12281 -- and then Lhs.Cmp1 = Rhs.Cmp1
12282 -- and then ...
12283 -- and then Lhs.Cmpn = Rhs.Cmpn
12285 -- The expression is folded by the back end for adjacent fields. This
12286 -- function is called for tagged record in only one occasion: for imple-
12287 -- menting predefined primitive equality (see Predefined_Primitives_Bodies)
12288 -- otherwise the primitive "=" is used directly.
12290 function Expand_Record_Equality
12291 (Nod : Node_Id;
12292 Typ : Entity_Id;
12293 Lhs : Node_Id;
12294 Rhs : Node_Id;
12295 Bodies : List_Id) return Node_Id
12297 Loc : constant Source_Ptr := Sloc (Nod);
12299 Result : Node_Id;
12300 C : Entity_Id;
12302 First_Time : Boolean := True;
12304 function Element_To_Compare (C : Entity_Id) return Entity_Id;
12305 -- Return the next discriminant or component to compare, starting with
12306 -- C, skipping inherited components.
12308 ------------------------
12309 -- Element_To_Compare --
12310 ------------------------
12312 function Element_To_Compare (C : Entity_Id) return Entity_Id is
12313 Comp : Entity_Id;
12315 begin
12316 Comp := C;
12317 loop
12318 -- Exit loop when the next element to be compared is found, or
12319 -- there is no more such element.
12321 exit when No (Comp);
12323 exit when Ekind_In (Comp, E_Discriminant, E_Component)
12324 and then not (
12326 -- Skip inherited components
12328 -- Note: for a tagged type, we always generate the "=" primitive
12329 -- for the base type (not on the first subtype), so the test for
12330 -- Comp /= Original_Record_Component (Comp) is True for
12331 -- inherited components only.
12333 (Is_Tagged_Type (Typ)
12334 and then Comp /= Original_Record_Component (Comp))
12336 -- Skip _Tag
12338 or else Chars (Comp) = Name_uTag
12340 -- Skip interface elements (secondary tags???)
12342 or else Is_Interface (Etype (Comp)));
12344 Next_Entity (Comp);
12345 end loop;
12347 return Comp;
12348 end Element_To_Compare;
12350 -- Start of processing for Expand_Record_Equality
12352 begin
12353 -- Generates the following code: (assuming that Typ has one Discr and
12354 -- component C2 is also a record)
12356 -- Lhs.Discr1 = Rhs.Discr1
12357 -- and then Lhs.C1 = Rhs.C1
12358 -- and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
12359 -- and then ...
12360 -- and then Lhs.Cmpn = Rhs.Cmpn
12362 Result := New_Occurrence_Of (Standard_True, Loc);
12363 C := Element_To_Compare (First_Entity (Typ));
12364 while Present (C) loop
12365 declare
12366 New_Lhs : Node_Id;
12367 New_Rhs : Node_Id;
12368 Check : Node_Id;
12370 begin
12371 if First_Time then
12372 New_Lhs := Lhs;
12373 New_Rhs := Rhs;
12374 else
12375 New_Lhs := New_Copy_Tree (Lhs);
12376 New_Rhs := New_Copy_Tree (Rhs);
12377 end if;
12379 Check :=
12380 Expand_Composite_Equality (Nod, Etype (C),
12381 Lhs =>
12382 Make_Selected_Component (Loc,
12383 Prefix => New_Lhs,
12384 Selector_Name => New_Occurrence_Of (C, Loc)),
12385 Rhs =>
12386 Make_Selected_Component (Loc,
12387 Prefix => New_Rhs,
12388 Selector_Name => New_Occurrence_Of (C, Loc)),
12389 Bodies => Bodies);
12391 -- If some (sub)component is an unchecked_union, the whole
12392 -- operation will raise program error.
12394 if Nkind (Check) = N_Raise_Program_Error then
12395 Result := Check;
12396 Set_Etype (Result, Standard_Boolean);
12397 exit;
12398 else
12399 if First_Time then
12400 Result := Check;
12402 -- Generate logical "and" for CodePeer to simplify the
12403 -- generated code and analysis.
12405 elsif CodePeer_Mode then
12406 Result :=
12407 Make_Op_And (Loc,
12408 Left_Opnd => Result,
12409 Right_Opnd => Check);
12411 else
12412 Result :=
12413 Make_And_Then (Loc,
12414 Left_Opnd => Result,
12415 Right_Opnd => Check);
12416 end if;
12417 end if;
12418 end;
12420 First_Time := False;
12421 C := Element_To_Compare (Next_Entity (C));
12422 end loop;
12424 return Result;
12425 end Expand_Record_Equality;
12427 ---------------------------
12428 -- Expand_Set_Membership --
12429 ---------------------------
12431 procedure Expand_Set_Membership (N : Node_Id) is
12432 Lop : constant Node_Id := Left_Opnd (N);
12433 Alt : Node_Id;
12434 Res : Node_Id;
12436 function Make_Cond (Alt : Node_Id) return Node_Id;
12437 -- If the alternative is a subtype mark, create a simple membership
12438 -- test. Otherwise create an equality test for it.
12440 ---------------
12441 -- Make_Cond --
12442 ---------------
12444 function Make_Cond (Alt : Node_Id) return Node_Id is
12445 Cond : Node_Id;
12446 L : constant Node_Id := New_Copy_Tree (Lop);
12447 R : constant Node_Id := Relocate_Node (Alt);
12449 begin
12450 if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
12451 or else Nkind (Alt) = N_Range
12452 then
12453 Cond :=
12454 Make_In (Sloc (Alt),
12455 Left_Opnd => L,
12456 Right_Opnd => R);
12457 else
12458 Cond :=
12459 Make_Op_Eq (Sloc (Alt),
12460 Left_Opnd => L,
12461 Right_Opnd => R);
12462 end if;
12464 return Cond;
12465 end Make_Cond;
12467 -- Start of processing for Expand_Set_Membership
12469 begin
12470 Remove_Side_Effects (Lop);
12472 Alt := Last (Alternatives (N));
12473 Res := Make_Cond (Alt);
12475 Prev (Alt);
12476 while Present (Alt) loop
12477 Res :=
12478 Make_Or_Else (Sloc (Alt),
12479 Left_Opnd => Make_Cond (Alt),
12480 Right_Opnd => Res);
12481 Prev (Alt);
12482 end loop;
12484 Rewrite (N, Res);
12485 Analyze_And_Resolve (N, Standard_Boolean);
12486 end Expand_Set_Membership;
12488 -----------------------------------
12489 -- Expand_Short_Circuit_Operator --
12490 -----------------------------------
12492 -- Deal with special expansion if actions are present for the right operand
12493 -- and deal with optimizing case of arguments being True or False. We also
12494 -- deal with the special case of non-standard boolean values.
12496 procedure Expand_Short_Circuit_Operator (N : Node_Id) is
12497 Loc : constant Source_Ptr := Sloc (N);
12498 Typ : constant Entity_Id := Etype (N);
12499 Left : constant Node_Id := Left_Opnd (N);
12500 Right : constant Node_Id := Right_Opnd (N);
12501 LocR : constant Source_Ptr := Sloc (Right);
12502 Actlist : List_Id;
12504 Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
12505 Shortcut_Ent : constant Entity_Id := Boolean_Literals (Shortcut_Value);
12506 -- If Left = Shortcut_Value then Right need not be evaluated
12508 function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
12509 -- For Opnd a boolean expression, return a Boolean expression equivalent
12510 -- to Opnd /= Shortcut_Value.
12512 function Useful (Actions : List_Id) return Boolean;
12513 -- Return True if Actions is not empty and contains useful nodes to
12514 -- process.
12516 --------------------
12517 -- Make_Test_Expr --
12518 --------------------
12520 function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
12521 begin
12522 if Shortcut_Value then
12523 return Make_Op_Not (Sloc (Opnd), Opnd);
12524 else
12525 return Opnd;
12526 end if;
12527 end Make_Test_Expr;
12529 ------------
12530 -- Useful --
12531 ------------
12533 function Useful (Actions : List_Id) return Boolean is
12534 L : Node_Id;
12535 begin
12536 if Present (Actions) then
12537 L := First (Actions);
12539 -- For now "useful" means not N_Variable_Reference_Marker.
12540 -- Consider stripping other nodes in the future.
12542 while Present (L) loop
12543 if Nkind (L) /= N_Variable_Reference_Marker then
12544 return True;
12545 end if;
12547 Next (L);
12548 end loop;
12549 end if;
12551 return False;
12552 end Useful;
12554 -- Local variables
12556 Op_Var : Entity_Id;
12557 -- Entity for a temporary variable holding the value of the operator,
12558 -- used for expansion in the case where actions are present.
12560 -- Start of processing for Expand_Short_Circuit_Operator
12562 begin
12563 -- Deal with non-standard booleans
12565 if Is_Boolean_Type (Typ) then
12566 Adjust_Condition (Left);
12567 Adjust_Condition (Right);
12568 Set_Etype (N, Standard_Boolean);
12569 end if;
12571 -- Check for cases where left argument is known to be True or False
12573 if Compile_Time_Known_Value (Left) then
12575 -- Mark SCO for left condition as compile time known
12577 if Generate_SCO and then Comes_From_Source (Left) then
12578 Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
12579 end if;
12581 -- Rewrite True AND THEN Right / False OR ELSE Right to Right.
12582 -- Any actions associated with Right will be executed unconditionally
12583 -- and can thus be inserted into the tree unconditionally.
12585 if Expr_Value_E (Left) /= Shortcut_Ent then
12586 if Present (Actions (N)) then
12587 Insert_Actions (N, Actions (N));
12588 end if;
12590 Rewrite (N, Right);
12592 -- Rewrite False AND THEN Right / True OR ELSE Right to Left.
12593 -- In this case we can forget the actions associated with Right,
12594 -- since they will never be executed.
12596 else
12597 Kill_Dead_Code (Right);
12598 Kill_Dead_Code (Actions (N));
12599 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12600 end if;
12602 Adjust_Result_Type (N, Typ);
12603 return;
12604 end if;
12606 -- If Actions are present for the right operand, we have to do some
12607 -- special processing. We can't just let these actions filter back into
12608 -- code preceding the short circuit (which is what would have happened
12609 -- if we had not trapped them in the short-circuit form), since they
12610 -- must only be executed if the right operand of the short circuit is
12611 -- executed and not otherwise.
12613 if Useful (Actions (N)) then
12614 Actlist := Actions (N);
12616 -- The old approach is to expand:
12618 -- left AND THEN right
12620 -- into
12622 -- C : Boolean := False;
12623 -- IF left THEN
12624 -- Actions;
12625 -- IF right THEN
12626 -- C := True;
12627 -- END IF;
12628 -- END IF;
12630 -- and finally rewrite the operator into a reference to C. Similarly
12631 -- for left OR ELSE right, with negated values. Note that this
12632 -- rewrite causes some difficulties for coverage analysis because
12633 -- of the introduction of the new variable C, which obscures the
12634 -- structure of the test.
12636 -- We use this "old approach" if Minimize_Expression_With_Actions
12637 -- is True.
12639 if Minimize_Expression_With_Actions then
12640 Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
12642 Insert_Action (N,
12643 Make_Object_Declaration (Loc,
12644 Defining_Identifier => Op_Var,
12645 Object_Definition =>
12646 New_Occurrence_Of (Standard_Boolean, Loc),
12647 Expression =>
12648 New_Occurrence_Of (Shortcut_Ent, Loc)));
12650 Append_To (Actlist,
12651 Make_Implicit_If_Statement (Right,
12652 Condition => Make_Test_Expr (Right),
12653 Then_Statements => New_List (
12654 Make_Assignment_Statement (LocR,
12655 Name => New_Occurrence_Of (Op_Var, LocR),
12656 Expression =>
12657 New_Occurrence_Of
12658 (Boolean_Literals (not Shortcut_Value), LocR)))));
12660 Insert_Action (N,
12661 Make_Implicit_If_Statement (Left,
12662 Condition => Make_Test_Expr (Left),
12663 Then_Statements => Actlist));
12665 Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
12666 Analyze_And_Resolve (N, Standard_Boolean);
12668 -- The new approach (the default) is to use an
12669 -- Expression_With_Actions node for the right operand of the
12670 -- short-circuit form. Note that this solves the traceability
12671 -- problems for coverage analysis.
12673 else
12674 Rewrite (Right,
12675 Make_Expression_With_Actions (LocR,
12676 Expression => Relocate_Node (Right),
12677 Actions => Actlist));
12679 Set_Actions (N, No_List);
12680 Analyze_And_Resolve (Right, Standard_Boolean);
12681 end if;
12683 Adjust_Result_Type (N, Typ);
12684 return;
12685 end if;
12687 -- No actions present, check for cases of right argument True/False
12689 if Compile_Time_Known_Value (Right) then
12691 -- Mark SCO for left condition as compile time known
12693 if Generate_SCO and then Comes_From_Source (Right) then
12694 Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
12695 end if;
12697 -- Change (Left and then True), (Left or else False) to Left. Note
12698 -- that we know there are no actions associated with the right
12699 -- operand, since we just checked for this case above.
12701 if Expr_Value_E (Right) /= Shortcut_Ent then
12702 Rewrite (N, Left);
12704 -- Change (Left and then False), (Left or else True) to Right,
12705 -- making sure to preserve any side effects associated with the Left
12706 -- operand.
12708 else
12709 Remove_Side_Effects (Left);
12710 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12711 end if;
12712 end if;
12714 Adjust_Result_Type (N, Typ);
12715 end Expand_Short_Circuit_Operator;
12717 ------------------------------------
12718 -- Fixup_Universal_Fixed_Operation --
12719 -------------------------------------
12721 procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
12722 Conv : constant Node_Id := Parent (N);
12724 begin
12725 -- We must have a type conversion immediately above us
12727 pragma Assert (Nkind (Conv) = N_Type_Conversion);
12729 -- Normally the type conversion gives our target type. The exception
12730 -- occurs in the case of the Round attribute, where the conversion
12731 -- will be to universal real, and our real type comes from the Round
12732 -- attribute (as well as an indication that we must round the result)
12734 if Nkind (Parent (Conv)) = N_Attribute_Reference
12735 and then Attribute_Name (Parent (Conv)) = Name_Round
12736 then
12737 Set_Etype (N, Base_Type (Etype (Parent (Conv))));
12738 Set_Rounded_Result (N);
12740 -- Normal case where type comes from conversion above us
12742 else
12743 Set_Etype (N, Base_Type (Etype (Conv)));
12744 end if;
12745 end Fixup_Universal_Fixed_Operation;
12747 ---------------------------------
12748 -- Has_Inferable_Discriminants --
12749 ---------------------------------
12751 function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
12753 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
12754 -- Determines whether the left-most prefix of a selected component is a
12755 -- formal parameter in a subprogram. Assumes N is a selected component.
12757 --------------------------------
12758 -- Prefix_Is_Formal_Parameter --
12759 --------------------------------
12761 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
12762 Sel_Comp : Node_Id;
12764 begin
12765 -- Move to the left-most prefix by climbing up the tree
12767 Sel_Comp := N;
12768 while Present (Parent (Sel_Comp))
12769 and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
12770 loop
12771 Sel_Comp := Parent (Sel_Comp);
12772 end loop;
12774 return Is_Formal (Entity (Prefix (Sel_Comp)));
12775 end Prefix_Is_Formal_Parameter;
12777 -- Start of processing for Has_Inferable_Discriminants
12779 begin
12780 -- For selected components, the subtype of the selector must be a
12781 -- constrained Unchecked_Union. If the component is subject to a
12782 -- per-object constraint, then the enclosing object must have inferable
12783 -- discriminants.
12785 if Nkind (N) = N_Selected_Component then
12786 if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
12788 -- A small hack. If we have a per-object constrained selected
12789 -- component of a formal parameter, return True since we do not
12790 -- know the actual parameter association yet.
12792 if Prefix_Is_Formal_Parameter (N) then
12793 return True;
12795 -- Otherwise, check the enclosing object and the selector
12797 else
12798 return Has_Inferable_Discriminants (Prefix (N))
12799 and then Has_Inferable_Discriminants (Selector_Name (N));
12800 end if;
12802 -- The call to Has_Inferable_Discriminants will determine whether
12803 -- the selector has a constrained Unchecked_Union nominal type.
12805 else
12806 return Has_Inferable_Discriminants (Selector_Name (N));
12807 end if;
12809 -- A qualified expression has inferable discriminants if its subtype
12810 -- mark is a constrained Unchecked_Union subtype.
12812 elsif Nkind (N) = N_Qualified_Expression then
12813 return Is_Unchecked_Union (Etype (Subtype_Mark (N)))
12814 and then Is_Constrained (Etype (Subtype_Mark (N)));
12816 -- For all other names, it is sufficient to have a constrained
12817 -- Unchecked_Union nominal subtype.
12819 else
12820 return Is_Unchecked_Union (Base_Type (Etype (N)))
12821 and then Is_Constrained (Etype (N));
12822 end if;
12823 end Has_Inferable_Discriminants;
12825 -------------------------------
12826 -- Insert_Dereference_Action --
12827 -------------------------------
12829 procedure Insert_Dereference_Action (N : Node_Id) is
12830 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
12831 -- Return true if type of P is derived from Checked_Pool;
12833 -----------------------------
12834 -- Is_Checked_Storage_Pool --
12835 -----------------------------
12837 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
12838 T : Entity_Id;
12840 begin
12841 if No (P) then
12842 return False;
12843 end if;
12845 T := Etype (P);
12846 while T /= Etype (T) loop
12847 if Is_RTE (T, RE_Checked_Pool) then
12848 return True;
12849 else
12850 T := Etype (T);
12851 end if;
12852 end loop;
12854 return False;
12855 end Is_Checked_Storage_Pool;
12857 -- Local variables
12859 Context : constant Node_Id := Parent (N);
12860 Ptr_Typ : constant Entity_Id := Etype (N);
12861 Desig_Typ : constant Entity_Id :=
12862 Available_View (Designated_Type (Ptr_Typ));
12863 Loc : constant Source_Ptr := Sloc (N);
12864 Pool : constant Entity_Id := Associated_Storage_Pool (Ptr_Typ);
12866 Addr : Entity_Id;
12867 Alig : Entity_Id;
12868 Deref : Node_Id;
12869 Size : Entity_Id;
12870 Size_Bits : Node_Id;
12871 Stmt : Node_Id;
12873 -- Start of processing for Insert_Dereference_Action
12875 begin
12876 pragma Assert (Nkind (Context) = N_Explicit_Dereference);
12878 -- Do not re-expand a dereference which has already been processed by
12879 -- this routine.
12881 if Has_Dereference_Action (Context) then
12882 return;
12884 -- Do not perform this type of expansion for internally-generated
12885 -- dereferences.
12887 elsif not Comes_From_Source (Original_Node (Context)) then
12888 return;
12890 -- A dereference action is only applicable to objects which have been
12891 -- allocated on a checked pool.
12893 elsif not Is_Checked_Storage_Pool (Pool) then
12894 return;
12895 end if;
12897 -- Extract the address of the dereferenced object. Generate:
12899 -- Addr : System.Address := <N>'Pool_Address;
12901 Addr := Make_Temporary (Loc, 'P');
12903 Insert_Action (N,
12904 Make_Object_Declaration (Loc,
12905 Defining_Identifier => Addr,
12906 Object_Definition =>
12907 New_Occurrence_Of (RTE (RE_Address), Loc),
12908 Expression =>
12909 Make_Attribute_Reference (Loc,
12910 Prefix => Duplicate_Subexpr_Move_Checks (N),
12911 Attribute_Name => Name_Pool_Address)));
12913 -- Calculate the size of the dereferenced object. Generate:
12915 -- Size : Storage_Count := <N>.all'Size / Storage_Unit;
12917 Deref :=
12918 Make_Explicit_Dereference (Loc,
12919 Prefix => Duplicate_Subexpr_Move_Checks (N));
12920 Set_Has_Dereference_Action (Deref);
12922 Size_Bits :=
12923 Make_Attribute_Reference (Loc,
12924 Prefix => Deref,
12925 Attribute_Name => Name_Size);
12927 -- Special case of an unconstrained array: need to add descriptor size
12929 if Is_Array_Type (Desig_Typ)
12930 and then not Is_Constrained (First_Subtype (Desig_Typ))
12931 then
12932 Size_Bits :=
12933 Make_Op_Add (Loc,
12934 Left_Opnd =>
12935 Make_Attribute_Reference (Loc,
12936 Prefix =>
12937 New_Occurrence_Of (First_Subtype (Desig_Typ), Loc),
12938 Attribute_Name => Name_Descriptor_Size),
12939 Right_Opnd => Size_Bits);
12940 end if;
12942 Size := Make_Temporary (Loc, 'S');
12943 Insert_Action (N,
12944 Make_Object_Declaration (Loc,
12945 Defining_Identifier => Size,
12946 Object_Definition =>
12947 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12948 Expression =>
12949 Make_Op_Divide (Loc,
12950 Left_Opnd => Size_Bits,
12951 Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
12953 -- Calculate the alignment of the dereferenced object. Generate:
12954 -- Alig : constant Storage_Count := <N>.all'Alignment;
12956 Deref :=
12957 Make_Explicit_Dereference (Loc,
12958 Prefix => Duplicate_Subexpr_Move_Checks (N));
12959 Set_Has_Dereference_Action (Deref);
12961 Alig := Make_Temporary (Loc, 'A');
12962 Insert_Action (N,
12963 Make_Object_Declaration (Loc,
12964 Defining_Identifier => Alig,
12965 Object_Definition =>
12966 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12967 Expression =>
12968 Make_Attribute_Reference (Loc,
12969 Prefix => Deref,
12970 Attribute_Name => Name_Alignment)));
12972 -- A dereference of a controlled object requires special processing. The
12973 -- finalization machinery requests additional space from the underlying
12974 -- pool to allocate and hide two pointers. As a result, a checked pool
12975 -- may mark the wrong memory as valid. Since checked pools do not have
12976 -- knowledge of hidden pointers, we have to bring the two pointers back
12977 -- in view in order to restore the original state of the object.
12979 -- The address manipulation is not performed for access types that are
12980 -- subject to pragma No_Heap_Finalization because the two pointers do
12981 -- not exist in the first place.
12983 if No_Heap_Finalization (Ptr_Typ) then
12984 null;
12986 elsif Needs_Finalization (Desig_Typ) then
12988 -- Adjust the address and size of the dereferenced object. Generate:
12989 -- Adjust_Controlled_Dereference (Addr, Size, Alig);
12991 Stmt :=
12992 Make_Procedure_Call_Statement (Loc,
12993 Name =>
12994 New_Occurrence_Of (RTE (RE_Adjust_Controlled_Dereference), Loc),
12995 Parameter_Associations => New_List (
12996 New_Occurrence_Of (Addr, Loc),
12997 New_Occurrence_Of (Size, Loc),
12998 New_Occurrence_Of (Alig, Loc)));
13000 -- Class-wide types complicate things because we cannot determine
13001 -- statically whether the actual object is truly controlled. We must
13002 -- generate a runtime check to detect this property. Generate:
13004 -- if Needs_Finalization (<N>.all'Tag) then
13005 -- <Stmt>;
13006 -- end if;
13008 if Is_Class_Wide_Type (Desig_Typ) then
13009 Deref :=
13010 Make_Explicit_Dereference (Loc,
13011 Prefix => Duplicate_Subexpr_Move_Checks (N));
13012 Set_Has_Dereference_Action (Deref);
13014 Stmt :=
13015 Make_Implicit_If_Statement (N,
13016 Condition =>
13017 Make_Function_Call (Loc,
13018 Name =>
13019 New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
13020 Parameter_Associations => New_List (
13021 Make_Attribute_Reference (Loc,
13022 Prefix => Deref,
13023 Attribute_Name => Name_Tag))),
13024 Then_Statements => New_List (Stmt));
13025 end if;
13027 Insert_Action (N, Stmt);
13028 end if;
13030 -- Generate:
13031 -- Dereference (Pool, Addr, Size, Alig);
13033 Insert_Action (N,
13034 Make_Procedure_Call_Statement (Loc,
13035 Name =>
13036 New_Occurrence_Of
13037 (Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
13038 Parameter_Associations => New_List (
13039 New_Occurrence_Of (Pool, Loc),
13040 New_Occurrence_Of (Addr, Loc),
13041 New_Occurrence_Of (Size, Loc),
13042 New_Occurrence_Of (Alig, Loc))));
13044 -- Mark the explicit dereference as processed to avoid potential
13045 -- infinite expansion.
13047 Set_Has_Dereference_Action (Context);
13049 exception
13050 when RE_Not_Available =>
13051 return;
13052 end Insert_Dereference_Action;
13054 --------------------------------
13055 -- Integer_Promotion_Possible --
13056 --------------------------------
13058 function Integer_Promotion_Possible (N : Node_Id) return Boolean is
13059 Operand : constant Node_Id := Expression (N);
13060 Operand_Type : constant Entity_Id := Etype (Operand);
13061 Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
13063 begin
13064 pragma Assert (Nkind (N) = N_Type_Conversion);
13066 return
13068 -- We only do the transformation for source constructs. We assume
13069 -- that the expander knows what it is doing when it generates code.
13071 Comes_From_Source (N)
13073 -- If the operand type is Short_Integer or Short_Short_Integer,
13074 -- then we will promote to Integer, which is available on all
13075 -- targets, and is sufficient to ensure no intermediate overflow.
13076 -- Furthermore it is likely to be as efficient or more efficient
13077 -- than using the smaller type for the computation so we do this
13078 -- unconditionally.
13080 and then
13081 (Root_Operand_Type = Base_Type (Standard_Short_Integer)
13082 or else
13083 Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
13085 -- Test for interesting operation, which includes addition,
13086 -- division, exponentiation, multiplication, subtraction, absolute
13087 -- value and unary negation. Unary "+" is omitted since it is a
13088 -- no-op and thus can't overflow.
13090 and then Nkind_In (Operand, N_Op_Abs,
13091 N_Op_Add,
13092 N_Op_Divide,
13093 N_Op_Expon,
13094 N_Op_Minus,
13095 N_Op_Multiply,
13096 N_Op_Subtract);
13097 end Integer_Promotion_Possible;
13099 ------------------------------
13100 -- Make_Array_Comparison_Op --
13101 ------------------------------
13103 -- This is a hand-coded expansion of the following generic function:
13105 -- generic
13106 -- type elem is (<>);
13107 -- type index is (<>);
13108 -- type a is array (index range <>) of elem;
13110 -- function Gnnn (X : a; Y: a) return boolean is
13111 -- J : index := Y'first;
13113 -- begin
13114 -- if X'length = 0 then
13115 -- return false;
13117 -- elsif Y'length = 0 then
13118 -- return true;
13120 -- else
13121 -- for I in X'range loop
13122 -- if X (I) = Y (J) then
13123 -- if J = Y'last then
13124 -- exit;
13125 -- else
13126 -- J := index'succ (J);
13127 -- end if;
13129 -- else
13130 -- return X (I) > Y (J);
13131 -- end if;
13132 -- end loop;
13134 -- return X'length > Y'length;
13135 -- end if;
13136 -- end Gnnn;
13138 -- Note that since we are essentially doing this expansion by hand, we
13139 -- do not need to generate an actual or formal generic part, just the
13140 -- instantiated function itself.
13142 -- Perhaps we could have the actual generic available in the run-time,
13143 -- obtained by rtsfind, and actually expand a real instantiation ???
13145 function Make_Array_Comparison_Op
13146 (Typ : Entity_Id;
13147 Nod : Node_Id) return Node_Id
13149 Loc : constant Source_Ptr := Sloc (Nod);
13151 X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
13152 Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
13153 I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
13154 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
13156 Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
13158 Loop_Statement : Node_Id;
13159 Loop_Body : Node_Id;
13160 If_Stat : Node_Id;
13161 Inner_If : Node_Id;
13162 Final_Expr : Node_Id;
13163 Func_Body : Node_Id;
13164 Func_Name : Entity_Id;
13165 Formals : List_Id;
13166 Length1 : Node_Id;
13167 Length2 : Node_Id;
13169 begin
13170 -- if J = Y'last then
13171 -- exit;
13172 -- else
13173 -- J := index'succ (J);
13174 -- end if;
13176 Inner_If :=
13177 Make_Implicit_If_Statement (Nod,
13178 Condition =>
13179 Make_Op_Eq (Loc,
13180 Left_Opnd => New_Occurrence_Of (J, Loc),
13181 Right_Opnd =>
13182 Make_Attribute_Reference (Loc,
13183 Prefix => New_Occurrence_Of (Y, Loc),
13184 Attribute_Name => Name_Last)),
13186 Then_Statements => New_List (
13187 Make_Exit_Statement (Loc)),
13189 Else_Statements =>
13190 New_List (
13191 Make_Assignment_Statement (Loc,
13192 Name => New_Occurrence_Of (J, Loc),
13193 Expression =>
13194 Make_Attribute_Reference (Loc,
13195 Prefix => New_Occurrence_Of (Index, Loc),
13196 Attribute_Name => Name_Succ,
13197 Expressions => New_List (New_Occurrence_Of (J, Loc))))));
13199 -- if X (I) = Y (J) then
13200 -- if ... end if;
13201 -- else
13202 -- return X (I) > Y (J);
13203 -- end if;
13205 Loop_Body :=
13206 Make_Implicit_If_Statement (Nod,
13207 Condition =>
13208 Make_Op_Eq (Loc,
13209 Left_Opnd =>
13210 Make_Indexed_Component (Loc,
13211 Prefix => New_Occurrence_Of (X, Loc),
13212 Expressions => New_List (New_Occurrence_Of (I, Loc))),
13214 Right_Opnd =>
13215 Make_Indexed_Component (Loc,
13216 Prefix => New_Occurrence_Of (Y, Loc),
13217 Expressions => New_List (New_Occurrence_Of (J, Loc)))),
13219 Then_Statements => New_List (Inner_If),
13221 Else_Statements => New_List (
13222 Make_Simple_Return_Statement (Loc,
13223 Expression =>
13224 Make_Op_Gt (Loc,
13225 Left_Opnd =>
13226 Make_Indexed_Component (Loc,
13227 Prefix => New_Occurrence_Of (X, Loc),
13228 Expressions => New_List (New_Occurrence_Of (I, Loc))),
13230 Right_Opnd =>
13231 Make_Indexed_Component (Loc,
13232 Prefix => New_Occurrence_Of (Y, Loc),
13233 Expressions => New_List (
13234 New_Occurrence_Of (J, Loc)))))));
13236 -- for I in X'range loop
13237 -- if ... end if;
13238 -- end loop;
13240 Loop_Statement :=
13241 Make_Implicit_Loop_Statement (Nod,
13242 Identifier => Empty,
13244 Iteration_Scheme =>
13245 Make_Iteration_Scheme (Loc,
13246 Loop_Parameter_Specification =>
13247 Make_Loop_Parameter_Specification (Loc,
13248 Defining_Identifier => I,
13249 Discrete_Subtype_Definition =>
13250 Make_Attribute_Reference (Loc,
13251 Prefix => New_Occurrence_Of (X, Loc),
13252 Attribute_Name => Name_Range))),
13254 Statements => New_List (Loop_Body));
13256 -- if X'length = 0 then
13257 -- return false;
13258 -- elsif Y'length = 0 then
13259 -- return true;
13260 -- else
13261 -- for ... loop ... end loop;
13262 -- return X'length > Y'length;
13263 -- end if;
13265 Length1 :=
13266 Make_Attribute_Reference (Loc,
13267 Prefix => New_Occurrence_Of (X, Loc),
13268 Attribute_Name => Name_Length);
13270 Length2 :=
13271 Make_Attribute_Reference (Loc,
13272 Prefix => New_Occurrence_Of (Y, Loc),
13273 Attribute_Name => Name_Length);
13275 Final_Expr :=
13276 Make_Op_Gt (Loc,
13277 Left_Opnd => Length1,
13278 Right_Opnd => Length2);
13280 If_Stat :=
13281 Make_Implicit_If_Statement (Nod,
13282 Condition =>
13283 Make_Op_Eq (Loc,
13284 Left_Opnd =>
13285 Make_Attribute_Reference (Loc,
13286 Prefix => New_Occurrence_Of (X, Loc),
13287 Attribute_Name => Name_Length),
13288 Right_Opnd =>
13289 Make_Integer_Literal (Loc, 0)),
13291 Then_Statements =>
13292 New_List (
13293 Make_Simple_Return_Statement (Loc,
13294 Expression => New_Occurrence_Of (Standard_False, Loc))),
13296 Elsif_Parts => New_List (
13297 Make_Elsif_Part (Loc,
13298 Condition =>
13299 Make_Op_Eq (Loc,
13300 Left_Opnd =>
13301 Make_Attribute_Reference (Loc,
13302 Prefix => New_Occurrence_Of (Y, Loc),
13303 Attribute_Name => Name_Length),
13304 Right_Opnd =>
13305 Make_Integer_Literal (Loc, 0)),
13307 Then_Statements =>
13308 New_List (
13309 Make_Simple_Return_Statement (Loc,
13310 Expression => New_Occurrence_Of (Standard_True, Loc))))),
13312 Else_Statements => New_List (
13313 Loop_Statement,
13314 Make_Simple_Return_Statement (Loc,
13315 Expression => Final_Expr)));
13317 -- (X : a; Y: a)
13319 Formals := New_List (
13320 Make_Parameter_Specification (Loc,
13321 Defining_Identifier => X,
13322 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
13324 Make_Parameter_Specification (Loc,
13325 Defining_Identifier => Y,
13326 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
13328 -- function Gnnn (...) return boolean is
13329 -- J : index := Y'first;
13330 -- begin
13331 -- if ... end if;
13332 -- end Gnnn;
13334 Func_Name := Make_Temporary (Loc, 'G');
13336 Func_Body :=
13337 Make_Subprogram_Body (Loc,
13338 Specification =>
13339 Make_Function_Specification (Loc,
13340 Defining_Unit_Name => Func_Name,
13341 Parameter_Specifications => Formals,
13342 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
13344 Declarations => New_List (
13345 Make_Object_Declaration (Loc,
13346 Defining_Identifier => J,
13347 Object_Definition => New_Occurrence_Of (Index, Loc),
13348 Expression =>
13349 Make_Attribute_Reference (Loc,
13350 Prefix => New_Occurrence_Of (Y, Loc),
13351 Attribute_Name => Name_First))),
13353 Handled_Statement_Sequence =>
13354 Make_Handled_Sequence_Of_Statements (Loc,
13355 Statements => New_List (If_Stat)));
13357 return Func_Body;
13358 end Make_Array_Comparison_Op;
13360 ---------------------------
13361 -- Make_Boolean_Array_Op --
13362 ---------------------------
13364 -- For logical operations on boolean arrays, expand in line the following,
13365 -- replacing 'and' with 'or' or 'xor' where needed:
13367 -- function Annn (A : typ; B: typ) return typ is
13368 -- C : typ;
13369 -- begin
13370 -- for J in A'range loop
13371 -- C (J) := A (J) op B (J);
13372 -- end loop;
13373 -- return C;
13374 -- end Annn;
13376 -- Here typ is the boolean array type
13378 function Make_Boolean_Array_Op
13379 (Typ : Entity_Id;
13380 N : Node_Id) return Node_Id
13382 Loc : constant Source_Ptr := Sloc (N);
13384 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
13385 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
13386 C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
13387 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
13389 A_J : Node_Id;
13390 B_J : Node_Id;
13391 C_J : Node_Id;
13392 Op : Node_Id;
13394 Formals : List_Id;
13395 Func_Name : Entity_Id;
13396 Func_Body : Node_Id;
13397 Loop_Statement : Node_Id;
13399 begin
13400 A_J :=
13401 Make_Indexed_Component (Loc,
13402 Prefix => New_Occurrence_Of (A, Loc),
13403 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13405 B_J :=
13406 Make_Indexed_Component (Loc,
13407 Prefix => New_Occurrence_Of (B, Loc),
13408 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13410 C_J :=
13411 Make_Indexed_Component (Loc,
13412 Prefix => New_Occurrence_Of (C, Loc),
13413 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13415 if Nkind (N) = N_Op_And then
13416 Op :=
13417 Make_Op_And (Loc,
13418 Left_Opnd => A_J,
13419 Right_Opnd => B_J);
13421 elsif Nkind (N) = N_Op_Or then
13422 Op :=
13423 Make_Op_Or (Loc,
13424 Left_Opnd => A_J,
13425 Right_Opnd => B_J);
13427 else
13428 Op :=
13429 Make_Op_Xor (Loc,
13430 Left_Opnd => A_J,
13431 Right_Opnd => B_J);
13432 end if;
13434 Loop_Statement :=
13435 Make_Implicit_Loop_Statement (N,
13436 Identifier => Empty,
13438 Iteration_Scheme =>
13439 Make_Iteration_Scheme (Loc,
13440 Loop_Parameter_Specification =>
13441 Make_Loop_Parameter_Specification (Loc,
13442 Defining_Identifier => J,
13443 Discrete_Subtype_Definition =>
13444 Make_Attribute_Reference (Loc,
13445 Prefix => New_Occurrence_Of (A, Loc),
13446 Attribute_Name => Name_Range))),
13448 Statements => New_List (
13449 Make_Assignment_Statement (Loc,
13450 Name => C_J,
13451 Expression => Op)));
13453 Formals := New_List (
13454 Make_Parameter_Specification (Loc,
13455 Defining_Identifier => A,
13456 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
13458 Make_Parameter_Specification (Loc,
13459 Defining_Identifier => B,
13460 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
13462 Func_Name := Make_Temporary (Loc, 'A');
13463 Set_Is_Inlined (Func_Name);
13465 Func_Body :=
13466 Make_Subprogram_Body (Loc,
13467 Specification =>
13468 Make_Function_Specification (Loc,
13469 Defining_Unit_Name => Func_Name,
13470 Parameter_Specifications => Formals,
13471 Result_Definition => New_Occurrence_Of (Typ, Loc)),
13473 Declarations => New_List (
13474 Make_Object_Declaration (Loc,
13475 Defining_Identifier => C,
13476 Object_Definition => New_Occurrence_Of (Typ, Loc))),
13478 Handled_Statement_Sequence =>
13479 Make_Handled_Sequence_Of_Statements (Loc,
13480 Statements => New_List (
13481 Loop_Statement,
13482 Make_Simple_Return_Statement (Loc,
13483 Expression => New_Occurrence_Of (C, Loc)))));
13485 return Func_Body;
13486 end Make_Boolean_Array_Op;
13488 -----------------------------------------
13489 -- Minimized_Eliminated_Overflow_Check --
13490 -----------------------------------------
13492 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean is
13493 begin
13494 return
13495 Is_Signed_Integer_Type (Etype (N))
13496 and then Overflow_Check_Mode in Minimized_Or_Eliminated;
13497 end Minimized_Eliminated_Overflow_Check;
13499 --------------------------------
13500 -- Optimize_Length_Comparison --
13501 --------------------------------
13503 procedure Optimize_Length_Comparison (N : Node_Id) is
13504 Loc : constant Source_Ptr := Sloc (N);
13505 Typ : constant Entity_Id := Etype (N);
13506 Result : Node_Id;
13508 Left : Node_Id;
13509 Right : Node_Id;
13510 -- First and Last attribute reference nodes, which end up as left and
13511 -- right operands of the optimized result.
13513 Is_Zero : Boolean;
13514 -- True for comparison operand of zero
13516 Comp : Node_Id;
13517 -- Comparison operand, set only if Is_Zero is false
13519 Ent : Entity_Id := Empty;
13520 -- Entity whose length is being compared
13522 Index : Node_Id := Empty;
13523 -- Integer_Literal node for length attribute expression, or Empty
13524 -- if there is no such expression present.
13526 Ityp : Entity_Id;
13527 -- Type of array index to which 'Length is applied
13529 Op : Node_Kind := Nkind (N);
13530 -- Kind of comparison operator, gets flipped if operands backwards
13532 function Is_Optimizable (N : Node_Id) return Boolean;
13533 -- Tests N to see if it is an optimizable comparison value (defined as
13534 -- constant zero or one, or something else where the value is known to
13535 -- be positive and in the range of 32-bits, and where the corresponding
13536 -- Length value is also known to be 32-bits. If result is true, sets
13537 -- Is_Zero, Ityp, and Comp accordingly.
13539 function Is_Entity_Length (N : Node_Id) return Boolean;
13540 -- Tests if N is a length attribute applied to a simple entity. If so,
13541 -- returns True, and sets Ent to the entity, and Index to the integer
13542 -- literal provided as an attribute expression, or to Empty if none.
13543 -- Also returns True if the expression is a generated type conversion
13544 -- whose expression is of the desired form. This latter case arises
13545 -- when Apply_Universal_Integer_Attribute_Check installs a conversion
13546 -- to check for being in range, which is not needed in this context.
13547 -- Returns False if neither condition holds.
13549 function Prepare_64 (N : Node_Id) return Node_Id;
13550 -- Given a discrete expression, returns a Long_Long_Integer typed
13551 -- expression representing the underlying value of the expression.
13552 -- This is done with an unchecked conversion to the result type. We
13553 -- use unchecked conversion to handle the enumeration type case.
13555 ----------------------
13556 -- Is_Entity_Length --
13557 ----------------------
13559 function Is_Entity_Length (N : Node_Id) return Boolean is
13560 begin
13561 if Nkind (N) = N_Attribute_Reference
13562 and then Attribute_Name (N) = Name_Length
13563 and then Is_Entity_Name (Prefix (N))
13564 then
13565 Ent := Entity (Prefix (N));
13567 if Present (Expressions (N)) then
13568 Index := First (Expressions (N));
13569 else
13570 Index := Empty;
13571 end if;
13573 return True;
13575 elsif Nkind (N) = N_Type_Conversion
13576 and then not Comes_From_Source (N)
13577 then
13578 return Is_Entity_Length (Expression (N));
13580 else
13581 return False;
13582 end if;
13583 end Is_Entity_Length;
13585 --------------------
13586 -- Is_Optimizable --
13587 --------------------
13589 function Is_Optimizable (N : Node_Id) return Boolean is
13590 Val : Uint;
13591 OK : Boolean;
13592 Lo : Uint;
13593 Hi : Uint;
13594 Indx : Node_Id;
13596 begin
13597 if Compile_Time_Known_Value (N) then
13598 Val := Expr_Value (N);
13600 if Val = Uint_0 then
13601 Is_Zero := True;
13602 Comp := Empty;
13603 return True;
13605 elsif Val = Uint_1 then
13606 Is_Zero := False;
13607 Comp := Empty;
13608 return True;
13609 end if;
13610 end if;
13612 -- Here we have to make sure of being within 32-bits
13614 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
13616 if not OK
13617 or else Lo < Uint_1
13618 or else Hi > UI_From_Int (Int'Last)
13619 then
13620 return False;
13621 end if;
13623 -- Comparison value was within range, so now we must check the index
13624 -- value to make sure it is also within 32-bits.
13626 Indx := First_Index (Etype (Ent));
13628 if Present (Index) then
13629 for J in 2 .. UI_To_Int (Intval (Index)) loop
13630 Next_Index (Indx);
13631 end loop;
13632 end if;
13634 Ityp := Etype (Indx);
13636 if Esize (Ityp) > 32 then
13637 return False;
13638 end if;
13640 Is_Zero := False;
13641 Comp := N;
13642 return True;
13643 end Is_Optimizable;
13645 ----------------
13646 -- Prepare_64 --
13647 ----------------
13649 function Prepare_64 (N : Node_Id) return Node_Id is
13650 begin
13651 return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
13652 end Prepare_64;
13654 -- Start of processing for Optimize_Length_Comparison
13656 begin
13657 -- Nothing to do if not a comparison
13659 if Op not in N_Op_Compare then
13660 return;
13661 end if;
13663 -- Nothing to do if special -gnatd.P debug flag set.
13665 if Debug_Flag_Dot_PP then
13666 return;
13667 end if;
13669 -- Ent'Length op 0/1
13671 if Is_Entity_Length (Left_Opnd (N))
13672 and then Is_Optimizable (Right_Opnd (N))
13673 then
13674 null;
13676 -- 0/1 op Ent'Length
13678 elsif Is_Entity_Length (Right_Opnd (N))
13679 and then Is_Optimizable (Left_Opnd (N))
13680 then
13681 -- Flip comparison to opposite sense
13683 case Op is
13684 when N_Op_Lt => Op := N_Op_Gt;
13685 when N_Op_Le => Op := N_Op_Ge;
13686 when N_Op_Gt => Op := N_Op_Lt;
13687 when N_Op_Ge => Op := N_Op_Le;
13688 when others => null;
13689 end case;
13691 -- Else optimization not possible
13693 else
13694 return;
13695 end if;
13697 -- Fall through if we will do the optimization
13699 -- Cases to handle:
13701 -- X'Length = 0 => X'First > X'Last
13702 -- X'Length = 1 => X'First = X'Last
13703 -- X'Length = n => X'First + (n - 1) = X'Last
13705 -- X'Length /= 0 => X'First <= X'Last
13706 -- X'Length /= 1 => X'First /= X'Last
13707 -- X'Length /= n => X'First + (n - 1) /= X'Last
13709 -- X'Length >= 0 => always true, warn
13710 -- X'Length >= 1 => X'First <= X'Last
13711 -- X'Length >= n => X'First + (n - 1) <= X'Last
13713 -- X'Length > 0 => X'First <= X'Last
13714 -- X'Length > 1 => X'First < X'Last
13715 -- X'Length > n => X'First + (n - 1) < X'Last
13717 -- X'Length <= 0 => X'First > X'Last (warn, could be =)
13718 -- X'Length <= 1 => X'First >= X'Last
13719 -- X'Length <= n => X'First + (n - 1) >= X'Last
13721 -- X'Length < 0 => always false (warn)
13722 -- X'Length < 1 => X'First > X'Last
13723 -- X'Length < n => X'First + (n - 1) > X'Last
13725 -- Note: for the cases of n (not constant 0,1), we require that the
13726 -- corresponding index type be integer or shorter (i.e. not 64-bit),
13727 -- and the same for the comparison value. Then we do the comparison
13728 -- using 64-bit arithmetic (actually long long integer), so that we
13729 -- cannot have overflow intefering with the result.
13731 -- First deal with warning cases
13733 if Is_Zero then
13734 case Op is
13736 -- X'Length >= 0
13738 when N_Op_Ge =>
13739 Rewrite (N,
13740 Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
13741 Analyze_And_Resolve (N, Typ);
13742 Warn_On_Known_Condition (N);
13743 return;
13745 -- X'Length < 0
13747 when N_Op_Lt =>
13748 Rewrite (N,
13749 Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
13750 Analyze_And_Resolve (N, Typ);
13751 Warn_On_Known_Condition (N);
13752 return;
13754 when N_Op_Le =>
13755 if Constant_Condition_Warnings
13756 and then Comes_From_Source (Original_Node (N))
13757 then
13758 Error_Msg_N ("could replace by ""'=""?c?", N);
13759 end if;
13761 Op := N_Op_Eq;
13763 when others =>
13764 null;
13765 end case;
13766 end if;
13768 -- Build the First reference we will use
13770 Left :=
13771 Make_Attribute_Reference (Loc,
13772 Prefix => New_Occurrence_Of (Ent, Loc),
13773 Attribute_Name => Name_First);
13775 if Present (Index) then
13776 Set_Expressions (Left, New_List (New_Copy (Index)));
13777 end if;
13779 -- If general value case, then do the addition of (n - 1), and
13780 -- also add the needed conversions to type Long_Long_Integer.
13782 if Present (Comp) then
13783 Left :=
13784 Make_Op_Add (Loc,
13785 Left_Opnd => Prepare_64 (Left),
13786 Right_Opnd =>
13787 Make_Op_Subtract (Loc,
13788 Left_Opnd => Prepare_64 (Comp),
13789 Right_Opnd => Make_Integer_Literal (Loc, 1)));
13790 end if;
13792 -- Build the Last reference we will use
13794 Right :=
13795 Make_Attribute_Reference (Loc,
13796 Prefix => New_Occurrence_Of (Ent, Loc),
13797 Attribute_Name => Name_Last);
13799 if Present (Index) then
13800 Set_Expressions (Right, New_List (New_Copy (Index)));
13801 end if;
13803 -- If general operand, convert Last reference to Long_Long_Integer
13805 if Present (Comp) then
13806 Right := Prepare_64 (Right);
13807 end if;
13809 -- Check for cases to optimize
13811 -- X'Length = 0 => X'First > X'Last
13812 -- X'Length < 1 => X'First > X'Last
13813 -- X'Length < n => X'First + (n - 1) > X'Last
13815 if (Is_Zero and then Op = N_Op_Eq)
13816 or else (not Is_Zero and then Op = N_Op_Lt)
13817 then
13818 Result :=
13819 Make_Op_Gt (Loc,
13820 Left_Opnd => Left,
13821 Right_Opnd => Right);
13823 -- X'Length = 1 => X'First = X'Last
13824 -- X'Length = n => X'First + (n - 1) = X'Last
13826 elsif not Is_Zero and then Op = N_Op_Eq then
13827 Result :=
13828 Make_Op_Eq (Loc,
13829 Left_Opnd => Left,
13830 Right_Opnd => Right);
13832 -- X'Length /= 0 => X'First <= X'Last
13833 -- X'Length > 0 => X'First <= X'Last
13835 elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
13836 Result :=
13837 Make_Op_Le (Loc,
13838 Left_Opnd => Left,
13839 Right_Opnd => Right);
13841 -- X'Length /= 1 => X'First /= X'Last
13842 -- X'Length /= n => X'First + (n - 1) /= X'Last
13844 elsif not Is_Zero and then Op = N_Op_Ne then
13845 Result :=
13846 Make_Op_Ne (Loc,
13847 Left_Opnd => Left,
13848 Right_Opnd => Right);
13850 -- X'Length >= 1 => X'First <= X'Last
13851 -- X'Length >= n => X'First + (n - 1) <= X'Last
13853 elsif not Is_Zero and then Op = N_Op_Ge then
13854 Result :=
13855 Make_Op_Le (Loc,
13856 Left_Opnd => Left,
13857 Right_Opnd => Right);
13859 -- X'Length > 1 => X'First < X'Last
13860 -- X'Length > n => X'First + (n = 1) < X'Last
13862 elsif not Is_Zero and then Op = N_Op_Gt then
13863 Result :=
13864 Make_Op_Lt (Loc,
13865 Left_Opnd => Left,
13866 Right_Opnd => Right);
13868 -- X'Length <= 1 => X'First >= X'Last
13869 -- X'Length <= n => X'First + (n - 1) >= X'Last
13871 elsif not Is_Zero and then Op = N_Op_Le then
13872 Result :=
13873 Make_Op_Ge (Loc,
13874 Left_Opnd => Left,
13875 Right_Opnd => Right);
13877 -- Should not happen at this stage
13879 else
13880 raise Program_Error;
13881 end if;
13883 -- Rewrite and finish up
13885 Rewrite (N, Result);
13886 Analyze_And_Resolve (N, Typ);
13887 return;
13888 end Optimize_Length_Comparison;
13890 --------------------------------
13891 -- Process_If_Case_Statements --
13892 --------------------------------
13894 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id) is
13895 Decl : Node_Id;
13897 begin
13898 Decl := First (Stmts);
13899 while Present (Decl) loop
13900 if Nkind (Decl) = N_Object_Declaration
13901 and then Is_Finalizable_Transient (Decl, N)
13902 then
13903 Process_Transient_In_Expression (Decl, N, Stmts);
13904 end if;
13906 Next (Decl);
13907 end loop;
13908 end Process_If_Case_Statements;
13910 -------------------------------------
13911 -- Process_Transient_In_Expression --
13912 -------------------------------------
13914 procedure Process_Transient_In_Expression
13915 (Obj_Decl : Node_Id;
13916 Expr : Node_Id;
13917 Stmts : List_Id)
13919 Loc : constant Source_Ptr := Sloc (Obj_Decl);
13920 Obj_Id : constant Entity_Id := Defining_Identifier (Obj_Decl);
13922 Hook_Context : constant Node_Id := Find_Hook_Context (Expr);
13923 -- The node on which to insert the hook as an action. This is usually
13924 -- the innermost enclosing non-transient construct.
13926 Fin_Call : Node_Id;
13927 Hook_Assign : Node_Id;
13928 Hook_Clear : Node_Id;
13929 Hook_Decl : Node_Id;
13930 Hook_Insert : Node_Id;
13931 Ptr_Decl : Node_Id;
13933 Fin_Context : Node_Id;
13934 -- The node after which to insert the finalization actions of the
13935 -- transient object.
13937 begin
13938 pragma Assert (Nkind_In (Expr, N_Case_Expression,
13939 N_Expression_With_Actions,
13940 N_If_Expression));
13942 -- When the context is a Boolean evaluation, all three nodes capture the
13943 -- result of their computation in a local temporary:
13945 -- do
13946 -- Trans_Id : Ctrl_Typ := ...;
13947 -- Result : constant Boolean := ... Trans_Id ...;
13948 -- <finalize Trans_Id>
13949 -- in Result end;
13951 -- As a result, the finalization of any transient objects can safely
13952 -- take place after the result capture.
13954 -- ??? could this be extended to elementary types?
13956 if Is_Boolean_Type (Etype (Expr)) then
13957 Fin_Context := Last (Stmts);
13959 -- Otherwise the immediate context may not be safe enough to carry
13960 -- out transient object finalization due to aliasing and nesting of
13961 -- constructs. Insert calls to [Deep_]Finalize after the innermost
13962 -- enclosing non-transient construct.
13964 else
13965 Fin_Context := Hook_Context;
13966 end if;
13968 -- Mark the transient object as successfully processed to avoid double
13969 -- finalization.
13971 Set_Is_Finalized_Transient (Obj_Id);
13973 -- Construct all the pieces necessary to hook and finalize a transient
13974 -- object.
13976 Build_Transient_Object_Statements
13977 (Obj_Decl => Obj_Decl,
13978 Fin_Call => Fin_Call,
13979 Hook_Assign => Hook_Assign,
13980 Hook_Clear => Hook_Clear,
13981 Hook_Decl => Hook_Decl,
13982 Ptr_Decl => Ptr_Decl,
13983 Finalize_Obj => False);
13985 -- Add the access type which provides a reference to the transient
13986 -- object. Generate:
13988 -- type Ptr_Typ is access all Desig_Typ;
13990 Insert_Action (Hook_Context, Ptr_Decl);
13992 -- Add the temporary which acts as a hook to the transient object.
13993 -- Generate:
13995 -- Hook : Ptr_Id := null;
13997 Insert_Action (Hook_Context, Hook_Decl);
13999 -- When the transient object is initialized by an aggregate, the hook
14000 -- must capture the object after the last aggregate assignment takes
14001 -- place. Only then is the object considered initialized. Generate:
14003 -- Hook := Ptr_Typ (Obj_Id);
14004 -- <or>
14005 -- Hook := Obj_Id'Unrestricted_Access;
14007 if Ekind_In (Obj_Id, E_Constant, E_Variable)
14008 and then Present (Last_Aggregate_Assignment (Obj_Id))
14009 then
14010 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
14012 -- Otherwise the hook seizes the related object immediately
14014 else
14015 Hook_Insert := Obj_Decl;
14016 end if;
14018 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
14020 -- When the node is part of a return statement, there is no need to
14021 -- insert a finalization call, as the general finalization mechanism
14022 -- (see Build_Finalizer) would take care of the transient object on
14023 -- subprogram exit. Note that it would also be impossible to insert the
14024 -- finalization code after the return statement as this will render it
14025 -- unreachable.
14027 if Nkind (Fin_Context) = N_Simple_Return_Statement then
14028 null;
14030 -- Finalize the hook after the context has been evaluated. Generate:
14032 -- if Hook /= null then
14033 -- [Deep_]Finalize (Hook.all);
14034 -- Hook := null;
14035 -- end if;
14037 else
14038 Insert_Action_After (Fin_Context,
14039 Make_Implicit_If_Statement (Obj_Decl,
14040 Condition =>
14041 Make_Op_Ne (Loc,
14042 Left_Opnd =>
14043 New_Occurrence_Of (Defining_Entity (Hook_Decl), Loc),
14044 Right_Opnd => Make_Null (Loc)),
14046 Then_Statements => New_List (
14047 Fin_Call,
14048 Hook_Clear)));
14049 end if;
14050 end Process_Transient_In_Expression;
14052 ------------------------
14053 -- Rewrite_Comparison --
14054 ------------------------
14056 procedure Rewrite_Comparison (N : Node_Id) is
14057 Typ : constant Entity_Id := Etype (N);
14059 False_Result : Boolean;
14060 True_Result : Boolean;
14062 begin
14063 if Nkind (N) = N_Type_Conversion then
14064 Rewrite_Comparison (Expression (N));
14065 return;
14067 elsif Nkind (N) not in N_Op_Compare then
14068 return;
14069 end if;
14071 -- Determine the potential outcome of the comparison assuming that the
14072 -- operands are valid and emit a warning when the comparison evaluates
14073 -- to True or False only in the presence of invalid values.
14075 Warn_On_Constant_Valid_Condition (N);
14077 -- Determine the potential outcome of the comparison assuming that the
14078 -- operands are not valid.
14080 Test_Comparison
14081 (Op => N,
14082 Assume_Valid => False,
14083 True_Result => True_Result,
14084 False_Result => False_Result);
14086 -- The outcome is a decisive False or True, rewrite the operator
14088 if False_Result or True_Result then
14089 Rewrite (N,
14090 Convert_To (Typ,
14091 New_Occurrence_Of (Boolean_Literals (True_Result), Sloc (N))));
14093 Analyze_And_Resolve (N, Typ);
14094 Warn_On_Known_Condition (N);
14095 end if;
14096 end Rewrite_Comparison;
14098 ----------------------------
14099 -- Safe_In_Place_Array_Op --
14100 ----------------------------
14102 function Safe_In_Place_Array_Op
14103 (Lhs : Node_Id;
14104 Op1 : Node_Id;
14105 Op2 : Node_Id) return Boolean
14107 Target : Entity_Id;
14109 function Is_Safe_Operand (Op : Node_Id) return Boolean;
14110 -- Operand is safe if it cannot overlap part of the target of the
14111 -- operation. If the operand and the target are identical, the operand
14112 -- is safe. The operand can be empty in the case of negation.
14114 function Is_Unaliased (N : Node_Id) return Boolean;
14115 -- Check that N is a stand-alone entity
14117 ------------------
14118 -- Is_Unaliased --
14119 ------------------
14121 function Is_Unaliased (N : Node_Id) return Boolean is
14122 begin
14123 return
14124 Is_Entity_Name (N)
14125 and then No (Address_Clause (Entity (N)))
14126 and then No (Renamed_Object (Entity (N)));
14127 end Is_Unaliased;
14129 ---------------------
14130 -- Is_Safe_Operand --
14131 ---------------------
14133 function Is_Safe_Operand (Op : Node_Id) return Boolean is
14134 begin
14135 if No (Op) then
14136 return True;
14138 elsif Is_Entity_Name (Op) then
14139 return Is_Unaliased (Op);
14141 elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
14142 return Is_Unaliased (Prefix (Op));
14144 elsif Nkind (Op) = N_Slice then
14145 return
14146 Is_Unaliased (Prefix (Op))
14147 and then Entity (Prefix (Op)) /= Target;
14149 elsif Nkind (Op) = N_Op_Not then
14150 return Is_Safe_Operand (Right_Opnd (Op));
14152 else
14153 return False;
14154 end if;
14155 end Is_Safe_Operand;
14157 -- Start of processing for Safe_In_Place_Array_Op
14159 begin
14160 -- Skip this processing if the component size is different from system
14161 -- storage unit (since at least for NOT this would cause problems).
14163 if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
14164 return False;
14166 -- Cannot do in place stuff if non-standard Boolean representation
14168 elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
14169 return False;
14171 elsif not Is_Unaliased (Lhs) then
14172 return False;
14174 else
14175 Target := Entity (Lhs);
14176 return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
14177 end if;
14178 end Safe_In_Place_Array_Op;
14180 -----------------------
14181 -- Tagged_Membership --
14182 -----------------------
14184 -- There are two different cases to consider depending on whether the right
14185 -- operand is a class-wide type or not. If not we just compare the actual
14186 -- tag of the left expr to the target type tag:
14188 -- Left_Expr.Tag = Right_Type'Tag;
14190 -- If it is a class-wide type we use the RT function CW_Membership which is
14191 -- usually implemented by looking in the ancestor tables contained in the
14192 -- dispatch table pointed by Left_Expr.Tag for Typ'Tag
14194 -- Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
14195 -- function IW_Membership which is usually implemented by looking in the
14196 -- table of abstract interface types plus the ancestor table contained in
14197 -- the dispatch table pointed by Left_Expr.Tag for Typ'Tag
14199 procedure Tagged_Membership
14200 (N : Node_Id;
14201 SCIL_Node : out Node_Id;
14202 Result : out Node_Id)
14204 Left : constant Node_Id := Left_Opnd (N);
14205 Right : constant Node_Id := Right_Opnd (N);
14206 Loc : constant Source_Ptr := Sloc (N);
14208 Full_R_Typ : Entity_Id;
14209 Left_Type : Entity_Id;
14210 New_Node : Node_Id;
14211 Right_Type : Entity_Id;
14212 Obj_Tag : Node_Id;
14214 begin
14215 SCIL_Node := Empty;
14217 -- Handle entities from the limited view
14219 Left_Type := Available_View (Etype (Left));
14220 Right_Type := Available_View (Etype (Right));
14222 -- In the case where the type is an access type, the test is applied
14223 -- using the designated types (needed in Ada 2012 for implicit anonymous
14224 -- access conversions, for AI05-0149).
14226 if Is_Access_Type (Right_Type) then
14227 Left_Type := Designated_Type (Left_Type);
14228 Right_Type := Designated_Type (Right_Type);
14229 end if;
14231 if Is_Class_Wide_Type (Left_Type) then
14232 Left_Type := Root_Type (Left_Type);
14233 end if;
14235 if Is_Class_Wide_Type (Right_Type) then
14236 Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
14237 else
14238 Full_R_Typ := Underlying_Type (Right_Type);
14239 end if;
14241 Obj_Tag :=
14242 Make_Selected_Component (Loc,
14243 Prefix => Relocate_Node (Left),
14244 Selector_Name =>
14245 New_Occurrence_Of (First_Tag_Component (Left_Type), Loc));
14247 if Is_Class_Wide_Type (Right_Type) or else Is_Interface (Left_Type) then
14249 -- No need to issue a run-time check if we statically know that the
14250 -- result of this membership test is always true. For example,
14251 -- considering the following declarations:
14253 -- type Iface is interface;
14254 -- type T is tagged null record;
14255 -- type DT is new T and Iface with null record;
14257 -- Obj1 : T;
14258 -- Obj2 : DT;
14260 -- These membership tests are always true:
14262 -- Obj1 in T'Class
14263 -- Obj2 in T'Class;
14264 -- Obj2 in Iface'Class;
14266 -- We do not need to handle cases where the membership is illegal.
14267 -- For example:
14269 -- Obj1 in DT'Class; -- Compile time error
14270 -- Obj1 in Iface'Class; -- Compile time error
14272 if not Is_Interface (Left_Type)
14273 and then not Is_Class_Wide_Type (Left_Type)
14274 and then (Is_Ancestor (Etype (Right_Type), Left_Type,
14275 Use_Full_View => True)
14276 or else (Is_Interface (Etype (Right_Type))
14277 and then Interface_Present_In_Ancestor
14278 (Typ => Left_Type,
14279 Iface => Etype (Right_Type))))
14280 then
14281 Result := New_Occurrence_Of (Standard_True, Loc);
14282 return;
14283 end if;
14285 -- Ada 2005 (AI-251): Class-wide applied to interfaces
14287 if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
14289 -- Support to: "Iface_CW_Typ in Typ'Class"
14291 or else Is_Interface (Left_Type)
14292 then
14293 -- Issue error if IW_Membership operation not available in a
14294 -- configurable run time setting.
14296 if not RTE_Available (RE_IW_Membership) then
14297 Error_Msg_CRT
14298 ("dynamic membership test on interface types", N);
14299 Result := Empty;
14300 return;
14301 end if;
14303 Result :=
14304 Make_Function_Call (Loc,
14305 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
14306 Parameter_Associations => New_List (
14307 Make_Attribute_Reference (Loc,
14308 Prefix => Obj_Tag,
14309 Attribute_Name => Name_Address),
14310 New_Occurrence_Of (
14311 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
14312 Loc)));
14314 -- Ada 95: Normal case
14316 else
14317 Build_CW_Membership (Loc,
14318 Obj_Tag_Node => Obj_Tag,
14319 Typ_Tag_Node =>
14320 New_Occurrence_Of (
14321 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc),
14322 Related_Nod => N,
14323 New_Node => New_Node);
14325 -- Generate the SCIL node for this class-wide membership test.
14326 -- Done here because the previous call to Build_CW_Membership
14327 -- relocates Obj_Tag.
14329 if Generate_SCIL then
14330 SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
14331 Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
14332 Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
14333 end if;
14335 Result := New_Node;
14336 end if;
14338 -- Right_Type is not a class-wide type
14340 else
14341 -- No need to check the tag of the object if Right_Typ is abstract
14343 if Is_Abstract_Type (Right_Type) then
14344 Result := New_Occurrence_Of (Standard_False, Loc);
14346 else
14347 Result :=
14348 Make_Op_Eq (Loc,
14349 Left_Opnd => Obj_Tag,
14350 Right_Opnd =>
14351 New_Occurrence_Of
14352 (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
14353 end if;
14354 end if;
14355 end Tagged_Membership;
14357 ------------------------------
14358 -- Unary_Op_Validity_Checks --
14359 ------------------------------
14361 procedure Unary_Op_Validity_Checks (N : Node_Id) is
14362 begin
14363 if Validity_Checks_On and Validity_Check_Operands then
14364 Ensure_Valid (Right_Opnd (N));
14365 end if;
14366 end Unary_Op_Validity_Checks;
14368 end Exp_Ch4;