* lto.c (do_stream_out): Add PART parameter; open dump file.
[official-gcc.git] / gcc / ada / checks.adb
blob8e061ebfd48731aad02a5d1093bdbee1d42229e7
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- C H E C K S --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2018, 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 Casing; use Casing;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Eval_Fat; use Eval_Fat;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Ch2; use Exp_Ch2;
34 with Exp_Ch4; use Exp_Ch4;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Util; use Exp_Util;
37 with Expander; use Expander;
38 with Freeze; use Freeze;
39 with Lib; use Lib;
40 with Nlists; use Nlists;
41 with Nmake; use Nmake;
42 with Opt; use Opt;
43 with Output; use Output;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
47 with Sem; use Sem;
48 with Sem_Aux; use Sem_Aux;
49 with Sem_Ch3; use Sem_Ch3;
50 with Sem_Ch8; use Sem_Ch8;
51 with Sem_Disp; use Sem_Disp;
52 with Sem_Eval; use Sem_Eval;
53 with Sem_Res; use Sem_Res;
54 with Sem_Util; use Sem_Util;
55 with Sem_Warn; use Sem_Warn;
56 with Sinfo; use Sinfo;
57 with Sinput; use Sinput;
58 with Snames; use Snames;
59 with Sprint; use Sprint;
60 with Stand; use Stand;
61 with Stringt; use Stringt;
62 with Targparm; use Targparm;
63 with Tbuild; use Tbuild;
64 with Ttypes; use Ttypes;
65 with Validsw; use Validsw;
67 package body Checks is
69 -- General note: many of these routines are concerned with generating
70 -- checking code to make sure that constraint error is raised at runtime.
71 -- Clearly this code is only needed if the expander is active, since
72 -- otherwise we will not be generating code or going into the runtime
73 -- execution anyway.
75 -- We therefore disconnect most of these checks if the expander is
76 -- inactive. This has the additional benefit that we do not need to
77 -- worry about the tree being messed up by previous errors (since errors
78 -- turn off expansion anyway).
80 -- There are a few exceptions to the above rule. For instance routines
81 -- such as Apply_Scalar_Range_Check that do not insert any code can be
82 -- safely called even when the Expander is inactive (but Errors_Detected
83 -- is 0). The benefit of executing this code when expansion is off, is
84 -- the ability to emit constraint error warning for static expressions
85 -- even when we are not generating code.
87 -- The above is modified in gnatprove mode to ensure that proper check
88 -- flags are always placed, even if expansion is off.
90 -------------------------------------
91 -- Suppression of Redundant Checks --
92 -------------------------------------
94 -- This unit implements a limited circuit for removal of redundant
95 -- checks. The processing is based on a tracing of simple sequential
96 -- flow. For any sequence of statements, we save expressions that are
97 -- marked to be checked, and then if the same expression appears later
98 -- with the same check, then under certain circumstances, the second
99 -- check can be suppressed.
101 -- Basically, we can suppress the check if we know for certain that
102 -- the previous expression has been elaborated (together with its
103 -- check), and we know that the exception frame is the same, and that
104 -- nothing has happened to change the result of the exception.
106 -- Let us examine each of these three conditions in turn to describe
107 -- how we ensure that this condition is met.
109 -- First, we need to know for certain that the previous expression has
110 -- been executed. This is done principally by the mechanism of calling
111 -- Conditional_Statements_Begin at the start of any statement sequence
112 -- and Conditional_Statements_End at the end. The End call causes all
113 -- checks remembered since the Begin call to be discarded. This does
114 -- miss a few cases, notably the case of a nested BEGIN-END block with
115 -- no exception handlers. But the important thing is to be conservative.
116 -- The other protection is that all checks are discarded if a label
117 -- is encountered, since then the assumption of sequential execution
118 -- is violated, and we don't know enough about the flow.
120 -- Second, we need to know that the exception frame is the same. We
121 -- do this by killing all remembered checks when we enter a new frame.
122 -- Again, that's over-conservative, but generally the cases we can help
123 -- with are pretty local anyway (like the body of a loop for example).
125 -- Third, we must be sure to forget any checks which are no longer valid.
126 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
127 -- used to note any changes to local variables. We only attempt to deal
128 -- with checks involving local variables, so we do not need to worry
129 -- about global variables. Second, a call to any non-global procedure
130 -- causes us to abandon all stored checks, since such a all may affect
131 -- the values of any local variables.
133 -- The following define the data structures used to deal with remembering
134 -- checks so that redundant checks can be eliminated as described above.
136 -- Right now, the only expressions that we deal with are of the form of
137 -- simple local objects (either declared locally, or IN parameters) or
138 -- such objects plus/minus a compile time known constant. We can do
139 -- more later on if it seems worthwhile, but this catches many simple
140 -- cases in practice.
142 -- The following record type reflects a single saved check. An entry
143 -- is made in the stack of saved checks if and only if the expression
144 -- has been elaborated with the indicated checks.
146 type Saved_Check is record
147 Killed : Boolean;
148 -- Set True if entry is killed by Kill_Checks
150 Entity : Entity_Id;
151 -- The entity involved in the expression that is checked
153 Offset : Uint;
154 -- A compile time value indicating the result of adding or
155 -- subtracting a compile time value. This value is to be
156 -- added to the value of the Entity. A value of zero is
157 -- used for the case of a simple entity reference.
159 Check_Type : Character;
160 -- This is set to 'R' for a range check (in which case Target_Type
161 -- is set to the target type for the range check) or to 'O' for an
162 -- overflow check (in which case Target_Type is set to Empty).
164 Target_Type : Entity_Id;
165 -- Used only if Do_Range_Check is set. Records the target type for
166 -- the check. We need this, because a check is a duplicate only if
167 -- it has the same target type (or more accurately one with a
168 -- range that is smaller or equal to the stored target type of a
169 -- saved check).
170 end record;
172 -- The following table keeps track of saved checks. Rather than use an
173 -- extensible table, we just use a table of fixed size, and we discard
174 -- any saved checks that do not fit. That's very unlikely to happen and
175 -- this is only an optimization in any case.
177 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
178 -- Array of saved checks
180 Num_Saved_Checks : Nat := 0;
181 -- Number of saved checks
183 -- The following stack keeps track of statement ranges. It is treated
184 -- as a stack. When Conditional_Statements_Begin is called, an entry
185 -- is pushed onto this stack containing the value of Num_Saved_Checks
186 -- at the time of the call. Then when Conditional_Statements_End is
187 -- called, this value is popped off and used to reset Num_Saved_Checks.
189 -- Note: again, this is a fixed length stack with a size that should
190 -- always be fine. If the value of the stack pointer goes above the
191 -- limit, then we just forget all saved checks.
193 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
194 Saved_Checks_TOS : Nat := 0;
196 -----------------------
197 -- Local Subprograms --
198 -----------------------
200 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id);
201 -- Used to apply arithmetic overflow checks for all cases except operators
202 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
203 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
204 -- signed integer arithmetic operator (but not an if or case expression).
205 -- It is also called for types other than signed integers.
207 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id);
208 -- Used to apply arithmetic overflow checks for the case where the overflow
209 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
210 -- arithmetic op (which includes the case of if and case expressions). Note
211 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
212 -- we have work to do even if overflow checking is suppressed.
214 procedure Apply_Division_Check
215 (N : Node_Id;
216 Rlo : Uint;
217 Rhi : Uint;
218 ROK : Boolean);
219 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
220 -- division checks as required if the Do_Division_Check flag is set.
221 -- Rlo and Rhi give the possible range of the right operand, these values
222 -- can be referenced and trusted only if ROK is set True.
224 procedure Apply_Float_Conversion_Check
225 (Ck_Node : Node_Id;
226 Target_Typ : Entity_Id);
227 -- The checks on a conversion from a floating-point type to an integer
228 -- type are delicate. They have to be performed before conversion, they
229 -- have to raise an exception when the operand is a NaN, and rounding must
230 -- be taken into account to determine the safe bounds of the operand.
232 procedure Apply_Selected_Length_Checks
233 (Ck_Node : Node_Id;
234 Target_Typ : Entity_Id;
235 Source_Typ : Entity_Id;
236 Do_Static : Boolean);
237 -- This is the subprogram that does all the work for Apply_Length_Check
238 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
239 -- described for the above routines. The Do_Static flag indicates that
240 -- only a static check is to be done.
242 procedure Apply_Selected_Range_Checks
243 (Ck_Node : Node_Id;
244 Target_Typ : Entity_Id;
245 Source_Typ : Entity_Id;
246 Do_Static : Boolean);
247 -- This is the subprogram that does all the work for Apply_Range_Check.
248 -- Expr, Target_Typ and Source_Typ are as described for the above
249 -- routine. The Do_Static flag indicates that only a static check is
250 -- to be done.
252 type Check_Type is new Check_Id range Access_Check .. Division_Check;
253 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
254 -- This function is used to see if an access or division by zero check is
255 -- needed. The check is to be applied to a single variable appearing in the
256 -- source, and N is the node for the reference. If N is not of this form,
257 -- True is returned with no further processing. If N is of the right form,
258 -- then further processing determines if the given Check is needed.
260 -- The particular circuit is to see if we have the case of a check that is
261 -- not needed because it appears in the right operand of a short circuited
262 -- conditional where the left operand guards the check. For example:
264 -- if Var = 0 or else Q / Var > 12 then
265 -- ...
266 -- end if;
268 -- In this example, the division check is not required. At the same time
269 -- we can issue warnings for suspicious use of non-short-circuited forms,
270 -- such as:
272 -- if Var = 0 or Q / Var > 12 then
273 -- ...
274 -- end if;
276 procedure Find_Check
277 (Expr : Node_Id;
278 Check_Type : Character;
279 Target_Type : Entity_Id;
280 Entry_OK : out Boolean;
281 Check_Num : out Nat;
282 Ent : out Entity_Id;
283 Ofs : out Uint);
284 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
285 -- to see if a check is of the form for optimization, and if so, to see
286 -- if it has already been performed. Expr is the expression to check,
287 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
288 -- Target_Type is the target type for a range check, and Empty for an
289 -- overflow check. If the entry is not of the form for optimization,
290 -- then Entry_OK is set to False, and the remaining out parameters
291 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
292 -- entity and offset from the expression. Check_Num is the number of
293 -- a matching saved entry in Saved_Checks, or zero if no such entry
294 -- is located.
296 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
297 -- If a discriminal is used in constraining a prival, Return reference
298 -- to the discriminal of the protected body (which renames the parameter
299 -- of the enclosing protected operation). This clumsy transformation is
300 -- needed because privals are created too late and their actual subtypes
301 -- are not available when analysing the bodies of the protected operations.
302 -- This function is called whenever the bound is an entity and the scope
303 -- indicates a protected operation. If the bound is an in-parameter of
304 -- a protected operation that is not a prival, the function returns the
305 -- bound itself.
306 -- To be cleaned up???
308 function Guard_Access
309 (Cond : Node_Id;
310 Loc : Source_Ptr;
311 Ck_Node : Node_Id) return Node_Id;
312 -- In the access type case, guard the test with a test to ensure
313 -- that the access value is non-null, since the checks do not
314 -- not apply to null access values.
316 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
317 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
318 -- Constraint_Error node.
320 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean;
321 -- Returns True if node N is for an arithmetic operation with signed
322 -- integer operands. This includes unary and binary operators, and also
323 -- if and case expression nodes where the dependent expressions are of
324 -- a signed integer type. These are the kinds of nodes for which special
325 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
327 function Range_Or_Validity_Checks_Suppressed
328 (Expr : Node_Id) return Boolean;
329 -- Returns True if either range or validity checks or both are suppressed
330 -- for the type of the given expression, or, if the expression is the name
331 -- of an entity, if these checks are suppressed for the entity.
333 function Selected_Length_Checks
334 (Ck_Node : Node_Id;
335 Target_Typ : Entity_Id;
336 Source_Typ : Entity_Id;
337 Warn_Node : Node_Id) return Check_Result;
338 -- Like Apply_Selected_Length_Checks, except it doesn't modify
339 -- anything, just returns a list of nodes as described in the spec of
340 -- this package for the Range_Check function.
341 -- ??? In fact it does construct the test and insert it into the tree,
342 -- and insert actions in various ways (calling Insert_Action directly
343 -- in particular) so we do not call it in GNATprove mode, contrary to
344 -- Selected_Range_Checks.
346 function Selected_Range_Checks
347 (Ck_Node : Node_Id;
348 Target_Typ : Entity_Id;
349 Source_Typ : Entity_Id;
350 Warn_Node : Node_Id) return Check_Result;
351 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
352 -- just returns a list of nodes as described in the spec of this package
353 -- for the Range_Check function.
355 ------------------------------
356 -- Access_Checks_Suppressed --
357 ------------------------------
359 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
360 begin
361 if Present (E) and then Checks_May_Be_Suppressed (E) then
362 return Is_Check_Suppressed (E, Access_Check);
363 else
364 return Scope_Suppress.Suppress (Access_Check);
365 end if;
366 end Access_Checks_Suppressed;
368 -------------------------------------
369 -- Accessibility_Checks_Suppressed --
370 -------------------------------------
372 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
373 begin
374 if Present (E) and then Checks_May_Be_Suppressed (E) then
375 return Is_Check_Suppressed (E, Accessibility_Check);
376 else
377 return Scope_Suppress.Suppress (Accessibility_Check);
378 end if;
379 end Accessibility_Checks_Suppressed;
381 -----------------------------
382 -- Activate_Division_Check --
383 -----------------------------
385 procedure Activate_Division_Check (N : Node_Id) is
386 begin
387 Set_Do_Division_Check (N, True);
388 Possible_Local_Raise (N, Standard_Constraint_Error);
389 end Activate_Division_Check;
391 -----------------------------
392 -- Activate_Overflow_Check --
393 -----------------------------
395 procedure Activate_Overflow_Check (N : Node_Id) is
396 Typ : constant Entity_Id := Etype (N);
398 begin
399 -- Floating-point case. If Etype is not set (this can happen when we
400 -- activate a check on a node that has not yet been analyzed), then
401 -- we assume we do not have a floating-point type (as per our spec).
403 if Present (Typ) and then Is_Floating_Point_Type (Typ) then
405 -- Ignore call if we have no automatic overflow checks on the target
406 -- and Check_Float_Overflow mode is not set. These are the cases in
407 -- which we expect to generate infinities and NaN's with no check.
409 if not (Machine_Overflows_On_Target or Check_Float_Overflow) then
410 return;
412 -- Ignore for unary operations ("+", "-", abs) since these can never
413 -- result in overflow for floating-point cases.
415 elsif Nkind (N) in N_Unary_Op then
416 return;
418 -- Otherwise we will set the flag
420 else
421 null;
422 end if;
424 -- Discrete case
426 else
427 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
428 -- for zero-divide is a divide check, not an overflow check).
430 if Nkind_In (N, N_Op_Rem, N_Op_Mod, N_Op_Plus) then
431 return;
432 end if;
433 end if;
435 -- Fall through for cases where we do set the flag
437 Set_Do_Overflow_Check (N, True);
438 Possible_Local_Raise (N, Standard_Constraint_Error);
439 end Activate_Overflow_Check;
441 --------------------------
442 -- Activate_Range_Check --
443 --------------------------
445 procedure Activate_Range_Check (N : Node_Id) is
446 begin
447 Set_Do_Range_Check (N, True);
448 Possible_Local_Raise (N, Standard_Constraint_Error);
449 end Activate_Range_Check;
451 ---------------------------------
452 -- Alignment_Checks_Suppressed --
453 ---------------------------------
455 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
456 begin
457 if Present (E) and then Checks_May_Be_Suppressed (E) then
458 return Is_Check_Suppressed (E, Alignment_Check);
459 else
460 return Scope_Suppress.Suppress (Alignment_Check);
461 end if;
462 end Alignment_Checks_Suppressed;
464 ----------------------------------
465 -- Allocation_Checks_Suppressed --
466 ----------------------------------
468 -- Note: at the current time there are no calls to this function, because
469 -- the relevant check is in the run-time, so it is not a check that the
470 -- compiler can suppress anyway, but we still have to recognize the check
471 -- name Allocation_Check since it is part of the standard.
473 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean is
474 begin
475 if Present (E) and then Checks_May_Be_Suppressed (E) then
476 return Is_Check_Suppressed (E, Allocation_Check);
477 else
478 return Scope_Suppress.Suppress (Allocation_Check);
479 end if;
480 end Allocation_Checks_Suppressed;
482 -------------------------
483 -- Append_Range_Checks --
484 -------------------------
486 procedure Append_Range_Checks
487 (Checks : Check_Result;
488 Stmts : List_Id;
489 Suppress_Typ : Entity_Id;
490 Static_Sloc : Source_Ptr;
491 Flag_Node : Node_Id)
493 Checks_On : constant Boolean :=
494 not Index_Checks_Suppressed (Suppress_Typ)
495 or else
496 not Range_Checks_Suppressed (Suppress_Typ);
498 Internal_Flag_Node : constant Node_Id := Flag_Node;
499 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
501 begin
502 -- For now we just return if Checks_On is false, however this should be
503 -- enhanced to check for an always True value in the condition and to
504 -- generate a compilation warning???
506 if not Checks_On then
507 return;
508 end if;
510 for J in 1 .. 2 loop
511 exit when No (Checks (J));
513 if Nkind (Checks (J)) = N_Raise_Constraint_Error
514 and then Present (Condition (Checks (J)))
515 then
516 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
517 Append_To (Stmts, Checks (J));
518 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
519 end if;
521 else
522 Append_To
523 (Stmts,
524 Make_Raise_Constraint_Error (Internal_Static_Sloc,
525 Reason => CE_Range_Check_Failed));
526 end if;
527 end loop;
528 end Append_Range_Checks;
530 ------------------------
531 -- Apply_Access_Check --
532 ------------------------
534 procedure Apply_Access_Check (N : Node_Id) is
535 P : constant Node_Id := Prefix (N);
537 begin
538 -- We do not need checks if we are not generating code (i.e. the
539 -- expander is not active). This is not just an optimization, there
540 -- are cases (e.g. with pragma Debug) where generating the checks
541 -- can cause real trouble).
543 if not Expander_Active then
544 return;
545 end if;
547 -- No check if short circuiting makes check unnecessary
549 if not Check_Needed (P, Access_Check) then
550 return;
551 end if;
553 -- No check if accessing the Offset_To_Top component of a dispatch
554 -- table. They are safe by construction.
556 if Tagged_Type_Expansion
557 and then Present (Etype (P))
558 and then RTU_Loaded (Ada_Tags)
559 and then RTE_Available (RE_Offset_To_Top_Ptr)
560 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
561 then
562 return;
563 end if;
565 -- Otherwise go ahead and install the check
567 Install_Null_Excluding_Check (P);
568 end Apply_Access_Check;
570 -------------------------------
571 -- Apply_Accessibility_Check --
572 -------------------------------
574 procedure Apply_Accessibility_Check
575 (N : Node_Id;
576 Typ : Entity_Id;
577 Insert_Node : Node_Id)
579 Loc : constant Source_Ptr := Sloc (N);
580 Param_Ent : Entity_Id := Param_Entity (N);
581 Param_Level : Node_Id;
582 Type_Level : Node_Id;
584 begin
585 if Ada_Version >= Ada_2012
586 and then not Present (Param_Ent)
587 and then Is_Entity_Name (N)
588 and then Ekind_In (Entity (N), E_Constant, E_Variable)
589 and then Present (Effective_Extra_Accessibility (Entity (N)))
590 then
591 Param_Ent := Entity (N);
592 while Present (Renamed_Object (Param_Ent)) loop
594 -- Renamed_Object must return an Entity_Name here
595 -- because of preceding "Present (E_E_A (...))" test.
597 Param_Ent := Entity (Renamed_Object (Param_Ent));
598 end loop;
599 end if;
601 if Inside_A_Generic then
602 return;
604 -- Only apply the run-time check if the access parameter has an
605 -- associated extra access level parameter and when the level of the
606 -- type is less deep than the level of the access parameter, and
607 -- accessibility checks are not suppressed.
609 elsif Present (Param_Ent)
610 and then Present (Extra_Accessibility (Param_Ent))
611 and then UI_Gt (Object_Access_Level (N),
612 Deepest_Type_Access_Level (Typ))
613 and then not Accessibility_Checks_Suppressed (Param_Ent)
614 and then not Accessibility_Checks_Suppressed (Typ)
615 then
616 Param_Level :=
617 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
619 Type_Level :=
620 Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
622 -- Raise Program_Error if the accessibility level of the access
623 -- parameter is deeper than the level of the target access type.
625 Insert_Action (Insert_Node,
626 Make_Raise_Program_Error (Loc,
627 Condition =>
628 Make_Op_Gt (Loc,
629 Left_Opnd => Param_Level,
630 Right_Opnd => Type_Level),
631 Reason => PE_Accessibility_Check_Failed));
633 Analyze_And_Resolve (N);
634 end if;
635 end Apply_Accessibility_Check;
637 --------------------------------
638 -- Apply_Address_Clause_Check --
639 --------------------------------
641 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
642 pragma Assert (Nkind (N) = N_Freeze_Entity);
644 AC : constant Node_Id := Address_Clause (E);
645 Loc : constant Source_Ptr := Sloc (AC);
646 Typ : constant Entity_Id := Etype (E);
648 Expr : Node_Id;
649 -- Address expression (not necessarily the same as Aexp, for example
650 -- when Aexp is a reference to a constant, in which case Expr gets
651 -- reset to reference the value expression of the constant).
653 begin
654 -- See if alignment check needed. Note that we never need a check if the
655 -- maximum alignment is one, since the check will always succeed.
657 -- Note: we do not check for checks suppressed here, since that check
658 -- was done in Sem_Ch13 when the address clause was processed. We are
659 -- only called if checks were not suppressed. The reason for this is
660 -- that we have to delay the call to Apply_Alignment_Check till freeze
661 -- time (so that all types etc are elaborated), but we have to check
662 -- the status of check suppressing at the point of the address clause.
664 if No (AC)
665 or else not Check_Address_Alignment (AC)
666 or else Maximum_Alignment = 1
667 then
668 return;
669 end if;
671 -- Obtain expression from address clause
673 Expr := Address_Value (Expression (AC));
675 -- See if we know that Expr has an acceptable value at compile time. If
676 -- it hasn't or we don't know, we defer issuing the warning until the
677 -- end of the compilation to take into account back end annotations.
679 if Compile_Time_Known_Value (Expr)
680 and then (Known_Alignment (E) or else Known_Alignment (Typ))
681 then
682 declare
683 AL : Uint := Alignment (Typ);
685 begin
686 -- The object alignment might be more restrictive than the type
687 -- alignment.
689 if Known_Alignment (E) then
690 AL := Alignment (E);
691 end if;
693 if Expr_Value (Expr) mod AL = 0 then
694 return;
695 end if;
696 end;
698 -- If the expression has the form X'Address, then we can find out if the
699 -- object X has an alignment that is compatible with the object E. If it
700 -- hasn't or we don't know, we defer issuing the warning until the end
701 -- of the compilation to take into account back end annotations.
703 elsif Nkind (Expr) = N_Attribute_Reference
704 and then Attribute_Name (Expr) = Name_Address
705 and then
706 Has_Compatible_Alignment (E, Prefix (Expr), False) = Known_Compatible
707 then
708 return;
709 end if;
711 -- Here we do not know if the value is acceptable. Strictly we don't
712 -- have to do anything, since if the alignment is bad, we have an
713 -- erroneous program. However we are allowed to check for erroneous
714 -- conditions and we decide to do this by default if the check is not
715 -- suppressed.
717 -- However, don't do the check if elaboration code is unwanted
719 if Restriction_Active (No_Elaboration_Code) then
720 return;
722 -- Generate a check to raise PE if alignment may be inappropriate
724 else
725 -- If the original expression is a non-static constant, use the name
726 -- of the constant itself rather than duplicating its initialization
727 -- expression, which was extracted above.
729 -- Note: Expr is empty if the address-clause is applied to in-mode
730 -- actuals (allowed by 13.1(22)).
732 if not Present (Expr)
733 or else
734 (Is_Entity_Name (Expression (AC))
735 and then Ekind (Entity (Expression (AC))) = E_Constant
736 and then Nkind (Parent (Entity (Expression (AC)))) =
737 N_Object_Declaration)
738 then
739 Expr := New_Copy_Tree (Expression (AC));
740 else
741 Remove_Side_Effects (Expr);
742 end if;
744 if No (Actions (N)) then
745 Set_Actions (N, New_List);
746 end if;
748 Prepend_To (Actions (N),
749 Make_Raise_Program_Error (Loc,
750 Condition =>
751 Make_Op_Ne (Loc,
752 Left_Opnd =>
753 Make_Op_Mod (Loc,
754 Left_Opnd =>
755 Unchecked_Convert_To
756 (RTE (RE_Integer_Address), Expr),
757 Right_Opnd =>
758 Make_Attribute_Reference (Loc,
759 Prefix => New_Occurrence_Of (E, Loc),
760 Attribute_Name => Name_Alignment)),
761 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
762 Reason => PE_Misaligned_Address_Value));
764 Warning_Msg := No_Error_Msg;
765 Analyze (First (Actions (N)), Suppress => All_Checks);
767 -- If the above raise action generated a warning message (for example
768 -- from Warn_On_Non_Local_Exception mode with the active restriction
769 -- No_Exception_Propagation).
771 if Warning_Msg /= No_Error_Msg then
773 -- If the expression has a known at compile time value, then
774 -- once we know the alignment of the type, we can check if the
775 -- exception will be raised or not, and if not, we don't need
776 -- the warning so we will kill the warning later on.
778 if Compile_Time_Known_Value (Expr) then
779 Alignment_Warnings.Append
780 ((E => E, A => Expr_Value (Expr), W => Warning_Msg));
782 -- Add explanation of the warning generated by the check
784 else
785 Error_Msg_N
786 ("\address value may be incompatible with alignment of "
787 & "object?X?", AC);
788 end if;
789 end if;
791 return;
792 end if;
794 exception
796 -- If we have some missing run time component in configurable run time
797 -- mode then just skip the check (it is not required in any case).
799 when RE_Not_Available =>
800 return;
801 end Apply_Address_Clause_Check;
803 -------------------------------------
804 -- Apply_Arithmetic_Overflow_Check --
805 -------------------------------------
807 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
808 begin
809 -- Use old routine in almost all cases (the only case we are treating
810 -- specially is the case of a signed integer arithmetic op with the
811 -- overflow checking mode set to MINIMIZED or ELIMINATED).
813 if Overflow_Check_Mode = Strict
814 or else not Is_Signed_Integer_Arithmetic_Op (N)
815 then
816 Apply_Arithmetic_Overflow_Strict (N);
818 -- Otherwise use the new routine for the case of a signed integer
819 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
820 -- mode is MINIMIZED or ELIMINATED.
822 else
823 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
824 end if;
825 end Apply_Arithmetic_Overflow_Check;
827 --------------------------------------
828 -- Apply_Arithmetic_Overflow_Strict --
829 --------------------------------------
831 -- This routine is called only if the type is an integer type and an
832 -- arithmetic overflow check may be needed for op (add, subtract, or
833 -- multiply). This check is performed if Backend_Overflow_Checks_On_Target
834 -- is not enabled and Do_Overflow_Check is set. In this case we expand the
835 -- operation into a more complex sequence of tests that ensures that
836 -- overflow is properly caught.
838 -- This is used in CHECKED modes. It is identical to the code for this
839 -- cases before the big overflow earthquake, thus ensuring that in this
840 -- modes we have compatible behavior (and reliability) to what was there
841 -- before. It is also called for types other than signed integers, and if
842 -- the Do_Overflow_Check flag is off.
844 -- Note: we also call this routine if we decide in the MINIMIZED case
845 -- to give up and just generate an overflow check without any fuss.
847 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id) is
848 Loc : constant Source_Ptr := Sloc (N);
849 Typ : constant Entity_Id := Etype (N);
850 Rtyp : constant Entity_Id := Root_Type (Typ);
852 begin
853 -- Nothing to do if Do_Overflow_Check not set or overflow checks
854 -- suppressed.
856 if not Do_Overflow_Check (N) then
857 return;
858 end if;
860 -- An interesting special case. If the arithmetic operation appears as
861 -- the operand of a type conversion:
863 -- type1 (x op y)
865 -- and all the following conditions apply:
867 -- arithmetic operation is for a signed integer type
868 -- target type type1 is a static integer subtype
869 -- range of x and y are both included in the range of type1
870 -- range of x op y is included in the range of type1
871 -- size of type1 is at least twice the result size of op
873 -- then we don't do an overflow check in any case. Instead, we transform
874 -- the operation so that we end up with:
876 -- type1 (type1 (x) op type1 (y))
878 -- This avoids intermediate overflow before the conversion. It is
879 -- explicitly permitted by RM 3.5.4(24):
881 -- For the execution of a predefined operation of a signed integer
882 -- type, the implementation need not raise Constraint_Error if the
883 -- result is outside the base range of the type, so long as the
884 -- correct result is produced.
886 -- It's hard to imagine that any programmer counts on the exception
887 -- being raised in this case, and in any case it's wrong coding to
888 -- have this expectation, given the RM permission. Furthermore, other
889 -- Ada compilers do allow such out of range results.
891 -- Note that we do this transformation even if overflow checking is
892 -- off, since this is precisely about giving the "right" result and
893 -- avoiding the need for an overflow check.
895 -- Note: this circuit is partially redundant with respect to the similar
896 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
897 -- with cases that do not come through here. We still need the following
898 -- processing even with the Exp_Ch4 code in place, since we want to be
899 -- sure not to generate the arithmetic overflow check in these cases
900 -- (Exp_Ch4 would have a hard time removing them once generated).
902 if Is_Signed_Integer_Type (Typ)
903 and then Nkind (Parent (N)) = N_Type_Conversion
904 then
905 Conversion_Optimization : declare
906 Target_Type : constant Entity_Id :=
907 Base_Type (Entity (Subtype_Mark (Parent (N))));
909 Llo, Lhi : Uint;
910 Rlo, Rhi : Uint;
911 LOK, ROK : Boolean;
913 Vlo : Uint;
914 Vhi : Uint;
915 VOK : Boolean;
917 Tlo : Uint;
918 Thi : Uint;
920 begin
921 if Is_Integer_Type (Target_Type)
922 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
923 then
924 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
925 Thi := Expr_Value (Type_High_Bound (Target_Type));
927 Determine_Range
928 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
929 Determine_Range
930 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
932 if (LOK and ROK)
933 and then Tlo <= Llo and then Lhi <= Thi
934 and then Tlo <= Rlo and then Rhi <= Thi
935 then
936 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
938 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
939 Rewrite (Left_Opnd (N),
940 Make_Type_Conversion (Loc,
941 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
942 Expression => Relocate_Node (Left_Opnd (N))));
944 Rewrite (Right_Opnd (N),
945 Make_Type_Conversion (Loc,
946 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
947 Expression => Relocate_Node (Right_Opnd (N))));
949 -- Rewrite the conversion operand so that the original
950 -- node is retained, in order to avoid the warning for
951 -- redundant conversions in Resolve_Type_Conversion.
953 Rewrite (N, Relocate_Node (N));
955 Set_Etype (N, Target_Type);
957 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
958 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
960 -- Given that the target type is twice the size of the
961 -- source type, overflow is now impossible, so we can
962 -- safely kill the overflow check and return.
964 Set_Do_Overflow_Check (N, False);
965 return;
966 end if;
967 end if;
968 end if;
969 end Conversion_Optimization;
970 end if;
972 -- Now see if an overflow check is required
974 declare
975 Siz : constant Int := UI_To_Int (Esize (Rtyp));
976 Dsiz : constant Int := Siz * 2;
977 Opnod : Node_Id;
978 Ctyp : Entity_Id;
979 Opnd : Node_Id;
980 Cent : RE_Id;
982 begin
983 -- Skip check if back end does overflow checks, or the overflow flag
984 -- is not set anyway, or we are not doing code expansion, or the
985 -- parent node is a type conversion whose operand is an arithmetic
986 -- operation on signed integers on which the expander can promote
987 -- later the operands to type Integer (see Expand_N_Type_Conversion).
989 if Backend_Overflow_Checks_On_Target
990 or else not Do_Overflow_Check (N)
991 or else not Expander_Active
992 or else (Present (Parent (N))
993 and then Nkind (Parent (N)) = N_Type_Conversion
994 and then Integer_Promotion_Possible (Parent (N)))
995 then
996 return;
997 end if;
999 -- Otherwise, generate the full general code for front end overflow
1000 -- detection, which works by doing arithmetic in a larger type:
1002 -- x op y
1004 -- is expanded into
1006 -- Typ (Checktyp (x) op Checktyp (y));
1008 -- where Typ is the type of the original expression, and Checktyp is
1009 -- an integer type of sufficient length to hold the largest possible
1010 -- result.
1012 -- If the size of check type exceeds the size of Long_Long_Integer,
1013 -- we use a different approach, expanding to:
1015 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
1017 -- where xxx is Add, Multiply or Subtract as appropriate
1019 -- Find check type if one exists
1021 if Dsiz <= Standard_Integer_Size then
1022 Ctyp := Standard_Integer;
1024 elsif Dsiz <= Standard_Long_Long_Integer_Size then
1025 Ctyp := Standard_Long_Long_Integer;
1027 -- No check type exists, use runtime call
1029 else
1030 if Nkind (N) = N_Op_Add then
1031 Cent := RE_Add_With_Ovflo_Check;
1033 elsif Nkind (N) = N_Op_Multiply then
1034 Cent := RE_Multiply_With_Ovflo_Check;
1036 else
1037 pragma Assert (Nkind (N) = N_Op_Subtract);
1038 Cent := RE_Subtract_With_Ovflo_Check;
1039 end if;
1041 Rewrite (N,
1042 OK_Convert_To (Typ,
1043 Make_Function_Call (Loc,
1044 Name => New_Occurrence_Of (RTE (Cent), Loc),
1045 Parameter_Associations => New_List (
1046 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
1047 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
1049 Analyze_And_Resolve (N, Typ);
1050 return;
1051 end if;
1053 -- If we fall through, we have the case where we do the arithmetic
1054 -- in the next higher type and get the check by conversion. In these
1055 -- cases Ctyp is set to the type to be used as the check type.
1057 Opnod := Relocate_Node (N);
1059 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
1061 Analyze (Opnd);
1062 Set_Etype (Opnd, Ctyp);
1063 Set_Analyzed (Opnd, True);
1064 Set_Left_Opnd (Opnod, Opnd);
1066 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
1068 Analyze (Opnd);
1069 Set_Etype (Opnd, Ctyp);
1070 Set_Analyzed (Opnd, True);
1071 Set_Right_Opnd (Opnod, Opnd);
1073 -- The type of the operation changes to the base type of the check
1074 -- type, and we reset the overflow check indication, since clearly no
1075 -- overflow is possible now that we are using a double length type.
1076 -- We also set the Analyzed flag to avoid a recursive attempt to
1077 -- expand the node.
1079 Set_Etype (Opnod, Base_Type (Ctyp));
1080 Set_Do_Overflow_Check (Opnod, False);
1081 Set_Analyzed (Opnod, True);
1083 -- Now build the outer conversion
1085 Opnd := OK_Convert_To (Typ, Opnod);
1086 Analyze (Opnd);
1087 Set_Etype (Opnd, Typ);
1089 -- In the discrete type case, we directly generate the range check
1090 -- for the outer operand. This range check will implement the
1091 -- required overflow check.
1093 if Is_Discrete_Type (Typ) then
1094 Rewrite (N, Opnd);
1095 Generate_Range_Check
1096 (Expression (N), Typ, CE_Overflow_Check_Failed);
1098 -- For other types, we enable overflow checking on the conversion,
1099 -- after setting the node as analyzed to prevent recursive attempts
1100 -- to expand the conversion node.
1102 else
1103 Set_Analyzed (Opnd, True);
1104 Enable_Overflow_Check (Opnd);
1105 Rewrite (N, Opnd);
1106 end if;
1108 exception
1109 when RE_Not_Available =>
1110 return;
1111 end;
1112 end Apply_Arithmetic_Overflow_Strict;
1114 ----------------------------------------------------
1115 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1116 ----------------------------------------------------
1118 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id) is
1119 pragma Assert (Is_Signed_Integer_Arithmetic_Op (Op));
1121 Loc : constant Source_Ptr := Sloc (Op);
1122 P : constant Node_Id := Parent (Op);
1124 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
1125 -- Operands and results are of this type when we convert
1127 Result_Type : constant Entity_Id := Etype (Op);
1128 -- Original result type
1130 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1131 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
1133 Lo, Hi : Uint;
1134 -- Ranges of values for result
1136 begin
1137 -- Nothing to do if our parent is one of the following:
1139 -- Another signed integer arithmetic op
1140 -- A membership operation
1141 -- A comparison operation
1143 -- In all these cases, we will process at the higher level (and then
1144 -- this node will be processed during the downwards recursion that
1145 -- is part of the processing in Minimize_Eliminate_Overflows).
1147 if Is_Signed_Integer_Arithmetic_Op (P)
1148 or else Nkind (P) in N_Membership_Test
1149 or else Nkind (P) in N_Op_Compare
1151 -- This is also true for an alternative in a case expression
1153 or else Nkind (P) = N_Case_Expression_Alternative
1155 -- This is also true for a range operand in a membership test
1157 or else (Nkind (P) = N_Range
1158 and then Nkind (Parent (P)) in N_Membership_Test)
1159 then
1160 -- If_Expressions and Case_Expressions are treated as arithmetic
1161 -- ops, but if they appear in an assignment or similar contexts
1162 -- there is no overflow check that starts from that parent node,
1163 -- so apply check now.
1165 if Nkind_In (P, N_If_Expression, N_Case_Expression)
1166 and then not Is_Signed_Integer_Arithmetic_Op (Parent (P))
1167 then
1168 null;
1169 else
1170 return;
1171 end if;
1172 end if;
1174 -- Otherwise, we have a top level arithmetic operation node, and this
1175 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1176 -- modes. This is the case where we tell the machinery not to move into
1177 -- Bignum mode at this top level (of course the top level operation
1178 -- will still be in Bignum mode if either of its operands are of type
1179 -- Bignum).
1181 Minimize_Eliminate_Overflows (Op, Lo, Hi, Top_Level => True);
1183 -- That call may but does not necessarily change the result type of Op.
1184 -- It is the job of this routine to undo such changes, so that at the
1185 -- top level, we have the proper type. This "undoing" is a point at
1186 -- which a final overflow check may be applied.
1188 -- If the result type was not fiddled we are all set. We go to base
1189 -- types here because things may have been rewritten to generate the
1190 -- base type of the operand types.
1192 if Base_Type (Etype (Op)) = Base_Type (Result_Type) then
1193 return;
1195 -- Bignum case
1197 elsif Is_RTE (Etype (Op), RE_Bignum) then
1199 -- We need a sequence that looks like:
1201 -- Rnn : Result_Type;
1203 -- declare
1204 -- M : Mark_Id := SS_Mark;
1205 -- begin
1206 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
1207 -- SS_Release (M);
1208 -- end;
1210 -- This block is inserted (using Insert_Actions), and then the node
1211 -- is replaced with a reference to Rnn.
1213 -- If our parent is a conversion node then there is no point in
1214 -- generating a conversion to Result_Type. Instead, we let the parent
1215 -- handle this. Note that this special case is not just about
1216 -- optimization. Consider
1218 -- A,B,C : Integer;
1219 -- ...
1220 -- X := Long_Long_Integer'Base (A * (B ** C));
1222 -- Now the product may fit in Long_Long_Integer but not in Integer.
1223 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1224 -- overflow exception for this intermediate value.
1226 declare
1227 Blk : constant Node_Id := Make_Bignum_Block (Loc);
1228 Rnn : constant Entity_Id := Make_Temporary (Loc, 'R', Op);
1229 RHS : Node_Id;
1231 Rtype : Entity_Id;
1233 begin
1234 RHS := Convert_From_Bignum (Op);
1236 if Nkind (P) /= N_Type_Conversion then
1237 Convert_To_And_Rewrite (Result_Type, RHS);
1238 Rtype := Result_Type;
1240 -- Interesting question, do we need a check on that conversion
1241 -- operation. Answer, not if we know the result is in range.
1242 -- At the moment we are not taking advantage of this. To be
1243 -- looked at later ???
1245 else
1246 Rtype := LLIB;
1247 end if;
1249 Insert_Before
1250 (First (Statements (Handled_Statement_Sequence (Blk))),
1251 Make_Assignment_Statement (Loc,
1252 Name => New_Occurrence_Of (Rnn, Loc),
1253 Expression => RHS));
1255 Insert_Actions (Op, New_List (
1256 Make_Object_Declaration (Loc,
1257 Defining_Identifier => Rnn,
1258 Object_Definition => New_Occurrence_Of (Rtype, Loc)),
1259 Blk));
1261 Rewrite (Op, New_Occurrence_Of (Rnn, Loc));
1262 Analyze_And_Resolve (Op);
1263 end;
1265 -- Here we know the result is Long_Long_Integer'Base, or that it has
1266 -- been rewritten because the parent operation is a conversion. See
1267 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
1269 else
1270 pragma Assert
1271 (Etype (Op) = LLIB or else Nkind (Parent (Op)) = N_Type_Conversion);
1273 -- All we need to do here is to convert the result to the proper
1274 -- result type. As explained above for the Bignum case, we can
1275 -- omit this if our parent is a type conversion.
1277 if Nkind (P) /= N_Type_Conversion then
1278 Convert_To_And_Rewrite (Result_Type, Op);
1279 end if;
1281 Analyze_And_Resolve (Op);
1282 end if;
1283 end Apply_Arithmetic_Overflow_Minimized_Eliminated;
1285 ----------------------------
1286 -- Apply_Constraint_Check --
1287 ----------------------------
1289 procedure Apply_Constraint_Check
1290 (N : Node_Id;
1291 Typ : Entity_Id;
1292 No_Sliding : Boolean := False)
1294 Desig_Typ : Entity_Id;
1296 begin
1297 -- No checks inside a generic (check the instantiations)
1299 if Inside_A_Generic then
1300 return;
1301 end if;
1303 -- Apply required constraint checks
1305 if Is_Scalar_Type (Typ) then
1306 Apply_Scalar_Range_Check (N, Typ);
1308 elsif Is_Array_Type (Typ) then
1310 -- A useful optimization: an aggregate with only an others clause
1311 -- always has the right bounds.
1313 if Nkind (N) = N_Aggregate
1314 and then No (Expressions (N))
1315 and then Nkind
1316 (First (Choices (First (Component_Associations (N)))))
1317 = N_Others_Choice
1318 then
1319 return;
1320 end if;
1322 if Is_Constrained (Typ) then
1323 Apply_Length_Check (N, Typ);
1325 if No_Sliding then
1326 Apply_Range_Check (N, Typ);
1327 end if;
1328 else
1329 Apply_Range_Check (N, Typ);
1330 end if;
1332 elsif (Is_Record_Type (Typ) or else Is_Private_Type (Typ))
1333 and then Has_Discriminants (Base_Type (Typ))
1334 and then Is_Constrained (Typ)
1335 then
1336 Apply_Discriminant_Check (N, Typ);
1338 elsif Is_Access_Type (Typ) then
1340 Desig_Typ := Designated_Type (Typ);
1342 -- No checks necessary if expression statically null
1344 if Known_Null (N) then
1345 if Can_Never_Be_Null (Typ) then
1346 Install_Null_Excluding_Check (N);
1347 end if;
1349 -- No sliding possible on access to arrays
1351 elsif Is_Array_Type (Desig_Typ) then
1352 if Is_Constrained (Desig_Typ) then
1353 Apply_Length_Check (N, Typ);
1354 end if;
1356 Apply_Range_Check (N, Typ);
1358 -- Do not install a discriminant check for a constrained subtype
1359 -- created for an unconstrained nominal type because the subtype
1360 -- has the correct constraints by construction.
1362 elsif Has_Discriminants (Base_Type (Desig_Typ))
1363 and then Is_Constrained (Desig_Typ)
1364 and then not Is_Constr_Subt_For_U_Nominal (Desig_Typ)
1365 then
1366 Apply_Discriminant_Check (N, Typ);
1367 end if;
1369 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1370 -- this check if the constraint node is illegal, as shown by having
1371 -- an error posted. This additional guard prevents cascaded errors
1372 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1374 if Can_Never_Be_Null (Typ)
1375 and then not Can_Never_Be_Null (Etype (N))
1376 and then not Error_Posted (N)
1377 then
1378 Install_Null_Excluding_Check (N);
1379 end if;
1380 end if;
1381 end Apply_Constraint_Check;
1383 ------------------------------
1384 -- Apply_Discriminant_Check --
1385 ------------------------------
1387 procedure Apply_Discriminant_Check
1388 (N : Node_Id;
1389 Typ : Entity_Id;
1390 Lhs : Node_Id := Empty)
1392 Loc : constant Source_Ptr := Sloc (N);
1393 Do_Access : constant Boolean := Is_Access_Type (Typ);
1394 S_Typ : Entity_Id := Etype (N);
1395 Cond : Node_Id;
1396 T_Typ : Entity_Id;
1398 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1399 -- A heap object with an indefinite subtype is constrained by its
1400 -- initial value, and assigning to it requires a constraint_check.
1401 -- The target may be an explicit dereference, or a renaming of one.
1403 function Is_Aliased_Unconstrained_Component return Boolean;
1404 -- It is possible for an aliased component to have a nominal
1405 -- unconstrained subtype (through instantiation). If this is a
1406 -- discriminated component assigned in the expansion of an aggregate
1407 -- in an initialization, the check must be suppressed. This unusual
1408 -- situation requires a predicate of its own.
1410 ----------------------------------
1411 -- Denotes_Explicit_Dereference --
1412 ----------------------------------
1414 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1415 begin
1416 return
1417 Nkind (Obj) = N_Explicit_Dereference
1418 or else
1419 (Is_Entity_Name (Obj)
1420 and then Present (Renamed_Object (Entity (Obj)))
1421 and then Nkind (Renamed_Object (Entity (Obj))) =
1422 N_Explicit_Dereference);
1423 end Denotes_Explicit_Dereference;
1425 ----------------------------------------
1426 -- Is_Aliased_Unconstrained_Component --
1427 ----------------------------------------
1429 function Is_Aliased_Unconstrained_Component return Boolean is
1430 Comp : Entity_Id;
1431 Pref : Node_Id;
1433 begin
1434 if Nkind (Lhs) /= N_Selected_Component then
1435 return False;
1436 else
1437 Comp := Entity (Selector_Name (Lhs));
1438 Pref := Prefix (Lhs);
1439 end if;
1441 if Ekind (Comp) /= E_Component
1442 or else not Is_Aliased (Comp)
1443 then
1444 return False;
1445 end if;
1447 return not Comes_From_Source (Pref)
1448 and then In_Instance
1449 and then not Is_Constrained (Etype (Comp));
1450 end Is_Aliased_Unconstrained_Component;
1452 -- Start of processing for Apply_Discriminant_Check
1454 begin
1455 if Do_Access then
1456 T_Typ := Designated_Type (Typ);
1457 else
1458 T_Typ := Typ;
1459 end if;
1461 -- If the expression is a function call that returns a limited object
1462 -- it cannot be copied. It is not clear how to perform the proper
1463 -- discriminant check in this case because the discriminant value must
1464 -- be retrieved from the constructed object itself.
1466 if Nkind (N) = N_Function_Call
1467 and then Is_Limited_Type (Typ)
1468 and then Is_Entity_Name (Name (N))
1469 and then Returns_By_Ref (Entity (Name (N)))
1470 then
1471 return;
1472 end if;
1474 -- Only apply checks when generating code and discriminant checks are
1475 -- not suppressed. In GNATprove mode, we do not apply the checks, but we
1476 -- still analyze the expression to possibly issue errors on SPARK code
1477 -- when a run-time error can be detected at compile time.
1479 if not GNATprove_Mode then
1480 if not Expander_Active
1481 or else Discriminant_Checks_Suppressed (T_Typ)
1482 then
1483 return;
1484 end if;
1485 end if;
1487 -- No discriminant checks necessary for an access when expression is
1488 -- statically Null. This is not only an optimization, it is fundamental
1489 -- because otherwise discriminant checks may be generated in init procs
1490 -- for types containing an access to a not-yet-frozen record, causing a
1491 -- deadly forward reference.
1493 -- Also, if the expression is of an access type whose designated type is
1494 -- incomplete, then the access value must be null and we suppress the
1495 -- check.
1497 if Known_Null (N) then
1498 return;
1500 elsif Is_Access_Type (S_Typ) then
1501 S_Typ := Designated_Type (S_Typ);
1503 if Ekind (S_Typ) = E_Incomplete_Type then
1504 return;
1505 end if;
1506 end if;
1508 -- If an assignment target is present, then we need to generate the
1509 -- actual subtype if the target is a parameter or aliased object with
1510 -- an unconstrained nominal subtype.
1512 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1513 -- subtype to the parameter and dereference cases, since other aliased
1514 -- objects are unconstrained (unless the nominal subtype is explicitly
1515 -- constrained).
1517 if Present (Lhs)
1518 and then (Present (Param_Entity (Lhs))
1519 or else (Ada_Version < Ada_2005
1520 and then not Is_Constrained (T_Typ)
1521 and then Is_Aliased_View (Lhs)
1522 and then not Is_Aliased_Unconstrained_Component)
1523 or else (Ada_Version >= Ada_2005
1524 and then not Is_Constrained (T_Typ)
1525 and then Denotes_Explicit_Dereference (Lhs)
1526 and then Nkind (Original_Node (Lhs)) /=
1527 N_Function_Call))
1528 then
1529 T_Typ := Get_Actual_Subtype (Lhs);
1530 end if;
1532 -- Nothing to do if the type is unconstrained (this is the case where
1533 -- the actual subtype in the RM sense of N is unconstrained and no check
1534 -- is required).
1536 if not Is_Constrained (T_Typ) then
1537 return;
1539 -- Ada 2005: nothing to do if the type is one for which there is a
1540 -- partial view that is constrained.
1542 elsif Ada_Version >= Ada_2005
1543 and then Object_Type_Has_Constrained_Partial_View
1544 (Typ => Base_Type (T_Typ),
1545 Scop => Current_Scope)
1546 then
1547 return;
1548 end if;
1550 -- Nothing to do if the type is an Unchecked_Union
1552 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1553 return;
1554 end if;
1556 -- Suppress checks if the subtypes are the same. The check must be
1557 -- preserved in an assignment to a formal, because the constraint is
1558 -- given by the actual.
1560 if Nkind (Original_Node (N)) /= N_Allocator
1561 and then (No (Lhs)
1562 or else not Is_Entity_Name (Lhs)
1563 or else No (Param_Entity (Lhs)))
1564 then
1565 if (Etype (N) = Typ
1566 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1567 and then not Is_Aliased_View (Lhs)
1568 then
1569 return;
1570 end if;
1572 -- We can also eliminate checks on allocators with a subtype mark that
1573 -- coincides with the context type. The context type may be a subtype
1574 -- without a constraint (common case, a generic actual).
1576 elsif Nkind (Original_Node (N)) = N_Allocator
1577 and then Is_Entity_Name (Expression (Original_Node (N)))
1578 then
1579 declare
1580 Alloc_Typ : constant Entity_Id :=
1581 Entity (Expression (Original_Node (N)));
1583 begin
1584 if Alloc_Typ = T_Typ
1585 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1586 and then Is_Entity_Name (
1587 Subtype_Indication (Parent (T_Typ)))
1588 and then Alloc_Typ = Base_Type (T_Typ))
1590 then
1591 return;
1592 end if;
1593 end;
1594 end if;
1596 -- See if we have a case where the types are both constrained, and all
1597 -- the constraints are constants. In this case, we can do the check
1598 -- successfully at compile time.
1600 -- We skip this check for the case where the node is rewritten as
1601 -- an allocator, because it already carries the context subtype,
1602 -- and extracting the discriminants from the aggregate is messy.
1604 if Is_Constrained (S_Typ)
1605 and then Nkind (Original_Node (N)) /= N_Allocator
1606 then
1607 declare
1608 DconT : Elmt_Id;
1609 Discr : Entity_Id;
1610 DconS : Elmt_Id;
1611 ItemS : Node_Id;
1612 ItemT : Node_Id;
1614 begin
1615 -- S_Typ may not have discriminants in the case where it is a
1616 -- private type completed by a default discriminated type. In that
1617 -- case, we need to get the constraints from the underlying type.
1618 -- If the underlying type is unconstrained (i.e. has no default
1619 -- discriminants) no check is needed.
1621 if Has_Discriminants (S_Typ) then
1622 Discr := First_Discriminant (S_Typ);
1623 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1625 else
1626 Discr := First_Discriminant (Underlying_Type (S_Typ));
1627 DconS :=
1628 First_Elmt
1629 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1631 if No (DconS) then
1632 return;
1633 end if;
1635 -- A further optimization: if T_Typ is derived from S_Typ
1636 -- without imposing a constraint, no check is needed.
1638 if Nkind (Original_Node (Parent (T_Typ))) =
1639 N_Full_Type_Declaration
1640 then
1641 declare
1642 Type_Def : constant Node_Id :=
1643 Type_Definition (Original_Node (Parent (T_Typ)));
1644 begin
1645 if Nkind (Type_Def) = N_Derived_Type_Definition
1646 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1647 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1648 then
1649 return;
1650 end if;
1651 end;
1652 end if;
1653 end if;
1655 -- Constraint may appear in full view of type
1657 if Ekind (T_Typ) = E_Private_Subtype
1658 and then Present (Full_View (T_Typ))
1659 then
1660 DconT :=
1661 First_Elmt (Discriminant_Constraint (Full_View (T_Typ)));
1662 else
1663 DconT :=
1664 First_Elmt (Discriminant_Constraint (T_Typ));
1665 end if;
1667 while Present (Discr) loop
1668 ItemS := Node (DconS);
1669 ItemT := Node (DconT);
1671 -- For a discriminated component type constrained by the
1672 -- current instance of an enclosing type, there is no
1673 -- applicable discriminant check.
1675 if Nkind (ItemT) = N_Attribute_Reference
1676 and then Is_Access_Type (Etype (ItemT))
1677 and then Is_Entity_Name (Prefix (ItemT))
1678 and then Is_Type (Entity (Prefix (ItemT)))
1679 then
1680 return;
1681 end if;
1683 -- If the expressions for the discriminants are identical
1684 -- and it is side-effect free (for now just an entity),
1685 -- this may be a shared constraint, e.g. from a subtype
1686 -- without a constraint introduced as a generic actual.
1687 -- Examine other discriminants if any.
1689 if ItemS = ItemT
1690 and then Is_Entity_Name (ItemS)
1691 then
1692 null;
1694 elsif not Is_OK_Static_Expression (ItemS)
1695 or else not Is_OK_Static_Expression (ItemT)
1696 then
1697 exit;
1699 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1700 if Do_Access then -- needs run-time check.
1701 exit;
1702 else
1703 Apply_Compile_Time_Constraint_Error
1704 (N, "incorrect value for discriminant&??",
1705 CE_Discriminant_Check_Failed, Ent => Discr);
1706 return;
1707 end if;
1708 end if;
1710 Next_Elmt (DconS);
1711 Next_Elmt (DconT);
1712 Next_Discriminant (Discr);
1713 end loop;
1715 if No (Discr) then
1716 return;
1717 end if;
1718 end;
1719 end if;
1721 -- In GNATprove mode, we do not apply the checks
1723 if GNATprove_Mode then
1724 return;
1725 end if;
1727 -- Here we need a discriminant check. First build the expression
1728 -- for the comparisons of the discriminants:
1730 -- (n.disc1 /= typ.disc1) or else
1731 -- (n.disc2 /= typ.disc2) or else
1732 -- ...
1733 -- (n.discn /= typ.discn)
1735 Cond := Build_Discriminant_Checks (N, T_Typ);
1737 -- If Lhs is set and is a parameter, then the condition is guarded by:
1738 -- lhs'constrained and then (condition built above)
1740 if Present (Param_Entity (Lhs)) then
1741 Cond :=
1742 Make_And_Then (Loc,
1743 Left_Opnd =>
1744 Make_Attribute_Reference (Loc,
1745 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1746 Attribute_Name => Name_Constrained),
1747 Right_Opnd => Cond);
1748 end if;
1750 if Do_Access then
1751 Cond := Guard_Access (Cond, Loc, N);
1752 end if;
1754 Insert_Action (N,
1755 Make_Raise_Constraint_Error (Loc,
1756 Condition => Cond,
1757 Reason => CE_Discriminant_Check_Failed));
1758 end Apply_Discriminant_Check;
1760 -------------------------
1761 -- Apply_Divide_Checks --
1762 -------------------------
1764 procedure Apply_Divide_Checks (N : Node_Id) is
1765 Loc : constant Source_Ptr := Sloc (N);
1766 Typ : constant Entity_Id := Etype (N);
1767 Left : constant Node_Id := Left_Opnd (N);
1768 Right : constant Node_Id := Right_Opnd (N);
1770 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1771 -- Current overflow checking mode
1773 LLB : Uint;
1774 Llo : Uint;
1775 Lhi : Uint;
1776 LOK : Boolean;
1777 Rlo : Uint;
1778 Rhi : Uint;
1779 ROK : Boolean;
1781 pragma Warnings (Off, Lhi);
1782 -- Don't actually use this value
1784 begin
1785 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1786 -- operating on signed integer types, then the only thing this routine
1787 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1788 -- procedure will (possibly later on during recursive downward calls),
1789 -- ensure that any needed overflow/division checks are properly applied.
1791 if Mode in Minimized_Or_Eliminated
1792 and then Is_Signed_Integer_Type (Typ)
1793 then
1794 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
1795 return;
1796 end if;
1798 -- Proceed here in SUPPRESSED or CHECKED modes
1800 if Expander_Active
1801 and then not Backend_Divide_Checks_On_Target
1802 and then Check_Needed (Right, Division_Check)
1803 then
1804 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1806 -- Deal with division check
1808 if Do_Division_Check (N)
1809 and then not Division_Checks_Suppressed (Typ)
1810 then
1811 Apply_Division_Check (N, Rlo, Rhi, ROK);
1812 end if;
1814 -- Deal with overflow check
1816 if Do_Overflow_Check (N)
1817 and then not Overflow_Checks_Suppressed (Etype (N))
1818 then
1819 Set_Do_Overflow_Check (N, False);
1821 -- Test for extremely annoying case of xxx'First divided by -1
1822 -- for division of signed integer types (only overflow case).
1824 if Nkind (N) = N_Op_Divide
1825 and then Is_Signed_Integer_Type (Typ)
1826 then
1827 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1828 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1830 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1831 and then
1832 ((not LOK) or else (Llo = LLB))
1833 then
1834 -- Ensure that expressions are not evaluated twice (once
1835 -- for their runtime checks and once for their regular
1836 -- computation).
1838 Force_Evaluation (Left, Mode => Strict);
1839 Force_Evaluation (Right, Mode => Strict);
1841 Insert_Action (N,
1842 Make_Raise_Constraint_Error (Loc,
1843 Condition =>
1844 Make_And_Then (Loc,
1845 Left_Opnd =>
1846 Make_Op_Eq (Loc,
1847 Left_Opnd =>
1848 Duplicate_Subexpr_Move_Checks (Left),
1849 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1851 Right_Opnd =>
1852 Make_Op_Eq (Loc,
1853 Left_Opnd => Duplicate_Subexpr (Right),
1854 Right_Opnd => Make_Integer_Literal (Loc, -1))),
1856 Reason => CE_Overflow_Check_Failed));
1857 end if;
1858 end if;
1859 end if;
1860 end if;
1861 end Apply_Divide_Checks;
1863 --------------------------
1864 -- Apply_Division_Check --
1865 --------------------------
1867 procedure Apply_Division_Check
1868 (N : Node_Id;
1869 Rlo : Uint;
1870 Rhi : Uint;
1871 ROK : Boolean)
1873 pragma Assert (Do_Division_Check (N));
1875 Loc : constant Source_Ptr := Sloc (N);
1876 Right : constant Node_Id := Right_Opnd (N);
1878 begin
1879 if Expander_Active
1880 and then not Backend_Divide_Checks_On_Target
1881 and then Check_Needed (Right, Division_Check)
1882 then
1883 -- See if division by zero possible, and if so generate test. This
1884 -- part of the test is not controlled by the -gnato switch, since
1885 -- it is a Division_Check and not an Overflow_Check.
1887 if Do_Division_Check (N) then
1888 Set_Do_Division_Check (N, False);
1890 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1891 Insert_Action (N,
1892 Make_Raise_Constraint_Error (Loc,
1893 Condition =>
1894 Make_Op_Eq (Loc,
1895 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1896 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1897 Reason => CE_Divide_By_Zero));
1898 end if;
1899 end if;
1900 end if;
1901 end Apply_Division_Check;
1903 ----------------------------------
1904 -- Apply_Float_Conversion_Check --
1905 ----------------------------------
1907 -- Let F and I be the source and target types of the conversion. The RM
1908 -- specifies that a floating-point value X is rounded to the nearest
1909 -- integer, with halfway cases being rounded away from zero. The rounded
1910 -- value of X is checked against I'Range.
1912 -- The catch in the above paragraph is that there is no good way to know
1913 -- whether the round-to-integer operation resulted in overflow. A remedy is
1914 -- to perform a range check in the floating-point domain instead, however:
1916 -- (1) The bounds may not be known at compile time
1917 -- (2) The check must take into account rounding or truncation.
1918 -- (3) The range of type I may not be exactly representable in F.
1919 -- (4) For the rounding case, The end-points I'First - 0.5 and
1920 -- I'Last + 0.5 may or may not be in range, depending on the
1921 -- sign of I'First and I'Last.
1922 -- (5) X may be a NaN, which will fail any comparison
1924 -- The following steps correctly convert X with rounding:
1926 -- (1) If either I'First or I'Last is not known at compile time, use
1927 -- I'Base instead of I in the next three steps and perform a
1928 -- regular range check against I'Range after conversion.
1929 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1930 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1931 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1932 -- In other words, take one of the closest floating-point numbers
1933 -- (which is an integer value) to I'First, and see if it is in
1934 -- range or not.
1935 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1936 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1937 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1938 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1939 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1941 -- For the truncating case, replace steps (2) and (3) as follows:
1942 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1943 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1944 -- Lo_OK be True.
1945 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1946 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1947 -- Hi_OK be True.
1949 procedure Apply_Float_Conversion_Check
1950 (Ck_Node : Node_Id;
1951 Target_Typ : Entity_Id)
1953 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1954 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1955 Loc : constant Source_Ptr := Sloc (Ck_Node);
1956 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1957 Target_Base : constant Entity_Id :=
1958 Implementation_Base_Type (Target_Typ);
1960 Par : constant Node_Id := Parent (Ck_Node);
1961 pragma Assert (Nkind (Par) = N_Type_Conversion);
1962 -- Parent of check node, must be a type conversion
1964 Truncate : constant Boolean := Float_Truncate (Par);
1965 Max_Bound : constant Uint :=
1966 UI_Expon
1967 (Machine_Radix_Value (Expr_Type),
1968 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1970 -- Largest bound, so bound plus or minus half is a machine number of F
1972 Ifirst, Ilast : Uint;
1973 -- Bounds of integer type
1975 Lo, Hi : Ureal;
1976 -- Bounds to check in floating-point domain
1978 Lo_OK, Hi_OK : Boolean;
1979 -- True iff Lo resp. Hi belongs to I'Range
1981 Lo_Chk, Hi_Chk : Node_Id;
1982 -- Expressions that are False iff check fails
1984 Reason : RT_Exception_Code;
1986 begin
1987 -- We do not need checks if we are not generating code (i.e. the full
1988 -- expander is not active). In SPARK mode, we specifically don't want
1989 -- the frontend to expand these checks, which are dealt with directly
1990 -- in the formal verification backend.
1992 if not Expander_Active then
1993 return;
1994 end if;
1996 if not Compile_Time_Known_Value (LB)
1997 or not Compile_Time_Known_Value (HB)
1998 then
1999 declare
2000 -- First check that the value falls in the range of the base type,
2001 -- to prevent overflow during conversion and then perform a
2002 -- regular range check against the (dynamic) bounds.
2004 pragma Assert (Target_Base /= Target_Typ);
2006 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
2008 begin
2009 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
2010 Set_Etype (Temp, Target_Base);
2012 Insert_Action (Parent (Par),
2013 Make_Object_Declaration (Loc,
2014 Defining_Identifier => Temp,
2015 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2016 Expression => New_Copy_Tree (Par)),
2017 Suppress => All_Checks);
2019 Insert_Action (Par,
2020 Make_Raise_Constraint_Error (Loc,
2021 Condition =>
2022 Make_Not_In (Loc,
2023 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2024 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2025 Reason => CE_Range_Check_Failed));
2026 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2028 return;
2029 end;
2030 end if;
2032 -- Get the (static) bounds of the target type
2034 Ifirst := Expr_Value (LB);
2035 Ilast := Expr_Value (HB);
2037 -- A simple optimization: if the expression is a universal literal,
2038 -- we can do the comparison with the bounds and the conversion to
2039 -- an integer type statically. The range checks are unchanged.
2041 if Nkind (Ck_Node) = N_Real_Literal
2042 and then Etype (Ck_Node) = Universal_Real
2043 and then Is_Integer_Type (Target_Typ)
2044 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
2045 then
2046 declare
2047 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
2049 begin
2050 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2052 -- Conversion is safe
2054 Rewrite (Parent (Ck_Node),
2055 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2056 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
2057 return;
2058 end if;
2059 end;
2060 end if;
2062 -- Check against lower bound
2064 if Truncate and then Ifirst > 0 then
2065 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2066 Lo_OK := False;
2068 elsif Truncate then
2069 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2070 Lo_OK := True;
2072 elsif abs (Ifirst) < Max_Bound then
2073 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2074 Lo_OK := (Ifirst > 0);
2076 else
2077 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
2078 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2079 end if;
2081 if Lo_OK then
2083 -- Lo_Chk := (X >= Lo)
2085 Lo_Chk := Make_Op_Ge (Loc,
2086 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2087 Right_Opnd => Make_Real_Literal (Loc, Lo));
2089 else
2090 -- Lo_Chk := (X > Lo)
2092 Lo_Chk := Make_Op_Gt (Loc,
2093 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2094 Right_Opnd => Make_Real_Literal (Loc, Lo));
2095 end if;
2097 -- Check against higher bound
2099 if Truncate and then Ilast < 0 then
2100 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
2101 Hi_OK := False;
2103 elsif Truncate then
2104 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2105 Hi_OK := True;
2107 elsif abs (Ilast) < Max_Bound then
2108 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2109 Hi_OK := (Ilast < 0);
2110 else
2111 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
2112 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2113 end if;
2115 if Hi_OK then
2117 -- Hi_Chk := (X <= Hi)
2119 Hi_Chk := Make_Op_Le (Loc,
2120 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2121 Right_Opnd => Make_Real_Literal (Loc, Hi));
2123 else
2124 -- Hi_Chk := (X < Hi)
2126 Hi_Chk := Make_Op_Lt (Loc,
2127 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2128 Right_Opnd => Make_Real_Literal (Loc, Hi));
2129 end if;
2131 -- If the bounds of the target type are the same as those of the base
2132 -- type, the check is an overflow check as a range check is not
2133 -- performed in these cases.
2135 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2136 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2137 then
2138 Reason := CE_Overflow_Check_Failed;
2139 else
2140 Reason := CE_Range_Check_Failed;
2141 end if;
2143 -- Raise CE if either conditions does not hold
2145 Insert_Action (Ck_Node,
2146 Make_Raise_Constraint_Error (Loc,
2147 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
2148 Reason => Reason));
2149 end Apply_Float_Conversion_Check;
2151 ------------------------
2152 -- Apply_Length_Check --
2153 ------------------------
2155 procedure Apply_Length_Check
2156 (Ck_Node : Node_Id;
2157 Target_Typ : Entity_Id;
2158 Source_Typ : Entity_Id := Empty)
2160 begin
2161 Apply_Selected_Length_Checks
2162 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2163 end Apply_Length_Check;
2165 -------------------------------------
2166 -- Apply_Parameter_Aliasing_Checks --
2167 -------------------------------------
2169 procedure Apply_Parameter_Aliasing_Checks
2170 (Call : Node_Id;
2171 Subp : Entity_Id)
2173 Loc : constant Source_Ptr := Sloc (Call);
2175 function May_Cause_Aliasing
2176 (Formal_1 : Entity_Id;
2177 Formal_2 : Entity_Id) return Boolean;
2178 -- Determine whether two formal parameters can alias each other
2179 -- depending on their modes.
2181 function Original_Actual (N : Node_Id) return Node_Id;
2182 -- The expander may replace an actual with a temporary for the sake of
2183 -- side effect removal. The temporary may hide a potential aliasing as
2184 -- it does not share the address of the actual. This routine attempts
2185 -- to retrieve the original actual.
2187 procedure Overlap_Check
2188 (Actual_1 : Node_Id;
2189 Actual_2 : Node_Id;
2190 Formal_1 : Entity_Id;
2191 Formal_2 : Entity_Id;
2192 Check : in out Node_Id);
2193 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2194 -- If detailed exception messages are enabled, the check is augmented to
2195 -- provide information about the names of the corresponding formals. See
2196 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2197 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2198 -- Check contains all and-ed simple tests generated so far or remains
2199 -- unchanged in the case of detailed exception messaged.
2201 ------------------------
2202 -- May_Cause_Aliasing --
2203 ------------------------
2205 function May_Cause_Aliasing
2206 (Formal_1 : Entity_Id;
2207 Formal_2 : Entity_Id) return Boolean
2209 begin
2210 -- The following combination cannot lead to aliasing
2212 -- Formal 1 Formal 2
2213 -- IN IN
2215 if Ekind (Formal_1) = E_In_Parameter
2216 and then
2217 Ekind (Formal_2) = E_In_Parameter
2218 then
2219 return False;
2221 -- The following combinations may lead to aliasing
2223 -- Formal 1 Formal 2
2224 -- IN OUT
2225 -- IN IN OUT
2226 -- OUT IN
2227 -- OUT IN OUT
2228 -- OUT OUT
2230 else
2231 return True;
2232 end if;
2233 end May_Cause_Aliasing;
2235 ---------------------
2236 -- Original_Actual --
2237 ---------------------
2239 function Original_Actual (N : Node_Id) return Node_Id is
2240 begin
2241 if Nkind (N) = N_Type_Conversion then
2242 return Expression (N);
2244 -- The expander created a temporary to capture the result of a type
2245 -- conversion where the expression is the real actual.
2247 elsif Nkind (N) = N_Identifier
2248 and then Present (Original_Node (N))
2249 and then Nkind (Original_Node (N)) = N_Type_Conversion
2250 then
2251 return Expression (Original_Node (N));
2252 end if;
2254 return N;
2255 end Original_Actual;
2257 -------------------
2258 -- Overlap_Check --
2259 -------------------
2261 procedure Overlap_Check
2262 (Actual_1 : Node_Id;
2263 Actual_2 : Node_Id;
2264 Formal_1 : Entity_Id;
2265 Formal_2 : Entity_Id;
2266 Check : in out Node_Id)
2268 Cond : Node_Id;
2269 ID_Casing : constant Casing_Type :=
2270 Identifier_Casing (Source_Index (Current_Sem_Unit));
2272 begin
2273 -- Generate:
2274 -- Actual_1'Overlaps_Storage (Actual_2)
2276 Cond :=
2277 Make_Attribute_Reference (Loc,
2278 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2279 Attribute_Name => Name_Overlaps_Storage,
2280 Expressions =>
2281 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2283 -- Generate the following check when detailed exception messages are
2284 -- enabled:
2286 -- if Actual_1'Overlaps_Storage (Actual_2) then
2287 -- raise Program_Error with <detailed message>;
2288 -- end if;
2290 if Exception_Extra_Info then
2291 Start_String;
2293 -- Do not generate location information for internal calls
2295 if Comes_From_Source (Call) then
2296 Store_String_Chars (Build_Location_String (Loc));
2297 Store_String_Char (' ');
2298 end if;
2300 Store_String_Chars ("aliased parameters, actuals for """);
2302 Get_Name_String (Chars (Formal_1));
2303 Set_Casing (ID_Casing);
2304 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2306 Store_String_Chars (""" and """);
2308 Get_Name_String (Chars (Formal_2));
2309 Set_Casing (ID_Casing);
2310 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2312 Store_String_Chars (""" overlap");
2314 Insert_Action (Call,
2315 Make_If_Statement (Loc,
2316 Condition => Cond,
2317 Then_Statements => New_List (
2318 Make_Raise_Statement (Loc,
2319 Name =>
2320 New_Occurrence_Of (Standard_Program_Error, Loc),
2321 Expression => Make_String_Literal (Loc, End_String)))));
2323 -- Create a sequence of overlapping checks by and-ing them all
2324 -- together.
2326 else
2327 if No (Check) then
2328 Check := Cond;
2329 else
2330 Check :=
2331 Make_And_Then (Loc,
2332 Left_Opnd => Check,
2333 Right_Opnd => Cond);
2334 end if;
2335 end if;
2336 end Overlap_Check;
2338 -- Local variables
2340 Actual_1 : Node_Id;
2341 Actual_2 : Node_Id;
2342 Check : Node_Id;
2343 Formal_1 : Entity_Id;
2344 Formal_2 : Entity_Id;
2345 Orig_Act_1 : Node_Id;
2346 Orig_Act_2 : Node_Id;
2348 -- Start of processing for Apply_Parameter_Aliasing_Checks
2350 begin
2351 Check := Empty;
2353 Actual_1 := First_Actual (Call);
2354 Formal_1 := First_Formal (Subp);
2355 while Present (Actual_1) and then Present (Formal_1) loop
2356 Orig_Act_1 := Original_Actual (Actual_1);
2358 -- Ensure that the actual is an object that is not passed by value.
2359 -- Elementary types are always passed by value, therefore actuals of
2360 -- such types cannot lead to aliasing. An aggregate is an object in
2361 -- Ada 2012, but an actual that is an aggregate cannot overlap with
2362 -- another actual. A type that is By_Reference (such as an array of
2363 -- controlled types) is not subject to the check because any update
2364 -- will be done in place and a subsequent read will always see the
2365 -- correct value, see RM 6.2 (12/3).
2367 if Nkind (Orig_Act_1) = N_Aggregate
2368 or else (Nkind (Orig_Act_1) = N_Qualified_Expression
2369 and then Nkind (Expression (Orig_Act_1)) = N_Aggregate)
2370 then
2371 null;
2373 elsif Is_Object_Reference (Orig_Act_1)
2374 and then not Is_Elementary_Type (Etype (Orig_Act_1))
2375 and then not Is_By_Reference_Type (Etype (Orig_Act_1))
2376 then
2377 Actual_2 := Next_Actual (Actual_1);
2378 Formal_2 := Next_Formal (Formal_1);
2379 while Present (Actual_2) and then Present (Formal_2) loop
2380 Orig_Act_2 := Original_Actual (Actual_2);
2382 -- The other actual we are testing against must also denote
2383 -- a non pass-by-value object. Generate the check only when
2384 -- the mode of the two formals may lead to aliasing.
2386 if Is_Object_Reference (Orig_Act_2)
2387 and then not Is_Elementary_Type (Etype (Orig_Act_2))
2388 and then May_Cause_Aliasing (Formal_1, Formal_2)
2389 then
2390 Remove_Side_Effects (Actual_1);
2391 Remove_Side_Effects (Actual_2);
2393 Overlap_Check
2394 (Actual_1 => Actual_1,
2395 Actual_2 => Actual_2,
2396 Formal_1 => Formal_1,
2397 Formal_2 => Formal_2,
2398 Check => Check);
2399 end if;
2401 Next_Actual (Actual_2);
2402 Next_Formal (Formal_2);
2403 end loop;
2404 end if;
2406 Next_Actual (Actual_1);
2407 Next_Formal (Formal_1);
2408 end loop;
2410 -- Place a simple check right before the call
2412 if Present (Check) and then not Exception_Extra_Info then
2413 Insert_Action (Call,
2414 Make_Raise_Program_Error (Loc,
2415 Condition => Check,
2416 Reason => PE_Aliased_Parameters));
2417 end if;
2418 end Apply_Parameter_Aliasing_Checks;
2420 -------------------------------------
2421 -- Apply_Parameter_Validity_Checks --
2422 -------------------------------------
2424 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2425 Subp_Decl : Node_Id;
2427 procedure Add_Validity_Check
2428 (Formal : Entity_Id;
2429 Prag_Nam : Name_Id;
2430 For_Result : Boolean := False);
2431 -- Add a single 'Valid[_Scalar] check which verifies the initialization
2432 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2433 -- Set flag For_Result when to verify the result of a function.
2435 ------------------------
2436 -- Add_Validity_Check --
2437 ------------------------
2439 procedure Add_Validity_Check
2440 (Formal : Entity_Id;
2441 Prag_Nam : Name_Id;
2442 For_Result : Boolean := False)
2444 procedure Build_Pre_Post_Condition (Expr : Node_Id);
2445 -- Create a pre/postcondition pragma that tests expression Expr
2447 ------------------------------
2448 -- Build_Pre_Post_Condition --
2449 ------------------------------
2451 procedure Build_Pre_Post_Condition (Expr : Node_Id) is
2452 Loc : constant Source_Ptr := Sloc (Subp);
2453 Decls : List_Id;
2454 Prag : Node_Id;
2456 begin
2457 Prag :=
2458 Make_Pragma (Loc,
2459 Chars => Prag_Nam,
2460 Pragma_Argument_Associations => New_List (
2461 Make_Pragma_Argument_Association (Loc,
2462 Chars => Name_Check,
2463 Expression => Expr)));
2465 -- Add a message unless exception messages are suppressed
2467 if not Exception_Locations_Suppressed then
2468 Append_To (Pragma_Argument_Associations (Prag),
2469 Make_Pragma_Argument_Association (Loc,
2470 Chars => Name_Message,
2471 Expression =>
2472 Make_String_Literal (Loc,
2473 Strval => "failed "
2474 & Get_Name_String (Prag_Nam)
2475 & " from "
2476 & Build_Location_String (Loc))));
2477 end if;
2479 -- Insert the pragma in the tree
2481 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2482 Add_Global_Declaration (Prag);
2483 Analyze (Prag);
2485 -- PPC pragmas associated with subprogram bodies must be inserted
2486 -- in the declarative part of the body.
2488 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2489 Decls := Declarations (Subp_Decl);
2491 if No (Decls) then
2492 Decls := New_List;
2493 Set_Declarations (Subp_Decl, Decls);
2494 end if;
2496 Prepend_To (Decls, Prag);
2497 Analyze (Prag);
2499 -- For subprogram declarations insert the PPC pragma right after
2500 -- the declarative node.
2502 else
2503 Insert_After_And_Analyze (Subp_Decl, Prag);
2504 end if;
2505 end Build_Pre_Post_Condition;
2507 -- Local variables
2509 Loc : constant Source_Ptr := Sloc (Subp);
2510 Typ : constant Entity_Id := Etype (Formal);
2511 Check : Node_Id;
2512 Nam : Name_Id;
2514 -- Start of processing for Add_Validity_Check
2516 begin
2517 -- For scalars, generate 'Valid test
2519 if Is_Scalar_Type (Typ) then
2520 Nam := Name_Valid;
2522 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2524 elsif Scalar_Part_Present (Typ) then
2525 Nam := Name_Valid_Scalars;
2527 -- No test needed for other cases (no scalars to test)
2529 else
2530 return;
2531 end if;
2533 -- Step 1: Create the expression to verify the validity of the
2534 -- context.
2536 Check := New_Occurrence_Of (Formal, Loc);
2538 -- When processing a function result, use 'Result. Generate
2539 -- Context'Result
2541 if For_Result then
2542 Check :=
2543 Make_Attribute_Reference (Loc,
2544 Prefix => Check,
2545 Attribute_Name => Name_Result);
2546 end if;
2548 -- Generate:
2549 -- Context['Result]'Valid[_Scalars]
2551 Check :=
2552 Make_Attribute_Reference (Loc,
2553 Prefix => Check,
2554 Attribute_Name => Nam);
2556 -- Step 2: Create a pre or post condition pragma
2558 Build_Pre_Post_Condition (Check);
2559 end Add_Validity_Check;
2561 -- Local variables
2563 Formal : Entity_Id;
2564 Subp_Spec : Node_Id;
2566 -- Start of processing for Apply_Parameter_Validity_Checks
2568 begin
2569 -- Extract the subprogram specification and declaration nodes
2571 Subp_Spec := Parent (Subp);
2573 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2574 Subp_Spec := Parent (Subp_Spec);
2575 end if;
2577 Subp_Decl := Parent (Subp_Spec);
2579 if not Comes_From_Source (Subp)
2581 -- Do not process formal subprograms because the corresponding actual
2582 -- will receive the proper checks when the instance is analyzed.
2584 or else Is_Formal_Subprogram (Subp)
2586 -- Do not process imported subprograms since pre and postconditions
2587 -- are never verified on routines coming from a different language.
2589 or else Is_Imported (Subp)
2590 or else Is_Intrinsic_Subprogram (Subp)
2592 -- The PPC pragmas generated by this routine do not correspond to
2593 -- source aspects, therefore they cannot be applied to abstract
2594 -- subprograms.
2596 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
2598 -- Do not consider subprogram renaminds because the renamed entity
2599 -- already has the proper PPC pragmas.
2601 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2603 -- Do not process null procedures because there is no benefit of
2604 -- adding the checks to a no action routine.
2606 or else (Nkind (Subp_Spec) = N_Procedure_Specification
2607 and then Null_Present (Subp_Spec))
2608 then
2609 return;
2610 end if;
2612 -- Inspect all the formals applying aliasing and scalar initialization
2613 -- checks where applicable.
2615 Formal := First_Formal (Subp);
2616 while Present (Formal) loop
2618 -- Generate the following scalar initialization checks for each
2619 -- formal parameter:
2621 -- mode IN - Pre => Formal'Valid[_Scalars]
2622 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2623 -- mode OUT - Post => Formal'Valid[_Scalars]
2625 if Check_Validity_Of_Parameters then
2626 if Ekind_In (Formal, E_In_Parameter, E_In_Out_Parameter) then
2627 Add_Validity_Check (Formal, Name_Precondition, False);
2628 end if;
2630 if Ekind_In (Formal, E_In_Out_Parameter, E_Out_Parameter) then
2631 Add_Validity_Check (Formal, Name_Postcondition, False);
2632 end if;
2633 end if;
2635 Next_Formal (Formal);
2636 end loop;
2638 -- Generate following scalar initialization check for function result:
2640 -- Post => Subp'Result'Valid[_Scalars]
2642 if Check_Validity_Of_Parameters and then Ekind (Subp) = E_Function then
2643 Add_Validity_Check (Subp, Name_Postcondition, True);
2644 end if;
2645 end Apply_Parameter_Validity_Checks;
2647 ---------------------------
2648 -- Apply_Predicate_Check --
2649 ---------------------------
2651 procedure Apply_Predicate_Check
2652 (N : Node_Id;
2653 Typ : Entity_Id;
2654 Fun : Entity_Id := Empty)
2656 S : Entity_Id;
2658 begin
2659 if Predicate_Checks_Suppressed (Empty) then
2660 return;
2662 elsif Predicates_Ignored (Typ) then
2663 return;
2665 elsif Present (Predicate_Function (Typ)) then
2666 S := Current_Scope;
2667 while Present (S) and then not Is_Subprogram (S) loop
2668 S := Scope (S);
2669 end loop;
2671 -- A predicate check does not apply within internally generated
2672 -- subprograms, such as TSS functions.
2674 if Within_Internal_Subprogram then
2675 return;
2677 -- If the check appears within the predicate function itself, it
2678 -- means that the user specified a check whose formal is the
2679 -- predicated subtype itself, rather than some covering type. This
2680 -- is likely to be a common error, and thus deserves a warning.
2682 elsif Present (S) and then S = Predicate_Function (Typ) then
2683 Error_Msg_NE
2684 ("predicate check includes a call to& that requires a "
2685 & "predicate check??", Parent (N), Fun);
2686 Error_Msg_N
2687 ("\this will result in infinite recursion??", Parent (N));
2689 if Is_First_Subtype (Typ) then
2690 Error_Msg_NE
2691 ("\use an explicit subtype of& to carry the predicate",
2692 Parent (N), Typ);
2693 end if;
2695 Insert_Action (N,
2696 Make_Raise_Storage_Error (Sloc (N),
2697 Reason => SE_Infinite_Recursion));
2699 -- Here for normal case of predicate active
2701 else
2702 -- If the type has a static predicate and the expression is known
2703 -- at compile time, see if the expression satisfies the predicate.
2705 Check_Expression_Against_Static_Predicate (N, Typ);
2707 if not Expander_Active then
2708 return;
2709 end if;
2711 -- For an entity of the type, generate a call to the predicate
2712 -- function, unless its type is an actual subtype, which is not
2713 -- visible outside of the enclosing subprogram.
2715 if Is_Entity_Name (N)
2716 and then not Is_Actual_Subtype (Typ)
2717 then
2718 Insert_Action (N,
2719 Make_Predicate_Check
2720 (Typ, New_Occurrence_Of (Entity (N), Sloc (N))));
2722 -- If the expression is not an entity it may have side effects,
2723 -- and the following call will create an object declaration for
2724 -- it. We disable checks during its analysis, to prevent an
2725 -- infinite recursion.
2727 -- If the prefix is an aggregate in an assignment, apply the
2728 -- check to the LHS after assignment, rather than create a
2729 -- redundant temporary. This is only necessary in rare cases
2730 -- of array types (including strings) initialized with an
2731 -- aggregate with an "others" clause, either coming from source
2732 -- or generated by an Initialize_Scalars pragma.
2734 elsif Nkind (N) = N_Aggregate
2735 and then Nkind (Parent (N)) = N_Assignment_Statement
2736 then
2737 Insert_Action_After (Parent (N),
2738 Make_Predicate_Check
2739 (Typ, Duplicate_Subexpr (Name (Parent (N)))));
2741 else
2742 Insert_Action (N,
2743 Make_Predicate_Check
2744 (Typ, Duplicate_Subexpr (N)), Suppress => All_Checks);
2745 end if;
2746 end if;
2747 end if;
2748 end Apply_Predicate_Check;
2750 -----------------------
2751 -- Apply_Range_Check --
2752 -----------------------
2754 procedure Apply_Range_Check
2755 (Ck_Node : Node_Id;
2756 Target_Typ : Entity_Id;
2757 Source_Typ : Entity_Id := Empty)
2759 begin
2760 Apply_Selected_Range_Checks
2761 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2762 end Apply_Range_Check;
2764 ------------------------------
2765 -- Apply_Scalar_Range_Check --
2766 ------------------------------
2768 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2769 -- off if it is already set on.
2771 procedure Apply_Scalar_Range_Check
2772 (Expr : Node_Id;
2773 Target_Typ : Entity_Id;
2774 Source_Typ : Entity_Id := Empty;
2775 Fixed_Int : Boolean := False)
2777 Parnt : constant Node_Id := Parent (Expr);
2778 S_Typ : Entity_Id;
2779 Arr : Node_Id := Empty; -- initialize to prevent warning
2780 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
2782 Is_Subscr_Ref : Boolean;
2783 -- Set true if Expr is a subscript
2785 Is_Unconstrained_Subscr_Ref : Boolean;
2786 -- Set true if Expr is a subscript of an unconstrained array. In this
2787 -- case we do not attempt to do an analysis of the value against the
2788 -- range of the subscript, since we don't know the actual subtype.
2790 Int_Real : Boolean;
2791 -- Set to True if Expr should be regarded as a real value even though
2792 -- the type of Expr might be discrete.
2794 procedure Bad_Value (Warn : Boolean := False);
2795 -- Procedure called if value is determined to be out of range. Warn is
2796 -- True to force a warning instead of an error, even when SPARK_Mode is
2797 -- On.
2799 ---------------
2800 -- Bad_Value --
2801 ---------------
2803 procedure Bad_Value (Warn : Boolean := False) is
2804 begin
2805 Apply_Compile_Time_Constraint_Error
2806 (Expr, "value not in range of}??", CE_Range_Check_Failed,
2807 Ent => Target_Typ,
2808 Typ => Target_Typ,
2809 Warn => Warn);
2810 end Bad_Value;
2812 -- Start of processing for Apply_Scalar_Range_Check
2814 begin
2815 -- Return if check obviously not needed
2818 -- Not needed inside generic
2820 Inside_A_Generic
2822 -- Not needed if previous error
2824 or else Target_Typ = Any_Type
2825 or else Nkind (Expr) = N_Error
2827 -- Not needed for non-scalar type
2829 or else not Is_Scalar_Type (Target_Typ)
2831 -- Not needed if we know node raises CE already
2833 or else Raises_Constraint_Error (Expr)
2834 then
2835 return;
2836 end if;
2838 -- Now, see if checks are suppressed
2840 Is_Subscr_Ref :=
2841 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
2843 if Is_Subscr_Ref then
2844 Arr := Prefix (Parnt);
2845 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
2847 if Is_Access_Type (Arr_Typ) then
2848 Arr_Typ := Designated_Type (Arr_Typ);
2849 end if;
2850 end if;
2852 if not Do_Range_Check (Expr) then
2854 -- Subscript reference. Check for Index_Checks suppressed
2856 if Is_Subscr_Ref then
2858 -- Check array type and its base type
2860 if Index_Checks_Suppressed (Arr_Typ)
2861 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
2862 then
2863 return;
2865 -- Check array itself if it is an entity name
2867 elsif Is_Entity_Name (Arr)
2868 and then Index_Checks_Suppressed (Entity (Arr))
2869 then
2870 return;
2872 -- Check expression itself if it is an entity name
2874 elsif Is_Entity_Name (Expr)
2875 and then Index_Checks_Suppressed (Entity (Expr))
2876 then
2877 return;
2878 end if;
2880 -- All other cases, check for Range_Checks suppressed
2882 else
2883 -- Check target type and its base type
2885 if Range_Checks_Suppressed (Target_Typ)
2886 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
2887 then
2888 return;
2890 -- Check expression itself if it is an entity name
2892 elsif Is_Entity_Name (Expr)
2893 and then Range_Checks_Suppressed (Entity (Expr))
2894 then
2895 return;
2897 -- If Expr is part of an assignment statement, then check left
2898 -- side of assignment if it is an entity name.
2900 elsif Nkind (Parnt) = N_Assignment_Statement
2901 and then Is_Entity_Name (Name (Parnt))
2902 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
2903 then
2904 return;
2905 end if;
2906 end if;
2907 end if;
2909 -- Do not set range checks if they are killed
2911 if Nkind (Expr) = N_Unchecked_Type_Conversion
2912 and then Kill_Range_Check (Expr)
2913 then
2914 return;
2915 end if;
2917 -- Do not set range checks for any values from System.Scalar_Values
2918 -- since the whole idea of such values is to avoid checking them.
2920 if Is_Entity_Name (Expr)
2921 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
2922 then
2923 return;
2924 end if;
2926 -- Now see if we need a check
2928 if No (Source_Typ) then
2929 S_Typ := Etype (Expr);
2930 else
2931 S_Typ := Source_Typ;
2932 end if;
2934 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
2935 return;
2936 end if;
2938 Is_Unconstrained_Subscr_Ref :=
2939 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
2941 -- Special checks for floating-point type
2943 if Is_Floating_Point_Type (S_Typ) then
2945 -- Always do a range check if the source type includes infinities and
2946 -- the target type does not include infinities. We do not do this if
2947 -- range checks are killed.
2948 -- If the expression is a literal and the bounds of the type are
2949 -- static constants it may be possible to optimize the check.
2951 if Has_Infinities (S_Typ)
2952 and then not Has_Infinities (Target_Typ)
2953 then
2954 -- If the expression is a literal and the bounds of the type are
2955 -- static constants it may be possible to optimize the check.
2957 if Nkind (Expr) = N_Real_Literal then
2958 declare
2959 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
2960 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
2962 begin
2963 if Compile_Time_Known_Value (Tlo)
2964 and then Compile_Time_Known_Value (Thi)
2965 and then Expr_Value_R (Expr) >= Expr_Value_R (Tlo)
2966 and then Expr_Value_R (Expr) <= Expr_Value_R (Thi)
2967 then
2968 return;
2969 else
2970 Enable_Range_Check (Expr);
2971 end if;
2972 end;
2974 else
2975 Enable_Range_Check (Expr);
2976 end if;
2977 end if;
2978 end if;
2980 -- Return if we know expression is definitely in the range of the target
2981 -- type as determined by Determine_Range. Right now we only do this for
2982 -- discrete types, and not fixed-point or floating-point types.
2984 -- The additional less-precise tests below catch these cases
2986 -- In GNATprove_Mode, also deal with the case of a conversion from
2987 -- floating-point to integer. It is only possible because analysis
2988 -- in GNATprove rules out the possibility of a NaN or infinite value.
2990 -- Note: skip this if we are given a source_typ, since the point of
2991 -- supplying a Source_Typ is to stop us looking at the expression.
2992 -- We could sharpen this test to be out parameters only ???
2994 if Is_Discrete_Type (Target_Typ)
2995 and then (Is_Discrete_Type (Etype (Expr))
2996 or else (GNATprove_Mode
2997 and then Is_Floating_Point_Type (Etype (Expr))))
2998 and then not Is_Unconstrained_Subscr_Ref
2999 and then No (Source_Typ)
3000 then
3001 declare
3002 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3003 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3005 begin
3006 if Compile_Time_Known_Value (Tlo)
3007 and then Compile_Time_Known_Value (Thi)
3008 then
3009 declare
3010 OK : Boolean := False; -- initialize to prevent warning
3011 Hiv : constant Uint := Expr_Value (Thi);
3012 Lov : constant Uint := Expr_Value (Tlo);
3013 Hi : Uint := No_Uint;
3014 Lo : Uint := No_Uint;
3016 begin
3017 -- If range is null, we for sure have a constraint error (we
3018 -- don't even need to look at the value involved, since all
3019 -- possible values will raise CE).
3021 if Lov > Hiv then
3023 -- When SPARK_Mode is On, force a warning instead of
3024 -- an error in that case, as this likely corresponds
3025 -- to deactivated code.
3027 Bad_Value (Warn => SPARK_Mode = On);
3029 -- In GNATprove mode, we enable the range check so that
3030 -- GNATprove will issue a message if it cannot be proved.
3032 if GNATprove_Mode then
3033 Enable_Range_Check (Expr);
3034 end if;
3036 return;
3037 end if;
3039 -- Otherwise determine range of value
3041 if Is_Discrete_Type (Etype (Expr)) then
3042 Determine_Range
3043 (Expr, OK, Lo, Hi, Assume_Valid => True);
3045 -- When converting a float to an integer type, determine the
3046 -- range in real first, and then convert the bounds using
3047 -- UR_To_Uint which correctly rounds away from zero when
3048 -- half way between two integers, as required by normal
3049 -- Ada 95 rounding semantics. It is only possible because
3050 -- analysis in GNATprove rules out the possibility of a NaN
3051 -- or infinite value.
3053 elsif GNATprove_Mode
3054 and then Is_Floating_Point_Type (Etype (Expr))
3055 then
3056 declare
3057 Hir : Ureal;
3058 Lor : Ureal;
3060 begin
3061 Determine_Range_R
3062 (Expr, OK, Lor, Hir, Assume_Valid => True);
3064 if OK then
3065 Lo := UR_To_Uint (Lor);
3066 Hi := UR_To_Uint (Hir);
3067 end if;
3068 end;
3069 end if;
3071 if OK then
3073 -- If definitely in range, all OK
3075 if Lo >= Lov and then Hi <= Hiv then
3076 return;
3078 -- If definitely not in range, warn
3080 elsif Lov > Hi or else Hiv < Lo then
3082 -- Ignore out of range values for System.Priority in
3083 -- CodePeer mode since the actual target compiler may
3084 -- provide a wider range.
3086 if not CodePeer_Mode
3087 or else Target_Typ /= RTE (RE_Priority)
3088 then
3089 Bad_Value;
3090 end if;
3092 return;
3094 -- Otherwise we don't know
3096 else
3097 null;
3098 end if;
3099 end if;
3100 end;
3101 end if;
3102 end;
3103 end if;
3105 Int_Real :=
3106 Is_Floating_Point_Type (S_Typ)
3107 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
3109 -- Check if we can determine at compile time whether Expr is in the
3110 -- range of the target type. Note that if S_Typ is within the bounds
3111 -- of Target_Typ then this must be the case. This check is meaningful
3112 -- only if this is not a conversion between integer and real types.
3114 if not Is_Unconstrained_Subscr_Ref
3115 and then Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
3116 and then
3117 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
3119 -- Also check if the expression itself is in the range of the
3120 -- target type if it is a known at compile time value. We skip
3121 -- this test if S_Typ is set since for OUT and IN OUT parameters
3122 -- the Expr itself is not relevant to the checking.
3124 or else
3125 (No (Source_Typ)
3126 and then Is_In_Range (Expr, Target_Typ,
3127 Assume_Valid => True,
3128 Fixed_Int => Fixed_Int,
3129 Int_Real => Int_Real)))
3130 then
3131 return;
3133 elsif Is_Out_Of_Range (Expr, Target_Typ,
3134 Assume_Valid => True,
3135 Fixed_Int => Fixed_Int,
3136 Int_Real => Int_Real)
3137 then
3138 Bad_Value;
3139 return;
3141 -- Floating-point case
3142 -- In the floating-point case, we only do range checks if the type is
3143 -- constrained. We definitely do NOT want range checks for unconstrained
3144 -- types, since we want to have infinities, except when
3145 -- Check_Float_Overflow is set.
3147 elsif Is_Floating_Point_Type (S_Typ) then
3148 if Is_Constrained (S_Typ) or else Check_Float_Overflow then
3149 Enable_Range_Check (Expr);
3150 end if;
3152 -- For all other cases we enable a range check unconditionally
3154 else
3155 Enable_Range_Check (Expr);
3156 return;
3157 end if;
3158 end Apply_Scalar_Range_Check;
3160 ----------------------------------
3161 -- Apply_Selected_Length_Checks --
3162 ----------------------------------
3164 procedure Apply_Selected_Length_Checks
3165 (Ck_Node : Node_Id;
3166 Target_Typ : Entity_Id;
3167 Source_Typ : Entity_Id;
3168 Do_Static : Boolean)
3170 Checks_On : constant Boolean :=
3171 not Index_Checks_Suppressed (Target_Typ)
3172 or else
3173 not Length_Checks_Suppressed (Target_Typ);
3175 Loc : constant Source_Ptr := Sloc (Ck_Node);
3177 Cond : Node_Id;
3178 R_Cno : Node_Id;
3179 R_Result : Check_Result;
3181 begin
3182 -- Only apply checks when generating code
3184 -- Note: this means that we lose some useful warnings if the expander
3185 -- is not active.
3187 if not Expander_Active then
3188 return;
3189 end if;
3191 R_Result :=
3192 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3194 for J in 1 .. 2 loop
3195 R_Cno := R_Result (J);
3196 exit when No (R_Cno);
3198 -- A length check may mention an Itype which is attached to a
3199 -- subsequent node. At the top level in a package this can cause
3200 -- an order-of-elaboration problem, so we make sure that the itype
3201 -- is referenced now.
3203 if Ekind (Current_Scope) = E_Package
3204 and then Is_Compilation_Unit (Current_Scope)
3205 then
3206 Ensure_Defined (Target_Typ, Ck_Node);
3208 if Present (Source_Typ) then
3209 Ensure_Defined (Source_Typ, Ck_Node);
3211 elsif Is_Itype (Etype (Ck_Node)) then
3212 Ensure_Defined (Etype (Ck_Node), Ck_Node);
3213 end if;
3214 end if;
3216 -- If the item is a conditional raise of constraint error, then have
3217 -- a look at what check is being performed and ???
3219 if Nkind (R_Cno) = N_Raise_Constraint_Error
3220 and then Present (Condition (R_Cno))
3221 then
3222 Cond := Condition (R_Cno);
3224 -- Case where node does not now have a dynamic check
3226 if not Has_Dynamic_Length_Check (Ck_Node) then
3228 -- If checks are on, just insert the check
3230 if Checks_On then
3231 Insert_Action (Ck_Node, R_Cno);
3233 if not Do_Static then
3234 Set_Has_Dynamic_Length_Check (Ck_Node);
3235 end if;
3237 -- If checks are off, then analyze the length check after
3238 -- temporarily attaching it to the tree in case the relevant
3239 -- condition can be evaluated at compile time. We still want a
3240 -- compile time warning in this case.
3242 else
3243 Set_Parent (R_Cno, Ck_Node);
3244 Analyze (R_Cno);
3245 end if;
3246 end if;
3248 -- Output a warning if the condition is known to be True
3250 if Is_Entity_Name (Cond)
3251 and then Entity (Cond) = Standard_True
3252 then
3253 Apply_Compile_Time_Constraint_Error
3254 (Ck_Node, "wrong length for array of}??",
3255 CE_Length_Check_Failed,
3256 Ent => Target_Typ,
3257 Typ => Target_Typ);
3259 -- If we were only doing a static check, or if checks are not
3260 -- on, then we want to delete the check, since it is not needed.
3261 -- We do this by replacing the if statement by a null statement
3263 elsif Do_Static or else not Checks_On then
3264 Remove_Warning_Messages (R_Cno);
3265 Rewrite (R_Cno, Make_Null_Statement (Loc));
3266 end if;
3268 else
3269 Install_Static_Check (R_Cno, Loc);
3270 end if;
3271 end loop;
3272 end Apply_Selected_Length_Checks;
3274 ---------------------------------
3275 -- Apply_Selected_Range_Checks --
3276 ---------------------------------
3278 procedure Apply_Selected_Range_Checks
3279 (Ck_Node : Node_Id;
3280 Target_Typ : Entity_Id;
3281 Source_Typ : Entity_Id;
3282 Do_Static : Boolean)
3284 Checks_On : constant Boolean :=
3285 not Index_Checks_Suppressed (Target_Typ)
3286 or else
3287 not Range_Checks_Suppressed (Target_Typ);
3289 Loc : constant Source_Ptr := Sloc (Ck_Node);
3291 Cond : Node_Id;
3292 R_Cno : Node_Id;
3293 R_Result : Check_Result;
3295 begin
3296 -- Only apply checks when generating code. In GNATprove mode, we do not
3297 -- apply the checks, but we still call Selected_Range_Checks to possibly
3298 -- issue errors on SPARK code when a run-time error can be detected at
3299 -- compile time.
3301 if not GNATprove_Mode then
3302 if not Expander_Active or not Checks_On then
3303 return;
3304 end if;
3305 end if;
3307 R_Result :=
3308 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3310 if GNATprove_Mode then
3311 return;
3312 end if;
3314 for J in 1 .. 2 loop
3315 R_Cno := R_Result (J);
3316 exit when No (R_Cno);
3318 -- The range check requires runtime evaluation. Depending on what its
3319 -- triggering condition is, the check may be converted into a compile
3320 -- time constraint check.
3322 if Nkind (R_Cno) = N_Raise_Constraint_Error
3323 and then Present (Condition (R_Cno))
3324 then
3325 Cond := Condition (R_Cno);
3327 -- Insert the range check before the related context. Note that
3328 -- this action analyses the triggering condition.
3330 Insert_Action (Ck_Node, R_Cno);
3332 -- This old code doesn't make sense, why is the context flagged as
3333 -- requiring dynamic range checks now in the middle of generating
3334 -- them ???
3336 if not Do_Static then
3337 Set_Has_Dynamic_Range_Check (Ck_Node);
3338 end if;
3340 -- The triggering condition evaluates to True, the range check
3341 -- can be converted into a compile time constraint check.
3343 if Is_Entity_Name (Cond)
3344 and then Entity (Cond) = Standard_True
3345 then
3346 -- Since an N_Range is technically not an expression, we have
3347 -- to set one of the bounds to C_E and then just flag the
3348 -- N_Range. The warning message will point to the lower bound
3349 -- and complain about a range, which seems OK.
3351 if Nkind (Ck_Node) = N_Range then
3352 Apply_Compile_Time_Constraint_Error
3353 (Low_Bound (Ck_Node),
3354 "static range out of bounds of}??",
3355 CE_Range_Check_Failed,
3356 Ent => Target_Typ,
3357 Typ => Target_Typ);
3359 Set_Raises_Constraint_Error (Ck_Node);
3361 else
3362 Apply_Compile_Time_Constraint_Error
3363 (Ck_Node,
3364 "static value out of range of}??",
3365 CE_Range_Check_Failed,
3366 Ent => Target_Typ,
3367 Typ => Target_Typ);
3368 end if;
3370 -- If we were only doing a static check, or if checks are not
3371 -- on, then we want to delete the check, since it is not needed.
3372 -- We do this by replacing the if statement by a null statement
3374 elsif Do_Static then
3375 Remove_Warning_Messages (R_Cno);
3376 Rewrite (R_Cno, Make_Null_Statement (Loc));
3377 end if;
3379 -- The range check raises Constraint_Error explicitly
3381 else
3382 Install_Static_Check (R_Cno, Loc);
3383 end if;
3384 end loop;
3385 end Apply_Selected_Range_Checks;
3387 -------------------------------
3388 -- Apply_Static_Length_Check --
3389 -------------------------------
3391 procedure Apply_Static_Length_Check
3392 (Expr : Node_Id;
3393 Target_Typ : Entity_Id;
3394 Source_Typ : Entity_Id := Empty)
3396 begin
3397 Apply_Selected_Length_Checks
3398 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3399 end Apply_Static_Length_Check;
3401 -------------------------------------
3402 -- Apply_Subscript_Validity_Checks --
3403 -------------------------------------
3405 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3406 Sub : Node_Id;
3408 begin
3409 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3411 -- Loop through subscripts
3413 Sub := First (Expressions (Expr));
3414 while Present (Sub) loop
3416 -- Check one subscript. Note that we do not worry about enumeration
3417 -- type with holes, since we will convert the value to a Pos value
3418 -- for the subscript, and that convert will do the necessary validity
3419 -- check.
3421 Ensure_Valid (Sub, Holes_OK => True);
3423 -- Move to next subscript
3425 Sub := Next (Sub);
3426 end loop;
3427 end Apply_Subscript_Validity_Checks;
3429 ----------------------------------
3430 -- Apply_Type_Conversion_Checks --
3431 ----------------------------------
3433 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3434 Target_Type : constant Entity_Id := Etype (N);
3435 Target_Base : constant Entity_Id := Base_Type (Target_Type);
3436 Expr : constant Node_Id := Expression (N);
3438 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
3439 -- Note: if Etype (Expr) is a private type without discriminants, its
3440 -- full view might have discriminants with defaults, so we need the
3441 -- full view here to retrieve the constraints.
3443 begin
3444 if Inside_A_Generic then
3445 return;
3447 -- Skip these checks if serious errors detected, there are some nasty
3448 -- situations of incomplete trees that blow things up.
3450 elsif Serious_Errors_Detected > 0 then
3451 return;
3453 -- Never generate discriminant checks for Unchecked_Union types
3455 elsif Present (Expr_Type)
3456 and then Is_Unchecked_Union (Expr_Type)
3457 then
3458 return;
3460 -- Scalar type conversions of the form Target_Type (Expr) require a
3461 -- range check if we cannot be sure that Expr is in the base type of
3462 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3463 -- are not quite the same condition from an implementation point of
3464 -- view, but clearly the second includes the first.
3466 elsif Is_Scalar_Type (Target_Type) then
3467 declare
3468 Conv_OK : constant Boolean := Conversion_OK (N);
3469 -- If the Conversion_OK flag on the type conversion is set and no
3470 -- floating-point type is involved in the type conversion then
3471 -- fixed-point values must be read as integral values.
3473 Float_To_Int : constant Boolean :=
3474 Is_Floating_Point_Type (Expr_Type)
3475 and then Is_Integer_Type (Target_Type);
3477 begin
3478 if not Overflow_Checks_Suppressed (Target_Base)
3479 and then not Overflow_Checks_Suppressed (Target_Type)
3480 and then not
3481 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
3482 and then not Float_To_Int
3483 then
3484 -- A small optimization: the attribute 'Pos applied to an
3485 -- enumeration type has a known range, even though its type is
3486 -- Universal_Integer. So in numeric conversions it is usually
3487 -- within range of the target integer type. Use the static
3488 -- bounds of the base types to check. Disable this optimization
3489 -- in case of a generic formal discrete type, because we don't
3490 -- necessarily know the upper bound yet.
3492 if Nkind (Expr) = N_Attribute_Reference
3493 and then Attribute_Name (Expr) = Name_Pos
3494 and then Is_Enumeration_Type (Etype (Prefix (Expr)))
3495 and then not Is_Generic_Type (Etype (Prefix (Expr)))
3496 and then Is_Integer_Type (Target_Type)
3497 then
3498 declare
3499 Enum_T : constant Entity_Id :=
3500 Root_Type (Etype (Prefix (Expr)));
3501 Int_T : constant Entity_Id := Base_Type (Target_Type);
3502 Last_I : constant Uint :=
3503 Intval (High_Bound (Scalar_Range (Int_T)));
3504 Last_E : Uint;
3506 begin
3507 -- Character types have no explicit literals, so we use
3508 -- the known number of characters in the type.
3510 if Root_Type (Enum_T) = Standard_Character then
3511 Last_E := UI_From_Int (255);
3513 elsif Enum_T = Standard_Wide_Character
3514 or else Enum_T = Standard_Wide_Wide_Character
3515 then
3516 Last_E := UI_From_Int (65535);
3518 else
3519 Last_E :=
3520 Enumeration_Pos
3521 (Entity (High_Bound (Scalar_Range (Enum_T))));
3522 end if;
3524 if Last_E <= Last_I then
3525 null;
3527 else
3528 Activate_Overflow_Check (N);
3529 end if;
3530 end;
3532 else
3533 Activate_Overflow_Check (N);
3534 end if;
3535 end if;
3537 if not Range_Checks_Suppressed (Target_Type)
3538 and then not Range_Checks_Suppressed (Expr_Type)
3539 then
3540 if Float_To_Int
3541 and then not GNATprove_Mode
3542 then
3543 Apply_Float_Conversion_Check (Expr, Target_Type);
3544 else
3545 Apply_Scalar_Range_Check
3546 (Expr, Target_Type, Fixed_Int => Conv_OK);
3548 -- If the target type has predicates, we need to indicate
3549 -- the need for a check, even if Determine_Range finds that
3550 -- the value is within bounds. This may be the case e.g for
3551 -- a division with a constant denominator.
3553 if Has_Predicates (Target_Type) then
3554 Enable_Range_Check (Expr);
3555 end if;
3556 end if;
3557 end if;
3558 end;
3560 elsif Comes_From_Source (N)
3561 and then not Discriminant_Checks_Suppressed (Target_Type)
3562 and then Is_Record_Type (Target_Type)
3563 and then Is_Derived_Type (Target_Type)
3564 and then not Is_Tagged_Type (Target_Type)
3565 and then not Is_Constrained (Target_Type)
3566 and then Present (Stored_Constraint (Target_Type))
3567 then
3568 -- An unconstrained derived type may have inherited discriminant.
3569 -- Build an actual discriminant constraint list using the stored
3570 -- constraint, to verify that the expression of the parent type
3571 -- satisfies the constraints imposed by the (unconstrained) derived
3572 -- type. This applies to value conversions, not to view conversions
3573 -- of tagged types.
3575 declare
3576 Loc : constant Source_Ptr := Sloc (N);
3577 Cond : Node_Id;
3578 Constraint : Elmt_Id;
3579 Discr_Value : Node_Id;
3580 Discr : Entity_Id;
3582 New_Constraints : constant Elist_Id := New_Elmt_List;
3583 Old_Constraints : constant Elist_Id :=
3584 Discriminant_Constraint (Expr_Type);
3586 begin
3587 Constraint := First_Elmt (Stored_Constraint (Target_Type));
3588 while Present (Constraint) loop
3589 Discr_Value := Node (Constraint);
3591 if Is_Entity_Name (Discr_Value)
3592 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3593 then
3594 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3596 if Present (Discr)
3597 and then Scope (Discr) = Base_Type (Expr_Type)
3598 then
3599 -- Parent is constrained by new discriminant. Obtain
3600 -- Value of original discriminant in expression. If the
3601 -- new discriminant has been used to constrain more than
3602 -- one of the stored discriminants, this will provide the
3603 -- required consistency check.
3605 Append_Elmt
3606 (Make_Selected_Component (Loc,
3607 Prefix =>
3608 Duplicate_Subexpr_No_Checks
3609 (Expr, Name_Req => True),
3610 Selector_Name =>
3611 Make_Identifier (Loc, Chars (Discr))),
3612 New_Constraints);
3614 else
3615 -- Discriminant of more remote ancestor ???
3617 return;
3618 end if;
3620 -- Derived type definition has an explicit value for this
3621 -- stored discriminant.
3623 else
3624 Append_Elmt
3625 (Duplicate_Subexpr_No_Checks (Discr_Value),
3626 New_Constraints);
3627 end if;
3629 Next_Elmt (Constraint);
3630 end loop;
3632 -- Use the unconstrained expression type to retrieve the
3633 -- discriminants of the parent, and apply momentarily the
3634 -- discriminant constraint synthesized above.
3636 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3637 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3638 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3640 Insert_Action (N,
3641 Make_Raise_Constraint_Error (Loc,
3642 Condition => Cond,
3643 Reason => CE_Discriminant_Check_Failed));
3644 end;
3646 -- For arrays, checks are set now, but conversions are applied during
3647 -- expansion, to take into accounts changes of representation. The
3648 -- checks become range checks on the base type or length checks on the
3649 -- subtype, depending on whether the target type is unconstrained or
3650 -- constrained. Note that the range check is put on the expression of a
3651 -- type conversion, while the length check is put on the type conversion
3652 -- itself.
3654 elsif Is_Array_Type (Target_Type) then
3655 if Is_Constrained (Target_Type) then
3656 Set_Do_Length_Check (N);
3657 else
3658 Set_Do_Range_Check (Expr);
3659 end if;
3660 end if;
3661 end Apply_Type_Conversion_Checks;
3663 ----------------------------------------------
3664 -- Apply_Universal_Integer_Attribute_Checks --
3665 ----------------------------------------------
3667 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3668 Loc : constant Source_Ptr := Sloc (N);
3669 Typ : constant Entity_Id := Etype (N);
3671 begin
3672 if Inside_A_Generic then
3673 return;
3675 -- Nothing to do if checks are suppressed
3677 elsif Range_Checks_Suppressed (Typ)
3678 and then Overflow_Checks_Suppressed (Typ)
3679 then
3680 return;
3682 -- Nothing to do if the attribute does not come from source. The
3683 -- internal attributes we generate of this type do not need checks,
3684 -- and furthermore the attempt to check them causes some circular
3685 -- elaboration orders when dealing with packed types.
3687 elsif not Comes_From_Source (N) then
3688 return;
3690 -- If the prefix is a selected component that depends on a discriminant
3691 -- the check may improperly expose a discriminant instead of using
3692 -- the bounds of the object itself. Set the type of the attribute to
3693 -- the base type of the context, so that a check will be imposed when
3694 -- needed (e.g. if the node appears as an index).
3696 elsif Nkind (Prefix (N)) = N_Selected_Component
3697 and then Ekind (Typ) = E_Signed_Integer_Subtype
3698 and then Depends_On_Discriminant (Scalar_Range (Typ))
3699 then
3700 Set_Etype (N, Base_Type (Typ));
3702 -- Otherwise, replace the attribute node with a type conversion node
3703 -- whose expression is the attribute, retyped to universal integer, and
3704 -- whose subtype mark is the target type. The call to analyze this
3705 -- conversion will set range and overflow checks as required for proper
3706 -- detection of an out of range value.
3708 else
3709 Set_Etype (N, Universal_Integer);
3710 Set_Analyzed (N, True);
3712 Rewrite (N,
3713 Make_Type_Conversion (Loc,
3714 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3715 Expression => Relocate_Node (N)));
3717 Analyze_And_Resolve (N, Typ);
3718 return;
3719 end if;
3720 end Apply_Universal_Integer_Attribute_Checks;
3722 -------------------------------------
3723 -- Atomic_Synchronization_Disabled --
3724 -------------------------------------
3726 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3727 -- using a bogus check called Atomic_Synchronization. This is to make it
3728 -- more convenient to get exactly the same semantics as [Un]Suppress.
3730 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3731 begin
3732 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3733 -- looks enabled, since it is never disabled.
3735 if Debug_Flag_Dot_E then
3736 return False;
3738 -- If debug flag d.d is set then always return True, i.e. all atomic
3739 -- sync looks disabled, since it always tests True.
3741 elsif Debug_Flag_Dot_D then
3742 return True;
3744 -- If entity present, then check result for that entity
3746 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
3747 return Is_Check_Suppressed (E, Atomic_Synchronization);
3749 -- Otherwise result depends on current scope setting
3751 else
3752 return Scope_Suppress.Suppress (Atomic_Synchronization);
3753 end if;
3754 end Atomic_Synchronization_Disabled;
3756 -------------------------------
3757 -- Build_Discriminant_Checks --
3758 -------------------------------
3760 function Build_Discriminant_Checks
3761 (N : Node_Id;
3762 T_Typ : Entity_Id) return Node_Id
3764 Loc : constant Source_Ptr := Sloc (N);
3765 Cond : Node_Id;
3766 Disc : Elmt_Id;
3767 Disc_Ent : Entity_Id;
3768 Dref : Node_Id;
3769 Dval : Node_Id;
3771 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3773 --------------------------------
3774 -- Aggregate_Discriminant_Val --
3775 --------------------------------
3777 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3778 Assoc : Node_Id;
3780 begin
3781 -- The aggregate has been normalized with named associations. We use
3782 -- the Chars field to locate the discriminant to take into account
3783 -- discriminants in derived types, which carry the same name as those
3784 -- in the parent.
3786 Assoc := First (Component_Associations (N));
3787 while Present (Assoc) loop
3788 if Chars (First (Choices (Assoc))) = Chars (Disc) then
3789 return Expression (Assoc);
3790 else
3791 Next (Assoc);
3792 end if;
3793 end loop;
3795 -- Discriminant must have been found in the loop above
3797 raise Program_Error;
3798 end Aggregate_Discriminant_Val;
3800 -- Start of processing for Build_Discriminant_Checks
3802 begin
3803 -- Loop through discriminants evolving the condition
3805 Cond := Empty;
3806 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
3808 -- For a fully private type, use the discriminants of the parent type
3810 if Is_Private_Type (T_Typ)
3811 and then No (Full_View (T_Typ))
3812 then
3813 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
3814 else
3815 Disc_Ent := First_Discriminant (T_Typ);
3816 end if;
3818 while Present (Disc) loop
3819 Dval := Node (Disc);
3821 if Nkind (Dval) = N_Identifier
3822 and then Ekind (Entity (Dval)) = E_Discriminant
3823 then
3824 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
3825 else
3826 Dval := Duplicate_Subexpr_No_Checks (Dval);
3827 end if;
3829 -- If we have an Unchecked_Union node, we can infer the discriminants
3830 -- of the node.
3832 if Is_Unchecked_Union (Base_Type (T_Typ)) then
3833 Dref := New_Copy (
3834 Get_Discriminant_Value (
3835 First_Discriminant (T_Typ),
3836 T_Typ,
3837 Stored_Constraint (T_Typ)));
3839 elsif Nkind (N) = N_Aggregate then
3840 Dref :=
3841 Duplicate_Subexpr_No_Checks
3842 (Aggregate_Discriminant_Val (Disc_Ent));
3844 else
3845 Dref :=
3846 Make_Selected_Component (Loc,
3847 Prefix =>
3848 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
3849 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
3851 Set_Is_In_Discriminant_Check (Dref);
3852 end if;
3854 Evolve_Or_Else (Cond,
3855 Make_Op_Ne (Loc,
3856 Left_Opnd => Dref,
3857 Right_Opnd => Dval));
3859 Next_Elmt (Disc);
3860 Next_Discriminant (Disc_Ent);
3861 end loop;
3863 return Cond;
3864 end Build_Discriminant_Checks;
3866 ------------------
3867 -- Check_Needed --
3868 ------------------
3870 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
3871 N : Node_Id;
3872 P : Node_Id;
3873 K : Node_Kind;
3874 L : Node_Id;
3875 R : Node_Id;
3877 function Left_Expression (Op : Node_Id) return Node_Id;
3878 -- Return the relevant expression from the left operand of the given
3879 -- short circuit form: this is LO itself, except if LO is a qualified
3880 -- expression, a type conversion, or an expression with actions, in
3881 -- which case this is Left_Expression (Expression (LO)).
3883 ---------------------
3884 -- Left_Expression --
3885 ---------------------
3887 function Left_Expression (Op : Node_Id) return Node_Id is
3888 LE : Node_Id := Left_Opnd (Op);
3889 begin
3890 while Nkind_In (LE, N_Qualified_Expression,
3891 N_Type_Conversion,
3892 N_Expression_With_Actions)
3893 loop
3894 LE := Expression (LE);
3895 end loop;
3897 return LE;
3898 end Left_Expression;
3900 -- Start of processing for Check_Needed
3902 begin
3903 -- Always check if not simple entity
3905 if Nkind (Nod) not in N_Has_Entity
3906 or else not Comes_From_Source (Nod)
3907 then
3908 return True;
3909 end if;
3911 -- Look up tree for short circuit
3913 N := Nod;
3914 loop
3915 P := Parent (N);
3916 K := Nkind (P);
3918 -- Done if out of subexpression (note that we allow generated stuff
3919 -- such as itype declarations in this context, to keep the loop going
3920 -- since we may well have generated such stuff in complex situations.
3921 -- Also done if no parent (probably an error condition, but no point
3922 -- in behaving nasty if we find it).
3924 if No (P)
3925 or else (K not in N_Subexpr and then Comes_From_Source (P))
3926 then
3927 return True;
3929 -- Or/Or Else case, where test is part of the right operand, or is
3930 -- part of one of the actions associated with the right operand, and
3931 -- the left operand is an equality test.
3933 elsif K = N_Op_Or then
3934 exit when N = Right_Opnd (P)
3935 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3937 elsif K = N_Or_Else then
3938 exit when (N = Right_Opnd (P)
3939 or else
3940 (Is_List_Member (N)
3941 and then List_Containing (N) = Actions (P)))
3942 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3944 -- Similar test for the And/And then case, where the left operand
3945 -- is an inequality test.
3947 elsif K = N_Op_And then
3948 exit when N = Right_Opnd (P)
3949 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3951 elsif K = N_And_Then then
3952 exit when (N = Right_Opnd (P)
3953 or else
3954 (Is_List_Member (N)
3955 and then List_Containing (N) = Actions (P)))
3956 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3957 end if;
3959 N := P;
3960 end loop;
3962 -- If we fall through the loop, then we have a conditional with an
3963 -- appropriate test as its left operand, so look further.
3965 L := Left_Expression (P);
3967 -- L is an "=" or "/=" operator: extract its operands
3969 R := Right_Opnd (L);
3970 L := Left_Opnd (L);
3972 -- Left operand of test must match original variable
3974 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
3975 return True;
3976 end if;
3978 -- Right operand of test must be key value (zero or null)
3980 case Check is
3981 when Access_Check =>
3982 if not Known_Null (R) then
3983 return True;
3984 end if;
3986 when Division_Check =>
3987 if not Compile_Time_Known_Value (R)
3988 or else Expr_Value (R) /= Uint_0
3989 then
3990 return True;
3991 end if;
3993 when others =>
3994 raise Program_Error;
3995 end case;
3997 -- Here we have the optimizable case, warn if not short-circuited
3999 if K = N_Op_And or else K = N_Op_Or then
4000 Error_Msg_Warn := SPARK_Mode /= On;
4002 case Check is
4003 when Access_Check =>
4004 if GNATprove_Mode then
4005 Error_Msg_N
4006 ("Constraint_Error might have been raised (access check)",
4007 Parent (Nod));
4008 else
4009 Error_Msg_N
4010 ("Constraint_Error may be raised (access check)??",
4011 Parent (Nod));
4012 end if;
4014 when Division_Check =>
4015 if GNATprove_Mode then
4016 Error_Msg_N
4017 ("Constraint_Error might have been raised (zero divide)",
4018 Parent (Nod));
4019 else
4020 Error_Msg_N
4021 ("Constraint_Error may be raised (zero divide)??",
4022 Parent (Nod));
4023 end if;
4025 when others =>
4026 raise Program_Error;
4027 end case;
4029 if K = N_Op_And then
4030 Error_Msg_N -- CODEFIX
4031 ("use `AND THEN` instead of AND??", P);
4032 else
4033 Error_Msg_N -- CODEFIX
4034 ("use `OR ELSE` instead of OR??", P);
4035 end if;
4037 -- If not short-circuited, we need the check
4039 return True;
4041 -- If short-circuited, we can omit the check
4043 else
4044 return False;
4045 end if;
4046 end Check_Needed;
4048 -----------------------------------
4049 -- Check_Valid_Lvalue_Subscripts --
4050 -----------------------------------
4052 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
4053 begin
4054 -- Skip this if range checks are suppressed
4056 if Range_Checks_Suppressed (Etype (Expr)) then
4057 return;
4059 -- Only do this check for expressions that come from source. We assume
4060 -- that expander generated assignments explicitly include any necessary
4061 -- checks. Note that this is not just an optimization, it avoids
4062 -- infinite recursions.
4064 elsif not Comes_From_Source (Expr) then
4065 return;
4067 -- For a selected component, check the prefix
4069 elsif Nkind (Expr) = N_Selected_Component then
4070 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4071 return;
4073 -- Case of indexed component
4075 elsif Nkind (Expr) = N_Indexed_Component then
4076 Apply_Subscript_Validity_Checks (Expr);
4078 -- Prefix may itself be or contain an indexed component, and these
4079 -- subscripts need checking as well.
4081 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4082 end if;
4083 end Check_Valid_Lvalue_Subscripts;
4085 ----------------------------------
4086 -- Null_Exclusion_Static_Checks --
4087 ----------------------------------
4089 procedure Null_Exclusion_Static_Checks
4090 (N : Node_Id;
4091 Comp : Node_Id := Empty;
4092 Array_Comp : Boolean := False)
4094 Has_Null : constant Boolean := Has_Null_Exclusion (N);
4095 Kind : constant Node_Kind := Nkind (N);
4096 Error_Nod : Node_Id;
4097 Expr : Node_Id;
4098 Typ : Entity_Id;
4100 begin
4101 pragma Assert
4102 (Nkind_In (Kind, N_Component_Declaration,
4103 N_Discriminant_Specification,
4104 N_Function_Specification,
4105 N_Object_Declaration,
4106 N_Parameter_Specification));
4108 if Kind = N_Function_Specification then
4109 Typ := Etype (Defining_Entity (N));
4110 else
4111 Typ := Etype (Defining_Identifier (N));
4112 end if;
4114 case Kind is
4115 when N_Component_Declaration =>
4116 if Present (Access_Definition (Component_Definition (N))) then
4117 Error_Nod := Component_Definition (N);
4118 else
4119 Error_Nod := Subtype_Indication (Component_Definition (N));
4120 end if;
4122 when N_Discriminant_Specification =>
4123 Error_Nod := Discriminant_Type (N);
4125 when N_Function_Specification =>
4126 Error_Nod := Result_Definition (N);
4128 when N_Object_Declaration =>
4129 Error_Nod := Object_Definition (N);
4131 when N_Parameter_Specification =>
4132 Error_Nod := Parameter_Type (N);
4134 when others =>
4135 raise Program_Error;
4136 end case;
4138 if Has_Null then
4140 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4141 -- applied to an access [sub]type.
4143 if not Is_Access_Type (Typ) then
4144 Error_Msg_N
4145 ("`NOT NULL` allowed only for an access type", Error_Nod);
4147 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4148 -- be applied to a [sub]type that does not exclude null already.
4150 elsif Can_Never_Be_Null (Typ) and then Comes_From_Source (Typ) then
4151 Error_Msg_NE
4152 ("`NOT NULL` not allowed (& already excludes null)",
4153 Error_Nod, Typ);
4154 end if;
4155 end if;
4157 -- Check that null-excluding objects are always initialized, except for
4158 -- deferred constants, for which the expression will appear in the full
4159 -- declaration.
4161 if Kind = N_Object_Declaration
4162 and then No (Expression (N))
4163 and then not Constant_Present (N)
4164 and then not No_Initialization (N)
4165 then
4166 if Present (Comp) then
4168 -- Specialize the warning message to indicate that we are dealing
4169 -- with an uninitialized composite object that has a defaulted
4170 -- null-excluding component.
4172 Error_Msg_Name_1 := Chars (Defining_Identifier (Comp));
4173 Error_Msg_Name_2 := Chars (Defining_Identifier (N));
4175 Discard_Node
4176 (Compile_Time_Constraint_Error
4177 (N => N,
4178 Msg =>
4179 "(Ada 2005) null-excluding component % of object % must "
4180 & "be initialized??",
4181 Ent => Defining_Identifier (Comp)));
4183 -- This is a case of an array with null-excluding components, so
4184 -- indicate that in the warning.
4186 elsif Array_Comp then
4187 Discard_Node
4188 (Compile_Time_Constraint_Error
4189 (N => N,
4190 Msg =>
4191 "(Ada 2005) null-excluding array components must "
4192 & "be initialized??",
4193 Ent => Defining_Identifier (N)));
4195 -- Normal case of object of a null-excluding access type
4197 else
4198 -- Add an expression that assigns null. This node is needed by
4199 -- Apply_Compile_Time_Constraint_Error, which will replace this
4200 -- with a Constraint_Error node.
4202 Set_Expression (N, Make_Null (Sloc (N)));
4203 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
4205 Apply_Compile_Time_Constraint_Error
4206 (N => Expression (N),
4207 Msg =>
4208 "(Ada 2005) null-excluding objects must be initialized??",
4209 Reason => CE_Null_Not_Allowed);
4210 end if;
4211 end if;
4213 -- Check that a null-excluding component, formal or object is not being
4214 -- assigned a null value. Otherwise generate a warning message and
4215 -- replace Expression (N) by an N_Constraint_Error node.
4217 if Kind /= N_Function_Specification then
4218 Expr := Expression (N);
4220 if Present (Expr) and then Known_Null (Expr) then
4221 case Kind is
4222 when N_Component_Declaration
4223 | N_Discriminant_Specification
4225 Apply_Compile_Time_Constraint_Error
4226 (N => Expr,
4227 Msg =>
4228 "(Ada 2005) null not allowed in null-excluding "
4229 & "components??",
4230 Reason => CE_Null_Not_Allowed);
4232 when N_Object_Declaration =>
4233 Apply_Compile_Time_Constraint_Error
4234 (N => Expr,
4235 Msg =>
4236 "(Ada 2005) null not allowed in null-excluding "
4237 & "objects??",
4238 Reason => CE_Null_Not_Allowed);
4240 when N_Parameter_Specification =>
4241 Apply_Compile_Time_Constraint_Error
4242 (N => Expr,
4243 Msg =>
4244 "(Ada 2005) null not allowed in null-excluding "
4245 & "formals??",
4246 Reason => CE_Null_Not_Allowed);
4248 when others =>
4249 null;
4250 end case;
4251 end if;
4252 end if;
4253 end Null_Exclusion_Static_Checks;
4255 ----------------------------------
4256 -- Conditional_Statements_Begin --
4257 ----------------------------------
4259 procedure Conditional_Statements_Begin is
4260 begin
4261 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4263 -- If stack overflows, kill all checks, that way we know to simply reset
4264 -- the number of saved checks to zero on return. This should never occur
4265 -- in practice.
4267 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4268 Kill_All_Checks;
4270 -- In the normal case, we just make a new stack entry saving the current
4271 -- number of saved checks for a later restore.
4273 else
4274 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4276 if Debug_Flag_CC then
4277 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4278 Num_Saved_Checks);
4279 end if;
4280 end if;
4281 end Conditional_Statements_Begin;
4283 --------------------------------
4284 -- Conditional_Statements_End --
4285 --------------------------------
4287 procedure Conditional_Statements_End is
4288 begin
4289 pragma Assert (Saved_Checks_TOS > 0);
4291 -- If the saved checks stack overflowed, then we killed all checks, so
4292 -- setting the number of saved checks back to zero is correct. This
4293 -- should never occur in practice.
4295 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4296 Num_Saved_Checks := 0;
4298 -- In the normal case, restore the number of saved checks from the top
4299 -- stack entry.
4301 else
4302 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
4304 if Debug_Flag_CC then
4305 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4306 Num_Saved_Checks);
4307 end if;
4308 end if;
4310 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4311 end Conditional_Statements_End;
4313 -------------------------
4314 -- Convert_From_Bignum --
4315 -------------------------
4317 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4318 Loc : constant Source_Ptr := Sloc (N);
4320 begin
4321 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4323 -- Construct call From Bignum
4325 return
4326 Make_Function_Call (Loc,
4327 Name =>
4328 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4329 Parameter_Associations => New_List (Relocate_Node (N)));
4330 end Convert_From_Bignum;
4332 -----------------------
4333 -- Convert_To_Bignum --
4334 -----------------------
4336 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4337 Loc : constant Source_Ptr := Sloc (N);
4339 begin
4340 -- Nothing to do if Bignum already except call Relocate_Node
4342 if Is_RTE (Etype (N), RE_Bignum) then
4343 return Relocate_Node (N);
4345 -- Otherwise construct call to To_Bignum, converting the operand to the
4346 -- required Long_Long_Integer form.
4348 else
4349 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4350 return
4351 Make_Function_Call (Loc,
4352 Name =>
4353 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4354 Parameter_Associations => New_List (
4355 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4356 end if;
4357 end Convert_To_Bignum;
4359 ---------------------
4360 -- Determine_Range --
4361 ---------------------
4363 Cache_Size : constant := 2 ** 10;
4364 type Cache_Index is range 0 .. Cache_Size - 1;
4365 -- Determine size of below cache (power of 2 is more efficient)
4367 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4368 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4369 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4370 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4371 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4372 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
4373 -- The above arrays are used to implement a small direct cache for
4374 -- Determine_Range and Determine_Range_R calls. Because of the way these
4375 -- subprograms recursively traces subexpressions, and because overflow
4376 -- checking calls the routine on the way up the tree, a quadratic behavior
4377 -- can otherwise be encountered in large expressions. The cache entry for
4378 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4379 -- by checking the actual node value stored there. The Range_Cache_V array
4380 -- records the setting of Assume_Valid for the cache entry.
4382 procedure Determine_Range
4383 (N : Node_Id;
4384 OK : out Boolean;
4385 Lo : out Uint;
4386 Hi : out Uint;
4387 Assume_Valid : Boolean := False)
4389 Typ : Entity_Id := Etype (N);
4390 -- Type to use, may get reset to base type for possibly invalid entity
4392 Lo_Left : Uint;
4393 Hi_Left : Uint;
4394 -- Lo and Hi bounds of left operand
4396 Lo_Right : Uint := No_Uint;
4397 Hi_Right : Uint := No_Uint;
4398 -- Lo and Hi bounds of right (or only) operand
4400 Bound : Node_Id;
4401 -- Temp variable used to hold a bound node
4403 Hbound : Uint;
4404 -- High bound of base type of expression
4406 Lor : Uint;
4407 Hir : Uint;
4408 -- Refined values for low and high bounds, after tightening
4410 OK1 : Boolean;
4411 -- Used in lower level calls to indicate if call succeeded
4413 Cindex : Cache_Index;
4414 -- Used to search cache
4416 Btyp : Entity_Id;
4417 -- Base type
4419 function OK_Operands return Boolean;
4420 -- Used for binary operators. Determines the ranges of the left and
4421 -- right operands, and if they are both OK, returns True, and puts
4422 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4424 -----------------
4425 -- OK_Operands --
4426 -----------------
4428 function OK_Operands return Boolean is
4429 begin
4430 Determine_Range
4431 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4433 if not OK1 then
4434 return False;
4435 end if;
4437 Determine_Range
4438 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4439 return OK1;
4440 end OK_Operands;
4442 -- Start of processing for Determine_Range
4444 begin
4445 -- Prevent junk warnings by initializing range variables
4447 Lo := No_Uint;
4448 Hi := No_Uint;
4449 Lor := No_Uint;
4450 Hir := No_Uint;
4452 -- For temporary constants internally generated to remove side effects
4453 -- we must use the corresponding expression to determine the range of
4454 -- the expression. But note that the expander can also generate
4455 -- constants in other cases, including deferred constants.
4457 if Is_Entity_Name (N)
4458 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4459 and then Ekind (Entity (N)) = E_Constant
4460 and then Is_Internal_Name (Chars (Entity (N)))
4461 then
4462 if Present (Expression (Parent (Entity (N)))) then
4463 Determine_Range
4464 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
4466 elsif Present (Full_View (Entity (N))) then
4467 Determine_Range
4468 (Expression (Parent (Full_View (Entity (N)))),
4469 OK, Lo, Hi, Assume_Valid);
4471 else
4472 OK := False;
4473 end if;
4474 return;
4475 end if;
4477 -- If type is not defined, we can't determine its range
4479 if No (Typ)
4481 -- We don't deal with anything except discrete types
4483 or else not Is_Discrete_Type (Typ)
4485 -- Ignore type for which an error has been posted, since range in
4486 -- this case may well be a bogosity deriving from the error. Also
4487 -- ignore if error posted on the reference node.
4489 or else Error_Posted (N) or else Error_Posted (Typ)
4490 then
4491 OK := False;
4492 return;
4493 end if;
4495 -- For all other cases, we can determine the range
4497 OK := True;
4499 -- If value is compile time known, then the possible range is the one
4500 -- value that we know this expression definitely has.
4502 if Compile_Time_Known_Value (N) then
4503 Lo := Expr_Value (N);
4504 Hi := Lo;
4505 return;
4506 end if;
4508 -- Return if already in the cache
4510 Cindex := Cache_Index (N mod Cache_Size);
4512 if Determine_Range_Cache_N (Cindex) = N
4513 and then
4514 Determine_Range_Cache_V (Cindex) = Assume_Valid
4515 then
4516 Lo := Determine_Range_Cache_Lo (Cindex);
4517 Hi := Determine_Range_Cache_Hi (Cindex);
4518 return;
4519 end if;
4521 -- Otherwise, start by finding the bounds of the type of the expression,
4522 -- the value cannot be outside this range (if it is, then we have an
4523 -- overflow situation, which is a separate check, we are talking here
4524 -- only about the expression value).
4526 -- First a check, never try to find the bounds of a generic type, since
4527 -- these bounds are always junk values, and it is only valid to look at
4528 -- the bounds in an instance.
4530 if Is_Generic_Type (Typ) then
4531 OK := False;
4532 return;
4533 end if;
4535 -- First step, change to use base type unless we know the value is valid
4537 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4538 or else Assume_No_Invalid_Values
4539 or else Assume_Valid
4540 then
4541 null;
4542 else
4543 Typ := Underlying_Type (Base_Type (Typ));
4544 end if;
4546 -- Retrieve the base type. Handle the case where the base type is a
4547 -- private enumeration type.
4549 Btyp := Base_Type (Typ);
4551 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4552 Btyp := Full_View (Btyp);
4553 end if;
4555 -- We use the actual bound unless it is dynamic, in which case use the
4556 -- corresponding base type bound if possible. If we can't get a bound
4557 -- then we figure we can't determine the range (a peculiar case, that
4558 -- perhaps cannot happen, but there is no point in bombing in this
4559 -- optimization circuit.
4561 -- First the low bound
4563 Bound := Type_Low_Bound (Typ);
4565 if Compile_Time_Known_Value (Bound) then
4566 Lo := Expr_Value (Bound);
4568 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4569 Lo := Expr_Value (Type_Low_Bound (Btyp));
4571 else
4572 OK := False;
4573 return;
4574 end if;
4576 -- Now the high bound
4578 Bound := Type_High_Bound (Typ);
4580 -- We need the high bound of the base type later on, and this should
4581 -- always be compile time known. Again, it is not clear that this
4582 -- can ever be false, but no point in bombing.
4584 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4585 Hbound := Expr_Value (Type_High_Bound (Btyp));
4586 Hi := Hbound;
4588 else
4589 OK := False;
4590 return;
4591 end if;
4593 -- If we have a static subtype, then that may have a tighter bound so
4594 -- use the upper bound of the subtype instead in this case.
4596 if Compile_Time_Known_Value (Bound) then
4597 Hi := Expr_Value (Bound);
4598 end if;
4600 -- We may be able to refine this value in certain situations. If any
4601 -- refinement is possible, then Lor and Hir are set to possibly tighter
4602 -- bounds, and OK1 is set to True.
4604 case Nkind (N) is
4606 -- For unary plus, result is limited by range of operand
4608 when N_Op_Plus =>
4609 Determine_Range
4610 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
4612 -- For unary minus, determine range of operand, and negate it
4614 when N_Op_Minus =>
4615 Determine_Range
4616 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4618 if OK1 then
4619 Lor := -Hi_Right;
4620 Hir := -Lo_Right;
4621 end if;
4623 -- For binary addition, get range of each operand and do the
4624 -- addition to get the result range.
4626 when N_Op_Add =>
4627 if OK_Operands then
4628 Lor := Lo_Left + Lo_Right;
4629 Hir := Hi_Left + Hi_Right;
4630 end if;
4632 -- Division is tricky. The only case we consider is where the right
4633 -- operand is a positive constant, and in this case we simply divide
4634 -- the bounds of the left operand
4636 when N_Op_Divide =>
4637 if OK_Operands then
4638 if Lo_Right = Hi_Right
4639 and then Lo_Right > 0
4640 then
4641 Lor := Lo_Left / Lo_Right;
4642 Hir := Hi_Left / Lo_Right;
4643 else
4644 OK1 := False;
4645 end if;
4646 end if;
4648 -- For binary subtraction, get range of each operand and do the worst
4649 -- case subtraction to get the result range.
4651 when N_Op_Subtract =>
4652 if OK_Operands then
4653 Lor := Lo_Left - Hi_Right;
4654 Hir := Hi_Left - Lo_Right;
4655 end if;
4657 -- For MOD, if right operand is a positive constant, then result must
4658 -- be in the allowable range of mod results.
4660 when N_Op_Mod =>
4661 if OK_Operands then
4662 if Lo_Right = Hi_Right
4663 and then Lo_Right /= 0
4664 then
4665 if Lo_Right > 0 then
4666 Lor := Uint_0;
4667 Hir := Lo_Right - 1;
4669 else -- Lo_Right < 0
4670 Lor := Lo_Right + 1;
4671 Hir := Uint_0;
4672 end if;
4674 else
4675 OK1 := False;
4676 end if;
4677 end if;
4679 -- For REM, if right operand is a positive constant, then result must
4680 -- be in the allowable range of mod results.
4682 when N_Op_Rem =>
4683 if OK_Operands then
4684 if Lo_Right = Hi_Right and then Lo_Right /= 0 then
4685 declare
4686 Dval : constant Uint := (abs Lo_Right) - 1;
4688 begin
4689 -- The sign of the result depends on the sign of the
4690 -- dividend (but not on the sign of the divisor, hence
4691 -- the abs operation above).
4693 if Lo_Left < 0 then
4694 Lor := -Dval;
4695 else
4696 Lor := Uint_0;
4697 end if;
4699 if Hi_Left < 0 then
4700 Hir := Uint_0;
4701 else
4702 Hir := Dval;
4703 end if;
4704 end;
4706 else
4707 OK1 := False;
4708 end if;
4709 end if;
4711 -- Attribute reference cases
4713 when N_Attribute_Reference =>
4714 case Attribute_Name (N) is
4716 -- For Pos/Val attributes, we can refine the range using the
4717 -- possible range of values of the attribute expression.
4719 when Name_Pos
4720 | Name_Val
4722 Determine_Range
4723 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
4725 -- For Length attribute, use the bounds of the corresponding
4726 -- index type to refine the range.
4728 when Name_Length =>
4729 declare
4730 Atyp : Entity_Id := Etype (Prefix (N));
4731 Inum : Nat;
4732 Indx : Node_Id;
4734 LL, LU : Uint;
4735 UL, UU : Uint;
4737 begin
4738 if Is_Access_Type (Atyp) then
4739 Atyp := Designated_Type (Atyp);
4740 end if;
4742 -- For string literal, we know exact value
4744 if Ekind (Atyp) = E_String_Literal_Subtype then
4745 OK := True;
4746 Lo := String_Literal_Length (Atyp);
4747 Hi := String_Literal_Length (Atyp);
4748 return;
4749 end if;
4751 -- Otherwise check for expression given
4753 if No (Expressions (N)) then
4754 Inum := 1;
4755 else
4756 Inum :=
4757 UI_To_Int (Expr_Value (First (Expressions (N))));
4758 end if;
4760 Indx := First_Index (Atyp);
4761 for J in 2 .. Inum loop
4762 Indx := Next_Index (Indx);
4763 end loop;
4765 -- If the index type is a formal type or derived from
4766 -- one, the bounds are not static.
4768 if Is_Generic_Type (Root_Type (Etype (Indx))) then
4769 OK := False;
4770 return;
4771 end if;
4773 Determine_Range
4774 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
4775 Assume_Valid);
4777 if OK1 then
4778 Determine_Range
4779 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
4780 Assume_Valid);
4782 if OK1 then
4784 -- The maximum value for Length is the biggest
4785 -- possible gap between the values of the bounds.
4786 -- But of course, this value cannot be negative.
4788 Hir := UI_Max (Uint_0, UU - LL + 1);
4790 -- For constrained arrays, the minimum value for
4791 -- Length is taken from the actual value of the
4792 -- bounds, since the index will be exactly of this
4793 -- subtype.
4795 if Is_Constrained (Atyp) then
4796 Lor := UI_Max (Uint_0, UL - LU + 1);
4798 -- For an unconstrained array, the minimum value
4799 -- for length is always zero.
4801 else
4802 Lor := Uint_0;
4803 end if;
4804 end if;
4805 end if;
4806 end;
4808 -- No special handling for other attributes
4809 -- Probably more opportunities exist here???
4811 when others =>
4812 OK1 := False;
4814 end case;
4816 when N_Type_Conversion =>
4818 -- For type conversion from one discrete type to another, we can
4819 -- refine the range using the converted value.
4821 if Is_Discrete_Type (Etype (Expression (N))) then
4822 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
4824 -- When converting a float to an integer type, determine the range
4825 -- in real first, and then convert the bounds using UR_To_Uint
4826 -- which correctly rounds away from zero when half way between two
4827 -- integers, as required by normal Ada 95 rounding semantics. It
4828 -- is only possible because analysis in GNATprove rules out the
4829 -- possibility of a NaN or infinite value.
4831 elsif GNATprove_Mode
4832 and then Is_Floating_Point_Type (Etype (Expression (N)))
4833 then
4834 declare
4835 Lor_Real, Hir_Real : Ureal;
4836 begin
4837 Determine_Range_R (Expression (N), OK1, Lor_Real, Hir_Real,
4838 Assume_Valid);
4840 if OK1 then
4841 Lor := UR_To_Uint (Lor_Real);
4842 Hir := UR_To_Uint (Hir_Real);
4843 end if;
4844 end;
4846 else
4847 OK1 := False;
4848 end if;
4850 -- Nothing special to do for all other expression kinds
4852 when others =>
4853 OK1 := False;
4854 Lor := No_Uint;
4855 Hir := No_Uint;
4856 end case;
4858 -- At this stage, if OK1 is true, then we know that the actual result of
4859 -- the computed expression is in the range Lor .. Hir. We can use this
4860 -- to restrict the possible range of results.
4862 if OK1 then
4864 -- If the refined value of the low bound is greater than the type
4865 -- low bound, then reset it to the more restrictive value. However,
4866 -- we do NOT do this for the case of a modular type where the
4867 -- possible upper bound on the value is above the base type high
4868 -- bound, because that means the result could wrap.
4870 if Lor > Lo
4871 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
4872 then
4873 Lo := Lor;
4874 end if;
4876 -- Similarly, if the refined value of the high bound is less than the
4877 -- value so far, then reset it to the more restrictive value. Again,
4878 -- we do not do this if the refined low bound is negative for a
4879 -- modular type, since this would wrap.
4881 if Hir < Hi
4882 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
4883 then
4884 Hi := Hir;
4885 end if;
4886 end if;
4888 -- Set cache entry for future call and we are all done
4890 Determine_Range_Cache_N (Cindex) := N;
4891 Determine_Range_Cache_V (Cindex) := Assume_Valid;
4892 Determine_Range_Cache_Lo (Cindex) := Lo;
4893 Determine_Range_Cache_Hi (Cindex) := Hi;
4894 return;
4896 -- If any exception occurs, it means that we have some bug in the compiler,
4897 -- possibly triggered by a previous error, or by some unforeseen peculiar
4898 -- occurrence. However, this is only an optimization attempt, so there is
4899 -- really no point in crashing the compiler. Instead we just decide, too
4900 -- bad, we can't figure out a range in this case after all.
4902 exception
4903 when others =>
4905 -- Debug flag K disables this behavior (useful for debugging)
4907 if Debug_Flag_K then
4908 raise;
4909 else
4910 OK := False;
4911 Lo := No_Uint;
4912 Hi := No_Uint;
4913 return;
4914 end if;
4915 end Determine_Range;
4917 -----------------------
4918 -- Determine_Range_R --
4919 -----------------------
4921 procedure Determine_Range_R
4922 (N : Node_Id;
4923 OK : out Boolean;
4924 Lo : out Ureal;
4925 Hi : out Ureal;
4926 Assume_Valid : Boolean := False)
4928 Typ : Entity_Id := Etype (N);
4929 -- Type to use, may get reset to base type for possibly invalid entity
4931 Lo_Left : Ureal;
4932 Hi_Left : Ureal;
4933 -- Lo and Hi bounds of left operand
4935 Lo_Right : Ureal := No_Ureal;
4936 Hi_Right : Ureal := No_Ureal;
4937 -- Lo and Hi bounds of right (or only) operand
4939 Bound : Node_Id;
4940 -- Temp variable used to hold a bound node
4942 Hbound : Ureal;
4943 -- High bound of base type of expression
4945 Lor : Ureal;
4946 Hir : Ureal;
4947 -- Refined values for low and high bounds, after tightening
4949 OK1 : Boolean;
4950 -- Used in lower level calls to indicate if call succeeded
4952 Cindex : Cache_Index;
4953 -- Used to search cache
4955 Btyp : Entity_Id;
4956 -- Base type
4958 function OK_Operands return Boolean;
4959 -- Used for binary operators. Determines the ranges of the left and
4960 -- right operands, and if they are both OK, returns True, and puts
4961 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4963 function Round_Machine (B : Ureal) return Ureal;
4964 -- B is a real bound. Round it using mode Round_Even.
4966 -----------------
4967 -- OK_Operands --
4968 -----------------
4970 function OK_Operands return Boolean is
4971 begin
4972 Determine_Range_R
4973 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4975 if not OK1 then
4976 return False;
4977 end if;
4979 Determine_Range_R
4980 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4981 return OK1;
4982 end OK_Operands;
4984 -------------------
4985 -- Round_Machine --
4986 -------------------
4988 function Round_Machine (B : Ureal) return Ureal is
4989 begin
4990 return Machine (Typ, B, Round_Even, N);
4991 end Round_Machine;
4993 -- Start of processing for Determine_Range_R
4995 begin
4996 -- Prevent junk warnings by initializing range variables
4998 Lo := No_Ureal;
4999 Hi := No_Ureal;
5000 Lor := No_Ureal;
5001 Hir := No_Ureal;
5003 -- For temporary constants internally generated to remove side effects
5004 -- we must use the corresponding expression to determine the range of
5005 -- the expression. But note that the expander can also generate
5006 -- constants in other cases, including deferred constants.
5008 if Is_Entity_Name (N)
5009 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5010 and then Ekind (Entity (N)) = E_Constant
5011 and then Is_Internal_Name (Chars (Entity (N)))
5012 then
5013 if Present (Expression (Parent (Entity (N)))) then
5014 Determine_Range_R
5015 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5017 elsif Present (Full_View (Entity (N))) then
5018 Determine_Range_R
5019 (Expression (Parent (Full_View (Entity (N)))),
5020 OK, Lo, Hi, Assume_Valid);
5022 else
5023 OK := False;
5024 end if;
5026 return;
5027 end if;
5029 -- If type is not defined, we can't determine its range
5031 if No (Typ)
5033 -- We don't deal with anything except IEEE floating-point types
5035 or else not Is_Floating_Point_Type (Typ)
5036 or else Float_Rep (Typ) /= IEEE_Binary
5038 -- Ignore type for which an error has been posted, since range in
5039 -- this case may well be a bogosity deriving from the error. Also
5040 -- ignore if error posted on the reference node.
5042 or else Error_Posted (N) or else Error_Posted (Typ)
5043 then
5044 OK := False;
5045 return;
5046 end if;
5048 -- For all other cases, we can determine the range
5050 OK := True;
5052 -- If value is compile time known, then the possible range is the one
5053 -- value that we know this expression definitely has.
5055 if Compile_Time_Known_Value (N) then
5056 Lo := Expr_Value_R (N);
5057 Hi := Lo;
5058 return;
5059 end if;
5061 -- Return if already in the cache
5063 Cindex := Cache_Index (N mod Cache_Size);
5065 if Determine_Range_Cache_N (Cindex) = N
5066 and then
5067 Determine_Range_Cache_V (Cindex) = Assume_Valid
5068 then
5069 Lo := Determine_Range_Cache_Lo_R (Cindex);
5070 Hi := Determine_Range_Cache_Hi_R (Cindex);
5071 return;
5072 end if;
5074 -- Otherwise, start by finding the bounds of the type of the expression,
5075 -- the value cannot be outside this range (if it is, then we have an
5076 -- overflow situation, which is a separate check, we are talking here
5077 -- only about the expression value).
5079 -- First a check, never try to find the bounds of a generic type, since
5080 -- these bounds are always junk values, and it is only valid to look at
5081 -- the bounds in an instance.
5083 if Is_Generic_Type (Typ) then
5084 OK := False;
5085 return;
5086 end if;
5088 -- First step, change to use base type unless we know the value is valid
5090 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5091 or else Assume_No_Invalid_Values
5092 or else Assume_Valid
5093 then
5094 null;
5095 else
5096 Typ := Underlying_Type (Base_Type (Typ));
5097 end if;
5099 -- Retrieve the base type. Handle the case where the base type is a
5100 -- private type.
5102 Btyp := Base_Type (Typ);
5104 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5105 Btyp := Full_View (Btyp);
5106 end if;
5108 -- We use the actual bound unless it is dynamic, in which case use the
5109 -- corresponding base type bound if possible. If we can't get a bound
5110 -- then we figure we can't determine the range (a peculiar case, that
5111 -- perhaps cannot happen, but there is no point in bombing in this
5112 -- optimization circuit).
5114 -- First the low bound
5116 Bound := Type_Low_Bound (Typ);
5118 if Compile_Time_Known_Value (Bound) then
5119 Lo := Expr_Value_R (Bound);
5121 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5122 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
5124 else
5125 OK := False;
5126 return;
5127 end if;
5129 -- Now the high bound
5131 Bound := Type_High_Bound (Typ);
5133 -- We need the high bound of the base type later on, and this should
5134 -- always be compile time known. Again, it is not clear that this
5135 -- can ever be false, but no point in bombing.
5137 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5138 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
5139 Hi := Hbound;
5141 else
5142 OK := False;
5143 return;
5144 end if;
5146 -- If we have a static subtype, then that may have a tighter bound so
5147 -- use the upper bound of the subtype instead in this case.
5149 if Compile_Time_Known_Value (Bound) then
5150 Hi := Expr_Value_R (Bound);
5151 end if;
5153 -- We may be able to refine this value in certain situations. If any
5154 -- refinement is possible, then Lor and Hir are set to possibly tighter
5155 -- bounds, and OK1 is set to True.
5157 case Nkind (N) is
5159 -- For unary plus, result is limited by range of operand
5161 when N_Op_Plus =>
5162 Determine_Range_R
5163 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
5165 -- For unary minus, determine range of operand, and negate it
5167 when N_Op_Minus =>
5168 Determine_Range_R
5169 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5171 if OK1 then
5172 Lor := -Hi_Right;
5173 Hir := -Lo_Right;
5174 end if;
5176 -- For binary addition, get range of each operand and do the
5177 -- addition to get the result range.
5179 when N_Op_Add =>
5180 if OK_Operands then
5181 Lor := Round_Machine (Lo_Left + Lo_Right);
5182 Hir := Round_Machine (Hi_Left + Hi_Right);
5183 end if;
5185 -- For binary subtraction, get range of each operand and do the worst
5186 -- case subtraction to get the result range.
5188 when N_Op_Subtract =>
5189 if OK_Operands then
5190 Lor := Round_Machine (Lo_Left - Hi_Right);
5191 Hir := Round_Machine (Hi_Left - Lo_Right);
5192 end if;
5194 -- For multiplication, get range of each operand and do the
5195 -- four multiplications to get the result range.
5197 when N_Op_Multiply =>
5198 if OK_Operands then
5199 declare
5200 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
5201 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
5202 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
5203 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
5205 begin
5206 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
5207 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
5208 end;
5209 end if;
5211 -- For division, consider separately the cases where the right
5212 -- operand is positive or negative. Otherwise, the right operand
5213 -- can be arbitrarily close to zero, so the result is likely to
5214 -- be unbounded in one direction, do not attempt to compute it.
5216 when N_Op_Divide =>
5217 if OK_Operands then
5219 -- Right operand is positive
5221 if Lo_Right > Ureal_0 then
5223 -- If the low bound of the left operand is negative, obtain
5224 -- the overall low bound by dividing it by the smallest
5225 -- value of the right operand, and otherwise by the largest
5226 -- value of the right operand.
5228 if Lo_Left < Ureal_0 then
5229 Lor := Round_Machine (Lo_Left / Lo_Right);
5230 else
5231 Lor := Round_Machine (Lo_Left / Hi_Right);
5232 end if;
5234 -- If the high bound of the left operand is negative, obtain
5235 -- the overall high bound by dividing it by the largest
5236 -- value of the right operand, and otherwise by the
5237 -- smallest value of the right operand.
5239 if Hi_Left < Ureal_0 then
5240 Hir := Round_Machine (Hi_Left / Hi_Right);
5241 else
5242 Hir := Round_Machine (Hi_Left / Lo_Right);
5243 end if;
5245 -- Right operand is negative
5247 elsif Hi_Right < Ureal_0 then
5249 -- If the low bound of the left operand is negative, obtain
5250 -- the overall low bound by dividing it by the largest
5251 -- value of the right operand, and otherwise by the smallest
5252 -- value of the right operand.
5254 if Lo_Left < Ureal_0 then
5255 Lor := Round_Machine (Lo_Left / Hi_Right);
5256 else
5257 Lor := Round_Machine (Lo_Left / Lo_Right);
5258 end if;
5260 -- If the high bound of the left operand is negative, obtain
5261 -- the overall high bound by dividing it by the smallest
5262 -- value of the right operand, and otherwise by the
5263 -- largest value of the right operand.
5265 if Hi_Left < Ureal_0 then
5266 Hir := Round_Machine (Hi_Left / Lo_Right);
5267 else
5268 Hir := Round_Machine (Hi_Left / Hi_Right);
5269 end if;
5271 else
5272 OK1 := False;
5273 end if;
5274 end if;
5276 when N_Type_Conversion =>
5278 -- For type conversion from one floating-point type to another, we
5279 -- can refine the range using the converted value.
5281 if Is_Floating_Point_Type (Etype (Expression (N))) then
5282 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5284 -- When converting an integer to a floating-point type, determine
5285 -- the range in integer first, and then convert the bounds.
5287 elsif Is_Discrete_Type (Etype (Expression (N))) then
5288 declare
5289 Hir_Int : Uint;
5290 Lor_Int : Uint;
5292 begin
5293 Determine_Range
5294 (Expression (N), OK1, Lor_Int, Hir_Int, Assume_Valid);
5296 if OK1 then
5297 Lor := Round_Machine (UR_From_Uint (Lor_Int));
5298 Hir := Round_Machine (UR_From_Uint (Hir_Int));
5299 end if;
5300 end;
5302 else
5303 OK1 := False;
5304 end if;
5306 -- Nothing special to do for all other expression kinds
5308 when others =>
5309 OK1 := False;
5310 Lor := No_Ureal;
5311 Hir := No_Ureal;
5312 end case;
5314 -- At this stage, if OK1 is true, then we know that the actual result of
5315 -- the computed expression is in the range Lor .. Hir. We can use this
5316 -- to restrict the possible range of results.
5318 if OK1 then
5320 -- If the refined value of the low bound is greater than the type
5321 -- low bound, then reset it to the more restrictive value.
5323 if Lor > Lo then
5324 Lo := Lor;
5325 end if;
5327 -- Similarly, if the refined value of the high bound is less than the
5328 -- value so far, then reset it to the more restrictive value.
5330 if Hir < Hi then
5331 Hi := Hir;
5332 end if;
5333 end if;
5335 -- Set cache entry for future call and we are all done
5337 Determine_Range_Cache_N (Cindex) := N;
5338 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5339 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5340 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5341 return;
5343 -- If any exception occurs, it means that we have some bug in the compiler,
5344 -- possibly triggered by a previous error, or by some unforeseen peculiar
5345 -- occurrence. However, this is only an optimization attempt, so there is
5346 -- really no point in crashing the compiler. Instead we just decide, too
5347 -- bad, we can't figure out a range in this case after all.
5349 exception
5350 when others =>
5352 -- Debug flag K disables this behavior (useful for debugging)
5354 if Debug_Flag_K then
5355 raise;
5356 else
5357 OK := False;
5358 Lo := No_Ureal;
5359 Hi := No_Ureal;
5360 return;
5361 end if;
5362 end Determine_Range_R;
5364 ------------------------------------
5365 -- Discriminant_Checks_Suppressed --
5366 ------------------------------------
5368 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
5369 begin
5370 if Present (E) then
5371 if Is_Unchecked_Union (E) then
5372 return True;
5373 elsif Checks_May_Be_Suppressed (E) then
5374 return Is_Check_Suppressed (E, Discriminant_Check);
5375 end if;
5376 end if;
5378 return Scope_Suppress.Suppress (Discriminant_Check);
5379 end Discriminant_Checks_Suppressed;
5381 --------------------------------
5382 -- Division_Checks_Suppressed --
5383 --------------------------------
5385 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
5386 begin
5387 if Present (E) and then Checks_May_Be_Suppressed (E) then
5388 return Is_Check_Suppressed (E, Division_Check);
5389 else
5390 return Scope_Suppress.Suppress (Division_Check);
5391 end if;
5392 end Division_Checks_Suppressed;
5394 --------------------------------------
5395 -- Duplicated_Tag_Checks_Suppressed --
5396 --------------------------------------
5398 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
5399 begin
5400 if Present (E) and then Checks_May_Be_Suppressed (E) then
5401 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
5402 else
5403 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
5404 end if;
5405 end Duplicated_Tag_Checks_Suppressed;
5407 -----------------------------------
5408 -- Elaboration_Checks_Suppressed --
5409 -----------------------------------
5411 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
5412 begin
5413 -- The complication in this routine is that if we are in the dynamic
5414 -- model of elaboration, we also check All_Checks, since All_Checks
5415 -- does not set Elaboration_Check explicitly.
5417 if Present (E) then
5418 if Kill_Elaboration_Checks (E) then
5419 return True;
5421 elsif Checks_May_Be_Suppressed (E) then
5422 if Is_Check_Suppressed (E, Elaboration_Check) then
5423 return True;
5425 elsif Dynamic_Elaboration_Checks then
5426 return Is_Check_Suppressed (E, All_Checks);
5428 else
5429 return False;
5430 end if;
5431 end if;
5432 end if;
5434 if Scope_Suppress.Suppress (Elaboration_Check) then
5435 return True;
5437 elsif Dynamic_Elaboration_Checks then
5438 return Scope_Suppress.Suppress (All_Checks);
5440 else
5441 return False;
5442 end if;
5443 end Elaboration_Checks_Suppressed;
5445 ---------------------------
5446 -- Enable_Overflow_Check --
5447 ---------------------------
5449 procedure Enable_Overflow_Check (N : Node_Id) is
5450 Typ : constant Entity_Id := Base_Type (Etype (N));
5451 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
5452 Chk : Nat;
5453 OK : Boolean;
5454 Ent : Entity_Id;
5455 Ofs : Uint;
5456 Lo : Uint;
5457 Hi : Uint;
5459 Do_Ovflow_Check : Boolean;
5461 begin
5462 if Debug_Flag_CC then
5463 w ("Enable_Overflow_Check for node ", Int (N));
5464 Write_Str (" Source location = ");
5465 wl (Sloc (N));
5466 pg (Union_Id (N));
5467 end if;
5469 -- No check if overflow checks suppressed for type of node
5471 if Overflow_Checks_Suppressed (Etype (N)) then
5472 return;
5474 -- Nothing to do for unsigned integer types, which do not overflow
5476 elsif Is_Modular_Integer_Type (Typ) then
5477 return;
5478 end if;
5480 -- This is the point at which processing for STRICT mode diverges
5481 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5482 -- probably more extreme that it needs to be, but what is going on here
5483 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
5484 -- to leave the processing for STRICT mode untouched. There were
5485 -- two reasons for this. First it avoided any incompatible change of
5486 -- behavior. Second, it guaranteed that STRICT mode continued to be
5487 -- legacy reliable.
5489 -- The big difference is that in STRICT mode there is a fair amount of
5490 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5491 -- know that no check is needed. We skip all that in the two new modes,
5492 -- since really overflow checking happens over a whole subtree, and we
5493 -- do the corresponding optimizations later on when applying the checks.
5495 if Mode in Minimized_Or_Eliminated then
5496 if not (Overflow_Checks_Suppressed (Etype (N)))
5497 and then not (Is_Entity_Name (N)
5498 and then Overflow_Checks_Suppressed (Entity (N)))
5499 then
5500 Activate_Overflow_Check (N);
5501 end if;
5503 if Debug_Flag_CC then
5504 w ("Minimized/Eliminated mode");
5505 end if;
5507 return;
5508 end if;
5510 -- Remainder of processing is for STRICT case, and is unchanged from
5511 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
5513 -- Nothing to do if the range of the result is known OK. We skip this
5514 -- for conversions, since the caller already did the check, and in any
5515 -- case the condition for deleting the check for a type conversion is
5516 -- different.
5518 if Nkind (N) /= N_Type_Conversion then
5519 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
5521 -- Note in the test below that we assume that the range is not OK
5522 -- if a bound of the range is equal to that of the type. That's not
5523 -- quite accurate but we do this for the following reasons:
5525 -- a) The way that Determine_Range works, it will typically report
5526 -- the bounds of the value as being equal to the bounds of the
5527 -- type, because it either can't tell anything more precise, or
5528 -- does not think it is worth the effort to be more precise.
5530 -- b) It is very unusual to have a situation in which this would
5531 -- generate an unnecessary overflow check (an example would be
5532 -- a subtype with a range 0 .. Integer'Last - 1 to which the
5533 -- literal value one is added).
5535 -- c) The alternative is a lot of special casing in this routine
5536 -- which would partially duplicate Determine_Range processing.
5538 if OK then
5539 Do_Ovflow_Check := True;
5541 -- Note that the following checks are quite deliberately > and <
5542 -- rather than >= and <= as explained above.
5544 if Lo > Expr_Value (Type_Low_Bound (Typ))
5545 and then
5546 Hi < Expr_Value (Type_High_Bound (Typ))
5547 then
5548 Do_Ovflow_Check := False;
5550 -- Despite the comments above, it is worth dealing specially with
5551 -- division specially. The only case where integer division can
5552 -- overflow is (largest negative number) / (-1). So we will do
5553 -- an extra range analysis to see if this is possible.
5555 elsif Nkind (N) = N_Op_Divide then
5556 Determine_Range
5557 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5559 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
5560 Do_Ovflow_Check := False;
5562 else
5563 Determine_Range
5564 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5566 if OK and then (Lo > Uint_Minus_1
5567 or else
5568 Hi < Uint_Minus_1)
5569 then
5570 Do_Ovflow_Check := False;
5571 end if;
5572 end if;
5573 end if;
5575 -- If no overflow check required, we are done
5577 if not Do_Ovflow_Check then
5578 if Debug_Flag_CC then
5579 w ("No overflow check required");
5580 end if;
5582 return;
5583 end if;
5584 end if;
5585 end if;
5587 -- If not in optimizing mode, set flag and we are done. We are also done
5588 -- (and just set the flag) if the type is not a discrete type, since it
5589 -- is not worth the effort to eliminate checks for other than discrete
5590 -- types. In addition, we take this same path if we have stored the
5591 -- maximum number of checks possible already (a very unlikely situation,
5592 -- but we do not want to blow up).
5594 if Optimization_Level = 0
5595 or else not Is_Discrete_Type (Etype (N))
5596 or else Num_Saved_Checks = Saved_Checks'Last
5597 then
5598 Activate_Overflow_Check (N);
5600 if Debug_Flag_CC then
5601 w ("Optimization off");
5602 end if;
5604 return;
5605 end if;
5607 -- Otherwise evaluate and check the expression
5609 Find_Check
5610 (Expr => N,
5611 Check_Type => 'O',
5612 Target_Type => Empty,
5613 Entry_OK => OK,
5614 Check_Num => Chk,
5615 Ent => Ent,
5616 Ofs => Ofs);
5618 if Debug_Flag_CC then
5619 w ("Called Find_Check");
5620 w (" OK = ", OK);
5622 if OK then
5623 w (" Check_Num = ", Chk);
5624 w (" Ent = ", Int (Ent));
5625 Write_Str (" Ofs = ");
5626 pid (Ofs);
5627 end if;
5628 end if;
5630 -- If check is not of form to optimize, then set flag and we are done
5632 if not OK then
5633 Activate_Overflow_Check (N);
5634 return;
5635 end if;
5637 -- If check is already performed, then return without setting flag
5639 if Chk /= 0 then
5640 if Debug_Flag_CC then
5641 w ("Check suppressed!");
5642 end if;
5644 return;
5645 end if;
5647 -- Here we will make a new entry for the new check
5649 Activate_Overflow_Check (N);
5650 Num_Saved_Checks := Num_Saved_Checks + 1;
5651 Saved_Checks (Num_Saved_Checks) :=
5652 (Killed => False,
5653 Entity => Ent,
5654 Offset => Ofs,
5655 Check_Type => 'O',
5656 Target_Type => Empty);
5658 if Debug_Flag_CC then
5659 w ("Make new entry, check number = ", Num_Saved_Checks);
5660 w (" Entity = ", Int (Ent));
5661 Write_Str (" Offset = ");
5662 pid (Ofs);
5663 w (" Check_Type = O");
5664 w (" Target_Type = Empty");
5665 end if;
5667 -- If we get an exception, then something went wrong, probably because of
5668 -- an error in the structure of the tree due to an incorrect program. Or
5669 -- it may be a bug in the optimization circuit. In either case the safest
5670 -- thing is simply to set the check flag unconditionally.
5672 exception
5673 when others =>
5674 Activate_Overflow_Check (N);
5676 if Debug_Flag_CC then
5677 w (" exception occurred, overflow flag set");
5678 end if;
5680 return;
5681 end Enable_Overflow_Check;
5683 ------------------------
5684 -- Enable_Range_Check --
5685 ------------------------
5687 procedure Enable_Range_Check (N : Node_Id) is
5688 Chk : Nat;
5689 OK : Boolean;
5690 Ent : Entity_Id;
5691 Ofs : Uint;
5692 Ttyp : Entity_Id;
5693 P : Node_Id;
5695 begin
5696 -- Return if unchecked type conversion with range check killed. In this
5697 -- case we never set the flag (that's what Kill_Range_Check is about).
5699 if Nkind (N) = N_Unchecked_Type_Conversion
5700 and then Kill_Range_Check (N)
5701 then
5702 return;
5703 end if;
5705 -- Do not set range check flag if parent is assignment statement or
5706 -- object declaration with Suppress_Assignment_Checks flag set
5708 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
5709 and then Suppress_Assignment_Checks (Parent (N))
5710 then
5711 return;
5712 end if;
5714 -- Check for various cases where we should suppress the range check
5716 -- No check if range checks suppressed for type of node
5718 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
5719 return;
5721 -- No check if node is an entity name, and range checks are suppressed
5722 -- for this entity, or for the type of this entity.
5724 elsif Is_Entity_Name (N)
5725 and then (Range_Checks_Suppressed (Entity (N))
5726 or else Range_Checks_Suppressed (Etype (Entity (N))))
5727 then
5728 return;
5730 -- No checks if index of array, and index checks are suppressed for
5731 -- the array object or the type of the array.
5733 elsif Nkind (Parent (N)) = N_Indexed_Component then
5734 declare
5735 Pref : constant Node_Id := Prefix (Parent (N));
5736 begin
5737 if Is_Entity_Name (Pref)
5738 and then Index_Checks_Suppressed (Entity (Pref))
5739 then
5740 return;
5741 elsif Index_Checks_Suppressed (Etype (Pref)) then
5742 return;
5743 end if;
5744 end;
5745 end if;
5747 -- Debug trace output
5749 if Debug_Flag_CC then
5750 w ("Enable_Range_Check for node ", Int (N));
5751 Write_Str (" Source location = ");
5752 wl (Sloc (N));
5753 pg (Union_Id (N));
5754 end if;
5756 -- If not in optimizing mode, set flag and we are done. We are also done
5757 -- (and just set the flag) if the type is not a discrete type, since it
5758 -- is not worth the effort to eliminate checks for other than discrete
5759 -- types. In addition, we take this same path if we have stored the
5760 -- maximum number of checks possible already (a very unlikely situation,
5761 -- but we do not want to blow up).
5763 if Optimization_Level = 0
5764 or else No (Etype (N))
5765 or else not Is_Discrete_Type (Etype (N))
5766 or else Num_Saved_Checks = Saved_Checks'Last
5767 then
5768 Activate_Range_Check (N);
5770 if Debug_Flag_CC then
5771 w ("Optimization off");
5772 end if;
5774 return;
5775 end if;
5777 -- Otherwise find out the target type
5779 P := Parent (N);
5781 -- For assignment, use left side subtype
5783 if Nkind (P) = N_Assignment_Statement
5784 and then Expression (P) = N
5785 then
5786 Ttyp := Etype (Name (P));
5788 -- For indexed component, use subscript subtype
5790 elsif Nkind (P) = N_Indexed_Component then
5791 declare
5792 Atyp : Entity_Id;
5793 Indx : Node_Id;
5794 Subs : Node_Id;
5796 begin
5797 Atyp := Etype (Prefix (P));
5799 if Is_Access_Type (Atyp) then
5800 Atyp := Designated_Type (Atyp);
5802 -- If the prefix is an access to an unconstrained array,
5803 -- perform check unconditionally: it depends on the bounds of
5804 -- an object and we cannot currently recognize whether the test
5805 -- may be redundant.
5807 if not Is_Constrained (Atyp) then
5808 Activate_Range_Check (N);
5809 return;
5810 end if;
5812 -- Ditto if prefix is simply an unconstrained array. We used
5813 -- to think this case was OK, if the prefix was not an explicit
5814 -- dereference, but we have now seen a case where this is not
5815 -- true, so it is safer to just suppress the optimization in this
5816 -- case. The back end is getting better at eliminating redundant
5817 -- checks in any case, so the loss won't be important.
5819 elsif Is_Array_Type (Atyp)
5820 and then not Is_Constrained (Atyp)
5821 then
5822 Activate_Range_Check (N);
5823 return;
5824 end if;
5826 Indx := First_Index (Atyp);
5827 Subs := First (Expressions (P));
5828 loop
5829 if Subs = N then
5830 Ttyp := Etype (Indx);
5831 exit;
5832 end if;
5834 Next_Index (Indx);
5835 Next (Subs);
5836 end loop;
5837 end;
5839 -- For now, ignore all other cases, they are not so interesting
5841 else
5842 if Debug_Flag_CC then
5843 w (" target type not found, flag set");
5844 end if;
5846 Activate_Range_Check (N);
5847 return;
5848 end if;
5850 -- Evaluate and check the expression
5852 Find_Check
5853 (Expr => N,
5854 Check_Type => 'R',
5855 Target_Type => Ttyp,
5856 Entry_OK => OK,
5857 Check_Num => Chk,
5858 Ent => Ent,
5859 Ofs => Ofs);
5861 if Debug_Flag_CC then
5862 w ("Called Find_Check");
5863 w ("Target_Typ = ", Int (Ttyp));
5864 w (" OK = ", OK);
5866 if OK then
5867 w (" Check_Num = ", Chk);
5868 w (" Ent = ", Int (Ent));
5869 Write_Str (" Ofs = ");
5870 pid (Ofs);
5871 end if;
5872 end if;
5874 -- If check is not of form to optimize, then set flag and we are done
5876 if not OK then
5877 if Debug_Flag_CC then
5878 w (" expression not of optimizable type, flag set");
5879 end if;
5881 Activate_Range_Check (N);
5882 return;
5883 end if;
5885 -- If check is already performed, then return without setting flag
5887 if Chk /= 0 then
5888 if Debug_Flag_CC then
5889 w ("Check suppressed!");
5890 end if;
5892 return;
5893 end if;
5895 -- Here we will make a new entry for the new check
5897 Activate_Range_Check (N);
5898 Num_Saved_Checks := Num_Saved_Checks + 1;
5899 Saved_Checks (Num_Saved_Checks) :=
5900 (Killed => False,
5901 Entity => Ent,
5902 Offset => Ofs,
5903 Check_Type => 'R',
5904 Target_Type => Ttyp);
5906 if Debug_Flag_CC then
5907 w ("Make new entry, check number = ", Num_Saved_Checks);
5908 w (" Entity = ", Int (Ent));
5909 Write_Str (" Offset = ");
5910 pid (Ofs);
5911 w (" Check_Type = R");
5912 w (" Target_Type = ", Int (Ttyp));
5913 pg (Union_Id (Ttyp));
5914 end if;
5916 -- If we get an exception, then something went wrong, probably because of
5917 -- an error in the structure of the tree due to an incorrect program. Or
5918 -- it may be a bug in the optimization circuit. In either case the safest
5919 -- thing is simply to set the check flag unconditionally.
5921 exception
5922 when others =>
5923 Activate_Range_Check (N);
5925 if Debug_Flag_CC then
5926 w (" exception occurred, range flag set");
5927 end if;
5929 return;
5930 end Enable_Range_Check;
5932 ------------------
5933 -- Ensure_Valid --
5934 ------------------
5936 procedure Ensure_Valid
5937 (Expr : Node_Id;
5938 Holes_OK : Boolean := False;
5939 Related_Id : Entity_Id := Empty;
5940 Is_Low_Bound : Boolean := False;
5941 Is_High_Bound : Boolean := False)
5943 Typ : constant Entity_Id := Etype (Expr);
5945 begin
5946 -- Ignore call if we are not doing any validity checking
5948 if not Validity_Checks_On then
5949 return;
5951 -- Ignore call if range or validity checks suppressed on entity or type
5953 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
5954 return;
5956 -- No check required if expression is from the expander, we assume the
5957 -- expander will generate whatever checks are needed. Note that this is
5958 -- not just an optimization, it avoids infinite recursions.
5960 -- Unchecked conversions must be checked, unless they are initialized
5961 -- scalar values, as in a component assignment in an init proc.
5963 -- In addition, we force a check if Force_Validity_Checks is set
5965 elsif not Comes_From_Source (Expr)
5966 and then not
5967 (Nkind (Expr) = N_Identifier
5968 and then Present (Renamed_Object (Entity (Expr)))
5969 and then Comes_From_Source (Renamed_Object (Entity (Expr))))
5970 and then not Force_Validity_Checks
5971 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
5972 or else Kill_Range_Check (Expr))
5973 then
5974 return;
5976 -- No check required if expression is known to have valid value
5978 elsif Expr_Known_Valid (Expr) then
5979 return;
5981 -- No check needed within a generated predicate function. Validity
5982 -- of input value will have been checked earlier.
5984 elsif Ekind (Current_Scope) = E_Function
5985 and then Is_Predicate_Function (Current_Scope)
5986 then
5987 return;
5989 -- Ignore case of enumeration with holes where the flag is set not to
5990 -- worry about holes, since no special validity check is needed
5992 elsif Is_Enumeration_Type (Typ)
5993 and then Has_Non_Standard_Rep (Typ)
5994 and then Holes_OK
5995 then
5996 return;
5998 -- No check required on the left-hand side of an assignment
6000 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
6001 and then Expr = Name (Parent (Expr))
6002 then
6003 return;
6005 -- No check on a universal real constant. The context will eventually
6006 -- convert it to a machine number for some target type, or report an
6007 -- illegality.
6009 elsif Nkind (Expr) = N_Real_Literal
6010 and then Etype (Expr) = Universal_Real
6011 then
6012 return;
6014 -- If the expression denotes a component of a packed boolean array,
6015 -- no possible check applies. We ignore the old ACATS chestnuts that
6016 -- involve Boolean range True..True.
6018 -- Note: validity checks are generated for expressions that yield a
6019 -- scalar type, when it is possible to create a value that is outside of
6020 -- the type. If this is a one-bit boolean no such value exists. This is
6021 -- an optimization, and it also prevents compiler blowing up during the
6022 -- elaboration of improperly expanded packed array references.
6024 elsif Nkind (Expr) = N_Indexed_Component
6025 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
6026 and then Root_Type (Etype (Expr)) = Standard_Boolean
6027 then
6028 return;
6030 -- For an expression with actions, we want to insert the validity check
6031 -- on the final Expression.
6033 elsif Nkind (Expr) = N_Expression_With_Actions then
6034 Ensure_Valid (Expression (Expr));
6035 return;
6037 -- An annoying special case. If this is an out parameter of a scalar
6038 -- type, then the value is not going to be accessed, therefore it is
6039 -- inappropriate to do any validity check at the call site.
6041 else
6042 -- Only need to worry about scalar types
6044 if Is_Scalar_Type (Typ) then
6045 declare
6046 P : Node_Id;
6047 N : Node_Id;
6048 E : Entity_Id;
6049 F : Entity_Id;
6050 A : Node_Id;
6051 L : List_Id;
6053 begin
6054 -- Find actual argument (which may be a parameter association)
6055 -- and the parent of the actual argument (the call statement)
6057 N := Expr;
6058 P := Parent (Expr);
6060 if Nkind (P) = N_Parameter_Association then
6061 N := P;
6062 P := Parent (N);
6063 end if;
6065 -- Only need to worry if we are argument of a procedure call
6066 -- since functions don't have out parameters. If this is an
6067 -- indirect or dispatching call, get signature from the
6068 -- subprogram type.
6070 if Nkind (P) = N_Procedure_Call_Statement then
6071 L := Parameter_Associations (P);
6073 if Is_Entity_Name (Name (P)) then
6074 E := Entity (Name (P));
6075 else
6076 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
6077 E := Etype (Name (P));
6078 end if;
6080 -- Only need to worry if there are indeed actuals, and if
6081 -- this could be a procedure call, otherwise we cannot get a
6082 -- match (either we are not an argument, or the mode of the
6083 -- formal is not OUT). This test also filters out the
6084 -- generic case.
6086 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
6088 -- This is the loop through parameters, looking for an
6089 -- OUT parameter for which we are the argument.
6091 F := First_Formal (E);
6092 A := First (L);
6093 while Present (F) loop
6094 if Ekind (F) = E_Out_Parameter and then A = N then
6095 return;
6096 end if;
6098 Next_Formal (F);
6099 Next (A);
6100 end loop;
6101 end if;
6102 end if;
6103 end;
6104 end if;
6105 end if;
6107 -- If this is a boolean expression, only its elementary operands need
6108 -- checking: if they are valid, a boolean or short-circuit operation
6109 -- with them will be valid as well.
6111 if Base_Type (Typ) = Standard_Boolean
6112 and then
6113 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
6114 then
6115 return;
6116 end if;
6118 -- If we fall through, a validity check is required
6120 Insert_Valid_Check (Expr, Related_Id, Is_Low_Bound, Is_High_Bound);
6122 if Is_Entity_Name (Expr)
6123 and then Safe_To_Capture_Value (Expr, Entity (Expr))
6124 then
6125 Set_Is_Known_Valid (Entity (Expr));
6126 end if;
6127 end Ensure_Valid;
6129 ----------------------
6130 -- Expr_Known_Valid --
6131 ----------------------
6133 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
6134 Typ : constant Entity_Id := Etype (Expr);
6136 begin
6137 -- Non-scalar types are always considered valid, since they never give
6138 -- rise to the issues of erroneous or bounded error behavior that are
6139 -- the concern. In formal reference manual terms the notion of validity
6140 -- only applies to scalar types. Note that even when packed arrays are
6141 -- represented using modular types, they are still arrays semantically,
6142 -- so they are also always valid (in particular, the unused bits can be
6143 -- random rubbish without affecting the validity of the array value).
6145 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
6146 return True;
6148 -- If no validity checking, then everything is considered valid
6150 elsif not Validity_Checks_On then
6151 return True;
6153 -- Floating-point types are considered valid unless floating-point
6154 -- validity checks have been specifically turned on.
6156 elsif Is_Floating_Point_Type (Typ)
6157 and then not Validity_Check_Floating_Point
6158 then
6159 return True;
6161 -- If the expression is the value of an object that is known to be
6162 -- valid, then clearly the expression value itself is valid.
6164 elsif Is_Entity_Name (Expr)
6165 and then Is_Known_Valid (Entity (Expr))
6167 -- Exclude volatile variables
6169 and then not Treat_As_Volatile (Entity (Expr))
6170 then
6171 return True;
6173 -- References to discriminants are always considered valid. The value
6174 -- of a discriminant gets checked when the object is built. Within the
6175 -- record, we consider it valid, and it is important to do so, since
6176 -- otherwise we can try to generate bogus validity checks which
6177 -- reference discriminants out of scope. Discriminants of concurrent
6178 -- types are excluded for the same reason.
6180 elsif Is_Entity_Name (Expr)
6181 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
6182 then
6183 return True;
6185 -- If the type is one for which all values are known valid, then we are
6186 -- sure that the value is valid except in the slightly odd case where
6187 -- the expression is a reference to a variable whose size has been
6188 -- explicitly set to a value greater than the object size.
6190 elsif Is_Known_Valid (Typ) then
6191 if Is_Entity_Name (Expr)
6192 and then Ekind (Entity (Expr)) = E_Variable
6193 and then Esize (Entity (Expr)) > Esize (Typ)
6194 then
6195 return False;
6196 else
6197 return True;
6198 end if;
6200 -- Integer and character literals always have valid values, where
6201 -- appropriate these will be range checked in any case.
6203 elsif Nkind_In (Expr, N_Integer_Literal, N_Character_Literal) then
6204 return True;
6206 -- If we have a type conversion or a qualification of a known valid
6207 -- value, then the result will always be valid.
6209 elsif Nkind_In (Expr, N_Type_Conversion, N_Qualified_Expression) then
6210 return Expr_Known_Valid (Expression (Expr));
6212 -- Case of expression is a non-floating-point operator. In this case we
6213 -- can assume the result is valid the generated code for the operator
6214 -- will include whatever checks are needed (e.g. range checks) to ensure
6215 -- validity. This assumption does not hold for the floating-point case,
6216 -- since floating-point operators can generate Infinite or NaN results
6217 -- which are considered invalid.
6219 -- Historical note: in older versions, the exemption of floating-point
6220 -- types from this assumption was done only in cases where the parent
6221 -- was an assignment, function call or parameter association. Presumably
6222 -- the idea was that in other contexts, the result would be checked
6223 -- elsewhere, but this list of cases was missing tests (at least the
6224 -- N_Object_Declaration case, as shown by a reported missing validity
6225 -- check), and it is not clear why function calls but not procedure
6226 -- calls were tested for. It really seems more accurate and much
6227 -- safer to recognize that expressions which are the result of a
6228 -- floating-point operator can never be assumed to be valid.
6230 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
6231 return True;
6233 -- The result of a membership test is always valid, since it is true or
6234 -- false, there are no other possibilities.
6236 elsif Nkind (Expr) in N_Membership_Test then
6237 return True;
6239 -- For all other cases, we do not know the expression is valid
6241 else
6242 return False;
6243 end if;
6244 end Expr_Known_Valid;
6246 ----------------
6247 -- Find_Check --
6248 ----------------
6250 procedure Find_Check
6251 (Expr : Node_Id;
6252 Check_Type : Character;
6253 Target_Type : Entity_Id;
6254 Entry_OK : out Boolean;
6255 Check_Num : out Nat;
6256 Ent : out Entity_Id;
6257 Ofs : out Uint)
6259 function Within_Range_Of
6260 (Target_Type : Entity_Id;
6261 Check_Type : Entity_Id) return Boolean;
6262 -- Given a requirement for checking a range against Target_Type, and
6263 -- and a range Check_Type against which a check has already been made,
6264 -- determines if the check against check type is sufficient to ensure
6265 -- that no check against Target_Type is required.
6267 ---------------------
6268 -- Within_Range_Of --
6269 ---------------------
6271 function Within_Range_Of
6272 (Target_Type : Entity_Id;
6273 Check_Type : Entity_Id) return Boolean
6275 begin
6276 if Target_Type = Check_Type then
6277 return True;
6279 else
6280 declare
6281 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
6282 Thi : constant Node_Id := Type_High_Bound (Target_Type);
6283 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
6284 Chi : constant Node_Id := Type_High_Bound (Check_Type);
6286 begin
6287 if (Tlo = Clo
6288 or else (Compile_Time_Known_Value (Tlo)
6289 and then
6290 Compile_Time_Known_Value (Clo)
6291 and then
6292 Expr_Value (Clo) >= Expr_Value (Tlo)))
6293 and then
6294 (Thi = Chi
6295 or else (Compile_Time_Known_Value (Thi)
6296 and then
6297 Compile_Time_Known_Value (Chi)
6298 and then
6299 Expr_Value (Chi) <= Expr_Value (Clo)))
6300 then
6301 return True;
6302 else
6303 return False;
6304 end if;
6305 end;
6306 end if;
6307 end Within_Range_Of;
6309 -- Start of processing for Find_Check
6311 begin
6312 -- Establish default, in case no entry is found
6314 Check_Num := 0;
6316 -- Case of expression is simple entity reference
6318 if Is_Entity_Name (Expr) then
6319 Ent := Entity (Expr);
6320 Ofs := Uint_0;
6322 -- Case of expression is entity + known constant
6324 elsif Nkind (Expr) = N_Op_Add
6325 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6326 and then Is_Entity_Name (Left_Opnd (Expr))
6327 then
6328 Ent := Entity (Left_Opnd (Expr));
6329 Ofs := Expr_Value (Right_Opnd (Expr));
6331 -- Case of expression is entity - known constant
6333 elsif Nkind (Expr) = N_Op_Subtract
6334 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6335 and then Is_Entity_Name (Left_Opnd (Expr))
6336 then
6337 Ent := Entity (Left_Opnd (Expr));
6338 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
6340 -- Any other expression is not of the right form
6342 else
6343 Ent := Empty;
6344 Ofs := Uint_0;
6345 Entry_OK := False;
6346 return;
6347 end if;
6349 -- Come here with expression of appropriate form, check if entity is an
6350 -- appropriate one for our purposes.
6352 if (Ekind (Ent) = E_Variable
6353 or else Is_Constant_Object (Ent))
6354 and then not Is_Library_Level_Entity (Ent)
6355 then
6356 Entry_OK := True;
6357 else
6358 Entry_OK := False;
6359 return;
6360 end if;
6362 -- See if there is matching check already
6364 for J in reverse 1 .. Num_Saved_Checks loop
6365 declare
6366 SC : Saved_Check renames Saved_Checks (J);
6367 begin
6368 if SC.Killed = False
6369 and then SC.Entity = Ent
6370 and then SC.Offset = Ofs
6371 and then SC.Check_Type = Check_Type
6372 and then Within_Range_Of (Target_Type, SC.Target_Type)
6373 then
6374 Check_Num := J;
6375 return;
6376 end if;
6377 end;
6378 end loop;
6380 -- If we fall through entry was not found
6382 return;
6383 end Find_Check;
6385 ---------------------------------
6386 -- Generate_Discriminant_Check --
6387 ---------------------------------
6389 -- Note: the code for this procedure is derived from the
6390 -- Emit_Discriminant_Check Routine in trans.c.
6392 procedure Generate_Discriminant_Check (N : Node_Id) is
6393 Loc : constant Source_Ptr := Sloc (N);
6394 Pref : constant Node_Id := Prefix (N);
6395 Sel : constant Node_Id := Selector_Name (N);
6397 Orig_Comp : constant Entity_Id :=
6398 Original_Record_Component (Entity (Sel));
6399 -- The original component to be checked
6401 Discr_Fct : constant Entity_Id :=
6402 Discriminant_Checking_Func (Orig_Comp);
6403 -- The discriminant checking function
6405 Discr : Entity_Id;
6406 -- One discriminant to be checked in the type
6408 Real_Discr : Entity_Id;
6409 -- Actual discriminant in the call
6411 Pref_Type : Entity_Id;
6412 -- Type of relevant prefix (ignoring private/access stuff)
6414 Args : List_Id;
6415 -- List of arguments for function call
6417 Formal : Entity_Id;
6418 -- Keep track of the formal corresponding to the actual we build for
6419 -- each discriminant, in order to be able to perform the necessary type
6420 -- conversions.
6422 Scomp : Node_Id;
6423 -- Selected component reference for checking function argument
6425 begin
6426 Pref_Type := Etype (Pref);
6428 -- Force evaluation of the prefix, so that it does not get evaluated
6429 -- twice (once for the check, once for the actual reference). Such a
6430 -- double evaluation is always a potential source of inefficiency, and
6431 -- is functionally incorrect in the volatile case, or when the prefix
6432 -- may have side effects. A nonvolatile entity or a component of a
6433 -- nonvolatile entity requires no evaluation.
6435 if Is_Entity_Name (Pref) then
6436 if Treat_As_Volatile (Entity (Pref)) then
6437 Force_Evaluation (Pref, Name_Req => True);
6438 end if;
6440 elsif Treat_As_Volatile (Etype (Pref)) then
6441 Force_Evaluation (Pref, Name_Req => True);
6443 elsif Nkind (Pref) = N_Selected_Component
6444 and then Is_Entity_Name (Prefix (Pref))
6445 then
6446 null;
6448 else
6449 Force_Evaluation (Pref, Name_Req => True);
6450 end if;
6452 -- For a tagged type, use the scope of the original component to
6453 -- obtain the type, because ???
6455 if Is_Tagged_Type (Scope (Orig_Comp)) then
6456 Pref_Type := Scope (Orig_Comp);
6458 -- For an untagged derived type, use the discriminants of the parent
6459 -- which have been renamed in the derivation, possibly by a one-to-many
6460 -- discriminant constraint. For untagged type, initially get the Etype
6461 -- of the prefix
6463 else
6464 if Is_Derived_Type (Pref_Type)
6465 and then Number_Discriminants (Pref_Type) /=
6466 Number_Discriminants (Etype (Base_Type (Pref_Type)))
6467 then
6468 Pref_Type := Etype (Base_Type (Pref_Type));
6469 end if;
6470 end if;
6472 -- We definitely should have a checking function, This routine should
6473 -- not be called if no discriminant checking function is present.
6475 pragma Assert (Present (Discr_Fct));
6477 -- Create the list of the actual parameters for the call. This list
6478 -- is the list of the discriminant fields of the record expression to
6479 -- be discriminant checked.
6481 Args := New_List;
6482 Formal := First_Formal (Discr_Fct);
6483 Discr := First_Discriminant (Pref_Type);
6484 while Present (Discr) loop
6486 -- If we have a corresponding discriminant field, and a parent
6487 -- subtype is present, then we want to use the corresponding
6488 -- discriminant since this is the one with the useful value.
6490 if Present (Corresponding_Discriminant (Discr))
6491 and then Ekind (Pref_Type) = E_Record_Type
6492 and then Present (Parent_Subtype (Pref_Type))
6493 then
6494 Real_Discr := Corresponding_Discriminant (Discr);
6495 else
6496 Real_Discr := Discr;
6497 end if;
6499 -- Construct the reference to the discriminant
6501 Scomp :=
6502 Make_Selected_Component (Loc,
6503 Prefix =>
6504 Unchecked_Convert_To (Pref_Type,
6505 Duplicate_Subexpr (Pref)),
6506 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
6508 -- Manually analyze and resolve this selected component. We really
6509 -- want it just as it appears above, and do not want the expander
6510 -- playing discriminal games etc with this reference. Then we append
6511 -- the argument to the list we are gathering.
6513 Set_Etype (Scomp, Etype (Real_Discr));
6514 Set_Analyzed (Scomp, True);
6515 Append_To (Args, Convert_To (Etype (Formal), Scomp));
6517 Next_Formal_With_Extras (Formal);
6518 Next_Discriminant (Discr);
6519 end loop;
6521 -- Now build and insert the call
6523 Insert_Action (N,
6524 Make_Raise_Constraint_Error (Loc,
6525 Condition =>
6526 Make_Function_Call (Loc,
6527 Name => New_Occurrence_Of (Discr_Fct, Loc),
6528 Parameter_Associations => Args),
6529 Reason => CE_Discriminant_Check_Failed));
6530 end Generate_Discriminant_Check;
6532 ---------------------------
6533 -- Generate_Index_Checks --
6534 ---------------------------
6536 procedure Generate_Index_Checks (N : Node_Id) is
6538 function Entity_Of_Prefix return Entity_Id;
6539 -- Returns the entity of the prefix of N (or Empty if not found)
6541 ----------------------
6542 -- Entity_Of_Prefix --
6543 ----------------------
6545 function Entity_Of_Prefix return Entity_Id is
6546 P : Node_Id;
6548 begin
6549 P := Prefix (N);
6550 while not Is_Entity_Name (P) loop
6551 if not Nkind_In (P, N_Selected_Component,
6552 N_Indexed_Component)
6553 then
6554 return Empty;
6555 end if;
6557 P := Prefix (P);
6558 end loop;
6560 return Entity (P);
6561 end Entity_Of_Prefix;
6563 -- Local variables
6565 Loc : constant Source_Ptr := Sloc (N);
6566 A : constant Node_Id := Prefix (N);
6567 A_Ent : constant Entity_Id := Entity_Of_Prefix;
6568 Sub : Node_Id;
6570 -- Start of processing for Generate_Index_Checks
6572 begin
6573 -- Ignore call if the prefix is not an array since we have a serious
6574 -- error in the sources. Ignore it also if index checks are suppressed
6575 -- for array object or type.
6577 if not Is_Array_Type (Etype (A))
6578 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
6579 or else Index_Checks_Suppressed (Etype (A))
6580 then
6581 return;
6583 -- The indexed component we are dealing with contains 'Loop_Entry in its
6584 -- prefix. This case arises when analysis has determined that constructs
6585 -- such as
6587 -- Prefix'Loop_Entry (Expr)
6588 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6590 -- require rewriting for error detection purposes. A side effect of this
6591 -- action is the generation of index checks that mention 'Loop_Entry.
6592 -- Delay the generation of the check until 'Loop_Entry has been properly
6593 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6595 elsif Nkind (Prefix (N)) = N_Attribute_Reference
6596 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
6597 then
6598 return;
6599 end if;
6601 -- Generate a raise of constraint error with the appropriate reason and
6602 -- a condition of the form:
6604 -- Base_Type (Sub) not in Array'Range (Subscript)
6606 -- Note that the reason we generate the conversion to the base type here
6607 -- is that we definitely want the range check to take place, even if it
6608 -- looks like the subtype is OK. Optimization considerations that allow
6609 -- us to omit the check have already been taken into account in the
6610 -- setting of the Do_Range_Check flag earlier on.
6612 Sub := First (Expressions (N));
6614 -- Handle string literals
6616 if Ekind (Etype (A)) = E_String_Literal_Subtype then
6617 if Do_Range_Check (Sub) then
6618 Set_Do_Range_Check (Sub, False);
6620 -- For string literals we obtain the bounds of the string from the
6621 -- associated subtype.
6623 Insert_Action (N,
6624 Make_Raise_Constraint_Error (Loc,
6625 Condition =>
6626 Make_Not_In (Loc,
6627 Left_Opnd =>
6628 Convert_To (Base_Type (Etype (Sub)),
6629 Duplicate_Subexpr_Move_Checks (Sub)),
6630 Right_Opnd =>
6631 Make_Attribute_Reference (Loc,
6632 Prefix => New_Occurrence_Of (Etype (A), Loc),
6633 Attribute_Name => Name_Range)),
6634 Reason => CE_Index_Check_Failed));
6635 end if;
6637 -- General case
6639 else
6640 declare
6641 A_Idx : Node_Id := Empty;
6642 A_Range : Node_Id;
6643 Ind : Nat;
6644 Num : List_Id;
6645 Range_N : Node_Id;
6647 begin
6648 A_Idx := First_Index (Etype (A));
6649 Ind := 1;
6650 while Present (Sub) loop
6651 if Do_Range_Check (Sub) then
6652 Set_Do_Range_Check (Sub, False);
6654 -- Force evaluation except for the case of a simple name of
6655 -- a nonvolatile entity.
6657 if not Is_Entity_Name (Sub)
6658 or else Treat_As_Volatile (Entity (Sub))
6659 then
6660 Force_Evaluation (Sub);
6661 end if;
6663 if Nkind (A_Idx) = N_Range then
6664 A_Range := A_Idx;
6666 elsif Nkind (A_Idx) = N_Identifier
6667 or else Nkind (A_Idx) = N_Expanded_Name
6668 then
6669 A_Range := Scalar_Range (Entity (A_Idx));
6671 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
6672 A_Range := Range_Expression (Constraint (A_Idx));
6673 end if;
6675 -- For array objects with constant bounds we can generate
6676 -- the index check using the bounds of the type of the index
6678 if Present (A_Ent)
6679 and then Ekind (A_Ent) = E_Variable
6680 and then Is_Constant_Bound (Low_Bound (A_Range))
6681 and then Is_Constant_Bound (High_Bound (A_Range))
6682 then
6683 Range_N :=
6684 Make_Attribute_Reference (Loc,
6685 Prefix =>
6686 New_Occurrence_Of (Etype (A_Idx), Loc),
6687 Attribute_Name => Name_Range);
6689 -- For arrays with non-constant bounds we cannot generate
6690 -- the index check using the bounds of the type of the index
6691 -- since it may reference discriminants of some enclosing
6692 -- type. We obtain the bounds directly from the prefix
6693 -- object.
6695 else
6696 if Ind = 1 then
6697 Num := No_List;
6698 else
6699 Num := New_List (Make_Integer_Literal (Loc, Ind));
6700 end if;
6702 Range_N :=
6703 Make_Attribute_Reference (Loc,
6704 Prefix =>
6705 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
6706 Attribute_Name => Name_Range,
6707 Expressions => Num);
6708 end if;
6710 Insert_Action (N,
6711 Make_Raise_Constraint_Error (Loc,
6712 Condition =>
6713 Make_Not_In (Loc,
6714 Left_Opnd =>
6715 Convert_To (Base_Type (Etype (Sub)),
6716 Duplicate_Subexpr_Move_Checks (Sub)),
6717 Right_Opnd => Range_N),
6718 Reason => CE_Index_Check_Failed));
6719 end if;
6721 A_Idx := Next_Index (A_Idx);
6722 Ind := Ind + 1;
6723 Next (Sub);
6724 end loop;
6725 end;
6726 end if;
6727 end Generate_Index_Checks;
6729 --------------------------
6730 -- Generate_Range_Check --
6731 --------------------------
6733 procedure Generate_Range_Check
6734 (N : Node_Id;
6735 Target_Type : Entity_Id;
6736 Reason : RT_Exception_Code)
6738 Loc : constant Source_Ptr := Sloc (N);
6739 Source_Type : constant Entity_Id := Etype (N);
6740 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
6741 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
6743 procedure Convert_And_Check_Range;
6744 -- Convert the conversion operand to the target base type and save in
6745 -- a temporary. Then check the converted value against the range of the
6746 -- target subtype.
6748 -----------------------------
6749 -- Convert_And_Check_Range --
6750 -----------------------------
6752 procedure Convert_And_Check_Range is
6753 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6755 begin
6756 -- We make a temporary to hold the value of the converted value
6757 -- (converted to the base type), and then do the test against this
6758 -- temporary. The conversion itself is replaced by an occurrence of
6759 -- Tnn and followed by the explicit range check. Note that checks
6760 -- are suppressed for this code, since we don't want a recursive
6761 -- range check popping up.
6763 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6764 -- [constraint_error when Tnn not in Target_Type]
6766 Insert_Actions (N, New_List (
6767 Make_Object_Declaration (Loc,
6768 Defining_Identifier => Tnn,
6769 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
6770 Constant_Present => True,
6771 Expression =>
6772 Make_Type_Conversion (Loc,
6773 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
6774 Expression => Duplicate_Subexpr (N))),
6776 Make_Raise_Constraint_Error (Loc,
6777 Condition =>
6778 Make_Not_In (Loc,
6779 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6780 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6781 Reason => Reason)),
6782 Suppress => All_Checks);
6784 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6786 -- Set the type of N, because the declaration for Tnn might not
6787 -- be analyzed yet, as is the case if N appears within a record
6788 -- declaration, as a discriminant constraint or expression.
6790 Set_Etype (N, Target_Base_Type);
6791 end Convert_And_Check_Range;
6793 -- Start of processing for Generate_Range_Check
6795 begin
6796 -- First special case, if the source type is already within the range
6797 -- of the target type, then no check is needed (probably we should have
6798 -- stopped Do_Range_Check from being set in the first place, but better
6799 -- late than never in preventing junk code and junk flag settings.
6801 if In_Subrange_Of (Source_Type, Target_Type)
6803 -- We do NOT apply this if the source node is a literal, since in this
6804 -- case the literal has already been labeled as having the subtype of
6805 -- the target.
6807 and then not
6808 (Nkind_In (N, N_Integer_Literal, N_Real_Literal, N_Character_Literal)
6809 or else
6810 (Is_Entity_Name (N)
6811 and then Ekind (Entity (N)) = E_Enumeration_Literal))
6812 then
6813 Set_Do_Range_Check (N, False);
6814 return;
6815 end if;
6817 -- Here a check is needed. If the expander is not active, or if we are
6818 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6819 -- are done. In both these cases, we just want to see the range check
6820 -- flag set, we do not want to generate the explicit range check code.
6822 if GNATprove_Mode or else not Expander_Active then
6823 Set_Do_Range_Check (N, True);
6824 return;
6825 end if;
6827 -- Here we will generate an explicit range check, so we don't want to
6828 -- set the Do_Range check flag, since the range check is taken care of
6829 -- by the code we will generate.
6831 Set_Do_Range_Check (N, False);
6833 -- Force evaluation of the node, so that it does not get evaluated twice
6834 -- (once for the check, once for the actual reference). Such a double
6835 -- evaluation is always a potential source of inefficiency, and is
6836 -- functionally incorrect in the volatile case.
6838 -- We skip the evaluation of attribute references because, after these
6839 -- runtime checks are generated, the expander may need to rewrite this
6840 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
6841 -- Expand_N_Attribute_Reference).
6843 if Nkind (N) /= N_Attribute_Reference
6844 and then (not Is_Entity_Name (N)
6845 or else Treat_As_Volatile (Entity (N)))
6846 then
6847 Force_Evaluation (N, Mode => Strict);
6848 end if;
6850 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6851 -- the same since in this case we can simply do a direct check of the
6852 -- value of N against the bounds of Target_Type.
6854 -- [constraint_error when N not in Target_Type]
6856 -- Note: this is by far the most common case, for example all cases of
6857 -- checks on the RHS of assignments are in this category, but not all
6858 -- cases are like this. Notably conversions can involve two types.
6860 if Source_Base_Type = Target_Base_Type then
6862 -- Insert the explicit range check. Note that we suppress checks for
6863 -- this code, since we don't want a recursive range check popping up.
6865 Insert_Action (N,
6866 Make_Raise_Constraint_Error (Loc,
6867 Condition =>
6868 Make_Not_In (Loc,
6869 Left_Opnd => Duplicate_Subexpr (N),
6870 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6871 Reason => Reason),
6872 Suppress => All_Checks);
6874 -- Next test for the case where the target type is within the bounds
6875 -- of the base type of the source type, since in this case we can
6876 -- simply convert these bounds to the base type of T to do the test.
6878 -- [constraint_error when N not in
6879 -- Source_Base_Type (Target_Type'First)
6880 -- ..
6881 -- Source_Base_Type(Target_Type'Last))]
6883 -- The conversions will always work and need no check
6885 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
6886 -- of converting from an enumeration value to an integer type, such as
6887 -- occurs for the case of generating a range check on Enum'Val(Exp)
6888 -- (which used to be handled by gigi). This is OK, since the conversion
6889 -- itself does not require a check.
6891 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
6893 -- Insert the explicit range check. Note that we suppress checks for
6894 -- this code, since we don't want a recursive range check popping up.
6896 if Is_Discrete_Type (Source_Base_Type)
6897 and then
6898 Is_Discrete_Type (Target_Base_Type)
6899 then
6900 Insert_Action (N,
6901 Make_Raise_Constraint_Error (Loc,
6902 Condition =>
6903 Make_Not_In (Loc,
6904 Left_Opnd => Duplicate_Subexpr (N),
6906 Right_Opnd =>
6907 Make_Range (Loc,
6908 Low_Bound =>
6909 Unchecked_Convert_To (Source_Base_Type,
6910 Make_Attribute_Reference (Loc,
6911 Prefix =>
6912 New_Occurrence_Of (Target_Type, Loc),
6913 Attribute_Name => Name_First)),
6915 High_Bound =>
6916 Unchecked_Convert_To (Source_Base_Type,
6917 Make_Attribute_Reference (Loc,
6918 Prefix =>
6919 New_Occurrence_Of (Target_Type, Loc),
6920 Attribute_Name => Name_Last)))),
6921 Reason => Reason),
6922 Suppress => All_Checks);
6924 -- For conversions involving at least one type that is not discrete,
6925 -- first convert to target type and then generate the range check.
6926 -- This avoids problems with values that are close to a bound of the
6927 -- target type that would fail a range check when done in a larger
6928 -- source type before converting but would pass if converted with
6929 -- rounding and then checked (such as in float-to-float conversions).
6931 else
6932 Convert_And_Check_Range;
6933 end if;
6935 -- Note that at this stage we now that the Target_Base_Type is not in
6936 -- the range of the Source_Base_Type (since even the Target_Type itself
6937 -- is not in this range). It could still be the case that Source_Type is
6938 -- in range of the target base type since we have not checked that case.
6940 -- If that is the case, we can freely convert the source to the target,
6941 -- and then test the target result against the bounds.
6943 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
6944 Convert_And_Check_Range;
6946 -- At this stage, we know that we have two scalar types, which are
6947 -- directly convertible, and where neither scalar type has a base
6948 -- range that is in the range of the other scalar type.
6950 -- The only way this can happen is with a signed and unsigned type.
6951 -- So test for these two cases:
6953 else
6954 -- Case of the source is unsigned and the target is signed
6956 if Is_Unsigned_Type (Source_Base_Type)
6957 and then not Is_Unsigned_Type (Target_Base_Type)
6958 then
6959 -- If the source is unsigned and the target is signed, then we
6960 -- know that the source is not shorter than the target (otherwise
6961 -- the source base type would be in the target base type range).
6963 -- In other words, the unsigned type is either the same size as
6964 -- the target, or it is larger. It cannot be smaller.
6966 pragma Assert
6967 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
6969 -- We only need to check the low bound if the low bound of the
6970 -- target type is non-negative. If the low bound of the target
6971 -- type is negative, then we know that we will fit fine.
6973 -- If the high bound of the target type is negative, then we
6974 -- know we have a constraint error, since we can't possibly
6975 -- have a negative source.
6977 -- With these two checks out of the way, we can do the check
6978 -- using the source type safely
6980 -- This is definitely the most annoying case.
6982 -- [constraint_error
6983 -- when (Target_Type'First >= 0
6984 -- and then
6985 -- N < Source_Base_Type (Target_Type'First))
6986 -- or else Target_Type'Last < 0
6987 -- or else N > Source_Base_Type (Target_Type'Last)];
6989 -- We turn off all checks since we know that the conversions
6990 -- will work fine, given the guards for negative values.
6992 Insert_Action (N,
6993 Make_Raise_Constraint_Error (Loc,
6994 Condition =>
6995 Make_Or_Else (Loc,
6996 Make_Or_Else (Loc,
6997 Left_Opnd =>
6998 Make_And_Then (Loc,
6999 Left_Opnd => Make_Op_Ge (Loc,
7000 Left_Opnd =>
7001 Make_Attribute_Reference (Loc,
7002 Prefix =>
7003 New_Occurrence_Of (Target_Type, Loc),
7004 Attribute_Name => Name_First),
7005 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7007 Right_Opnd =>
7008 Make_Op_Lt (Loc,
7009 Left_Opnd => Duplicate_Subexpr (N),
7010 Right_Opnd =>
7011 Convert_To (Source_Base_Type,
7012 Make_Attribute_Reference (Loc,
7013 Prefix =>
7014 New_Occurrence_Of (Target_Type, Loc),
7015 Attribute_Name => Name_First)))),
7017 Right_Opnd =>
7018 Make_Op_Lt (Loc,
7019 Left_Opnd =>
7020 Make_Attribute_Reference (Loc,
7021 Prefix => New_Occurrence_Of (Target_Type, Loc),
7022 Attribute_Name => Name_Last),
7023 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
7025 Right_Opnd =>
7026 Make_Op_Gt (Loc,
7027 Left_Opnd => Duplicate_Subexpr (N),
7028 Right_Opnd =>
7029 Convert_To (Source_Base_Type,
7030 Make_Attribute_Reference (Loc,
7031 Prefix => New_Occurrence_Of (Target_Type, Loc),
7032 Attribute_Name => Name_Last)))),
7034 Reason => Reason),
7035 Suppress => All_Checks);
7037 -- Only remaining possibility is that the source is signed and
7038 -- the target is unsigned.
7040 else
7041 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
7042 and then Is_Unsigned_Type (Target_Base_Type));
7044 -- If the source is signed and the target is unsigned, then we
7045 -- know that the target is not shorter than the source (otherwise
7046 -- the target base type would be in the source base type range).
7048 -- In other words, the unsigned type is either the same size as
7049 -- the target, or it is larger. It cannot be smaller.
7051 -- Clearly we have an error if the source value is negative since
7052 -- no unsigned type can have negative values. If the source type
7053 -- is non-negative, then the check can be done using the target
7054 -- type.
7056 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7058 -- [constraint_error
7059 -- when N < 0 or else Tnn not in Target_Type];
7061 -- We turn off all checks for the conversion of N to the target
7062 -- base type, since we generate the explicit check to ensure that
7063 -- the value is non-negative
7065 declare
7066 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7068 begin
7069 Insert_Actions (N, New_List (
7070 Make_Object_Declaration (Loc,
7071 Defining_Identifier => Tnn,
7072 Object_Definition =>
7073 New_Occurrence_Of (Target_Base_Type, Loc),
7074 Constant_Present => True,
7075 Expression =>
7076 Make_Unchecked_Type_Conversion (Loc,
7077 Subtype_Mark =>
7078 New_Occurrence_Of (Target_Base_Type, Loc),
7079 Expression => Duplicate_Subexpr (N))),
7081 Make_Raise_Constraint_Error (Loc,
7082 Condition =>
7083 Make_Or_Else (Loc,
7084 Left_Opnd =>
7085 Make_Op_Lt (Loc,
7086 Left_Opnd => Duplicate_Subexpr (N),
7087 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7089 Right_Opnd =>
7090 Make_Not_In (Loc,
7091 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7092 Right_Opnd =>
7093 New_Occurrence_Of (Target_Type, Loc))),
7095 Reason => Reason)),
7096 Suppress => All_Checks);
7098 -- Set the Etype explicitly, because Insert_Actions may have
7099 -- placed the declaration in the freeze list for an enclosing
7100 -- construct, and thus it is not analyzed yet.
7102 Set_Etype (Tnn, Target_Base_Type);
7103 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7104 end;
7105 end if;
7106 end if;
7107 end Generate_Range_Check;
7109 ------------------
7110 -- Get_Check_Id --
7111 ------------------
7113 function Get_Check_Id (N : Name_Id) return Check_Id is
7114 begin
7115 -- For standard check name, we can do a direct computation
7117 if N in First_Check_Name .. Last_Check_Name then
7118 return Check_Id (N - (First_Check_Name - 1));
7120 -- For non-standard names added by pragma Check_Name, search table
7122 else
7123 for J in All_Checks + 1 .. Check_Names.Last loop
7124 if Check_Names.Table (J) = N then
7125 return J;
7126 end if;
7127 end loop;
7128 end if;
7130 -- No matching name found
7132 return No_Check_Id;
7133 end Get_Check_Id;
7135 ---------------------
7136 -- Get_Discriminal --
7137 ---------------------
7139 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
7140 Loc : constant Source_Ptr := Sloc (E);
7141 D : Entity_Id;
7142 Sc : Entity_Id;
7144 begin
7145 -- The bound can be a bona fide parameter of a protected operation,
7146 -- rather than a prival encoded as an in-parameter.
7148 if No (Discriminal_Link (Entity (Bound))) then
7149 return Bound;
7150 end if;
7152 -- Climb the scope stack looking for an enclosing protected type. If
7153 -- we run out of scopes, return the bound itself.
7155 Sc := Scope (E);
7156 while Present (Sc) loop
7157 if Sc = Standard_Standard then
7158 return Bound;
7159 elsif Ekind (Sc) = E_Protected_Type then
7160 exit;
7161 end if;
7163 Sc := Scope (Sc);
7164 end loop;
7166 D := First_Discriminant (Sc);
7167 while Present (D) loop
7168 if Chars (D) = Chars (Bound) then
7169 return New_Occurrence_Of (Discriminal (D), Loc);
7170 end if;
7172 Next_Discriminant (D);
7173 end loop;
7175 return Bound;
7176 end Get_Discriminal;
7178 ----------------------
7179 -- Get_Range_Checks --
7180 ----------------------
7182 function Get_Range_Checks
7183 (Ck_Node : Node_Id;
7184 Target_Typ : Entity_Id;
7185 Source_Typ : Entity_Id := Empty;
7186 Warn_Node : Node_Id := Empty) return Check_Result
7188 begin
7189 return
7190 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
7191 end Get_Range_Checks;
7193 ------------------
7194 -- Guard_Access --
7195 ------------------
7197 function Guard_Access
7198 (Cond : Node_Id;
7199 Loc : Source_Ptr;
7200 Ck_Node : Node_Id) return Node_Id
7202 begin
7203 if Nkind (Cond) = N_Or_Else then
7204 Set_Paren_Count (Cond, 1);
7205 end if;
7207 if Nkind (Ck_Node) = N_Allocator then
7208 return Cond;
7210 else
7211 return
7212 Make_And_Then (Loc,
7213 Left_Opnd =>
7214 Make_Op_Ne (Loc,
7215 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
7216 Right_Opnd => Make_Null (Loc)),
7217 Right_Opnd => Cond);
7218 end if;
7219 end Guard_Access;
7221 -----------------------------
7222 -- Index_Checks_Suppressed --
7223 -----------------------------
7225 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
7226 begin
7227 if Present (E) and then Checks_May_Be_Suppressed (E) then
7228 return Is_Check_Suppressed (E, Index_Check);
7229 else
7230 return Scope_Suppress.Suppress (Index_Check);
7231 end if;
7232 end Index_Checks_Suppressed;
7234 ----------------
7235 -- Initialize --
7236 ----------------
7238 procedure Initialize is
7239 begin
7240 for J in Determine_Range_Cache_N'Range loop
7241 Determine_Range_Cache_N (J) := Empty;
7242 end loop;
7244 Check_Names.Init;
7246 for J in Int range 1 .. All_Checks loop
7247 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
7248 end loop;
7249 end Initialize;
7251 -------------------------
7252 -- Insert_Range_Checks --
7253 -------------------------
7255 procedure Insert_Range_Checks
7256 (Checks : Check_Result;
7257 Node : Node_Id;
7258 Suppress_Typ : Entity_Id;
7259 Static_Sloc : Source_Ptr := No_Location;
7260 Flag_Node : Node_Id := Empty;
7261 Do_Before : Boolean := False)
7263 Checks_On : constant Boolean :=
7264 not Index_Checks_Suppressed (Suppress_Typ)
7265 or else
7266 not Range_Checks_Suppressed (Suppress_Typ);
7268 Check_Node : Node_Id;
7269 Internal_Flag_Node : Node_Id := Flag_Node;
7270 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
7272 begin
7273 -- For now we just return if Checks_On is false, however this should be
7274 -- enhanced to check for an always True value in the condition and to
7275 -- generate a compilation warning???
7277 if not Expander_Active or not Checks_On then
7278 return;
7279 end if;
7281 if Static_Sloc = No_Location then
7282 Internal_Static_Sloc := Sloc (Node);
7283 end if;
7285 if No (Flag_Node) then
7286 Internal_Flag_Node := Node;
7287 end if;
7289 for J in 1 .. 2 loop
7290 exit when No (Checks (J));
7292 if Nkind (Checks (J)) = N_Raise_Constraint_Error
7293 and then Present (Condition (Checks (J)))
7294 then
7295 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
7296 Check_Node := Checks (J);
7297 Mark_Rewrite_Insertion (Check_Node);
7299 if Do_Before then
7300 Insert_Before_And_Analyze (Node, Check_Node);
7301 else
7302 Insert_After_And_Analyze (Node, Check_Node);
7303 end if;
7305 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
7306 end if;
7308 else
7309 Check_Node :=
7310 Make_Raise_Constraint_Error (Internal_Static_Sloc,
7311 Reason => CE_Range_Check_Failed);
7312 Mark_Rewrite_Insertion (Check_Node);
7314 if Do_Before then
7315 Insert_Before_And_Analyze (Node, Check_Node);
7316 else
7317 Insert_After_And_Analyze (Node, Check_Node);
7318 end if;
7319 end if;
7320 end loop;
7321 end Insert_Range_Checks;
7323 ------------------------
7324 -- Insert_Valid_Check --
7325 ------------------------
7327 procedure Insert_Valid_Check
7328 (Expr : Node_Id;
7329 Related_Id : Entity_Id := Empty;
7330 Is_Low_Bound : Boolean := False;
7331 Is_High_Bound : Boolean := False)
7333 Loc : constant Source_Ptr := Sloc (Expr);
7334 Typ : constant Entity_Id := Etype (Expr);
7335 Exp : Node_Id;
7337 begin
7338 -- Do not insert if checks off, or if not checking validity or if
7339 -- expression is known to be valid.
7341 if not Validity_Checks_On
7342 or else Range_Or_Validity_Checks_Suppressed (Expr)
7343 or else Expr_Known_Valid (Expr)
7344 then
7345 return;
7347 -- Do not insert checks within a predicate function. This will arise
7348 -- if the current unit and the predicate function are being compiled
7349 -- with validity checks enabled.
7351 elsif Present (Predicate_Function (Typ))
7352 and then Current_Scope = Predicate_Function (Typ)
7353 then
7354 return;
7356 -- If the expression is a packed component of a modular type of the
7357 -- right size, the data is always valid.
7359 elsif Nkind (Expr) = N_Selected_Component
7360 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
7361 and then Is_Modular_Integer_Type (Typ)
7362 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
7363 then
7364 return;
7366 -- Do not generate a validity check when inside a generic unit as this
7367 -- is an expansion activity.
7369 elsif Inside_A_Generic then
7370 return;
7371 end if;
7373 -- If we have a checked conversion, then validity check applies to
7374 -- the expression inside the conversion, not the result, since if
7375 -- the expression inside is valid, then so is the conversion result.
7377 Exp := Expr;
7378 while Nkind (Exp) = N_Type_Conversion loop
7379 Exp := Expression (Exp);
7380 end loop;
7382 -- Do not generate a check for a variable which already validates the
7383 -- value of an assignable object.
7385 if Is_Validation_Variable_Reference (Exp) then
7386 return;
7387 end if;
7389 declare
7390 CE : Node_Id;
7391 PV : Node_Id;
7392 Var_Id : Entity_Id;
7394 begin
7395 -- If the expression denotes an assignable object, capture its value
7396 -- in a variable and replace the original expression by the variable.
7397 -- This approach has several effects:
7399 -- 1) The evaluation of the object results in only one read in the
7400 -- case where the object is atomic or volatile.
7402 -- Var ... := Object; -- read
7404 -- 2) The captured value is the one verified by attribute 'Valid.
7405 -- As a result the object is not evaluated again, which would
7406 -- result in an unwanted read in the case where the object is
7407 -- atomic or volatile.
7409 -- if not Var'Valid then -- OK, no read of Object
7411 -- if not Object'Valid then -- Wrong, extra read of Object
7413 -- 3) The captured value replaces the original object reference.
7414 -- As a result the object is not evaluated again, in the same
7415 -- vein as 2).
7417 -- ... Var ... -- OK, no read of Object
7419 -- ... Object ... -- Wrong, extra read of Object
7421 -- 4) The use of a variable to capture the value of the object
7422 -- allows the propagation of any changes back to the original
7423 -- object.
7425 -- procedure Call (Val : in out ...);
7427 -- Var : ... := Object; -- read Object
7428 -- if not Var'Valid then -- validity check
7429 -- Call (Var); -- modify Var
7430 -- Object := Var; -- update Object
7432 if Is_Variable (Exp) then
7433 Var_Id := Make_Temporary (Loc, 'T', Exp);
7435 -- Because we could be dealing with a transient scope which would
7436 -- cause our object declaration to remain unanalyzed we must do
7437 -- some manual decoration.
7439 Set_Ekind (Var_Id, E_Variable);
7440 Set_Etype (Var_Id, Typ);
7442 Insert_Action (Exp,
7443 Make_Object_Declaration (Loc,
7444 Defining_Identifier => Var_Id,
7445 Object_Definition => New_Occurrence_Of (Typ, Loc),
7446 Expression => New_Copy_Tree (Exp)),
7447 Suppress => Validity_Check);
7449 Set_Validated_Object (Var_Id, New_Copy_Tree (Exp));
7450 Rewrite (Exp, New_Occurrence_Of (Var_Id, Loc));
7451 PV := New_Occurrence_Of (Var_Id, Loc);
7453 -- Copy the Do_Range_Check flag over to the new Exp, so it doesn't
7454 -- get lost. Floating point types are handled elsewhere.
7456 if not Is_Floating_Point_Type (Typ) then
7457 Set_Do_Range_Check (Exp, Do_Range_Check (Original_Node (Exp)));
7458 end if;
7460 -- Otherwise the expression does not denote a variable. Force its
7461 -- evaluation by capturing its value in a constant. Generate:
7463 -- Temp : constant ... := Exp;
7465 else
7466 Force_Evaluation
7467 (Exp => Exp,
7468 Related_Id => Related_Id,
7469 Is_Low_Bound => Is_Low_Bound,
7470 Is_High_Bound => Is_High_Bound);
7472 PV := New_Copy_Tree (Exp);
7473 end if;
7475 -- A rather specialized test. If PV is an analyzed expression which
7476 -- is an indexed component of a packed array that has not been
7477 -- properly expanded, turn off its Analyzed flag to make sure it
7478 -- gets properly reexpanded. If the prefix is an access value,
7479 -- the dereference will be added later.
7481 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7482 -- an analyze with the old parent pointer. This may point e.g. to
7483 -- a subprogram call, which deactivates this expansion.
7485 if Analyzed (PV)
7486 and then Nkind (PV) = N_Indexed_Component
7487 and then Is_Array_Type (Etype (Prefix (PV)))
7488 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
7489 then
7490 Set_Analyzed (PV, False);
7491 end if;
7493 -- Build the raise CE node to check for validity. We build a type
7494 -- qualification for the prefix, since it may not be of the form of
7495 -- a name, and we don't care in this context!
7497 CE :=
7498 Make_Raise_Constraint_Error (Loc,
7499 Condition =>
7500 Make_Op_Not (Loc,
7501 Right_Opnd =>
7502 Make_Attribute_Reference (Loc,
7503 Prefix => PV,
7504 Attribute_Name => Name_Valid)),
7505 Reason => CE_Invalid_Data);
7507 -- Insert the validity check. Note that we do this with validity
7508 -- checks turned off, to avoid recursion, we do not want validity
7509 -- checks on the validity checking code itself.
7511 Insert_Action (Expr, CE, Suppress => Validity_Check);
7513 -- If the expression is a reference to an element of a bit-packed
7514 -- array, then it is rewritten as a renaming declaration. If the
7515 -- expression is an actual in a call, it has not been expanded,
7516 -- waiting for the proper point at which to do it. The same happens
7517 -- with renamings, so that we have to force the expansion now. This
7518 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7519 -- and exp_ch6.adb.
7521 if Is_Entity_Name (Exp)
7522 and then Nkind (Parent (Entity (Exp))) =
7523 N_Object_Renaming_Declaration
7524 then
7525 declare
7526 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
7527 begin
7528 if Nkind (Old_Exp) = N_Indexed_Component
7529 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
7530 then
7531 Expand_Packed_Element_Reference (Old_Exp);
7532 end if;
7533 end;
7534 end if;
7535 end;
7536 end Insert_Valid_Check;
7538 -------------------------------------
7539 -- Is_Signed_Integer_Arithmetic_Op --
7540 -------------------------------------
7542 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
7543 begin
7544 case Nkind (N) is
7545 when N_Op_Abs
7546 | N_Op_Add
7547 | N_Op_Divide
7548 | N_Op_Expon
7549 | N_Op_Minus
7550 | N_Op_Mod
7551 | N_Op_Multiply
7552 | N_Op_Plus
7553 | N_Op_Rem
7554 | N_Op_Subtract
7556 return Is_Signed_Integer_Type (Etype (N));
7558 when N_Case_Expression
7559 | N_If_Expression
7561 return Is_Signed_Integer_Type (Etype (N));
7563 when others =>
7564 return False;
7565 end case;
7566 end Is_Signed_Integer_Arithmetic_Op;
7568 ----------------------------------
7569 -- Install_Null_Excluding_Check --
7570 ----------------------------------
7572 procedure Install_Null_Excluding_Check (N : Node_Id) is
7573 Loc : constant Source_Ptr := Sloc (Parent (N));
7574 Typ : constant Entity_Id := Etype (N);
7576 function Safe_To_Capture_In_Parameter_Value return Boolean;
7577 -- Determines if it is safe to capture Known_Non_Null status for an
7578 -- the entity referenced by node N. The caller ensures that N is indeed
7579 -- an entity name. It is safe to capture the non-null status for an IN
7580 -- parameter when the reference occurs within a declaration that is sure
7581 -- to be executed as part of the declarative region.
7583 procedure Mark_Non_Null;
7584 -- After installation of check, if the node in question is an entity
7585 -- name, then mark this entity as non-null if possible.
7587 function Safe_To_Capture_In_Parameter_Value return Boolean is
7588 E : constant Entity_Id := Entity (N);
7589 S : constant Entity_Id := Current_Scope;
7590 S_Par : Node_Id;
7592 begin
7593 if Ekind (E) /= E_In_Parameter then
7594 return False;
7595 end if;
7597 -- Two initial context checks. We must be inside a subprogram body
7598 -- with declarations and reference must not appear in nested scopes.
7600 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
7601 or else Scope (E) /= S
7602 then
7603 return False;
7604 end if;
7606 S_Par := Parent (Parent (S));
7608 if Nkind (S_Par) /= N_Subprogram_Body
7609 or else No (Declarations (S_Par))
7610 then
7611 return False;
7612 end if;
7614 declare
7615 N_Decl : Node_Id;
7616 P : Node_Id;
7618 begin
7619 -- Retrieve the declaration node of N (if any). Note that N
7620 -- may be a part of a complex initialization expression.
7622 P := Parent (N);
7623 N_Decl := Empty;
7624 while Present (P) loop
7626 -- If we have a short circuit form, and we are within the right
7627 -- hand expression, we return false, since the right hand side
7628 -- is not guaranteed to be elaborated.
7630 if Nkind (P) in N_Short_Circuit
7631 and then N = Right_Opnd (P)
7632 then
7633 return False;
7634 end if;
7636 -- Similarly, if we are in an if expression and not part of the
7637 -- condition, then we return False, since neither the THEN or
7638 -- ELSE dependent expressions will always be elaborated.
7640 if Nkind (P) = N_If_Expression
7641 and then N /= First (Expressions (P))
7642 then
7643 return False;
7644 end if;
7646 -- If within a case expression, and not part of the expression,
7647 -- then return False, since a particular dependent expression
7648 -- may not always be elaborated
7650 if Nkind (P) = N_Case_Expression
7651 and then N /= Expression (P)
7652 then
7653 return False;
7654 end if;
7656 -- While traversing the parent chain, if node N belongs to a
7657 -- statement, then it may never appear in a declarative region.
7659 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
7660 or else Nkind (P) = N_Procedure_Call_Statement
7661 then
7662 return False;
7663 end if;
7665 -- If we are at a declaration, record it and exit
7667 if Nkind (P) in N_Declaration
7668 and then Nkind (P) not in N_Subprogram_Specification
7669 then
7670 N_Decl := P;
7671 exit;
7672 end if;
7674 P := Parent (P);
7675 end loop;
7677 if No (N_Decl) then
7678 return False;
7679 end if;
7681 return List_Containing (N_Decl) = Declarations (S_Par);
7682 end;
7683 end Safe_To_Capture_In_Parameter_Value;
7685 -------------------
7686 -- Mark_Non_Null --
7687 -------------------
7689 procedure Mark_Non_Null is
7690 begin
7691 -- Only case of interest is if node N is an entity name
7693 if Is_Entity_Name (N) then
7695 -- For sure, we want to clear an indication that this is known to
7696 -- be null, since if we get past this check, it definitely is not.
7698 Set_Is_Known_Null (Entity (N), False);
7700 -- We can mark the entity as known to be non-null if either it is
7701 -- safe to capture the value, or in the case of an IN parameter,
7702 -- which is a constant, if the check we just installed is in the
7703 -- declarative region of the subprogram body. In this latter case,
7704 -- a check is decisive for the rest of the body if the expression
7705 -- is sure to be elaborated, since we know we have to elaborate
7706 -- all declarations before executing the body.
7708 -- Couldn't this always be part of Safe_To_Capture_Value ???
7710 if Safe_To_Capture_Value (N, Entity (N))
7711 or else Safe_To_Capture_In_Parameter_Value
7712 then
7713 Set_Is_Known_Non_Null (Entity (N));
7714 end if;
7715 end if;
7716 end Mark_Non_Null;
7718 -- Start of processing for Install_Null_Excluding_Check
7720 begin
7721 pragma Assert (Is_Access_Type (Typ));
7723 -- No check inside a generic, check will be emitted in instance
7725 if Inside_A_Generic then
7726 return;
7727 end if;
7729 -- No check needed if known to be non-null
7731 if Known_Non_Null (N) then
7732 return;
7733 end if;
7735 -- If known to be null, here is where we generate a compile time check
7737 if Known_Null (N) then
7739 -- Avoid generating warning message inside init procs. In SPARK mode
7740 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
7741 -- since it will be turned into an error in any case.
7743 if (not Inside_Init_Proc or else SPARK_Mode = On)
7745 -- Do not emit the warning within a conditional expression,
7746 -- where the expression might not be evaluated, and the warning
7747 -- appear as extraneous noise.
7749 and then not Within_Case_Or_If_Expression (N)
7750 then
7751 Apply_Compile_Time_Constraint_Error
7752 (N, "null value not allowed here??", CE_Access_Check_Failed);
7754 -- Remaining cases, where we silently insert the raise
7756 else
7757 Insert_Action (N,
7758 Make_Raise_Constraint_Error (Loc,
7759 Reason => CE_Access_Check_Failed));
7760 end if;
7762 Mark_Non_Null;
7763 return;
7764 end if;
7766 -- If entity is never assigned, for sure a warning is appropriate
7768 if Is_Entity_Name (N) then
7769 Check_Unset_Reference (N);
7770 end if;
7772 -- No check needed if checks are suppressed on the range. Note that we
7773 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7774 -- so, since the program is erroneous, but we don't like to casually
7775 -- propagate such conclusions from erroneosity).
7777 if Access_Checks_Suppressed (Typ) then
7778 return;
7779 end if;
7781 -- No check needed for access to concurrent record types generated by
7782 -- the expander. This is not just an optimization (though it does indeed
7783 -- remove junk checks). It also avoids generation of junk warnings.
7785 if Nkind (N) in N_Has_Chars
7786 and then Chars (N) = Name_uObject
7787 and then Is_Concurrent_Record_Type
7788 (Directly_Designated_Type (Etype (N)))
7789 then
7790 return;
7791 end if;
7793 -- No check needed in interface thunks since the runtime check is
7794 -- already performed at the caller side.
7796 if Is_Thunk (Current_Scope) then
7797 return;
7798 end if;
7800 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7801 -- the expander within exception handlers, since we know that the value
7802 -- can never be null.
7804 -- Is this really the right way to do this? Normally we generate such
7805 -- code in the expander with checks off, and that's how we suppress this
7806 -- kind of junk check ???
7808 if Nkind (N) = N_Function_Call
7809 and then Nkind (Name (N)) = N_Explicit_Dereference
7810 and then Nkind (Prefix (Name (N))) = N_Identifier
7811 and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
7812 then
7813 return;
7814 end if;
7816 -- Otherwise install access check
7818 Insert_Action (N,
7819 Make_Raise_Constraint_Error (Loc,
7820 Condition =>
7821 Make_Op_Eq (Loc,
7822 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
7823 Right_Opnd => Make_Null (Loc)),
7824 Reason => CE_Access_Check_Failed));
7826 Mark_Non_Null;
7827 end Install_Null_Excluding_Check;
7829 -----------------------------------------
7830 -- Install_Primitive_Elaboration_Check --
7831 -----------------------------------------
7833 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id) is
7834 function Within_Compilation_Unit_Instance
7835 (Subp_Id : Entity_Id) return Boolean;
7836 -- Determine whether subprogram Subp_Id appears within an instance which
7837 -- acts as a compilation unit.
7839 --------------------------------------
7840 -- Within_Compilation_Unit_Instance --
7841 --------------------------------------
7843 function Within_Compilation_Unit_Instance
7844 (Subp_Id : Entity_Id) return Boolean
7846 Pack : Entity_Id;
7848 begin
7849 -- Examine the scope chain looking for a compilation-unit-level
7850 -- instance.
7852 Pack := Scope (Subp_Id);
7853 while Present (Pack) and then Pack /= Standard_Standard loop
7854 if Ekind (Pack) = E_Package
7855 and then Is_Generic_Instance (Pack)
7856 and then Nkind (Parent (Unit_Declaration_Node (Pack))) =
7857 N_Compilation_Unit
7858 then
7859 return True;
7860 end if;
7862 Pack := Scope (Pack);
7863 end loop;
7865 return False;
7866 end Within_Compilation_Unit_Instance;
7868 -- Local declarations
7870 Context : constant Node_Id := Parent (Subp_Body);
7871 Loc : constant Source_Ptr := Sloc (Subp_Body);
7872 Subp_Id : constant Entity_Id := Unique_Defining_Entity (Subp_Body);
7873 Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
7875 Decls : List_Id;
7876 Flag_Id : Entity_Id;
7877 Set_Ins : Node_Id;
7878 Set_Stmt : Node_Id;
7879 Tag_Typ : Entity_Id;
7881 -- Start of processing for Install_Primitive_Elaboration_Check
7883 begin
7884 -- Do not generate an elaboration check in compilation modes where
7885 -- expansion is not desirable.
7887 if ASIS_Mode or GNATprove_Mode then
7888 return;
7890 -- Do not generate an elaboration check if all checks have been
7891 -- suppressed.
7893 elsif Suppress_Checks then
7894 return;
7896 -- Do not generate an elaboration check if the related subprogram is
7897 -- not subjected to accessibility checks.
7899 elsif Elaboration_Checks_Suppressed (Subp_Id) then
7900 return;
7902 -- Do not generate an elaboration check if such code is not desirable
7904 elsif Restriction_Active (No_Elaboration_Code) then
7905 return;
7907 -- Do not consider subprograms which act as compilation units, because
7908 -- they cannot be the target of a dispatching call.
7910 elsif Nkind (Context) = N_Compilation_Unit then
7911 return;
7913 -- Do not consider anything other than nonabstract library-level source
7914 -- primitives.
7916 elsif not
7917 (Comes_From_Source (Subp_Id)
7918 and then Is_Library_Level_Entity (Subp_Id)
7919 and then Is_Primitive (Subp_Id)
7920 and then not Is_Abstract_Subprogram (Subp_Id))
7921 then
7922 return;
7924 -- Do not consider inlined primitives, because once the body is inlined
7925 -- the reference to the elaboration flag will be out of place and will
7926 -- result in an undefined symbol.
7928 elsif Is_Inlined (Subp_Id) or else Has_Pragma_Inline (Subp_Id) then
7929 return;
7931 -- Do not generate a duplicate elaboration check. This happens only in
7932 -- the case of primitives completed by an expression function, as the
7933 -- corresponding body is apparently analyzed and expanded twice.
7935 elsif Analyzed (Subp_Body) then
7936 return;
7938 -- Do not consider primitives which occur within an instance that acts
7939 -- as a compilation unit. Such an instance defines its spec and body out
7940 -- of order (body is first) within the tree, which causes the reference
7941 -- to the elaboration flag to appear as an undefined symbol.
7943 elsif Within_Compilation_Unit_Instance (Subp_Id) then
7944 return;
7945 end if;
7947 Tag_Typ := Find_Dispatching_Type (Subp_Id);
7949 -- Only tagged primitives may be the target of a dispatching call
7951 if No (Tag_Typ) then
7952 return;
7954 -- Do not consider finalization-related primitives, because they may
7955 -- need to be called while elaboration is taking place.
7957 elsif Is_Controlled (Tag_Typ)
7958 and then Nam_In (Chars (Subp_Id), Name_Adjust,
7959 Name_Finalize,
7960 Name_Initialize)
7961 then
7962 return;
7963 end if;
7965 -- Create the declaration of the elaboration flag. The name carries a
7966 -- unique counter in case of name overloading.
7968 Flag_Id :=
7969 Make_Defining_Identifier (Loc,
7970 Chars => New_External_Name (Chars (Subp_Id), 'E', -1));
7971 Set_Is_Frozen (Flag_Id);
7973 -- Insert the declaration of the elaboration flag in front of the
7974 -- primitive spec and analyze it in the proper context.
7976 Push_Scope (Scope (Subp_Id));
7978 -- Generate:
7979 -- E : Boolean := False;
7981 Insert_Action (Subp_Decl,
7982 Make_Object_Declaration (Loc,
7983 Defining_Identifier => Flag_Id,
7984 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
7985 Expression => New_Occurrence_Of (Standard_False, Loc)));
7986 Pop_Scope;
7988 -- Prevent the compiler from optimizing the elaboration check by killing
7989 -- the current value of the flag and the associated assignment.
7991 Set_Current_Value (Flag_Id, Empty);
7992 Set_Last_Assignment (Flag_Id, Empty);
7994 -- Add a check at the top of the body declarations to ensure that the
7995 -- elaboration flag has been set.
7997 Decls := Declarations (Subp_Body);
7999 if No (Decls) then
8000 Decls := New_List;
8001 Set_Declarations (Subp_Body, Decls);
8002 end if;
8004 -- Generate:
8005 -- if not F then
8006 -- raise Program_Error with "access before elaboration";
8007 -- end if;
8009 Prepend_To (Decls,
8010 Make_Raise_Program_Error (Loc,
8011 Condition =>
8012 Make_Op_Not (Loc,
8013 Right_Opnd => New_Occurrence_Of (Flag_Id, Loc)),
8014 Reason => PE_Access_Before_Elaboration));
8016 Analyze (First (Decls));
8018 -- Set the elaboration flag once the body has been elaborated. Insert
8019 -- the statement after the subprogram stub when the primitive body is
8020 -- a subunit.
8022 if Nkind (Context) = N_Subunit then
8023 Set_Ins := Corresponding_Stub (Context);
8024 else
8025 Set_Ins := Subp_Body;
8026 end if;
8028 -- Generate:
8029 -- E := True;
8031 Set_Stmt :=
8032 Make_Assignment_Statement (Loc,
8033 Name => New_Occurrence_Of (Flag_Id, Loc),
8034 Expression => New_Occurrence_Of (Standard_True, Loc));
8036 -- Mark the assignment statement as elaboration code. This allows the
8037 -- early call region mechanism (see Sem_Elab) to properly ignore such
8038 -- assignments even though they are non-preelaborable code.
8040 Set_Is_Elaboration_Code (Set_Stmt);
8042 Insert_After_And_Analyze (Set_Ins, Set_Stmt);
8043 end Install_Primitive_Elaboration_Check;
8045 --------------------------
8046 -- Install_Static_Check --
8047 --------------------------
8049 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
8050 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
8051 Typ : constant Entity_Id := Etype (R_Cno);
8053 begin
8054 Rewrite (R_Cno,
8055 Make_Raise_Constraint_Error (Loc,
8056 Reason => CE_Range_Check_Failed));
8057 Set_Analyzed (R_Cno);
8058 Set_Etype (R_Cno, Typ);
8059 Set_Raises_Constraint_Error (R_Cno);
8060 Set_Is_Static_Expression (R_Cno, Stat);
8062 -- Now deal with possible local raise handling
8064 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
8065 end Install_Static_Check;
8067 -------------------------
8068 -- Is_Check_Suppressed --
8069 -------------------------
8071 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
8072 Ptr : Suppress_Stack_Entry_Ptr;
8074 begin
8075 -- First search the local entity suppress stack. We search this from the
8076 -- top of the stack down so that we get the innermost entry that applies
8077 -- to this case if there are nested entries.
8079 Ptr := Local_Suppress_Stack_Top;
8080 while Ptr /= null loop
8081 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8082 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8083 then
8084 return Ptr.Suppress;
8085 end if;
8087 Ptr := Ptr.Prev;
8088 end loop;
8090 -- Now search the global entity suppress table for a matching entry.
8091 -- We also search this from the top down so that if there are multiple
8092 -- pragmas for the same entity, the last one applies (not clear what
8093 -- or whether the RM specifies this handling, but it seems reasonable).
8095 Ptr := Global_Suppress_Stack_Top;
8096 while Ptr /= null loop
8097 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8098 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8099 then
8100 return Ptr.Suppress;
8101 end if;
8103 Ptr := Ptr.Prev;
8104 end loop;
8106 -- If we did not find a matching entry, then use the normal scope
8107 -- suppress value after all (actually this will be the global setting
8108 -- since it clearly was not overridden at any point). For a predefined
8109 -- check, we test the specific flag. For a user defined check, we check
8110 -- the All_Checks flag. The Overflow flag requires special handling to
8111 -- deal with the General vs Assertion case.
8113 if C = Overflow_Check then
8114 return Overflow_Checks_Suppressed (Empty);
8116 elsif C in Predefined_Check_Id then
8117 return Scope_Suppress.Suppress (C);
8119 else
8120 return Scope_Suppress.Suppress (All_Checks);
8121 end if;
8122 end Is_Check_Suppressed;
8124 ---------------------
8125 -- Kill_All_Checks --
8126 ---------------------
8128 procedure Kill_All_Checks is
8129 begin
8130 if Debug_Flag_CC then
8131 w ("Kill_All_Checks");
8132 end if;
8134 -- We reset the number of saved checks to zero, and also modify all
8135 -- stack entries for statement ranges to indicate that the number of
8136 -- checks at each level is now zero.
8138 Num_Saved_Checks := 0;
8140 -- Note: the Int'Min here avoids any possibility of J being out of
8141 -- range when called from e.g. Conditional_Statements_Begin.
8143 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
8144 Saved_Checks_Stack (J) := 0;
8145 end loop;
8146 end Kill_All_Checks;
8148 -----------------
8149 -- Kill_Checks --
8150 -----------------
8152 procedure Kill_Checks (V : Entity_Id) is
8153 begin
8154 if Debug_Flag_CC then
8155 w ("Kill_Checks for entity", Int (V));
8156 end if;
8158 for J in 1 .. Num_Saved_Checks loop
8159 if Saved_Checks (J).Entity = V then
8160 if Debug_Flag_CC then
8161 w (" Checks killed for saved check ", J);
8162 end if;
8164 Saved_Checks (J).Killed := True;
8165 end if;
8166 end loop;
8167 end Kill_Checks;
8169 ------------------------------
8170 -- Length_Checks_Suppressed --
8171 ------------------------------
8173 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
8174 begin
8175 if Present (E) and then Checks_May_Be_Suppressed (E) then
8176 return Is_Check_Suppressed (E, Length_Check);
8177 else
8178 return Scope_Suppress.Suppress (Length_Check);
8179 end if;
8180 end Length_Checks_Suppressed;
8182 -----------------------
8183 -- Make_Bignum_Block --
8184 -----------------------
8186 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
8187 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
8188 begin
8189 return
8190 Make_Block_Statement (Loc,
8191 Declarations =>
8192 New_List (Build_SS_Mark_Call (Loc, M)),
8193 Handled_Statement_Sequence =>
8194 Make_Handled_Sequence_Of_Statements (Loc,
8195 Statements => New_List (Build_SS_Release_Call (Loc, M))));
8196 end Make_Bignum_Block;
8198 ----------------------------------
8199 -- Minimize_Eliminate_Overflows --
8200 ----------------------------------
8202 -- This is a recursive routine that is called at the top of an expression
8203 -- tree to properly process overflow checking for a whole subtree by making
8204 -- recursive calls to process operands. This processing may involve the use
8205 -- of bignum or long long integer arithmetic, which will change the types
8206 -- of operands and results. That's why we can't do this bottom up (since
8207 -- it would interfere with semantic analysis).
8209 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8210 -- the operator expansion routines, as well as the expansion routines for
8211 -- if/case expression, do nothing (for the moment) except call the routine
8212 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8213 -- routine does nothing for non top-level nodes, so at the point where the
8214 -- call is made for the top level node, the entire expression subtree has
8215 -- not been expanded, or processed for overflow. All that has to happen as
8216 -- a result of the top level call to this routine.
8218 -- As noted above, the overflow processing works by making recursive calls
8219 -- for the operands, and figuring out what to do, based on the processing
8220 -- of these operands (e.g. if a bignum operand appears, the parent op has
8221 -- to be done in bignum mode), and the determined ranges of the operands.
8223 -- After possible rewriting of a constituent subexpression node, a call is
8224 -- made to either reexpand the node (if nothing has changed) or reanalyze
8225 -- the node (if it has been modified by the overflow check processing). The
8226 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8227 -- a recursive call into the whole overflow apparatus, an important rule
8228 -- for this call is that the overflow handling mode must be temporarily set
8229 -- to STRICT.
8231 procedure Minimize_Eliminate_Overflows
8232 (N : Node_Id;
8233 Lo : out Uint;
8234 Hi : out Uint;
8235 Top_Level : Boolean)
8237 Rtyp : constant Entity_Id := Etype (N);
8238 pragma Assert (Is_Signed_Integer_Type (Rtyp));
8239 -- Result type, must be a signed integer type
8241 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
8242 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
8244 Loc : constant Source_Ptr := Sloc (N);
8246 Rlo, Rhi : Uint;
8247 -- Ranges of values for right operand (operator case)
8249 Llo : Uint := No_Uint; -- initialize to prevent warning
8250 Lhi : Uint := No_Uint; -- initialize to prevent warning
8251 -- Ranges of values for left operand (operator case)
8253 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
8254 -- Operands and results are of this type when we convert
8256 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
8257 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
8258 -- Bounds of Long_Long_Integer
8260 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
8261 -- Indicates binary operator case
8263 OK : Boolean;
8264 -- Used in call to Determine_Range
8266 Bignum_Operands : Boolean;
8267 -- Set True if one or more operands is already of type Bignum, meaning
8268 -- that for sure (regardless of Top_Level setting) we are committed to
8269 -- doing the operation in Bignum mode (or in the case of a case or if
8270 -- expression, converting all the dependent expressions to Bignum).
8272 Long_Long_Integer_Operands : Boolean;
8273 -- Set True if one or more operands is already of type Long_Long_Integer
8274 -- which means that if the result is known to be in the result type
8275 -- range, then we must convert such operands back to the result type.
8277 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
8278 -- This is called when we have modified the node and we therefore need
8279 -- to reanalyze it. It is important that we reset the mode to STRICT for
8280 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
8281 -- we would reenter this routine recursively which would not be good.
8282 -- The argument Suppress is set True if we also want to suppress
8283 -- overflow checking for the reexpansion (this is set when we know
8284 -- overflow is not possible). Typ is the type for the reanalysis.
8286 procedure Reexpand (Suppress : Boolean := False);
8287 -- This is like Reanalyze, but does not do the Analyze step, it only
8288 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8289 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8290 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8291 -- Note that skipping reanalysis is not just an optimization, testing
8292 -- has showed up several complex cases in which reanalyzing an already
8293 -- analyzed node causes incorrect behavior.
8295 function In_Result_Range return Boolean;
8296 -- Returns True iff Lo .. Hi are within range of the result type
8298 procedure Max (A : in out Uint; B : Uint);
8299 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
8301 procedure Min (A : in out Uint; B : Uint);
8302 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
8304 ---------------------
8305 -- In_Result_Range --
8306 ---------------------
8308 function In_Result_Range return Boolean is
8309 begin
8310 if Lo = No_Uint or else Hi = No_Uint then
8311 return False;
8313 elsif Is_OK_Static_Subtype (Etype (N)) then
8314 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
8315 and then
8316 Hi <= Expr_Value (Type_High_Bound (Rtyp));
8318 else
8319 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
8320 and then
8321 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
8322 end if;
8323 end In_Result_Range;
8325 ---------
8326 -- Max --
8327 ---------
8329 procedure Max (A : in out Uint; B : Uint) is
8330 begin
8331 if A = No_Uint or else B > A then
8332 A := B;
8333 end if;
8334 end Max;
8336 ---------
8337 -- Min --
8338 ---------
8340 procedure Min (A : in out Uint; B : Uint) is
8341 begin
8342 if A = No_Uint or else B < A then
8343 A := B;
8344 end if;
8345 end Min;
8347 ---------------
8348 -- Reanalyze --
8349 ---------------
8351 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
8352 Svg : constant Overflow_Mode_Type :=
8353 Scope_Suppress.Overflow_Mode_General;
8354 Sva : constant Overflow_Mode_Type :=
8355 Scope_Suppress.Overflow_Mode_Assertions;
8356 Svo : constant Boolean :=
8357 Scope_Suppress.Suppress (Overflow_Check);
8359 begin
8360 Scope_Suppress.Overflow_Mode_General := Strict;
8361 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8363 if Suppress then
8364 Scope_Suppress.Suppress (Overflow_Check) := True;
8365 end if;
8367 Analyze_And_Resolve (N, Typ);
8369 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8370 Scope_Suppress.Overflow_Mode_General := Svg;
8371 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8372 end Reanalyze;
8374 --------------
8375 -- Reexpand --
8376 --------------
8378 procedure Reexpand (Suppress : Boolean := False) is
8379 Svg : constant Overflow_Mode_Type :=
8380 Scope_Suppress.Overflow_Mode_General;
8381 Sva : constant Overflow_Mode_Type :=
8382 Scope_Suppress.Overflow_Mode_Assertions;
8383 Svo : constant Boolean :=
8384 Scope_Suppress.Suppress (Overflow_Check);
8386 begin
8387 Scope_Suppress.Overflow_Mode_General := Strict;
8388 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8389 Set_Analyzed (N, False);
8391 if Suppress then
8392 Scope_Suppress.Suppress (Overflow_Check) := True;
8393 end if;
8395 Expand (N);
8397 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8398 Scope_Suppress.Overflow_Mode_General := Svg;
8399 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8400 end Reexpand;
8402 -- Start of processing for Minimize_Eliminate_Overflows
8404 begin
8405 -- Default initialize Lo and Hi since these are not guaranteed to be
8406 -- set otherwise.
8408 Lo := No_Uint;
8409 Hi := No_Uint;
8411 -- Case where we do not have a signed integer arithmetic operation
8413 if not Is_Signed_Integer_Arithmetic_Op (N) then
8415 -- Use the normal Determine_Range routine to get the range. We
8416 -- don't require operands to be valid, invalid values may result in
8417 -- rubbish results where the result has not been properly checked for
8418 -- overflow, that's fine.
8420 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
8422 -- If Determine_Range did not work (can this in fact happen? Not
8423 -- clear but might as well protect), use type bounds.
8425 if not OK then
8426 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
8427 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
8428 end if;
8430 -- If we don't have a binary operator, all we have to do is to set
8431 -- the Hi/Lo range, so we are done.
8433 return;
8435 -- Processing for if expression
8437 elsif Nkind (N) = N_If_Expression then
8438 declare
8439 Then_DE : constant Node_Id := Next (First (Expressions (N)));
8440 Else_DE : constant Node_Id := Next (Then_DE);
8442 begin
8443 Bignum_Operands := False;
8445 Minimize_Eliminate_Overflows
8446 (Then_DE, Lo, Hi, Top_Level => False);
8448 if Lo = No_Uint then
8449 Bignum_Operands := True;
8450 end if;
8452 Minimize_Eliminate_Overflows
8453 (Else_DE, Rlo, Rhi, Top_Level => False);
8455 if Rlo = No_Uint then
8456 Bignum_Operands := True;
8457 else
8458 Long_Long_Integer_Operands :=
8459 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
8461 Min (Lo, Rlo);
8462 Max (Hi, Rhi);
8463 end if;
8465 -- If at least one of our operands is now Bignum, we must rebuild
8466 -- the if expression to use Bignum operands. We will analyze the
8467 -- rebuilt if expression with overflow checks off, since once we
8468 -- are in bignum mode, we are all done with overflow checks.
8470 if Bignum_Operands then
8471 Rewrite (N,
8472 Make_If_Expression (Loc,
8473 Expressions => New_List (
8474 Remove_Head (Expressions (N)),
8475 Convert_To_Bignum (Then_DE),
8476 Convert_To_Bignum (Else_DE)),
8477 Is_Elsif => Is_Elsif (N)));
8479 Reanalyze (RTE (RE_Bignum), Suppress => True);
8481 -- If we have no Long_Long_Integer operands, then we are in result
8482 -- range, since it means that none of our operands felt the need
8483 -- to worry about overflow (otherwise it would have already been
8484 -- converted to long long integer or bignum). We reexpand to
8485 -- complete the expansion of the if expression (but we do not
8486 -- need to reanalyze).
8488 elsif not Long_Long_Integer_Operands then
8489 Set_Do_Overflow_Check (N, False);
8490 Reexpand;
8492 -- Otherwise convert us to long long integer mode. Note that we
8493 -- don't need any further overflow checking at this level.
8495 else
8496 Convert_To_And_Rewrite (LLIB, Then_DE);
8497 Convert_To_And_Rewrite (LLIB, Else_DE);
8498 Set_Etype (N, LLIB);
8500 -- Now reanalyze with overflow checks off
8502 Set_Do_Overflow_Check (N, False);
8503 Reanalyze (LLIB, Suppress => True);
8504 end if;
8505 end;
8507 return;
8509 -- Here for case expression
8511 elsif Nkind (N) = N_Case_Expression then
8512 Bignum_Operands := False;
8513 Long_Long_Integer_Operands := False;
8515 declare
8516 Alt : Node_Id;
8518 begin
8519 -- Loop through expressions applying recursive call
8521 Alt := First (Alternatives (N));
8522 while Present (Alt) loop
8523 declare
8524 Aexp : constant Node_Id := Expression (Alt);
8526 begin
8527 Minimize_Eliminate_Overflows
8528 (Aexp, Lo, Hi, Top_Level => False);
8530 if Lo = No_Uint then
8531 Bignum_Operands := True;
8532 elsif Etype (Aexp) = LLIB then
8533 Long_Long_Integer_Operands := True;
8534 end if;
8535 end;
8537 Next (Alt);
8538 end loop;
8540 -- If we have no bignum or long long integer operands, it means
8541 -- that none of our dependent expressions could raise overflow.
8542 -- In this case, we simply return with no changes except for
8543 -- resetting the overflow flag, since we are done with overflow
8544 -- checks for this node. We will reexpand to get the needed
8545 -- expansion for the case expression, but we do not need to
8546 -- reanalyze, since nothing has changed.
8548 if not (Bignum_Operands or Long_Long_Integer_Operands) then
8549 Set_Do_Overflow_Check (N, False);
8550 Reexpand (Suppress => True);
8552 -- Otherwise we are going to rebuild the case expression using
8553 -- either bignum or long long integer operands throughout.
8555 else
8556 declare
8557 Rtype : Entity_Id;
8558 pragma Warnings (Off, Rtype);
8559 New_Alts : List_Id;
8560 New_Exp : Node_Id;
8562 begin
8563 New_Alts := New_List;
8564 Alt := First (Alternatives (N));
8565 while Present (Alt) loop
8566 if Bignum_Operands then
8567 New_Exp := Convert_To_Bignum (Expression (Alt));
8568 Rtype := RTE (RE_Bignum);
8569 else
8570 New_Exp := Convert_To (LLIB, Expression (Alt));
8571 Rtype := LLIB;
8572 end if;
8574 Append_To (New_Alts,
8575 Make_Case_Expression_Alternative (Sloc (Alt),
8576 Actions => No_List,
8577 Discrete_Choices => Discrete_Choices (Alt),
8578 Expression => New_Exp));
8580 Next (Alt);
8581 end loop;
8583 Rewrite (N,
8584 Make_Case_Expression (Loc,
8585 Expression => Expression (N),
8586 Alternatives => New_Alts));
8588 Reanalyze (Rtype, Suppress => True);
8589 end;
8590 end if;
8591 end;
8593 return;
8594 end if;
8596 -- If we have an arithmetic operator we make recursive calls on the
8597 -- operands to get the ranges (and to properly process the subtree
8598 -- that lies below us).
8600 Minimize_Eliminate_Overflows
8601 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
8603 if Binary then
8604 Minimize_Eliminate_Overflows
8605 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
8606 end if;
8608 -- Record if we have Long_Long_Integer operands
8610 Long_Long_Integer_Operands :=
8611 Etype (Right_Opnd (N)) = LLIB
8612 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
8614 -- If either operand is a bignum, then result will be a bignum and we
8615 -- don't need to do any range analysis. As previously discussed we could
8616 -- do range analysis in such cases, but it could mean working with giant
8617 -- numbers at compile time for very little gain (the number of cases
8618 -- in which we could slip back from bignum mode is small).
8620 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
8621 Lo := No_Uint;
8622 Hi := No_Uint;
8623 Bignum_Operands := True;
8625 -- Otherwise compute result range
8627 else
8628 Bignum_Operands := False;
8630 case Nkind (N) is
8632 -- Absolute value
8634 when N_Op_Abs =>
8635 Lo := Uint_0;
8636 Hi := UI_Max (abs Rlo, abs Rhi);
8638 -- Addition
8640 when N_Op_Add =>
8641 Lo := Llo + Rlo;
8642 Hi := Lhi + Rhi;
8644 -- Division
8646 when N_Op_Divide =>
8648 -- If the right operand can only be zero, set 0..0
8650 if Rlo = 0 and then Rhi = 0 then
8651 Lo := Uint_0;
8652 Hi := Uint_0;
8654 -- Possible bounds of division must come from dividing end
8655 -- values of the input ranges (four possibilities), provided
8656 -- zero is not included in the possible values of the right
8657 -- operand.
8659 -- Otherwise, we just consider two intervals of values for
8660 -- the right operand: the interval of negative values (up to
8661 -- -1) and the interval of positive values (starting at 1).
8662 -- Since division by 1 is the identity, and division by -1
8663 -- is negation, we get all possible bounds of division in that
8664 -- case by considering:
8665 -- - all values from the division of end values of input
8666 -- ranges;
8667 -- - the end values of the left operand;
8668 -- - the negation of the end values of the left operand.
8670 else
8671 declare
8672 Mrk : constant Uintp.Save_Mark := Mark;
8673 -- Mark so we can release the RR and Ev values
8675 Ev1 : Uint;
8676 Ev2 : Uint;
8677 Ev3 : Uint;
8678 Ev4 : Uint;
8680 begin
8681 -- Discard extreme values of zero for the divisor, since
8682 -- they will simply result in an exception in any case.
8684 if Rlo = 0 then
8685 Rlo := Uint_1;
8686 elsif Rhi = 0 then
8687 Rhi := -Uint_1;
8688 end if;
8690 -- Compute possible bounds coming from dividing end
8691 -- values of the input ranges.
8693 Ev1 := Llo / Rlo;
8694 Ev2 := Llo / Rhi;
8695 Ev3 := Lhi / Rlo;
8696 Ev4 := Lhi / Rhi;
8698 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8699 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8701 -- If the right operand can be both negative or positive,
8702 -- include the end values of the left operand in the
8703 -- extreme values, as well as their negation.
8705 if Rlo < 0 and then Rhi > 0 then
8706 Ev1 := Llo;
8707 Ev2 := -Llo;
8708 Ev3 := Lhi;
8709 Ev4 := -Lhi;
8711 Min (Lo,
8712 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
8713 Max (Hi,
8714 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
8715 end if;
8717 -- Release the RR and Ev values
8719 Release_And_Save (Mrk, Lo, Hi);
8720 end;
8721 end if;
8723 -- Exponentiation
8725 when N_Op_Expon =>
8727 -- Discard negative values for the exponent, since they will
8728 -- simply result in an exception in any case.
8730 if Rhi < 0 then
8731 Rhi := Uint_0;
8732 elsif Rlo < 0 then
8733 Rlo := Uint_0;
8734 end if;
8736 -- Estimate number of bits in result before we go computing
8737 -- giant useless bounds. Basically the number of bits in the
8738 -- result is the number of bits in the base multiplied by the
8739 -- value of the exponent. If this is big enough that the result
8740 -- definitely won't fit in Long_Long_Integer, switch to bignum
8741 -- mode immediately, and avoid computing giant bounds.
8743 -- The comparison here is approximate, but conservative, it
8744 -- only clicks on cases that are sure to exceed the bounds.
8746 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
8747 Lo := No_Uint;
8748 Hi := No_Uint;
8750 -- If right operand is zero then result is 1
8752 elsif Rhi = 0 then
8753 Lo := Uint_1;
8754 Hi := Uint_1;
8756 else
8757 -- High bound comes either from exponentiation of largest
8758 -- positive value to largest exponent value, or from
8759 -- the exponentiation of most negative value to an
8760 -- even exponent.
8762 declare
8763 Hi1, Hi2 : Uint;
8765 begin
8766 if Lhi > 0 then
8767 Hi1 := Lhi ** Rhi;
8768 else
8769 Hi1 := Uint_0;
8770 end if;
8772 if Llo < 0 then
8773 if Rhi mod 2 = 0 then
8774 Hi2 := Llo ** Rhi;
8775 else
8776 Hi2 := Llo ** (Rhi - 1);
8777 end if;
8778 else
8779 Hi2 := Uint_0;
8780 end if;
8782 Hi := UI_Max (Hi1, Hi2);
8783 end;
8785 -- Result can only be negative if base can be negative
8787 if Llo < 0 then
8788 if Rhi mod 2 = 0 then
8789 Lo := Llo ** (Rhi - 1);
8790 else
8791 Lo := Llo ** Rhi;
8792 end if;
8794 -- Otherwise low bound is minimum ** minimum
8796 else
8797 Lo := Llo ** Rlo;
8798 end if;
8799 end if;
8801 -- Negation
8803 when N_Op_Minus =>
8804 Lo := -Rhi;
8805 Hi := -Rlo;
8807 -- Mod
8809 when N_Op_Mod =>
8810 declare
8811 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8812 -- This is the maximum absolute value of the result
8814 begin
8815 Lo := Uint_0;
8816 Hi := Uint_0;
8818 -- The result depends only on the sign and magnitude of
8819 -- the right operand, it does not depend on the sign or
8820 -- magnitude of the left operand.
8822 if Rlo < 0 then
8823 Lo := -Maxabs;
8824 end if;
8826 if Rhi > 0 then
8827 Hi := Maxabs;
8828 end if;
8829 end;
8831 -- Multiplication
8833 when N_Op_Multiply =>
8835 -- Possible bounds of multiplication must come from multiplying
8836 -- end values of the input ranges (four possibilities).
8838 declare
8839 Mrk : constant Uintp.Save_Mark := Mark;
8840 -- Mark so we can release the Ev values
8842 Ev1 : constant Uint := Llo * Rlo;
8843 Ev2 : constant Uint := Llo * Rhi;
8844 Ev3 : constant Uint := Lhi * Rlo;
8845 Ev4 : constant Uint := Lhi * Rhi;
8847 begin
8848 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8849 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8851 -- Release the Ev values
8853 Release_And_Save (Mrk, Lo, Hi);
8854 end;
8856 -- Plus operator (affirmation)
8858 when N_Op_Plus =>
8859 Lo := Rlo;
8860 Hi := Rhi;
8862 -- Remainder
8864 when N_Op_Rem =>
8865 declare
8866 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8867 -- This is the maximum absolute value of the result. Note
8868 -- that the result range does not depend on the sign of the
8869 -- right operand.
8871 begin
8872 Lo := Uint_0;
8873 Hi := Uint_0;
8875 -- Case of left operand negative, which results in a range
8876 -- of -Maxabs .. 0 for those negative values. If there are
8877 -- no negative values then Lo value of result is always 0.
8879 if Llo < 0 then
8880 Lo := -Maxabs;
8881 end if;
8883 -- Case of left operand positive
8885 if Lhi > 0 then
8886 Hi := Maxabs;
8887 end if;
8888 end;
8890 -- Subtract
8892 when N_Op_Subtract =>
8893 Lo := Llo - Rhi;
8894 Hi := Lhi - Rlo;
8896 -- Nothing else should be possible
8898 when others =>
8899 raise Program_Error;
8900 end case;
8901 end if;
8903 -- Here for the case where we have not rewritten anything (no bignum
8904 -- operands or long long integer operands), and we know the result.
8905 -- If we know we are in the result range, and we do not have Bignum
8906 -- operands or Long_Long_Integer operands, we can just reexpand with
8907 -- overflow checks turned off (since we know we cannot have overflow).
8908 -- As always the reexpansion is required to complete expansion of the
8909 -- operator, but we do not need to reanalyze, and we prevent recursion
8910 -- by suppressing the check.
8912 if not (Bignum_Operands or Long_Long_Integer_Operands)
8913 and then In_Result_Range
8914 then
8915 Set_Do_Overflow_Check (N, False);
8916 Reexpand (Suppress => True);
8917 return;
8919 -- Here we know that we are not in the result range, and in the general
8920 -- case we will move into either the Bignum or Long_Long_Integer domain
8921 -- to compute the result. However, there is one exception. If we are
8922 -- at the top level, and we do not have Bignum or Long_Long_Integer
8923 -- operands, we will have to immediately convert the result back to
8924 -- the result type, so there is no point in Bignum/Long_Long_Integer
8925 -- fiddling.
8927 elsif Top_Level
8928 and then not (Bignum_Operands or Long_Long_Integer_Operands)
8930 -- One further refinement. If we are at the top level, but our parent
8931 -- is a type conversion, then go into bignum or long long integer node
8932 -- since the result will be converted to that type directly without
8933 -- going through the result type, and we may avoid an overflow. This
8934 -- is the case for example of Long_Long_Integer (A ** 4), where A is
8935 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
8936 -- but does not fit in Integer.
8938 and then Nkind (Parent (N)) /= N_Type_Conversion
8939 then
8940 -- Here keep original types, but we need to complete analysis
8942 -- One subtlety. We can't just go ahead and do an analyze operation
8943 -- here because it will cause recursion into the whole MINIMIZED/
8944 -- ELIMINATED overflow processing which is not what we want. Here
8945 -- we are at the top level, and we need a check against the result
8946 -- mode (i.e. we want to use STRICT mode). So do exactly that.
8947 -- Also, we have not modified the node, so this is a case where
8948 -- we need to reexpand, but not reanalyze.
8950 Reexpand;
8951 return;
8953 -- Cases where we do the operation in Bignum mode. This happens either
8954 -- because one of our operands is in Bignum mode already, or because
8955 -- the computed bounds are outside the bounds of Long_Long_Integer,
8956 -- which in some cases can be indicated by Hi and Lo being No_Uint.
8958 -- Note: we could do better here and in some cases switch back from
8959 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
8960 -- 0 .. 1, but the cases are rare and it is not worth the effort.
8961 -- Failing to do this switching back is only an efficiency issue.
8963 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
8965 -- OK, we are definitely outside the range of Long_Long_Integer. The
8966 -- question is whether to move to Bignum mode, or stay in the domain
8967 -- of Long_Long_Integer, signalling that an overflow check is needed.
8969 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
8970 -- the Bignum business. In ELIMINATED mode, we will normally move
8971 -- into Bignum mode, but there is an exception if neither of our
8972 -- operands is Bignum now, and we are at the top level (Top_Level
8973 -- set True). In this case, there is no point in moving into Bignum
8974 -- mode to prevent overflow if the caller will immediately convert
8975 -- the Bignum value back to LLI with an overflow check. It's more
8976 -- efficient to stay in LLI mode with an overflow check (if needed)
8978 if Check_Mode = Minimized
8979 or else (Top_Level and not Bignum_Operands)
8980 then
8981 if Do_Overflow_Check (N) then
8982 Enable_Overflow_Check (N);
8983 end if;
8985 -- The result now has to be in Long_Long_Integer mode, so adjust
8986 -- the possible range to reflect this. Note these calls also
8987 -- change No_Uint values from the top level case to LLI bounds.
8989 Max (Lo, LLLo);
8990 Min (Hi, LLHi);
8992 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
8994 else
8995 pragma Assert (Check_Mode = Eliminated);
8997 declare
8998 Fent : Entity_Id;
8999 Args : List_Id;
9001 begin
9002 case Nkind (N) is
9003 when N_Op_Abs =>
9004 Fent := RTE (RE_Big_Abs);
9006 when N_Op_Add =>
9007 Fent := RTE (RE_Big_Add);
9009 when N_Op_Divide =>
9010 Fent := RTE (RE_Big_Div);
9012 when N_Op_Expon =>
9013 Fent := RTE (RE_Big_Exp);
9015 when N_Op_Minus =>
9016 Fent := RTE (RE_Big_Neg);
9018 when N_Op_Mod =>
9019 Fent := RTE (RE_Big_Mod);
9021 when N_Op_Multiply =>
9022 Fent := RTE (RE_Big_Mul);
9024 when N_Op_Rem =>
9025 Fent := RTE (RE_Big_Rem);
9027 when N_Op_Subtract =>
9028 Fent := RTE (RE_Big_Sub);
9030 -- Anything else is an internal error, this includes the
9031 -- N_Op_Plus case, since how can plus cause the result
9032 -- to be out of range if the operand is in range?
9034 when others =>
9035 raise Program_Error;
9036 end case;
9038 -- Construct argument list for Bignum call, converting our
9039 -- operands to Bignum form if they are not already there.
9041 Args := New_List;
9043 if Binary then
9044 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
9045 end if;
9047 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
9049 -- Now rewrite the arithmetic operator with a call to the
9050 -- corresponding bignum function.
9052 Rewrite (N,
9053 Make_Function_Call (Loc,
9054 Name => New_Occurrence_Of (Fent, Loc),
9055 Parameter_Associations => Args));
9056 Reanalyze (RTE (RE_Bignum), Suppress => True);
9058 -- Indicate result is Bignum mode
9060 Lo := No_Uint;
9061 Hi := No_Uint;
9062 return;
9063 end;
9064 end if;
9066 -- Otherwise we are in range of Long_Long_Integer, so no overflow
9067 -- check is required, at least not yet.
9069 else
9070 Set_Do_Overflow_Check (N, False);
9071 end if;
9073 -- Here we are not in Bignum territory, but we may have long long
9074 -- integer operands that need special handling. First a special check:
9075 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9076 -- it means we converted it to prevent overflow, but exponentiation
9077 -- requires a Natural right operand, so convert it back to Natural.
9078 -- This conversion may raise an exception which is fine.
9080 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
9081 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
9082 end if;
9084 -- Here we will do the operation in Long_Long_Integer. We do this even
9085 -- if we know an overflow check is required, better to do this in long
9086 -- long integer mode, since we are less likely to overflow.
9088 -- Convert right or only operand to Long_Long_Integer, except that
9089 -- we do not touch the exponentiation right operand.
9091 if Nkind (N) /= N_Op_Expon then
9092 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
9093 end if;
9095 -- Convert left operand to Long_Long_Integer for binary case
9097 if Binary then
9098 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
9099 end if;
9101 -- Reset node to unanalyzed
9103 Set_Analyzed (N, False);
9104 Set_Etype (N, Empty);
9105 Set_Entity (N, Empty);
9107 -- Now analyze this new node. This reanalysis will complete processing
9108 -- for the node. In particular we will complete the expansion of an
9109 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9110 -- we will complete any division checks (since we have not changed the
9111 -- setting of the Do_Division_Check flag).
9113 -- We do this reanalysis in STRICT mode to avoid recursion into the
9114 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9116 declare
9117 SG : constant Overflow_Mode_Type :=
9118 Scope_Suppress.Overflow_Mode_General;
9119 SA : constant Overflow_Mode_Type :=
9120 Scope_Suppress.Overflow_Mode_Assertions;
9122 begin
9123 Scope_Suppress.Overflow_Mode_General := Strict;
9124 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9126 if not Do_Overflow_Check (N) then
9127 Reanalyze (LLIB, Suppress => True);
9128 else
9129 Reanalyze (LLIB);
9130 end if;
9132 Scope_Suppress.Overflow_Mode_General := SG;
9133 Scope_Suppress.Overflow_Mode_Assertions := SA;
9134 end;
9135 end Minimize_Eliminate_Overflows;
9137 -------------------------
9138 -- Overflow_Check_Mode --
9139 -------------------------
9141 function Overflow_Check_Mode return Overflow_Mode_Type is
9142 begin
9143 if In_Assertion_Expr = 0 then
9144 return Scope_Suppress.Overflow_Mode_General;
9145 else
9146 return Scope_Suppress.Overflow_Mode_Assertions;
9147 end if;
9148 end Overflow_Check_Mode;
9150 --------------------------------
9151 -- Overflow_Checks_Suppressed --
9152 --------------------------------
9154 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
9155 begin
9156 if Present (E) and then Checks_May_Be_Suppressed (E) then
9157 return Is_Check_Suppressed (E, Overflow_Check);
9158 else
9159 return Scope_Suppress.Suppress (Overflow_Check);
9160 end if;
9161 end Overflow_Checks_Suppressed;
9163 ---------------------------------
9164 -- Predicate_Checks_Suppressed --
9165 ---------------------------------
9167 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
9168 begin
9169 if Present (E) and then Checks_May_Be_Suppressed (E) then
9170 return Is_Check_Suppressed (E, Predicate_Check);
9171 else
9172 return Scope_Suppress.Suppress (Predicate_Check);
9173 end if;
9174 end Predicate_Checks_Suppressed;
9176 -----------------------------
9177 -- Range_Checks_Suppressed --
9178 -----------------------------
9180 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
9181 begin
9182 if Present (E) then
9183 if Kill_Range_Checks (E) then
9184 return True;
9186 elsif Checks_May_Be_Suppressed (E) then
9187 return Is_Check_Suppressed (E, Range_Check);
9188 end if;
9189 end if;
9191 return Scope_Suppress.Suppress (Range_Check);
9192 end Range_Checks_Suppressed;
9194 -----------------------------------------
9195 -- Range_Or_Validity_Checks_Suppressed --
9196 -----------------------------------------
9198 -- Note: the coding would be simpler here if we simply made appropriate
9199 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9200 -- duplicated checks which we prefer to avoid.
9202 function Range_Or_Validity_Checks_Suppressed
9203 (Expr : Node_Id) return Boolean
9205 begin
9206 -- Immediate return if scope checks suppressed for either check
9208 if Scope_Suppress.Suppress (Range_Check)
9210 Scope_Suppress.Suppress (Validity_Check)
9211 then
9212 return True;
9213 end if;
9215 -- If no expression, that's odd, decide that checks are suppressed,
9216 -- since we don't want anyone trying to do checks in this case, which
9217 -- is most likely the result of some other error.
9219 if No (Expr) then
9220 return True;
9221 end if;
9223 -- Expression is present, so perform suppress checks on type
9225 declare
9226 Typ : constant Entity_Id := Etype (Expr);
9227 begin
9228 if Checks_May_Be_Suppressed (Typ)
9229 and then (Is_Check_Suppressed (Typ, Range_Check)
9230 or else
9231 Is_Check_Suppressed (Typ, Validity_Check))
9232 then
9233 return True;
9234 end if;
9235 end;
9237 -- If expression is an entity name, perform checks on this entity
9239 if Is_Entity_Name (Expr) then
9240 declare
9241 Ent : constant Entity_Id := Entity (Expr);
9242 begin
9243 if Checks_May_Be_Suppressed (Ent) then
9244 return Is_Check_Suppressed (Ent, Range_Check)
9245 or else Is_Check_Suppressed (Ent, Validity_Check);
9246 end if;
9247 end;
9248 end if;
9250 -- If we fall through, no checks suppressed
9252 return False;
9253 end Range_Or_Validity_Checks_Suppressed;
9255 -------------------
9256 -- Remove_Checks --
9257 -------------------
9259 procedure Remove_Checks (Expr : Node_Id) is
9260 function Process (N : Node_Id) return Traverse_Result;
9261 -- Process a single node during the traversal
9263 procedure Traverse is new Traverse_Proc (Process);
9264 -- The traversal procedure itself
9266 -------------
9267 -- Process --
9268 -------------
9270 function Process (N : Node_Id) return Traverse_Result is
9271 begin
9272 if Nkind (N) not in N_Subexpr then
9273 return Skip;
9274 end if;
9276 Set_Do_Range_Check (N, False);
9278 case Nkind (N) is
9279 when N_And_Then =>
9280 Traverse (Left_Opnd (N));
9281 return Skip;
9283 when N_Attribute_Reference =>
9284 Set_Do_Overflow_Check (N, False);
9286 when N_Function_Call =>
9287 Set_Do_Tag_Check (N, False);
9289 when N_Op =>
9290 Set_Do_Overflow_Check (N, False);
9292 case Nkind (N) is
9293 when N_Op_Divide =>
9294 Set_Do_Division_Check (N, False);
9296 when N_Op_And =>
9297 Set_Do_Length_Check (N, False);
9299 when N_Op_Mod =>
9300 Set_Do_Division_Check (N, False);
9302 when N_Op_Or =>
9303 Set_Do_Length_Check (N, False);
9305 when N_Op_Rem =>
9306 Set_Do_Division_Check (N, False);
9308 when N_Op_Xor =>
9309 Set_Do_Length_Check (N, False);
9311 when others =>
9312 null;
9313 end case;
9315 when N_Or_Else =>
9316 Traverse (Left_Opnd (N));
9317 return Skip;
9319 when N_Selected_Component =>
9320 Set_Do_Discriminant_Check (N, False);
9322 when N_Type_Conversion =>
9323 Set_Do_Length_Check (N, False);
9324 Set_Do_Tag_Check (N, False);
9325 Set_Do_Overflow_Check (N, False);
9327 when others =>
9328 null;
9329 end case;
9331 return OK;
9332 end Process;
9334 -- Start of processing for Remove_Checks
9336 begin
9337 Traverse (Expr);
9338 end Remove_Checks;
9340 ----------------------------
9341 -- Selected_Length_Checks --
9342 ----------------------------
9344 function Selected_Length_Checks
9345 (Ck_Node : Node_Id;
9346 Target_Typ : Entity_Id;
9347 Source_Typ : Entity_Id;
9348 Warn_Node : Node_Id) return Check_Result
9350 Loc : constant Source_Ptr := Sloc (Ck_Node);
9351 S_Typ : Entity_Id;
9352 T_Typ : Entity_Id;
9353 Expr_Actual : Node_Id;
9354 Exptyp : Entity_Id;
9355 Cond : Node_Id := Empty;
9356 Do_Access : Boolean := False;
9357 Wnode : Node_Id := Warn_Node;
9358 Ret_Result : Check_Result := (Empty, Empty);
9359 Num_Checks : Natural := 0;
9361 procedure Add_Check (N : Node_Id);
9362 -- Adds the action given to Ret_Result if N is non-Empty
9364 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
9365 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
9366 -- Comments required ???
9368 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
9369 -- True for equal literals and for nodes that denote the same constant
9370 -- entity, even if its value is not a static constant. This includes the
9371 -- case of a discriminal reference within an init proc. Removes some
9372 -- obviously superfluous checks.
9374 function Length_E_Cond
9375 (Exptyp : Entity_Id;
9376 Typ : Entity_Id;
9377 Indx : Nat) return Node_Id;
9378 -- Returns expression to compute:
9379 -- Typ'Length /= Exptyp'Length
9381 function Length_N_Cond
9382 (Expr : Node_Id;
9383 Typ : Entity_Id;
9384 Indx : Nat) return Node_Id;
9385 -- Returns expression to compute:
9386 -- Typ'Length /= Expr'Length
9388 ---------------
9389 -- Add_Check --
9390 ---------------
9392 procedure Add_Check (N : Node_Id) is
9393 begin
9394 if Present (N) then
9396 -- For now, ignore attempt to place more than two checks ???
9397 -- This is really worrisome, are we really discarding checks ???
9399 if Num_Checks = 2 then
9400 return;
9401 end if;
9403 pragma Assert (Num_Checks <= 1);
9404 Num_Checks := Num_Checks + 1;
9405 Ret_Result (Num_Checks) := N;
9406 end if;
9407 end Add_Check;
9409 ------------------
9410 -- Get_E_Length --
9411 ------------------
9413 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
9414 SE : constant Entity_Id := Scope (E);
9415 N : Node_Id;
9416 E1 : Entity_Id := E;
9418 begin
9419 if Ekind (Scope (E)) = E_Record_Type
9420 and then Has_Discriminants (Scope (E))
9421 then
9422 N := Build_Discriminal_Subtype_Of_Component (E);
9424 if Present (N) then
9425 Insert_Action (Ck_Node, N);
9426 E1 := Defining_Identifier (N);
9427 end if;
9428 end if;
9430 if Ekind (E1) = E_String_Literal_Subtype then
9431 return
9432 Make_Integer_Literal (Loc,
9433 Intval => String_Literal_Length (E1));
9435 elsif SE /= Standard_Standard
9436 and then Ekind (Scope (SE)) = E_Protected_Type
9437 and then Has_Discriminants (Scope (SE))
9438 and then Has_Completion (Scope (SE))
9439 and then not Inside_Init_Proc
9440 then
9441 -- If the type whose length is needed is a private component
9442 -- constrained by a discriminant, we must expand the 'Length
9443 -- attribute into an explicit computation, using the discriminal
9444 -- of the current protected operation. This is because the actual
9445 -- type of the prival is constructed after the protected opera-
9446 -- tion has been fully expanded.
9448 declare
9449 Indx_Type : Node_Id;
9450 Lo : Node_Id;
9451 Hi : Node_Id;
9452 Do_Expand : Boolean := False;
9454 begin
9455 Indx_Type := First_Index (E);
9457 for J in 1 .. Indx - 1 loop
9458 Next_Index (Indx_Type);
9459 end loop;
9461 Get_Index_Bounds (Indx_Type, Lo, Hi);
9463 if Nkind (Lo) = N_Identifier
9464 and then Ekind (Entity (Lo)) = E_In_Parameter
9465 then
9466 Lo := Get_Discriminal (E, Lo);
9467 Do_Expand := True;
9468 end if;
9470 if Nkind (Hi) = N_Identifier
9471 and then Ekind (Entity (Hi)) = E_In_Parameter
9472 then
9473 Hi := Get_Discriminal (E, Hi);
9474 Do_Expand := True;
9475 end if;
9477 if Do_Expand then
9478 if not Is_Entity_Name (Lo) then
9479 Lo := Duplicate_Subexpr_No_Checks (Lo);
9480 end if;
9482 if not Is_Entity_Name (Hi) then
9483 Lo := Duplicate_Subexpr_No_Checks (Hi);
9484 end if;
9486 N :=
9487 Make_Op_Add (Loc,
9488 Left_Opnd =>
9489 Make_Op_Subtract (Loc,
9490 Left_Opnd => Hi,
9491 Right_Opnd => Lo),
9493 Right_Opnd => Make_Integer_Literal (Loc, 1));
9494 return N;
9496 else
9497 N :=
9498 Make_Attribute_Reference (Loc,
9499 Attribute_Name => Name_Length,
9500 Prefix =>
9501 New_Occurrence_Of (E1, Loc));
9503 if Indx > 1 then
9504 Set_Expressions (N, New_List (
9505 Make_Integer_Literal (Loc, Indx)));
9506 end if;
9508 return N;
9509 end if;
9510 end;
9512 else
9513 N :=
9514 Make_Attribute_Reference (Loc,
9515 Attribute_Name => Name_Length,
9516 Prefix =>
9517 New_Occurrence_Of (E1, Loc));
9519 if Indx > 1 then
9520 Set_Expressions (N, New_List (
9521 Make_Integer_Literal (Loc, Indx)));
9522 end if;
9524 return N;
9525 end if;
9526 end Get_E_Length;
9528 ------------------
9529 -- Get_N_Length --
9530 ------------------
9532 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
9533 begin
9534 return
9535 Make_Attribute_Reference (Loc,
9536 Attribute_Name => Name_Length,
9537 Prefix =>
9538 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
9539 Expressions => New_List (
9540 Make_Integer_Literal (Loc, Indx)));
9541 end Get_N_Length;
9543 -------------------
9544 -- Length_E_Cond --
9545 -------------------
9547 function Length_E_Cond
9548 (Exptyp : Entity_Id;
9549 Typ : Entity_Id;
9550 Indx : Nat) return Node_Id
9552 begin
9553 return
9554 Make_Op_Ne (Loc,
9555 Left_Opnd => Get_E_Length (Typ, Indx),
9556 Right_Opnd => Get_E_Length (Exptyp, Indx));
9557 end Length_E_Cond;
9559 -------------------
9560 -- Length_N_Cond --
9561 -------------------
9563 function Length_N_Cond
9564 (Expr : Node_Id;
9565 Typ : Entity_Id;
9566 Indx : Nat) return Node_Id
9568 begin
9569 return
9570 Make_Op_Ne (Loc,
9571 Left_Opnd => Get_E_Length (Typ, Indx),
9572 Right_Opnd => Get_N_Length (Expr, Indx));
9573 end Length_N_Cond;
9575 -----------------
9576 -- Same_Bounds --
9577 -----------------
9579 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
9580 begin
9581 return
9582 (Nkind (L) = N_Integer_Literal
9583 and then Nkind (R) = N_Integer_Literal
9584 and then Intval (L) = Intval (R))
9586 or else
9587 (Is_Entity_Name (L)
9588 and then Ekind (Entity (L)) = E_Constant
9589 and then ((Is_Entity_Name (R)
9590 and then Entity (L) = Entity (R))
9591 or else
9592 (Nkind (R) = N_Type_Conversion
9593 and then Is_Entity_Name (Expression (R))
9594 and then Entity (L) = Entity (Expression (R)))))
9596 or else
9597 (Is_Entity_Name (R)
9598 and then Ekind (Entity (R)) = E_Constant
9599 and then Nkind (L) = N_Type_Conversion
9600 and then Is_Entity_Name (Expression (L))
9601 and then Entity (R) = Entity (Expression (L)))
9603 or else
9604 (Is_Entity_Name (L)
9605 and then Is_Entity_Name (R)
9606 and then Entity (L) = Entity (R)
9607 and then Ekind (Entity (L)) = E_In_Parameter
9608 and then Inside_Init_Proc);
9609 end Same_Bounds;
9611 -- Start of processing for Selected_Length_Checks
9613 begin
9614 -- Checks will be applied only when generating code
9616 if not Expander_Active then
9617 return Ret_Result;
9618 end if;
9620 if Target_Typ = Any_Type
9621 or else Target_Typ = Any_Composite
9622 or else Raises_Constraint_Error (Ck_Node)
9623 then
9624 return Ret_Result;
9625 end if;
9627 if No (Wnode) then
9628 Wnode := Ck_Node;
9629 end if;
9631 T_Typ := Target_Typ;
9633 if No (Source_Typ) then
9634 S_Typ := Etype (Ck_Node);
9635 else
9636 S_Typ := Source_Typ;
9637 end if;
9639 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9640 return Ret_Result;
9641 end if;
9643 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9644 S_Typ := Designated_Type (S_Typ);
9645 T_Typ := Designated_Type (T_Typ);
9646 Do_Access := True;
9648 -- A simple optimization for the null case
9650 if Known_Null (Ck_Node) then
9651 return Ret_Result;
9652 end if;
9653 end if;
9655 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9656 if Is_Constrained (T_Typ) then
9658 -- The checking code to be generated will freeze the corresponding
9659 -- array type. However, we must freeze the type now, so that the
9660 -- freeze node does not appear within the generated if expression,
9661 -- but ahead of it.
9663 Freeze_Before (Ck_Node, T_Typ);
9665 Expr_Actual := Get_Referenced_Object (Ck_Node);
9666 Exptyp := Get_Actual_Subtype (Ck_Node);
9668 if Is_Access_Type (Exptyp) then
9669 Exptyp := Designated_Type (Exptyp);
9670 end if;
9672 -- String_Literal case. This needs to be handled specially be-
9673 -- cause no index types are available for string literals. The
9674 -- condition is simply:
9676 -- T_Typ'Length = string-literal-length
9678 if Nkind (Expr_Actual) = N_String_Literal
9679 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
9680 then
9681 Cond :=
9682 Make_Op_Ne (Loc,
9683 Left_Opnd => Get_E_Length (T_Typ, 1),
9684 Right_Opnd =>
9685 Make_Integer_Literal (Loc,
9686 Intval =>
9687 String_Literal_Length (Etype (Expr_Actual))));
9689 -- General array case. Here we have a usable actual subtype for
9690 -- the expression, and the condition is built from the two types
9691 -- (Do_Length):
9693 -- T_Typ'Length /= Exptyp'Length or else
9694 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9695 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9696 -- ...
9698 elsif Is_Constrained (Exptyp) then
9699 declare
9700 Ndims : constant Nat := Number_Dimensions (T_Typ);
9702 L_Index : Node_Id;
9703 R_Index : Node_Id;
9704 L_Low : Node_Id;
9705 L_High : Node_Id;
9706 R_Low : Node_Id;
9707 R_High : Node_Id;
9708 L_Length : Uint;
9709 R_Length : Uint;
9710 Ref_Node : Node_Id;
9712 begin
9713 -- At the library level, we need to ensure that the type of
9714 -- the object is elaborated before the check itself is
9715 -- emitted. This is only done if the object is in the
9716 -- current compilation unit, otherwise the type is frozen
9717 -- and elaborated in its unit.
9719 if Is_Itype (Exptyp)
9720 and then
9721 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
9722 and then
9723 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
9724 and then In_Open_Scopes (Scope (Exptyp))
9725 then
9726 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
9727 Set_Itype (Ref_Node, Exptyp);
9728 Insert_Action (Ck_Node, Ref_Node);
9729 end if;
9731 L_Index := First_Index (T_Typ);
9732 R_Index := First_Index (Exptyp);
9734 for Indx in 1 .. Ndims loop
9735 if not (Nkind (L_Index) = N_Raise_Constraint_Error
9736 or else
9737 Nkind (R_Index) = N_Raise_Constraint_Error)
9738 then
9739 Get_Index_Bounds (L_Index, L_Low, L_High);
9740 Get_Index_Bounds (R_Index, R_Low, R_High);
9742 -- Deal with compile time length check. Note that we
9743 -- skip this in the access case, because the access
9744 -- value may be null, so we cannot know statically.
9746 if not Do_Access
9747 and then Compile_Time_Known_Value (L_Low)
9748 and then Compile_Time_Known_Value (L_High)
9749 and then Compile_Time_Known_Value (R_Low)
9750 and then Compile_Time_Known_Value (R_High)
9751 then
9752 if Expr_Value (L_High) >= Expr_Value (L_Low) then
9753 L_Length := Expr_Value (L_High) -
9754 Expr_Value (L_Low) + 1;
9755 else
9756 L_Length := UI_From_Int (0);
9757 end if;
9759 if Expr_Value (R_High) >= Expr_Value (R_Low) then
9760 R_Length := Expr_Value (R_High) -
9761 Expr_Value (R_Low) + 1;
9762 else
9763 R_Length := UI_From_Int (0);
9764 end if;
9766 if L_Length > R_Length then
9767 Add_Check
9768 (Compile_Time_Constraint_Error
9769 (Wnode, "too few elements for}??", T_Typ));
9771 elsif L_Length < R_Length then
9772 Add_Check
9773 (Compile_Time_Constraint_Error
9774 (Wnode, "too many elements for}??", T_Typ));
9775 end if;
9777 -- The comparison for an individual index subtype
9778 -- is omitted if the corresponding index subtypes
9779 -- statically match, since the result is known to
9780 -- be true. Note that this test is worth while even
9781 -- though we do static evaluation, because non-static
9782 -- subtypes can statically match.
9784 elsif not
9785 Subtypes_Statically_Match
9786 (Etype (L_Index), Etype (R_Index))
9788 and then not
9789 (Same_Bounds (L_Low, R_Low)
9790 and then Same_Bounds (L_High, R_High))
9791 then
9792 Evolve_Or_Else
9793 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
9794 end if;
9796 Next (L_Index);
9797 Next (R_Index);
9798 end if;
9799 end loop;
9800 end;
9802 -- Handle cases where we do not get a usable actual subtype that
9803 -- is constrained. This happens for example in the function call
9804 -- and explicit dereference cases. In these cases, we have to get
9805 -- the length or range from the expression itself, making sure we
9806 -- do not evaluate it more than once.
9808 -- Here Ck_Node is the original expression, or more properly the
9809 -- result of applying Duplicate_Expr to the original tree, forcing
9810 -- the result to be a name.
9812 else
9813 declare
9814 Ndims : constant Nat := Number_Dimensions (T_Typ);
9816 begin
9817 -- Build the condition for the explicit dereference case
9819 for Indx in 1 .. Ndims loop
9820 Evolve_Or_Else
9821 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
9822 end loop;
9823 end;
9824 end if;
9825 end if;
9826 end if;
9828 -- Construct the test and insert into the tree
9830 if Present (Cond) then
9831 if Do_Access then
9832 Cond := Guard_Access (Cond, Loc, Ck_Node);
9833 end if;
9835 Add_Check
9836 (Make_Raise_Constraint_Error (Loc,
9837 Condition => Cond,
9838 Reason => CE_Length_Check_Failed));
9839 end if;
9841 return Ret_Result;
9842 end Selected_Length_Checks;
9844 ---------------------------
9845 -- Selected_Range_Checks --
9846 ---------------------------
9848 function Selected_Range_Checks
9849 (Ck_Node : Node_Id;
9850 Target_Typ : Entity_Id;
9851 Source_Typ : Entity_Id;
9852 Warn_Node : Node_Id) return Check_Result
9854 Loc : constant Source_Ptr := Sloc (Ck_Node);
9855 S_Typ : Entity_Id;
9856 T_Typ : Entity_Id;
9857 Expr_Actual : Node_Id;
9858 Exptyp : Entity_Id;
9859 Cond : Node_Id := Empty;
9860 Do_Access : Boolean := False;
9861 Wnode : Node_Id := Warn_Node;
9862 Ret_Result : Check_Result := (Empty, Empty);
9863 Num_Checks : Natural := 0;
9865 procedure Add_Check (N : Node_Id);
9866 -- Adds the action given to Ret_Result if N is non-Empty
9868 function Discrete_Range_Cond
9869 (Expr : Node_Id;
9870 Typ : Entity_Id) return Node_Id;
9871 -- Returns expression to compute:
9872 -- Low_Bound (Expr) < Typ'First
9873 -- or else
9874 -- High_Bound (Expr) > Typ'Last
9876 function Discrete_Expr_Cond
9877 (Expr : Node_Id;
9878 Typ : Entity_Id) return Node_Id;
9879 -- Returns expression to compute:
9880 -- Expr < Typ'First
9881 -- or else
9882 -- Expr > Typ'Last
9884 function Get_E_First_Or_Last
9885 (Loc : Source_Ptr;
9886 E : Entity_Id;
9887 Indx : Nat;
9888 Nam : Name_Id) return Node_Id;
9889 -- Returns an attribute reference
9890 -- E'First or E'Last
9891 -- with a source location of Loc.
9893 -- Nam is Name_First or Name_Last, according to which attribute is
9894 -- desired. If Indx is non-zero, it is passed as a literal in the
9895 -- Expressions of the attribute reference (identifying the desired
9896 -- array dimension).
9898 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
9899 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
9900 -- Returns expression to compute:
9901 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
9903 function Range_E_Cond
9904 (Exptyp : Entity_Id;
9905 Typ : Entity_Id;
9906 Indx : Nat)
9907 return Node_Id;
9908 -- Returns expression to compute:
9909 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
9911 function Range_Equal_E_Cond
9912 (Exptyp : Entity_Id;
9913 Typ : Entity_Id;
9914 Indx : Nat) return Node_Id;
9915 -- Returns expression to compute:
9916 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
9918 function Range_N_Cond
9919 (Expr : Node_Id;
9920 Typ : Entity_Id;
9921 Indx : Nat) return Node_Id;
9922 -- Return expression to compute:
9923 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
9925 ---------------
9926 -- Add_Check --
9927 ---------------
9929 procedure Add_Check (N : Node_Id) is
9930 begin
9931 if Present (N) then
9933 -- For now, ignore attempt to place more than 2 checks ???
9935 if Num_Checks = 2 then
9936 return;
9937 end if;
9939 pragma Assert (Num_Checks <= 1);
9940 Num_Checks := Num_Checks + 1;
9941 Ret_Result (Num_Checks) := N;
9942 end if;
9943 end Add_Check;
9945 -------------------------
9946 -- Discrete_Expr_Cond --
9947 -------------------------
9949 function Discrete_Expr_Cond
9950 (Expr : Node_Id;
9951 Typ : Entity_Id) return Node_Id
9953 begin
9954 return
9955 Make_Or_Else (Loc,
9956 Left_Opnd =>
9957 Make_Op_Lt (Loc,
9958 Left_Opnd =>
9959 Convert_To (Base_Type (Typ),
9960 Duplicate_Subexpr_No_Checks (Expr)),
9961 Right_Opnd =>
9962 Convert_To (Base_Type (Typ),
9963 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
9965 Right_Opnd =>
9966 Make_Op_Gt (Loc,
9967 Left_Opnd =>
9968 Convert_To (Base_Type (Typ),
9969 Duplicate_Subexpr_No_Checks (Expr)),
9970 Right_Opnd =>
9971 Convert_To
9972 (Base_Type (Typ),
9973 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
9974 end Discrete_Expr_Cond;
9976 -------------------------
9977 -- Discrete_Range_Cond --
9978 -------------------------
9980 function Discrete_Range_Cond
9981 (Expr : Node_Id;
9982 Typ : Entity_Id) return Node_Id
9984 LB : Node_Id := Low_Bound (Expr);
9985 HB : Node_Id := High_Bound (Expr);
9987 Left_Opnd : Node_Id;
9988 Right_Opnd : Node_Id;
9990 begin
9991 if Nkind (LB) = N_Identifier
9992 and then Ekind (Entity (LB)) = E_Discriminant
9993 then
9994 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
9995 end if;
9997 Left_Opnd :=
9998 Make_Op_Lt (Loc,
9999 Left_Opnd =>
10000 Convert_To
10001 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
10003 Right_Opnd =>
10004 Convert_To
10005 (Base_Type (Typ),
10006 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
10008 if Nkind (HB) = N_Identifier
10009 and then Ekind (Entity (HB)) = E_Discriminant
10010 then
10011 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10012 end if;
10014 Right_Opnd :=
10015 Make_Op_Gt (Loc,
10016 Left_Opnd =>
10017 Convert_To
10018 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
10020 Right_Opnd =>
10021 Convert_To
10022 (Base_Type (Typ),
10023 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
10025 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
10026 end Discrete_Range_Cond;
10028 -------------------------
10029 -- Get_E_First_Or_Last --
10030 -------------------------
10032 function Get_E_First_Or_Last
10033 (Loc : Source_Ptr;
10034 E : Entity_Id;
10035 Indx : Nat;
10036 Nam : Name_Id) return Node_Id
10038 Exprs : List_Id;
10039 begin
10040 if Indx > 0 then
10041 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
10042 else
10043 Exprs := No_List;
10044 end if;
10046 return Make_Attribute_Reference (Loc,
10047 Prefix => New_Occurrence_Of (E, Loc),
10048 Attribute_Name => Nam,
10049 Expressions => Exprs);
10050 end Get_E_First_Or_Last;
10052 -----------------
10053 -- Get_N_First --
10054 -----------------
10056 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
10057 begin
10058 return
10059 Make_Attribute_Reference (Loc,
10060 Attribute_Name => Name_First,
10061 Prefix =>
10062 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10063 Expressions => New_List (
10064 Make_Integer_Literal (Loc, Indx)));
10065 end Get_N_First;
10067 ----------------
10068 -- Get_N_Last --
10069 ----------------
10071 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
10072 begin
10073 return
10074 Make_Attribute_Reference (Loc,
10075 Attribute_Name => Name_Last,
10076 Prefix =>
10077 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10078 Expressions => New_List (
10079 Make_Integer_Literal (Loc, Indx)));
10080 end Get_N_Last;
10082 ------------------
10083 -- Range_E_Cond --
10084 ------------------
10086 function Range_E_Cond
10087 (Exptyp : Entity_Id;
10088 Typ : Entity_Id;
10089 Indx : Nat) return Node_Id
10091 begin
10092 return
10093 Make_Or_Else (Loc,
10094 Left_Opnd =>
10095 Make_Op_Lt (Loc,
10096 Left_Opnd =>
10097 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10098 Right_Opnd =>
10099 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10101 Right_Opnd =>
10102 Make_Op_Gt (Loc,
10103 Left_Opnd =>
10104 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10105 Right_Opnd =>
10106 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10107 end Range_E_Cond;
10109 ------------------------
10110 -- Range_Equal_E_Cond --
10111 ------------------------
10113 function Range_Equal_E_Cond
10114 (Exptyp : Entity_Id;
10115 Typ : Entity_Id;
10116 Indx : Nat) return Node_Id
10118 begin
10119 return
10120 Make_Or_Else (Loc,
10121 Left_Opnd =>
10122 Make_Op_Ne (Loc,
10123 Left_Opnd =>
10124 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10125 Right_Opnd =>
10126 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10128 Right_Opnd =>
10129 Make_Op_Ne (Loc,
10130 Left_Opnd =>
10131 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10132 Right_Opnd =>
10133 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10134 end Range_Equal_E_Cond;
10136 ------------------
10137 -- Range_N_Cond --
10138 ------------------
10140 function Range_N_Cond
10141 (Expr : Node_Id;
10142 Typ : Entity_Id;
10143 Indx : Nat) return Node_Id
10145 begin
10146 return
10147 Make_Or_Else (Loc,
10148 Left_Opnd =>
10149 Make_Op_Lt (Loc,
10150 Left_Opnd =>
10151 Get_N_First (Expr, Indx),
10152 Right_Opnd =>
10153 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10155 Right_Opnd =>
10156 Make_Op_Gt (Loc,
10157 Left_Opnd =>
10158 Get_N_Last (Expr, Indx),
10159 Right_Opnd =>
10160 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10161 end Range_N_Cond;
10163 -- Start of processing for Selected_Range_Checks
10165 begin
10166 -- Checks will be applied only when generating code. In GNATprove mode,
10167 -- we do not apply the checks, but we still call Selected_Range_Checks
10168 -- to possibly issue errors on SPARK code when a run-time error can be
10169 -- detected at compile time.
10171 if not Expander_Active and not GNATprove_Mode then
10172 return Ret_Result;
10173 end if;
10175 if Target_Typ = Any_Type
10176 or else Target_Typ = Any_Composite
10177 or else Raises_Constraint_Error (Ck_Node)
10178 then
10179 return Ret_Result;
10180 end if;
10182 if No (Wnode) then
10183 Wnode := Ck_Node;
10184 end if;
10186 T_Typ := Target_Typ;
10188 if No (Source_Typ) then
10189 S_Typ := Etype (Ck_Node);
10190 else
10191 S_Typ := Source_Typ;
10192 end if;
10194 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10195 return Ret_Result;
10196 end if;
10198 -- The order of evaluating T_Typ before S_Typ seems to be critical
10199 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
10200 -- in, and since Node can be an N_Range node, it might be invalid.
10201 -- Should there be an assert check somewhere for taking the Etype of
10202 -- an N_Range node ???
10204 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10205 S_Typ := Designated_Type (S_Typ);
10206 T_Typ := Designated_Type (T_Typ);
10207 Do_Access := True;
10209 -- A simple optimization for the null case
10211 if Known_Null (Ck_Node) then
10212 return Ret_Result;
10213 end if;
10214 end if;
10216 -- For an N_Range Node, check for a null range and then if not
10217 -- null generate a range check action.
10219 if Nkind (Ck_Node) = N_Range then
10221 -- There's no point in checking a range against itself
10223 if Ck_Node = Scalar_Range (T_Typ) then
10224 return Ret_Result;
10225 end if;
10227 declare
10228 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
10229 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
10230 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
10231 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
10233 LB : Node_Id := Low_Bound (Ck_Node);
10234 HB : Node_Id := High_Bound (Ck_Node);
10235 Known_LB : Boolean := False;
10236 Known_HB : Boolean := False;
10238 Null_Range : Boolean;
10239 Out_Of_Range_L : Boolean;
10240 Out_Of_Range_H : Boolean;
10242 begin
10243 -- Compute what is known at compile time
10245 if Known_T_LB and Known_T_HB then
10246 if Compile_Time_Known_Value (LB) then
10247 Known_LB := True;
10249 -- There's no point in checking that a bound is within its
10250 -- own range so pretend that it is known in this case. First
10251 -- deal with low bound.
10253 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
10254 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
10255 then
10256 LB := T_LB;
10257 Known_LB := True;
10258 end if;
10260 -- Likewise for the high bound
10262 if Compile_Time_Known_Value (HB) then
10263 Known_HB := True;
10265 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
10266 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
10267 then
10268 HB := T_HB;
10269 Known_HB := True;
10270 end if;
10271 end if;
10273 -- Check for case where everything is static and we can do the
10274 -- check at compile time. This is skipped if we have an access
10275 -- type, since the access value may be null.
10277 -- ??? This code can be improved since you only need to know that
10278 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
10279 -- compile time to emit pertinent messages.
10281 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
10282 and not Do_Access
10283 then
10284 -- Floating-point case
10286 if Is_Floating_Point_Type (S_Typ) then
10287 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
10288 Out_Of_Range_L :=
10289 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
10290 or else
10291 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
10293 Out_Of_Range_H :=
10294 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
10295 or else
10296 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
10298 -- Fixed or discrete type case
10300 else
10301 Null_Range := Expr_Value (HB) < Expr_Value (LB);
10302 Out_Of_Range_L :=
10303 (Expr_Value (LB) < Expr_Value (T_LB))
10304 or else
10305 (Expr_Value (LB) > Expr_Value (T_HB));
10307 Out_Of_Range_H :=
10308 (Expr_Value (HB) > Expr_Value (T_HB))
10309 or else
10310 (Expr_Value (HB) < Expr_Value (T_LB));
10311 end if;
10313 if not Null_Range then
10314 if Out_Of_Range_L then
10315 if No (Warn_Node) then
10316 Add_Check
10317 (Compile_Time_Constraint_Error
10318 (Low_Bound (Ck_Node),
10319 "static value out of range of}??", T_Typ));
10321 else
10322 Add_Check
10323 (Compile_Time_Constraint_Error
10324 (Wnode,
10325 "static range out of bounds of}??", T_Typ));
10326 end if;
10327 end if;
10329 if Out_Of_Range_H then
10330 if No (Warn_Node) then
10331 Add_Check
10332 (Compile_Time_Constraint_Error
10333 (High_Bound (Ck_Node),
10334 "static value out of range of}??", T_Typ));
10336 else
10337 Add_Check
10338 (Compile_Time_Constraint_Error
10339 (Wnode,
10340 "static range out of bounds of}??", T_Typ));
10341 end if;
10342 end if;
10343 end if;
10345 else
10346 declare
10347 LB : Node_Id := Low_Bound (Ck_Node);
10348 HB : Node_Id := High_Bound (Ck_Node);
10350 begin
10351 -- If either bound is a discriminant and we are within the
10352 -- record declaration, it is a use of the discriminant in a
10353 -- constraint of a component, and nothing can be checked
10354 -- here. The check will be emitted within the init proc.
10355 -- Before then, the discriminal has no real meaning.
10356 -- Similarly, if the entity is a discriminal, there is no
10357 -- check to perform yet.
10359 -- The same holds within a discriminated synchronized type,
10360 -- where the discriminant may constrain a component or an
10361 -- entry family.
10363 if Nkind (LB) = N_Identifier
10364 and then Denotes_Discriminant (LB, True)
10365 then
10366 if Current_Scope = Scope (Entity (LB))
10367 or else Is_Concurrent_Type (Current_Scope)
10368 or else Ekind (Entity (LB)) /= E_Discriminant
10369 then
10370 return Ret_Result;
10371 else
10372 LB :=
10373 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10374 end if;
10375 end if;
10377 if Nkind (HB) = N_Identifier
10378 and then Denotes_Discriminant (HB, True)
10379 then
10380 if Current_Scope = Scope (Entity (HB))
10381 or else Is_Concurrent_Type (Current_Scope)
10382 or else Ekind (Entity (HB)) /= E_Discriminant
10383 then
10384 return Ret_Result;
10385 else
10386 HB :=
10387 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10388 end if;
10389 end if;
10391 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
10392 Set_Paren_Count (Cond, 1);
10394 Cond :=
10395 Make_And_Then (Loc,
10396 Left_Opnd =>
10397 Make_Op_Ge (Loc,
10398 Left_Opnd =>
10399 Convert_To (Base_Type (Etype (HB)),
10400 Duplicate_Subexpr_No_Checks (HB)),
10401 Right_Opnd =>
10402 Convert_To (Base_Type (Etype (LB)),
10403 Duplicate_Subexpr_No_Checks (LB))),
10404 Right_Opnd => Cond);
10405 end;
10406 end if;
10407 end;
10409 elsif Is_Scalar_Type (S_Typ) then
10411 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10412 -- except the above simply sets a flag in the node and lets
10413 -- gigi generate the check base on the Etype of the expression.
10414 -- Sometimes, however we want to do a dynamic check against an
10415 -- arbitrary target type, so we do that here.
10417 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
10418 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10420 -- For literals, we can tell if the constraint error will be
10421 -- raised at compile time, so we never need a dynamic check, but
10422 -- if the exception will be raised, then post the usual warning,
10423 -- and replace the literal with a raise constraint error
10424 -- expression. As usual, skip this for access types
10426 elsif Compile_Time_Known_Value (Ck_Node) and then not Do_Access then
10427 declare
10428 LB : constant Node_Id := Type_Low_Bound (T_Typ);
10429 UB : constant Node_Id := Type_High_Bound (T_Typ);
10431 Out_Of_Range : Boolean;
10432 Static_Bounds : constant Boolean :=
10433 Compile_Time_Known_Value (LB)
10434 and Compile_Time_Known_Value (UB);
10436 begin
10437 -- Following range tests should use Sem_Eval routine ???
10439 if Static_Bounds then
10440 if Is_Floating_Point_Type (S_Typ) then
10441 Out_Of_Range :=
10442 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
10443 or else
10444 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
10446 -- Fixed or discrete type
10448 else
10449 Out_Of_Range :=
10450 Expr_Value (Ck_Node) < Expr_Value (LB)
10451 or else
10452 Expr_Value (Ck_Node) > Expr_Value (UB);
10453 end if;
10455 -- Bounds of the type are static and the literal is out of
10456 -- range so output a warning message.
10458 if Out_Of_Range then
10459 if No (Warn_Node) then
10460 Add_Check
10461 (Compile_Time_Constraint_Error
10462 (Ck_Node,
10463 "static value out of range of}??", T_Typ));
10465 else
10466 Add_Check
10467 (Compile_Time_Constraint_Error
10468 (Wnode,
10469 "static value out of range of}??", T_Typ));
10470 end if;
10471 end if;
10473 else
10474 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10475 end if;
10476 end;
10478 -- Here for the case of a non-static expression, we need a runtime
10479 -- check unless the source type range is guaranteed to be in the
10480 -- range of the target type.
10482 else
10483 if not In_Subrange_Of (S_Typ, T_Typ) then
10484 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10485 end if;
10486 end if;
10487 end if;
10489 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10490 if Is_Constrained (T_Typ) then
10492 Expr_Actual := Get_Referenced_Object (Ck_Node);
10493 Exptyp := Get_Actual_Subtype (Expr_Actual);
10495 if Is_Access_Type (Exptyp) then
10496 Exptyp := Designated_Type (Exptyp);
10497 end if;
10499 -- String_Literal case. This needs to be handled specially be-
10500 -- cause no index types are available for string literals. The
10501 -- condition is simply:
10503 -- T_Typ'Length = string-literal-length
10505 if Nkind (Expr_Actual) = N_String_Literal then
10506 null;
10508 -- General array case. Here we have a usable actual subtype for
10509 -- the expression, and the condition is built from the two types
10511 -- T_Typ'First < Exptyp'First or else
10512 -- T_Typ'Last > Exptyp'Last or else
10513 -- T_Typ'First(1) < Exptyp'First(1) or else
10514 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10515 -- ...
10517 elsif Is_Constrained (Exptyp) then
10518 declare
10519 Ndims : constant Nat := Number_Dimensions (T_Typ);
10521 L_Index : Node_Id;
10522 R_Index : Node_Id;
10524 begin
10525 L_Index := First_Index (T_Typ);
10526 R_Index := First_Index (Exptyp);
10528 for Indx in 1 .. Ndims loop
10529 if not (Nkind (L_Index) = N_Raise_Constraint_Error
10530 or else
10531 Nkind (R_Index) = N_Raise_Constraint_Error)
10532 then
10533 -- Deal with compile time length check. Note that we
10534 -- skip this in the access case, because the access
10535 -- value may be null, so we cannot know statically.
10537 if not
10538 Subtypes_Statically_Match
10539 (Etype (L_Index), Etype (R_Index))
10540 then
10541 -- If the target type is constrained then we
10542 -- have to check for exact equality of bounds
10543 -- (required for qualified expressions).
10545 if Is_Constrained (T_Typ) then
10546 Evolve_Or_Else
10547 (Cond,
10548 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
10549 else
10550 Evolve_Or_Else
10551 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
10552 end if;
10553 end if;
10555 Next (L_Index);
10556 Next (R_Index);
10557 end if;
10558 end loop;
10559 end;
10561 -- Handle cases where we do not get a usable actual subtype that
10562 -- is constrained. This happens for example in the function call
10563 -- and explicit dereference cases. In these cases, we have to get
10564 -- the length or range from the expression itself, making sure we
10565 -- do not evaluate it more than once.
10567 -- Here Ck_Node is the original expression, or more properly the
10568 -- result of applying Duplicate_Expr to the original tree,
10569 -- forcing the result to be a name.
10571 else
10572 declare
10573 Ndims : constant Nat := Number_Dimensions (T_Typ);
10575 begin
10576 -- Build the condition for the explicit dereference case
10578 for Indx in 1 .. Ndims loop
10579 Evolve_Or_Else
10580 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
10581 end loop;
10582 end;
10583 end if;
10585 else
10586 -- For a conversion to an unconstrained array type, generate an
10587 -- Action to check that the bounds of the source value are within
10588 -- the constraints imposed by the target type (RM 4.6(38)). No
10589 -- check is needed for a conversion to an access to unconstrained
10590 -- array type, as 4.6(24.15/2) requires the designated subtypes
10591 -- of the two access types to statically match.
10593 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
10594 and then not Do_Access
10595 then
10596 declare
10597 Opnd_Index : Node_Id;
10598 Targ_Index : Node_Id;
10599 Opnd_Range : Node_Id;
10601 begin
10602 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
10603 Targ_Index := First_Index (T_Typ);
10604 while Present (Opnd_Index) loop
10606 -- If the index is a range, use its bounds. If it is an
10607 -- entity (as will be the case if it is a named subtype
10608 -- or an itype created for a slice) retrieve its range.
10610 if Is_Entity_Name (Opnd_Index)
10611 and then Is_Type (Entity (Opnd_Index))
10612 then
10613 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
10614 else
10615 Opnd_Range := Opnd_Index;
10616 end if;
10618 if Nkind (Opnd_Range) = N_Range then
10619 if Is_In_Range
10620 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10621 Assume_Valid => True)
10622 and then
10623 Is_In_Range
10624 (High_Bound (Opnd_Range), Etype (Targ_Index),
10625 Assume_Valid => True)
10626 then
10627 null;
10629 -- If null range, no check needed
10631 elsif
10632 Compile_Time_Known_Value (High_Bound (Opnd_Range))
10633 and then
10634 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
10635 and then
10636 Expr_Value (High_Bound (Opnd_Range)) <
10637 Expr_Value (Low_Bound (Opnd_Range))
10638 then
10639 null;
10641 elsif Is_Out_Of_Range
10642 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10643 Assume_Valid => True)
10644 or else
10645 Is_Out_Of_Range
10646 (High_Bound (Opnd_Range), Etype (Targ_Index),
10647 Assume_Valid => True)
10648 then
10649 Add_Check
10650 (Compile_Time_Constraint_Error
10651 (Wnode, "value out of range of}??", T_Typ));
10653 else
10654 Evolve_Or_Else
10655 (Cond,
10656 Discrete_Range_Cond
10657 (Opnd_Range, Etype (Targ_Index)));
10658 end if;
10659 end if;
10661 Next_Index (Opnd_Index);
10662 Next_Index (Targ_Index);
10663 end loop;
10664 end;
10665 end if;
10666 end if;
10667 end if;
10669 -- Construct the test and insert into the tree
10671 if Present (Cond) then
10672 if Do_Access then
10673 Cond := Guard_Access (Cond, Loc, Ck_Node);
10674 end if;
10676 Add_Check
10677 (Make_Raise_Constraint_Error (Loc,
10678 Condition => Cond,
10679 Reason => CE_Range_Check_Failed));
10680 end if;
10682 return Ret_Result;
10683 end Selected_Range_Checks;
10685 -------------------------------
10686 -- Storage_Checks_Suppressed --
10687 -------------------------------
10689 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
10690 begin
10691 if Present (E) and then Checks_May_Be_Suppressed (E) then
10692 return Is_Check_Suppressed (E, Storage_Check);
10693 else
10694 return Scope_Suppress.Suppress (Storage_Check);
10695 end if;
10696 end Storage_Checks_Suppressed;
10698 ---------------------------
10699 -- Tag_Checks_Suppressed --
10700 ---------------------------
10702 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
10703 begin
10704 if Present (E)
10705 and then Checks_May_Be_Suppressed (E)
10706 then
10707 return Is_Check_Suppressed (E, Tag_Check);
10708 else
10709 return Scope_Suppress.Suppress (Tag_Check);
10710 end if;
10711 end Tag_Checks_Suppressed;
10713 ---------------------------------------
10714 -- Validate_Alignment_Check_Warnings --
10715 ---------------------------------------
10717 procedure Validate_Alignment_Check_Warnings is
10718 begin
10719 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
10720 declare
10721 AWR : Alignment_Warnings_Record
10722 renames Alignment_Warnings.Table (J);
10723 begin
10724 if Known_Alignment (AWR.E)
10725 and then AWR.A mod Alignment (AWR.E) = 0
10726 then
10727 Delete_Warning_And_Continuations (AWR.W);
10728 end if;
10729 end;
10730 end loop;
10731 end Validate_Alignment_Check_Warnings;
10733 --------------------------
10734 -- Validity_Check_Range --
10735 --------------------------
10737 procedure Validity_Check_Range
10738 (N : Node_Id;
10739 Related_Id : Entity_Id := Empty)
10741 begin
10742 if Validity_Checks_On and Validity_Check_Operands then
10743 if Nkind (N) = N_Range then
10744 Ensure_Valid
10745 (Expr => Low_Bound (N),
10746 Related_Id => Related_Id,
10747 Is_Low_Bound => True);
10749 Ensure_Valid
10750 (Expr => High_Bound (N),
10751 Related_Id => Related_Id,
10752 Is_High_Bound => True);
10753 end if;
10754 end if;
10755 end Validity_Check_Range;
10757 --------------------------------
10758 -- Validity_Checks_Suppressed --
10759 --------------------------------
10761 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
10762 begin
10763 if Present (E) and then Checks_May_Be_Suppressed (E) then
10764 return Is_Check_Suppressed (E, Validity_Check);
10765 else
10766 return Scope_Suppress.Suppress (Validity_Check);
10767 end if;
10768 end Validity_Checks_Suppressed;
10770 end Checks;