1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2017, Free Software Foundation, Inc. --
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. --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
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
;
40 with Nlists
; use Nlists
;
41 with Nmake
; use Nmake
;
43 with Output
; use Output
;
44 with Restrict
; use Restrict
;
45 with Rident
; use Rident
;
46 with Rtsfind
; use Rtsfind
;
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
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
148 -- Set True if entry is killed by Kill_Checks
151 -- The entity involved in the expression that is checked
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
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
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
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
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
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
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
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,
272 -- if Var = 0 or Q / Var > 12 then
278 Check_Type
: Character;
279 Target_Type
: Entity_Id
;
280 Entry_OK
: out Boolean;
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
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
306 -- To be cleaned up???
308 function Guard_Access
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
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
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
361 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
362 return Is_Check_Suppressed
(E
, Access_Check
);
364 return Scope_Suppress
.Suppress
(Access_Check
);
366 end Access_Checks_Suppressed
;
368 -------------------------------------
369 -- Accessibility_Checks_Suppressed --
370 -------------------------------------
372 function Accessibility_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
374 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
375 return Is_Check_Suppressed
(E
, Accessibility_Check
);
377 return Scope_Suppress
.Suppress
(Accessibility_Check
);
379 end Accessibility_Checks_Suppressed
;
381 -----------------------------
382 -- Activate_Division_Check --
383 -----------------------------
385 procedure Activate_Division_Check
(N
: Node_Id
) is
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
);
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
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
418 -- Otherwise we will set the flag
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
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
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
457 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
458 return Is_Check_Suppressed
(E
, Alignment_Check
);
460 return Scope_Suppress
.Suppress
(Alignment_Check
);
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
475 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
476 return Is_Check_Suppressed
(E
, Allocation_Check
);
478 return Scope_Suppress
.Suppress
(Allocation_Check
);
480 end Allocation_Checks_Suppressed
;
482 -------------------------
483 -- Append_Range_Checks --
484 -------------------------
486 procedure Append_Range_Checks
487 (Checks
: Check_Result
;
489 Suppress_Typ
: Entity_Id
;
490 Static_Sloc
: Source_Ptr
;
493 Checks_On
: constant Boolean :=
494 not Index_Checks_Suppressed
(Suppress_Typ
)
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
;
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
511 exit when No
(Checks
(J
));
513 if Nkind
(Checks
(J
)) = N_Raise_Constraint_Error
514 and then Present
(Condition
(Checks
(J
)))
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
);
524 Make_Raise_Constraint_Error
(Internal_Static_Sloc
,
525 Reason
=> CE_Range_Check_Failed
));
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
);
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
547 -- No check if short circuiting makes check unnecessary
549 if not Check_Needed
(P
, Access_Check
) then
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
)
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
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
;
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
)))
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
));
601 if Inside_A_Generic
then
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
)
617 New_Occurrence_Of
(Extra_Accessibility
(Param_Ent
), Loc
);
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
,
629 Left_Opnd
=> Param_Level
,
630 Right_Opnd
=> Type_Level
),
631 Reason
=> PE_Accessibility_Check_Failed
));
633 Analyze_And_Resolve
(N
);
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
);
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).
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.
665 or else not Check_Address_Alignment
(AC
)
666 or else Maximum_Alignment
= 1
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
))
683 AL
: Uint
:= Alignment
(Typ
);
686 -- The object alignment might be more restrictive than the type
689 if Known_Alignment
(E
) then
693 if Expr_Value
(Expr
) mod AL
= 0 then
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
706 Has_Compatible_Alignment
(E
, Prefix
(Expr
), False) = Known_Compatible
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
717 -- However, don't do the check if elaboration code is unwanted
719 if Restriction_Active
(No_Elaboration_Code
) then
722 -- Generate a check to raise PE if alignment may be inappropriate
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
)
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
)
739 Expr
:= New_Copy_Tree
(Expression
(AC
));
741 Remove_Side_Effects
(Expr
);
744 if No
(Actions
(N
)) then
745 Set_Actions
(N
, New_List
);
748 Prepend_To
(Actions
(N
),
749 Make_Raise_Program_Error
(Loc
,
756 (RTE
(RE_Integer_Address
), Expr
),
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
786 ("\address value may be incompatible with alignment of "
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
=>
801 end Apply_Address_Clause_Check
;
803 -------------------------------------
804 -- Apply_Arithmetic_Overflow_Check --
805 -------------------------------------
807 procedure Apply_Arithmetic_Overflow_Check
(N
: Node_Id
) is
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
)
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.
823 Apply_Arithmetic_Overflow_Minimized_Eliminated
(N
);
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
);
853 -- Nothing to do if Do_Overflow_Check not set or overflow checks
856 if not Do_Overflow_Check
(N
) then
860 -- An interesting special case. If the arithmetic operation appears as
861 -- the operand of a type conversion:
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
905 Conversion_Optimization
: declare
906 Target_Type
: constant Entity_Id
:=
907 Base_Type
(Entity
(Subtype_Mark
(Parent
(N
))));
921 if Is_Integer_Type
(Target_Type
)
922 and then RM_Size
(Root_Type
(Target_Type
)) >= 2 * RM_Size
(Rtyp
)
924 Tlo
:= Expr_Value
(Type_Low_Bound
(Target_Type
));
925 Thi
:= Expr_Value
(Type_High_Bound
(Target_Type
));
928 (Left_Opnd
(N
), LOK
, Llo
, Lhi
, Assume_Valid
=> True);
930 (Right_Opnd
(N
), ROK
, Rlo
, Rhi
, Assume_Valid
=> True);
933 and then Tlo
<= Llo
and then Lhi
<= Thi
934 and then Tlo
<= Rlo
and then Rhi
<= Thi
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);
969 end Conversion_Optimization
;
972 -- Now see if an overflow check is required
975 Siz
: constant Int
:= UI_To_Int
(Esize
(Rtyp
));
976 Dsiz
: constant Int
:= Siz
* 2;
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
)))
999 -- Otherwise, generate the full general code for front end overflow
1000 -- detection, which works by doing arithmetic in a larger type:
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
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
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
;
1037 pragma Assert
(Nkind
(N
) = N_Op_Subtract
);
1038 Cent
:= RE_Subtract_With_Ovflo_Check
;
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
);
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
));
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
));
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
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
);
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
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.
1103 Set_Analyzed
(Opnd
, True);
1104 Enable_Overflow_Check
(Opnd
);
1109 when RE_Not_Available
=>
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
);
1134 -- Ranges of values for result
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
)
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
))
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
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
1197 elsif Is_RTE
(Etype
(Op
), RE_Bignum
) then
1199 -- We need a sequence that looks like:
1201 -- Rnn : Result_Type;
1204 -- M : Mark_Id := SS_Mark;
1206 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
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
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.
1227 Blk
: constant Node_Id
:= Make_Bignum_Block
(Loc
);
1228 Rnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'R', Op
);
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 ???
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
)),
1261 Rewrite
(Op
, New_Occurrence_Of
(Rnn
, Loc
));
1262 Analyze_And_Resolve
(Op
);
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.
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
);
1281 Analyze_And_Resolve
(Op
);
1283 end Apply_Arithmetic_Overflow_Minimized_Eliminated
;
1285 ----------------------------
1286 -- Apply_Constraint_Check --
1287 ----------------------------
1289 procedure Apply_Constraint_Check
1292 No_Sliding
: Boolean := False)
1294 Desig_Typ
: Entity_Id
;
1297 -- No checks inside a generic (check the instantiations)
1299 if Inside_A_Generic
then
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
))
1316 (First
(Choices
(First
(Component_Associations
(N
)))))
1322 if Is_Constrained
(Typ
) then
1323 Apply_Length_Check
(N
, Typ
);
1326 Apply_Range_Check
(N
, Typ
);
1329 Apply_Range_Check
(N
, Typ
);
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
)
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
);
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
);
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
)
1366 Apply_Discriminant_Check
(N
, Typ
);
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
)
1378 Install_Null_Excluding_Check
(N
);
1381 end Apply_Constraint_Check
;
1383 ------------------------------
1384 -- Apply_Discriminant_Check --
1385 ------------------------------
1387 procedure Apply_Discriminant_Check
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
);
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
1417 Nkind
(Obj
) = N_Explicit_Dereference
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
1434 if Nkind
(Lhs
) /= N_Selected_Component
then
1437 Comp
:= Entity
(Selector_Name
(Lhs
));
1438 Pref
:= Prefix
(Lhs
);
1441 if Ekind
(Comp
) /= E_Component
1442 or else not Is_Aliased
(Comp
)
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
1456 T_Typ
:= Designated_Type
(Typ
);
1461 -- Only apply checks when generating code and discriminant checks are
1462 -- not suppressed. In GNATprove mode, we do not apply the checks, but we
1463 -- still analyze the expression to possibly issue errors on SPARK code
1464 -- when a run-time error can be detected at compile time.
1466 if not GNATprove_Mode
then
1467 if not Expander_Active
1468 or else Discriminant_Checks_Suppressed
(T_Typ
)
1474 -- No discriminant checks necessary for an access when expression is
1475 -- statically Null. This is not only an optimization, it is fundamental
1476 -- because otherwise discriminant checks may be generated in init procs
1477 -- for types containing an access to a not-yet-frozen record, causing a
1478 -- deadly forward reference.
1480 -- Also, if the expression is of an access type whose designated type is
1481 -- incomplete, then the access value must be null and we suppress the
1484 if Known_Null
(N
) then
1487 elsif Is_Access_Type
(S_Typ
) then
1488 S_Typ
:= Designated_Type
(S_Typ
);
1490 if Ekind
(S_Typ
) = E_Incomplete_Type
then
1495 -- If an assignment target is present, then we need to generate the
1496 -- actual subtype if the target is a parameter or aliased object with
1497 -- an unconstrained nominal subtype.
1499 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1500 -- subtype to the parameter and dereference cases, since other aliased
1501 -- objects are unconstrained (unless the nominal subtype is explicitly
1505 and then (Present
(Param_Entity
(Lhs
))
1506 or else (Ada_Version
< Ada_2005
1507 and then not Is_Constrained
(T_Typ
)
1508 and then Is_Aliased_View
(Lhs
)
1509 and then not Is_Aliased_Unconstrained_Component
)
1510 or else (Ada_Version
>= Ada_2005
1511 and then not Is_Constrained
(T_Typ
)
1512 and then Denotes_Explicit_Dereference
(Lhs
)
1513 and then Nkind
(Original_Node
(Lhs
)) /=
1516 T_Typ
:= Get_Actual_Subtype
(Lhs
);
1519 -- Nothing to do if the type is unconstrained (this is the case where
1520 -- the actual subtype in the RM sense of N is unconstrained and no check
1523 if not Is_Constrained
(T_Typ
) then
1526 -- Ada 2005: nothing to do if the type is one for which there is a
1527 -- partial view that is constrained.
1529 elsif Ada_Version
>= Ada_2005
1530 and then Object_Type_Has_Constrained_Partial_View
1531 (Typ
=> Base_Type
(T_Typ
),
1532 Scop
=> Current_Scope
)
1537 -- Nothing to do if the type is an Unchecked_Union
1539 if Is_Unchecked_Union
(Base_Type
(T_Typ
)) then
1543 -- Suppress checks if the subtypes are the same. The check must be
1544 -- preserved in an assignment to a formal, because the constraint is
1545 -- given by the actual.
1547 if Nkind
(Original_Node
(N
)) /= N_Allocator
1549 or else not Is_Entity_Name
(Lhs
)
1550 or else No
(Param_Entity
(Lhs
)))
1553 or else (Do_Access
and then Designated_Type
(Typ
) = S_Typ
))
1554 and then not Is_Aliased_View
(Lhs
)
1559 -- We can also eliminate checks on allocators with a subtype mark that
1560 -- coincides with the context type. The context type may be a subtype
1561 -- without a constraint (common case, a generic actual).
1563 elsif Nkind
(Original_Node
(N
)) = N_Allocator
1564 and then Is_Entity_Name
(Expression
(Original_Node
(N
)))
1567 Alloc_Typ
: constant Entity_Id
:=
1568 Entity
(Expression
(Original_Node
(N
)));
1571 if Alloc_Typ
= T_Typ
1572 or else (Nkind
(Parent
(T_Typ
)) = N_Subtype_Declaration
1573 and then Is_Entity_Name
(
1574 Subtype_Indication
(Parent
(T_Typ
)))
1575 and then Alloc_Typ
= Base_Type
(T_Typ
))
1583 -- See if we have a case where the types are both constrained, and all
1584 -- the constraints are constants. In this case, we can do the check
1585 -- successfully at compile time.
1587 -- We skip this check for the case where the node is rewritten as
1588 -- an allocator, because it already carries the context subtype,
1589 -- and extracting the discriminants from the aggregate is messy.
1591 if Is_Constrained
(S_Typ
)
1592 and then Nkind
(Original_Node
(N
)) /= N_Allocator
1602 -- S_Typ may not have discriminants in the case where it is a
1603 -- private type completed by a default discriminated type. In that
1604 -- case, we need to get the constraints from the underlying type.
1605 -- If the underlying type is unconstrained (i.e. has no default
1606 -- discriminants) no check is needed.
1608 if Has_Discriminants
(S_Typ
) then
1609 Discr
:= First_Discriminant
(S_Typ
);
1610 DconS
:= First_Elmt
(Discriminant_Constraint
(S_Typ
));
1613 Discr
:= First_Discriminant
(Underlying_Type
(S_Typ
));
1616 (Discriminant_Constraint
(Underlying_Type
(S_Typ
)));
1622 -- A further optimization: if T_Typ is derived from S_Typ
1623 -- without imposing a constraint, no check is needed.
1625 if Nkind
(Original_Node
(Parent
(T_Typ
))) =
1626 N_Full_Type_Declaration
1629 Type_Def
: constant Node_Id
:=
1630 Type_Definition
(Original_Node
(Parent
(T_Typ
)));
1632 if Nkind
(Type_Def
) = N_Derived_Type_Definition
1633 and then Is_Entity_Name
(Subtype_Indication
(Type_Def
))
1634 and then Entity
(Subtype_Indication
(Type_Def
)) = S_Typ
1642 -- Constraint may appear in full view of type
1644 if Ekind
(T_Typ
) = E_Private_Subtype
1645 and then Present
(Full_View
(T_Typ
))
1648 First_Elmt
(Discriminant_Constraint
(Full_View
(T_Typ
)));
1651 First_Elmt
(Discriminant_Constraint
(T_Typ
));
1654 while Present
(Discr
) loop
1655 ItemS
:= Node
(DconS
);
1656 ItemT
:= Node
(DconT
);
1658 -- For a discriminated component type constrained by the
1659 -- current instance of an enclosing type, there is no
1660 -- applicable discriminant check.
1662 if Nkind
(ItemT
) = N_Attribute_Reference
1663 and then Is_Access_Type
(Etype
(ItemT
))
1664 and then Is_Entity_Name
(Prefix
(ItemT
))
1665 and then Is_Type
(Entity
(Prefix
(ItemT
)))
1670 -- If the expressions for the discriminants are identical
1671 -- and it is side-effect free (for now just an entity),
1672 -- this may be a shared constraint, e.g. from a subtype
1673 -- without a constraint introduced as a generic actual.
1674 -- Examine other discriminants if any.
1677 and then Is_Entity_Name
(ItemS
)
1681 elsif not Is_OK_Static_Expression
(ItemS
)
1682 or else not Is_OK_Static_Expression
(ItemT
)
1686 elsif Expr_Value
(ItemS
) /= Expr_Value
(ItemT
) then
1687 if Do_Access
then -- needs run-time check.
1690 Apply_Compile_Time_Constraint_Error
1691 (N
, "incorrect value for discriminant&??",
1692 CE_Discriminant_Check_Failed
, Ent
=> Discr
);
1699 Next_Discriminant
(Discr
);
1708 -- In GNATprove mode, we do not apply the checks
1710 if GNATprove_Mode
then
1714 -- Here we need a discriminant check. First build the expression
1715 -- for the comparisons of the discriminants:
1717 -- (n.disc1 /= typ.disc1) or else
1718 -- (n.disc2 /= typ.disc2) or else
1720 -- (n.discn /= typ.discn)
1722 Cond
:= Build_Discriminant_Checks
(N
, T_Typ
);
1724 -- If Lhs is set and is a parameter, then the condition is guarded by:
1725 -- lhs'constrained and then (condition built above)
1727 if Present
(Param_Entity
(Lhs
)) then
1731 Make_Attribute_Reference
(Loc
,
1732 Prefix
=> New_Occurrence_Of
(Param_Entity
(Lhs
), Loc
),
1733 Attribute_Name
=> Name_Constrained
),
1734 Right_Opnd
=> Cond
);
1738 Cond
:= Guard_Access
(Cond
, Loc
, N
);
1742 Make_Raise_Constraint_Error
(Loc
,
1744 Reason
=> CE_Discriminant_Check_Failed
));
1745 end Apply_Discriminant_Check
;
1747 -------------------------
1748 -- Apply_Divide_Checks --
1749 -------------------------
1751 procedure Apply_Divide_Checks
(N
: Node_Id
) is
1752 Loc
: constant Source_Ptr
:= Sloc
(N
);
1753 Typ
: constant Entity_Id
:= Etype
(N
);
1754 Left
: constant Node_Id
:= Left_Opnd
(N
);
1755 Right
: constant Node_Id
:= Right_Opnd
(N
);
1757 Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
1758 -- Current overflow checking mode
1768 pragma Warnings
(Off
, Lhi
);
1769 -- Don't actually use this value
1772 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1773 -- operating on signed integer types, then the only thing this routine
1774 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1775 -- procedure will (possibly later on during recursive downward calls),
1776 -- ensure that any needed overflow/division checks are properly applied.
1778 if Mode
in Minimized_Or_Eliminated
1779 and then Is_Signed_Integer_Type
(Typ
)
1781 Apply_Arithmetic_Overflow_Minimized_Eliminated
(N
);
1785 -- Proceed here in SUPPRESSED or CHECKED modes
1788 and then not Backend_Divide_Checks_On_Target
1789 and then Check_Needed
(Right
, Division_Check
)
1791 Determine_Range
(Right
, ROK
, Rlo
, Rhi
, Assume_Valid
=> True);
1793 -- Deal with division check
1795 if Do_Division_Check
(N
)
1796 and then not Division_Checks_Suppressed
(Typ
)
1798 Apply_Division_Check
(N
, Rlo
, Rhi
, ROK
);
1801 -- Deal with overflow check
1803 if Do_Overflow_Check
(N
)
1804 and then not Overflow_Checks_Suppressed
(Etype
(N
))
1806 Set_Do_Overflow_Check
(N
, False);
1808 -- Test for extremely annoying case of xxx'First divided by -1
1809 -- for division of signed integer types (only overflow case).
1811 if Nkind
(N
) = N_Op_Divide
1812 and then Is_Signed_Integer_Type
(Typ
)
1814 Determine_Range
(Left
, LOK
, Llo
, Lhi
, Assume_Valid
=> True);
1815 LLB
:= Expr_Value
(Type_Low_Bound
(Base_Type
(Typ
)));
1817 if ((not ROK
) or else (Rlo
<= (-1) and then (-1) <= Rhi
))
1819 ((not LOK
) or else (Llo
= LLB
))
1822 Make_Raise_Constraint_Error
(Loc
,
1828 Duplicate_Subexpr_Move_Checks
(Left
),
1829 Right_Opnd
=> Make_Integer_Literal
(Loc
, LLB
)),
1833 Left_Opnd
=> Duplicate_Subexpr
(Right
),
1834 Right_Opnd
=> Make_Integer_Literal
(Loc
, -1))),
1836 Reason
=> CE_Overflow_Check_Failed
));
1841 end Apply_Divide_Checks
;
1843 --------------------------
1844 -- Apply_Division_Check --
1845 --------------------------
1847 procedure Apply_Division_Check
1853 pragma Assert
(Do_Division_Check
(N
));
1855 Loc
: constant Source_Ptr
:= Sloc
(N
);
1856 Right
: constant Node_Id
:= Right_Opnd
(N
);
1860 and then not Backend_Divide_Checks_On_Target
1861 and then Check_Needed
(Right
, Division_Check
)
1863 -- See if division by zero possible, and if so generate test. This
1864 -- part of the test is not controlled by the -gnato switch, since
1865 -- it is a Division_Check and not an Overflow_Check.
1867 if Do_Division_Check
(N
) then
1868 Set_Do_Division_Check
(N
, False);
1870 if (not ROK
) or else (Rlo
<= 0 and then 0 <= Rhi
) then
1872 Make_Raise_Constraint_Error
(Loc
,
1875 Left_Opnd
=> Duplicate_Subexpr_Move_Checks
(Right
),
1876 Right_Opnd
=> Make_Integer_Literal
(Loc
, 0)),
1877 Reason
=> CE_Divide_By_Zero
));
1881 end Apply_Division_Check
;
1883 ----------------------------------
1884 -- Apply_Float_Conversion_Check --
1885 ----------------------------------
1887 -- Let F and I be the source and target types of the conversion. The RM
1888 -- specifies that a floating-point value X is rounded to the nearest
1889 -- integer, with halfway cases being rounded away from zero. The rounded
1890 -- value of X is checked against I'Range.
1892 -- The catch in the above paragraph is that there is no good way to know
1893 -- whether the round-to-integer operation resulted in overflow. A remedy is
1894 -- to perform a range check in the floating-point domain instead, however:
1896 -- (1) The bounds may not be known at compile time
1897 -- (2) The check must take into account rounding or truncation.
1898 -- (3) The range of type I may not be exactly representable in F.
1899 -- (4) For the rounding case, The end-points I'First - 0.5 and
1900 -- I'Last + 0.5 may or may not be in range, depending on the
1901 -- sign of I'First and I'Last.
1902 -- (5) X may be a NaN, which will fail any comparison
1904 -- The following steps correctly convert X with rounding:
1906 -- (1) If either I'First or I'Last is not known at compile time, use
1907 -- I'Base instead of I in the next three steps and perform a
1908 -- regular range check against I'Range after conversion.
1909 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1910 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1911 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1912 -- In other words, take one of the closest floating-point numbers
1913 -- (which is an integer value) to I'First, and see if it is in
1915 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1916 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1917 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1918 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1919 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1921 -- For the truncating case, replace steps (2) and (3) as follows:
1922 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1923 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1925 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1926 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1929 procedure Apply_Float_Conversion_Check
1931 Target_Typ
: Entity_Id
)
1933 LB
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
1934 HB
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
1935 Loc
: constant Source_Ptr
:= Sloc
(Ck_Node
);
1936 Expr_Type
: constant Entity_Id
:= Base_Type
(Etype
(Ck_Node
));
1937 Target_Base
: constant Entity_Id
:=
1938 Implementation_Base_Type
(Target_Typ
);
1940 Par
: constant Node_Id
:= Parent
(Ck_Node
);
1941 pragma Assert
(Nkind
(Par
) = N_Type_Conversion
);
1942 -- Parent of check node, must be a type conversion
1944 Truncate
: constant Boolean := Float_Truncate
(Par
);
1945 Max_Bound
: constant Uint
:=
1947 (Machine_Radix_Value
(Expr_Type
),
1948 Machine_Mantissa_Value
(Expr_Type
) - 1) - 1;
1950 -- Largest bound, so bound plus or minus half is a machine number of F
1952 Ifirst
, Ilast
: Uint
;
1953 -- Bounds of integer type
1956 -- Bounds to check in floating-point domain
1958 Lo_OK
, Hi_OK
: Boolean;
1959 -- True iff Lo resp. Hi belongs to I'Range
1961 Lo_Chk
, Hi_Chk
: Node_Id
;
1962 -- Expressions that are False iff check fails
1964 Reason
: RT_Exception_Code
;
1967 -- We do not need checks if we are not generating code (i.e. the full
1968 -- expander is not active). In SPARK mode, we specifically don't want
1969 -- the frontend to expand these checks, which are dealt with directly
1970 -- in the formal verification backend.
1972 if not Expander_Active
then
1976 if not Compile_Time_Known_Value
(LB
)
1977 or not Compile_Time_Known_Value
(HB
)
1980 -- First check that the value falls in the range of the base type,
1981 -- to prevent overflow during conversion and then perform a
1982 -- regular range check against the (dynamic) bounds.
1984 pragma Assert
(Target_Base
/= Target_Typ
);
1986 Temp
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', Par
);
1989 Apply_Float_Conversion_Check
(Ck_Node
, Target_Base
);
1990 Set_Etype
(Temp
, Target_Base
);
1992 Insert_Action
(Parent
(Par
),
1993 Make_Object_Declaration
(Loc
,
1994 Defining_Identifier
=> Temp
,
1995 Object_Definition
=> New_Occurrence_Of
(Target_Typ
, Loc
),
1996 Expression
=> New_Copy_Tree
(Par
)),
1997 Suppress
=> All_Checks
);
2000 Make_Raise_Constraint_Error
(Loc
,
2003 Left_Opnd
=> New_Occurrence_Of
(Temp
, Loc
),
2004 Right_Opnd
=> New_Occurrence_Of
(Target_Typ
, Loc
)),
2005 Reason
=> CE_Range_Check_Failed
));
2006 Rewrite
(Par
, New_Occurrence_Of
(Temp
, Loc
));
2012 -- Get the (static) bounds of the target type
2014 Ifirst
:= Expr_Value
(LB
);
2015 Ilast
:= Expr_Value
(HB
);
2017 -- A simple optimization: if the expression is a universal literal,
2018 -- we can do the comparison with the bounds and the conversion to
2019 -- an integer type statically. The range checks are unchanged.
2021 if Nkind
(Ck_Node
) = N_Real_Literal
2022 and then Etype
(Ck_Node
) = Universal_Real
2023 and then Is_Integer_Type
(Target_Typ
)
2024 and then Nkind
(Parent
(Ck_Node
)) = N_Type_Conversion
2027 Int_Val
: constant Uint
:= UR_To_Uint
(Realval
(Ck_Node
));
2030 if Int_Val
<= Ilast
and then Int_Val
>= Ifirst
then
2032 -- Conversion is safe
2034 Rewrite
(Parent
(Ck_Node
),
2035 Make_Integer_Literal
(Loc
, UI_To_Int
(Int_Val
)));
2036 Analyze_And_Resolve
(Parent
(Ck_Node
), Target_Typ
);
2042 -- Check against lower bound
2044 if Truncate
and then Ifirst
> 0 then
2045 Lo
:= Pred
(Expr_Type
, UR_From_Uint
(Ifirst
));
2049 Lo
:= Succ
(Expr_Type
, UR_From_Uint
(Ifirst
- 1));
2052 elsif abs (Ifirst
) < Max_Bound
then
2053 Lo
:= UR_From_Uint
(Ifirst
) - Ureal_Half
;
2054 Lo_OK
:= (Ifirst
> 0);
2057 Lo
:= Machine
(Expr_Type
, UR_From_Uint
(Ifirst
), Round_Even
, Ck_Node
);
2058 Lo_OK
:= (Lo
>= UR_From_Uint
(Ifirst
));
2063 -- Lo_Chk := (X >= Lo)
2065 Lo_Chk
:= Make_Op_Ge
(Loc
,
2066 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Ck_Node
),
2067 Right_Opnd
=> Make_Real_Literal
(Loc
, Lo
));
2070 -- Lo_Chk := (X > Lo)
2072 Lo_Chk
:= Make_Op_Gt
(Loc
,
2073 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Ck_Node
),
2074 Right_Opnd
=> Make_Real_Literal
(Loc
, Lo
));
2077 -- Check against higher bound
2079 if Truncate
and then Ilast
< 0 then
2080 Hi
:= Succ
(Expr_Type
, UR_From_Uint
(Ilast
));
2084 Hi
:= Pred
(Expr_Type
, UR_From_Uint
(Ilast
+ 1));
2087 elsif abs (Ilast
) < Max_Bound
then
2088 Hi
:= UR_From_Uint
(Ilast
) + Ureal_Half
;
2089 Hi_OK
:= (Ilast
< 0);
2091 Hi
:= Machine
(Expr_Type
, UR_From_Uint
(Ilast
), Round_Even
, Ck_Node
);
2092 Hi_OK
:= (Hi
<= UR_From_Uint
(Ilast
));
2097 -- Hi_Chk := (X <= Hi)
2099 Hi_Chk
:= Make_Op_Le
(Loc
,
2100 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Ck_Node
),
2101 Right_Opnd
=> Make_Real_Literal
(Loc
, Hi
));
2104 -- Hi_Chk := (X < Hi)
2106 Hi_Chk
:= Make_Op_Lt
(Loc
,
2107 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Ck_Node
),
2108 Right_Opnd
=> Make_Real_Literal
(Loc
, Hi
));
2111 -- If the bounds of the target type are the same as those of the base
2112 -- type, the check is an overflow check as a range check is not
2113 -- performed in these cases.
2115 if Expr_Value
(Type_Low_Bound
(Target_Base
)) = Ifirst
2116 and then Expr_Value
(Type_High_Bound
(Target_Base
)) = Ilast
2118 Reason
:= CE_Overflow_Check_Failed
;
2120 Reason
:= CE_Range_Check_Failed
;
2123 -- Raise CE if either conditions does not hold
2125 Insert_Action
(Ck_Node
,
2126 Make_Raise_Constraint_Error
(Loc
,
2127 Condition
=> Make_Op_Not
(Loc
, Make_And_Then
(Loc
, Lo_Chk
, Hi_Chk
)),
2129 end Apply_Float_Conversion_Check
;
2131 ------------------------
2132 -- Apply_Length_Check --
2133 ------------------------
2135 procedure Apply_Length_Check
2137 Target_Typ
: Entity_Id
;
2138 Source_Typ
: Entity_Id
:= Empty
)
2141 Apply_Selected_Length_Checks
2142 (Ck_Node
, Target_Typ
, Source_Typ
, Do_Static
=> False);
2143 end Apply_Length_Check
;
2145 -------------------------------------
2146 -- Apply_Parameter_Aliasing_Checks --
2147 -------------------------------------
2149 procedure Apply_Parameter_Aliasing_Checks
2153 Loc
: constant Source_Ptr
:= Sloc
(Call
);
2155 function May_Cause_Aliasing
2156 (Formal_1
: Entity_Id
;
2157 Formal_2
: Entity_Id
) return Boolean;
2158 -- Determine whether two formal parameters can alias each other
2159 -- depending on their modes.
2161 function Original_Actual
(N
: Node_Id
) return Node_Id
;
2162 -- The expander may replace an actual with a temporary for the sake of
2163 -- side effect removal. The temporary may hide a potential aliasing as
2164 -- it does not share the address of the actual. This routine attempts
2165 -- to retrieve the original actual.
2167 procedure Overlap_Check
2168 (Actual_1
: Node_Id
;
2170 Formal_1
: Entity_Id
;
2171 Formal_2
: Entity_Id
;
2172 Check
: in out Node_Id
);
2173 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2174 -- If detailed exception messages are enabled, the check is augmented to
2175 -- provide information about the names of the corresponding formals. See
2176 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2177 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2178 -- Check contains all and-ed simple tests generated so far or remains
2179 -- unchanged in the case of detailed exception messaged.
2181 ------------------------
2182 -- May_Cause_Aliasing --
2183 ------------------------
2185 function May_Cause_Aliasing
2186 (Formal_1
: Entity_Id
;
2187 Formal_2
: Entity_Id
) return Boolean
2190 -- The following combination cannot lead to aliasing
2192 -- Formal 1 Formal 2
2195 if Ekind
(Formal_1
) = E_In_Parameter
2197 Ekind
(Formal_2
) = E_In_Parameter
2201 -- The following combinations may lead to aliasing
2203 -- Formal 1 Formal 2
2213 end May_Cause_Aliasing
;
2215 ---------------------
2216 -- Original_Actual --
2217 ---------------------
2219 function Original_Actual
(N
: Node_Id
) return Node_Id
is
2221 if Nkind
(N
) = N_Type_Conversion
then
2222 return Expression
(N
);
2224 -- The expander created a temporary to capture the result of a type
2225 -- conversion where the expression is the real actual.
2227 elsif Nkind
(N
) = N_Identifier
2228 and then Present
(Original_Node
(N
))
2229 and then Nkind
(Original_Node
(N
)) = N_Type_Conversion
2231 return Expression
(Original_Node
(N
));
2235 end Original_Actual
;
2241 procedure Overlap_Check
2242 (Actual_1
: Node_Id
;
2244 Formal_1
: Entity_Id
;
2245 Formal_2
: Entity_Id
;
2246 Check
: in out Node_Id
)
2249 ID_Casing
: constant Casing_Type
:=
2250 Identifier_Casing
(Source_Index
(Current_Sem_Unit
));
2254 -- Actual_1'Overlaps_Storage (Actual_2)
2257 Make_Attribute_Reference
(Loc
,
2258 Prefix
=> New_Copy_Tree
(Original_Actual
(Actual_1
)),
2259 Attribute_Name
=> Name_Overlaps_Storage
,
2261 New_List
(New_Copy_Tree
(Original_Actual
(Actual_2
))));
2263 -- Generate the following check when detailed exception messages are
2266 -- if Actual_1'Overlaps_Storage (Actual_2) then
2267 -- raise Program_Error with <detailed message>;
2270 if Exception_Extra_Info
then
2273 -- Do not generate location information for internal calls
2275 if Comes_From_Source
(Call
) then
2276 Store_String_Chars
(Build_Location_String
(Loc
));
2277 Store_String_Char
(' ');
2280 Store_String_Chars
("aliased parameters, actuals for """);
2282 Get_Name_String
(Chars
(Formal_1
));
2283 Set_Casing
(ID_Casing
);
2284 Store_String_Chars
(Name_Buffer
(1 .. Name_Len
));
2286 Store_String_Chars
(""" and """);
2288 Get_Name_String
(Chars
(Formal_2
));
2289 Set_Casing
(ID_Casing
);
2290 Store_String_Chars
(Name_Buffer
(1 .. Name_Len
));
2292 Store_String_Chars
(""" overlap");
2294 Insert_Action
(Call
,
2295 Make_If_Statement
(Loc
,
2297 Then_Statements
=> New_List
(
2298 Make_Raise_Statement
(Loc
,
2300 New_Occurrence_Of
(Standard_Program_Error
, Loc
),
2301 Expression
=> Make_String_Literal
(Loc
, End_String
)))));
2303 -- Create a sequence of overlapping checks by and-ing them all
2313 Right_Opnd
=> Cond
);
2323 Formal_1
: Entity_Id
;
2324 Formal_2
: Entity_Id
;
2325 Orig_Act_1
: Node_Id
;
2326 Orig_Act_2
: Node_Id
;
2328 -- Start of processing for Apply_Parameter_Aliasing_Checks
2333 Actual_1
:= First_Actual
(Call
);
2334 Formal_1
:= First_Formal
(Subp
);
2335 while Present
(Actual_1
) and then Present
(Formal_1
) loop
2336 Orig_Act_1
:= Original_Actual
(Actual_1
);
2338 -- Ensure that the actual is an object that is not passed by value.
2339 -- Elementary types are always passed by value, therefore actuals of
2340 -- such types cannot lead to aliasing. An aggregate is an object in
2341 -- Ada 2012, but an actual that is an aggregate cannot overlap with
2342 -- another actual. A type that is By_Reference (such as an array of
2343 -- controlled types) is not subject to the check because any update
2344 -- will be done in place and a subsequent read will always see the
2345 -- correct value, see RM 6.2 (12/3).
2347 if Nkind
(Orig_Act_1
) = N_Aggregate
2348 or else (Nkind
(Orig_Act_1
) = N_Qualified_Expression
2349 and then Nkind
(Expression
(Orig_Act_1
)) = N_Aggregate
)
2353 elsif Is_Object_Reference
(Orig_Act_1
)
2354 and then not Is_Elementary_Type
(Etype
(Orig_Act_1
))
2355 and then not Is_By_Reference_Type
(Etype
(Orig_Act_1
))
2357 Actual_2
:= Next_Actual
(Actual_1
);
2358 Formal_2
:= Next_Formal
(Formal_1
);
2359 while Present
(Actual_2
) and then Present
(Formal_2
) loop
2360 Orig_Act_2
:= Original_Actual
(Actual_2
);
2362 -- The other actual we are testing against must also denote
2363 -- a non pass-by-value object. Generate the check only when
2364 -- the mode of the two formals may lead to aliasing.
2366 if Is_Object_Reference
(Orig_Act_2
)
2367 and then not Is_Elementary_Type
(Etype
(Orig_Act_2
))
2368 and then May_Cause_Aliasing
(Formal_1
, Formal_2
)
2370 Remove_Side_Effects
(Actual_1
);
2371 Remove_Side_Effects
(Actual_2
);
2374 (Actual_1
=> Actual_1
,
2375 Actual_2
=> Actual_2
,
2376 Formal_1
=> Formal_1
,
2377 Formal_2
=> Formal_2
,
2381 Next_Actual
(Actual_2
);
2382 Next_Formal
(Formal_2
);
2386 Next_Actual
(Actual_1
);
2387 Next_Formal
(Formal_1
);
2390 -- Place a simple check right before the call
2392 if Present
(Check
) and then not Exception_Extra_Info
then
2393 Insert_Action
(Call
,
2394 Make_Raise_Program_Error
(Loc
,
2396 Reason
=> PE_Aliased_Parameters
));
2398 end Apply_Parameter_Aliasing_Checks
;
2400 -------------------------------------
2401 -- Apply_Parameter_Validity_Checks --
2402 -------------------------------------
2404 procedure Apply_Parameter_Validity_Checks
(Subp
: Entity_Id
) is
2405 Subp_Decl
: Node_Id
;
2407 procedure Add_Validity_Check
2408 (Formal
: Entity_Id
;
2410 For_Result
: Boolean := False);
2411 -- Add a single 'Valid[_Scalar] check which verifies the initialization
2412 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2413 -- Set flag For_Result when to verify the result of a function.
2415 ------------------------
2416 -- Add_Validity_Check --
2417 ------------------------
2419 procedure Add_Validity_Check
2420 (Formal
: Entity_Id
;
2422 For_Result
: Boolean := False)
2424 procedure Build_Pre_Post_Condition
(Expr
: Node_Id
);
2425 -- Create a pre/postcondition pragma that tests expression Expr
2427 ------------------------------
2428 -- Build_Pre_Post_Condition --
2429 ------------------------------
2431 procedure Build_Pre_Post_Condition
(Expr
: Node_Id
) is
2432 Loc
: constant Source_Ptr
:= Sloc
(Subp
);
2440 Pragma_Argument_Associations
=> New_List
(
2441 Make_Pragma_Argument_Association
(Loc
,
2442 Chars
=> Name_Check
,
2443 Expression
=> Expr
)));
2445 -- Add a message unless exception messages are suppressed
2447 if not Exception_Locations_Suppressed
then
2448 Append_To
(Pragma_Argument_Associations
(Prag
),
2449 Make_Pragma_Argument_Association
(Loc
,
2450 Chars
=> Name_Message
,
2452 Make_String_Literal
(Loc
,
2454 & Get_Name_String
(Prag_Nam
)
2456 & Build_Location_String
(Loc
))));
2459 -- Insert the pragma in the tree
2461 if Nkind
(Parent
(Subp_Decl
)) = N_Compilation_Unit
then
2462 Add_Global_Declaration
(Prag
);
2465 -- PPC pragmas associated with subprogram bodies must be inserted
2466 -- in the declarative part of the body.
2468 elsif Nkind
(Subp_Decl
) = N_Subprogram_Body
then
2469 Decls
:= Declarations
(Subp_Decl
);
2473 Set_Declarations
(Subp_Decl
, Decls
);
2476 Prepend_To
(Decls
, Prag
);
2479 -- For subprogram declarations insert the PPC pragma right after
2480 -- the declarative node.
2483 Insert_After_And_Analyze
(Subp_Decl
, Prag
);
2485 end Build_Pre_Post_Condition
;
2489 Loc
: constant Source_Ptr
:= Sloc
(Subp
);
2490 Typ
: constant Entity_Id
:= Etype
(Formal
);
2494 -- Start of processing for Add_Validity_Check
2497 -- For scalars, generate 'Valid test
2499 if Is_Scalar_Type
(Typ
) then
2502 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2504 elsif Scalar_Part_Present
(Typ
) then
2505 Nam
:= Name_Valid_Scalars
;
2507 -- No test needed for other cases (no scalars to test)
2513 -- Step 1: Create the expression to verify the validity of the
2516 Check
:= New_Occurrence_Of
(Formal
, Loc
);
2518 -- When processing a function result, use 'Result. Generate
2523 Make_Attribute_Reference
(Loc
,
2525 Attribute_Name
=> Name_Result
);
2529 -- Context['Result]'Valid[_Scalars]
2532 Make_Attribute_Reference
(Loc
,
2534 Attribute_Name
=> Nam
);
2536 -- Step 2: Create a pre or post condition pragma
2538 Build_Pre_Post_Condition
(Check
);
2539 end Add_Validity_Check
;
2544 Subp_Spec
: Node_Id
;
2546 -- Start of processing for Apply_Parameter_Validity_Checks
2549 -- Extract the subprogram specification and declaration nodes
2551 Subp_Spec
:= Parent
(Subp
);
2553 if Nkind
(Subp_Spec
) = N_Defining_Program_Unit_Name
then
2554 Subp_Spec
:= Parent
(Subp_Spec
);
2557 Subp_Decl
:= Parent
(Subp_Spec
);
2559 if not Comes_From_Source
(Subp
)
2561 -- Do not process formal subprograms because the corresponding actual
2562 -- will receive the proper checks when the instance is analyzed.
2564 or else Is_Formal_Subprogram
(Subp
)
2566 -- Do not process imported subprograms since pre and postconditions
2567 -- are never verified on routines coming from a different language.
2569 or else Is_Imported
(Subp
)
2570 or else Is_Intrinsic_Subprogram
(Subp
)
2572 -- The PPC pragmas generated by this routine do not correspond to
2573 -- source aspects, therefore they cannot be applied to abstract
2576 or else Nkind
(Subp_Decl
) = N_Abstract_Subprogram_Declaration
2578 -- Do not consider subprogram renaminds because the renamed entity
2579 -- already has the proper PPC pragmas.
2581 or else Nkind
(Subp_Decl
) = N_Subprogram_Renaming_Declaration
2583 -- Do not process null procedures because there is no benefit of
2584 -- adding the checks to a no action routine.
2586 or else (Nkind
(Subp_Spec
) = N_Procedure_Specification
2587 and then Null_Present
(Subp_Spec
))
2592 -- Inspect all the formals applying aliasing and scalar initialization
2593 -- checks where applicable.
2595 Formal
:= First_Formal
(Subp
);
2596 while Present
(Formal
) loop
2598 -- Generate the following scalar initialization checks for each
2599 -- formal parameter:
2601 -- mode IN - Pre => Formal'Valid[_Scalars]
2602 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2603 -- mode OUT - Post => Formal'Valid[_Scalars]
2605 if Check_Validity_Of_Parameters
then
2606 if Ekind_In
(Formal
, E_In_Parameter
, E_In_Out_Parameter
) then
2607 Add_Validity_Check
(Formal
, Name_Precondition
, False);
2610 if Ekind_In
(Formal
, E_In_Out_Parameter
, E_Out_Parameter
) then
2611 Add_Validity_Check
(Formal
, Name_Postcondition
, False);
2615 Next_Formal
(Formal
);
2618 -- Generate following scalar initialization check for function result:
2620 -- Post => Subp'Result'Valid[_Scalars]
2622 if Check_Validity_Of_Parameters
and then Ekind
(Subp
) = E_Function
then
2623 Add_Validity_Check
(Subp
, Name_Postcondition
, True);
2625 end Apply_Parameter_Validity_Checks
;
2627 ---------------------------
2628 -- Apply_Predicate_Check --
2629 ---------------------------
2631 procedure Apply_Predicate_Check
2634 Fun
: Entity_Id
:= Empty
)
2639 if Predicate_Checks_Suppressed
(Empty
) then
2642 elsif Predicates_Ignored
(Typ
) then
2645 elsif Present
(Predicate_Function
(Typ
)) then
2647 while Present
(S
) and then not Is_Subprogram
(S
) loop
2651 -- A predicate check does not apply within internally generated
2652 -- subprograms, such as TSS functions.
2654 if Within_Internal_Subprogram
then
2657 -- If the check appears within the predicate function itself, it
2658 -- means that the user specified a check whose formal is the
2659 -- predicated subtype itself, rather than some covering type. This
2660 -- is likely to be a common error, and thus deserves a warning.
2662 elsif Present
(S
) and then S
= Predicate_Function
(Typ
) then
2664 ("predicate check includes a call to& that requires a "
2665 & "predicate check??", Parent
(N
), Fun
);
2667 ("\this will result in infinite recursion??", Parent
(N
));
2669 if Is_First_Subtype
(Typ
) then
2671 ("\use an explicit subtype of& to carry the predicate",
2676 Make_Raise_Storage_Error
(Sloc
(N
),
2677 Reason
=> SE_Infinite_Recursion
));
2679 -- Here for normal case of predicate active
2682 -- If the type has a static predicate and the expression is known
2683 -- at compile time, see if the expression satisfies the predicate.
2685 Check_Expression_Against_Static_Predicate
(N
, Typ
);
2687 if not Expander_Active
then
2691 -- For an entity of the type, generate a call to the predicate
2692 -- function, unless its type is an actual subtype, which is not
2693 -- visible outside of the enclosing subprogram.
2695 if Is_Entity_Name
(N
)
2696 and then not Is_Actual_Subtype
(Typ
)
2699 Make_Predicate_Check
2700 (Typ
, New_Occurrence_Of
(Entity
(N
), Sloc
(N
))));
2702 -- If the expression is not an entity it may have side effects,
2703 -- and the following call will create an object declaration for
2704 -- it. We disable checks during its analysis, to prevent an
2705 -- infinite recursion.
2709 Make_Predicate_Check
2710 (Typ
, Duplicate_Subexpr
(N
)), Suppress
=> All_Checks
);
2714 end Apply_Predicate_Check
;
2716 -----------------------
2717 -- Apply_Range_Check --
2718 -----------------------
2720 procedure Apply_Range_Check
2722 Target_Typ
: Entity_Id
;
2723 Source_Typ
: Entity_Id
:= Empty
)
2726 Apply_Selected_Range_Checks
2727 (Ck_Node
, Target_Typ
, Source_Typ
, Do_Static
=> False);
2728 end Apply_Range_Check
;
2730 ------------------------------
2731 -- Apply_Scalar_Range_Check --
2732 ------------------------------
2734 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2735 -- off if it is already set on.
2737 procedure Apply_Scalar_Range_Check
2739 Target_Typ
: Entity_Id
;
2740 Source_Typ
: Entity_Id
:= Empty
;
2741 Fixed_Int
: Boolean := False)
2743 Parnt
: constant Node_Id
:= Parent
(Expr
);
2745 Arr
: Node_Id
:= Empty
; -- initialize to prevent warning
2746 Arr_Typ
: Entity_Id
:= Empty
; -- initialize to prevent warning
2747 OK
: Boolean := False; -- initialize to prevent warning
2749 Is_Subscr_Ref
: Boolean;
2750 -- Set true if Expr is a subscript
2752 Is_Unconstrained_Subscr_Ref
: Boolean;
2753 -- Set true if Expr is a subscript of an unconstrained array. In this
2754 -- case we do not attempt to do an analysis of the value against the
2755 -- range of the subscript, since we don't know the actual subtype.
2758 -- Set to True if Expr should be regarded as a real value even though
2759 -- the type of Expr might be discrete.
2761 procedure Bad_Value
(Warn
: Boolean := False);
2762 -- Procedure called if value is determined to be out of range. Warn is
2763 -- True to force a warning instead of an error, even when SPARK_Mode is
2770 procedure Bad_Value
(Warn
: Boolean := False) is
2772 Apply_Compile_Time_Constraint_Error
2773 (Expr
, "value not in range of}??", CE_Range_Check_Failed
,
2779 -- Start of processing for Apply_Scalar_Range_Check
2782 -- Return if check obviously not needed
2785 -- Not needed inside generic
2789 -- Not needed if previous error
2791 or else Target_Typ
= Any_Type
2792 or else Nkind
(Expr
) = N_Error
2794 -- Not needed for non-scalar type
2796 or else not Is_Scalar_Type
(Target_Typ
)
2798 -- Not needed if we know node raises CE already
2800 or else Raises_Constraint_Error
(Expr
)
2805 -- Now, see if checks are suppressed
2808 Is_List_Member
(Expr
) and then Nkind
(Parnt
) = N_Indexed_Component
;
2810 if Is_Subscr_Ref
then
2811 Arr
:= Prefix
(Parnt
);
2812 Arr_Typ
:= Get_Actual_Subtype_If_Available
(Arr
);
2814 if Is_Access_Type
(Arr_Typ
) then
2815 Arr_Typ
:= Designated_Type
(Arr_Typ
);
2819 if not Do_Range_Check
(Expr
) then
2821 -- Subscript reference. Check for Index_Checks suppressed
2823 if Is_Subscr_Ref
then
2825 -- Check array type and its base type
2827 if Index_Checks_Suppressed
(Arr_Typ
)
2828 or else Index_Checks_Suppressed
(Base_Type
(Arr_Typ
))
2832 -- Check array itself if it is an entity name
2834 elsif Is_Entity_Name
(Arr
)
2835 and then Index_Checks_Suppressed
(Entity
(Arr
))
2839 -- Check expression itself if it is an entity name
2841 elsif Is_Entity_Name
(Expr
)
2842 and then Index_Checks_Suppressed
(Entity
(Expr
))
2847 -- All other cases, check for Range_Checks suppressed
2850 -- Check target type and its base type
2852 if Range_Checks_Suppressed
(Target_Typ
)
2853 or else Range_Checks_Suppressed
(Base_Type
(Target_Typ
))
2857 -- Check expression itself if it is an entity name
2859 elsif Is_Entity_Name
(Expr
)
2860 and then Range_Checks_Suppressed
(Entity
(Expr
))
2864 -- If Expr is part of an assignment statement, then check left
2865 -- side of assignment if it is an entity name.
2867 elsif Nkind
(Parnt
) = N_Assignment_Statement
2868 and then Is_Entity_Name
(Name
(Parnt
))
2869 and then Range_Checks_Suppressed
(Entity
(Name
(Parnt
)))
2876 -- Do not set range checks if they are killed
2878 if Nkind
(Expr
) = N_Unchecked_Type_Conversion
2879 and then Kill_Range_Check
(Expr
)
2884 -- Do not set range checks for any values from System.Scalar_Values
2885 -- since the whole idea of such values is to avoid checking them.
2887 if Is_Entity_Name
(Expr
)
2888 and then Is_RTU
(Scope
(Entity
(Expr
)), System_Scalar_Values
)
2893 -- Now see if we need a check
2895 if No
(Source_Typ
) then
2896 S_Typ
:= Etype
(Expr
);
2898 S_Typ
:= Source_Typ
;
2901 if not Is_Scalar_Type
(S_Typ
) or else S_Typ
= Any_Type
then
2905 Is_Unconstrained_Subscr_Ref
:=
2906 Is_Subscr_Ref
and then not Is_Constrained
(Arr_Typ
);
2908 -- Special checks for floating-point type
2910 if Is_Floating_Point_Type
(S_Typ
) then
2912 -- Always do a range check if the source type includes infinities and
2913 -- the target type does not include infinities. We do not do this if
2914 -- range checks are killed.
2915 -- If the expression is a literal and the bounds of the type are
2916 -- static constants it may be possible to optimize the check.
2918 if Has_Infinities
(S_Typ
)
2919 and then not Has_Infinities
(Target_Typ
)
2921 -- If the expression is a literal and the bounds of the type are
2922 -- static constants it may be possible to optimize the check.
2924 if Nkind
(Expr
) = N_Real_Literal
then
2926 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
2927 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
2930 if Compile_Time_Known_Value
(Tlo
)
2931 and then Compile_Time_Known_Value
(Thi
)
2932 and then Expr_Value_R
(Expr
) >= Expr_Value_R
(Tlo
)
2933 and then Expr_Value_R
(Expr
) <= Expr_Value_R
(Thi
)
2937 Enable_Range_Check
(Expr
);
2942 Enable_Range_Check
(Expr
);
2947 -- Return if we know expression is definitely in the range of the target
2948 -- type as determined by Determine_Range. Right now we only do this for
2949 -- discrete types, and not fixed-point or floating-point types.
2951 -- The additional less-precise tests below catch these cases
2953 -- In GNATprove_Mode, also deal with the case of a conversion from
2954 -- floating-point to integer. It is only possible because analysis
2955 -- in GNATprove rules out the possibility of a NaN or infinite value.
2957 -- Note: skip this if we are given a source_typ, since the point of
2958 -- supplying a Source_Typ is to stop us looking at the expression.
2959 -- We could sharpen this test to be out parameters only ???
2961 if Is_Discrete_Type
(Target_Typ
)
2962 and then (Is_Discrete_Type
(Etype
(Expr
))
2963 or else (GNATprove_Mode
2964 and then Is_Floating_Point_Type
(Etype
(Expr
))))
2965 and then not Is_Unconstrained_Subscr_Ref
2966 and then No
(Source_Typ
)
2969 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Typ
);
2970 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Typ
);
2973 if Compile_Time_Known_Value
(Tlo
)
2974 and then Compile_Time_Known_Value
(Thi
)
2977 Hiv
: constant Uint
:= Expr_Value
(Thi
);
2978 Lov
: constant Uint
:= Expr_Value
(Tlo
);
2983 -- If range is null, we for sure have a constraint error (we
2984 -- don't even need to look at the value involved, since all
2985 -- possible values will raise CE).
2989 -- When SPARK_Mode is On, force a warning instead of
2990 -- an error in that case, as this likely corresponds
2991 -- to deactivated code.
2993 Bad_Value
(Warn
=> SPARK_Mode
= On
);
2995 -- In GNATprove mode, we enable the range check so that
2996 -- GNATprove will issue a message if it cannot be proved.
2998 if GNATprove_Mode
then
2999 Enable_Range_Check
(Expr
);
3005 -- Otherwise determine range of value
3007 if Is_Discrete_Type
(Etype
(Expr
)) then
3009 (Expr
, OK
, Lo
, Hi
, Assume_Valid
=> True);
3011 -- When converting a float to an integer type, determine the
3012 -- range in real first, and then convert the bounds using
3013 -- UR_To_Uint which correctly rounds away from zero when
3014 -- half way between two integers, as required by normal
3015 -- Ada 95 rounding semantics. It is only possible because
3016 -- analysis in GNATprove rules out the possibility of a NaN
3017 -- or infinite value.
3019 elsif GNATprove_Mode
3020 and then Is_Floating_Point_Type
(Etype
(Expr
))
3028 (Expr
, OK
, Lor
, Hir
, Assume_Valid
=> True);
3031 Lo
:= UR_To_Uint
(Lor
);
3032 Hi
:= UR_To_Uint
(Hir
);
3039 -- If definitely in range, all OK
3041 if Lo
>= Lov
and then Hi
<= Hiv
then
3044 -- If definitely not in range, warn
3046 elsif Lov
> Hi
or else Hiv
< Lo
then
3050 -- Otherwise we don't know
3062 Is_Floating_Point_Type
(S_Typ
)
3063 or else (Is_Fixed_Point_Type
(S_Typ
) and then not Fixed_Int
);
3065 -- Check if we can determine at compile time whether Expr is in the
3066 -- range of the target type. Note that if S_Typ is within the bounds
3067 -- of Target_Typ then this must be the case. This check is meaningful
3068 -- only if this is not a conversion between integer and real types.
3070 if not Is_Unconstrained_Subscr_Ref
3071 and then Is_Discrete_Type
(S_Typ
) = Is_Discrete_Type
(Target_Typ
)
3073 (In_Subrange_Of
(S_Typ
, Target_Typ
, Fixed_Int
)
3075 -- Also check if the expression itself is in the range of the
3076 -- target type if it is a known at compile time value. We skip
3077 -- this test if S_Typ is set since for OUT and IN OUT parameters
3078 -- the Expr itself is not relevant to the checking.
3082 and then Is_In_Range
(Expr
, Target_Typ
,
3083 Assume_Valid
=> True,
3084 Fixed_Int
=> Fixed_Int
,
3085 Int_Real
=> Int_Real
)))
3089 elsif Is_Out_Of_Range
(Expr
, Target_Typ
,
3090 Assume_Valid
=> True,
3091 Fixed_Int
=> Fixed_Int
,
3092 Int_Real
=> Int_Real
)
3097 -- Floating-point case
3098 -- In the floating-point case, we only do range checks if the type is
3099 -- constrained. We definitely do NOT want range checks for unconstrained
3100 -- types, since we want to have infinities, except when
3101 -- Check_Float_Overflow is set.
3103 elsif Is_Floating_Point_Type
(S_Typ
) then
3104 if Is_Constrained
(S_Typ
) or else Check_Float_Overflow
then
3105 Enable_Range_Check
(Expr
);
3108 -- For all other cases we enable a range check unconditionally
3111 Enable_Range_Check
(Expr
);
3114 end Apply_Scalar_Range_Check
;
3116 ----------------------------------
3117 -- Apply_Selected_Length_Checks --
3118 ----------------------------------
3120 procedure Apply_Selected_Length_Checks
3122 Target_Typ
: Entity_Id
;
3123 Source_Typ
: Entity_Id
;
3124 Do_Static
: Boolean)
3126 Checks_On
: constant Boolean :=
3127 not Index_Checks_Suppressed
(Target_Typ
)
3129 not Length_Checks_Suppressed
(Target_Typ
);
3131 Loc
: constant Source_Ptr
:= Sloc
(Ck_Node
);
3135 R_Result
: Check_Result
;
3138 -- Only apply checks when generating code
3140 -- Note: this means that we lose some useful warnings if the expander
3143 if not Expander_Active
then
3148 Selected_Length_Checks
(Ck_Node
, Target_Typ
, Source_Typ
, Empty
);
3150 for J
in 1 .. 2 loop
3151 R_Cno
:= R_Result
(J
);
3152 exit when No
(R_Cno
);
3154 -- A length check may mention an Itype which is attached to a
3155 -- subsequent node. At the top level in a package this can cause
3156 -- an order-of-elaboration problem, so we make sure that the itype
3157 -- is referenced now.
3159 if Ekind
(Current_Scope
) = E_Package
3160 and then Is_Compilation_Unit
(Current_Scope
)
3162 Ensure_Defined
(Target_Typ
, Ck_Node
);
3164 if Present
(Source_Typ
) then
3165 Ensure_Defined
(Source_Typ
, Ck_Node
);
3167 elsif Is_Itype
(Etype
(Ck_Node
)) then
3168 Ensure_Defined
(Etype
(Ck_Node
), Ck_Node
);
3172 -- If the item is a conditional raise of constraint error, then have
3173 -- a look at what check is being performed and ???
3175 if Nkind
(R_Cno
) = N_Raise_Constraint_Error
3176 and then Present
(Condition
(R_Cno
))
3178 Cond
:= Condition
(R_Cno
);
3180 -- Case where node does not now have a dynamic check
3182 if not Has_Dynamic_Length_Check
(Ck_Node
) then
3184 -- If checks are on, just insert the check
3187 Insert_Action
(Ck_Node
, R_Cno
);
3189 if not Do_Static
then
3190 Set_Has_Dynamic_Length_Check
(Ck_Node
);
3193 -- If checks are off, then analyze the length check after
3194 -- temporarily attaching it to the tree in case the relevant
3195 -- condition can be evaluated at compile time. We still want a
3196 -- compile time warning in this case.
3199 Set_Parent
(R_Cno
, Ck_Node
);
3204 -- Output a warning if the condition is known to be True
3206 if Is_Entity_Name
(Cond
)
3207 and then Entity
(Cond
) = Standard_True
3209 Apply_Compile_Time_Constraint_Error
3210 (Ck_Node
, "wrong length for array of}??",
3211 CE_Length_Check_Failed
,
3215 -- If we were only doing a static check, or if checks are not
3216 -- on, then we want to delete the check, since it is not needed.
3217 -- We do this by replacing the if statement by a null statement
3219 elsif Do_Static
or else not Checks_On
then
3220 Remove_Warning_Messages
(R_Cno
);
3221 Rewrite
(R_Cno
, Make_Null_Statement
(Loc
));
3225 Install_Static_Check
(R_Cno
, Loc
);
3228 end Apply_Selected_Length_Checks
;
3230 ---------------------------------
3231 -- Apply_Selected_Range_Checks --
3232 ---------------------------------
3234 procedure Apply_Selected_Range_Checks
3236 Target_Typ
: Entity_Id
;
3237 Source_Typ
: Entity_Id
;
3238 Do_Static
: Boolean)
3240 Checks_On
: constant Boolean :=
3241 not Index_Checks_Suppressed
(Target_Typ
)
3243 not Range_Checks_Suppressed
(Target_Typ
);
3245 Loc
: constant Source_Ptr
:= Sloc
(Ck_Node
);
3249 R_Result
: Check_Result
;
3252 -- Only apply checks when generating code. In GNATprove mode, we do not
3253 -- apply the checks, but we still call Selected_Range_Checks to possibly
3254 -- issue errors on SPARK code when a run-time error can be detected at
3257 if not GNATprove_Mode
then
3258 if not Expander_Active
or not Checks_On
then
3264 Selected_Range_Checks
(Ck_Node
, Target_Typ
, Source_Typ
, Empty
);
3266 if GNATprove_Mode
then
3270 for J
in 1 .. 2 loop
3271 R_Cno
:= R_Result
(J
);
3272 exit when No
(R_Cno
);
3274 -- The range check requires runtime evaluation. Depending on what its
3275 -- triggering condition is, the check may be converted into a compile
3276 -- time constraint check.
3278 if Nkind
(R_Cno
) = N_Raise_Constraint_Error
3279 and then Present
(Condition
(R_Cno
))
3281 Cond
:= Condition
(R_Cno
);
3283 -- Insert the range check before the related context. Note that
3284 -- this action analyses the triggering condition.
3286 Insert_Action
(Ck_Node
, R_Cno
);
3288 -- This old code doesn't make sense, why is the context flagged as
3289 -- requiring dynamic range checks now in the middle of generating
3292 if not Do_Static
then
3293 Set_Has_Dynamic_Range_Check
(Ck_Node
);
3296 -- The triggering condition evaluates to True, the range check
3297 -- can be converted into a compile time constraint check.
3299 if Is_Entity_Name
(Cond
)
3300 and then Entity
(Cond
) = Standard_True
3302 -- Since an N_Range is technically not an expression, we have
3303 -- to set one of the bounds to C_E and then just flag the
3304 -- N_Range. The warning message will point to the lower bound
3305 -- and complain about a range, which seems OK.
3307 if Nkind
(Ck_Node
) = N_Range
then
3308 Apply_Compile_Time_Constraint_Error
3309 (Low_Bound
(Ck_Node
),
3310 "static range out of bounds of}??",
3311 CE_Range_Check_Failed
,
3315 Set_Raises_Constraint_Error
(Ck_Node
);
3318 Apply_Compile_Time_Constraint_Error
3320 "static value out of range of}??",
3321 CE_Range_Check_Failed
,
3326 -- If we were only doing a static check, or if checks are not
3327 -- on, then we want to delete the check, since it is not needed.
3328 -- We do this by replacing the if statement by a null statement
3330 elsif Do_Static
then
3331 Remove_Warning_Messages
(R_Cno
);
3332 Rewrite
(R_Cno
, Make_Null_Statement
(Loc
));
3335 -- The range check raises Constraint_Error explicitly
3338 Install_Static_Check
(R_Cno
, Loc
);
3341 end Apply_Selected_Range_Checks
;
3343 -------------------------------
3344 -- Apply_Static_Length_Check --
3345 -------------------------------
3347 procedure Apply_Static_Length_Check
3349 Target_Typ
: Entity_Id
;
3350 Source_Typ
: Entity_Id
:= Empty
)
3353 Apply_Selected_Length_Checks
3354 (Expr
, Target_Typ
, Source_Typ
, Do_Static
=> True);
3355 end Apply_Static_Length_Check
;
3357 -------------------------------------
3358 -- Apply_Subscript_Validity_Checks --
3359 -------------------------------------
3361 procedure Apply_Subscript_Validity_Checks
(Expr
: Node_Id
) is
3365 pragma Assert
(Nkind
(Expr
) = N_Indexed_Component
);
3367 -- Loop through subscripts
3369 Sub
:= First
(Expressions
(Expr
));
3370 while Present
(Sub
) loop
3372 -- Check one subscript. Note that we do not worry about enumeration
3373 -- type with holes, since we will convert the value to a Pos value
3374 -- for the subscript, and that convert will do the necessary validity
3377 Ensure_Valid
(Sub
, Holes_OK
=> True);
3379 -- Move to next subscript
3383 end Apply_Subscript_Validity_Checks
;
3385 ----------------------------------
3386 -- Apply_Type_Conversion_Checks --
3387 ----------------------------------
3389 procedure Apply_Type_Conversion_Checks
(N
: Node_Id
) is
3390 Target_Type
: constant Entity_Id
:= Etype
(N
);
3391 Target_Base
: constant Entity_Id
:= Base_Type
(Target_Type
);
3392 Expr
: constant Node_Id
:= Expression
(N
);
3394 Expr_Type
: constant Entity_Id
:= Underlying_Type
(Etype
(Expr
));
3395 -- Note: if Etype (Expr) is a private type without discriminants, its
3396 -- full view might have discriminants with defaults, so we need the
3397 -- full view here to retrieve the constraints.
3400 if Inside_A_Generic
then
3403 -- Skip these checks if serious errors detected, there are some nasty
3404 -- situations of incomplete trees that blow things up.
3406 elsif Serious_Errors_Detected
> 0 then
3409 -- Never generate discriminant checks for Unchecked_Union types
3411 elsif Present
(Expr_Type
)
3412 and then Is_Unchecked_Union
(Expr_Type
)
3416 -- Scalar type conversions of the form Target_Type (Expr) require a
3417 -- range check if we cannot be sure that Expr is in the base type of
3418 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3419 -- are not quite the same condition from an implementation point of
3420 -- view, but clearly the second includes the first.
3422 elsif Is_Scalar_Type
(Target_Type
) then
3424 Conv_OK
: constant Boolean := Conversion_OK
(N
);
3425 -- If the Conversion_OK flag on the type conversion is set and no
3426 -- floating-point type is involved in the type conversion then
3427 -- fixed-point values must be read as integral values.
3429 Float_To_Int
: constant Boolean :=
3430 Is_Floating_Point_Type
(Expr_Type
)
3431 and then Is_Integer_Type
(Target_Type
);
3434 if not Overflow_Checks_Suppressed
(Target_Base
)
3435 and then not Overflow_Checks_Suppressed
(Target_Type
)
3437 In_Subrange_Of
(Expr_Type
, Target_Base
, Fixed_Int
=> Conv_OK
)
3438 and then not Float_To_Int
3440 -- A small optimization: the attribute 'Pos applied to an
3441 -- enumeration type has a known range, even though its type is
3442 -- Universal_Integer. So in numeric conversions it is usually
3443 -- within range of the target integer type. Use the static
3444 -- bounds of the base types to check. Disable this optimization
3445 -- in case of a generic formal discrete type, because we don't
3446 -- necessarily know the upper bound yet.
3448 if Nkind
(Expr
) = N_Attribute_Reference
3449 and then Attribute_Name
(Expr
) = Name_Pos
3450 and then Is_Enumeration_Type
(Etype
(Prefix
(Expr
)))
3451 and then not Is_Generic_Type
(Etype
(Prefix
(Expr
)))
3452 and then Is_Integer_Type
(Target_Type
)
3455 Enum_T
: constant Entity_Id
:=
3456 Root_Type
(Etype
(Prefix
(Expr
)));
3457 Int_T
: constant Entity_Id
:= Base_Type
(Target_Type
);
3458 Last_I
: constant Uint
:=
3459 Intval
(High_Bound
(Scalar_Range
(Int_T
)));
3463 -- Character types have no explicit literals, so we use
3464 -- the known number of characters in the type.
3466 if Root_Type
(Enum_T
) = Standard_Character
then
3467 Last_E
:= UI_From_Int
(255);
3469 elsif Enum_T
= Standard_Wide_Character
3470 or else Enum_T
= Standard_Wide_Wide_Character
3472 Last_E
:= UI_From_Int
(65535);
3477 (Entity
(High_Bound
(Scalar_Range
(Enum_T
))));
3480 if Last_E
<= Last_I
then
3484 Activate_Overflow_Check
(N
);
3489 Activate_Overflow_Check
(N
);
3493 if not Range_Checks_Suppressed
(Target_Type
)
3494 and then not Range_Checks_Suppressed
(Expr_Type
)
3497 and then not GNATprove_Mode
3499 Apply_Float_Conversion_Check
(Expr
, Target_Type
);
3501 Apply_Scalar_Range_Check
3502 (Expr
, Target_Type
, Fixed_Int
=> Conv_OK
);
3504 -- If the target type has predicates, we need to indicate
3505 -- the need for a check, even if Determine_Range finds that
3506 -- the value is within bounds. This may be the case e.g for
3507 -- a division with a constant denominator.
3509 if Has_Predicates
(Target_Type
) then
3510 Enable_Range_Check
(Expr
);
3516 elsif Comes_From_Source
(N
)
3517 and then not Discriminant_Checks_Suppressed
(Target_Type
)
3518 and then Is_Record_Type
(Target_Type
)
3519 and then Is_Derived_Type
(Target_Type
)
3520 and then not Is_Tagged_Type
(Target_Type
)
3521 and then not Is_Constrained
(Target_Type
)
3522 and then Present
(Stored_Constraint
(Target_Type
))
3524 -- An unconstrained derived type may have inherited discriminant.
3525 -- Build an actual discriminant constraint list using the stored
3526 -- constraint, to verify that the expression of the parent type
3527 -- satisfies the constraints imposed by the (unconstrained) derived
3528 -- type. This applies to value conversions, not to view conversions
3532 Loc
: constant Source_Ptr
:= Sloc
(N
);
3534 Constraint
: Elmt_Id
;
3535 Discr_Value
: Node_Id
;
3538 New_Constraints
: constant Elist_Id
:= New_Elmt_List
;
3539 Old_Constraints
: constant Elist_Id
:=
3540 Discriminant_Constraint
(Expr_Type
);
3543 Constraint
:= First_Elmt
(Stored_Constraint
(Target_Type
));
3544 while Present
(Constraint
) loop
3545 Discr_Value
:= Node
(Constraint
);
3547 if Is_Entity_Name
(Discr_Value
)
3548 and then Ekind
(Entity
(Discr_Value
)) = E_Discriminant
3550 Discr
:= Corresponding_Discriminant
(Entity
(Discr_Value
));
3553 and then Scope
(Discr
) = Base_Type
(Expr_Type
)
3555 -- Parent is constrained by new discriminant. Obtain
3556 -- Value of original discriminant in expression. If the
3557 -- new discriminant has been used to constrain more than
3558 -- one of the stored discriminants, this will provide the
3559 -- required consistency check.
3562 (Make_Selected_Component
(Loc
,
3564 Duplicate_Subexpr_No_Checks
3565 (Expr
, Name_Req
=> True),
3567 Make_Identifier
(Loc
, Chars
(Discr
))),
3571 -- Discriminant of more remote ancestor ???
3576 -- Derived type definition has an explicit value for this
3577 -- stored discriminant.
3581 (Duplicate_Subexpr_No_Checks
(Discr_Value
),
3585 Next_Elmt
(Constraint
);
3588 -- Use the unconstrained expression type to retrieve the
3589 -- discriminants of the parent, and apply momentarily the
3590 -- discriminant constraint synthesized above.
3592 Set_Discriminant_Constraint
(Expr_Type
, New_Constraints
);
3593 Cond
:= Build_Discriminant_Checks
(Expr
, Expr_Type
);
3594 Set_Discriminant_Constraint
(Expr_Type
, Old_Constraints
);
3597 Make_Raise_Constraint_Error
(Loc
,
3599 Reason
=> CE_Discriminant_Check_Failed
));
3602 -- For arrays, checks are set now, but conversions are applied during
3603 -- expansion, to take into accounts changes of representation. The
3604 -- checks become range checks on the base type or length checks on the
3605 -- subtype, depending on whether the target type is unconstrained or
3606 -- constrained. Note that the range check is put on the expression of a
3607 -- type conversion, while the length check is put on the type conversion
3610 elsif Is_Array_Type
(Target_Type
) then
3611 if Is_Constrained
(Target_Type
) then
3612 Set_Do_Length_Check
(N
);
3614 Set_Do_Range_Check
(Expr
);
3617 end Apply_Type_Conversion_Checks
;
3619 ----------------------------------------------
3620 -- Apply_Universal_Integer_Attribute_Checks --
3621 ----------------------------------------------
3623 procedure Apply_Universal_Integer_Attribute_Checks
(N
: Node_Id
) is
3624 Loc
: constant Source_Ptr
:= Sloc
(N
);
3625 Typ
: constant Entity_Id
:= Etype
(N
);
3628 if Inside_A_Generic
then
3631 -- Nothing to do if checks are suppressed
3633 elsif Range_Checks_Suppressed
(Typ
)
3634 and then Overflow_Checks_Suppressed
(Typ
)
3638 -- Nothing to do if the attribute does not come from source. The
3639 -- internal attributes we generate of this type do not need checks,
3640 -- and furthermore the attempt to check them causes some circular
3641 -- elaboration orders when dealing with packed types.
3643 elsif not Comes_From_Source
(N
) then
3646 -- If the prefix is a selected component that depends on a discriminant
3647 -- the check may improperly expose a discriminant instead of using
3648 -- the bounds of the object itself. Set the type of the attribute to
3649 -- the base type of the context, so that a check will be imposed when
3650 -- needed (e.g. if the node appears as an index).
3652 elsif Nkind
(Prefix
(N
)) = N_Selected_Component
3653 and then Ekind
(Typ
) = E_Signed_Integer_Subtype
3654 and then Depends_On_Discriminant
(Scalar_Range
(Typ
))
3656 Set_Etype
(N
, Base_Type
(Typ
));
3658 -- Otherwise, replace the attribute node with a type conversion node
3659 -- whose expression is the attribute, retyped to universal integer, and
3660 -- whose subtype mark is the target type. The call to analyze this
3661 -- conversion will set range and overflow checks as required for proper
3662 -- detection of an out of range value.
3665 Set_Etype
(N
, Universal_Integer
);
3666 Set_Analyzed
(N
, True);
3669 Make_Type_Conversion
(Loc
,
3670 Subtype_Mark
=> New_Occurrence_Of
(Typ
, Loc
),
3671 Expression
=> Relocate_Node
(N
)));
3673 Analyze_And_Resolve
(N
, Typ
);
3676 end Apply_Universal_Integer_Attribute_Checks
;
3678 -------------------------------------
3679 -- Atomic_Synchronization_Disabled --
3680 -------------------------------------
3682 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3683 -- using a bogus check called Atomic_Synchronization. This is to make it
3684 -- more convenient to get exactly the same semantics as [Un]Suppress.
3686 function Atomic_Synchronization_Disabled
(E
: Entity_Id
) return Boolean is
3688 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3689 -- looks enabled, since it is never disabled.
3691 if Debug_Flag_Dot_E
then
3694 -- If debug flag d.d is set then always return True, i.e. all atomic
3695 -- sync looks disabled, since it always tests True.
3697 elsif Debug_Flag_Dot_D
then
3700 -- If entity present, then check result for that entity
3702 elsif Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
3703 return Is_Check_Suppressed
(E
, Atomic_Synchronization
);
3705 -- Otherwise result depends on current scope setting
3708 return Scope_Suppress
.Suppress
(Atomic_Synchronization
);
3710 end Atomic_Synchronization_Disabled
;
3712 -------------------------------
3713 -- Build_Discriminant_Checks --
3714 -------------------------------
3716 function Build_Discriminant_Checks
3718 T_Typ
: Entity_Id
) return Node_Id
3720 Loc
: constant Source_Ptr
:= Sloc
(N
);
3723 Disc_Ent
: Entity_Id
;
3727 function Aggregate_Discriminant_Val
(Disc
: Entity_Id
) return Node_Id
;
3729 ----------------------------------
3730 -- Aggregate_Discriminant_Value --
3731 ----------------------------------
3733 function Aggregate_Discriminant_Val
(Disc
: Entity_Id
) return Node_Id
is
3737 -- The aggregate has been normalized with named associations. We use
3738 -- the Chars field to locate the discriminant to take into account
3739 -- discriminants in derived types, which carry the same name as those
3742 Assoc
:= First
(Component_Associations
(N
));
3743 while Present
(Assoc
) loop
3744 if Chars
(First
(Choices
(Assoc
))) = Chars
(Disc
) then
3745 return Expression
(Assoc
);
3751 -- Discriminant must have been found in the loop above
3753 raise Program_Error
;
3754 end Aggregate_Discriminant_Val
;
3756 -- Start of processing for Build_Discriminant_Checks
3759 -- Loop through discriminants evolving the condition
3762 Disc
:= First_Elmt
(Discriminant_Constraint
(T_Typ
));
3764 -- For a fully private type, use the discriminants of the parent type
3766 if Is_Private_Type
(T_Typ
)
3767 and then No
(Full_View
(T_Typ
))
3769 Disc_Ent
:= First_Discriminant
(Etype
(Base_Type
(T_Typ
)));
3771 Disc_Ent
:= First_Discriminant
(T_Typ
);
3774 while Present
(Disc
) loop
3775 Dval
:= Node
(Disc
);
3777 if Nkind
(Dval
) = N_Identifier
3778 and then Ekind
(Entity
(Dval
)) = E_Discriminant
3780 Dval
:= New_Occurrence_Of
(Discriminal
(Entity
(Dval
)), Loc
);
3782 Dval
:= Duplicate_Subexpr_No_Checks
(Dval
);
3785 -- If we have an Unchecked_Union node, we can infer the discriminants
3788 if Is_Unchecked_Union
(Base_Type
(T_Typ
)) then
3790 Get_Discriminant_Value
(
3791 First_Discriminant
(T_Typ
),
3793 Stored_Constraint
(T_Typ
)));
3795 elsif Nkind
(N
) = N_Aggregate
then
3797 Duplicate_Subexpr_No_Checks
3798 (Aggregate_Discriminant_Val
(Disc_Ent
));
3802 Make_Selected_Component
(Loc
,
3804 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
3805 Selector_Name
=> Make_Identifier
(Loc
, Chars
(Disc_Ent
)));
3807 Set_Is_In_Discriminant_Check
(Dref
);
3810 Evolve_Or_Else
(Cond
,
3813 Right_Opnd
=> Dval
));
3816 Next_Discriminant
(Disc_Ent
);
3820 end Build_Discriminant_Checks
;
3826 function Check_Needed
(Nod
: Node_Id
; Check
: Check_Type
) return Boolean is
3833 function Left_Expression
(Op
: Node_Id
) return Node_Id
;
3834 -- Return the relevant expression from the left operand of the given
3835 -- short circuit form: this is LO itself, except if LO is a qualified
3836 -- expression, a type conversion, or an expression with actions, in
3837 -- which case this is Left_Expression (Expression (LO)).
3839 ---------------------
3840 -- Left_Expression --
3841 ---------------------
3843 function Left_Expression
(Op
: Node_Id
) return Node_Id
is
3844 LE
: Node_Id
:= Left_Opnd
(Op
);
3846 while Nkind_In
(LE
, N_Qualified_Expression
,
3848 N_Expression_With_Actions
)
3850 LE
:= Expression
(LE
);
3854 end Left_Expression
;
3856 -- Start of processing for Check_Needed
3859 -- Always check if not simple entity
3861 if Nkind
(Nod
) not in N_Has_Entity
3862 or else not Comes_From_Source
(Nod
)
3867 -- Look up tree for short circuit
3874 -- Done if out of subexpression (note that we allow generated stuff
3875 -- such as itype declarations in this context, to keep the loop going
3876 -- since we may well have generated such stuff in complex situations.
3877 -- Also done if no parent (probably an error condition, but no point
3878 -- in behaving nasty if we find it).
3881 or else (K
not in N_Subexpr
and then Comes_From_Source
(P
))
3885 -- Or/Or Else case, where test is part of the right operand, or is
3886 -- part of one of the actions associated with the right operand, and
3887 -- the left operand is an equality test.
3889 elsif K
= N_Op_Or
then
3890 exit when N
= Right_Opnd
(P
)
3891 and then Nkind
(Left_Expression
(P
)) = N_Op_Eq
;
3893 elsif K
= N_Or_Else
then
3894 exit when (N
= Right_Opnd
(P
)
3897 and then List_Containing
(N
) = Actions
(P
)))
3898 and then Nkind
(Left_Expression
(P
)) = N_Op_Eq
;
3900 -- Similar test for the And/And then case, where the left operand
3901 -- is an inequality test.
3903 elsif K
= N_Op_And
then
3904 exit when N
= Right_Opnd
(P
)
3905 and then Nkind
(Left_Expression
(P
)) = N_Op_Ne
;
3907 elsif K
= N_And_Then
then
3908 exit when (N
= Right_Opnd
(P
)
3911 and then List_Containing
(N
) = Actions
(P
)))
3912 and then Nkind
(Left_Expression
(P
)) = N_Op_Ne
;
3918 -- If we fall through the loop, then we have a conditional with an
3919 -- appropriate test as its left operand, so look further.
3921 L
:= Left_Expression
(P
);
3923 -- L is an "=" or "/=" operator: extract its operands
3925 R
:= Right_Opnd
(L
);
3928 -- Left operand of test must match original variable
3930 if Nkind
(L
) not in N_Has_Entity
or else Entity
(L
) /= Entity
(Nod
) then
3934 -- Right operand of test must be key value (zero or null)
3937 when Access_Check
=>
3938 if not Known_Null
(R
) then
3942 when Division_Check
=>
3943 if not Compile_Time_Known_Value
(R
)
3944 or else Expr_Value
(R
) /= Uint_0
3950 raise Program_Error
;
3953 -- Here we have the optimizable case, warn if not short-circuited
3955 if K
= N_Op_And
or else K
= N_Op_Or
then
3956 Error_Msg_Warn
:= SPARK_Mode
/= On
;
3959 when Access_Check
=>
3960 if GNATprove_Mode
then
3962 ("Constraint_Error might have been raised (access check)",
3966 ("Constraint_Error may be raised (access check)??",
3970 when Division_Check
=>
3971 if GNATprove_Mode
then
3973 ("Constraint_Error might have been raised (zero divide)",
3977 ("Constraint_Error may be raised (zero divide)??",
3982 raise Program_Error
;
3985 if K
= N_Op_And
then
3986 Error_Msg_N
-- CODEFIX
3987 ("use `AND THEN` instead of AND??", P
);
3989 Error_Msg_N
-- CODEFIX
3990 ("use `OR ELSE` instead of OR??", P
);
3993 -- If not short-circuited, we need the check
3997 -- If short-circuited, we can omit the check
4004 -----------------------------------
4005 -- Check_Valid_Lvalue_Subscripts --
4006 -----------------------------------
4008 procedure Check_Valid_Lvalue_Subscripts
(Expr
: Node_Id
) is
4010 -- Skip this if range checks are suppressed
4012 if Range_Checks_Suppressed
(Etype
(Expr
)) then
4015 -- Only do this check for expressions that come from source. We assume
4016 -- that expander generated assignments explicitly include any necessary
4017 -- checks. Note that this is not just an optimization, it avoids
4018 -- infinite recursions.
4020 elsif not Comes_From_Source
(Expr
) then
4023 -- For a selected component, check the prefix
4025 elsif Nkind
(Expr
) = N_Selected_Component
then
4026 Check_Valid_Lvalue_Subscripts
(Prefix
(Expr
));
4029 -- Case of indexed component
4031 elsif Nkind
(Expr
) = N_Indexed_Component
then
4032 Apply_Subscript_Validity_Checks
(Expr
);
4034 -- Prefix may itself be or contain an indexed component, and these
4035 -- subscripts need checking as well.
4037 Check_Valid_Lvalue_Subscripts
(Prefix
(Expr
));
4039 end Check_Valid_Lvalue_Subscripts
;
4041 ----------------------------------
4042 -- Null_Exclusion_Static_Checks --
4043 ----------------------------------
4045 procedure Null_Exclusion_Static_Checks
4047 Comp
: Node_Id
:= Empty
;
4048 Array_Comp
: Boolean := False)
4050 Has_Null
: constant Boolean := Has_Null_Exclusion
(N
);
4051 Kind
: constant Node_Kind
:= Nkind
(N
);
4052 Error_Nod
: Node_Id
;
4058 (Nkind_In
(Kind
, N_Component_Declaration
,
4059 N_Discriminant_Specification
,
4060 N_Function_Specification
,
4061 N_Object_Declaration
,
4062 N_Parameter_Specification
));
4064 if Kind
= N_Function_Specification
then
4065 Typ
:= Etype
(Defining_Entity
(N
));
4067 Typ
:= Etype
(Defining_Identifier
(N
));
4071 when N_Component_Declaration
=>
4072 if Present
(Access_Definition
(Component_Definition
(N
))) then
4073 Error_Nod
:= Component_Definition
(N
);
4075 Error_Nod
:= Subtype_Indication
(Component_Definition
(N
));
4078 when N_Discriminant_Specification
=>
4079 Error_Nod
:= Discriminant_Type
(N
);
4081 when N_Function_Specification
=>
4082 Error_Nod
:= Result_Definition
(N
);
4084 when N_Object_Declaration
=>
4085 Error_Nod
:= Object_Definition
(N
);
4087 when N_Parameter_Specification
=>
4088 Error_Nod
:= Parameter_Type
(N
);
4091 raise Program_Error
;
4096 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4097 -- applied to an access [sub]type.
4099 if not Is_Access_Type
(Typ
) then
4101 ("`NOT NULL` allowed only for an access type", Error_Nod
);
4103 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4104 -- be applied to a [sub]type that does not exclude null already.
4106 elsif Can_Never_Be_Null
(Typ
) and then Comes_From_Source
(Typ
) then
4108 ("`NOT NULL` not allowed (& already excludes null)",
4113 -- Check that null-excluding objects are always initialized, except for
4114 -- deferred constants, for which the expression will appear in the full
4117 if Kind
= N_Object_Declaration
4118 and then No
(Expression
(N
))
4119 and then not Constant_Present
(N
)
4120 and then not No_Initialization
(N
)
4122 if Present
(Comp
) then
4124 -- Specialize the warning message to indicate that we are dealing
4125 -- with an uninitialized composite object that has a defaulted
4126 -- null-excluding component.
4128 Error_Msg_Name_1
:= Chars
(Defining_Identifier
(Comp
));
4129 Error_Msg_Name_2
:= Chars
(Defining_Identifier
(N
));
4132 (Compile_Time_Constraint_Error
4135 "(Ada 2005) null-excluding component % of object % must "
4136 & "be initialized??",
4137 Ent
=> Defining_Identifier
(Comp
)));
4139 -- This is a case of an array with null-excluding components, so
4140 -- indicate that in the warning.
4142 elsif Array_Comp
then
4144 (Compile_Time_Constraint_Error
4147 "(Ada 2005) null-excluding array components must "
4148 & "be initialized??",
4149 Ent
=> Defining_Identifier
(N
)));
4151 -- Normal case of object of a null-excluding access type
4154 -- Add an expression that assigns null. This node is needed by
4155 -- Apply_Compile_Time_Constraint_Error, which will replace this
4156 -- with a Constraint_Error node.
4158 Set_Expression
(N
, Make_Null
(Sloc
(N
)));
4159 Set_Etype
(Expression
(N
), Etype
(Defining_Identifier
(N
)));
4161 Apply_Compile_Time_Constraint_Error
4162 (N
=> Expression
(N
),
4164 "(Ada 2005) null-excluding objects must be initialized??",
4165 Reason
=> CE_Null_Not_Allowed
);
4169 -- Check that a null-excluding component, formal or object is not being
4170 -- assigned a null value. Otherwise generate a warning message and
4171 -- replace Expression (N) by an N_Constraint_Error node.
4173 if Kind
/= N_Function_Specification
then
4174 Expr
:= Expression
(N
);
4176 if Present
(Expr
) and then Known_Null
(Expr
) then
4178 when N_Component_Declaration
4179 | N_Discriminant_Specification
4181 Apply_Compile_Time_Constraint_Error
4184 "(Ada 2005) null not allowed in null-excluding "
4186 Reason
=> CE_Null_Not_Allowed
);
4188 when N_Object_Declaration
=>
4189 Apply_Compile_Time_Constraint_Error
4192 "(Ada 2005) null not allowed in null-excluding "
4194 Reason
=> CE_Null_Not_Allowed
);
4196 when N_Parameter_Specification
=>
4197 Apply_Compile_Time_Constraint_Error
4200 "(Ada 2005) null not allowed in null-excluding "
4202 Reason
=> CE_Null_Not_Allowed
);
4209 end Null_Exclusion_Static_Checks
;
4211 ----------------------------------
4212 -- Conditional_Statements_Begin --
4213 ----------------------------------
4215 procedure Conditional_Statements_Begin
is
4217 Saved_Checks_TOS
:= Saved_Checks_TOS
+ 1;
4219 -- If stack overflows, kill all checks, that way we know to simply reset
4220 -- the number of saved checks to zero on return. This should never occur
4223 if Saved_Checks_TOS
> Saved_Checks_Stack
'Last then
4226 -- In the normal case, we just make a new stack entry saving the current
4227 -- number of saved checks for a later restore.
4230 Saved_Checks_Stack
(Saved_Checks_TOS
) := Num_Saved_Checks
;
4232 if Debug_Flag_CC
then
4233 w
("Conditional_Statements_Begin: Num_Saved_Checks = ",
4237 end Conditional_Statements_Begin
;
4239 --------------------------------
4240 -- Conditional_Statements_End --
4241 --------------------------------
4243 procedure Conditional_Statements_End
is
4245 pragma Assert
(Saved_Checks_TOS
> 0);
4247 -- If the saved checks stack overflowed, then we killed all checks, so
4248 -- setting the number of saved checks back to zero is correct. This
4249 -- should never occur in practice.
4251 if Saved_Checks_TOS
> Saved_Checks_Stack
'Last then
4252 Num_Saved_Checks
:= 0;
4254 -- In the normal case, restore the number of saved checks from the top
4258 Num_Saved_Checks
:= Saved_Checks_Stack
(Saved_Checks_TOS
);
4260 if Debug_Flag_CC
then
4261 w
("Conditional_Statements_End: Num_Saved_Checks = ",
4266 Saved_Checks_TOS
:= Saved_Checks_TOS
- 1;
4267 end Conditional_Statements_End
;
4269 -------------------------
4270 -- Convert_From_Bignum --
4271 -------------------------
4273 function Convert_From_Bignum
(N
: Node_Id
) return Node_Id
is
4274 Loc
: constant Source_Ptr
:= Sloc
(N
);
4277 pragma Assert
(Is_RTE
(Etype
(N
), RE_Bignum
));
4279 -- Construct call From Bignum
4282 Make_Function_Call
(Loc
,
4284 New_Occurrence_Of
(RTE
(RE_From_Bignum
), Loc
),
4285 Parameter_Associations
=> New_List
(Relocate_Node
(N
)));
4286 end Convert_From_Bignum
;
4288 -----------------------
4289 -- Convert_To_Bignum --
4290 -----------------------
4292 function Convert_To_Bignum
(N
: Node_Id
) return Node_Id
is
4293 Loc
: constant Source_Ptr
:= Sloc
(N
);
4296 -- Nothing to do if Bignum already except call Relocate_Node
4298 if Is_RTE
(Etype
(N
), RE_Bignum
) then
4299 return Relocate_Node
(N
);
4301 -- Otherwise construct call to To_Bignum, converting the operand to the
4302 -- required Long_Long_Integer form.
4305 pragma Assert
(Is_Signed_Integer_Type
(Etype
(N
)));
4307 Make_Function_Call
(Loc
,
4309 New_Occurrence_Of
(RTE
(RE_To_Bignum
), Loc
),
4310 Parameter_Associations
=> New_List
(
4311 Convert_To
(Standard_Long_Long_Integer
, Relocate_Node
(N
))));
4313 end Convert_To_Bignum
;
4315 ---------------------
4316 -- Determine_Range --
4317 ---------------------
4319 Cache_Size
: constant := 2 ** 10;
4320 type Cache_Index
is range 0 .. Cache_Size
- 1;
4321 -- Determine size of below cache (power of 2 is more efficient)
4323 Determine_Range_Cache_N
: array (Cache_Index
) of Node_Id
;
4324 Determine_Range_Cache_V
: array (Cache_Index
) of Boolean;
4325 Determine_Range_Cache_Lo
: array (Cache_Index
) of Uint
;
4326 Determine_Range_Cache_Hi
: array (Cache_Index
) of Uint
;
4327 Determine_Range_Cache_Lo_R
: array (Cache_Index
) of Ureal
;
4328 Determine_Range_Cache_Hi_R
: array (Cache_Index
) of Ureal
;
4329 -- The above arrays are used to implement a small direct cache for
4330 -- Determine_Range and Determine_Range_R calls. Because of the way these
4331 -- subprograms recursively traces subexpressions, and because overflow
4332 -- checking calls the routine on the way up the tree, a quadratic behavior
4333 -- can otherwise be encountered in large expressions. The cache entry for
4334 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4335 -- by checking the actual node value stored there. The Range_Cache_V array
4336 -- records the setting of Assume_Valid for the cache entry.
4338 procedure Determine_Range
4343 Assume_Valid
: Boolean := False)
4345 Typ
: Entity_Id
:= Etype
(N
);
4346 -- Type to use, may get reset to base type for possibly invalid entity
4350 -- Lo and Hi bounds of left operand
4354 -- Lo and Hi bounds of right (or only) operand
4357 -- Temp variable used to hold a bound node
4360 -- High bound of base type of expression
4364 -- Refined values for low and high bounds, after tightening
4367 -- Used in lower level calls to indicate if call succeeded
4369 Cindex
: Cache_Index
;
4370 -- Used to search cache
4375 function OK_Operands
return Boolean;
4376 -- Used for binary operators. Determines the ranges of the left and
4377 -- right operands, and if they are both OK, returns True, and puts
4378 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4384 function OK_Operands
return Boolean is
4387 (Left_Opnd
(N
), OK1
, Lo_Left
, Hi_Left
, Assume_Valid
);
4394 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
4398 -- Start of processing for Determine_Range
4401 -- Prevent junk warnings by initializing range variables
4408 -- For temporary constants internally generated to remove side effects
4409 -- we must use the corresponding expression to determine the range of
4410 -- the expression. But note that the expander can also generate
4411 -- constants in other cases, including deferred constants.
4413 if Is_Entity_Name
(N
)
4414 and then Nkind
(Parent
(Entity
(N
))) = N_Object_Declaration
4415 and then Ekind
(Entity
(N
)) = E_Constant
4416 and then Is_Internal_Name
(Chars
(Entity
(N
)))
4418 if Present
(Expression
(Parent
(Entity
(N
)))) then
4420 (Expression
(Parent
(Entity
(N
))), OK
, Lo
, Hi
, Assume_Valid
);
4422 elsif Present
(Full_View
(Entity
(N
))) then
4424 (Expression
(Parent
(Full_View
(Entity
(N
)))),
4425 OK
, Lo
, Hi
, Assume_Valid
);
4433 -- If type is not defined, we can't determine its range
4437 -- We don't deal with anything except discrete types
4439 or else not Is_Discrete_Type
(Typ
)
4441 -- Ignore type for which an error has been posted, since range in
4442 -- this case may well be a bogosity deriving from the error. Also
4443 -- ignore if error posted on the reference node.
4445 or else Error_Posted
(N
) or else Error_Posted
(Typ
)
4451 -- For all other cases, we can determine the range
4455 -- If value is compile time known, then the possible range is the one
4456 -- value that we know this expression definitely has.
4458 if Compile_Time_Known_Value
(N
) then
4459 Lo
:= Expr_Value
(N
);
4464 -- Return if already in the cache
4466 Cindex
:= Cache_Index
(N
mod Cache_Size
);
4468 if Determine_Range_Cache_N
(Cindex
) = N
4470 Determine_Range_Cache_V
(Cindex
) = Assume_Valid
4472 Lo
:= Determine_Range_Cache_Lo
(Cindex
);
4473 Hi
:= Determine_Range_Cache_Hi
(Cindex
);
4477 -- Otherwise, start by finding the bounds of the type of the expression,
4478 -- the value cannot be outside this range (if it is, then we have an
4479 -- overflow situation, which is a separate check, we are talking here
4480 -- only about the expression value).
4482 -- First a check, never try to find the bounds of a generic type, since
4483 -- these bounds are always junk values, and it is only valid to look at
4484 -- the bounds in an instance.
4486 if Is_Generic_Type
(Typ
) then
4491 -- First step, change to use base type unless we know the value is valid
4493 if (Is_Entity_Name
(N
) and then Is_Known_Valid
(Entity
(N
)))
4494 or else Assume_No_Invalid_Values
4495 or else Assume_Valid
4499 Typ
:= Underlying_Type
(Base_Type
(Typ
));
4502 -- Retrieve the base type. Handle the case where the base type is a
4503 -- private enumeration type.
4505 Btyp
:= Base_Type
(Typ
);
4507 if Is_Private_Type
(Btyp
) and then Present
(Full_View
(Btyp
)) then
4508 Btyp
:= Full_View
(Btyp
);
4511 -- We use the actual bound unless it is dynamic, in which case use the
4512 -- corresponding base type bound if possible. If we can't get a bound
4513 -- then we figure we can't determine the range (a peculiar case, that
4514 -- perhaps cannot happen, but there is no point in bombing in this
4515 -- optimization circuit.
4517 -- First the low bound
4519 Bound
:= Type_Low_Bound
(Typ
);
4521 if Compile_Time_Known_Value
(Bound
) then
4522 Lo
:= Expr_Value
(Bound
);
4524 elsif Compile_Time_Known_Value
(Type_Low_Bound
(Btyp
)) then
4525 Lo
:= Expr_Value
(Type_Low_Bound
(Btyp
));
4532 -- Now the high bound
4534 Bound
:= Type_High_Bound
(Typ
);
4536 -- We need the high bound of the base type later on, and this should
4537 -- always be compile time known. Again, it is not clear that this
4538 -- can ever be false, but no point in bombing.
4540 if Compile_Time_Known_Value
(Type_High_Bound
(Btyp
)) then
4541 Hbound
:= Expr_Value
(Type_High_Bound
(Btyp
));
4549 -- If we have a static subtype, then that may have a tighter bound so
4550 -- use the upper bound of the subtype instead in this case.
4552 if Compile_Time_Known_Value
(Bound
) then
4553 Hi
:= Expr_Value
(Bound
);
4556 -- We may be able to refine this value in certain situations. If any
4557 -- refinement is possible, then Lor and Hir are set to possibly tighter
4558 -- bounds, and OK1 is set to True.
4562 -- For unary plus, result is limited by range of operand
4566 (Right_Opnd
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
4568 -- For unary minus, determine range of operand, and negate it
4572 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
4579 -- For binary addition, get range of each operand and do the
4580 -- addition to get the result range.
4584 Lor
:= Lo_Left
+ Lo_Right
;
4585 Hir
:= Hi_Left
+ Hi_Right
;
4588 -- Division is tricky. The only case we consider is where the right
4589 -- operand is a positive constant, and in this case we simply divide
4590 -- the bounds of the left operand
4594 if Lo_Right
= Hi_Right
4595 and then Lo_Right
> 0
4597 Lor
:= Lo_Left
/ Lo_Right
;
4598 Hir
:= Hi_Left
/ Lo_Right
;
4604 -- For binary subtraction, get range of each operand and do the worst
4605 -- case subtraction to get the result range.
4607 when N_Op_Subtract
=>
4609 Lor
:= Lo_Left
- Hi_Right
;
4610 Hir
:= Hi_Left
- Lo_Right
;
4613 -- For MOD, if right operand is a positive constant, then result must
4614 -- be in the allowable range of mod results.
4618 if Lo_Right
= Hi_Right
4619 and then Lo_Right
/= 0
4621 if Lo_Right
> 0 then
4623 Hir
:= Lo_Right
- 1;
4625 else -- Lo_Right < 0
4626 Lor
:= Lo_Right
+ 1;
4635 -- For REM, if right operand is a positive constant, then result must
4636 -- be in the allowable range of mod results.
4640 if Lo_Right
= Hi_Right
and then Lo_Right
/= 0 then
4642 Dval
: constant Uint
:= (abs Lo_Right
) - 1;
4645 -- The sign of the result depends on the sign of the
4646 -- dividend (but not on the sign of the divisor, hence
4647 -- the abs operation above).
4667 -- Attribute reference cases
4669 when N_Attribute_Reference
=>
4670 case Attribute_Name
(N
) is
4672 -- For Pos/Val attributes, we can refine the range using the
4673 -- possible range of values of the attribute expression.
4679 (First
(Expressions
(N
)), OK1
, Lor
, Hir
, Assume_Valid
);
4681 -- For Length attribute, use the bounds of the corresponding
4682 -- index type to refine the range.
4686 Atyp
: Entity_Id
:= Etype
(Prefix
(N
));
4694 if Is_Access_Type
(Atyp
) then
4695 Atyp
:= Designated_Type
(Atyp
);
4698 -- For string literal, we know exact value
4700 if Ekind
(Atyp
) = E_String_Literal_Subtype
then
4702 Lo
:= String_Literal_Length
(Atyp
);
4703 Hi
:= String_Literal_Length
(Atyp
);
4707 -- Otherwise check for expression given
4709 if No
(Expressions
(N
)) then
4713 UI_To_Int
(Expr_Value
(First
(Expressions
(N
))));
4716 Indx
:= First_Index
(Atyp
);
4717 for J
in 2 .. Inum
loop
4718 Indx
:= Next_Index
(Indx
);
4721 -- If the index type is a formal type or derived from
4722 -- one, the bounds are not static.
4724 if Is_Generic_Type
(Root_Type
(Etype
(Indx
))) then
4730 (Type_Low_Bound
(Etype
(Indx
)), OK1
, LL
, LU
,
4735 (Type_High_Bound
(Etype
(Indx
)), OK1
, UL
, UU
,
4740 -- The maximum value for Length is the biggest
4741 -- possible gap between the values of the bounds.
4742 -- But of course, this value cannot be negative.
4744 Hir
:= UI_Max
(Uint_0
, UU
- LL
+ 1);
4746 -- For constrained arrays, the minimum value for
4747 -- Length is taken from the actual value of the
4748 -- bounds, since the index will be exactly of this
4751 if Is_Constrained
(Atyp
) then
4752 Lor
:= UI_Max
(Uint_0
, UL
- LU
+ 1);
4754 -- For an unconstrained array, the minimum value
4755 -- for length is always zero.
4764 -- No special handling for other attributes
4765 -- Probably more opportunities exist here???
4772 when N_Type_Conversion
=>
4774 -- For type conversion from one discrete type to another, we can
4775 -- refine the range using the converted value.
4777 if Is_Discrete_Type
(Etype
(Expression
(N
))) then
4778 Determine_Range
(Expression
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
4780 -- When converting a float to an integer type, determine the range
4781 -- in real first, and then convert the bounds using UR_To_Uint
4782 -- which correctly rounds away from zero when half way between two
4783 -- integers, as required by normal Ada 95 rounding semantics. It
4784 -- is only possible because analysis in GNATprove rules out the
4785 -- possibility of a NaN or infinite value.
4787 elsif GNATprove_Mode
4788 and then Is_Floating_Point_Type
(Etype
(Expression
(N
)))
4791 Lor_Real
, Hir_Real
: Ureal
;
4793 Determine_Range_R
(Expression
(N
), OK1
, Lor_Real
, Hir_Real
,
4797 Lor
:= UR_To_Uint
(Lor_Real
);
4798 Hir
:= UR_To_Uint
(Hir_Real
);
4806 -- Nothing special to do for all other expression kinds
4814 -- At this stage, if OK1 is true, then we know that the actual result of
4815 -- the computed expression is in the range Lor .. Hir. We can use this
4816 -- to restrict the possible range of results.
4820 -- If the refined value of the low bound is greater than the type
4821 -- low bound, then reset it to the more restrictive value. However,
4822 -- we do NOT do this for the case of a modular type where the
4823 -- possible upper bound on the value is above the base type high
4824 -- bound, because that means the result could wrap.
4827 and then not (Is_Modular_Integer_Type
(Typ
) and then Hir
> Hbound
)
4832 -- Similarly, if the refined value of the high bound is less than the
4833 -- value so far, then reset it to the more restrictive value. Again,
4834 -- we do not do this if the refined low bound is negative for a
4835 -- modular type, since this would wrap.
4838 and then not (Is_Modular_Integer_Type
(Typ
) and then Lor
< Uint_0
)
4844 -- Set cache entry for future call and we are all done
4846 Determine_Range_Cache_N
(Cindex
) := N
;
4847 Determine_Range_Cache_V
(Cindex
) := Assume_Valid
;
4848 Determine_Range_Cache_Lo
(Cindex
) := Lo
;
4849 Determine_Range_Cache_Hi
(Cindex
) := Hi
;
4852 -- If any exception occurs, it means that we have some bug in the compiler,
4853 -- possibly triggered by a previous error, or by some unforeseen peculiar
4854 -- occurrence. However, this is only an optimization attempt, so there is
4855 -- really no point in crashing the compiler. Instead we just decide, too
4856 -- bad, we can't figure out a range in this case after all.
4861 -- Debug flag K disables this behavior (useful for debugging)
4863 if Debug_Flag_K
then
4871 end Determine_Range
;
4873 -----------------------
4874 -- Determine_Range_R --
4875 -----------------------
4877 procedure Determine_Range_R
4882 Assume_Valid
: Boolean := False)
4884 Typ
: Entity_Id
:= Etype
(N
);
4885 -- Type to use, may get reset to base type for possibly invalid entity
4889 -- Lo and Hi bounds of left operand
4893 -- Lo and Hi bounds of right (or only) operand
4896 -- Temp variable used to hold a bound node
4899 -- High bound of base type of expression
4903 -- Refined values for low and high bounds, after tightening
4906 -- Used in lower level calls to indicate if call succeeded
4908 Cindex
: Cache_Index
;
4909 -- Used to search cache
4914 function OK_Operands
return Boolean;
4915 -- Used for binary operators. Determines the ranges of the left and
4916 -- right operands, and if they are both OK, returns True, and puts
4917 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4919 function Round_Machine
(B
: Ureal
) return Ureal
;
4920 -- B is a real bound. Round it using mode Round_Even.
4926 function OK_Operands
return Boolean is
4929 (Left_Opnd
(N
), OK1
, Lo_Left
, Hi_Left
, Assume_Valid
);
4936 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
4944 function Round_Machine
(B
: Ureal
) return Ureal
is
4946 return Machine
(Typ
, B
, Round_Even
, N
);
4949 -- Start of processing for Determine_Range_R
4952 -- Prevent junk warnings by initializing range variables
4959 -- For temporary constants internally generated to remove side effects
4960 -- we must use the corresponding expression to determine the range of
4961 -- the expression. But note that the expander can also generate
4962 -- constants in other cases, including deferred constants.
4964 if Is_Entity_Name
(N
)
4965 and then Nkind
(Parent
(Entity
(N
))) = N_Object_Declaration
4966 and then Ekind
(Entity
(N
)) = E_Constant
4967 and then Is_Internal_Name
(Chars
(Entity
(N
)))
4969 if Present
(Expression
(Parent
(Entity
(N
)))) then
4971 (Expression
(Parent
(Entity
(N
))), OK
, Lo
, Hi
, Assume_Valid
);
4973 elsif Present
(Full_View
(Entity
(N
))) then
4975 (Expression
(Parent
(Full_View
(Entity
(N
)))),
4976 OK
, Lo
, Hi
, Assume_Valid
);
4985 -- If type is not defined, we can't determine its range
4989 -- We don't deal with anything except IEEE floating-point types
4991 or else not Is_Floating_Point_Type
(Typ
)
4992 or else Float_Rep
(Typ
) /= IEEE_Binary
4994 -- Ignore type for which an error has been posted, since range in
4995 -- this case may well be a bogosity deriving from the error. Also
4996 -- ignore if error posted on the reference node.
4998 or else Error_Posted
(N
) or else Error_Posted
(Typ
)
5004 -- For all other cases, we can determine the range
5008 -- If value is compile time known, then the possible range is the one
5009 -- value that we know this expression definitely has.
5011 if Compile_Time_Known_Value
(N
) then
5012 Lo
:= Expr_Value_R
(N
);
5017 -- Return if already in the cache
5019 Cindex
:= Cache_Index
(N
mod Cache_Size
);
5021 if Determine_Range_Cache_N
(Cindex
) = N
5023 Determine_Range_Cache_V
(Cindex
) = Assume_Valid
5025 Lo
:= Determine_Range_Cache_Lo_R
(Cindex
);
5026 Hi
:= Determine_Range_Cache_Hi_R
(Cindex
);
5030 -- Otherwise, start by finding the bounds of the type of the expression,
5031 -- the value cannot be outside this range (if it is, then we have an
5032 -- overflow situation, which is a separate check, we are talking here
5033 -- only about the expression value).
5035 -- First a check, never try to find the bounds of a generic type, since
5036 -- these bounds are always junk values, and it is only valid to look at
5037 -- the bounds in an instance.
5039 if Is_Generic_Type
(Typ
) then
5044 -- First step, change to use base type unless we know the value is valid
5046 if (Is_Entity_Name
(N
) and then Is_Known_Valid
(Entity
(N
)))
5047 or else Assume_No_Invalid_Values
5048 or else Assume_Valid
5052 Typ
:= Underlying_Type
(Base_Type
(Typ
));
5055 -- Retrieve the base type. Handle the case where the base type is a
5058 Btyp
:= Base_Type
(Typ
);
5060 if Is_Private_Type
(Btyp
) and then Present
(Full_View
(Btyp
)) then
5061 Btyp
:= Full_View
(Btyp
);
5064 -- We use the actual bound unless it is dynamic, in which case use the
5065 -- corresponding base type bound if possible. If we can't get a bound
5066 -- then we figure we can't determine the range (a peculiar case, that
5067 -- perhaps cannot happen, but there is no point in bombing in this
5068 -- optimization circuit).
5070 -- First the low bound
5072 Bound
:= Type_Low_Bound
(Typ
);
5074 if Compile_Time_Known_Value
(Bound
) then
5075 Lo
:= Expr_Value_R
(Bound
);
5077 elsif Compile_Time_Known_Value
(Type_Low_Bound
(Btyp
)) then
5078 Lo
:= Expr_Value_R
(Type_Low_Bound
(Btyp
));
5085 -- Now the high bound
5087 Bound
:= Type_High_Bound
(Typ
);
5089 -- We need the high bound of the base type later on, and this should
5090 -- always be compile time known. Again, it is not clear that this
5091 -- can ever be false, but no point in bombing.
5093 if Compile_Time_Known_Value
(Type_High_Bound
(Btyp
)) then
5094 Hbound
:= Expr_Value_R
(Type_High_Bound
(Btyp
));
5102 -- If we have a static subtype, then that may have a tighter bound so
5103 -- use the upper bound of the subtype instead in this case.
5105 if Compile_Time_Known_Value
(Bound
) then
5106 Hi
:= Expr_Value_R
(Bound
);
5109 -- We may be able to refine this value in certain situations. If any
5110 -- refinement is possible, then Lor and Hir are set to possibly tighter
5111 -- bounds, and OK1 is set to True.
5115 -- For unary plus, result is limited by range of operand
5119 (Right_Opnd
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
5121 -- For unary minus, determine range of operand, and negate it
5125 (Right_Opnd
(N
), OK1
, Lo_Right
, Hi_Right
, Assume_Valid
);
5132 -- For binary addition, get range of each operand and do the
5133 -- addition to get the result range.
5137 Lor
:= Round_Machine
(Lo_Left
+ Lo_Right
);
5138 Hir
:= Round_Machine
(Hi_Left
+ Hi_Right
);
5141 -- For binary subtraction, get range of each operand and do the worst
5142 -- case subtraction to get the result range.
5144 when N_Op_Subtract
=>
5146 Lor
:= Round_Machine
(Lo_Left
- Hi_Right
);
5147 Hir
:= Round_Machine
(Hi_Left
- Lo_Right
);
5150 -- For multiplication, get range of each operand and do the
5151 -- four multiplications to get the result range.
5153 when N_Op_Multiply
=>
5156 M1
: constant Ureal
:= Round_Machine
(Lo_Left
* Lo_Right
);
5157 M2
: constant Ureal
:= Round_Machine
(Lo_Left
* Hi_Right
);
5158 M3
: constant Ureal
:= Round_Machine
(Hi_Left
* Lo_Right
);
5159 M4
: constant Ureal
:= Round_Machine
(Hi_Left
* Hi_Right
);
5162 Lor
:= UR_Min
(UR_Min
(M1
, M2
), UR_Min
(M3
, M4
));
5163 Hir
:= UR_Max
(UR_Max
(M1
, M2
), UR_Max
(M3
, M4
));
5167 -- For division, consider separately the cases where the right
5168 -- operand is positive or negative. Otherwise, the right operand
5169 -- can be arbitrarily close to zero, so the result is likely to
5170 -- be unbounded in one direction, do not attempt to compute it.
5175 -- Right operand is positive
5177 if Lo_Right
> Ureal_0
then
5179 -- If the low bound of the left operand is negative, obtain
5180 -- the overall low bound by dividing it by the smallest
5181 -- value of the right operand, and otherwise by the largest
5182 -- value of the right operand.
5184 if Lo_Left
< Ureal_0
then
5185 Lor
:= Round_Machine
(Lo_Left
/ Lo_Right
);
5187 Lor
:= Round_Machine
(Lo_Left
/ Hi_Right
);
5190 -- If the high bound of the left operand is negative, obtain
5191 -- the overall high bound by dividing it by the largest
5192 -- value of the right operand, and otherwise by the
5193 -- smallest value of the right operand.
5195 if Hi_Left
< Ureal_0
then
5196 Hir
:= Round_Machine
(Hi_Left
/ Hi_Right
);
5198 Hir
:= Round_Machine
(Hi_Left
/ Lo_Right
);
5201 -- Right operand is negative
5203 elsif Hi_Right
< Ureal_0
then
5205 -- If the low bound of the left operand is negative, obtain
5206 -- the overall low bound by dividing it by the largest
5207 -- value of the right operand, and otherwise by the smallest
5208 -- value of the right operand.
5210 if Lo_Left
< Ureal_0
then
5211 Lor
:= Round_Machine
(Lo_Left
/ Hi_Right
);
5213 Lor
:= Round_Machine
(Lo_Left
/ Lo_Right
);
5216 -- If the high bound of the left operand is negative, obtain
5217 -- the overall high bound by dividing it by the smallest
5218 -- value of the right operand, and otherwise by the
5219 -- largest value of the right operand.
5221 if Hi_Left
< Ureal_0
then
5222 Hir
:= Round_Machine
(Hi_Left
/ Lo_Right
);
5224 Hir
:= Round_Machine
(Hi_Left
/ Hi_Right
);
5232 when N_Type_Conversion
=>
5234 -- For type conversion from one floating-point type to another, we
5235 -- can refine the range using the converted value.
5237 if Is_Floating_Point_Type
(Etype
(Expression
(N
))) then
5238 Determine_Range_R
(Expression
(N
), OK1
, Lor
, Hir
, Assume_Valid
);
5240 -- When converting an integer to a floating-point type, determine
5241 -- the range in integer first, and then convert the bounds.
5243 elsif Is_Discrete_Type
(Etype
(Expression
(N
))) then
5250 (Expression
(N
), OK1
, Lor_Int
, Hir_Int
, Assume_Valid
);
5253 Lor
:= Round_Machine
(UR_From_Uint
(Lor_Int
));
5254 Hir
:= Round_Machine
(UR_From_Uint
(Hir_Int
));
5262 -- Nothing special to do for all other expression kinds
5270 -- At this stage, if OK1 is true, then we know that the actual result of
5271 -- the computed expression is in the range Lor .. Hir. We can use this
5272 -- to restrict the possible range of results.
5276 -- If the refined value of the low bound is greater than the type
5277 -- low bound, then reset it to the more restrictive value.
5283 -- Similarly, if the refined value of the high bound is less than the
5284 -- value so far, then reset it to the more restrictive value.
5291 -- Set cache entry for future call and we are all done
5293 Determine_Range_Cache_N
(Cindex
) := N
;
5294 Determine_Range_Cache_V
(Cindex
) := Assume_Valid
;
5295 Determine_Range_Cache_Lo_R
(Cindex
) := Lo
;
5296 Determine_Range_Cache_Hi_R
(Cindex
) := Hi
;
5299 -- If any exception occurs, it means that we have some bug in the compiler,
5300 -- possibly triggered by a previous error, or by some unforeseen peculiar
5301 -- occurrence. However, this is only an optimization attempt, so there is
5302 -- really no point in crashing the compiler. Instead we just decide, too
5303 -- bad, we can't figure out a range in this case after all.
5308 -- Debug flag K disables this behavior (useful for debugging)
5310 if Debug_Flag_K
then
5318 end Determine_Range_R
;
5320 ------------------------------------
5321 -- Discriminant_Checks_Suppressed --
5322 ------------------------------------
5324 function Discriminant_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
5327 if Is_Unchecked_Union
(E
) then
5329 elsif Checks_May_Be_Suppressed
(E
) then
5330 return Is_Check_Suppressed
(E
, Discriminant_Check
);
5334 return Scope_Suppress
.Suppress
(Discriminant_Check
);
5335 end Discriminant_Checks_Suppressed
;
5337 --------------------------------
5338 -- Division_Checks_Suppressed --
5339 --------------------------------
5341 function Division_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
5343 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
5344 return Is_Check_Suppressed
(E
, Division_Check
);
5346 return Scope_Suppress
.Suppress
(Division_Check
);
5348 end Division_Checks_Suppressed
;
5350 --------------------------------------
5351 -- Duplicated_Tag_Checks_Suppressed --
5352 --------------------------------------
5354 function Duplicated_Tag_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
5356 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
5357 return Is_Check_Suppressed
(E
, Duplicated_Tag_Check
);
5359 return Scope_Suppress
.Suppress
(Duplicated_Tag_Check
);
5361 end Duplicated_Tag_Checks_Suppressed
;
5363 -----------------------------------
5364 -- Elaboration_Checks_Suppressed --
5365 -----------------------------------
5367 function Elaboration_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
5369 -- The complication in this routine is that if we are in the dynamic
5370 -- model of elaboration, we also check All_Checks, since All_Checks
5371 -- does not set Elaboration_Check explicitly.
5374 if Kill_Elaboration_Checks
(E
) then
5377 elsif Checks_May_Be_Suppressed
(E
) then
5378 if Is_Check_Suppressed
(E
, Elaboration_Check
) then
5380 elsif Dynamic_Elaboration_Checks
then
5381 return Is_Check_Suppressed
(E
, All_Checks
);
5388 if Scope_Suppress
.Suppress
(Elaboration_Check
) then
5390 elsif Dynamic_Elaboration_Checks
then
5391 return Scope_Suppress
.Suppress
(All_Checks
);
5395 end Elaboration_Checks_Suppressed
;
5397 ---------------------------
5398 -- Enable_Overflow_Check --
5399 ---------------------------
5401 procedure Enable_Overflow_Check
(N
: Node_Id
) is
5402 Typ
: constant Entity_Id
:= Base_Type
(Etype
(N
));
5403 Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
5411 Do_Ovflow_Check
: Boolean;
5414 if Debug_Flag_CC
then
5415 w
("Enable_Overflow_Check for node ", Int
(N
));
5416 Write_Str
(" Source location = ");
5421 -- No check if overflow checks suppressed for type of node
5423 if Overflow_Checks_Suppressed
(Etype
(N
)) then
5426 -- Nothing to do for unsigned integer types, which do not overflow
5428 elsif Is_Modular_Integer_Type
(Typ
) then
5432 -- This is the point at which processing for STRICT mode diverges
5433 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5434 -- probably more extreme that it needs to be, but what is going on here
5435 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
5436 -- to leave the processing for STRICT mode untouched. There were
5437 -- two reasons for this. First it avoided any incompatible change of
5438 -- behavior. Second, it guaranteed that STRICT mode continued to be
5441 -- The big difference is that in STRICT mode there is a fair amount of
5442 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5443 -- know that no check is needed. We skip all that in the two new modes,
5444 -- since really overflow checking happens over a whole subtree, and we
5445 -- do the corresponding optimizations later on when applying the checks.
5447 if Mode
in Minimized_Or_Eliminated
then
5448 if not (Overflow_Checks_Suppressed
(Etype
(N
)))
5449 and then not (Is_Entity_Name
(N
)
5450 and then Overflow_Checks_Suppressed
(Entity
(N
)))
5452 Activate_Overflow_Check
(N
);
5455 if Debug_Flag_CC
then
5456 w
("Minimized/Eliminated mode");
5462 -- Remainder of processing is for STRICT case, and is unchanged from
5463 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
5465 -- Nothing to do if the range of the result is known OK. We skip this
5466 -- for conversions, since the caller already did the check, and in any
5467 -- case the condition for deleting the check for a type conversion is
5470 if Nkind
(N
) /= N_Type_Conversion
then
5471 Determine_Range
(N
, OK
, Lo
, Hi
, Assume_Valid
=> True);
5473 -- Note in the test below that we assume that the range is not OK
5474 -- if a bound of the range is equal to that of the type. That's not
5475 -- quite accurate but we do this for the following reasons:
5477 -- a) The way that Determine_Range works, it will typically report
5478 -- the bounds of the value as being equal to the bounds of the
5479 -- type, because it either can't tell anything more precise, or
5480 -- does not think it is worth the effort to be more precise.
5482 -- b) It is very unusual to have a situation in which this would
5483 -- generate an unnecessary overflow check (an example would be
5484 -- a subtype with a range 0 .. Integer'Last - 1 to which the
5485 -- literal value one is added).
5487 -- c) The alternative is a lot of special casing in this routine
5488 -- which would partially duplicate Determine_Range processing.
5491 Do_Ovflow_Check
:= True;
5493 -- Note that the following checks are quite deliberately > and <
5494 -- rather than >= and <= as explained above.
5496 if Lo
> Expr_Value
(Type_Low_Bound
(Typ
))
5498 Hi
< Expr_Value
(Type_High_Bound
(Typ
))
5500 Do_Ovflow_Check
:= False;
5502 -- Despite the comments above, it is worth dealing specially with
5503 -- division specially. The only case where integer division can
5504 -- overflow is (largest negative number) / (-1). So we will do
5505 -- an extra range analysis to see if this is possible.
5507 elsif Nkind
(N
) = N_Op_Divide
then
5509 (Left_Opnd
(N
), OK
, Lo
, Hi
, Assume_Valid
=> True);
5511 if OK
and then Lo
> Expr_Value
(Type_Low_Bound
(Typ
)) then
5512 Do_Ovflow_Check
:= False;
5516 (Right_Opnd
(N
), OK
, Lo
, Hi
, Assume_Valid
=> True);
5518 if OK
and then (Lo
> Uint_Minus_1
5522 Do_Ovflow_Check
:= False;
5527 -- If no overflow check required, we are done
5529 if not Do_Ovflow_Check
then
5530 if Debug_Flag_CC
then
5531 w
("No overflow check required");
5539 -- If not in optimizing mode, set flag and we are done. We are also done
5540 -- (and just set the flag) if the type is not a discrete type, since it
5541 -- is not worth the effort to eliminate checks for other than discrete
5542 -- types. In addition, we take this same path if we have stored the
5543 -- maximum number of checks possible already (a very unlikely situation,
5544 -- but we do not want to blow up).
5546 if Optimization_Level
= 0
5547 or else not Is_Discrete_Type
(Etype
(N
))
5548 or else Num_Saved_Checks
= Saved_Checks
'Last
5550 Activate_Overflow_Check
(N
);
5552 if Debug_Flag_CC
then
5553 w
("Optimization off");
5559 -- Otherwise evaluate and check the expression
5564 Target_Type
=> Empty
,
5570 if Debug_Flag_CC
then
5571 w
("Called Find_Check");
5575 w
(" Check_Num = ", Chk
);
5576 w
(" Ent = ", Int
(Ent
));
5577 Write_Str
(" Ofs = ");
5582 -- If check is not of form to optimize, then set flag and we are done
5585 Activate_Overflow_Check
(N
);
5589 -- If check is already performed, then return without setting flag
5592 if Debug_Flag_CC
then
5593 w
("Check suppressed!");
5599 -- Here we will make a new entry for the new check
5601 Activate_Overflow_Check
(N
);
5602 Num_Saved_Checks
:= Num_Saved_Checks
+ 1;
5603 Saved_Checks
(Num_Saved_Checks
) :=
5608 Target_Type
=> Empty
);
5610 if Debug_Flag_CC
then
5611 w
("Make new entry, check number = ", Num_Saved_Checks
);
5612 w
(" Entity = ", Int
(Ent
));
5613 Write_Str
(" Offset = ");
5615 w
(" Check_Type = O");
5616 w
(" Target_Type = Empty");
5619 -- If we get an exception, then something went wrong, probably because of
5620 -- an error in the structure of the tree due to an incorrect program. Or
5621 -- it may be a bug in the optimization circuit. In either case the safest
5622 -- thing is simply to set the check flag unconditionally.
5626 Activate_Overflow_Check
(N
);
5628 if Debug_Flag_CC
then
5629 w
(" exception occurred, overflow flag set");
5633 end Enable_Overflow_Check
;
5635 ------------------------
5636 -- Enable_Range_Check --
5637 ------------------------
5639 procedure Enable_Range_Check
(N
: Node_Id
) is
5648 -- Return if unchecked type conversion with range check killed. In this
5649 -- case we never set the flag (that's what Kill_Range_Check is about).
5651 if Nkind
(N
) = N_Unchecked_Type_Conversion
5652 and then Kill_Range_Check
(N
)
5657 -- Do not set range check flag if parent is assignment statement or
5658 -- object declaration with Suppress_Assignment_Checks flag set
5660 if Nkind_In
(Parent
(N
), N_Assignment_Statement
, N_Object_Declaration
)
5661 and then Suppress_Assignment_Checks
(Parent
(N
))
5666 -- Check for various cases where we should suppress the range check
5668 -- No check if range checks suppressed for type of node
5670 if Present
(Etype
(N
)) and then Range_Checks_Suppressed
(Etype
(N
)) then
5673 -- No check if node is an entity name, and range checks are suppressed
5674 -- for this entity, or for the type of this entity.
5676 elsif Is_Entity_Name
(N
)
5677 and then (Range_Checks_Suppressed
(Entity
(N
))
5678 or else Range_Checks_Suppressed
(Etype
(Entity
(N
))))
5682 -- No checks if index of array, and index checks are suppressed for
5683 -- the array object or the type of the array.
5685 elsif Nkind
(Parent
(N
)) = N_Indexed_Component
then
5687 Pref
: constant Node_Id
:= Prefix
(Parent
(N
));
5689 if Is_Entity_Name
(Pref
)
5690 and then Index_Checks_Suppressed
(Entity
(Pref
))
5693 elsif Index_Checks_Suppressed
(Etype
(Pref
)) then
5699 -- Debug trace output
5701 if Debug_Flag_CC
then
5702 w
("Enable_Range_Check for node ", Int
(N
));
5703 Write_Str
(" Source location = ");
5708 -- If not in optimizing mode, set flag and we are done. We are also done
5709 -- (and just set the flag) if the type is not a discrete type, since it
5710 -- is not worth the effort to eliminate checks for other than discrete
5711 -- types. In addition, we take this same path if we have stored the
5712 -- maximum number of checks possible already (a very unlikely situation,
5713 -- but we do not want to blow up).
5715 if Optimization_Level
= 0
5716 or else No
(Etype
(N
))
5717 or else not Is_Discrete_Type
(Etype
(N
))
5718 or else Num_Saved_Checks
= Saved_Checks
'Last
5720 Activate_Range_Check
(N
);
5722 if Debug_Flag_CC
then
5723 w
("Optimization off");
5729 -- Otherwise find out the target type
5733 -- For assignment, use left side subtype
5735 if Nkind
(P
) = N_Assignment_Statement
5736 and then Expression
(P
) = N
5738 Ttyp
:= Etype
(Name
(P
));
5740 -- For indexed component, use subscript subtype
5742 elsif Nkind
(P
) = N_Indexed_Component
then
5749 Atyp
:= Etype
(Prefix
(P
));
5751 if Is_Access_Type
(Atyp
) then
5752 Atyp
:= Designated_Type
(Atyp
);
5754 -- If the prefix is an access to an unconstrained array,
5755 -- perform check unconditionally: it depends on the bounds of
5756 -- an object and we cannot currently recognize whether the test
5757 -- may be redundant.
5759 if not Is_Constrained
(Atyp
) then
5760 Activate_Range_Check
(N
);
5764 -- Ditto if prefix is simply an unconstrained array. We used
5765 -- to think this case was OK, if the prefix was not an explicit
5766 -- dereference, but we have now seen a case where this is not
5767 -- true, so it is safer to just suppress the optimization in this
5768 -- case. The back end is getting better at eliminating redundant
5769 -- checks in any case, so the loss won't be important.
5771 elsif Is_Array_Type
(Atyp
)
5772 and then not Is_Constrained
(Atyp
)
5774 Activate_Range_Check
(N
);
5778 Indx
:= First_Index
(Atyp
);
5779 Subs
:= First
(Expressions
(P
));
5782 Ttyp
:= Etype
(Indx
);
5791 -- For now, ignore all other cases, they are not so interesting
5794 if Debug_Flag_CC
then
5795 w
(" target type not found, flag set");
5798 Activate_Range_Check
(N
);
5802 -- Evaluate and check the expression
5807 Target_Type
=> Ttyp
,
5813 if Debug_Flag_CC
then
5814 w
("Called Find_Check");
5815 w
("Target_Typ = ", Int
(Ttyp
));
5819 w
(" Check_Num = ", Chk
);
5820 w
(" Ent = ", Int
(Ent
));
5821 Write_Str
(" Ofs = ");
5826 -- If check is not of form to optimize, then set flag and we are done
5829 if Debug_Flag_CC
then
5830 w
(" expression not of optimizable type, flag set");
5833 Activate_Range_Check
(N
);
5837 -- If check is already performed, then return without setting flag
5840 if Debug_Flag_CC
then
5841 w
("Check suppressed!");
5847 -- Here we will make a new entry for the new check
5849 Activate_Range_Check
(N
);
5850 Num_Saved_Checks
:= Num_Saved_Checks
+ 1;
5851 Saved_Checks
(Num_Saved_Checks
) :=
5856 Target_Type
=> Ttyp
);
5858 if Debug_Flag_CC
then
5859 w
("Make new entry, check number = ", Num_Saved_Checks
);
5860 w
(" Entity = ", Int
(Ent
));
5861 Write_Str
(" Offset = ");
5863 w
(" Check_Type = R");
5864 w
(" Target_Type = ", Int
(Ttyp
));
5865 pg
(Union_Id
(Ttyp
));
5868 -- If we get an exception, then something went wrong, probably because of
5869 -- an error in the structure of the tree due to an incorrect program. Or
5870 -- it may be a bug in the optimization circuit. In either case the safest
5871 -- thing is simply to set the check flag unconditionally.
5875 Activate_Range_Check
(N
);
5877 if Debug_Flag_CC
then
5878 w
(" exception occurred, range flag set");
5882 end Enable_Range_Check
;
5888 procedure Ensure_Valid
5890 Holes_OK
: Boolean := False;
5891 Related_Id
: Entity_Id
:= Empty
;
5892 Is_Low_Bound
: Boolean := False;
5893 Is_High_Bound
: Boolean := False)
5895 Typ
: constant Entity_Id
:= Etype
(Expr
);
5898 -- Ignore call if we are not doing any validity checking
5900 if not Validity_Checks_On
then
5903 -- Ignore call if range or validity checks suppressed on entity or type
5905 elsif Range_Or_Validity_Checks_Suppressed
(Expr
) then
5908 -- No check required if expression is from the expander, we assume the
5909 -- expander will generate whatever checks are needed. Note that this is
5910 -- not just an optimization, it avoids infinite recursions.
5912 -- Unchecked conversions must be checked, unless they are initialized
5913 -- scalar values, as in a component assignment in an init proc.
5915 -- In addition, we force a check if Force_Validity_Checks is set
5917 elsif not Comes_From_Source
(Expr
)
5918 and then not Force_Validity_Checks
5919 and then (Nkind
(Expr
) /= N_Unchecked_Type_Conversion
5920 or else Kill_Range_Check
(Expr
))
5924 -- No check required if expression is known to have valid value
5926 elsif Expr_Known_Valid
(Expr
) then
5929 -- No check needed within a generated predicate function. Validity
5930 -- of input value will have been checked earlier.
5932 elsif Ekind
(Current_Scope
) = E_Function
5933 and then Is_Predicate_Function
(Current_Scope
)
5937 -- Ignore case of enumeration with holes where the flag is set not to
5938 -- worry about holes, since no special validity check is needed
5940 elsif Is_Enumeration_Type
(Typ
)
5941 and then Has_Non_Standard_Rep
(Typ
)
5946 -- No check required on the left-hand side of an assignment
5948 elsif Nkind
(Parent
(Expr
)) = N_Assignment_Statement
5949 and then Expr
= Name
(Parent
(Expr
))
5953 -- No check on a universal real constant. The context will eventually
5954 -- convert it to a machine number for some target type, or report an
5957 elsif Nkind
(Expr
) = N_Real_Literal
5958 and then Etype
(Expr
) = Universal_Real
5962 -- If the expression denotes a component of a packed boolean array,
5963 -- no possible check applies. We ignore the old ACATS chestnuts that
5964 -- involve Boolean range True..True.
5966 -- Note: validity checks are generated for expressions that yield a
5967 -- scalar type, when it is possible to create a value that is outside of
5968 -- the type. If this is a one-bit boolean no such value exists. This is
5969 -- an optimization, and it also prevents compiler blowing up during the
5970 -- elaboration of improperly expanded packed array references.
5972 elsif Nkind
(Expr
) = N_Indexed_Component
5973 and then Is_Bit_Packed_Array
(Etype
(Prefix
(Expr
)))
5974 and then Root_Type
(Etype
(Expr
)) = Standard_Boolean
5978 -- For an expression with actions, we want to insert the validity check
5979 -- on the final Expression.
5981 elsif Nkind
(Expr
) = N_Expression_With_Actions
then
5982 Ensure_Valid
(Expression
(Expr
));
5985 -- An annoying special case. If this is an out parameter of a scalar
5986 -- type, then the value is not going to be accessed, therefore it is
5987 -- inappropriate to do any validity check at the call site.
5990 -- Only need to worry about scalar types
5992 if Is_Scalar_Type
(Typ
) then
6002 -- Find actual argument (which may be a parameter association)
6003 -- and the parent of the actual argument (the call statement)
6008 if Nkind
(P
) = N_Parameter_Association
then
6013 -- Only need to worry if we are argument of a procedure call
6014 -- since functions don't have out parameters. If this is an
6015 -- indirect or dispatching call, get signature from the
6018 if Nkind
(P
) = N_Procedure_Call_Statement
then
6019 L
:= Parameter_Associations
(P
);
6021 if Is_Entity_Name
(Name
(P
)) then
6022 E
:= Entity
(Name
(P
));
6024 pragma Assert
(Nkind
(Name
(P
)) = N_Explicit_Dereference
);
6025 E
:= Etype
(Name
(P
));
6028 -- Only need to worry if there are indeed actuals, and if
6029 -- this could be a procedure call, otherwise we cannot get a
6030 -- match (either we are not an argument, or the mode of the
6031 -- formal is not OUT). This test also filters out the
6034 if Is_Non_Empty_List
(L
) and then Is_Subprogram
(E
) then
6036 -- This is the loop through parameters, looking for an
6037 -- OUT parameter for which we are the argument.
6039 F
:= First_Formal
(E
);
6041 while Present
(F
) loop
6042 if Ekind
(F
) = E_Out_Parameter
and then A
= N
then
6055 -- If this is a boolean expression, only its elementary operands need
6056 -- checking: if they are valid, a boolean or short-circuit operation
6057 -- with them will be valid as well.
6059 if Base_Type
(Typ
) = Standard_Boolean
6061 (Nkind
(Expr
) in N_Op
or else Nkind
(Expr
) in N_Short_Circuit
)
6066 -- If we fall through, a validity check is required
6068 Insert_Valid_Check
(Expr
, Related_Id
, Is_Low_Bound
, Is_High_Bound
);
6070 if Is_Entity_Name
(Expr
)
6071 and then Safe_To_Capture_Value
(Expr
, Entity
(Expr
))
6073 Set_Is_Known_Valid
(Entity
(Expr
));
6077 ----------------------
6078 -- Expr_Known_Valid --
6079 ----------------------
6081 function Expr_Known_Valid
(Expr
: Node_Id
) return Boolean is
6082 Typ
: constant Entity_Id
:= Etype
(Expr
);
6085 -- Non-scalar types are always considered valid, since they never give
6086 -- rise to the issues of erroneous or bounded error behavior that are
6087 -- the concern. In formal reference manual terms the notion of validity
6088 -- only applies to scalar types. Note that even when packed arrays are
6089 -- represented using modular types, they are still arrays semantically,
6090 -- so they are also always valid (in particular, the unused bits can be
6091 -- random rubbish without affecting the validity of the array value).
6093 if not Is_Scalar_Type
(Typ
) or else Is_Packed_Array_Impl_Type
(Typ
) then
6096 -- If no validity checking, then everything is considered valid
6098 elsif not Validity_Checks_On
then
6101 -- Floating-point types are considered valid unless floating-point
6102 -- validity checks have been specifically turned on.
6104 elsif Is_Floating_Point_Type
(Typ
)
6105 and then not Validity_Check_Floating_Point
6109 -- If the expression is the value of an object that is known to be
6110 -- valid, then clearly the expression value itself is valid.
6112 elsif Is_Entity_Name
(Expr
)
6113 and then Is_Known_Valid
(Entity
(Expr
))
6115 -- Exclude volatile variables
6117 and then not Treat_As_Volatile
(Entity
(Expr
))
6121 -- References to discriminants are always considered valid. The value
6122 -- of a discriminant gets checked when the object is built. Within the
6123 -- record, we consider it valid, and it is important to do so, since
6124 -- otherwise we can try to generate bogus validity checks which
6125 -- reference discriminants out of scope. Discriminants of concurrent
6126 -- types are excluded for the same reason.
6128 elsif Is_Entity_Name
(Expr
)
6129 and then Denotes_Discriminant
(Expr
, Check_Concurrent
=> True)
6133 -- If the type is one for which all values are known valid, then we are
6134 -- sure that the value is valid except in the slightly odd case where
6135 -- the expression is a reference to a variable whose size has been
6136 -- explicitly set to a value greater than the object size.
6138 elsif Is_Known_Valid
(Typ
) then
6139 if Is_Entity_Name
(Expr
)
6140 and then Ekind
(Entity
(Expr
)) = E_Variable
6141 and then Esize
(Entity
(Expr
)) > Esize
(Typ
)
6148 -- Integer and character literals always have valid values, where
6149 -- appropriate these will be range checked in any case.
6151 elsif Nkind_In
(Expr
, N_Integer_Literal
, N_Character_Literal
) then
6154 -- If we have a type conversion or a qualification of a known valid
6155 -- value, then the result will always be valid.
6157 elsif Nkind_In
(Expr
, N_Type_Conversion
, N_Qualified_Expression
) then
6158 return Expr_Known_Valid
(Expression
(Expr
));
6160 -- Case of expression is a non-floating-point operator. In this case we
6161 -- can assume the result is valid the generated code for the operator
6162 -- will include whatever checks are needed (e.g. range checks) to ensure
6163 -- validity. This assumption does not hold for the floating-point case,
6164 -- since floating-point operators can generate Infinite or NaN results
6165 -- which are considered invalid.
6167 -- Historical note: in older versions, the exemption of floating-point
6168 -- types from this assumption was done only in cases where the parent
6169 -- was an assignment, function call or parameter association. Presumably
6170 -- the idea was that in other contexts, the result would be checked
6171 -- elsewhere, but this list of cases was missing tests (at least the
6172 -- N_Object_Declaration case, as shown by a reported missing validity
6173 -- check), and it is not clear why function calls but not procedure
6174 -- calls were tested for. It really seems more accurate and much
6175 -- safer to recognize that expressions which are the result of a
6176 -- floating-point operator can never be assumed to be valid.
6178 elsif Nkind
(Expr
) in N_Op
and then not Is_Floating_Point_Type
(Typ
) then
6181 -- The result of a membership test is always valid, since it is true or
6182 -- false, there are no other possibilities.
6184 elsif Nkind
(Expr
) in N_Membership_Test
then
6187 -- For all other cases, we do not know the expression is valid
6192 end Expr_Known_Valid
;
6198 procedure Find_Check
6200 Check_Type
: Character;
6201 Target_Type
: Entity_Id
;
6202 Entry_OK
: out Boolean;
6203 Check_Num
: out Nat
;
6204 Ent
: out Entity_Id
;
6207 function Within_Range_Of
6208 (Target_Type
: Entity_Id
;
6209 Check_Type
: Entity_Id
) return Boolean;
6210 -- Given a requirement for checking a range against Target_Type, and
6211 -- and a range Check_Type against which a check has already been made,
6212 -- determines if the check against check type is sufficient to ensure
6213 -- that no check against Target_Type is required.
6215 ---------------------
6216 -- Within_Range_Of --
6217 ---------------------
6219 function Within_Range_Of
6220 (Target_Type
: Entity_Id
;
6221 Check_Type
: Entity_Id
) return Boolean
6224 if Target_Type
= Check_Type
then
6229 Tlo
: constant Node_Id
:= Type_Low_Bound
(Target_Type
);
6230 Thi
: constant Node_Id
:= Type_High_Bound
(Target_Type
);
6231 Clo
: constant Node_Id
:= Type_Low_Bound
(Check_Type
);
6232 Chi
: constant Node_Id
:= Type_High_Bound
(Check_Type
);
6236 or else (Compile_Time_Known_Value
(Tlo
)
6238 Compile_Time_Known_Value
(Clo
)
6240 Expr_Value
(Clo
) >= Expr_Value
(Tlo
)))
6243 or else (Compile_Time_Known_Value
(Thi
)
6245 Compile_Time_Known_Value
(Chi
)
6247 Expr_Value
(Chi
) <= Expr_Value
(Clo
)))
6255 end Within_Range_Of
;
6257 -- Start of processing for Find_Check
6260 -- Establish default, in case no entry is found
6264 -- Case of expression is simple entity reference
6266 if Is_Entity_Name
(Expr
) then
6267 Ent
:= Entity
(Expr
);
6270 -- Case of expression is entity + known constant
6272 elsif Nkind
(Expr
) = N_Op_Add
6273 and then Compile_Time_Known_Value
(Right_Opnd
(Expr
))
6274 and then Is_Entity_Name
(Left_Opnd
(Expr
))
6276 Ent
:= Entity
(Left_Opnd
(Expr
));
6277 Ofs
:= Expr_Value
(Right_Opnd
(Expr
));
6279 -- Case of expression is entity - known constant
6281 elsif Nkind
(Expr
) = N_Op_Subtract
6282 and then Compile_Time_Known_Value
(Right_Opnd
(Expr
))
6283 and then Is_Entity_Name
(Left_Opnd
(Expr
))
6285 Ent
:= Entity
(Left_Opnd
(Expr
));
6286 Ofs
:= UI_Negate
(Expr_Value
(Right_Opnd
(Expr
)));
6288 -- Any other expression is not of the right form
6297 -- Come here with expression of appropriate form, check if entity is an
6298 -- appropriate one for our purposes.
6300 if (Ekind
(Ent
) = E_Variable
6301 or else Is_Constant_Object
(Ent
))
6302 and then not Is_Library_Level_Entity
(Ent
)
6310 -- See if there is matching check already
6312 for J
in reverse 1 .. Num_Saved_Checks
loop
6314 SC
: Saved_Check
renames Saved_Checks
(J
);
6316 if SC
.Killed
= False
6317 and then SC
.Entity
= Ent
6318 and then SC
.Offset
= Ofs
6319 and then SC
.Check_Type
= Check_Type
6320 and then Within_Range_Of
(Target_Type
, SC
.Target_Type
)
6328 -- If we fall through entry was not found
6333 ---------------------------------
6334 -- Generate_Discriminant_Check --
6335 ---------------------------------
6337 -- Note: the code for this procedure is derived from the
6338 -- Emit_Discriminant_Check Routine in trans.c.
6340 procedure Generate_Discriminant_Check
(N
: Node_Id
) is
6341 Loc
: constant Source_Ptr
:= Sloc
(N
);
6342 Pref
: constant Node_Id
:= Prefix
(N
);
6343 Sel
: constant Node_Id
:= Selector_Name
(N
);
6345 Orig_Comp
: constant Entity_Id
:=
6346 Original_Record_Component
(Entity
(Sel
));
6347 -- The original component to be checked
6349 Discr_Fct
: constant Entity_Id
:=
6350 Discriminant_Checking_Func
(Orig_Comp
);
6351 -- The discriminant checking function
6354 -- One discriminant to be checked in the type
6356 Real_Discr
: Entity_Id
;
6357 -- Actual discriminant in the call
6359 Pref_Type
: Entity_Id
;
6360 -- Type of relevant prefix (ignoring private/access stuff)
6363 -- List of arguments for function call
6366 -- Keep track of the formal corresponding to the actual we build for
6367 -- each discriminant, in order to be able to perform the necessary type
6371 -- Selected component reference for checking function argument
6374 Pref_Type
:= Etype
(Pref
);
6376 -- Force evaluation of the prefix, so that it does not get evaluated
6377 -- twice (once for the check, once for the actual reference). Such a
6378 -- double evaluation is always a potential source of inefficiency, and
6379 -- is functionally incorrect in the volatile case, or when the prefix
6380 -- may have side effects. A nonvolatile entity or a component of a
6381 -- nonvolatile entity requires no evaluation.
6383 if Is_Entity_Name
(Pref
) then
6384 if Treat_As_Volatile
(Entity
(Pref
)) then
6385 Force_Evaluation
(Pref
, Name_Req
=> True);
6388 elsif Treat_As_Volatile
(Etype
(Pref
)) then
6389 Force_Evaluation
(Pref
, Name_Req
=> True);
6391 elsif Nkind
(Pref
) = N_Selected_Component
6392 and then Is_Entity_Name
(Prefix
(Pref
))
6397 Force_Evaluation
(Pref
, Name_Req
=> True);
6400 -- For a tagged type, use the scope of the original component to
6401 -- obtain the type, because ???
6403 if Is_Tagged_Type
(Scope
(Orig_Comp
)) then
6404 Pref_Type
:= Scope
(Orig_Comp
);
6406 -- For an untagged derived type, use the discriminants of the parent
6407 -- which have been renamed in the derivation, possibly by a one-to-many
6408 -- discriminant constraint. For untagged type, initially get the Etype
6412 if Is_Derived_Type
(Pref_Type
)
6413 and then Number_Discriminants
(Pref_Type
) /=
6414 Number_Discriminants
(Etype
(Base_Type
(Pref_Type
)))
6416 Pref_Type
:= Etype
(Base_Type
(Pref_Type
));
6420 -- We definitely should have a checking function, This routine should
6421 -- not be called if no discriminant checking function is present.
6423 pragma Assert
(Present
(Discr_Fct
));
6425 -- Create the list of the actual parameters for the call. This list
6426 -- is the list of the discriminant fields of the record expression to
6427 -- be discriminant checked.
6430 Formal
:= First_Formal
(Discr_Fct
);
6431 Discr
:= First_Discriminant
(Pref_Type
);
6432 while Present
(Discr
) loop
6434 -- If we have a corresponding discriminant field, and a parent
6435 -- subtype is present, then we want to use the corresponding
6436 -- discriminant since this is the one with the useful value.
6438 if Present
(Corresponding_Discriminant
(Discr
))
6439 and then Ekind
(Pref_Type
) = E_Record_Type
6440 and then Present
(Parent_Subtype
(Pref_Type
))
6442 Real_Discr
:= Corresponding_Discriminant
(Discr
);
6444 Real_Discr
:= Discr
;
6447 -- Construct the reference to the discriminant
6450 Make_Selected_Component
(Loc
,
6452 Unchecked_Convert_To
(Pref_Type
,
6453 Duplicate_Subexpr
(Pref
)),
6454 Selector_Name
=> New_Occurrence_Of
(Real_Discr
, Loc
));
6456 -- Manually analyze and resolve this selected component. We really
6457 -- want it just as it appears above, and do not want the expander
6458 -- playing discriminal games etc with this reference. Then we append
6459 -- the argument to the list we are gathering.
6461 Set_Etype
(Scomp
, Etype
(Real_Discr
));
6462 Set_Analyzed
(Scomp
, True);
6463 Append_To
(Args
, Convert_To
(Etype
(Formal
), Scomp
));
6465 Next_Formal_With_Extras
(Formal
);
6466 Next_Discriminant
(Discr
);
6469 -- Now build and insert the call
6472 Make_Raise_Constraint_Error
(Loc
,
6474 Make_Function_Call
(Loc
,
6475 Name
=> New_Occurrence_Of
(Discr_Fct
, Loc
),
6476 Parameter_Associations
=> Args
),
6477 Reason
=> CE_Discriminant_Check_Failed
));
6478 end Generate_Discriminant_Check
;
6480 ---------------------------
6481 -- Generate_Index_Checks --
6482 ---------------------------
6484 procedure Generate_Index_Checks
(N
: Node_Id
) is
6486 function Entity_Of_Prefix
return Entity_Id
;
6487 -- Returns the entity of the prefix of N (or Empty if not found)
6489 ----------------------
6490 -- Entity_Of_Prefix --
6491 ----------------------
6493 function Entity_Of_Prefix
return Entity_Id
is
6498 while not Is_Entity_Name
(P
) loop
6499 if not Nkind_In
(P
, N_Selected_Component
,
6500 N_Indexed_Component
)
6509 end Entity_Of_Prefix
;
6513 Loc
: constant Source_Ptr
:= Sloc
(N
);
6514 A
: constant Node_Id
:= Prefix
(N
);
6515 A_Ent
: constant Entity_Id
:= Entity_Of_Prefix
;
6518 -- Start of processing for Generate_Index_Checks
6521 -- Ignore call if the prefix is not an array since we have a serious
6522 -- error in the sources. Ignore it also if index checks are suppressed
6523 -- for array object or type.
6525 if not Is_Array_Type
(Etype
(A
))
6526 or else (Present
(A_Ent
) and then Index_Checks_Suppressed
(A_Ent
))
6527 or else Index_Checks_Suppressed
(Etype
(A
))
6531 -- The indexed component we are dealing with contains 'Loop_Entry in its
6532 -- prefix. This case arises when analysis has determined that constructs
6535 -- Prefix'Loop_Entry (Expr)
6536 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6538 -- require rewriting for error detection purposes. A side effect of this
6539 -- action is the generation of index checks that mention 'Loop_Entry.
6540 -- Delay the generation of the check until 'Loop_Entry has been properly
6541 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6543 elsif Nkind
(Prefix
(N
)) = N_Attribute_Reference
6544 and then Attribute_Name
(Prefix
(N
)) = Name_Loop_Entry
6549 -- Generate a raise of constraint error with the appropriate reason and
6550 -- a condition of the form:
6552 -- Base_Type (Sub) not in Array'Range (Subscript)
6554 -- Note that the reason we generate the conversion to the base type here
6555 -- is that we definitely want the range check to take place, even if it
6556 -- looks like the subtype is OK. Optimization considerations that allow
6557 -- us to omit the check have already been taken into account in the
6558 -- setting of the Do_Range_Check flag earlier on.
6560 Sub
:= First
(Expressions
(N
));
6562 -- Handle string literals
6564 if Ekind
(Etype
(A
)) = E_String_Literal_Subtype
then
6565 if Do_Range_Check
(Sub
) then
6566 Set_Do_Range_Check
(Sub
, False);
6568 -- For string literals we obtain the bounds of the string from the
6569 -- associated subtype.
6572 Make_Raise_Constraint_Error
(Loc
,
6576 Convert_To
(Base_Type
(Etype
(Sub
)),
6577 Duplicate_Subexpr_Move_Checks
(Sub
)),
6579 Make_Attribute_Reference
(Loc
,
6580 Prefix
=> New_Occurrence_Of
(Etype
(A
), Loc
),
6581 Attribute_Name
=> Name_Range
)),
6582 Reason
=> CE_Index_Check_Failed
));
6589 A_Idx
: Node_Id
:= Empty
;
6596 A_Idx
:= First_Index
(Etype
(A
));
6598 while Present
(Sub
) loop
6599 if Do_Range_Check
(Sub
) then
6600 Set_Do_Range_Check
(Sub
, False);
6602 -- Force evaluation except for the case of a simple name of
6603 -- a nonvolatile entity.
6605 if not Is_Entity_Name
(Sub
)
6606 or else Treat_As_Volatile
(Entity
(Sub
))
6608 Force_Evaluation
(Sub
);
6611 if Nkind
(A_Idx
) = N_Range
then
6614 elsif Nkind
(A_Idx
) = N_Identifier
6615 or else Nkind
(A_Idx
) = N_Expanded_Name
6617 A_Range
:= Scalar_Range
(Entity
(A_Idx
));
6619 else pragma Assert
(Nkind
(A_Idx
) = N_Subtype_Indication
);
6620 A_Range
:= Range_Expression
(Constraint
(A_Idx
));
6623 -- For array objects with constant bounds we can generate
6624 -- the index check using the bounds of the type of the index
6627 and then Ekind
(A_Ent
) = E_Variable
6628 and then Is_Constant_Bound
(Low_Bound
(A_Range
))
6629 and then Is_Constant_Bound
(High_Bound
(A_Range
))
6632 Make_Attribute_Reference
(Loc
,
6634 New_Occurrence_Of
(Etype
(A_Idx
), Loc
),
6635 Attribute_Name
=> Name_Range
);
6637 -- For arrays with non-constant bounds we cannot generate
6638 -- the index check using the bounds of the type of the index
6639 -- since it may reference discriminants of some enclosing
6640 -- type. We obtain the bounds directly from the prefix
6647 Num
:= New_List
(Make_Integer_Literal
(Loc
, Ind
));
6651 Make_Attribute_Reference
(Loc
,
6653 Duplicate_Subexpr_Move_Checks
(A
, Name_Req
=> True),
6654 Attribute_Name
=> Name_Range
,
6655 Expressions
=> Num
);
6659 Make_Raise_Constraint_Error
(Loc
,
6663 Convert_To
(Base_Type
(Etype
(Sub
)),
6664 Duplicate_Subexpr_Move_Checks
(Sub
)),
6665 Right_Opnd
=> Range_N
),
6666 Reason
=> CE_Index_Check_Failed
));
6669 A_Idx
:= Next_Index
(A_Idx
);
6675 end Generate_Index_Checks
;
6677 --------------------------
6678 -- Generate_Range_Check --
6679 --------------------------
6681 procedure Generate_Range_Check
6683 Target_Type
: Entity_Id
;
6684 Reason
: RT_Exception_Code
)
6686 Loc
: constant Source_Ptr
:= Sloc
(N
);
6687 Source_Type
: constant Entity_Id
:= Etype
(N
);
6688 Source_Base_Type
: constant Entity_Id
:= Base_Type
(Source_Type
);
6689 Target_Base_Type
: constant Entity_Id
:= Base_Type
(Target_Type
);
6691 procedure Convert_And_Check_Range
;
6692 -- Convert the conversion operand to the target base type and save in
6693 -- a temporary. Then check the converted value against the range of the
6696 -----------------------------
6697 -- Convert_And_Check_Range --
6698 -----------------------------
6700 procedure Convert_And_Check_Range
is
6701 Tnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', N
);
6704 -- We make a temporary to hold the value of the converted value
6705 -- (converted to the base type), and then do the test against this
6706 -- temporary. The conversion itself is replaced by an occurrence of
6707 -- Tnn and followed by the explicit range check. Note that checks
6708 -- are suppressed for this code, since we don't want a recursive
6709 -- range check popping up.
6711 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6712 -- [constraint_error when Tnn not in Target_Type]
6714 Insert_Actions
(N
, New_List
(
6715 Make_Object_Declaration
(Loc
,
6716 Defining_Identifier
=> Tnn
,
6717 Object_Definition
=> New_Occurrence_Of
(Target_Base_Type
, Loc
),
6718 Constant_Present
=> True,
6720 Make_Type_Conversion
(Loc
,
6721 Subtype_Mark
=> New_Occurrence_Of
(Target_Base_Type
, Loc
),
6722 Expression
=> Duplicate_Subexpr
(N
))),
6724 Make_Raise_Constraint_Error
(Loc
,
6727 Left_Opnd
=> New_Occurrence_Of
(Tnn
, Loc
),
6728 Right_Opnd
=> New_Occurrence_Of
(Target_Type
, Loc
)),
6730 Suppress
=> All_Checks
);
6732 Rewrite
(N
, New_Occurrence_Of
(Tnn
, Loc
));
6734 -- Set the type of N, because the declaration for Tnn might not
6735 -- be analyzed yet, as is the case if N appears within a record
6736 -- declaration, as a discriminant constraint or expression.
6738 Set_Etype
(N
, Target_Base_Type
);
6739 end Convert_And_Check_Range
;
6741 -- Start of processing for Generate_Range_Check
6744 -- First special case, if the source type is already within the range
6745 -- of the target type, then no check is needed (probably we should have
6746 -- stopped Do_Range_Check from being set in the first place, but better
6747 -- late than never in preventing junk code and junk flag settings.
6749 if In_Subrange_Of
(Source_Type
, Target_Type
)
6751 -- We do NOT apply this if the source node is a literal, since in this
6752 -- case the literal has already been labeled as having the subtype of
6756 (Nkind_In
(N
, N_Integer_Literal
, N_Real_Literal
, N_Character_Literal
)
6759 and then Ekind
(Entity
(N
)) = E_Enumeration_Literal
))
6761 Set_Do_Range_Check
(N
, False);
6765 -- Here a check is needed. If the expander is not active, or if we are
6766 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6767 -- are done. In both these cases, we just want to see the range check
6768 -- flag set, we do not want to generate the explicit range check code.
6770 if GNATprove_Mode
or else not Expander_Active
then
6771 Set_Do_Range_Check
(N
, True);
6775 -- Here we will generate an explicit range check, so we don't want to
6776 -- set the Do_Range check flag, since the range check is taken care of
6777 -- by the code we will generate.
6779 Set_Do_Range_Check
(N
, False);
6781 -- Force evaluation of the node, so that it does not get evaluated twice
6782 -- (once for the check, once for the actual reference). Such a double
6783 -- evaluation is always a potential source of inefficiency, and is
6784 -- functionally incorrect in the volatile case.
6786 if not Is_Entity_Name
(N
) or else Treat_As_Volatile
(Entity
(N
)) then
6787 Force_Evaluation
(N
);
6790 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6791 -- the same since in this case we can simply do a direct check of the
6792 -- value of N against the bounds of Target_Type.
6794 -- [constraint_error when N not in Target_Type]
6796 -- Note: this is by far the most common case, for example all cases of
6797 -- checks on the RHS of assignments are in this category, but not all
6798 -- cases are like this. Notably conversions can involve two types.
6800 if Source_Base_Type
= Target_Base_Type
then
6802 -- Insert the explicit range check. Note that we suppress checks for
6803 -- this code, since we don't want a recursive range check popping up.
6806 Make_Raise_Constraint_Error
(Loc
,
6809 Left_Opnd
=> Duplicate_Subexpr
(N
),
6810 Right_Opnd
=> New_Occurrence_Of
(Target_Type
, Loc
)),
6812 Suppress
=> All_Checks
);
6814 -- Next test for the case where the target type is within the bounds
6815 -- of the base type of the source type, since in this case we can
6816 -- simply convert these bounds to the base type of T to do the test.
6818 -- [constraint_error when N not in
6819 -- Source_Base_Type (Target_Type'First)
6821 -- Source_Base_Type(Target_Type'Last))]
6823 -- The conversions will always work and need no check
6825 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
6826 -- of converting from an enumeration value to an integer type, such as
6827 -- occurs for the case of generating a range check on Enum'Val(Exp)
6828 -- (which used to be handled by gigi). This is OK, since the conversion
6829 -- itself does not require a check.
6831 elsif In_Subrange_Of
(Target_Type
, Source_Base_Type
) then
6833 -- Insert the explicit range check. Note that we suppress checks for
6834 -- this code, since we don't want a recursive range check popping up.
6836 if Is_Discrete_Type
(Source_Base_Type
)
6838 Is_Discrete_Type
(Target_Base_Type
)
6841 Make_Raise_Constraint_Error
(Loc
,
6844 Left_Opnd
=> Duplicate_Subexpr
(N
),
6849 Unchecked_Convert_To
(Source_Base_Type
,
6850 Make_Attribute_Reference
(Loc
,
6852 New_Occurrence_Of
(Target_Type
, Loc
),
6853 Attribute_Name
=> Name_First
)),
6856 Unchecked_Convert_To
(Source_Base_Type
,
6857 Make_Attribute_Reference
(Loc
,
6859 New_Occurrence_Of
(Target_Type
, Loc
),
6860 Attribute_Name
=> Name_Last
)))),
6862 Suppress
=> All_Checks
);
6864 -- For conversions involving at least one type that is not discrete,
6865 -- first convert to target type and then generate the range check.
6866 -- This avoids problems with values that are close to a bound of the
6867 -- target type that would fail a range check when done in a larger
6868 -- source type before converting but would pass if converted with
6869 -- rounding and then checked (such as in float-to-float conversions).
6872 Convert_And_Check_Range
;
6875 -- Note that at this stage we now that the Target_Base_Type is not in
6876 -- the range of the Source_Base_Type (since even the Target_Type itself
6877 -- is not in this range). It could still be the case that Source_Type is
6878 -- in range of the target base type since we have not checked that case.
6880 -- If that is the case, we can freely convert the source to the target,
6881 -- and then test the target result against the bounds.
6883 elsif In_Subrange_Of
(Source_Type
, Target_Base_Type
) then
6884 Convert_And_Check_Range
;
6886 -- At this stage, we know that we have two scalar types, which are
6887 -- directly convertible, and where neither scalar type has a base
6888 -- range that is in the range of the other scalar type.
6890 -- The only way this can happen is with a signed and unsigned type.
6891 -- So test for these two cases:
6894 -- Case of the source is unsigned and the target is signed
6896 if Is_Unsigned_Type
(Source_Base_Type
)
6897 and then not Is_Unsigned_Type
(Target_Base_Type
)
6899 -- If the source is unsigned and the target is signed, then we
6900 -- know that the source is not shorter than the target (otherwise
6901 -- the source base type would be in the target base type range).
6903 -- In other words, the unsigned type is either the same size as
6904 -- the target, or it is larger. It cannot be smaller.
6907 (Esize
(Source_Base_Type
) >= Esize
(Target_Base_Type
));
6909 -- We only need to check the low bound if the low bound of the
6910 -- target type is non-negative. If the low bound of the target
6911 -- type is negative, then we know that we will fit fine.
6913 -- If the high bound of the target type is negative, then we
6914 -- know we have a constraint error, since we can't possibly
6915 -- have a negative source.
6917 -- With these two checks out of the way, we can do the check
6918 -- using the source type safely
6920 -- This is definitely the most annoying case.
6922 -- [constraint_error
6923 -- when (Target_Type'First >= 0
6925 -- N < Source_Base_Type (Target_Type'First))
6926 -- or else Target_Type'Last < 0
6927 -- or else N > Source_Base_Type (Target_Type'Last)];
6929 -- We turn off all checks since we know that the conversions
6930 -- will work fine, given the guards for negative values.
6933 Make_Raise_Constraint_Error
(Loc
,
6939 Left_Opnd
=> Make_Op_Ge
(Loc
,
6941 Make_Attribute_Reference
(Loc
,
6943 New_Occurrence_Of
(Target_Type
, Loc
),
6944 Attribute_Name
=> Name_First
),
6945 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
)),
6949 Left_Opnd
=> Duplicate_Subexpr
(N
),
6951 Convert_To
(Source_Base_Type
,
6952 Make_Attribute_Reference
(Loc
,
6954 New_Occurrence_Of
(Target_Type
, Loc
),
6955 Attribute_Name
=> Name_First
)))),
6960 Make_Attribute_Reference
(Loc
,
6961 Prefix
=> New_Occurrence_Of
(Target_Type
, Loc
),
6962 Attribute_Name
=> Name_Last
),
6963 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
))),
6967 Left_Opnd
=> Duplicate_Subexpr
(N
),
6969 Convert_To
(Source_Base_Type
,
6970 Make_Attribute_Reference
(Loc
,
6971 Prefix
=> New_Occurrence_Of
(Target_Type
, Loc
),
6972 Attribute_Name
=> Name_Last
)))),
6975 Suppress
=> All_Checks
);
6977 -- Only remaining possibility is that the source is signed and
6978 -- the target is unsigned.
6981 pragma Assert
(not Is_Unsigned_Type
(Source_Base_Type
)
6982 and then Is_Unsigned_Type
(Target_Base_Type
));
6984 -- If the source is signed and the target is unsigned, then we
6985 -- know that the target is not shorter than the source (otherwise
6986 -- the target base type would be in the source base type range).
6988 -- In other words, the unsigned type is either the same size as
6989 -- the target, or it is larger. It cannot be smaller.
6991 -- Clearly we have an error if the source value is negative since
6992 -- no unsigned type can have negative values. If the source type
6993 -- is non-negative, then the check can be done using the target
6996 -- Tnn : constant Target_Base_Type (N) := Target_Type;
6998 -- [constraint_error
6999 -- when N < 0 or else Tnn not in Target_Type];
7001 -- We turn off all checks for the conversion of N to the target
7002 -- base type, since we generate the explicit check to ensure that
7003 -- the value is non-negative
7006 Tnn
: constant Entity_Id
:= Make_Temporary
(Loc
, 'T', N
);
7009 Insert_Actions
(N
, New_List
(
7010 Make_Object_Declaration
(Loc
,
7011 Defining_Identifier
=> Tnn
,
7012 Object_Definition
=>
7013 New_Occurrence_Of
(Target_Base_Type
, Loc
),
7014 Constant_Present
=> True,
7016 Make_Unchecked_Type_Conversion
(Loc
,
7018 New_Occurrence_Of
(Target_Base_Type
, Loc
),
7019 Expression
=> Duplicate_Subexpr
(N
))),
7021 Make_Raise_Constraint_Error
(Loc
,
7026 Left_Opnd
=> Duplicate_Subexpr
(N
),
7027 Right_Opnd
=> Make_Integer_Literal
(Loc
, Uint_0
)),
7031 Left_Opnd
=> New_Occurrence_Of
(Tnn
, Loc
),
7033 New_Occurrence_Of
(Target_Type
, Loc
))),
7036 Suppress
=> All_Checks
);
7038 -- Set the Etype explicitly, because Insert_Actions may have
7039 -- placed the declaration in the freeze list for an enclosing
7040 -- construct, and thus it is not analyzed yet.
7042 Set_Etype
(Tnn
, Target_Base_Type
);
7043 Rewrite
(N
, New_Occurrence_Of
(Tnn
, Loc
));
7047 end Generate_Range_Check
;
7053 function Get_Check_Id
(N
: Name_Id
) return Check_Id
is
7055 -- For standard check name, we can do a direct computation
7057 if N
in First_Check_Name
.. Last_Check_Name
then
7058 return Check_Id
(N
- (First_Check_Name
- 1));
7060 -- For non-standard names added by pragma Check_Name, search table
7063 for J
in All_Checks
+ 1 .. Check_Names
.Last
loop
7064 if Check_Names
.Table
(J
) = N
then
7070 -- No matching name found
7075 ---------------------
7076 -- Get_Discriminal --
7077 ---------------------
7079 function Get_Discriminal
(E
: Entity_Id
; Bound
: Node_Id
) return Node_Id
is
7080 Loc
: constant Source_Ptr
:= Sloc
(E
);
7085 -- The bound can be a bona fide parameter of a protected operation,
7086 -- rather than a prival encoded as an in-parameter.
7088 if No
(Discriminal_Link
(Entity
(Bound
))) then
7092 -- Climb the scope stack looking for an enclosing protected type. If
7093 -- we run out of scopes, return the bound itself.
7096 while Present
(Sc
) loop
7097 if Sc
= Standard_Standard
then
7099 elsif Ekind
(Sc
) = E_Protected_Type
then
7106 D
:= First_Discriminant
(Sc
);
7107 while Present
(D
) loop
7108 if Chars
(D
) = Chars
(Bound
) then
7109 return New_Occurrence_Of
(Discriminal
(D
), Loc
);
7112 Next_Discriminant
(D
);
7116 end Get_Discriminal
;
7118 ----------------------
7119 -- Get_Range_Checks --
7120 ----------------------
7122 function Get_Range_Checks
7124 Target_Typ
: Entity_Id
;
7125 Source_Typ
: Entity_Id
:= Empty
;
7126 Warn_Node
: Node_Id
:= Empty
) return Check_Result
7130 Selected_Range_Checks
(Ck_Node
, Target_Typ
, Source_Typ
, Warn_Node
);
7131 end Get_Range_Checks
;
7137 function Guard_Access
7140 Ck_Node
: Node_Id
) return Node_Id
7143 if Nkind
(Cond
) = N_Or_Else
then
7144 Set_Paren_Count
(Cond
, 1);
7147 if Nkind
(Ck_Node
) = N_Allocator
then
7155 Left_Opnd
=> Duplicate_Subexpr_No_Checks
(Ck_Node
),
7156 Right_Opnd
=> Make_Null
(Loc
)),
7157 Right_Opnd
=> Cond
);
7161 -----------------------------
7162 -- Index_Checks_Suppressed --
7163 -----------------------------
7165 function Index_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
7167 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
7168 return Is_Check_Suppressed
(E
, Index_Check
);
7170 return Scope_Suppress
.Suppress
(Index_Check
);
7172 end Index_Checks_Suppressed
;
7178 procedure Initialize
is
7180 for J
in Determine_Range_Cache_N
'Range loop
7181 Determine_Range_Cache_N
(J
) := Empty
;
7186 for J
in Int
range 1 .. All_Checks
loop
7187 Check_Names
.Append
(Name_Id
(Int
(First_Check_Name
) + J
- 1));
7191 -------------------------
7192 -- Insert_Range_Checks --
7193 -------------------------
7195 procedure Insert_Range_Checks
7196 (Checks
: Check_Result
;
7198 Suppress_Typ
: Entity_Id
;
7199 Static_Sloc
: Source_Ptr
:= No_Location
;
7200 Flag_Node
: Node_Id
:= Empty
;
7201 Do_Before
: Boolean := False)
7203 Checks_On
: constant Boolean :=
7204 not Index_Checks_Suppressed
(Suppress_Typ
)
7206 not Range_Checks_Suppressed
(Suppress_Typ
);
7208 Check_Node
: Node_Id
;
7209 Internal_Flag_Node
: Node_Id
:= Flag_Node
;
7210 Internal_Static_Sloc
: Source_Ptr
:= Static_Sloc
;
7213 -- For now we just return if Checks_On is false, however this should be
7214 -- enhanced to check for an always True value in the condition and to
7215 -- generate a compilation warning???
7217 if not Expander_Active
or not Checks_On
then
7221 if Static_Sloc
= No_Location
then
7222 Internal_Static_Sloc
:= Sloc
(Node
);
7225 if No
(Flag_Node
) then
7226 Internal_Flag_Node
:= Node
;
7229 for J
in 1 .. 2 loop
7230 exit when No
(Checks
(J
));
7232 if Nkind
(Checks
(J
)) = N_Raise_Constraint_Error
7233 and then Present
(Condition
(Checks
(J
)))
7235 if not Has_Dynamic_Range_Check
(Internal_Flag_Node
) then
7236 Check_Node
:= Checks
(J
);
7237 Mark_Rewrite_Insertion
(Check_Node
);
7240 Insert_Before_And_Analyze
(Node
, Check_Node
);
7242 Insert_After_And_Analyze
(Node
, Check_Node
);
7245 Set_Has_Dynamic_Range_Check
(Internal_Flag_Node
);
7250 Make_Raise_Constraint_Error
(Internal_Static_Sloc
,
7251 Reason
=> CE_Range_Check_Failed
);
7252 Mark_Rewrite_Insertion
(Check_Node
);
7255 Insert_Before_And_Analyze
(Node
, Check_Node
);
7257 Insert_After_And_Analyze
(Node
, Check_Node
);
7261 end Insert_Range_Checks
;
7263 ------------------------
7264 -- Insert_Valid_Check --
7265 ------------------------
7267 procedure Insert_Valid_Check
7269 Related_Id
: Entity_Id
:= Empty
;
7270 Is_Low_Bound
: Boolean := False;
7271 Is_High_Bound
: Boolean := False)
7273 Loc
: constant Source_Ptr
:= Sloc
(Expr
);
7274 Typ
: constant Entity_Id
:= Etype
(Expr
);
7278 -- Do not insert if checks off, or if not checking validity or if
7279 -- expression is known to be valid.
7281 if not Validity_Checks_On
7282 or else Range_Or_Validity_Checks_Suppressed
(Expr
)
7283 or else Expr_Known_Valid
(Expr
)
7287 -- Do not insert checks within a predicate function. This will arise
7288 -- if the current unit and the predicate function are being compiled
7289 -- with validity checks enabled.
7291 elsif Present
(Predicate_Function
(Typ
))
7292 and then Current_Scope
= Predicate_Function
(Typ
)
7296 -- If the expression is a packed component of a modular type of the
7297 -- right size, the data is always valid.
7299 elsif Nkind
(Expr
) = N_Selected_Component
7300 and then Present
(Component_Clause
(Entity
(Selector_Name
(Expr
))))
7301 and then Is_Modular_Integer_Type
(Typ
)
7302 and then Modulus
(Typ
) = 2 ** Esize
(Entity
(Selector_Name
(Expr
)))
7306 -- Do not generate a validity check when inside a generic unit as this
7307 -- is an expansion activity.
7309 elsif Inside_A_Generic
then
7313 -- If we have a checked conversion, then validity check applies to
7314 -- the expression inside the conversion, not the result, since if
7315 -- the expression inside is valid, then so is the conversion result.
7318 while Nkind
(Exp
) = N_Type_Conversion
loop
7319 Exp
:= Expression
(Exp
);
7322 -- Do not generate a check for a variable which already validates the
7323 -- value of an assignable object.
7325 if Is_Validation_Variable_Reference
(Exp
) then
7329 -- We are about to insert the validity check for Exp. We save and
7330 -- reset the Do_Range_Check flag over this validity check, and then
7331 -- put it back for the final original reference (Exp may be rewritten).
7334 DRC
: constant Boolean := Do_Range_Check
(Exp
);
7342 Set_Do_Range_Check
(Exp
, False);
7344 -- If the expression denotes an assignable object, capture its value
7345 -- in a variable and replace the original expression by the variable.
7346 -- This approach has several effects:
7348 -- 1) The evaluation of the object results in only one read in the
7349 -- case where the object is atomic or volatile.
7351 -- Var ... := Object; -- read
7353 -- 2) The captured value is the one verified by attribute 'Valid.
7354 -- As a result the object is not evaluated again, which would
7355 -- result in an unwanted read in the case where the object is
7356 -- atomic or volatile.
7358 -- if not Var'Valid then -- OK, no read of Object
7360 -- if not Object'Valid then -- Wrong, extra read of Object
7362 -- 3) The captured value replaces the original object reference.
7363 -- As a result the object is not evaluated again, in the same
7366 -- ... Var ... -- OK, no read of Object
7368 -- ... Object ... -- Wrong, extra read of Object
7370 -- 4) The use of a variable to capture the value of the object
7371 -- allows the propagation of any changes back to the original
7374 -- procedure Call (Val : in out ...);
7376 -- Var : ... := Object; -- read Object
7377 -- if not Var'Valid then -- validity check
7378 -- Call (Var); -- modify Var
7379 -- Object := Var; -- update Object
7381 if Is_Variable
(Exp
) then
7382 Obj
:= New_Copy_Tree
(Exp
);
7383 Var_Id
:= Make_Temporary
(Loc
, 'T', Exp
);
7386 Make_Object_Declaration
(Loc
,
7387 Defining_Identifier
=> Var_Id
,
7388 Object_Definition
=> New_Occurrence_Of
(Typ
, Loc
),
7389 Expression
=> Relocate_Node
(Exp
)));
7390 Set_Validated_Object
(Var_Id
, Obj
);
7392 Rewrite
(Exp
, New_Occurrence_Of
(Var_Id
, Loc
));
7393 PV
:= New_Occurrence_Of
(Var_Id
, Loc
);
7395 -- Otherwise the expression does not denote a variable. Force its
7396 -- evaluation by capturing its value in a constant. Generate:
7398 -- Temp : constant ... := Exp;
7403 Related_Id
=> Related_Id
,
7404 Is_Low_Bound
=> Is_Low_Bound
,
7405 Is_High_Bound
=> Is_High_Bound
);
7407 PV
:= New_Copy_Tree
(Exp
);
7410 -- A rather specialized test. If PV is an analyzed expression which
7411 -- is an indexed component of a packed array that has not been
7412 -- properly expanded, turn off its Analyzed flag to make sure it
7413 -- gets properly reexpanded. If the prefix is an access value,
7414 -- the dereference will be added later.
7416 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7417 -- an analyze with the old parent pointer. This may point e.g. to
7418 -- a subprogram call, which deactivates this expansion.
7421 and then Nkind
(PV
) = N_Indexed_Component
7422 and then Is_Array_Type
(Etype
(Prefix
(PV
)))
7423 and then Present
(Packed_Array_Impl_Type
(Etype
(Prefix
(PV
))))
7425 Set_Analyzed
(PV
, False);
7428 -- Build the raise CE node to check for validity. We build a type
7429 -- qualification for the prefix, since it may not be of the form of
7430 -- a name, and we don't care in this context!
7433 Make_Raise_Constraint_Error
(Loc
,
7437 Make_Attribute_Reference
(Loc
,
7439 Attribute_Name
=> Name_Valid
)),
7440 Reason
=> CE_Invalid_Data
);
7442 -- Insert the validity check. Note that we do this with validity
7443 -- checks turned off, to avoid recursion, we do not want validity
7444 -- checks on the validity checking code itself.
7446 Insert_Action
(Expr
, CE
, Suppress
=> Validity_Check
);
7448 -- If the expression is a reference to an element of a bit-packed
7449 -- array, then it is rewritten as a renaming declaration. If the
7450 -- expression is an actual in a call, it has not been expanded,
7451 -- waiting for the proper point at which to do it. The same happens
7452 -- with renamings, so that we have to force the expansion now. This
7453 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7456 if Is_Entity_Name
(Exp
)
7457 and then Nkind
(Parent
(Entity
(Exp
))) =
7458 N_Object_Renaming_Declaration
7461 Old_Exp
: constant Node_Id
:= Name
(Parent
(Entity
(Exp
)));
7463 if Nkind
(Old_Exp
) = N_Indexed_Component
7464 and then Is_Bit_Packed_Array
(Etype
(Prefix
(Old_Exp
)))
7466 Expand_Packed_Element_Reference
(Old_Exp
);
7471 -- Put back the Do_Range_Check flag on the resulting (possibly
7472 -- rewritten) expression.
7474 -- Note: it might be thought that a validity check is not required
7475 -- when a range check is present, but that's not the case, because
7476 -- the back end is allowed to assume for the range check that the
7477 -- operand is within its declared range (an assumption that validity
7478 -- checking is all about NOT assuming).
7480 -- Note: no need to worry about Possible_Local_Raise here, it will
7481 -- already have been called if original node has Do_Range_Check set.
7483 Set_Do_Range_Check
(Exp
, DRC
);
7485 end Insert_Valid_Check
;
7487 -------------------------------------
7488 -- Is_Signed_Integer_Arithmetic_Op --
7489 -------------------------------------
7491 function Is_Signed_Integer_Arithmetic_Op
(N
: Node_Id
) return Boolean is
7505 return Is_Signed_Integer_Type
(Etype
(N
));
7507 when N_Case_Expression
7510 return Is_Signed_Integer_Type
(Etype
(N
));
7515 end Is_Signed_Integer_Arithmetic_Op
;
7517 ----------------------------------
7518 -- Install_Null_Excluding_Check --
7519 ----------------------------------
7521 procedure Install_Null_Excluding_Check
(N
: Node_Id
) is
7522 Loc
: constant Source_Ptr
:= Sloc
(Parent
(N
));
7523 Typ
: constant Entity_Id
:= Etype
(N
);
7525 function Safe_To_Capture_In_Parameter_Value
return Boolean;
7526 -- Determines if it is safe to capture Known_Non_Null status for an
7527 -- the entity referenced by node N. The caller ensures that N is indeed
7528 -- an entity name. It is safe to capture the non-null status for an IN
7529 -- parameter when the reference occurs within a declaration that is sure
7530 -- to be executed as part of the declarative region.
7532 procedure Mark_Non_Null
;
7533 -- After installation of check, if the node in question is an entity
7534 -- name, then mark this entity as non-null if possible.
7536 function Safe_To_Capture_In_Parameter_Value
return Boolean is
7537 E
: constant Entity_Id
:= Entity
(N
);
7538 S
: constant Entity_Id
:= Current_Scope
;
7542 if Ekind
(E
) /= E_In_Parameter
then
7546 -- Two initial context checks. We must be inside a subprogram body
7547 -- with declarations and reference must not appear in nested scopes.
7549 if (Ekind
(S
) /= E_Function
and then Ekind
(S
) /= E_Procedure
)
7550 or else Scope
(E
) /= S
7555 S_Par
:= Parent
(Parent
(S
));
7557 if Nkind
(S_Par
) /= N_Subprogram_Body
7558 or else No
(Declarations
(S_Par
))
7568 -- Retrieve the declaration node of N (if any). Note that N
7569 -- may be a part of a complex initialization expression.
7573 while Present
(P
) loop
7575 -- If we have a short circuit form, and we are within the right
7576 -- hand expression, we return false, since the right hand side
7577 -- is not guaranteed to be elaborated.
7579 if Nkind
(P
) in N_Short_Circuit
7580 and then N
= Right_Opnd
(P
)
7585 -- Similarly, if we are in an if expression and not part of the
7586 -- condition, then we return False, since neither the THEN or
7587 -- ELSE dependent expressions will always be elaborated.
7589 if Nkind
(P
) = N_If_Expression
7590 and then N
/= First
(Expressions
(P
))
7595 -- If within a case expression, and not part of the expression,
7596 -- then return False, since a particular dependent expression
7597 -- may not always be elaborated
7599 if Nkind
(P
) = N_Case_Expression
7600 and then N
/= Expression
(P
)
7605 -- While traversing the parent chain, if node N belongs to a
7606 -- statement, then it may never appear in a declarative region.
7608 if Nkind
(P
) in N_Statement_Other_Than_Procedure_Call
7609 or else Nkind
(P
) = N_Procedure_Call_Statement
7614 -- If we are at a declaration, record it and exit
7616 if Nkind
(P
) in N_Declaration
7617 and then Nkind
(P
) not in N_Subprogram_Specification
7630 return List_Containing
(N_Decl
) = Declarations
(S_Par
);
7632 end Safe_To_Capture_In_Parameter_Value
;
7638 procedure Mark_Non_Null
is
7640 -- Only case of interest is if node N is an entity name
7642 if Is_Entity_Name
(N
) then
7644 -- For sure, we want to clear an indication that this is known to
7645 -- be null, since if we get past this check, it definitely is not.
7647 Set_Is_Known_Null
(Entity
(N
), False);
7649 -- We can mark the entity as known to be non-null if either it is
7650 -- safe to capture the value, or in the case of an IN parameter,
7651 -- which is a constant, if the check we just installed is in the
7652 -- declarative region of the subprogram body. In this latter case,
7653 -- a check is decisive for the rest of the body if the expression
7654 -- is sure to be elaborated, since we know we have to elaborate
7655 -- all declarations before executing the body.
7657 -- Couldn't this always be part of Safe_To_Capture_Value ???
7659 if Safe_To_Capture_Value
(N
, Entity
(N
))
7660 or else Safe_To_Capture_In_Parameter_Value
7662 Set_Is_Known_Non_Null
(Entity
(N
));
7667 -- Start of processing for Install_Null_Excluding_Check
7670 pragma Assert
(Is_Access_Type
(Typ
));
7672 -- No check inside a generic, check will be emitted in instance
7674 if Inside_A_Generic
then
7678 -- No check needed if known to be non-null
7680 if Known_Non_Null
(N
) then
7684 -- If known to be null, here is where we generate a compile time check
7686 if Known_Null
(N
) then
7688 -- Avoid generating warning message inside init procs. In SPARK mode
7689 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
7690 -- since it will be turned into an error in any case.
7692 if (not Inside_Init_Proc
or else SPARK_Mode
= On
)
7694 -- Do not emit the warning within a conditional expression,
7695 -- where the expression might not be evaluated, and the warning
7696 -- appear as extraneous noise.
7698 and then not Within_Case_Or_If_Expression
(N
)
7700 Apply_Compile_Time_Constraint_Error
7701 (N
, "null value not allowed here??", CE_Access_Check_Failed
);
7703 -- Remaining cases, where we silently insert the raise
7707 Make_Raise_Constraint_Error
(Loc
,
7708 Reason
=> CE_Access_Check_Failed
));
7715 -- If entity is never assigned, for sure a warning is appropriate
7717 if Is_Entity_Name
(N
) then
7718 Check_Unset_Reference
(N
);
7721 -- No check needed if checks are suppressed on the range. Note that we
7722 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7723 -- so, since the program is erroneous, but we don't like to casually
7724 -- propagate such conclusions from erroneosity).
7726 if Access_Checks_Suppressed
(Typ
) then
7730 -- No check needed for access to concurrent record types generated by
7731 -- the expander. This is not just an optimization (though it does indeed
7732 -- remove junk checks). It also avoids generation of junk warnings.
7734 if Nkind
(N
) in N_Has_Chars
7735 and then Chars
(N
) = Name_uObject
7736 and then Is_Concurrent_Record_Type
7737 (Directly_Designated_Type
(Etype
(N
)))
7742 -- No check needed in interface thunks since the runtime check is
7743 -- already performed at the caller side.
7745 if Is_Thunk
(Current_Scope
) then
7749 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7750 -- the expander within exception handlers, since we know that the value
7751 -- can never be null.
7753 -- Is this really the right way to do this? Normally we generate such
7754 -- code in the expander with checks off, and that's how we suppress this
7755 -- kind of junk check ???
7757 if Nkind
(N
) = N_Function_Call
7758 and then Nkind
(Name
(N
)) = N_Explicit_Dereference
7759 and then Nkind
(Prefix
(Name
(N
))) = N_Identifier
7760 and then Is_RTE
(Entity
(Prefix
(Name
(N
))), RE_Get_Current_Excep
)
7765 -- Otherwise install access check
7768 Make_Raise_Constraint_Error
(Loc
,
7771 Left_Opnd
=> Duplicate_Subexpr_Move_Checks
(N
),
7772 Right_Opnd
=> Make_Null
(Loc
)),
7773 Reason
=> CE_Access_Check_Failed
));
7776 end Install_Null_Excluding_Check
;
7778 -----------------------------------------
7779 -- Install_Primitive_Elaboration_Check --
7780 -----------------------------------------
7782 procedure Install_Primitive_Elaboration_Check
(Subp_Body
: Node_Id
) is
7783 function Within_Compilation_Unit_Instance
7784 (Subp_Id
: Entity_Id
) return Boolean;
7785 -- Determine whether subprogram Subp_Id appears within an instance which
7786 -- acts as a compilation unit.
7788 --------------------------------------
7789 -- Within_Compilation_Unit_Instance --
7790 --------------------------------------
7792 function Within_Compilation_Unit_Instance
7793 (Subp_Id
: Entity_Id
) return Boolean
7798 -- Examine the scope chain looking for a compilation-unit-level
7801 Pack
:= Scope
(Subp_Id
);
7802 while Present
(Pack
) and then Pack
/= Standard_Standard
loop
7803 if Ekind
(Pack
) = E_Package
7804 and then Is_Generic_Instance
(Pack
)
7805 and then Nkind
(Parent
(Unit_Declaration_Node
(Pack
))) =
7811 Pack
:= Scope
(Pack
);
7815 end Within_Compilation_Unit_Instance
;
7817 -- Local declarations
7819 Context
: constant Node_Id
:= Parent
(Subp_Body
);
7820 Loc
: constant Source_Ptr
:= Sloc
(Subp_Body
);
7821 Subp_Id
: constant Entity_Id
:= Unique_Defining_Entity
(Subp_Body
);
7822 Subp_Decl
: constant Node_Id
:= Unit_Declaration_Node
(Subp_Id
);
7825 Flag_Id
: Entity_Id
;
7827 Tag_Typ
: Entity_Id
;
7829 -- Start of processing for Install_Primitive_Elaboration_Check
7832 -- Do not generate an elaboration check in compilation modes where
7833 -- expansion is not desirable.
7835 if ASIS_Mode
or GNATprove_Mode
then
7838 -- Do not generate an elaboration check if all checks have been
7841 elsif Suppress_Checks
then
7844 -- Do not generate an elaboration check if the related subprogram is
7845 -- not subjected to accessibility checks.
7847 elsif Elaboration_Checks_Suppressed
(Subp_Id
) then
7850 -- Do not generate an elaboration check if such code is not desirable
7852 elsif Restriction_Active
(No_Elaboration_Code
) then
7855 -- Do not consider subprograms which act as compilation units, because
7856 -- they cannot be the target of a dispatching call.
7858 elsif Nkind
(Context
) = N_Compilation_Unit
then
7861 -- Only nonabstract library-level source primitives are considered for
7865 (Comes_From_Source
(Subp_Id
)
7866 and then Is_Library_Level_Entity
(Subp_Id
)
7867 and then Is_Primitive
(Subp_Id
)
7868 and then not Is_Abstract_Subprogram
(Subp_Id
))
7872 -- Do not consider inlined primitives, because once the body is inlined
7873 -- the reference to the elaboration flag will be out of place and will
7874 -- result in an undefined symbol.
7876 elsif Is_Inlined
(Subp_Id
) or else Has_Pragma_Inline
(Subp_Id
) then
7879 -- Do not generate a duplicate elaboration check. This happens only in
7880 -- the case of primitives completed by an expression function, as the
7881 -- corresponding body is apparently analyzed and expanded twice.
7883 elsif Analyzed
(Subp_Body
) then
7886 -- Do not consider primitives which occur within an instance that acts
7887 -- as a compilation unit. Such an instance defines its spec and body out
7888 -- of order (body is first) within the tree, which causes the reference
7889 -- to the elaboration flag to appear as an undefined symbol.
7891 elsif Within_Compilation_Unit_Instance
(Subp_Id
) then
7895 Tag_Typ
:= Find_Dispatching_Type
(Subp_Id
);
7897 -- Only tagged primitives may be the target of a dispatching call
7899 if No
(Tag_Typ
) then
7902 -- Do not consider finalization-related primitives, because they may
7903 -- need to be called while elaboration is taking place.
7905 elsif Is_Controlled
(Tag_Typ
)
7906 and then Nam_In
(Chars
(Subp_Id
), Name_Adjust
,
7913 -- Create the declaration of the elaboration flag. The name carries a
7914 -- unique counter in case of name overloading.
7917 Make_Defining_Identifier
(Loc
,
7918 Chars
=> New_External_Name
(Chars
(Subp_Id
), 'F', -1));
7919 Set_Is_Frozen
(Flag_Id
);
7921 -- Insert the declaration of the elaboration flag in front of the
7922 -- primitive spec and analyze it in the proper context.
7924 Push_Scope
(Scope
(Subp_Id
));
7927 -- F : Boolean := False;
7929 Insert_Action
(Subp_Decl
,
7930 Make_Object_Declaration
(Loc
,
7931 Defining_Identifier
=> Flag_Id
,
7932 Object_Definition
=> New_Occurrence_Of
(Standard_Boolean
, Loc
),
7933 Expression
=> New_Occurrence_Of
(Standard_False
, Loc
)));
7936 -- Prevent the compiler from optimizing the elaboration check by killing
7937 -- the current value of the flag and the associated assignment.
7939 Set_Current_Value
(Flag_Id
, Empty
);
7940 Set_Last_Assignment
(Flag_Id
, Empty
);
7942 -- Add a check at the top of the body declarations to ensure that the
7943 -- elaboration flag has been set.
7945 Decls
:= Declarations
(Subp_Body
);
7949 Set_Declarations
(Subp_Body
, Decls
);
7954 -- raise Program_Error with "access before elaboration";
7958 Make_Raise_Program_Error
(Loc
,
7961 Right_Opnd
=> New_Occurrence_Of
(Flag_Id
, Loc
)),
7962 Reason
=> PE_Access_Before_Elaboration
));
7964 Analyze
(First
(Decls
));
7966 -- Set the elaboration flag once the body has been elaborated. Insert
7967 -- the statement after the subprogram stub when the primitive body is
7970 if Nkind
(Context
) = N_Subunit
then
7971 Set_Ins
:= Corresponding_Stub
(Context
);
7973 Set_Ins
:= Subp_Body
;
7979 Insert_After_And_Analyze
(Set_Ins
,
7980 Make_Assignment_Statement
(Loc
,
7981 Name
=> New_Occurrence_Of
(Flag_Id
, Loc
),
7982 Expression
=> New_Occurrence_Of
(Standard_True
, Loc
)));
7983 end Install_Primitive_Elaboration_Check
;
7985 --------------------------
7986 -- Install_Static_Check --
7987 --------------------------
7989 procedure Install_Static_Check
(R_Cno
: Node_Id
; Loc
: Source_Ptr
) is
7990 Stat
: constant Boolean := Is_OK_Static_Expression
(R_Cno
);
7991 Typ
: constant Entity_Id
:= Etype
(R_Cno
);
7995 Make_Raise_Constraint_Error
(Loc
,
7996 Reason
=> CE_Range_Check_Failed
));
7997 Set_Analyzed
(R_Cno
);
7998 Set_Etype
(R_Cno
, Typ
);
7999 Set_Raises_Constraint_Error
(R_Cno
);
8000 Set_Is_Static_Expression
(R_Cno
, Stat
);
8002 -- Now deal with possible local raise handling
8004 Possible_Local_Raise
(R_Cno
, Standard_Constraint_Error
);
8005 end Install_Static_Check
;
8007 -------------------------
8008 -- Is_Check_Suppressed --
8009 -------------------------
8011 function Is_Check_Suppressed
(E
: Entity_Id
; C
: Check_Id
) return Boolean is
8012 Ptr
: Suppress_Stack_Entry_Ptr
;
8015 -- First search the local entity suppress stack. We search this from the
8016 -- top of the stack down so that we get the innermost entry that applies
8017 -- to this case if there are nested entries.
8019 Ptr
:= Local_Suppress_Stack_Top
;
8020 while Ptr
/= null loop
8021 if (Ptr
.Entity
= Empty
or else Ptr
.Entity
= E
)
8022 and then (Ptr
.Check
= All_Checks
or else Ptr
.Check
= C
)
8024 return Ptr
.Suppress
;
8030 -- Now search the global entity suppress table for a matching entry.
8031 -- We also search this from the top down so that if there are multiple
8032 -- pragmas for the same entity, the last one applies (not clear what
8033 -- or whether the RM specifies this handling, but it seems reasonable).
8035 Ptr
:= Global_Suppress_Stack_Top
;
8036 while Ptr
/= null loop
8037 if (Ptr
.Entity
= Empty
or else Ptr
.Entity
= E
)
8038 and then (Ptr
.Check
= All_Checks
or else Ptr
.Check
= C
)
8040 return Ptr
.Suppress
;
8046 -- If we did not find a matching entry, then use the normal scope
8047 -- suppress value after all (actually this will be the global setting
8048 -- since it clearly was not overridden at any point). For a predefined
8049 -- check, we test the specific flag. For a user defined check, we check
8050 -- the All_Checks flag. The Overflow flag requires special handling to
8051 -- deal with the General vs Assertion case
8053 if C
= Overflow_Check
then
8054 return Overflow_Checks_Suppressed
(Empty
);
8055 elsif C
in Predefined_Check_Id
then
8056 return Scope_Suppress
.Suppress
(C
);
8058 return Scope_Suppress
.Suppress
(All_Checks
);
8060 end Is_Check_Suppressed
;
8062 ---------------------
8063 -- Kill_All_Checks --
8064 ---------------------
8066 procedure Kill_All_Checks
is
8068 if Debug_Flag_CC
then
8069 w
("Kill_All_Checks");
8072 -- We reset the number of saved checks to zero, and also modify all
8073 -- stack entries for statement ranges to indicate that the number of
8074 -- checks at each level is now zero.
8076 Num_Saved_Checks
:= 0;
8078 -- Note: the Int'Min here avoids any possibility of J being out of
8079 -- range when called from e.g. Conditional_Statements_Begin.
8081 for J
in 1 .. Int
'Min (Saved_Checks_TOS
, Saved_Checks_Stack
'Last) loop
8082 Saved_Checks_Stack
(J
) := 0;
8084 end Kill_All_Checks
;
8090 procedure Kill_Checks
(V
: Entity_Id
) is
8092 if Debug_Flag_CC
then
8093 w
("Kill_Checks for entity", Int
(V
));
8096 for J
in 1 .. Num_Saved_Checks
loop
8097 if Saved_Checks
(J
).Entity
= V
then
8098 if Debug_Flag_CC
then
8099 w
(" Checks killed for saved check ", J
);
8102 Saved_Checks
(J
).Killed
:= True;
8107 ------------------------------
8108 -- Length_Checks_Suppressed --
8109 ------------------------------
8111 function Length_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
8113 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
8114 return Is_Check_Suppressed
(E
, Length_Check
);
8116 return Scope_Suppress
.Suppress
(Length_Check
);
8118 end Length_Checks_Suppressed
;
8120 -----------------------
8121 -- Make_Bignum_Block --
8122 -----------------------
8124 function Make_Bignum_Block
(Loc
: Source_Ptr
) return Node_Id
is
8125 M
: constant Entity_Id
:= Make_Defining_Identifier
(Loc
, Name_uM
);
8128 Make_Block_Statement
(Loc
,
8130 New_List
(Build_SS_Mark_Call
(Loc
, M
)),
8131 Handled_Statement_Sequence
=>
8132 Make_Handled_Sequence_Of_Statements
(Loc
,
8133 Statements
=> New_List
(Build_SS_Release_Call
(Loc
, M
))));
8134 end Make_Bignum_Block
;
8136 ----------------------------------
8137 -- Minimize_Eliminate_Overflows --
8138 ----------------------------------
8140 -- This is a recursive routine that is called at the top of an expression
8141 -- tree to properly process overflow checking for a whole subtree by making
8142 -- recursive calls to process operands. This processing may involve the use
8143 -- of bignum or long long integer arithmetic, which will change the types
8144 -- of operands and results. That's why we can't do this bottom up (since
8145 -- it would interfere with semantic analysis).
8147 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8148 -- the operator expansion routines, as well as the expansion routines for
8149 -- if/case expression, do nothing (for the moment) except call the routine
8150 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8151 -- routine does nothing for non top-level nodes, so at the point where the
8152 -- call is made for the top level node, the entire expression subtree has
8153 -- not been expanded, or processed for overflow. All that has to happen as
8154 -- a result of the top level call to this routine.
8156 -- As noted above, the overflow processing works by making recursive calls
8157 -- for the operands, and figuring out what to do, based on the processing
8158 -- of these operands (e.g. if a bignum operand appears, the parent op has
8159 -- to be done in bignum mode), and the determined ranges of the operands.
8161 -- After possible rewriting of a constituent subexpression node, a call is
8162 -- made to either reexpand the node (if nothing has changed) or reanalyze
8163 -- the node (if it has been modified by the overflow check processing). The
8164 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8165 -- a recursive call into the whole overflow apparatus, an important rule
8166 -- for this call is that the overflow handling mode must be temporarily set
8169 procedure Minimize_Eliminate_Overflows
8173 Top_Level
: Boolean)
8175 Rtyp
: constant Entity_Id
:= Etype
(N
);
8176 pragma Assert
(Is_Signed_Integer_Type
(Rtyp
));
8177 -- Result type, must be a signed integer type
8179 Check_Mode
: constant Overflow_Mode_Type
:= Overflow_Check_Mode
;
8180 pragma Assert
(Check_Mode
in Minimized_Or_Eliminated
);
8182 Loc
: constant Source_Ptr
:= Sloc
(N
);
8185 -- Ranges of values for right operand (operator case)
8187 Llo
: Uint
:= No_Uint
; -- initialize to prevent warning
8188 Lhi
: Uint
:= No_Uint
; -- initialize to prevent warning
8189 -- Ranges of values for left operand (operator case)
8191 LLIB
: constant Entity_Id
:= Base_Type
(Standard_Long_Long_Integer
);
8192 -- Operands and results are of this type when we convert
8194 LLLo
: constant Uint
:= Intval
(Type_Low_Bound
(LLIB
));
8195 LLHi
: constant Uint
:= Intval
(Type_High_Bound
(LLIB
));
8196 -- Bounds of Long_Long_Integer
8198 Binary
: constant Boolean := Nkind
(N
) in N_Binary_Op
;
8199 -- Indicates binary operator case
8202 -- Used in call to Determine_Range
8204 Bignum_Operands
: Boolean;
8205 -- Set True if one or more operands is already of type Bignum, meaning
8206 -- that for sure (regardless of Top_Level setting) we are committed to
8207 -- doing the operation in Bignum mode (or in the case of a case or if
8208 -- expression, converting all the dependent expressions to Bignum).
8210 Long_Long_Integer_Operands
: Boolean;
8211 -- Set True if one or more operands is already of type Long_Long_Integer
8212 -- which means that if the result is known to be in the result type
8213 -- range, then we must convert such operands back to the result type.
8215 procedure Reanalyze
(Typ
: Entity_Id
; Suppress
: Boolean := False);
8216 -- This is called when we have modified the node and we therefore need
8217 -- to reanalyze it. It is important that we reset the mode to STRICT for
8218 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
8219 -- we would reenter this routine recursively which would not be good.
8220 -- The argument Suppress is set True if we also want to suppress
8221 -- overflow checking for the reexpansion (this is set when we know
8222 -- overflow is not possible). Typ is the type for the reanalysis.
8224 procedure Reexpand
(Suppress
: Boolean := False);
8225 -- This is like Reanalyze, but does not do the Analyze step, it only
8226 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8227 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8228 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8229 -- Note that skipping reanalysis is not just an optimization, testing
8230 -- has showed up several complex cases in which reanalyzing an already
8231 -- analyzed node causes incorrect behavior.
8233 function In_Result_Range
return Boolean;
8234 -- Returns True iff Lo .. Hi are within range of the result type
8236 procedure Max
(A
: in out Uint
; B
: Uint
);
8237 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
8239 procedure Min
(A
: in out Uint
; B
: Uint
);
8240 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
8242 ---------------------
8243 -- In_Result_Range --
8244 ---------------------
8246 function In_Result_Range
return Boolean is
8248 if Lo
= No_Uint
or else Hi
= No_Uint
then
8251 elsif Is_OK_Static_Subtype
(Etype
(N
)) then
8252 return Lo
>= Expr_Value
(Type_Low_Bound
(Rtyp
))
8254 Hi
<= Expr_Value
(Type_High_Bound
(Rtyp
));
8257 return Lo
>= Expr_Value
(Type_Low_Bound
(Base_Type
(Rtyp
)))
8259 Hi
<= Expr_Value
(Type_High_Bound
(Base_Type
(Rtyp
)));
8261 end In_Result_Range
;
8267 procedure Max
(A
: in out Uint
; B
: Uint
) is
8269 if A
= No_Uint
or else B
> A
then
8278 procedure Min
(A
: in out Uint
; B
: Uint
) is
8280 if A
= No_Uint
or else B
< A
then
8289 procedure Reanalyze
(Typ
: Entity_Id
; Suppress
: Boolean := False) is
8290 Svg
: constant Overflow_Mode_Type
:=
8291 Scope_Suppress
.Overflow_Mode_General
;
8292 Sva
: constant Overflow_Mode_Type
:=
8293 Scope_Suppress
.Overflow_Mode_Assertions
;
8294 Svo
: constant Boolean :=
8295 Scope_Suppress
.Suppress
(Overflow_Check
);
8298 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
8299 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
8302 Scope_Suppress
.Suppress
(Overflow_Check
) := True;
8305 Analyze_And_Resolve
(N
, Typ
);
8307 Scope_Suppress
.Suppress
(Overflow_Check
) := Svo
;
8308 Scope_Suppress
.Overflow_Mode_General
:= Svg
;
8309 Scope_Suppress
.Overflow_Mode_Assertions
:= Sva
;
8316 procedure Reexpand
(Suppress
: Boolean := False) is
8317 Svg
: constant Overflow_Mode_Type
:=
8318 Scope_Suppress
.Overflow_Mode_General
;
8319 Sva
: constant Overflow_Mode_Type
:=
8320 Scope_Suppress
.Overflow_Mode_Assertions
;
8321 Svo
: constant Boolean :=
8322 Scope_Suppress
.Suppress
(Overflow_Check
);
8325 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
8326 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
8327 Set_Analyzed
(N
, False);
8330 Scope_Suppress
.Suppress
(Overflow_Check
) := True;
8335 Scope_Suppress
.Suppress
(Overflow_Check
) := Svo
;
8336 Scope_Suppress
.Overflow_Mode_General
:= Svg
;
8337 Scope_Suppress
.Overflow_Mode_Assertions
:= Sva
;
8340 -- Start of processing for Minimize_Eliminate_Overflows
8343 -- Case where we do not have a signed integer arithmetic operation
8345 if not Is_Signed_Integer_Arithmetic_Op
(N
) then
8347 -- Use the normal Determine_Range routine to get the range. We
8348 -- don't require operands to be valid, invalid values may result in
8349 -- rubbish results where the result has not been properly checked for
8350 -- overflow, that's fine.
8352 Determine_Range
(N
, OK
, Lo
, Hi
, Assume_Valid
=> False);
8354 -- If Determine_Range did not work (can this in fact happen? Not
8355 -- clear but might as well protect), use type bounds.
8358 Lo
:= Intval
(Type_Low_Bound
(Base_Type
(Etype
(N
))));
8359 Hi
:= Intval
(Type_High_Bound
(Base_Type
(Etype
(N
))));
8362 -- If we don't have a binary operator, all we have to do is to set
8363 -- the Hi/Lo range, so we are done.
8367 -- Processing for if expression
8369 elsif Nkind
(N
) = N_If_Expression
then
8371 Then_DE
: constant Node_Id
:= Next
(First
(Expressions
(N
)));
8372 Else_DE
: constant Node_Id
:= Next
(Then_DE
);
8375 Bignum_Operands
:= False;
8377 Minimize_Eliminate_Overflows
8378 (Then_DE
, Lo
, Hi
, Top_Level
=> False);
8380 if Lo
= No_Uint
then
8381 Bignum_Operands
:= True;
8384 Minimize_Eliminate_Overflows
8385 (Else_DE
, Rlo
, Rhi
, Top_Level
=> False);
8387 if Rlo
= No_Uint
then
8388 Bignum_Operands
:= True;
8390 Long_Long_Integer_Operands
:=
8391 Etype
(Then_DE
) = LLIB
or else Etype
(Else_DE
) = LLIB
;
8397 -- If at least one of our operands is now Bignum, we must rebuild
8398 -- the if expression to use Bignum operands. We will analyze the
8399 -- rebuilt if expression with overflow checks off, since once we
8400 -- are in bignum mode, we are all done with overflow checks.
8402 if Bignum_Operands
then
8404 Make_If_Expression
(Loc
,
8405 Expressions
=> New_List
(
8406 Remove_Head
(Expressions
(N
)),
8407 Convert_To_Bignum
(Then_DE
),
8408 Convert_To_Bignum
(Else_DE
)),
8409 Is_Elsif
=> Is_Elsif
(N
)));
8411 Reanalyze
(RTE
(RE_Bignum
), Suppress
=> True);
8413 -- If we have no Long_Long_Integer operands, then we are in result
8414 -- range, since it means that none of our operands felt the need
8415 -- to worry about overflow (otherwise it would have already been
8416 -- converted to long long integer or bignum). We reexpand to
8417 -- complete the expansion of the if expression (but we do not
8418 -- need to reanalyze).
8420 elsif not Long_Long_Integer_Operands
then
8421 Set_Do_Overflow_Check
(N
, False);
8424 -- Otherwise convert us to long long integer mode. Note that we
8425 -- don't need any further overflow checking at this level.
8428 Convert_To_And_Rewrite
(LLIB
, Then_DE
);
8429 Convert_To_And_Rewrite
(LLIB
, Else_DE
);
8430 Set_Etype
(N
, LLIB
);
8432 -- Now reanalyze with overflow checks off
8434 Set_Do_Overflow_Check
(N
, False);
8435 Reanalyze
(LLIB
, Suppress
=> True);
8441 -- Here for case expression
8443 elsif Nkind
(N
) = N_Case_Expression
then
8444 Bignum_Operands
:= False;
8445 Long_Long_Integer_Operands
:= False;
8451 -- Loop through expressions applying recursive call
8453 Alt
:= First
(Alternatives
(N
));
8454 while Present
(Alt
) loop
8456 Aexp
: constant Node_Id
:= Expression
(Alt
);
8459 Minimize_Eliminate_Overflows
8460 (Aexp
, Lo
, Hi
, Top_Level
=> False);
8462 if Lo
= No_Uint
then
8463 Bignum_Operands
:= True;
8464 elsif Etype
(Aexp
) = LLIB
then
8465 Long_Long_Integer_Operands
:= True;
8472 -- If we have no bignum or long long integer operands, it means
8473 -- that none of our dependent expressions could raise overflow.
8474 -- In this case, we simply return with no changes except for
8475 -- resetting the overflow flag, since we are done with overflow
8476 -- checks for this node. We will reexpand to get the needed
8477 -- expansion for the case expression, but we do not need to
8478 -- reanalyze, since nothing has changed.
8480 if not (Bignum_Operands
or Long_Long_Integer_Operands
) then
8481 Set_Do_Overflow_Check
(N
, False);
8482 Reexpand
(Suppress
=> True);
8484 -- Otherwise we are going to rebuild the case expression using
8485 -- either bignum or long long integer operands throughout.
8490 pragma Warnings
(Off
, Rtype
);
8495 New_Alts
:= New_List
;
8496 Alt
:= First
(Alternatives
(N
));
8497 while Present
(Alt
) loop
8498 if Bignum_Operands
then
8499 New_Exp
:= Convert_To_Bignum
(Expression
(Alt
));
8500 Rtype
:= RTE
(RE_Bignum
);
8502 New_Exp
:= Convert_To
(LLIB
, Expression
(Alt
));
8506 Append_To
(New_Alts
,
8507 Make_Case_Expression_Alternative
(Sloc
(Alt
),
8509 Discrete_Choices
=> Discrete_Choices
(Alt
),
8510 Expression
=> New_Exp
));
8516 Make_Case_Expression
(Loc
,
8517 Expression
=> Expression
(N
),
8518 Alternatives
=> New_Alts
));
8520 Reanalyze
(Rtype
, Suppress
=> True);
8528 -- If we have an arithmetic operator we make recursive calls on the
8529 -- operands to get the ranges (and to properly process the subtree
8530 -- that lies below us).
8532 Minimize_Eliminate_Overflows
8533 (Right_Opnd
(N
), Rlo
, Rhi
, Top_Level
=> False);
8536 Minimize_Eliminate_Overflows
8537 (Left_Opnd
(N
), Llo
, Lhi
, Top_Level
=> False);
8540 -- Record if we have Long_Long_Integer operands
8542 Long_Long_Integer_Operands
:=
8543 Etype
(Right_Opnd
(N
)) = LLIB
8544 or else (Binary
and then Etype
(Left_Opnd
(N
)) = LLIB
);
8546 -- If either operand is a bignum, then result will be a bignum and we
8547 -- don't need to do any range analysis. As previously discussed we could
8548 -- do range analysis in such cases, but it could mean working with giant
8549 -- numbers at compile time for very little gain (the number of cases
8550 -- in which we could slip back from bignum mode is small).
8552 if Rlo
= No_Uint
or else (Binary
and then Llo
= No_Uint
) then
8555 Bignum_Operands
:= True;
8557 -- Otherwise compute result range
8560 Bignum_Operands
:= False;
8568 Hi
:= UI_Max
(abs Rlo
, abs Rhi
);
8580 -- If the right operand can only be zero, set 0..0
8582 if Rlo
= 0 and then Rhi
= 0 then
8586 -- Possible bounds of division must come from dividing end
8587 -- values of the input ranges (four possibilities), provided
8588 -- zero is not included in the possible values of the right
8591 -- Otherwise, we just consider two intervals of values for
8592 -- the right operand: the interval of negative values (up to
8593 -- -1) and the interval of positive values (starting at 1).
8594 -- Since division by 1 is the identity, and division by -1
8595 -- is negation, we get all possible bounds of division in that
8596 -- case by considering:
8597 -- - all values from the division of end values of input
8599 -- - the end values of the left operand;
8600 -- - the negation of the end values of the left operand.
8604 Mrk
: constant Uintp
.Save_Mark
:= Mark
;
8605 -- Mark so we can release the RR and Ev values
8613 -- Discard extreme values of zero for the divisor, since
8614 -- they will simply result in an exception in any case.
8622 -- Compute possible bounds coming from dividing end
8623 -- values of the input ranges.
8630 Lo
:= UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
));
8631 Hi
:= UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
));
8633 -- If the right operand can be both negative or positive,
8634 -- include the end values of the left operand in the
8635 -- extreme values, as well as their negation.
8637 if Rlo
< 0 and then Rhi
> 0 then
8644 UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
)));
8646 UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
)));
8649 -- Release the RR and Ev values
8651 Release_And_Save
(Mrk
, Lo
, Hi
);
8659 -- Discard negative values for the exponent, since they will
8660 -- simply result in an exception in any case.
8668 -- Estimate number of bits in result before we go computing
8669 -- giant useless bounds. Basically the number of bits in the
8670 -- result is the number of bits in the base multiplied by the
8671 -- value of the exponent. If this is big enough that the result
8672 -- definitely won't fit in Long_Long_Integer, switch to bignum
8673 -- mode immediately, and avoid computing giant bounds.
8675 -- The comparison here is approximate, but conservative, it
8676 -- only clicks on cases that are sure to exceed the bounds.
8678 if Num_Bits
(UI_Max
(abs Llo
, abs Lhi
)) * Rhi
+ 1 > 100 then
8682 -- If right operand is zero then result is 1
8689 -- High bound comes either from exponentiation of largest
8690 -- positive value to largest exponent value, or from
8691 -- the exponentiation of most negative value to an
8705 if Rhi
mod 2 = 0 then
8708 Hi2
:= Llo
** (Rhi
- 1);
8714 Hi
:= UI_Max
(Hi1
, Hi2
);
8717 -- Result can only be negative if base can be negative
8720 if Rhi
mod 2 = 0 then
8721 Lo
:= Llo
** (Rhi
- 1);
8726 -- Otherwise low bound is minimum ** minimum
8743 Maxabs
: constant Uint
:= UI_Max
(abs Rlo
, abs Rhi
) - 1;
8744 -- This is the maximum absolute value of the result
8750 -- The result depends only on the sign and magnitude of
8751 -- the right operand, it does not depend on the sign or
8752 -- magnitude of the left operand.
8765 when N_Op_Multiply
=>
8767 -- Possible bounds of multiplication must come from multiplying
8768 -- end values of the input ranges (four possibilities).
8771 Mrk
: constant Uintp
.Save_Mark
:= Mark
;
8772 -- Mark so we can release the Ev values
8774 Ev1
: constant Uint
:= Llo
* Rlo
;
8775 Ev2
: constant Uint
:= Llo
* Rhi
;
8776 Ev3
: constant Uint
:= Lhi
* Rlo
;
8777 Ev4
: constant Uint
:= Lhi
* Rhi
;
8780 Lo
:= UI_Min
(UI_Min
(Ev1
, Ev2
), UI_Min
(Ev3
, Ev4
));
8781 Hi
:= UI_Max
(UI_Max
(Ev1
, Ev2
), UI_Max
(Ev3
, Ev4
));
8783 -- Release the Ev values
8785 Release_And_Save
(Mrk
, Lo
, Hi
);
8788 -- Plus operator (affirmation)
8798 Maxabs
: constant Uint
:= UI_Max
(abs Rlo
, abs Rhi
) - 1;
8799 -- This is the maximum absolute value of the result. Note
8800 -- that the result range does not depend on the sign of the
8807 -- Case of left operand negative, which results in a range
8808 -- of -Maxabs .. 0 for those negative values. If there are
8809 -- no negative values then Lo value of result is always 0.
8815 -- Case of left operand positive
8824 when N_Op_Subtract
=>
8828 -- Nothing else should be possible
8831 raise Program_Error
;
8835 -- Here for the case where we have not rewritten anything (no bignum
8836 -- operands or long long integer operands), and we know the result.
8837 -- If we know we are in the result range, and we do not have Bignum
8838 -- operands or Long_Long_Integer operands, we can just reexpand with
8839 -- overflow checks turned off (since we know we cannot have overflow).
8840 -- As always the reexpansion is required to complete expansion of the
8841 -- operator, but we do not need to reanalyze, and we prevent recursion
8842 -- by suppressing the check.
8844 if not (Bignum_Operands
or Long_Long_Integer_Operands
)
8845 and then In_Result_Range
8847 Set_Do_Overflow_Check
(N
, False);
8848 Reexpand
(Suppress
=> True);
8851 -- Here we know that we are not in the result range, and in the general
8852 -- case we will move into either the Bignum or Long_Long_Integer domain
8853 -- to compute the result. However, there is one exception. If we are
8854 -- at the top level, and we do not have Bignum or Long_Long_Integer
8855 -- operands, we will have to immediately convert the result back to
8856 -- the result type, so there is no point in Bignum/Long_Long_Integer
8860 and then not (Bignum_Operands
or Long_Long_Integer_Operands
)
8862 -- One further refinement. If we are at the top level, but our parent
8863 -- is a type conversion, then go into bignum or long long integer node
8864 -- since the result will be converted to that type directly without
8865 -- going through the result type, and we may avoid an overflow. This
8866 -- is the case for example of Long_Long_Integer (A ** 4), where A is
8867 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
8868 -- but does not fit in Integer.
8870 and then Nkind
(Parent
(N
)) /= N_Type_Conversion
8872 -- Here keep original types, but we need to complete analysis
8874 -- One subtlety. We can't just go ahead and do an analyze operation
8875 -- here because it will cause recursion into the whole MINIMIZED/
8876 -- ELIMINATED overflow processing which is not what we want. Here
8877 -- we are at the top level, and we need a check against the result
8878 -- mode (i.e. we want to use STRICT mode). So do exactly that.
8879 -- Also, we have not modified the node, so this is a case where
8880 -- we need to reexpand, but not reanalyze.
8885 -- Cases where we do the operation in Bignum mode. This happens either
8886 -- because one of our operands is in Bignum mode already, or because
8887 -- the computed bounds are outside the bounds of Long_Long_Integer,
8888 -- which in some cases can be indicated by Hi and Lo being No_Uint.
8890 -- Note: we could do better here and in some cases switch back from
8891 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
8892 -- 0 .. 1, but the cases are rare and it is not worth the effort.
8893 -- Failing to do this switching back is only an efficiency issue.
8895 elsif Lo
= No_Uint
or else Lo
< LLLo
or else Hi
> LLHi
then
8897 -- OK, we are definitely outside the range of Long_Long_Integer. The
8898 -- question is whether to move to Bignum mode, or stay in the domain
8899 -- of Long_Long_Integer, signalling that an overflow check is needed.
8901 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
8902 -- the Bignum business. In ELIMINATED mode, we will normally move
8903 -- into Bignum mode, but there is an exception if neither of our
8904 -- operands is Bignum now, and we are at the top level (Top_Level
8905 -- set True). In this case, there is no point in moving into Bignum
8906 -- mode to prevent overflow if the caller will immediately convert
8907 -- the Bignum value back to LLI with an overflow check. It's more
8908 -- efficient to stay in LLI mode with an overflow check (if needed)
8910 if Check_Mode
= Minimized
8911 or else (Top_Level
and not Bignum_Operands
)
8913 if Do_Overflow_Check
(N
) then
8914 Enable_Overflow_Check
(N
);
8917 -- The result now has to be in Long_Long_Integer mode, so adjust
8918 -- the possible range to reflect this. Note these calls also
8919 -- change No_Uint values from the top level case to LLI bounds.
8924 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
8927 pragma Assert
(Check_Mode
= Eliminated
);
8936 Fent
:= RTE
(RE_Big_Abs
);
8939 Fent
:= RTE
(RE_Big_Add
);
8942 Fent
:= RTE
(RE_Big_Div
);
8945 Fent
:= RTE
(RE_Big_Exp
);
8948 Fent
:= RTE
(RE_Big_Neg
);
8951 Fent
:= RTE
(RE_Big_Mod
);
8953 when N_Op_Multiply
=>
8954 Fent
:= RTE
(RE_Big_Mul
);
8957 Fent
:= RTE
(RE_Big_Rem
);
8959 when N_Op_Subtract
=>
8960 Fent
:= RTE
(RE_Big_Sub
);
8962 -- Anything else is an internal error, this includes the
8963 -- N_Op_Plus case, since how can plus cause the result
8964 -- to be out of range if the operand is in range?
8967 raise Program_Error
;
8970 -- Construct argument list for Bignum call, converting our
8971 -- operands to Bignum form if they are not already there.
8976 Append_To
(Args
, Convert_To_Bignum
(Left_Opnd
(N
)));
8979 Append_To
(Args
, Convert_To_Bignum
(Right_Opnd
(N
)));
8981 -- Now rewrite the arithmetic operator with a call to the
8982 -- corresponding bignum function.
8985 Make_Function_Call
(Loc
,
8986 Name
=> New_Occurrence_Of
(Fent
, Loc
),
8987 Parameter_Associations
=> Args
));
8988 Reanalyze
(RTE
(RE_Bignum
), Suppress
=> True);
8990 -- Indicate result is Bignum mode
8998 -- Otherwise we are in range of Long_Long_Integer, so no overflow
8999 -- check is required, at least not yet.
9002 Set_Do_Overflow_Check
(N
, False);
9005 -- Here we are not in Bignum territory, but we may have long long
9006 -- integer operands that need special handling. First a special check:
9007 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9008 -- it means we converted it to prevent overflow, but exponentiation
9009 -- requires a Natural right operand, so convert it back to Natural.
9010 -- This conversion may raise an exception which is fine.
9012 if Nkind
(N
) = N_Op_Expon
and then Etype
(Right_Opnd
(N
)) = LLIB
then
9013 Convert_To_And_Rewrite
(Standard_Natural
, Right_Opnd
(N
));
9016 -- Here we will do the operation in Long_Long_Integer. We do this even
9017 -- if we know an overflow check is required, better to do this in long
9018 -- long integer mode, since we are less likely to overflow.
9020 -- Convert right or only operand to Long_Long_Integer, except that
9021 -- we do not touch the exponentiation right operand.
9023 if Nkind
(N
) /= N_Op_Expon
then
9024 Convert_To_And_Rewrite
(LLIB
, Right_Opnd
(N
));
9027 -- Convert left operand to Long_Long_Integer for binary case
9030 Convert_To_And_Rewrite
(LLIB
, Left_Opnd
(N
));
9033 -- Reset node to unanalyzed
9035 Set_Analyzed
(N
, False);
9036 Set_Etype
(N
, Empty
);
9037 Set_Entity
(N
, Empty
);
9039 -- Now analyze this new node. This reanalysis will complete processing
9040 -- for the node. In particular we will complete the expansion of an
9041 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9042 -- we will complete any division checks (since we have not changed the
9043 -- setting of the Do_Division_Check flag).
9045 -- We do this reanalysis in STRICT mode to avoid recursion into the
9046 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9049 SG
: constant Overflow_Mode_Type
:=
9050 Scope_Suppress
.Overflow_Mode_General
;
9051 SA
: constant Overflow_Mode_Type
:=
9052 Scope_Suppress
.Overflow_Mode_Assertions
;
9055 Scope_Suppress
.Overflow_Mode_General
:= Strict
;
9056 Scope_Suppress
.Overflow_Mode_Assertions
:= Strict
;
9058 if not Do_Overflow_Check
(N
) then
9059 Reanalyze
(LLIB
, Suppress
=> True);
9064 Scope_Suppress
.Overflow_Mode_General
:= SG
;
9065 Scope_Suppress
.Overflow_Mode_Assertions
:= SA
;
9067 end Minimize_Eliminate_Overflows
;
9069 -------------------------
9070 -- Overflow_Check_Mode --
9071 -------------------------
9073 function Overflow_Check_Mode
return Overflow_Mode_Type
is
9075 if In_Assertion_Expr
= 0 then
9076 return Scope_Suppress
.Overflow_Mode_General
;
9078 return Scope_Suppress
.Overflow_Mode_Assertions
;
9080 end Overflow_Check_Mode
;
9082 --------------------------------
9083 -- Overflow_Checks_Suppressed --
9084 --------------------------------
9086 function Overflow_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9088 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
9089 return Is_Check_Suppressed
(E
, Overflow_Check
);
9091 return Scope_Suppress
.Suppress
(Overflow_Check
);
9093 end Overflow_Checks_Suppressed
;
9095 ---------------------------------
9096 -- Predicate_Checks_Suppressed --
9097 ---------------------------------
9099 function Predicate_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9101 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
9102 return Is_Check_Suppressed
(E
, Predicate_Check
);
9104 return Scope_Suppress
.Suppress
(Predicate_Check
);
9106 end Predicate_Checks_Suppressed
;
9108 -----------------------------
9109 -- Range_Checks_Suppressed --
9110 -----------------------------
9112 function Range_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
9115 if Kill_Range_Checks
(E
) then
9118 elsif Checks_May_Be_Suppressed
(E
) then
9119 return Is_Check_Suppressed
(E
, Range_Check
);
9123 return Scope_Suppress
.Suppress
(Range_Check
);
9124 end Range_Checks_Suppressed
;
9126 -----------------------------------------
9127 -- Range_Or_Validity_Checks_Suppressed --
9128 -----------------------------------------
9130 -- Note: the coding would be simpler here if we simply made appropriate
9131 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9132 -- duplicated checks which we prefer to avoid.
9134 function Range_Or_Validity_Checks_Suppressed
9135 (Expr
: Node_Id
) return Boolean
9138 -- Immediate return if scope checks suppressed for either check
9140 if Scope_Suppress
.Suppress
(Range_Check
)
9142 Scope_Suppress
.Suppress
(Validity_Check
)
9147 -- If no expression, that's odd, decide that checks are suppressed,
9148 -- since we don't want anyone trying to do checks in this case, which
9149 -- is most likely the result of some other error.
9155 -- Expression is present, so perform suppress checks on type
9158 Typ
: constant Entity_Id
:= Etype
(Expr
);
9160 if Checks_May_Be_Suppressed
(Typ
)
9161 and then (Is_Check_Suppressed
(Typ
, Range_Check
)
9163 Is_Check_Suppressed
(Typ
, Validity_Check
))
9169 -- If expression is an entity name, perform checks on this entity
9171 if Is_Entity_Name
(Expr
) then
9173 Ent
: constant Entity_Id
:= Entity
(Expr
);
9175 if Checks_May_Be_Suppressed
(Ent
) then
9176 return Is_Check_Suppressed
(Ent
, Range_Check
)
9177 or else Is_Check_Suppressed
(Ent
, Validity_Check
);
9182 -- If we fall through, no checks suppressed
9185 end Range_Or_Validity_Checks_Suppressed
;
9191 procedure Remove_Checks
(Expr
: Node_Id
) is
9192 function Process
(N
: Node_Id
) return Traverse_Result
;
9193 -- Process a single node during the traversal
9195 procedure Traverse
is new Traverse_Proc
(Process
);
9196 -- The traversal procedure itself
9202 function Process
(N
: Node_Id
) return Traverse_Result
is
9204 if Nkind
(N
) not in N_Subexpr
then
9208 Set_Do_Range_Check
(N
, False);
9212 Traverse
(Left_Opnd
(N
));
9215 when N_Attribute_Reference
=>
9216 Set_Do_Overflow_Check
(N
, False);
9218 when N_Function_Call
=>
9219 Set_Do_Tag_Check
(N
, False);
9222 Set_Do_Overflow_Check
(N
, False);
9226 Set_Do_Division_Check
(N
, False);
9229 Set_Do_Length_Check
(N
, False);
9232 Set_Do_Division_Check
(N
, False);
9235 Set_Do_Length_Check
(N
, False);
9238 Set_Do_Division_Check
(N
, False);
9241 Set_Do_Length_Check
(N
, False);
9248 Traverse
(Left_Opnd
(N
));
9251 when N_Selected_Component
=>
9252 Set_Do_Discriminant_Check
(N
, False);
9254 when N_Type_Conversion
=>
9255 Set_Do_Length_Check
(N
, False);
9256 Set_Do_Tag_Check
(N
, False);
9257 Set_Do_Overflow_Check
(N
, False);
9266 -- Start of processing for Remove_Checks
9272 ----------------------------
9273 -- Selected_Length_Checks --
9274 ----------------------------
9276 function Selected_Length_Checks
9278 Target_Typ
: Entity_Id
;
9279 Source_Typ
: Entity_Id
;
9280 Warn_Node
: Node_Id
) return Check_Result
9282 Loc
: constant Source_Ptr
:= Sloc
(Ck_Node
);
9285 Expr_Actual
: Node_Id
;
9287 Cond
: Node_Id
:= Empty
;
9288 Do_Access
: Boolean := False;
9289 Wnode
: Node_Id
:= Warn_Node
;
9290 Ret_Result
: Check_Result
:= (Empty
, Empty
);
9291 Num_Checks
: Natural := 0;
9293 procedure Add_Check
(N
: Node_Id
);
9294 -- Adds the action given to Ret_Result if N is non-Empty
9296 function Get_E_Length
(E
: Entity_Id
; Indx
: Nat
) return Node_Id
;
9297 function Get_N_Length
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
9298 -- Comments required ???
9300 function Same_Bounds
(L
: Node_Id
; R
: Node_Id
) return Boolean;
9301 -- True for equal literals and for nodes that denote the same constant
9302 -- entity, even if its value is not a static constant. This includes the
9303 -- case of a discriminal reference within an init proc. Removes some
9304 -- obviously superfluous checks.
9306 function Length_E_Cond
9307 (Exptyp
: Entity_Id
;
9309 Indx
: Nat
) return Node_Id
;
9310 -- Returns expression to compute:
9311 -- Typ'Length /= Exptyp'Length
9313 function Length_N_Cond
9316 Indx
: Nat
) return Node_Id
;
9317 -- Returns expression to compute:
9318 -- Typ'Length /= Expr'Length
9324 procedure Add_Check
(N
: Node_Id
) is
9328 -- For now, ignore attempt to place more than two checks ???
9329 -- This is really worrisome, are we really discarding checks ???
9331 if Num_Checks
= 2 then
9335 pragma Assert
(Num_Checks
<= 1);
9336 Num_Checks
:= Num_Checks
+ 1;
9337 Ret_Result
(Num_Checks
) := N
;
9345 function Get_E_Length
(E
: Entity_Id
; Indx
: Nat
) return Node_Id
is
9346 SE
: constant Entity_Id
:= Scope
(E
);
9348 E1
: Entity_Id
:= E
;
9351 if Ekind
(Scope
(E
)) = E_Record_Type
9352 and then Has_Discriminants
(Scope
(E
))
9354 N
:= Build_Discriminal_Subtype_Of_Component
(E
);
9357 Insert_Action
(Ck_Node
, N
);
9358 E1
:= Defining_Identifier
(N
);
9362 if Ekind
(E1
) = E_String_Literal_Subtype
then
9364 Make_Integer_Literal
(Loc
,
9365 Intval
=> String_Literal_Length
(E1
));
9367 elsif SE
/= Standard_Standard
9368 and then Ekind
(Scope
(SE
)) = E_Protected_Type
9369 and then Has_Discriminants
(Scope
(SE
))
9370 and then Has_Completion
(Scope
(SE
))
9371 and then not Inside_Init_Proc
9373 -- If the type whose length is needed is a private component
9374 -- constrained by a discriminant, we must expand the 'Length
9375 -- attribute into an explicit computation, using the discriminal
9376 -- of the current protected operation. This is because the actual
9377 -- type of the prival is constructed after the protected opera-
9378 -- tion has been fully expanded.
9381 Indx_Type
: Node_Id
;
9384 Do_Expand
: Boolean := False;
9387 Indx_Type
:= First_Index
(E
);
9389 for J
in 1 .. Indx
- 1 loop
9390 Next_Index
(Indx_Type
);
9393 Get_Index_Bounds
(Indx_Type
, Lo
, Hi
);
9395 if Nkind
(Lo
) = N_Identifier
9396 and then Ekind
(Entity
(Lo
)) = E_In_Parameter
9398 Lo
:= Get_Discriminal
(E
, Lo
);
9402 if Nkind
(Hi
) = N_Identifier
9403 and then Ekind
(Entity
(Hi
)) = E_In_Parameter
9405 Hi
:= Get_Discriminal
(E
, Hi
);
9410 if not Is_Entity_Name
(Lo
) then
9411 Lo
:= Duplicate_Subexpr_No_Checks
(Lo
);
9414 if not Is_Entity_Name
(Hi
) then
9415 Lo
:= Duplicate_Subexpr_No_Checks
(Hi
);
9421 Make_Op_Subtract
(Loc
,
9425 Right_Opnd
=> Make_Integer_Literal
(Loc
, 1));
9430 Make_Attribute_Reference
(Loc
,
9431 Attribute_Name
=> Name_Length
,
9433 New_Occurrence_Of
(E1
, Loc
));
9436 Set_Expressions
(N
, New_List
(
9437 Make_Integer_Literal
(Loc
, Indx
)));
9446 Make_Attribute_Reference
(Loc
,
9447 Attribute_Name
=> Name_Length
,
9449 New_Occurrence_Of
(E1
, Loc
));
9452 Set_Expressions
(N
, New_List
(
9453 Make_Integer_Literal
(Loc
, Indx
)));
9464 function Get_N_Length
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
9467 Make_Attribute_Reference
(Loc
,
9468 Attribute_Name
=> Name_Length
,
9470 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
9471 Expressions
=> New_List
(
9472 Make_Integer_Literal
(Loc
, Indx
)));
9479 function Length_E_Cond
9480 (Exptyp
: Entity_Id
;
9482 Indx
: Nat
) return Node_Id
9487 Left_Opnd
=> Get_E_Length
(Typ
, Indx
),
9488 Right_Opnd
=> Get_E_Length
(Exptyp
, Indx
));
9495 function Length_N_Cond
9498 Indx
: Nat
) return Node_Id
9503 Left_Opnd
=> Get_E_Length
(Typ
, Indx
),
9504 Right_Opnd
=> Get_N_Length
(Expr
, Indx
));
9511 function Same_Bounds
(L
: Node_Id
; R
: Node_Id
) return Boolean is
9514 (Nkind
(L
) = N_Integer_Literal
9515 and then Nkind
(R
) = N_Integer_Literal
9516 and then Intval
(L
) = Intval
(R
))
9520 and then Ekind
(Entity
(L
)) = E_Constant
9521 and then ((Is_Entity_Name
(R
)
9522 and then Entity
(L
) = Entity
(R
))
9524 (Nkind
(R
) = N_Type_Conversion
9525 and then Is_Entity_Name
(Expression
(R
))
9526 and then Entity
(L
) = Entity
(Expression
(R
)))))
9530 and then Ekind
(Entity
(R
)) = E_Constant
9531 and then Nkind
(L
) = N_Type_Conversion
9532 and then Is_Entity_Name
(Expression
(L
))
9533 and then Entity
(R
) = Entity
(Expression
(L
)))
9537 and then Is_Entity_Name
(R
)
9538 and then Entity
(L
) = Entity
(R
)
9539 and then Ekind
(Entity
(L
)) = E_In_Parameter
9540 and then Inside_Init_Proc
);
9543 -- Start of processing for Selected_Length_Checks
9546 -- Checks will be applied only when generating code
9548 if not Expander_Active
then
9552 if Target_Typ
= Any_Type
9553 or else Target_Typ
= Any_Composite
9554 or else Raises_Constraint_Error
(Ck_Node
)
9563 T_Typ
:= Target_Typ
;
9565 if No
(Source_Typ
) then
9566 S_Typ
:= Etype
(Ck_Node
);
9568 S_Typ
:= Source_Typ
;
9571 if S_Typ
= Any_Type
or else S_Typ
= Any_Composite
then
9575 if Is_Access_Type
(T_Typ
) and then Is_Access_Type
(S_Typ
) then
9576 S_Typ
:= Designated_Type
(S_Typ
);
9577 T_Typ
:= Designated_Type
(T_Typ
);
9580 -- A simple optimization for the null case
9582 if Known_Null
(Ck_Node
) then
9587 if Is_Array_Type
(T_Typ
) and then Is_Array_Type
(S_Typ
) then
9588 if Is_Constrained
(T_Typ
) then
9590 -- The checking code to be generated will freeze the corresponding
9591 -- array type. However, we must freeze the type now, so that the
9592 -- freeze node does not appear within the generated if expression,
9595 Freeze_Before
(Ck_Node
, T_Typ
);
9597 Expr_Actual
:= Get_Referenced_Object
(Ck_Node
);
9598 Exptyp
:= Get_Actual_Subtype
(Ck_Node
);
9600 if Is_Access_Type
(Exptyp
) then
9601 Exptyp
:= Designated_Type
(Exptyp
);
9604 -- String_Literal case. This needs to be handled specially be-
9605 -- cause no index types are available for string literals. The
9606 -- condition is simply:
9608 -- T_Typ'Length = string-literal-length
9610 if Nkind
(Expr_Actual
) = N_String_Literal
9611 and then Ekind
(Etype
(Expr_Actual
)) = E_String_Literal_Subtype
9615 Left_Opnd
=> Get_E_Length
(T_Typ
, 1),
9617 Make_Integer_Literal
(Loc
,
9619 String_Literal_Length
(Etype
(Expr_Actual
))));
9621 -- General array case. Here we have a usable actual subtype for
9622 -- the expression, and the condition is built from the two types
9625 -- T_Typ'Length /= Exptyp'Length or else
9626 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9627 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9630 elsif Is_Constrained
(Exptyp
) then
9632 Ndims
: constant Nat
:= Number_Dimensions
(T_Typ
);
9645 -- At the library level, we need to ensure that the type of
9646 -- the object is elaborated before the check itself is
9647 -- emitted. This is only done if the object is in the
9648 -- current compilation unit, otherwise the type is frozen
9649 -- and elaborated in its unit.
9651 if Is_Itype
(Exptyp
)
9653 Ekind
(Cunit_Entity
(Current_Sem_Unit
)) = E_Package
9655 not In_Package_Body
(Cunit_Entity
(Current_Sem_Unit
))
9656 and then In_Open_Scopes
(Scope
(Exptyp
))
9658 Ref_Node
:= Make_Itype_Reference
(Sloc
(Ck_Node
));
9659 Set_Itype
(Ref_Node
, Exptyp
);
9660 Insert_Action
(Ck_Node
, Ref_Node
);
9663 L_Index
:= First_Index
(T_Typ
);
9664 R_Index
:= First_Index
(Exptyp
);
9666 for Indx
in 1 .. Ndims
loop
9667 if not (Nkind
(L_Index
) = N_Raise_Constraint_Error
9669 Nkind
(R_Index
) = N_Raise_Constraint_Error
)
9671 Get_Index_Bounds
(L_Index
, L_Low
, L_High
);
9672 Get_Index_Bounds
(R_Index
, R_Low
, R_High
);
9674 -- Deal with compile time length check. Note that we
9675 -- skip this in the access case, because the access
9676 -- value may be null, so we cannot know statically.
9679 and then Compile_Time_Known_Value
(L_Low
)
9680 and then Compile_Time_Known_Value
(L_High
)
9681 and then Compile_Time_Known_Value
(R_Low
)
9682 and then Compile_Time_Known_Value
(R_High
)
9684 if Expr_Value
(L_High
) >= Expr_Value
(L_Low
) then
9685 L_Length
:= Expr_Value
(L_High
) -
9686 Expr_Value
(L_Low
) + 1;
9688 L_Length
:= UI_From_Int
(0);
9691 if Expr_Value
(R_High
) >= Expr_Value
(R_Low
) then
9692 R_Length
:= Expr_Value
(R_High
) -
9693 Expr_Value
(R_Low
) + 1;
9695 R_Length
:= UI_From_Int
(0);
9698 if L_Length
> R_Length
then
9700 (Compile_Time_Constraint_Error
9701 (Wnode
, "too few elements for}??", T_Typ
));
9703 elsif L_Length
< R_Length
then
9705 (Compile_Time_Constraint_Error
9706 (Wnode
, "too many elements for}??", T_Typ
));
9709 -- The comparison for an individual index subtype
9710 -- is omitted if the corresponding index subtypes
9711 -- statically match, since the result is known to
9712 -- be true. Note that this test is worth while even
9713 -- though we do static evaluation, because non-static
9714 -- subtypes can statically match.
9717 Subtypes_Statically_Match
9718 (Etype
(L_Index
), Etype
(R_Index
))
9721 (Same_Bounds
(L_Low
, R_Low
)
9722 and then Same_Bounds
(L_High
, R_High
))
9725 (Cond
, Length_E_Cond
(Exptyp
, T_Typ
, Indx
));
9734 -- Handle cases where we do not get a usable actual subtype that
9735 -- is constrained. This happens for example in the function call
9736 -- and explicit dereference cases. In these cases, we have to get
9737 -- the length or range from the expression itself, making sure we
9738 -- do not evaluate it more than once.
9740 -- Here Ck_Node is the original expression, or more properly the
9741 -- result of applying Duplicate_Expr to the original tree, forcing
9742 -- the result to be a name.
9746 Ndims
: constant Nat
:= Number_Dimensions
(T_Typ
);
9749 -- Build the condition for the explicit dereference case
9751 for Indx
in 1 .. Ndims
loop
9753 (Cond
, Length_N_Cond
(Ck_Node
, T_Typ
, Indx
));
9760 -- Construct the test and insert into the tree
9762 if Present
(Cond
) then
9764 Cond
:= Guard_Access
(Cond
, Loc
, Ck_Node
);
9768 (Make_Raise_Constraint_Error
(Loc
,
9770 Reason
=> CE_Length_Check_Failed
));
9774 end Selected_Length_Checks
;
9776 ---------------------------
9777 -- Selected_Range_Checks --
9778 ---------------------------
9780 function Selected_Range_Checks
9782 Target_Typ
: Entity_Id
;
9783 Source_Typ
: Entity_Id
;
9784 Warn_Node
: Node_Id
) return Check_Result
9786 Loc
: constant Source_Ptr
:= Sloc
(Ck_Node
);
9789 Expr_Actual
: Node_Id
;
9791 Cond
: Node_Id
:= Empty
;
9792 Do_Access
: Boolean := False;
9793 Wnode
: Node_Id
:= Warn_Node
;
9794 Ret_Result
: Check_Result
:= (Empty
, Empty
);
9795 Num_Checks
: Integer := 0;
9797 procedure Add_Check
(N
: Node_Id
);
9798 -- Adds the action given to Ret_Result if N is non-Empty
9800 function Discrete_Range_Cond
9802 Typ
: Entity_Id
) return Node_Id
;
9803 -- Returns expression to compute:
9804 -- Low_Bound (Expr) < Typ'First
9806 -- High_Bound (Expr) > Typ'Last
9808 function Discrete_Expr_Cond
9810 Typ
: Entity_Id
) return Node_Id
;
9811 -- Returns expression to compute:
9816 function Get_E_First_Or_Last
9820 Nam
: Name_Id
) return Node_Id
;
9821 -- Returns an attribute reference
9822 -- E'First or E'Last
9823 -- with a source location of Loc.
9825 -- Nam is Name_First or Name_Last, according to which attribute is
9826 -- desired. If Indx is non-zero, it is passed as a literal in the
9827 -- Expressions of the attribute reference (identifying the desired
9828 -- array dimension).
9830 function Get_N_First
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
9831 function Get_N_Last
(N
: Node_Id
; Indx
: Nat
) return Node_Id
;
9832 -- Returns expression to compute:
9833 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
9835 function Range_E_Cond
9836 (Exptyp
: Entity_Id
;
9840 -- Returns expression to compute:
9841 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
9843 function Range_Equal_E_Cond
9844 (Exptyp
: Entity_Id
;
9846 Indx
: Nat
) return Node_Id
;
9847 -- Returns expression to compute:
9848 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
9850 function Range_N_Cond
9853 Indx
: Nat
) return Node_Id
;
9854 -- Return expression to compute:
9855 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
9861 procedure Add_Check
(N
: Node_Id
) is
9865 -- For now, ignore attempt to place more than 2 checks ???
9867 if Num_Checks
= 2 then
9871 pragma Assert
(Num_Checks
<= 1);
9872 Num_Checks
:= Num_Checks
+ 1;
9873 Ret_Result
(Num_Checks
) := N
;
9877 -------------------------
9878 -- Discrete_Expr_Cond --
9879 -------------------------
9881 function Discrete_Expr_Cond
9883 Typ
: Entity_Id
) return Node_Id
9891 Convert_To
(Base_Type
(Typ
),
9892 Duplicate_Subexpr_No_Checks
(Expr
)),
9894 Convert_To
(Base_Type
(Typ
),
9895 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_First
))),
9900 Convert_To
(Base_Type
(Typ
),
9901 Duplicate_Subexpr_No_Checks
(Expr
)),
9905 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_Last
))));
9906 end Discrete_Expr_Cond
;
9908 -------------------------
9909 -- Discrete_Range_Cond --
9910 -------------------------
9912 function Discrete_Range_Cond
9914 Typ
: Entity_Id
) return Node_Id
9916 LB
: Node_Id
:= Low_Bound
(Expr
);
9917 HB
: Node_Id
:= High_Bound
(Expr
);
9919 Left_Opnd
: Node_Id
;
9920 Right_Opnd
: Node_Id
;
9923 if Nkind
(LB
) = N_Identifier
9924 and then Ekind
(Entity
(LB
)) = E_Discriminant
9926 LB
:= New_Occurrence_Of
(Discriminal
(Entity
(LB
)), Loc
);
9933 (Base_Type
(Typ
), Duplicate_Subexpr_No_Checks
(LB
)),
9938 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_First
)));
9940 if Nkind
(HB
) = N_Identifier
9941 and then Ekind
(Entity
(HB
)) = E_Discriminant
9943 HB
:= New_Occurrence_Of
(Discriminal
(Entity
(HB
)), Loc
);
9950 (Base_Type
(Typ
), Duplicate_Subexpr_No_Checks
(HB
)),
9955 Get_E_First_Or_Last
(Loc
, Typ
, 0, Name_Last
)));
9957 return Make_Or_Else
(Loc
, Left_Opnd
, Right_Opnd
);
9958 end Discrete_Range_Cond
;
9960 -------------------------
9961 -- Get_E_First_Or_Last --
9962 -------------------------
9964 function Get_E_First_Or_Last
9968 Nam
: Name_Id
) return Node_Id
9973 Exprs
:= New_List
(Make_Integer_Literal
(Loc
, UI_From_Int
(Indx
)));
9978 return Make_Attribute_Reference
(Loc
,
9979 Prefix
=> New_Occurrence_Of
(E
, Loc
),
9980 Attribute_Name
=> Nam
,
9981 Expressions
=> Exprs
);
9982 end Get_E_First_Or_Last
;
9988 function Get_N_First
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
9991 Make_Attribute_Reference
(Loc
,
9992 Attribute_Name
=> Name_First
,
9994 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
9995 Expressions
=> New_List
(
9996 Make_Integer_Literal
(Loc
, Indx
)));
10003 function Get_N_Last
(N
: Node_Id
; Indx
: Nat
) return Node_Id
is
10006 Make_Attribute_Reference
(Loc
,
10007 Attribute_Name
=> Name_Last
,
10009 Duplicate_Subexpr_No_Checks
(N
, Name_Req
=> True),
10010 Expressions
=> New_List
(
10011 Make_Integer_Literal
(Loc
, Indx
)));
10018 function Range_E_Cond
10019 (Exptyp
: Entity_Id
;
10021 Indx
: Nat
) return Node_Id
10029 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_First
),
10031 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10036 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_Last
),
10038 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10041 ------------------------
10042 -- Range_Equal_E_Cond --
10043 ------------------------
10045 function Range_Equal_E_Cond
10046 (Exptyp
: Entity_Id
;
10048 Indx
: Nat
) return Node_Id
10056 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_First
),
10058 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10063 Get_E_First_Or_Last
(Loc
, Exptyp
, Indx
, Name_Last
),
10065 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10066 end Range_Equal_E_Cond
;
10072 function Range_N_Cond
10075 Indx
: Nat
) return Node_Id
10083 Get_N_First
(Expr
, Indx
),
10085 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_First
)),
10090 Get_N_Last
(Expr
, Indx
),
10092 Get_E_First_Or_Last
(Loc
, Typ
, Indx
, Name_Last
)));
10095 -- Start of processing for Selected_Range_Checks
10098 -- Checks will be applied only when generating code. In GNATprove mode,
10099 -- we do not apply the checks, but we still call Selected_Range_Checks
10100 -- to possibly issue errors on SPARK code when a run-time error can be
10101 -- detected at compile time.
10103 if not Expander_Active
and not GNATprove_Mode
then
10107 if Target_Typ
= Any_Type
10108 or else Target_Typ
= Any_Composite
10109 or else Raises_Constraint_Error
(Ck_Node
)
10118 T_Typ
:= Target_Typ
;
10120 if No
(Source_Typ
) then
10121 S_Typ
:= Etype
(Ck_Node
);
10123 S_Typ
:= Source_Typ
;
10126 if S_Typ
= Any_Type
or else S_Typ
= Any_Composite
then
10130 -- The order of evaluating T_Typ before S_Typ seems to be critical
10131 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
10132 -- in, and since Node can be an N_Range node, it might be invalid.
10133 -- Should there be an assert check somewhere for taking the Etype of
10134 -- an N_Range node ???
10136 if Is_Access_Type
(T_Typ
) and then Is_Access_Type
(S_Typ
) then
10137 S_Typ
:= Designated_Type
(S_Typ
);
10138 T_Typ
:= Designated_Type
(T_Typ
);
10141 -- A simple optimization for the null case
10143 if Known_Null
(Ck_Node
) then
10148 -- For an N_Range Node, check for a null range and then if not
10149 -- null generate a range check action.
10151 if Nkind
(Ck_Node
) = N_Range
then
10153 -- There's no point in checking a range against itself
10155 if Ck_Node
= Scalar_Range
(T_Typ
) then
10160 T_LB
: constant Node_Id
:= Type_Low_Bound
(T_Typ
);
10161 T_HB
: constant Node_Id
:= Type_High_Bound
(T_Typ
);
10162 Known_T_LB
: constant Boolean := Compile_Time_Known_Value
(T_LB
);
10163 Known_T_HB
: constant Boolean := Compile_Time_Known_Value
(T_HB
);
10165 LB
: Node_Id
:= Low_Bound
(Ck_Node
);
10166 HB
: Node_Id
:= High_Bound
(Ck_Node
);
10167 Known_LB
: Boolean := False;
10168 Known_HB
: Boolean := False;
10170 Null_Range
: Boolean;
10171 Out_Of_Range_L
: Boolean;
10172 Out_Of_Range_H
: Boolean;
10175 -- Compute what is known at compile time
10177 if Known_T_LB
and Known_T_HB
then
10178 if Compile_Time_Known_Value
(LB
) then
10181 -- There's no point in checking that a bound is within its
10182 -- own range so pretend that it is known in this case. First
10183 -- deal with low bound.
10185 elsif Ekind
(Etype
(LB
)) = E_Signed_Integer_Subtype
10186 and then Scalar_Range
(Etype
(LB
)) = Scalar_Range
(T_Typ
)
10192 -- Likewise for the high bound
10194 if Compile_Time_Known_Value
(HB
) then
10197 elsif Ekind
(Etype
(HB
)) = E_Signed_Integer_Subtype
10198 and then Scalar_Range
(Etype
(HB
)) = Scalar_Range
(T_Typ
)
10205 -- Check for case where everything is static and we can do the
10206 -- check at compile time. This is skipped if we have an access
10207 -- type, since the access value may be null.
10209 -- ??? This code can be improved since you only need to know that
10210 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
10211 -- compile time to emit pertinent messages.
10213 if Known_T_LB
and Known_T_HB
and Known_LB
and Known_HB
10216 -- Floating-point case
10218 if Is_Floating_Point_Type
(S_Typ
) then
10219 Null_Range
:= Expr_Value_R
(HB
) < Expr_Value_R
(LB
);
10221 (Expr_Value_R
(LB
) < Expr_Value_R
(T_LB
))
10223 (Expr_Value_R
(LB
) > Expr_Value_R
(T_HB
));
10226 (Expr_Value_R
(HB
) > Expr_Value_R
(T_HB
))
10228 (Expr_Value_R
(HB
) < Expr_Value_R
(T_LB
));
10230 -- Fixed or discrete type case
10233 Null_Range
:= Expr_Value
(HB
) < Expr_Value
(LB
);
10235 (Expr_Value
(LB
) < Expr_Value
(T_LB
))
10237 (Expr_Value
(LB
) > Expr_Value
(T_HB
));
10240 (Expr_Value
(HB
) > Expr_Value
(T_HB
))
10242 (Expr_Value
(HB
) < Expr_Value
(T_LB
));
10245 if not Null_Range
then
10246 if Out_Of_Range_L
then
10247 if No
(Warn_Node
) then
10249 (Compile_Time_Constraint_Error
10250 (Low_Bound
(Ck_Node
),
10251 "static value out of range of}??", T_Typ
));
10255 (Compile_Time_Constraint_Error
10257 "static range out of bounds of}??", T_Typ
));
10261 if Out_Of_Range_H
then
10262 if No
(Warn_Node
) then
10264 (Compile_Time_Constraint_Error
10265 (High_Bound
(Ck_Node
),
10266 "static value out of range of}??", T_Typ
));
10270 (Compile_Time_Constraint_Error
10272 "static range out of bounds of}??", T_Typ
));
10279 LB
: Node_Id
:= Low_Bound
(Ck_Node
);
10280 HB
: Node_Id
:= High_Bound
(Ck_Node
);
10283 -- If either bound is a discriminant and we are within the
10284 -- record declaration, it is a use of the discriminant in a
10285 -- constraint of a component, and nothing can be checked
10286 -- here. The check will be emitted within the init proc.
10287 -- Before then, the discriminal has no real meaning.
10288 -- Similarly, if the entity is a discriminal, there is no
10289 -- check to perform yet.
10291 -- The same holds within a discriminated synchronized type,
10292 -- where the discriminant may constrain a component or an
10295 if Nkind
(LB
) = N_Identifier
10296 and then Denotes_Discriminant
(LB
, True)
10298 if Current_Scope
= Scope
(Entity
(LB
))
10299 or else Is_Concurrent_Type
(Current_Scope
)
10300 or else Ekind
(Entity
(LB
)) /= E_Discriminant
10305 New_Occurrence_Of
(Discriminal
(Entity
(LB
)), Loc
);
10309 if Nkind
(HB
) = N_Identifier
10310 and then Denotes_Discriminant
(HB
, True)
10312 if Current_Scope
= Scope
(Entity
(HB
))
10313 or else Is_Concurrent_Type
(Current_Scope
)
10314 or else Ekind
(Entity
(HB
)) /= E_Discriminant
10319 New_Occurrence_Of
(Discriminal
(Entity
(HB
)), Loc
);
10323 Cond
:= Discrete_Range_Cond
(Ck_Node
, T_Typ
);
10324 Set_Paren_Count
(Cond
, 1);
10327 Make_And_Then
(Loc
,
10331 Convert_To
(Base_Type
(Etype
(HB
)),
10332 Duplicate_Subexpr_No_Checks
(HB
)),
10334 Convert_To
(Base_Type
(Etype
(LB
)),
10335 Duplicate_Subexpr_No_Checks
(LB
))),
10336 Right_Opnd
=> Cond
);
10341 elsif Is_Scalar_Type
(S_Typ
) then
10343 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10344 -- except the above simply sets a flag in the node and lets
10345 -- gigi generate the check base on the Etype of the expression.
10346 -- Sometimes, however we want to do a dynamic check against an
10347 -- arbitrary target type, so we do that here.
10349 if Ekind
(Base_Type
(S_Typ
)) /= Ekind
(Base_Type
(T_Typ
)) then
10350 Cond
:= Discrete_Expr_Cond
(Ck_Node
, T_Typ
);
10352 -- For literals, we can tell if the constraint error will be
10353 -- raised at compile time, so we never need a dynamic check, but
10354 -- if the exception will be raised, then post the usual warning,
10355 -- and replace the literal with a raise constraint error
10356 -- expression. As usual, skip this for access types
10358 elsif Compile_Time_Known_Value
(Ck_Node
) and then not Do_Access
then
10360 LB
: constant Node_Id
:= Type_Low_Bound
(T_Typ
);
10361 UB
: constant Node_Id
:= Type_High_Bound
(T_Typ
);
10363 Out_Of_Range
: Boolean;
10364 Static_Bounds
: constant Boolean :=
10365 Compile_Time_Known_Value
(LB
)
10366 and Compile_Time_Known_Value
(UB
);
10369 -- Following range tests should use Sem_Eval routine ???
10371 if Static_Bounds
then
10372 if Is_Floating_Point_Type
(S_Typ
) then
10374 (Expr_Value_R
(Ck_Node
) < Expr_Value_R
(LB
))
10376 (Expr_Value_R
(Ck_Node
) > Expr_Value_R
(UB
));
10378 -- Fixed or discrete type
10382 Expr_Value
(Ck_Node
) < Expr_Value
(LB
)
10384 Expr_Value
(Ck_Node
) > Expr_Value
(UB
);
10387 -- Bounds of the type are static and the literal is out of
10388 -- range so output a warning message.
10390 if Out_Of_Range
then
10391 if No
(Warn_Node
) then
10393 (Compile_Time_Constraint_Error
10395 "static value out of range of}??", T_Typ
));
10399 (Compile_Time_Constraint_Error
10401 "static value out of range of}??", T_Typ
));
10406 Cond
:= Discrete_Expr_Cond
(Ck_Node
, T_Typ
);
10410 -- Here for the case of a non-static expression, we need a runtime
10411 -- check unless the source type range is guaranteed to be in the
10412 -- range of the target type.
10415 if not In_Subrange_Of
(S_Typ
, T_Typ
) then
10416 Cond
:= Discrete_Expr_Cond
(Ck_Node
, T_Typ
);
10421 if Is_Array_Type
(T_Typ
) and then Is_Array_Type
(S_Typ
) then
10422 if Is_Constrained
(T_Typ
) then
10424 Expr_Actual
:= Get_Referenced_Object
(Ck_Node
);
10425 Exptyp
:= Get_Actual_Subtype
(Expr_Actual
);
10427 if Is_Access_Type
(Exptyp
) then
10428 Exptyp
:= Designated_Type
(Exptyp
);
10431 -- String_Literal case. This needs to be handled specially be-
10432 -- cause no index types are available for string literals. The
10433 -- condition is simply:
10435 -- T_Typ'Length = string-literal-length
10437 if Nkind
(Expr_Actual
) = N_String_Literal
then
10440 -- General array case. Here we have a usable actual subtype for
10441 -- the expression, and the condition is built from the two types
10443 -- T_Typ'First < Exptyp'First or else
10444 -- T_Typ'Last > Exptyp'Last or else
10445 -- T_Typ'First(1) < Exptyp'First(1) or else
10446 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10449 elsif Is_Constrained
(Exptyp
) then
10451 Ndims
: constant Nat
:= Number_Dimensions
(T_Typ
);
10457 L_Index
:= First_Index
(T_Typ
);
10458 R_Index
:= First_Index
(Exptyp
);
10460 for Indx
in 1 .. Ndims
loop
10461 if not (Nkind
(L_Index
) = N_Raise_Constraint_Error
10463 Nkind
(R_Index
) = N_Raise_Constraint_Error
)
10465 -- Deal with compile time length check. Note that we
10466 -- skip this in the access case, because the access
10467 -- value may be null, so we cannot know statically.
10470 Subtypes_Statically_Match
10471 (Etype
(L_Index
), Etype
(R_Index
))
10473 -- If the target type is constrained then we
10474 -- have to check for exact equality of bounds
10475 -- (required for qualified expressions).
10477 if Is_Constrained
(T_Typ
) then
10480 Range_Equal_E_Cond
(Exptyp
, T_Typ
, Indx
));
10483 (Cond
, Range_E_Cond
(Exptyp
, T_Typ
, Indx
));
10493 -- Handle cases where we do not get a usable actual subtype that
10494 -- is constrained. This happens for example in the function call
10495 -- and explicit dereference cases. In these cases, we have to get
10496 -- the length or range from the expression itself, making sure we
10497 -- do not evaluate it more than once.
10499 -- Here Ck_Node is the original expression, or more properly the
10500 -- result of applying Duplicate_Expr to the original tree,
10501 -- forcing the result to be a name.
10505 Ndims
: constant Nat
:= Number_Dimensions
(T_Typ
);
10508 -- Build the condition for the explicit dereference case
10510 for Indx
in 1 .. Ndims
loop
10512 (Cond
, Range_N_Cond
(Ck_Node
, T_Typ
, Indx
));
10518 -- For a conversion to an unconstrained array type, generate an
10519 -- Action to check that the bounds of the source value are within
10520 -- the constraints imposed by the target type (RM 4.6(38)). No
10521 -- check is needed for a conversion to an access to unconstrained
10522 -- array type, as 4.6(24.15/2) requires the designated subtypes
10523 -- of the two access types to statically match.
10525 if Nkind
(Parent
(Ck_Node
)) = N_Type_Conversion
10526 and then not Do_Access
10529 Opnd_Index
: Node_Id
;
10530 Targ_Index
: Node_Id
;
10531 Opnd_Range
: Node_Id
;
10534 Opnd_Index
:= First_Index
(Get_Actual_Subtype
(Ck_Node
));
10535 Targ_Index
:= First_Index
(T_Typ
);
10536 while Present
(Opnd_Index
) loop
10538 -- If the index is a range, use its bounds. If it is an
10539 -- entity (as will be the case if it is a named subtype
10540 -- or an itype created for a slice) retrieve its range.
10542 if Is_Entity_Name
(Opnd_Index
)
10543 and then Is_Type
(Entity
(Opnd_Index
))
10545 Opnd_Range
:= Scalar_Range
(Entity
(Opnd_Index
));
10547 Opnd_Range
:= Opnd_Index
;
10550 if Nkind
(Opnd_Range
) = N_Range
then
10552 (Low_Bound
(Opnd_Range
), Etype
(Targ_Index
),
10553 Assume_Valid
=> True)
10556 (High_Bound
(Opnd_Range
), Etype
(Targ_Index
),
10557 Assume_Valid
=> True)
10561 -- If null range, no check needed
10564 Compile_Time_Known_Value
(High_Bound
(Opnd_Range
))
10566 Compile_Time_Known_Value
(Low_Bound
(Opnd_Range
))
10568 Expr_Value
(High_Bound
(Opnd_Range
)) <
10569 Expr_Value
(Low_Bound
(Opnd_Range
))
10573 elsif Is_Out_Of_Range
10574 (Low_Bound
(Opnd_Range
), Etype
(Targ_Index
),
10575 Assume_Valid
=> True)
10578 (High_Bound
(Opnd_Range
), Etype
(Targ_Index
),
10579 Assume_Valid
=> True)
10582 (Compile_Time_Constraint_Error
10583 (Wnode
, "value out of range of}??", T_Typ
));
10588 Discrete_Range_Cond
10589 (Opnd_Range
, Etype
(Targ_Index
)));
10593 Next_Index
(Opnd_Index
);
10594 Next_Index
(Targ_Index
);
10601 -- Construct the test and insert into the tree
10603 if Present
(Cond
) then
10605 Cond
:= Guard_Access
(Cond
, Loc
, Ck_Node
);
10609 (Make_Raise_Constraint_Error
(Loc
,
10611 Reason
=> CE_Range_Check_Failed
));
10615 end Selected_Range_Checks
;
10617 -------------------------------
10618 -- Storage_Checks_Suppressed --
10619 -------------------------------
10621 function Storage_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
10623 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
10624 return Is_Check_Suppressed
(E
, Storage_Check
);
10626 return Scope_Suppress
.Suppress
(Storage_Check
);
10628 end Storage_Checks_Suppressed
;
10630 ---------------------------
10631 -- Tag_Checks_Suppressed --
10632 ---------------------------
10634 function Tag_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
10637 and then Checks_May_Be_Suppressed
(E
)
10639 return Is_Check_Suppressed
(E
, Tag_Check
);
10641 return Scope_Suppress
.Suppress
(Tag_Check
);
10643 end Tag_Checks_Suppressed
;
10645 ---------------------------------------
10646 -- Validate_Alignment_Check_Warnings --
10647 ---------------------------------------
10649 procedure Validate_Alignment_Check_Warnings
is
10651 for J
in Alignment_Warnings
.First
.. Alignment_Warnings
.Last
loop
10653 AWR
: Alignment_Warnings_Record
10654 renames Alignment_Warnings
.Table
(J
);
10656 if Known_Alignment
(AWR
.E
)
10657 and then AWR
.A
mod Alignment
(AWR
.E
) = 0
10659 Delete_Warning_And_Continuations
(AWR
.W
);
10663 end Validate_Alignment_Check_Warnings
;
10665 --------------------------
10666 -- Validity_Check_Range --
10667 --------------------------
10669 procedure Validity_Check_Range
10671 Related_Id
: Entity_Id
:= Empty
)
10674 if Validity_Checks_On
and Validity_Check_Operands
then
10675 if Nkind
(N
) = N_Range
then
10677 (Expr
=> Low_Bound
(N
),
10678 Related_Id
=> Related_Id
,
10679 Is_Low_Bound
=> True);
10682 (Expr
=> High_Bound
(N
),
10683 Related_Id
=> Related_Id
,
10684 Is_High_Bound
=> True);
10687 end Validity_Check_Range
;
10689 --------------------------------
10690 -- Validity_Checks_Suppressed --
10691 --------------------------------
10693 function Validity_Checks_Suppressed
(E
: Entity_Id
) return Boolean is
10695 if Present
(E
) and then Checks_May_Be_Suppressed
(E
) then
10696 return Is_Check_Suppressed
(E
, Validity_Check
);
10698 return Scope_Suppress
.Suppress
(Validity_Check
);
10700 end Validity_Checks_Suppressed
;